OpenMax
免费试用

登录

拿到「当前是谁在用」:嵌在 Workspace 里时向宿主要授权码,新标签打开时跳转授权;两条路都有能跑的 Node.js 代码。

应用要知道「当前是谁在用」,按打开方式分两条路,后端最后都用 code 换 token、验 id_token、建自己的会话:

支持嵌入的应用两条都要接:嵌入时一律向宿主要授权码,只有判断出「不在嵌入里」时才跳转授权。

参数、返回值和错误码不在这页重复,见参考:authorize、token、/api/v1/me、登录和令牌的错误码、嵌入时的错误码、限流。

准备:后端共用代码

两条路共用下面这份 server.js 骨架(Node.js 20+,npm i express jose cookie-parser)。后面两节的路由都加在它里面,拼起来就能跑。

// 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 的地址
const APP_ID = process.env.OPENMAX_APP_ID;                  // app_…
const APP_SECRET = process.env.OPENMAX_APP_SECRET;
const APP_ORIGIN = process.env.APP_ORIGIN;                  // 你自己的 origin,如 https://my-app.example.com
const REDIRECT_URI = `${APP_ORIGIN}/auth/openmax/callback`; // 和 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");

// 用 code 换 token,验 id_token,核组织。两条路共用。
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 等,见错误码参考
  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 …
}

// 你自己的会话。示例放内存;上限 = id_token 的 exp(见「会话多久要重新登录」)。
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" }); // 接口不 302,前端自己重新登录
  }
  req.session = s;
  next();
}

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

// …下面两节的路由加在这里…

app.listen(3000);

ALLOWED_ORG_IDS:组织应用就是它所属的那一个组织;官方应用会被多个组织安装,按 org_id 分租户,或者只放行名单里的组织。真实应用里,issueSession 前要按 (issuer, org_id, member_id) 查你自己的账号绑定,见已有系统接入。

嵌入时登录:向宿主要授权码

应用嵌在 Workspace 里时,不要在 iframe 里跳转登录。iPhone / iPad 上的所有浏览器和桌面 Safari 都是 WebKit 内核,iframe 里的第三方 cookie 存不下也带不上;在 iframe 里跳授权页、再回到回调地址,会在回调处断,用户看到白屏 / 黑屏。

改为向 Workspace 宿主要授权码:宿主是顶层页面,本来就有成员的登录态,它替你签发一个 code,只回给你的 iframe。全程不跳转、不靠 cookie。

你的前端(iframe)           Workspace 宿主(顶层)          你的后端                 OpenMax
      │ 生成 code_verifier、challenge │                         │                        │
      │── openmax:auth:request ──────>│                         │                        │
      │                               │── 用成员会话申请 code ──────────────────────────>│
      │<── openmax:auth:code ─────────│<────────────────────────────────────── code ──────│
      │── POST code + verifier + nonce ────────────────────────>│                        │
      │                               │                         │── token 端点换 token ─>│
      │                               │                         │<── id_token ───────────│
      │<── 会话凭据(响应体) ──────────────────────────────────│ 验 id_token、核组织     │
      │ 之后每个请求带 Authorization: Bearer <会话凭据>          │                        │

第 1 步:前端向宿主要 code

@openmaxai/app-sdk 还没发布到 npm,现在按下面的写法自己发 postMessage。把它放进你的前端(需要 https,用到 Web Crypto):

// openmax-auth.js(前端)
const WORKSPACE_ORIGIN = "https://openmax.com";             // 只发给它,不用 "*"
const REDIRECT_URI = "https://my-app.example.com/auth/openmax/callback"; // 和 manifest 逐字节相同,不会跳过去

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

let inflight = null;                                       // 同一时刻只有一个请求在途
function requestAuthCode({ timeoutMs = 10_000 } = {}) {
  if (window.parent === window) return Promise.reject(new Error("not_embedded"));
  return (inflight ??= (async () => {
    const codeVerifier = rand(32);                         // 43 个字符,只留在页面里
    const requestId = rand(16);
    const nonce = rand(16);                                // 回显在 id_token 里,后端核对
    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; // 只认父窗口 + Workspace
        const m = e.data;
        if (!m || m.requestId !== requestId) return;                             // 只认这一次
        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;                                        // 只放内存
export async function ensureSignedIn(attempt = 1) {
  if (session) return session;
  try {
    const { code, codeVerifier, nonce } = await requestAuthCode();
    const res = await fetch("/auth/openmax/embedded", {     // code 60 秒内有效,拿到马上换
      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") {                         // 新标签 / 顶层:唯一走跳转授权的情况
      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);                  // 总共最多 3 次
    }
    showSignInError(code);                                 // 说明 +「新标签打开」;绝不在 iframe 里跳转
    return null;
  }
}

// 调你自己的接口:带会话;401 说明会话到期,清掉后静默再要一次 code,只重来一次
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 是你自己的界面:显示原因,给一个「在新标签打开」(target="_blank" rel="noopener",打开你自己的应用地址),可以另给「重试」。

出错时只按这三条走,每个错误码的含义见嵌入时的错误码:

  • 只有 not_embedded(顶层 / 新标签)才走跳转授权。
  • host_timeout、timeout、busy 重试,总共最多 3 次。
  • 其他错误、你的后端换 token 失败、重试用尽:显示说明 +「在新标签打开」。绝不在 iframe 里跳到授权端点或你的登录页,在 WebKit 上那正是白屏的路径。

协议消息

和主题 / 语言消息用同一套来源规则(见打开方式与地址)。

应用 → 宿主:openmax:auth:request

字段 说明
requestId 1–64 个 [A-Za-z0-9_-],每次随机
codeChallenge 43 位 base64url(S256,见上)
codeChallengeMethod 固定 "S256"
redirectUri ≤ 2048 的 http(s) 绝对地址,必须和 manifest 里登记的 redirect_uri 逐字节相同
nonce(可选) ≤ 256 个可见 ASCII,回显在 id_token 的 nonce 里
scope(可选) 空格分隔,只能收窄安装时批准的 scope

不带 client_id、state;宿主只认上面这些字段。

宿主 → 应用

消息 字段
openmax:auth:code requestId、code(一次性,60 秒内有效)
openmax:auth:error requestId、error(见嵌入时的错误码)、retryAfter(可选,单位秒,只在 rate_limited 时出现)

来源校验

  • 只发给 Workspace origin https://openmax.com,不要用 "*"。Workspace 以 referrerPolicy="no-referrer" 打开应用,应用拿不到父页面的 origin,所以写这个固定值。
  • 收到消息时三项都要核:event.source === window.parent、event.origin 是配置的 Workspace origin、requestId 等于在途的那一个。对不上的一律丢弃。不认识的错误码按 failed 处理。
  • 宿主只认来自你这个 iframe、且 event.origin 等于 manifest url 的 origin 的请求(和主题 / 语言消息一样,url 必须是你的最终 origin),来源不符的不回信。requestId 不合法时宿主无法回信,静默丢弃;其他字段不合法回 invalid_request。
  • 同一时刻只保留一个在途请求(上面的 requestAuthCode 在途时再调用,返回同一个 promise)。

第 2 步:后端用 code 换会话

加到 server.js 里:

// 嵌入登录:前端从宿主拿到 code 后 POST 到这里。不跳转、不读写 cookie。
app.post("/auth/openmax/embedded", express.json(), async (req, res) => {
  if (req.get("origin") !== APP_ORIGIN) return res.status(403).end();  // 只收自己页面发来的
  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 }); // 放响应体,不 Set-Cookie
  } catch (e) {
    res.status(e.message === "org" ? 403 : 401).json({ error: e.message });       // 前端显示错误,不跳转
  }
});

第 3 步:会话放哪

  • 放内存(页面里的 JS 变量),每个请求用 Authorization 头带,不依赖 cookie。页面刷新后内存里的会话没了,ensureSignedIn() 静默再要一次 code,成员无感。
  • 也可以放 sessionStorage(同一标签页里整页跳转不用重新要码),代价是同源脚本都读得到,XSS 影响面更大。不要放 localStorage。
  • 页面里带不了请求头的子资源(子 iframe、<img>、下载链接):给它们签短期票据放在地址上(如 60 秒、HMAC、绑定用户和具体资源),不要把会话凭据放进 URL。
  • 会话有效期内复用会话,不要每个接口请求都要一次 code:宿主对每个 iframe 有限流。

新标签打开时登录:跳转授权

应用在新标签或顶层打开时,是第一方页面,cookie 照常可用,走标准的 OAuth 2.0 授权码 + PKCE。成员已登录 Workspace 时无感,没有同意弹窗。

浏览器                        你的后端                         OpenMax
  │── GET /auth/openmax/login ─>│ 生成 state、nonce、verifier      │
  │                             │ 存服务端,cookie 绑定这个浏览器   │
  │<── 302 到 authorize ────────│                                  │
  │── GET /api/v1/apps/authorize ──────────────────────────────────>│ 成员已登录:签发 code
  │<── 回到 redirect_uri?code=…&state=…&iss=… ──────────────────────│
  │── GET /auth/openmax/callback ─>│ 核 iss、state                  │
  │                             │── token 端点换 token ───────────>│
  │                             │<── id_token ─────────────────────│
  │<── Set-Cookie 会话,302 回原页 │ 验 id_token、核组织             │

加到 server.js 里:

const flows = new Map();                                    // 一次登录流程,用一次就删
const FLOW_COOKIE = { httpOnly: true, secure: true, sameSite: "lax", maxAge: 10 * 60_000 };

// 只接受以单个 / 开头的同源路径,其余一律回首页;最好再限定到你自己的路由白名单
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);                     // 一个流程只用一次
  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);                            // 只从服务端流程里取,不读 URL
  } catch (e) {
    res.redirect(`/?login_error=${encodeURIComponent(e.message)}`);
  }
});

几条要点,代码里已经照做:

  • state、nonce、code_verifier 都是不可猜的随机值,存在服务端;state 里不要塞返回路径等数据。
  • 回调先核 iss 等于 https://openmax.com(带 error 的回调也核),再用常量时间比较 state。
  • 返回路径只从服务端流程里取。会话过期时用户可能在深层页(如 /reports/42),把这个路径作为 return_to 传进来,登录后落回原页;不要写死成首页。

不要做成重定向死循环

回调失败时带一个标记回首页(如上面的 /?login_error=…)。首页看到这个标记,或刚退出(?signed_out=1),不自动发起授权,只显示说明和「重新登录」按钮。自动发起授权只在「没有会话、也没有失败标记」时做一次。

接口请求(fetch)遇到会话失效回 401(上面的 requireSession 就是这样),由前端整页导航到 /auth/openmax/login;不要在接口里 302 到授权端点,fetch 跟随跨域重定向只会失败。

每个错误码的含义和应用该怎么做,见登录和令牌的错误码。

会话多久要重新登录

  • access_token 和 id_token 都是 15 分钟,你的会话上限就是 id_token 的 exp(上面的代码用它当会话过期时间)。到期就作废会话、重新登录;不要因为用户还在操作就往后延。
  • 重新登录对成员是无感的:嵌入时 ensureSignedIn() 静默再要一次 code;新标签时整页导航到 /auth/openmax/login。
  • 要更长的会话(比如 4 小时),manifest 里申请 offline_access,用 refresh_token 每 15 分钟换一次新 token;每次换都会轮换 refresh_token,必须存新的,换不到就当授权没了。参数见 token 参考。
  • 调 /api/v1/me 只回答「这个人此刻是否仍是成员」,不产生新 token,不是续期。
  • Workspace 退出登录不会通知应用,也不吊销已签发的应用 token:应用会话最多再活到 token 过期,所以会话上限不能长于 token 过期时间。

token 和刷新

token 端点的请求参数、返回字段、id_token 的 claims、刷新和撤销,见 token 参考。

实践:嵌入与登录

平台规则见上面几节,以及应用类型与 manifest、打开方式与地址(含「入口地址上的参数」「路由同步」「应用请求打开会话」)、已有系统接入。下面只写参考实现(OpenMax Workflows)验证过的做法和踩过的坑。

manifest 与嵌入

建议做法

  • 允许嵌入的源用一份名单配置(逗号分隔,每项只能是 https://host[:port],不收 *)。有一项不合规就整体当没配,回落成 frame-ancestors 'none' + X-Frame-Options: DENY,写错只会更严;服务端遇到写错的值直接拒绝启动。
  • 同一份名单写进页面 <meta>,前端只从这里认外层的源,不从 referrer 或地址参数里猜。

踩过的坑

  • 早期「外壳签发 launch code、带 code 打开 redirect_uri」的方式已被平台删除且不留兼容;按旧方式做的接入只能整套重写成「应用发起授权」(见发布与版本「从旧 launch 方式迁移」)。
  • 部署在路径前缀下时(如 /app),manifest 的 redirect_uri 要带前缀,应用里拼链接、重定向、静态资源、cookie Path 也要用同一个前缀配置。

Workspace 登录

建议做法

  • 换会话的接口只收 POST + JSON 并校验 Origin;nonce 必带,并与 id_token 比对。
  • 会话时长:上限按「会话多久要重新登录」。没申请 offline_access 时,会话最长就是 token 的 15 分钟。

踩过的坑

  • 嵌入页自动授权的 60 秒退避把成功那次也挡住,之后刷新停在登录卡。
  • iframe 存不下 cookie 时不该自动授权:先用探测 cookie 判断。
  • 会话放内存、用请求头带时,CSP 要严(如 default-src 'self'),会话令牌短期且不续期,降低 XSS 被带走后的影响。
  • 同一个回包里既设分区 cookie、又发不分区的 Max-Age=0 去清,会丢嵌入会话。一个回包只发一条 Set-Cookie。
  • 请求头会话下的下载 / 导出改为「新标签打开」,不在嵌入页里存 blob。

主题、语言、当前页同步

建议做法

  • 路由上报和握手放在一个小模块里,并有端到端测试覆盖。

踩过的坑

  • 宿主只在 iframe load 时发一次 theme / lang,前端 hydration 完挂上监听时多半已经错过,于是一直认不出外层源,location 也一直没发出去。改法:挂好监听后主动向名单里的每个源发一次 openmax:theme:request 握手;兜底再看 ancestorOrigins[0] 和 referrer,但必须在名单里;只认 window.parent 发来的回话。
  • location 的 path 不带部署前缀,宿主不认(如部署在 /app 下,要发 /app/todos,不是 /todos)。
  • 收到 openmax:theme / openmax:lang 要真的切换界面,不能只做握手。