OpenMax
Free Trial

Sign-in

Find out who is using your app: when embedded in Workspace, ask the host for an authorization code; when opened in a new tab, use redirect sign-in. Both paths come with runnable Node.js code.

To know who is using your app right now, pick a path by how the app is opened. Either way, your backend ends up exchanging a code for tokens, verifying the id_token and creating its own session:

Apps that support embedding implement both: when embedded, always ask the host for a code; use redirect sign-in only once you know the app is not embedded.

Parameters, responses and error codes are not repeated here; see the reference: authorize, token, /api/v1/me, sign-in and token error codes, embedded error codes, rate limits.

Setup: shared backend code

Both paths share this server.js skeleton (Node.js 20+, npm i express jose cookie-parser). Add the routes from the next two sections to it and it runs.

// server.js
import crypto from "node:crypto";
import express from "express";
import cookieParser from "cookie-parser";
import { createRemoteJWKSet, jwtVerify } from "jose";

const ISSUER = "https://openmax.com";                       // OpenMax address
const APP_ID = process.env.OPENMAX_APP_ID;                  // app_…
const APP_SECRET = process.env.OPENMAX_APP_SECRET;
const APP_ORIGIN = process.env.APP_ORIGIN;                  // your own origin, e.g. https://my-app.example.com
const REDIRECT_URI = `${APP_ORIGIN}/auth/openmax/callback`; // byte-for-byte identical to the manifest
const ALLOWED_ORG_IDS = new Set(process.env.ALLOWED_ORG_IDS.split(","));
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/api/v1/apps/jwks`));

const app = express();
app.use(cookieParser());

const rand = (n = 32) => crypto.randomBytes(n).toString("base64url");
const sha256 = (s) => crypto.createHash("sha256").update(s).digest("base64url");

// Exchange the code for tokens, verify the id_token, check the org. Shared by both paths.
async function exchange({ code, codeVerifier, nonce }) {
  const r = await fetch(`${ISSUER}/api/v1/apps/token`, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code", code, redirect_uri: REDIRECT_URI,
      code_verifier: codeVerifier, client_id: APP_ID, client_secret: APP_SECRET,
    }),
  });
  if (!r.ok) throw new Error("token");                      // invalid_grant etc., see the error code reference
  const tok = await r.json();
  const { payload } = await jwtVerify(tok.id_token, JWKS, {
    issuer: ISSUER, audience: APP_ID, algorithms: ["RS256"], clockTolerance: 30,
  });
  if (payload.nonce !== nonce || payload.sub !== payload.member_id) throw new Error("token");
  if (!ALLOWED_ORG_IDS.has(payload.org_id)) throw new Error("org");
  return payload;                                           // member_id、org_id、name、exp …
}

// Your own session. Kept in memory here; capped at the id_token exp (see "How long a session lasts").
const sessions = new Map();
function issueSession(p) {
  const token = rand();
  sessions.set(token, { memberId: p.member_id, orgId: p.org_id, name: p.name, expiresAt: p.exp * 1000 });
  return token;
}
function requireSession(req, res, next) {
  const token = req.get("authorization")?.replace(/^Bearer /, "") ?? req.cookies.sid;
  const s = token && sessions.get(token);
  if (!s || s.expiresAt <= Date.now()) {
    sessions.delete(token);
    return res.status(401).json({ error: "reauth_required" }); // APIs never 302; the frontend signs in again
  }
  req.session = s;
  next();
}

app.get("/api/whoami", requireSession, (req, res) => res.json(req.session));

// …add the routes from the next two sections here…

app.listen(3000);

ALLOWED_ORG_IDS: an organization app belongs to exactly one organization; an official app is installed by many, so split tenants by org_id or allow only listed organizations. In a real app, look up your own account binding by (issuer, org_id, member_id) before issueSession; see Integrating existing systems.

Sign-in when embedded: ask the host for a code

When your app is embedded in Workspace, do not run redirect sign-in inside the iframe. Every browser on iPhone / iPad, and desktop Safari, uses WebKit, which neither stores nor sends third-party cookies in an iframe. Redirecting to the authorization page inside the iframe and back to your callback breaks at the callback, and users see a white / black screen.

Ask the Workspace host for an authorization code instead. The host is the top-level page and already has the member's session; it issues a code for you and sends it only to your iframe. No redirects, no cookies.

Your frontend (iframe)       Workspace host (top level)     Your backend             OpenMax
      │ create code_verifier, challenge│                        │                        │
      │── openmax:auth:request ──────>│                         │                        │
      │                               │── request code with member session ─────────────>│
      │<── openmax:auth:code ─────────│<────────────────────────────────────── code ──────│
      │── POST code + verifier + nonce ────────────────────────>│                        │
      │                               │                         │── token endpoint ─────>│
      │                               │                         │<── id_token ───────────│
      │<── session credential (body) ───────────────────────────│ verify id_token, org   │
      │ then send Authorization: Bearer <session> on each request │                      │

Step 1: the frontend asks the host for a code

@openmaxai/app-sdk is not on npm yet, so send the postMessage yourself as below. Put this in your frontend (it needs https for Web Crypto):

// openmax-auth.js (frontend)
const WORKSPACE_ORIGIN = "https://openmax.com";             // send only to it, never "*"
const REDIRECT_URI = "https://my-app.example.com/auth/openmax/callback"; // identical to the manifest; never navigated to

const b64u = (bytes) => btoa(String.fromCharCode(...bytes))
  .replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const rand = (n) => b64u(crypto.getRandomValues(new Uint8Array(n)));

let inflight = null;                                       // only one request in flight at a time
function requestAuthCode({ timeoutMs = 10_000 } = {}) {
  if (window.parent === window) return Promise.reject(new Error("not_embedded"));
  return (inflight ??= (async () => {
    const codeVerifier = rand(32);                         // 43 characters, stays in the page
    const requestId = rand(16);
    const nonce = rand(16);                                // echoed in the id_token, checked by the backend
    const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
    const codeChallenge = b64u(new Uint8Array(digest));
    return await new Promise((resolve, reject) => {
      const finish = (err, code) => {
        clearTimeout(timer);
        window.removeEventListener("message", onMessage);
        err ? reject(new Error(err)) : resolve({ code, codeVerifier, nonce });
      };
      const timer = setTimeout(() => finish("timeout"), timeoutMs);
      function onMessage(e) {
        if (e.source !== window.parent || e.origin !== WORKSPACE_ORIGIN) return; // only the parent window + Workspace
        const m = e.data;
        if (!m || m.requestId !== requestId) return;                             // only this request
        if (m.type === "openmax:auth:code" && typeof m.code === "string") finish(null, m.code);
        else if (m.type === "openmax:auth:error") finish(m.error || "failed");
      }
      window.addEventListener("message", onMessage);
      window.parent.postMessage({ type: "openmax:auth:request", requestId, codeChallenge,
        codeChallengeMethod: "S256", redirectUri: REDIRECT_URI, nonce }, WORKSPACE_ORIGIN);
    });
  })().finally(() => { inflight = null; }));
}

let session = null;                                        // memory only
export async function ensureSignedIn(attempt = 1) {
  if (session) return session;
  try {
    const { code, codeVerifier, nonce } = await requestAuthCode();
    const res = await fetch("/auth/openmax/embedded", {     // the code is valid for 60 seconds; exchange it right away
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ code, codeVerifier, nonce }),
    });
    if (!res.ok) throw new Error("exchange_failed");
    return (session = (await res.json()).session);
  } catch (e) {
    const code = e.message;
    if (code === "not_embedded") {                         // new tab / top level: the only case that uses redirect sign-in
      location.assign("/auth/openmax/login?return_to=" + encodeURIComponent(location.pathname));
      return null;
    }
    if (["host_timeout", "timeout", "busy"].includes(code) && attempt < 3) {
      if (code === "busy") await new Promise((r) => setTimeout(r, 1000));
      return ensureSignedIn(attempt + 1);                  // at most 3 attempts in total
    }
    showSignInError(code);                                 // explanation + "Open in new tab"; never navigate inside the iframe
    return null;
  }
}

// Call your own API with the session; a 401 means it expired: clear it, silently request a new code, retry once
export async function api(path, init = {}, retried = false) {
  const s = await ensureSignedIn();
  if (!s) throw new Error("not_signed_in");
  const res = await fetch(path, { ...init, headers: { ...init.headers, Authorization: `Bearer ${s}` } });
  if (res.status === 401 && !retried) { session = null; return api(path, init, true); }
  return res;
}

showSignInError is your own UI: show the reason, offer "Open in new tab" (target="_blank" rel="noopener", pointing at your own app URL), and optionally "Retry".

On errors follow only these three rules; what each code means is in embedded error codes:

  • Only not_embedded (top level / new tab) uses redirect sign-in.
  • Retry host_timeout, timeout and busy, at most 3 attempts in total.
  • For any other error, a failed token exchange in your backend, or retries used up: show an explanation + "Open in new tab". Never navigate the iframe to the authorization endpoint or your sign-in page; on WebKit that is exactly the path to a white screen.

Protocol messages

Uses the same source rules as the theme / language messages (see Open modes and URLs).

App → host: openmax:auth:request

Field Description
requestId 1–64 characters of [A-Za-z0-9_-], random each time
codeChallenge 43-character base64url (S256, see above)
codeChallengeMethod Always "S256"
redirectUri An absolute http(s) URL ≤ 2048, byte-for-byte identical to the redirect_uri registered in the manifest
nonce (optional) ≤ 256 visible ASCII, echoed in the id_token's nonce
scope (optional) Space-separated; can only narrow the scopes approved at install

Do not send client_id or state; the host only accepts the fields above.

Host → app

Message Fields
openmax:auth:code requestId, code (single-use, valid for 60 seconds)
openmax:auth:error requestId, error (see embedded error codes), retryAfter (optional, in seconds, only with rate_limited)

Source checks

  • Send only to the Workspace origin https://openmax.com, never "*". Workspace opens apps with referrerPolicy="no-referrer", so the app cannot learn the parent page's origin; use this fixed value.
  • Check all three on every received message: event.source === window.parent, event.origin is the configured Workspace origin, and requestId equals the one in flight. Drop anything that does not match. Treat unknown error codes as failed.
  • The host only accepts requests from your iframe whose event.origin equals the origin of the manifest url (as with theme / language messages, url must be your final origin); it does not reply to mismatched sources. If requestId is invalid the host cannot reply and silently drops it; other invalid fields get invalid_request.
  • Keep only one request in flight at a time (calling requestAuthCode above while one is in flight returns the same promise).

Step 2: the backend exchanges the code for a session

Add to server.js:

// Embedded sign-in: the frontend POSTs the code from the host here. No redirects, no cookies.
app.post("/auth/openmax/embedded", express.json(), async (req, res) => {
  if (req.get("origin") !== APP_ORIGIN) return res.status(403).end();  // only from your own pages
  const { code, codeVerifier, nonce } = req.body ?? {};
  if (![code, codeVerifier, nonce].every((v) => typeof v === "string"))
    return res.status(400).json({ error: "invalid_request" });
  try {
    const payload = await exchange({ code, codeVerifier, nonce });
    res.json({ session: issueSession(payload), expires_at: payload.exp * 1000 }); // in the response body, no Set-Cookie
  } catch (e) {
    res.status(e.message === "org" ? 403 : 401).json({ error: e.message });       // the frontend shows an error, no redirect
  }
});

Step 3: where to keep the session

  • Keep it in memory (a JS variable in the page) and send it in the Authorization header on every request, with no cookies. After a page reload the in-memory session is gone, and ensureSignedIn() silently requests a new code; the member notices nothing.
  • sessionStorage also works (full-page navigations in the same tab don't need a new code), at the cost that any same-origin script can read it, which widens the impact of XSS. Do not use localStorage.
  • For subresources that cannot send headers (child iframes, <img>, download links), put a short-lived ticket in the URL (for example 60 seconds, HMAC, bound to the user and the specific resource). Never put the session credential itself in a URL.
  • Reuse the session while it is valid; don't request a code for every API call. The host rate-limits each iframe.

Sign-in in a new tab: redirect

In a new tab or at top level your app is a first-party page and cookies work normally, so use the standard OAuth 2.0 authorization code + PKCE flow. When the member is signed in to Workspace it is seamless, with no consent screen.

Browser                       Your backend                     OpenMax
  │── GET /auth/openmax/login ─>│ create state, nonce, verifier    │
  │                             │ store server-side, bind by cookie│
  │<── 302 to authorize ────────│                                  │
  │── GET /api/v1/apps/authorize ──────────────────────────────────>│ member signed in: issue code
  │<── back to redirect_uri?code=…&state=…&iss=… ───────────────────│
  │── GET /auth/openmax/callback ─>│ check iss, state               │
  │                             │── token endpoint ───────────────>│
  │                             │<── id_token ─────────────────────│
  │<── Set-Cookie session, 302 back │ verify id_token, check org     │

Add to server.js:

const flows = new Map();                                    // one sign-in flow, deleted after one use
const FLOW_COOKIE = { httpOnly: true, secure: true, sameSite: "lax", maxAge: 10 * 60_000 };

// accept only same-origin paths starting with a single /; anything else goes home.
// Better still, also restrict it to an allowlist of your own routes.
function safeReturnTo(p) {
  return typeof p === "string" && /^\/(?![\/\\])[^\\\x00-\x1f]*$/.test(p) && !p.includes("..") ? p : "/";
}

app.get("/auth/openmax/login", (req, res) => {
  const flowId = rand(), state = rand(), nonce = rand(), codeVerifier = rand();
  flows.set(flowId, { state, nonce, codeVerifier, returnTo: safeReturnTo(req.query.return_to) });
  res.cookie("oauth_flow", flowId, FLOW_COOKIE);
  const u = new URL(`${ISSUER}/api/v1/apps/authorize`);
  u.search = new URLSearchParams({
    response_type: "code", client_id: APP_ID, redirect_uri: REDIRECT_URI, state, nonce,
    code_challenge: sha256(codeVerifier), code_challenge_method: "S256",
  });
  res.redirect(u.href);
});

app.get("/auth/openmax/callback", async (req, res) => {
  const flow = flows.get(req.cookies.oauth_flow);
  flows.delete(req.cookies.oauth_flow);                     // each flow is used once
  res.clearCookie("oauth_flow");
  const { code, state, iss, error } = req.query;
  const same = (a, b) => typeof a === "string" && a.length === b.length &&
    crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b));
  if (!flow || iss !== ISSUER || !same(state, flow.state))
    return res.redirect("/?login_error=invalid_callback");
  if (error) return res.redirect(`/?login_error=${encodeURIComponent(error)}`);
  try {
    const payload = await exchange({ code, codeVerifier: flow.codeVerifier, nonce: flow.nonce });
    res.cookie("sid", issueSession(payload), {
      httpOnly: true, secure: true, sameSite: "lax", expires: new Date(payload.exp * 1000),
    });
    res.redirect(flow.returnTo);                            // only from the server-side flow, never from the URL
  } catch (e) {
    res.redirect(`/?login_error=${encodeURIComponent(e.message)}`);
  }
});

Key points, all handled in the code above:

  • state, nonce and code_verifier are unguessable random values kept server-side; don't put the return path or other data in state.
  • The callback first checks that iss equals https://openmax.com (also on callbacks carrying error), then compares state in constant time.
  • The return path comes only from the server-side flow. When a session expires the user may be on a deep page (such as /reports/42); pass that path as return_to so they land back on it after sign-in. Don't hard-code the home page.

Avoid redirect loops

When the callback fails, go back to the home page with a marker (such as /?login_error=… above). When the home page sees that marker, or the user just signed out (?signed_out=1), do not start authorization automatically; show an explanation and a "Sign in again" button. Start authorization automatically only once, when there is neither a session nor a failure marker.

When an API request (fetch) hits an invalid session, return 401 (as requireSession above does) and let the frontend navigate the whole page to /auth/openmax/login. Don't 302 an API request to the authorization endpoint; fetch following a cross-origin redirect just fails.

What each error code means and what your app should do: sign-in and token error codes.

How long a session lasts

  • The access_token and id_token both last 15 minutes, and your session is capped at the id_token exp (the code above uses it as the session expiry). When it expires, drop the session and sign in again; don't extend it because the user is still active.
  • Signing in again is seamless for the member: when embedded, ensureSignedIn() silently requests a new code; in a new tab, navigate the whole page to /auth/openmax/login.
  • For longer sessions (say 4 hours), request offline_access in the manifest and exchange the refresh_token for new tokens every 15 minutes. Each exchange rotates the refresh_token, so always store the new one; if the exchange fails, treat the authorization as gone. Parameters are in the token reference.
  • Calling /api/v1/me only answers "is this person still a member right now"; it issues no new token and is not a renewal.
  • Signing out of Workspace does not notify apps or revoke app tokens already issued: your session lives at most until the token expires, so the session cap must never exceed the token expiry.

Tokens and refresh

Token endpoint parameters, response fields, id_token claims, refresh and revocation: see the token reference.

In practice: embedding and sign-in

For platform rules, see the sections above, plus App types and manifest, Open modes and URLs (including "Parameters on the entry URL", "Route sync", and "App requests to open a conversation") and Integrating existing systems. Below are only the approaches proven and pitfalls found in the reference implementation (OpenMax Workflows).

Manifest and embedding

  • Configure the origins allowed to embed you as a single list (comma-separated; each entry must be https://host[:port]; * is not accepted). If any entry is invalid, treat the whole list as unset and fall back to frame-ancestors 'none' + X-Frame-Options: DENY, so a mistake only makes things stricter. The server refuses to start on an invalid value.
  • Write the same list into a page <meta> tag. The frontend identifies the parent origin only from there, never by guessing from the referrer or URL parameters.

Pitfalls

  • The early flow where "the shell issues a launch code and opens redirect_uri with the code" has been removed from the platform with no compatibility layer. Integrations built that way must be fully rewritten to "the app starts authorization" (see "Migrating from the old launch flow" in Release and versions).
  • When deployed under a path prefix (such as /app), the manifest redirect_uri must include the prefix, and the app's links, redirects, static assets, and cookie Path must use the same prefix setting.

Workspace sign-in

  • The session exchange endpoint accepts only POST + JSON and checks Origin; nonce is required and is compared with the id_token.
  • Session length: the limit follows "How long a session lasts". Without offline_access, a session lasts at most the token's 15 minutes.

Pitfalls

  • A 60-second backoff on auto-authorization in the embedded page also blocked the successful attempt, so later refreshes got stuck on the sign-in card.
  • Do not auto-authorize when the iframe cannot store cookies: check with a probe cookie first.
  • When the session lives in memory and is sent in a request header, use a strict CSP (such as default-src 'self') and keep the session token short-lived and non-renewable, to limit the damage if XSS steals it.
  • Setting a partitioned cookie and sending an unpartitioned Max-Age=0 to clear it in the same response loses the embedded session. Send only one Set-Cookie per response.
  • With header-based sessions, open downloads / exports in a new tab instead of saving blobs in the embedded page.

Theme, language, and current page sync

  • Keep route reporting and the handshake in one small module, covered by end-to-end tests.

Pitfalls

  • The host sends theme / lang only once, on iframe load, and by the time the frontend hydrates and attaches its listener it has usually missed them. So it never identifies the parent origin and never sends location. Fix: after attaching the listener, actively send an openmax:theme:request handshake to each origin in the list; as a fallback, check ancestorOrigins[0] and the referrer, but only if they are in the list; only accept replies from window.parent.
  • If the location path lacks the deployment prefix, the host does not recognize it (for example, when deployed under /app, send /app/todos, not /todos).
  • When you receive openmax:theme / openmax:lang, actually switch the UI; do not stop at the handshake.