Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server): receive the provider key-minting redirect without a session, so it works in the desktop app (#502)

Yaowei Zheng38e26f7dbac0
diff --git a/changelog/unreleased/2026-08-26-model-oauth-desktop-callback.md b/changelog/unreleased/2026-08-26-model-oauth-desktop-callback.md
new file mode 100644
index 00000000..2de24759
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-model-oauth-desktop-callback.md
@@ -0,0 +1,20 @@
+# The provider key-minting redirect completes in the desktop app
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`, `docs`
+- **PR:** [#502](https://github.com/Prism-Shadow/penguin-harness/pull/502)
+
+[中文版](2026-08-26-model-oauth-desktop-callback.zh.md)
+
+TokenDance's **Authorize key** action failed in the desktop app with `unauthorized` — "Not signed in or the sign-in has expired." — while the same action completed in the browser. Every desktop authorization had been ending on a 401 before the handler ran: the authorization page opened in the system browser, and the provider redirected *that* browser back to `http://localhost:<port>`, where it carried no `penguin_session` cookie. The redirect receiver stopped requiring a session — and stopped redeeming anything on its own, so that the route answering without one never gained the authority to write a credential.
+
+## Details
+
+- Mounted `GET /api/projects/:projectId/model-oauth/callback` ahead of the global auth middleware, so it authorizes on the flow id rather than a session cookie: 32 random bytes minted server-side, bound to a user, a Project, a provider and a PKCE verifier that never leaves the process, and good for ten minutes.
+- Split the redemption in two. The receiver deposits the code on the flow and answers "Authorization received"; the exchange with the provider and the write into the Project's models moved onto `GET /:flowId`, the owner's own poll, which stayed behind the auth gate. A failed exchange reaches the dialog there as `{status: error, error}` instead of on the redirect page.
+- Gave a flow one deposit slot, and refused a deposit for one opened with `mode: manual` — that mode hands out no callback URL, so a deployment that picked it had not opted into an unauthenticated receiver. The deposited code and the PKCE verifier are both claimed before the exchange's first `await`, so two redirects racing deposit once and two polls racing redeem once.
+- Answered `HEAD` on the callback path with 405: Hono re-dispatches a HEAD as a GET before routing, which would otherwise have let a method HTTP requires to be safe spend the flow's deposit.
+- Held the exemption to that one literal path. `/start`, `/:flowId/code` and the status route were left owner-only, and registering the literal path first keeps `:flowId` from matching `callback`.
+- Deleted the unused `ModelOAuthService.providerOf`.
+- Recorded the receiver, its exact scope and the two-step redemption in the Server API and Models documents, in both languages.
diff --git a/changelog/unreleased/2026-08-26-model-oauth-desktop-callback.zh.md b/changelog/unreleased/2026-08-26-model-oauth-desktop-callback.zh.md
new file mode 100644
index 00000000..81c671e1
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-model-oauth-desktop-callback.zh.md
@@ -0,0 +1,20 @@
+# 桌面端也能走完授权新建 API key 的跳回
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`, `docs`
+- **PR:** [#502](https://github.com/Prism-Shadow/penguin-harness/pull/502)
+
+[English](2026-08-26-model-oauth-desktop-callback.md)
+
+TokenDance 的**授权新建 key** 在桌面端会以 `unauthorized`("Not signed in or the sign-in has expired.")失败,同样的操作在浏览器里却能完成。此前每一次桌面端授权都在处理函数运行前就以 401 结束:授权页在系统浏览器中打开,供应商跳回的也是**那个**浏览器,而它并不持有 `http://localhost:<port>` 的 `penguin_session` Cookie。跳回地址不再要求会话——同时也不再自行兑换任何东西,这样这条无需会话即可应答的路由就始终没有写入凭据的权限。
+
+## 细节
+
+- 把 `GET /api/projects/:projectId/model-oauth/callback` 挂载到全局认证中间件之前,改以 flow id 而非会话 Cookie 授权:服务端铸造的 32 字节随机数,绑定着一个用户、一个 Project、一个供应商,以及一个从不离开本进程的 PKCE verifier,有效期十分钟。
+- 把兑换拆成两步。跳回地址只把授权码存到流程上并回以"Authorization received";与供应商的兑换、以及写入该 Project 模型的动作,都挪到了 `GET /:flowId`——Owner 自己的轮询,仍在认证之后。兑换失败也改为在那里以 `{status: error, error}` 抵达对话框,而不再显示在跳回页面上。
+- 每个流程只留一个存放授权码的位置,并拒绝为 `mode: manual` 开启的流程存入——该模式压根不下发跳回地址,选用它的部署也就从未同意过多出一条无需会话的入口。存下的授权码与 PKCE verifier 都在兑换的第一个 `await` 之前被取走,因此两个跳回相争只会存入一次,两个轮询相争也只会兑换一次。
+- 跳回路径上的 `HEAD` 返回 405:Hono 会在路由之前把 HEAD 改派为 GET,否则一个 HTTP 要求必须安全的方法就能把流程的存入名额用掉。
+- 豁免范围严格限于这一条字面路径。`/start`、`/:flowId/code` 与状态查询路由维持仅限 Owner,字面路径注册在前,也使 `:flowId` 不会匹配到 `callback`。
+- 删除了没有任何调用方的 `ModelOAuthService.providerOf`。
+- 在 Server API 与模型文档中以双语记录了这条跳回地址、它确切的豁免范围,以及两步兑换。
diff --git a/packages/docs/content/models.en.md b/packages/docs/content/models.en.md
index 0c551ddf..2a82eb8b 100644
--- a/packages/docs/content/models.en.md
+++ b/packages/docs/content/models.en.md
@@ -101,9 +101,9 @@ Pressing it opens the provider's authorization page in a new tab. Authorize ther
The exchange runs entirely on the server: the PKCE verifier is generated there and never reaches the browser, and the minted key goes straight into the model table without passing through it. An authorization is good for one key and expires in ten minutes.
-Where the redirect cannot come back — a desktop window that hands external links to the system browser, or a server the browser cannot reach on the address it was given — pick **Page can't redirect back? Enter the code by hand**. The authorization page then displays a one-time code instead of redirecting, and pasting it into the dialog finishes the same flow.
+Where the redirect cannot come back — a server the browser cannot reach on the address it was given — pick **Page can't redirect back? Enter the code by hand**. The authorization page then displays a one-time code instead of redirecting, and pasting it into the dialog finishes the same flow.
-Only the Project owner can start or finish an authorization. The full key is shown once and never again, so if saving it fails you have to authorize again and delete the unused key in the provider's console.
+Only the Project owner can start an authorization, and only their own signed-in session finishes one — in practice, the tab the dialog is open in. The redirect itself is received without a session, and has to be, because the browser the provider sends back is not always the one you started in. But all that redirect does is hand the code over: nothing is redeemed and no key is saved until the dialog asks for the result. The full key is shown once and never again, so if saving it fails you have to authorize again and delete the unused key in the provider's console.
## Local / self-hosted OpenAI-compatible endpoints (e.g. vLLM)
diff --git a/packages/docs/content/models.zh.md b/packages/docs/content/models.zh.md
index 78fbe70d..d3d23fec 100644
--- a/packages/docs/content/models.zh.md
+++ b/packages/docs/content/models.zh.md
@@ -101,9 +101,9 @@ api_key = "sk-..."
整个兑换过程都在服务端进行:PKCE 的 verifier 在服务端生成、从不进入浏览器,新建出的 key 也直接写入模型表,不经过浏览器。一次授权只能换一个 key,且十分钟后过期。
-如果跳转回不来——桌面窗口会把外部链接交给系统浏览器,或者浏览器根本访问不到那个地址的服务——请选择**授权页跳不回来?改为手动填写授权码**。授权页会改为显示一次性授权码,粘贴到对话框即可完成同一套流程。
+如果跳转回不来——比如浏览器根本访问不到那个地址的服务——请选择**授权页跳不回来?改为手动填写授权码**。授权页会改为显示一次性授权码,粘贴到对话框即可完成同一套流程。
-只有 Project owner 能发起或完成授权。完整的 key 只会出现一次,因此一旦保存失败,需要重新授权,并到供应商控制台删掉那个没用上的 key。
+只有 Project owner 能发起授权,也只有他自己已登录的会话能完成授权——实际上就是打开着对话框的那个标签页。跳回地址本身不要求会话,也只能如此:供应商送回的浏览器未必就是你发起时的那一个。但跳回所做的只是把授权码交出来——在对话框去取结果之前,不会发生任何兑换,也不会有 key 被保存。完整的 key 只会出现一次,因此一旦保存失败,需要重新授权,并到供应商控制台删掉那个没用上的 key。
## 本地 / 自建 OpenAI 兼容端点(如 vLLM)
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 35ff0b46..45baa283 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -146,16 +146,22 @@ Every endpoint that names a model takes the complete `(provider, modelId)` pair.
#### Provider key minting
-Owner-only. A provider group that publishes an authorization flow in the built-in catalog can mint a **new** API key for the user in the browser, instead of the user copying one out of a console.
+Owner-only, except the redirect receiver `GET /callback`, which answers without a session and can do nothing but hand the code it was redirected with to the flow — see below. A provider group that publishes an authorization flow in the built-in catalog can mint a **new** API key for the user in the browser, instead of the user copying one out of a console.
| Method | Path | Description |
| --- | --- | --- |
| POST | /api/projects/:projectId/model-oauth/start | Open a flow: `{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |
-| GET | /api/projects/:projectId/model-oauth/callback | Where the provider redirects (`?flow=&code=`); exchanges, applies the key, answers an HTML page |
-| GET | /api/projects/:projectId/model-oauth/:flowId | Poll a flow: `{status: pending\|done\|error, provider, error?}` |
+| GET | /api/projects/:projectId/model-oauth/callback | Where the provider redirects (`?flow=&code=`); deposits the code on the flow and answers an HTML page. `HEAD` answers 405 |
+| GET | /api/projects/:projectId/model-oauth/:flowId | Poll a flow, redeeming a deposited code and applying the key: `{status: pending\|done\|error, provider, error?}` |
| POST | /api/projects/:projectId/model-oauth/:flowId/code | Redeem a code the user pasted: `{code}` → `{ok, applied?, error?}` |
-The PKCE verifier is generated server-side, held in memory for ten minutes, and never sent to a client; the minted key goes straight into the provider group's models and is never returned, logged, or put in a URL. A flow belongs to one user in one Project and is single-use — anyone else's request, and any second redemption, is refused. `mode: manual` omits the callback so the authorization page shows a one-time code to carry back by hand, for deployments the redirect cannot reach. A completed flow invalidates cached runtimes and publishes `credentials_updated`, exactly as `PUT /models` does.
+The PKCE verifier is generated server-side, held in memory for ten minutes, and never sent to a client; the minted key goes straight into the provider group's models and is never returned, logged, or put in a URL. A flow belongs to one user in one Project and is single-use: a second redemption is refused, and `/start`, `/:flowId` and `/:flowId/code` refuse anyone but that owner.
+
+`GET /callback` is the exception, and has to be. A loopback OAuth redirect is delivered by whichever browser the provider redirected, which is not necessarily the one that started the flow — the desktop shell opens the authorization page in the *system* browser, which holds no cookie for the app's origin. So that one path is mounted outside the session gate and authorizes on the flow id instead: 32 random bytes, valid for ten minutes, depositable once, and only against the Project the flow was opened in, and only for a flow that asked for a callback at all (a `manual` flow is refused, since it was handed no callback URL).
+
+What that route may do is bounded a second time: it stores the code on the flow and nothing else. The exchange with the provider and the write into the Project's models both run on `GET /:flowId`, the owner's own poll, behind the session gate — so no key reaches a Project without its owner asking for its flow's status, and a failed exchange is reported there as `{status: error, error}` rather than on the redirect page. Nothing adjacent is exempt either: a longer path, any other method (`HEAD` on the literal path answers 405), and the three sibling routes all still require the session.
+
+`mode: manual` omits the callback so the authorization page shows a one-time code to carry back by hand, for deployments the redirect cannot reach. Whichever route redeems the code, a completed flow invalidates cached runtimes and publishes `credentials_updated`, exactly as `PUT /models` does.
### Agents
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 807b431f..6a86f330 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -146,16 +146,22 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
#### 授权新建 API key
-仅限 Owner。若某个供应商分组在内置目录中声明了授权流程,用户可以在浏览器里授权并**新建**一个 API key,不必再去控制台复制。
+仅限 Owner,但供应商跳回的 `GET /callback` 例外——它无需会话即可应答,且只能把跳回时带来的授权码存到流程上,详见下文。若某个供应商分组在内置目录中声明了授权流程,用户可以在浏览器里授权并**新建**一个 API key,不必再去控制台复制。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| POST | /api/projects/:projectId/model-oauth/start | 开启一次流程:`{provider, mode?: callback\|manual}` → `{flowId, authorizeUrl}` |
-| GET | /api/projects/:projectId/model-oauth/callback | 供应商跳回的地址(`?flow=&code=`):兑换、写入 key,并返回一个 HTML 页面 |
-| GET | /api/projects/:projectId/model-oauth/:flowId | 轮询流程状态:`{status: pending\|done\|error, provider, error?}` |
+| GET | /api/projects/:projectId/model-oauth/callback | 供应商跳回的地址(`?flow=&code=`):把授权码存到流程上,并返回一个 HTML 页面;`HEAD` 返回 405 |
+| GET | /api/projects/:projectId/model-oauth/:flowId | 轮询流程状态,并顺带兑换已存下的授权码、写入 key:`{status: pending\|done\|error, provider, error?}` |
| POST | /api/projects/:projectId/model-oauth/:flowId/code | 兑换用户粘贴的授权码:`{code}` → `{ok, applied?, error?}` |
-PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不下发到客户端;新建出的 key 直接写入该分组的模型,不回传、不记录日志、也不出现在 URL 中。一次流程只属于某个 Project 下的某个用户且只能用一次——其他人的请求、以及第二次兑换,都会被拒绝。`mode: manual` 不传回调地址,授权页改为显示一次性授权码供用户手动带回,适用于跳转回不来的部署。流程完成后同样会使缓存的运行时失效并发布 `credentials_updated`,与 `PUT /models` 一致。
+PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不下发到客户端;新建出的 key 直接写入该分组的模型,不回传、不记录日志、也不出现在 URL 中。一次流程只属于某个 Project 下的某个用户且只能用一次:第二次兑换会被拒绝,`/start`、`/:flowId`、`/:flowId/code` 也拒绝该 Owner 以外的任何人。
+
+`GET /callback` 是唯一的例外,且只能如此。环回地址上的 OAuth 跳转由供应商所跳转的那个浏览器送达,而它未必就是发起流程的那一个——桌面端 shell 会把授权页交给**系统**浏览器打开,系统浏览器并不持有该应用来源的 Cookie。因此这一条路径挂载在会话校验之外,改以 flow id 作为凭据:32 字节随机数,十分钟有效,只能存入一次,只对开启该流程的那个 Project 生效,且只服务于确实要了跳回地址的流程(`manual` 流程会被拒绝,它压根没拿到过跳回地址)。
+
+这条路由能做的事还有第二重边界:它只把授权码存到流程上,此外什么都不做。与供应商的兑换、以及写入该 Project 模型的动作,都发生在 `GET /:flowId`——Owner 自己的轮询,仍在会话校验之内。因此没有 Owner 主动查询流程状态,就不会有 key 落进任何 Project;兑换失败也在那里以 `{status: error, error}` 报出,而不是显示在跳回页面上。周边的一切同样不在豁免之内:更长的路径、其它任何请求方法(该字面路径上的 `HEAD` 返回 405),以及另外三条同级路由,仍然都需要会话。
+
+`mode: manual` 不传回调地址,授权页改为显示一次性授权码供用户手动带回,适用于跳转回不来的部署。无论由哪条路由完成兑换,流程完成后同样会使缓存的运行时失效并发布 `credentials_updated`,与 `PUT /models` 一致。
### Agent
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index b3861348..899807b8 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -122,7 +122,7 @@ import { eventsRoutes, userChannelKey } from "./http/routes/events.js";
import { projectsRoutes } from "./http/routes/projects.js";
import { membersRoutes } from "./http/routes/members.js";
import { modelsRoutes } from "./http/routes/models.js";
-import { modelOAuthRoutes } from "./http/routes/model-oauth.js";
+import { modelOAuthCallbackRoutes, modelOAuthRoutes } from "./http/routes/model-oauth.js";
import { chatDefaultsRoutes } from "./http/routes/chat-defaults.js";
import { commandPolicyRoutes } from "./http/routes/command-policy.js";
import { vaultRoutes } from "./http/routes/vault.js";
@@ -880,6 +880,21 @@ export function createApp(
await next();
});
+ // The provider key-minting redirect receiver, and the only business route mounted outside
+ // the auth gate below — the same shape /api/desktop/update uses in reverse, and for the
+ // mirror-image reason. A loopback OAuth callback is reached by whichever browser the
+ // provider redirected: on the desktop the shell hands the authorization page to the system
+ // browser, which holds no session cookie for this origin, so requiring one 401'd every
+ // desktop authorization. It authorizes on the flow id instead, and all it may do with one
+ // is deposit the code it carried: the exchange that writes a key runs on the owner's poll
+ // of the status route, behind this gate (see the route module).
+ //
+ // Exactly this literal path, registered here so the exemption cannot widen: the group
+ // mount below still carries /start, /:flowId/code and the status route behind the gate,
+ // and because this registration comes first, `:flowId` can never swallow "callback". Only
+ // GET is served, and the handler refuses the HEAD that Hono re-dispatches into it.
+ app.route("/api/projects/:projectId/model-oauth/callback", modelOAuthCallbackRoutes(deps));
+
// Protected routes: cookie -> auth_session -> user, over the runtime's auth service.
app.use("/api/*", authMiddleware(deps.authService));
app.route("/api/me", meRoutes(deps));
diff --git a/packages/server/src/http/routes/model-oauth.ts b/packages/server/src/http/routes/model-oauth.ts
index d4f9ed39..c1633489 100644
--- a/packages/server/src/http/routes/model-oauth.ts
+++ b/packages/server/src/http/routes/model-oauth.ts
@@ -5,10 +5,14 @@
* POST /api/projects/:p/model-oauth/:flowId/code,
* GET /api/projects/:p/model-oauth/:flowId.
*
- * Owner only, like every other route that spends or rewrites a Project's credentials. The
- * whole exchange runs here: the PKCE verifier is generated server-side and never leaves this
- * process, and the minted key goes straight into the Project's model config without passing
- * through the browser. A caller only ever holds an opaque flow id and a status.
+ * Owner only, like every other route that spends or rewrites a Project's credentials — with
+ * one deliberate exception, `GET /callback`, which is mounted ahead of the global auth
+ * middleware and only deposits the code it was redirected with (see
+ * `modelOAuthCallbackRoutes` below and its mount in app.ts).
+ *
+ * The whole exchange runs here: the PKCE verifier is generated server-side and never leaves
+ * this process, and the minted key goes straight into the Project's model config without
+ * passing through the browser. A caller only ever holds an opaque flow id and a status.
*/
import { Hono } from "hono";
import type {
@@ -101,27 +105,95 @@ p { margin: 0; color: #4b5563; }
`;
}
-/** One sentence per failure reason, phrased for the redirect page (the Web App localizes its own). */
-const FAILURE_TEXT: Record<string, string> = {
- invalid_request:
- "TokenDance rejected the authorization request. Start a new one in PenguinHarness.",
- code_rejected:
- "The authorization is no longer valid — it may have expired or already been used. Start a new one in PenguinHarness.",
- upstream_failed: "The provider did not return a usable key. Start a new one in PenguinHarness.",
- unreachable:
- "The provider could not be reached. Check the network and start a new one in PenguinHarness.",
- apply_failed:
- "A key was created but could not be saved. Authorize again, then delete the unused key in the provider's console.",
-};
+/** Credential change: same follow-up the models PUT performs, so live Sessions pick the key up. */
+function credentialsChanged(deps: AppDeps, projectId: string): void {
+ deps.manager.invalidateProjectRuntimes(projectId);
+ publishCredentialsUpdated(deps, projectId);
+}
-export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
+/**
+ * `GET /api/projects/:projectId/model-oauth/callback` — where the provider sends the browser
+ * back, and the ONE route of this group that does not require a session.
+ *
+ * It cannot require one. A loopback OAuth redirect receiver is reached by whichever browser
+ * the provider redirected, which is not necessarily the one that started the flow: the
+ * desktop shell hands every non-app URL to `shell.openExternal`, so the authorization page
+ * opens in the *system* browser, and the system browser holds no `penguin_session` cookie
+ * for `http://localhost:<port>`. Behind the global auth middleware every desktop
+ * authorization therefore ended on a bare 401 while the same flow completed in the browser,
+ * where the popup is a tab of the session that opened it.
+ *
+ * What it does without a session is deliberately less than finishing the flow: it deposits
+ * the code on the flow and says so. The exchange that redeems that code and writes the key
+ * runs on the owner's next poll of `GET /:flowId`, which is behind the gate — so this route
+ * has no authority of its own to write a credential into a Project. A caller who learned a
+ * flow id can put a code in front of that poll — but only by beating the provider's own
+ * redirect to the flow's single deposit slot, and what they deposit stays inert unless the
+ * owner's own session goes on to poll that flow.
+ *
+ * The flow id it authorizes on is a capability rather than a name: 32 random bytes minted
+ * server-side, bound in ModelOAuthService to a user, a Project, a provider and a PKCE
+ * verifier that never leaves this process, valid for ten minutes and depositable once. The
+ * Project in the path must be the flow's own, so a flow id cannot be redirected at a Project
+ * it does not belong to, and a flow opened in manual mode is refused outright — it was
+ * handed no callback URL, so it has no redirect to receive.
+ *
+ * Mounted separately (not inside `modelOAuthRoutes`) because the exemption has to be exactly
+ * this literal path: it is registered ahead of the auth middleware in app.ts, where a
+ * whole-group mount would have exempted /start, /:flowId/code and the status route with it.
+ * Those stay owner-only, unchanged. Only GET is served — the handler refuses the HEAD that
+ * Hono re-dispatches into it rather than let a safe method spend the deposit.
+ *
+ * Answers HTML throughout — a person is looking at this tab, not a client parsing JSON.
+ */
+export function modelOAuthCallbackRoutes(deps: AppDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
- /** Credential change: same follow-up the models PUT performs, so live Sessions pick the key up. */
- const credentialsChanged = (projectId: string): void => {
- deps.manager.invalidateProjectRuntimes(projectId);
- publishCredentialsUpdated(deps, projectId);
- };
+ app.get("/", (c) => {
+ // Hono re-dispatches a HEAD as a GET before routing and returns the result bodiless, so
+ // without this a HEAD would run the handler below and spend the flow's one deposit. The
+ // re-dispatch carries the original Request, so the method still reads as HEAD here.
+ if (c.req.method === "HEAD") return c.body(null, 405);
+ const projectId = requireValidId(c, "projectId");
+ const flowId = c.req.query("flow") ?? "";
+ // The provider appends `code=` to the callback URL it was given, preserving its path and
+ // query, which is how the flow id rides back alongside it.
+ const code = c.req.query("code") ?? "";
+ if (!FLOW_ID_RE.test(flowId) || !CODE_RE.test(code)) {
+ return c.html(
+ resultPage(
+ "Authorization failed",
+ "This link is incomplete. Return to PenguinHarness and start a new authorization.",
+ ),
+ 400,
+ );
+ }
+ try {
+ // The flow id is the credential here; there is no session to read a user from — and
+ // depositing is all this route may do with it.
+ deps.modelOAuth.deposit({ flowId, projectId, code });
+ } catch (err) {
+ const message =
+ err instanceof HttpError
+ ? err.message
+ : "Something went wrong. Return to PenguinHarness and start a new authorization.";
+ // A refusal is a page, not an API error: every one of them answers 400, and the
+ // service's own sentence is what tells the person what to do about it.
+ return c.html(resultPage("Authorization failed", message), 400);
+ }
+ return c.html(
+ resultPage(
+ "Authorization received",
+ "Return to PenguinHarness — it finishes the authorization and reports the outcome there. You can close this tab.",
+ ),
+ );
+ });
+
+ return app;
+}
+
+export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
// Opens a flow and returns the page to send the user to. The provider is looked up in the
// built-in catalog inside the service, which is what rejects a group that publishes no
@@ -153,54 +225,9 @@ export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
return c.json(started satisfies ModelOAuthStartResponse);
});
- // Where the provider sends the browser back. Registered before the `:flowId` status route
- // so the literal path wins. Answers HTML throughout — a person is looking at this tab, not
- // a client parsing JSON.
- app.get("/callback", async (c) => {
- const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
- const flowId = c.req.query("flow") ?? "";
- // The provider appends `code=` to the callback URL it was given, preserving its path and
- // query, which is how the flow id rides back alongside it.
- const code = c.req.query("code") ?? "";
- if (!FLOW_ID_RE.test(flowId) || !CODE_RE.test(code)) {
- return c.html(
- resultPage(
- "Authorization failed",
- "This link is incomplete. Return to PenguinHarness and start a new authorization.",
- ),
- 400,
- );
- }
- let result: Awaited<ReturnType<typeof deps.modelOAuth.complete>>;
- try {
- result = await deps.modelOAuth.complete({
- flowId,
- userId: c.var.user.userId,
- projectId,
- code,
- });
- } catch (err) {
- const message =
- err instanceof HttpError
- ? err.message
- : "Something went wrong. Return to PenguinHarness and start a new authorization.";
- return c.html(resultPage("Authorization failed", message), 400);
- }
- if (!result.ok) {
- return c.html(resultPage("Authorization failed", FAILURE_TEXT[result.error]!), 400);
- }
- credentialsChanged(projectId);
- return c.html(
- resultPage(
- "API key created",
- "The new key has been saved to this Project's models. You can close this tab and return to PenguinHarness.",
- ),
- );
- });
-
// Manual counterpart of the callback: the user pastes the one-time code the authorization
- // page displayed when it was asked not to redirect.
+ // page displayed when it was asked not to redirect. Owner-only, because unlike the
+ // callback this one IS reached by the App's own signed-in tab.
app.post("/:flowId/code", async (c) => {
const projectId = requireValidId(c, "projectId");
deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
@@ -224,12 +251,14 @@ export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
if (!result.ok) {
return c.json({ ok: false, error: result.error } satisfies ModelOAuthCodeResponse);
}
- credentialsChanged(projectId);
+ credentialsChanged(deps, projectId);
return c.json({ ok: true, applied: result.applied } satisfies ModelOAuthCodeResponse);
});
- // Poll target while the user is authorizing in the other tab.
- app.get("/:flowId", (c) => {
+ // Poll target while the user is authorizing in the other tab, and where a redirect flow's
+ // exchange actually runs: the receiver only deposits the code, so the key is minted and
+ // written under the owner's own session (see the service's `deposit` and `poll`).
+ app.get("/:flowId", async (c) => {
const projectId = requireValidId(c, "projectId");
deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
const flowId = c.req.param("flowId") ?? "";
@@ -240,8 +269,15 @@ export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
"This authorization has expired or does not exist. Start a new one.",
);
}
- const state = deps.modelOAuth.status({ flowId, userId: c.var.user.userId, projectId });
- return c.json(state satisfies ModelOAuthStatusResponse);
+ const state = await deps.modelOAuth.poll({ flowId, userId: c.var.user.userId, projectId });
+ // Set only on the poll that redeemed, so the follow-up fires once, exactly as it does on
+ // the pasted-code route.
+ if (state.applied !== undefined) credentialsChanged(deps, projectId);
+ return c.json({
+ status: state.status,
+ provider: state.provider,
+ ...(state.error !== undefined ? { error: state.error } : {}),
+ } satisfies ModelOAuthStatusResponse);
});
return app;
diff --git a/packages/server/src/services/model-oauth-service.ts b/packages/server/src/services/model-oauth-service.ts
index 56f82b9a..98c6ab0c 100644
--- a/packages/server/src/services/model-oauth-service.ts
+++ b/packages/server/src/services/model-oauth-service.ts
@@ -12,6 +12,13 @@
* straight into the Project's model config and is never echoed to a caller, a URL, or a
* log line. What the Web App holds is an opaque flow id and a status.
*
+ * That flow id is also a capability, and the flow store treats it as one: 32 random bytes
+ * bound here to a user, a Project, a provider and a verifier, valid for ten minutes and
+ * spendable once. The loopback redirect receiver leans on exactly that, because the browser
+ * the provider redirects cannot be assumed to hold a session — see the route module. What
+ * that receiver may do with the id is only `deposit`: the exchange itself runs on the
+ * owner's own poll, so no key is ever written for a Project without its owner asking.
+ *
* Flows are in-memory and per-App: a restart or a platform push drops the pending ones,
* which costs the user a re-authorization and nothing else (the upstream code expires in
* minutes anyway, and no key exists until the exchange runs).
@@ -47,9 +54,18 @@ interface Flow {
projectId: string;
userId: string;
provider: string;
+ /** How the code travels back; only a `callback` flow has a redirect receiver to serve. */
+ mode: ModelOAuthMode;
exchangeUrl: string;
- /** PKCE verifier; dropped the moment the flow reaches a terminal state. */
+ /** PKCE verifier; dropped the moment the flow is spent. */
verifier: string | null;
+ /**
+ * The authorization code a redirect deposited, waiting for the owner's next poll to
+ * redeem it. Null until the redirect arrives and null again the instant the exchange
+ * claims it, so it can never be redeemed twice; the flow's TTL bounds how long it may sit
+ * here unspent.
+ */
+ code: string | null;
createdAt: number;
expiresAt: number;
status: ModelOAuthStatus;
@@ -241,8 +257,10 @@ export class ModelOAuthService {
projectId: input.projectId,
userId: input.userId,
provider: input.provider,
+ mode: input.mode,
exchangeUrl: oauth.exchangeUrl,
verifier,
+ code: null,
createdAt,
expiresAt: createdAt + FLOW_TTL_MS,
status: "pending",
@@ -258,31 +276,76 @@ export class ModelOAuthService {
}
/**
- * A flow's current state for its owner. 404 for anything the caller may not see —
- * unknown, expired, or belonging to another user or Project — so a flow id is never a
- * probe for what exists.
+ * Record the authorization code a redirect carried back — the whole power of the loopback
+ * receiver, which answers without a session because the browser the provider redirects
+ * cannot be assumed to hold one (on the desktop it is the *system* browser; see the route
+ * module).
+ *
+ * Depositing reaches no provider and writes no credential. The exchange runs later, in
+ * `poll`, under the flow owner's own session, so a caller who learned a flow id can at
+ * most put a code in front of that poll — and only by beating the provider's own redirect
+ * to the flow's single deposit slot, after which what they left there stays inert unless
+ * the owner's own session polls the flow.
+ *
+ * Refused for anything the depositor may not act on: an unknown, foreign or expired flow
+ * (404, the same answer to each, so a flow id stays useless as a probe for what exists), a
+ * flow opened in manual mode — which was handed no callback URL and therefore has no
+ * redirect to receive — and a flow already carrying a code or already spent (409). The
+ * check and the write are one synchronous step, so two redirects arriving together cannot
+ * both deposit.
*/
- status(input: { flowId: string; userId: string; projectId: string }): {
+ deposit(input: { flowId: string; projectId: string; code: string }): void {
+ const flow = this.require({ ...input, userId: null });
+ if (flow.mode !== "callback") {
+ throw new HttpError(
+ 404,
+ "model_oauth_flow_not_found",
+ "This authorization has expired or does not exist. Start a new one.",
+ );
+ }
+ if (flow.status !== "pending" || flow.verifier === null || flow.code !== null) {
+ throw new HttpError(
+ 409,
+ "model_oauth_flow_used",
+ "This authorization has already been used. Start a new one in PenguinHarness.",
+ );
+ }
+ flow.code = input.code;
+ }
+
+ /**
+ * A flow's current state for its owner, redeeming a deposited code on the way. 404 for
+ * anything the caller may not see — unknown, expired, or belonging to another user or
+ * Project — so a flow id is never a probe for what exists.
+ *
+ * The redirect flow's exchange happens here rather than in the receiver, which is what
+ * keeps writing a key into a Project behind that Project owner's session. `applied` is set
+ * only on the call that actually redeemed, and is how the route knows to publish the
+ * credential change; a deposited code nobody polls for is dropped with the flow at its TTL.
+ */
+ async poll(input: { flowId: string; userId: string; projectId: string }): Promise<{
status: ModelOAuthStatus;
provider: string;
error?: ModelOAuthErrorCode;
- } {
+ applied?: number;
+ }> {
const flow = this.require(input);
+ // Reading the code and claiming it inside `redeem` is one synchronous stretch, so two
+ // overlapping polls cannot both reach the exchange: the second finds nothing deposited
+ // and reports the flow still pending, and the tick after that reports the outcome.
+ const result = flow.code !== null ? await this.redeem(flow, flow.code) : null;
return {
status: flow.status,
provider: flow.provider,
...(flow.errorCode !== undefined ? { error: flow.errorCode } : {}),
+ ...(result?.ok === true ? { applied: result.applied } : {}),
};
}
/**
- * Redeem a code against a pending flow and write the minted key onto the group.
- *
- * One shot: the flow leaves `pending` before the exchange runs, so a replayed callback
- * cannot spend the same verifier twice, and the verifier is dropped from memory as soon
- * as it has been used. A key that arrives but cannot be stored is reported as
- * `apply_failed` — the user has to authorize again and delete the orphan, and saying so
- * is the only honest answer, since the provider reveals a key exactly once.
+ * Redeem a code the owner pasted — manual mode's counterpart to the redirect, and the
+ * only redemption a caller asks for directly. The flow must be this user's, in the named
+ * Project, inside its TTL and unspent.
*/
async complete(input: {
flowId: string;
@@ -290,19 +353,36 @@ export class ModelOAuthService {
projectId: string;
code: string;
}): Promise<{ ok: true; applied: number } | { ok: false; error: ModelOAuthErrorCode }> {
- const flow = this.require(input);
- if (flow.status !== "pending" || flow.verifier === null) {
+ return this.redeem(this.require(input), input.code);
+ }
+
+ /**
+ * Spend a flow: redeem one code against its verifier and write the minted key onto the
+ * group. Refuses a flow that is not still pending with a verifier in hand.
+ *
+ * One shot: everything that marks the flow as spent happens before the first await, so
+ * two callers arriving together cannot both reach the exchange, and the verifier and the
+ * deposited code leave memory as they are used. A key that arrives but cannot be stored is
+ * reported as `apply_failed` — the user has to authorize again and delete the orphan, and
+ * saying so is the only honest answer, since the provider reveals a key exactly once.
+ */
+ private async redeem(
+ flow: Flow,
+ code: string,
+ ): Promise<{ ok: true; applied: number } | { ok: false; error: ModelOAuthErrorCode }> {
+ const verifier = flow.verifier;
+ if (flow.status !== "pending" || verifier === null) {
throw new HttpError(
409,
"model_oauth_flow_used",
"This authorization has already been completed. Start a new one.",
);
}
- const verifier = flow.verifier;
flow.verifier = null;
+ flow.code = null;
const result = await exchangeCode({
exchangeUrl: flow.exchangeUrl,
- code: input.code,
+ code,
verifier,
fetchImpl: this.fetchImpl,
});
@@ -323,17 +403,21 @@ export class ModelOAuthService {
return { ok: true, applied };
}
- /** The provider group a flow belongs to (the route needs it before it can complete one). */
- providerOf(input: { flowId: string; userId: string; projectId: string }): string {
- return this.require(input).provider;
- }
-
- private require(input: { flowId: string; userId: string; projectId: string }): Flow {
+ /**
+ * The flow a caller may act on. 404 for anything they may not see — unknown, expired, or
+ * belonging to another user or another Project — so a flow id is never a probe for what
+ * exists.
+ *
+ * A `null` userId waives the user check and nothing else, and only `deposit` passes it
+ * (see there): the flow id is then the credential. The Project and the TTL are checked
+ * either way.
+ */
+ private require(input: { flowId: string; userId: string | null; projectId: string }): Flow {
this.sweep();
const flow = this.flows.get(input.flowId);
if (
flow === undefined ||
- flow.userId !== input.userId ||
+ (input.userId !== null && flow.userId !== input.userId) ||
flow.projectId !== input.projectId ||
flow.expiresAt <= this.now()
) {
diff --git a/packages/server/test/model-oauth.test.ts b/packages/server/test/model-oauth.test.ts
index e520044b..f33b00cb 100644
--- a/packages/server/test/model-oauth.test.ts
+++ b/packages/server/test/model-oauth.test.ts
@@ -3,6 +3,10 @@
* expiry and single-use rules, the exchange's error mapping, and the routes end to end —
* owner-only, key written to every model of the group, `credentials_updated` published.
*
+ * The redirect receiver is the one route of the group that answers without a session, and
+ * the last describe covers exactly that: what the flow id alone buys, and — case by case —
+ * what it still does not.
+ *
* No test reaches the network: `exchangeCode` takes its fetch as an argument, and the route
* cases stub the global one.
*/
@@ -24,6 +28,7 @@ import {
codeChallenge,
createVerifier,
exchangeCode,
+ FLOW_TTL_MS,
ModelOAuthService,
} from "../src/services/model-oauth-service.js";
import { requestOrigin } from "../src/http/routes/model-oauth.js";
@@ -164,6 +169,8 @@ describe("code exchange", () => {
describe("flow store", () => {
let clock: number;
let applied: { projectId: string; provider: string; apiKey: string }[];
+ /** Codes the stub exchange was asked to redeem, in order. */
+ let exchanged: string[];
let service: ModelOAuthService;
const start = () =>
@@ -178,12 +185,16 @@ describe("flow store", () => {
beforeEach(() => {
clock = 1_700_000_000_000;
applied = [];
+ exchanged = [];
service = new ModelOAuthService({
applyGroupKey: async (projectId, provider, apiKey) => {
applied.push({ projectId, provider, apiKey });
return 6;
},
- fetchImpl: (async () => jsonResponse(200, { key: "sk-minted" })) as unknown as typeof fetch,
+ fetchImpl: (async (_url: string, init: RequestInit) => {
+ exchanged.push((JSON.parse(String(init.body)) as { code: string }).code);
+ return jsonResponse(200, { key: "sk-minted" });
+ }) as unknown as typeof fetch,
now: () => clock,
});
});
@@ -211,12 +222,16 @@ describe("flow store", () => {
expect(flowId).toMatch(/^[A-Za-z0-9_-]{43}$/);
});
- it("a flow belongs to one user in one Project; anyone else sees a 404", () => {
+ it("a flow belongs to one user in one Project; anyone else sees a 404", async () => {
const { flowId } = start();
- expect(service.status({ flowId, userId: "u1", projectId: "p1" }).status).toBe("pending");
- expect(() => service.status({ flowId, userId: "u2", projectId: "p1" })).toThrow(HttpError);
- expect(() => service.status({ flowId, userId: "u1", projectId: "p2" })).toThrow(HttpError);
- expect(() => service.status({ flowId: "nope", userId: "u1", projectId: "p1" })).toThrow(
+ expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).status).toBe("pending");
+ await expect(service.poll({ flowId, userId: "u2", projectId: "p1" })).rejects.toThrow(
+ HttpError,
+ );
+ await expect(service.poll({ flowId, userId: "u1", projectId: "p2" })).rejects.toThrow(
+ HttpError,
+ );
+ await expect(service.poll({ flowId: "nope", userId: "u1", projectId: "p1" })).rejects.toThrow(
HttpError,
);
});
@@ -224,9 +239,11 @@ describe("flow store", () => {
it("expires after ten minutes, and the expired flow is gone rather than failed", async () => {
const { flowId } = start();
clock += 10 * 60 * 1000 - 1;
- expect(service.status({ flowId, userId: "u1", projectId: "p1" }).status).toBe("pending");
+ expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).status).toBe("pending");
clock += 1;
- expect(() => service.status({ flowId, userId: "u1", projectId: "p1" })).toThrow(HttpError);
+ await expect(service.poll({ flowId, userId: "u1", projectId: "p1" })).rejects.toThrow(
+ HttpError,
+ );
await expect(
service.complete({ flowId, userId: "u1", projectId: "p1", code: "c" }),
).rejects.toThrow(HttpError);
@@ -239,7 +256,7 @@ describe("flow store", () => {
applied: 6,
});
expect(applied).toEqual([{ projectId: "p1", provider: "tokendance", apiKey: "sk-minted" }]);
- expect(service.status({ flowId, userId: "u1", projectId: "p1" }).status).toBe("done");
+ expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).status).toBe("done");
await expect(
service.complete({ flowId, userId: "u1", projectId: "p1", code: "c" }),
).rejects.toThrow(HttpError);
@@ -257,7 +274,7 @@ describe("flow store", () => {
ok: false,
error: "code_rejected",
});
- const state = service.status({ flowId, userId: "u1", projectId: "p1" });
+ const state = await service.poll({ flowId, userId: "u1", projectId: "p1" });
expect(state).toEqual({ status: "error", provider: "tokendance", error: "code_rejected" });
});
@@ -274,7 +291,54 @@ describe("flow store", () => {
ok: false,
error: "apply_failed",
});
- expect(service.status({ flowId, userId: "u1", projectId: "p1" }).error).toBe("apply_failed");
+ expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).error).toBe(
+ "apply_failed",
+ );
+ });
+
+ it("a deposited code is redeemed by the owner's poll, not by the deposit itself", async () => {
+ const { flowId } = start();
+ service.deposit({ flowId, projectId: "p1", code: "redirected-code" });
+ // The deposit alone reaches no provider and writes nothing.
+ expect(applied).toEqual([]);
+ expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).status).toBe("done");
+ expect(applied).toEqual([{ projectId: "p1", provider: "tokendance", apiKey: "sk-minted" }]);
+ // `applied` is set on the redeeming poll only, so the route publishes the change once.
+ expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).applied).toBeUndefined();
+ expect(applied).toHaveLength(1);
+ });
+
+ it("a manual flow has no redirect to receive, so it cannot be deposited into", () => {
+ const { flowId } = service.start({
+ projectId: "p1",
+ userId: "u1",
+ provider: "tokendance",
+ mode: "manual",
+ callbackOrigin: "http://127.0.0.1:8123",
+ });
+ expect(() => service.deposit({ flowId, projectId: "p1", code: "c" })).toThrow(HttpError);
+ });
+
+ it("the deposit slot holds one code: a second redirect neither overwrites it nor re-arms it", async () => {
+ const { flowId } = start();
+ service.deposit({ flowId, projectId: "p1", code: "first" });
+ expect(() => service.deposit({ flowId, projectId: "p1", code: "second" })).toThrow(HttpError);
+ expect((await service.poll({ flowId, userId: "u1", projectId: "p1" })).status).toBe("done");
+ expect(exchanged).toEqual(["first"]);
+ // And once redeemed there is nothing left to deposit into either.
+ expect(() => service.deposit({ flowId, projectId: "p1", code: "third" })).toThrow(HttpError);
+ expect(exchanged).toEqual(["first"]);
+ });
+
+ it("a deposited code that nobody polls for expires with the flow", async () => {
+ const { flowId } = start();
+ service.deposit({ flowId, projectId: "p1", code: "never-polled" });
+ clock += FLOW_TTL_MS;
+ await expect(service.poll({ flowId, userId: "u1", projectId: "p1" })).rejects.toThrow(
+ HttpError,
+ );
+ expect(exchanged).toEqual([]);
+ expect(applied).toEqual([]);
});
});
@@ -355,7 +419,7 @@ describe("model-oauth routes", () => {
expect((await owner.post(`${base()}/start`, { provider: "deepseek" })).status).toBe(400);
});
- it("the callback redeems the code, writes the key to every model of the group, and reports it back in HTML", async () => {
+ it("the callback deposits the code and the owner's poll redeems it, writing the key to every model of the group", async () => {
const started = (await (
await owner.post(`${base()}/start`, { provider: "tokendance" })
).json()) as ModelOAuthStartResponse;
@@ -382,11 +446,19 @@ describe("model-oauth routes", () => {
expect(cb.status).toBe(200);
expect(cb.headers.get("content-type")).toContain("text/html");
const page = await cb.text();
- expect(page).toContain("API key created");
- // The page tells the user the outcome and nothing else.
+ expect(page).toContain("Authorization received");
+ // The page tells the user where to look and nothing else.
expect(page).not.toContain("sk-oauth-minted-key-9911");
expect(page).not.toContain("auth-code-1");
expect(page).not.toContain("http://");
+ // The receiver only wrote the code onto the flow: no provider was called yet.
+ expect(exchanges).toHaveLength(0);
+
+ // The owner's poll is what redeems it, and it reports the finished flow in the same tick.
+ const status = (await (
+ await owner.get(`${base()}/${started.flowId}`)
+ ).json()) as ModelOAuthStatusResponse;
+ expect(status).toEqual({ status: "done", provider: "tokendance" });
// The exchange spoke the documented protocol, with a verifier this side never published.
expect(exchanges).toHaveLength(1);
@@ -416,11 +488,18 @@ describe("model-oauth routes", () => {
.filter((e) => e.event === "server_event")
.map((e) => (JSON.parse(e.data) as { type: string }).type),
).toContain("credentials_updated");
-
- const status = (await (
- await owner.get(`${base()}/${started.flowId}`)
- ).json()) as ModelOAuthStatusResponse;
- expect(status).toEqual({ status: "done", provider: "tokendance" });
+ // Published by the redeeming poll alone; the ones after it report a finished flow only.
+ expect(await (await owner.get(`${base()}/${started.flowId}`)).json()).toEqual({
+ status: "done",
+ provider: "tokendance",
+ });
+ expect(
+ events.filter(
+ (e) =>
+ e.event === "server_event" &&
+ (JSON.parse(e.data) as { type: string }).type === "credentials_updated",
+ ),
+ ).toHaveLength(1);
// Replaying the same callback cannot spend the flow twice.
const replay = await owner.get(
@@ -430,7 +509,7 @@ describe("model-oauth routes", () => {
expect(exchanges).toHaveLength(1);
});
- it("a rejected code leaves the flow in error and never touches the models", async () => {
+ it("a rejected code leaves the flow in error, reaches the dialog through the poll, and never touches the models", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => jsonResponse(403, { error: "invalid_code" })),
@@ -438,15 +517,20 @@ describe("model-oauth routes", () => {
const started = (await (
await owner.post(`${base()}/start`, { provider: "tokendance" })
).json()) as ModelOAuthStartResponse;
+ // The redirect cannot know the exchange will fail — it deposits and says so.
const cb = await owner.get(`${base()}/callback?flow=${started.flowId}&code=stale`);
- expect(cb.status).toBe(400);
- expect(await cb.text()).toContain("no longer valid");
+ expect(cb.status).toBe(200);
+ expect(await cb.text()).toContain("Authorization received");
+ // The failure surfaces where the dialog is looking, and the flow is left ended, not stuck.
const status = (await (
await owner.get(`${base()}/${started.flowId}`)
).json()) as ModelOAuthStatusResponse;
expect(status.status).toBe("error");
expect(status.error).toBe("code_rejected");
+ expect(
+ (await (await owner.get(`${base()}/${started.flowId}`)).json()) as ModelOAuthStatusResponse,
+ ).toEqual({ status: "error", provider: "tokendance", error: "code_rejected" });
const models = (await (
await owner.get(`/api/projects/${projectId}/models`)
@@ -491,3 +575,267 @@ describe("model-oauth routes", () => {
);
});
});
+
+/**
+ * The redirect receiver's exemption from the session gate.
+ *
+ * This is the desktop's whole story: the shell hands every non-app URL to
+ * `shell.openExternal`, so the authorization page opens in the *system* browser, and the
+ * system browser is redirected back to `http://localhost:<port>` holding no
+ * `penguin_session` cookie for it. Behind the gate that was a bare 401 on every desktop
+ * authorization while the browser — whose popup is a tab of the session that opened it —
+ * completed fine.
+ *
+ * So the flow id is the credential on this one route, and these cases pin the whole of what
+ * it buys. It is bounded twice over: depositing a code is all the route can do — no key
+ * reaches a Project until that Project's owner polls — and the deposit itself is one
+ * Project, one code, ten minutes, once, callback flows only, GET only. Everything below is
+ * asserted with NO cookie unless the case is specifically about a signed-in browser.
+ */
+describe("model-oauth callback without a session", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ /** A signed-in member of the flow's Project who is not its owner — the closest anyone gets. */
+ let stranger: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let otherProjectId: string;
+ let exchanges: number;
+
+ const base = (p = projectId) => `/api/projects/${p}/model-oauth`;
+ /** The system browser the provider redirected: a request carrying no cookie at all. */
+ const noSession = (apiPath: string, init?: RequestInit) => t.app.request(apiPath, init);
+ const startFlow = async (p = projectId): Promise<string> =>
+ (
+ (await (
+ await owner.post(`${base(p)}/start`, { provider: "tokendance" })
+ ).json()) as ModelOAuthStartResponse
+ ).flowId;
+ const callback = (flowId: string, code = "auth-code-1", p = projectId) =>
+ `${base(p)}/callback?flow=${encodeURIComponent(flowId)}&code=${code}`;
+ /** What the owner's dialog asks for every two seconds — and what redeems a deposited code. */
+ const poll = async (flowId: string, p = projectId): Promise<ModelOAuthStatusResponse> =>
+ (await (await owner.get(`${base(p)}/${flowId}`)).json()) as ModelOAuthStatusResponse;
+ /**
+ * Whether any model of the group ended up with a stored key. The group's entries always
+ * carry a `credential` (it holds the catalog's base URL), so only `apiKeyMasked` answers
+ * the question actually being asked.
+ */
+ const groupHasKey = async (p = projectId): Promise<boolean> => {
+ const models = (await (await owner.get(`/api/projects/${p}/models`)).json()) as ModelsResponse;
+ return models.models.some(
+ (m) => m.provider === "tokendance" && m.credential?.apiKeyMasked !== undefined,
+ );
+ };
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_o");
+ owner = apiClient(t.app, a.cookie);
+ const b = await provisionUser(t.app, "stranger_s");
+ stranger = apiClient(t.app, b.cookie);
+ const create = async (id: string): Promise<string> =>
+ (
+ (await (
+ await owner.post("/api/projects", { projectId: id, name: id })
+ ).json()) as ProjectCreateResponse
+ ).project.projectId;
+ projectId = await create("owner_o-td");
+ otherProjectId = await create("owner_o-td2");
+ expect(
+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "stranger_s" })).status,
+ ).toBe(201);
+
+ exchanges = 0;
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ exchanges += 1;
+ return jsonResponse(200, { key: "sk-oauth-minted-key-9911" });
+ }),
+ );
+ });
+ afterEach(async () => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ await t.cleanup();
+ });
+
+ it("takes the code from the system browser, which carries no cookie, and writes nothing until the owner polls", async () => {
+ // The desktop path: nothing but the flow id in the URL.
+ const flowId = await startFlow();
+ const desktop = await noSession(callback(flowId));
+ expect(desktop.status).toBe(200);
+ expect(desktop.headers.get("content-type")).toContain("text/html");
+ const page = await desktop.text();
+ expect(page).toContain("Authorization received");
+ // Says nothing but where to look, session or no session.
+ expect(page).not.toContain("sk-oauth-minted-key-9911");
+ expect(page).not.toContain("auth-code-1");
+
+ // Nothing was redeemed and nothing was stored: the route has no such authority.
+ expect(exchanges).toBe(0);
+ expect(await groupHasKey()).toBe(false);
+
+ // The owner's own poll is what spends the code and lands the key.
+ expect(await poll(flowId)).toEqual({ status: "done", provider: "tokendance" });
+ expect(exchanges).toBe(1);
+ expect(await groupHasKey()).toBe(true);
+ });
+
+ it("still takes the redirect of a signed-in tab, which is the browser path", async () => {
+ // The popup of the session that opened it was never broken and must not become so —
+ // the cookie is simply not consulted here.
+ const flowId = await startFlow();
+ const browser = await owner.get(callback(flowId, "auth-code-2"));
+ expect(browser.status).toBe(200);
+ expect(await browser.text()).toContain("Authorization received");
+ expect(await poll(flowId)).toEqual({ status: "done", provider: "tokendance" });
+ expect(exchanges).toBe(1);
+ expect(await groupHasKey()).toBe(true);
+ });
+
+ it("lets another signed-in user deposit no more than a stranger, and land nothing", async () => {
+ const flowId = await startFlow();
+ // Their cookie is not consulted on this route, so their redirect is received like anyone's.
+ expect((await stranger.get(callback(flowId))).status).toBe(200);
+ // And that is the end of what it buys them: they cannot poll the flow, so they cannot
+ // make the code they deposited become a key in someone else's Project.
+ expect((await stranger.get(`${base()}/${flowId}`)).status).toBe(403);
+ expect(exchanges).toBe(0);
+ expect(await groupHasKey()).toBe(false);
+ // Only the owner's poll spends it.
+ expect((await poll(flowId)).status).toBe("done");
+ expect(await groupHasKey()).toBe(true);
+ });
+
+ it("buys nothing for a flow id that does not exist", async () => {
+ const res = await noSession(callback("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
+ expect(res.status).toBe(400);
+ // The same page an expired or foreign flow gets: a flow id is not a probe for what exists.
+ expect(await res.text()).toContain("Authorization failed");
+ expect(exchanges).toBe(0);
+ expect(await groupHasKey()).toBe(false);
+ });
+
+ it("cannot be redirected at a Project the flow does not belong to", async () => {
+ const flowId = await startFlow();
+ const res = await noSession(callback(flowId, "auth-code-1", otherProjectId));
+ expect(res.status).toBe(400);
+ expect(exchanges).toBe(0);
+ expect(await groupHasKey(otherProjectId)).toBe(false);
+ // And the flow itself is untouched — the misdirected attempt did not spend it.
+ expect((await noSession(callback(flowId))).status).toBe(200);
+ expect((await poll(flowId)).status).toBe("done");
+ expect(await groupHasKey()).toBe(true);
+ });
+
+ it("refuses a flow past its ten-minute TTL", async () => {
+ const flowId = await startFlow();
+ // The service reads the clock through `Date.now()` at call time, so moving it is enough.
+ const expired = Date.now() + FLOW_TTL_MS + 1;
+ vi.spyOn(Date, "now").mockReturnValue(expired);
+ const res = await noSession(callback(flowId));
+ expect(res.status).toBe(400);
+ expect(exchanges).toBe(0);
+ vi.restoreAllMocks();
+ expect(await groupHasKey()).toBe(false);
+ });
+
+ it("bounds a deposited code by the same TTL: an unpolled flow expires with it", async () => {
+ const flowId = await startFlow();
+ expect((await noSession(callback(flowId))).status).toBe(200);
+ // The dialog was closed before its next tick; the code must not outlive the flow.
+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + FLOW_TTL_MS + 1);
+ expect((await owner.get(`${base()}/${flowId}`)).status).toBe(404);
+ vi.restoreAllMocks();
+ expect(exchanges).toBe(0);
+ expect(await groupHasKey()).toBe(false);
+ });
+
+ it("is single use: the redirect cannot be replayed, before or after the exchange", async () => {
+ const flowId = await startFlow();
+ expect((await noSession(callback(flowId))).status).toBe(200);
+ // A second redirect must not overwrite the deposited code nor re-arm the exchange.
+ const replay = await noSession(callback(flowId, "auth-code-2"));
+ expect(replay.status).toBe(400);
+ expect(await replay.text()).toContain("Authorization failed");
+
+ expect((await poll(flowId)).status).toBe("done");
+ expect((await noSession(callback(flowId))).status).toBe(400);
+ // One code redeemed, one verifier spent — and it was the first code, not the replay's.
+ expect(exchanges).toBe(1);
+ });
+
+ it("deposits once when two redirects arrive together, and spends it once", async () => {
+ const flowId = await startFlow();
+ const both = await Promise.all([
+ noSession(callback(flowId, "race-a")),
+ noSession(callback(flowId, "race-b")),
+ ]);
+ // The deposit slot is claimed synchronously, so exactly one of them can take it.
+ expect(both.map((r) => r.status).sort()).toEqual([200, 400]);
+ expect((await poll(flowId)).status).toBe("done");
+ expect(exchanges).toBe(1);
+ });
+
+ it("redeems a deposited code once when two polls arrive together", async () => {
+ // The single-use property lives in the exchange claim now: the verifier and the code are
+ // both nulled before the first await, so overlapping polls cannot both mint a key.
+ const flowId = await startFlow();
+ expect((await noSession(callback(flowId))).status).toBe(200);
+ const both = await Promise.all([poll(flowId), poll(flowId)]);
+ expect(exchanges).toBe(1);
+ expect(both.map((r) => r.status)).toContain("done");
+ for (const r of both) expect(r.status).not.toBe("error");
+ expect(await groupHasKey()).toBe(true);
+ });
+
+ it("refuses the HEAD that Hono re-dispatches as a GET, leaving the flow unspent", async () => {
+ const flowId = await startFlow();
+ const head = await noSession(callback(flowId), { method: "HEAD" });
+ expect(head.status).toBe(405);
+ expect(await head.text()).toBe("");
+ // A method HTTP requires to be safe changed nothing, so the real redirect still lands.
+ expect((await noSession(callback(flowId))).status).toBe(200);
+ expect((await poll(flowId)).status).toBe("done");
+ expect(exchanges).toBe(1);
+ expect(await groupHasKey()).toBe(true);
+ });
+
+ it("has no redirect to receive for a flow that chose manual mode", async () => {
+ const started = (await (
+ await owner.post(`${base()}/start`, { provider: "tokendance", mode: "manual" })
+ ).json()) as ModelOAuthStartResponse;
+ // The deployment opted out: no callback URL was ever handed to the provider.
+ expect(new URL(started.authorizeUrl).searchParams.has("callback_url")).toBe(false);
+
+ const res = await noSession(callback(started.flowId));
+ expect(res.status).toBe(400);
+ expect(await res.text()).toContain("Authorization failed");
+ expect(exchanges).toBe(0);
+ expect(await groupHasKey()).toBe(false);
+
+ // The paste box that mode did opt into still redeems it.
+ expect((await owner.post(`${base()}/${started.flowId}/code`, { code: "pasted" })).status).toBe(
+ 200,
+ );
+ expect(exchanges).toBe(1);
+ expect(await groupHasKey()).toBe(true);
+ });
+
+ it("exempts exactly this literal path, and nothing around it", async () => {
+ const flowId = await startFlow();
+ // GET on the literal path is the exemption — and it beats the `:flowId` status route,
+ // which would otherwise match "callback" and answer JSON from behind the gate.
+ const literal = await noSession(`${base()}/callback`);
+ expect(literal.status).toBe(400);
+ expect(literal.headers.get("content-type")).toContain("text/html");
+ // Everything adjacent is still gated: a longer path, another method, the sibling routes.
+ expect((await noSession(`${base()}/callback/extra`)).status).toBe(401);
+ expect((await noSession(`${base()}/callback`, { method: "POST" })).status).toBe(401);
+ expect((await noSession(`${base()}/start`, { method: "POST" })).status).toBe(401);
+ expect((await noSession(`${base()}/${flowId}`)).status).toBe(401);
+ expect((await noSession(`${base()}/${flowId}/code`, { method: "POST" })).status).toBe(401);
+ expect(exchanges).toBe(0);
+ });
+});