Skip to content

Commit 02a1e2f

Browse files
feat(scenarios): door mode builds a card through the MCP draft door with no project, in skill and rule arms (#35241)
Part of #34780 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:场景卡评测运行器新增 `--modes door`:客户端只拿到应用的 MCP 草稿门和技能,没有任何项目文件;运行器替人建包、连客户端、发布草稿,然后按现有规则评分。 - 为什么改:要实测"托管的规则文本还需要多少",就得能在同一张卡上对比带不带某个技能、带不带某组规则时的构建结果。 - 风险与回滚:只改 `@objectstack/scenarios`(评测工具包),产品包零改动;不传 `--modes door` 时行为不变。回滚即还原本 PR。 - 先看:`packages/qa/scenarios/src/runner/orchestrate.ts` 的 `doorMode`(建包、取令牌、发布、评分顺序);`src/runner/door.ts` 的 `readDoorRules`(规则文件拒收条件);`src/runner/driver.ts` 的 `doorAuthor`(客户端只能调 `mcp__app`)。 - 两分钟验证:`pnpm --filter @objectstack/scenarios exec vitest run --maxWorkers=2 test/runner/door.test.ts`,预期 21 个用例全绿。 - 需要你做的:合并后按 README「One round, five reps per arm」跑一轮(每个 arm 5 次),规则文件由你在仓库外提供。 ## What changes A fourth runner mode, `door`, in `@objectstack/scenarios`. No product package is touched. - **The client gets the draft door and nothing else.** A door turn runs in a fresh, empty directory outside the host project, removed after the turn. It is handed the booted app's MCP server with an OAuth token scoped `openid metadata:write`; the token sits in a 0600 config file outside that directory and never appears on argv or in the record. It may call `mcp__app` (plus `Skill` when given skills); `Bash`, `Edit`, `Write` and `NotebookEdit` are denied. The prompt (`doorBuildPrompt`) names the package and namespace and is the same text in every arm. - **Person-equivalent steps around the turn** (`doorMode`, `src/runner/orchestrate.ts`). Before the turn, the runner boots the host with the OAuth provider on and creates a writable package `com.scenario.NAMESPACE` in the card's namespace (`POST /api/v1/packages`). It mints the token over OAuth 2.1 + PKCE (`mintAuthoringToken`, `src/runner/app.ts`). After the turn, it lists the drafts and publishes them (`POST /api/v1/packages/ID/publish-drafts`). Then it grades what the environment serves, exactly as a scratch build is graded: Build half, then Run half. A publish that does not answer `published` is a finding naming each refused draft; the door answers a refusal on a 200, with `outcome: refused` under `data`. A refused package or token is a finding, and a harness without the doors is a skip naming them. - **Arms** (`src/runner/door.ts`, `src/runner/cli.ts`). There are two: - **Skills.** `--door-skills DIR`, less `--door-skill-omit`, uses the `--ask-skills` reader and its closed front-matter set. - **Rules.** `--door-rules FILE` or `OS_SCENARIOS_DOOR_RULES`, less `--door-rules-omit`, takes rule texts **the maintainer supplies at run time** in a documented generic format: `{ rules: [{ id, text }], sets? }`. The texts reach the client as its directory's `CLAUDE.md`. A missing, malformed or in-checkout rules file is refused before any card runs, naming what is wrong. The record states the arm: skills with sha256, the rules file's name and sha256, and the active and omitted ids, never a text. `summary` refuses to sum two arms. - **Replay.** `RecordedDriver` re-sends a door turn's recorded `save_metadata_draft` / `delete_metadata_draft` calls through the replay's own door and token, and reports a mismatch as not faithful. Codex and external drivers are refused for door mode. - README: a door mode section with the rules file format, the flags, and the maintainer's one-round command at five reps per arm. ## Tests The tests use replay and stub drivers only; no live model is run. - `test/runner/door.test.ts` (new, 21 cases), with invented rule texts: - **Rules file:** a valid file; each refusal (missing, a directory, no JSON, unknown key, empty text, bad id, empty set, duplicate id, a set naming an unknown id, a set named like a rule, an unknown selector, an empty selector entry, a selector that omits every rule, a file inside the checkout); `renderDoorRules`; `omitSkills`; `doorArmText`. - **Live-driver door turn, via a stand-in `claude`:** `--allowedTools mcp__app`; the four denied tools; an empty cwd; the token only in the MCP config; the arm's skills under `.claude/skills/` less the omitted one; the rules as `CLAUDE.md`; the record's arm; a scratch turn untouched by the arm. - **CLI parse and refusals:** door flags without door mode; an omit without its source; Codex/external refused; replay refusing live flags. - **Replay and summary:** a replay states the arm; `summary` refuses mixing arms. - `test/runner/orchestrate.test.ts` gains a top-level `runCard` describe for door mode (6 cases, on the file's existing fake harness): - end to end, covering the empty client cwd outside the host, the package, the token scope, the drafts, the publish, the scored Build and Run halves, the scorecard line, and the token absent from the record; - a publish refused on a 200; - a publish short of `published` with no refused draft; - a refused token, after which the driver is never asked; - the harness-gap skip; - a replay re-sending the saves through a new token, and a replay against an app that refuses a save, which leaves the build not measured. - One existing pin updated: the unknown-mode refusal now lists `door`. ## Acceptance notes - **Maintainer action after merge.** This is the card's "Done when": one eval round at five reps per arm. The containers are keyless, so no live model ran here. The command is in `packages/qa/scenarios/README.md` under "One round, five reps per arm". In short, for each arm: `pnpm --filter @objectstack/scenarios run-scenarios --modes door [--door-skills "$PWD/skills" [--door-skill-omit NAME]] [--door-rules /abs/path/outside/repo/rules.json [--door-rules-omit SET]] --record runs/door-ARM/repN.rec.json --out runs/door-ARM/repN` Then run `summary --mode door runs/door-ARM` once per arm. - **NOT MEASURED live.** Nothing was run against a live `os dev`: - the OAuth flow on `os dev -p PORT` (canonical origin and token audience); - package creation and the publish of door-made drafts. These doors were read from source, not exercised. A step the app refuses is recorded as a finding naming the step, never as a score. - **Follow-ups, not in this PR:** - The build skill the "with build skill" arm needs (#34778) does not exist yet. Until it does, the skills arm is the published `skills/` directory with and without a named omission. - The scenario-eval skill (governed `.claude/**`) needs a line about door mode. - The gallery exporter's record mode enum does not list `door`; door records are not exported to the gallery yet. - Moving a hosted rule corpus into this repository is left for the maintainer's own explicit word. This PR takes rules only from a maintainer-supplied file outside the repository, and every fixture text is invented. - **Ablation** (one-off, not a kept test): - **Run 1** removed the `publish.outcome !== 'published' ||` clause and checked it against the refused-publish case. That run stayed green: the refused case also carries `failed[]`, so it does not pin that clause. - **The fix.** I added the `published_unregistered` case, which publishes with no refused draft. - **Run 2** applied the same deletion and that case went red (`expected [] to deeply equal [ Array(1) ]`). The restore was proven: blob == HEAD and `git diff HEAD` was empty. - **A first no-op attempt.** An empty `--replacement` was refused by `ablation-replace` before anything ran, so it is not counted. ## Verification All at head `4e1b7624f1e`. <details><summary>Package tests and typecheck (under os-verify-lock)</summary> - `pnpm --filter @objectstack/scenarios build && pnpm --filter @objectstack/scenarios test`: `Test Files 40 passed (40)`, `Tests 1176 passed (1176)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/scenarios typecheck` (tsconfig includes `test/**`): `VERDICT command-exit 0`. - The dependency closure was built first: `pnpm --workspace-concurrency=2 --filter '@objectstack/scenarios^...' build`, `VERDICT command-exit 0`. - `test:repo` was not run locally: the diff touches no repo-project test. It is declared to CI. </details> <details><summary>Derived gate families</summary> - `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --commands` derived 67 families against merge base `ec227fc7b`. - All 67 ran at this head and exited 0. That includes `check:error-code-casing`, which was red once on a lowercase test fixture code and is fixed; `check:nul-bytes`; `check:published-files`; `check:dts-closure`; `check:dual-build-cjs-loads`; and `check:lean-entry-closure`. - `--ran` reconciliation: `67 derived famil(ies) accounted for — 67 run, 0 NOT-MEASURED (a DERIVED zero — all 67 recorded an exit code and none of them is 3)`. - `node scripts/pm/overlap-check.mjs` before each push: `VERDICT clean exit 0`. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbaX2qDxUq9sF93EqqL)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f2078e3 commit 02a1e2f

17 files changed

Lines changed: 1486 additions & 55 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/scenarios': patch
3+
---
4+
5+
feat(scenarios): `--modes door` builds a card through the MCP draft door with no project, then publishes it as a person would
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The runner gains a fourth mode. A door mode turn is given the booted app's MCP draft door (an OAuth token scoped `openid metadata:write`, in a 0600 config outside its directory), an empty directory of its own outside the host project, and nothing else: file and command tools are denied. The runner then does what a person does in Studio: it creates a writable package in the card's namespace before the turn, and lists and publishes that package's drafts after it (`POST /api/v1/packages/:id/publish-drafts`). It grades what the environment then serves exactly as a scratch build is graded, Build half then Run half. A publish that does not answer `published` is a finding naming each refused draft, since a refusal answers on a 200.
11+
12+
A round measures what instruction text is worth by arms. `--door-skills DIR` (less `--door-skill-omit`) gives the client Claude Code skills. `--door-rules FILE` or `OS_SCENARIOS_DOOR_RULES` (less `--door-rules-omit`) gives it rule texts the maintainer supplies from outside the repository, in a documented `{ rules: [{ id, text }], sets }` format that is refused loudly when malformed. The record states the arm (skills with sha256, the rules file's name and sha256, the ids active and omitted, never a text), and `summary` never sums two arms. A replay re-sends the recorded draft saves through the replay's own door. Codex and external drivers are refused for door mode.

‎packages/qa/scenarios/README.md‎

Lines changed: 89 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ pnpm --filter @objectstack/scenarios run-scenarios --effort medium # t
237237
pnpm --filter @objectstack/scenarios run-scenarios --author-effort high --ask-effort low # build and persona turns apart
238238
pnpm --filter @objectstack/scenarios run-scenarios --lang zh --prompt short # the card's Chinese texts, and its short build prompt (default: en, else zh; detailed)
239239
pnpm --filter @objectstack/scenarios run-scenarios --packages workspace # on this checkout's unreleased packages (default: published)
240+
pnpm --filter @objectstack/scenarios run-scenarios --modes door --door-skills "$PWD/skills" # build through the MCP draft door, no project (below)
240241
```
241242

242243
Per card and mode the runner writes `docs/qa/platform-checklist/runs/<date>-scenario-<card>.json`
@@ -263,7 +264,7 @@ files only: no model, no network, and no score of its own — every figure is th
263264
`this run’s from-scratch build` takes that run's scratch author.
264265
- **Never summed silently**: a table's runs must share the prompt choice, the package source, the ask repeats and the
265266
driver (a replay is its own driver), the ask skills (`--ask-skills`: names and sha256; a record without them
266-
reads `none`), and the card file they graded (`card`, below; a record without it reads `card: not recorded`).
267+
reads `none`), the door arm (`--modes door`, below; a record without one reads `skills: none · rules: none`), and the card file they graded (`card`, below; a record without it reads `card: not recorded`).
267268
When they do not, that table is refused with a line naming each difference and
268269
the files on each side; the other tables print, and the command exits 1. Summarize each side apart.
269270
- **The card stamp**: every record names the card file it graded at its top level, `card: { id, sha256 }` (the sha256
@@ -280,6 +281,93 @@ files only: no model, no network, and no score of its own — every figure is th
280281
- `--card ID[,ID]` and `--mode M[,M]` narrow the tables. Other JSON in a directory (recordings) is skipped and listed
281282
on stderr; a file named directly that is not a run record fails the command.
282283

284+
### Door mode — `--modes door`
285+
286+
Door mode builds the card the way a person's own MCP client builds an app on a running environment: through the
287+
app's **MCP draft door** (`save_metadata_draft` and its reads), with **no project and no files**. Then a
288+
person-equivalent step publishes what it staged, and the result is graded exactly as a scratch build is: the Build
289+
half on what the environment serves after the publish, then the Run half on that app. It builds once (no iterate).
290+
291+
Per card (`doorMode` in `src/runner/orchestrate.ts`):
292+
293+
1. A host project of its own namespace (`host<code>`) boots with the OAuth authorization server on
294+
(`OS_OIDC_PROVIDER_ENABLED=true`), and the runner signs in as the dev admin.
295+
2. **The person's steps, through the same doors Studio uses**: create a writable package `com.scenario.<namespace>`
296+
in the card's namespace (`POST /api/v1/packages`), and connect an MCP client: an OAuth 2.1 + PKCE token scoped
297+
`openid metadata:write`, the scope that serves the authoring tools.
298+
3. **The client's turn**: a fresh, empty directory outside the host project, removed after the turn. The token goes
299+
in a 0600 MCP config file outside that directory (never on argv, never in the record). The turn may call
300+
`mcp__app` (and `Skill` when it is given skills); `Bash`, `Edit`, `Write` and `NotebookEdit` are denied. The prompt
301+
names the package and the namespace and is the same text in every arm.
302+
4. **The publish**: the runner lists the package's drafts and publishes them
303+
(`POST /api/v1/packages/<id>/publish-drafts`), recording the outcome and each refused draft. A publish that does
304+
not answer `published` (a refusal answers on a 200) is a finding; the build is graded on what is served anyway.
305+
306+
A refused package, a refused token or a harness without these doors is a finding or a skip naming the step, never a
307+
score. The scorecard prints the steps on one line (`- door: package … created · client connected (…) · N drafts
308+
pending · publish: published, N published`).
309+
310+
**Arms.** One round measures what a piece of instruction text is worth by running the same cards with and without
311+
it. The arm is part of the driver's record (`env.driver.door`), and `summary` never sums two arms into one table.
312+
313+
- `--door-skills DIR`: the Claude Code skills the client is given, under its directory's `.claude/skills/` (the same
314+
reader and closed front-matter key set as `--ask-skills`). `--door-skill-omit NAME[,NAME]` leaves named skills of
315+
`DIR` out: with and without one skill is the same directory with and without that omission. The record names each
316+
skill given, with its version and sha256, and each omitted.
317+
- `--door-rules FILE` (or `OS_SCENARIOS_DOOR_RULES=FILE`): rule texts **the maintainer supplies at run time**, given to
318+
the client as its directory's `CLAUDE.md`. The file lives outside this repository; one inside the checkout is
319+
refused. `--door-rules-omit A[,B]` leaves out rule ids or named sets. The record names the file (its name, not its
320+
path), its sha256, and the ids active and omitted, never a text.
321+
322+
The rules file is one JSON object (`src/runner/door.ts` holds the whole contract):
323+
324+
```json
325+
{
326+
"rules": [
327+
{ "id": "rule-a", "text": "The full text of the first rule." },
328+
{ "id": "rule-b", "text": "The full text of the second rule." }
329+
],
330+
"sets": { "set-x": ["rule-a"] }
331+
}
332+
```
333+
334+
`rules` is a non-empty list of `{ id, text }` with unique ids; `sets` (optional) names lists of those ids. Refused
335+
before any card runs, naming what is wrong: a missing file, no JSON, an unknown key, an empty text, a duplicate id, a
336+
set naming no rule of the file or named like a rule, a selector naming nothing in the file, a selector that omits
337+
every rule (that arm is the run without `--door-rules`), and a file inside this checkout.
338+
339+
A rules-arm run's record and recording (`--record`) hold the client's transcripts, and a transcript can quote rule
340+
text the client was given: read them before filing either anywhere public.
341+
342+
Door mode runs on the live `claude` driver, or a replay of one (`--driver recorded:FILE` re-sends the recorded draft
343+
saves through the replay's own door and token, and refuses the run as not faithful when the app answers one
344+
otherwise). Codex and an external driver are refused.
345+
346+
**One round, five reps per arm** (the maintainer's run; each arm writes its own records directory):
347+
348+
```bash
349+
RULES=/abs/path/outside/the/repo/rules.json # the maintainer's file
350+
for arm in bare skills rules both; do
351+
case $arm in
352+
bare) flags=() ;;
353+
skills) flags=(--door-skills "$PWD/skills") ;;
354+
rules) flags=(--door-rules "$RULES") ;;
355+
both) flags=(--door-skills "$PWD/skills" --door-rules "$RULES") ;;
356+
esac
357+
for rep in 1 2 3 4 5; do
358+
pnpm --filter @objectstack/scenarios run-scenarios --modes door "${flags[@]}" \
359+
--record "$PWD/runs/door-$arm/rep$rep.rec.json" --out "$PWD/runs/door-$arm/rep$rep"
360+
done
361+
done
362+
for arm in bare skills rules both; do
363+
pnpm --filter @objectstack/scenarios run-scenarios summary --mode door "$PWD/runs/door-$arm"
364+
done
365+
```
366+
367+
Add `--door-skill-omit NAME` to an arm to measure one skill, or `--door-rules-omit SET` to measure one named set of
368+
rules; add `--model` / `--effort` as any round does. Summarize each arm apart: `summary` refuses a table whose runs
369+
differ in arm, naming both, and prints the arm on each table's dimensions line.
370+
283371
### Running from npm
284372

285373
No checkout needed: the package's `objectstack-scenarios` command is the same runner, with the same flags.

‎packages/qa/scenarios/src/runner/app.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,25 @@
5252
* answer is its text content; a refusal is that text carrying
5353
* `{ error: { code, status } }` with `isError` set.
5454
*
55+
* Door mode's doors (`doorMode` in `orchestrate.ts`), read from their sources and
56+
* the in-process dogfood that drives the same OAuth flow, not yet measured
57+
* against `os dev`:
58+
*
59+
* a writable package POST /api/v1/packages { manifest } — Studio's new-package
60+
* door; a scope-less package is a writable base (ADR-0070)
61+
* the door's token {@link mintAuthoringToken}: OAuth 2.1 + PKCE as the admin
62+
* pending drafts GET /api/v1/meta/_drafts?package=…
63+
* the person's publish POST /api/v1/packages/:id/publish-drafts — Studio's
64+
* Changes > Publish; a refusal answers `outcome: refused`
65+
* with `failed[]` on a 200
66+
*
5567
* The data API's refusal is the flat `{ error, code }` envelope; the auth and
5668
* install doors answer `{ success: false, error: { code, message } }`. Both
5769
* are read by {@link codeOf}.
5870
*/
5971

72+
import { createHash, randomBytes } from 'node:crypto';
73+
6074
import { PLURAL_TO_SINGULAR } from '@objectstack/spec/meta-spelling';
6175

6276
export interface HttpAnswer {
@@ -179,6 +193,20 @@ export interface AppHarness {
179193
metadataAsArtifact(collections: readonly string[]): Promise<Record<string, unknown[]>>;
180194
/** One MCP tool call as the owner of `apiKey`, through the door the agent uses (`mcpUrl`). */
181195
callTool(apiKey: string, tool: string, args: Record<string, unknown>): Promise<ToolAnswer>;
196+
// ── Door mode (`doorMode` in `orchestrate.ts`): each optional, so a harness
197+
// written before it keeps compiling; without them door mode is skipped, saying so.
198+
/** Studio's new-package door as the signed-in admin: `POST /api/v1/packages { manifest }`. */
199+
createPackage?(manifest: Record<string, unknown>): Promise<HttpAnswer>;
200+
/**
201+
* An OAuth access token for the MCP door, consented by the signed-in admin
202+
* and scoped `scope` (`mintAuthoringToken`, below): what a person's MCP
203+
* client holds after they connect it. Never written to a record.
204+
*/
205+
mintAuthoringToken?(scope: string): Promise<HttpAnswer & { token?: string }>;
206+
/** The package's pending drafts, as Studio's Changes review lists them: `GET /api/v1/meta/_drafts?package=`. */
207+
listDrafts?(packageId: string): Promise<HttpAnswer & { drafts: Array<{ type: string; name: string }> }>;
208+
/** Studio's publish of a package's drafts, as the signed-in admin: `POST /api/v1/packages/:id/publish-drafts`. */
209+
publishDrafts?(packageId: string): Promise<HttpAnswer>;
182210
}
183211

184212
export interface HttpAppOptions {
@@ -365,6 +393,26 @@ export class HttpApp implements AppHarness {
365393
return toolAnswerOf(rpc.result);
366394
}
367395

396+
createPackage(manifest: Record<string, unknown>): Promise<HttpAnswer> {
397+
return this.call('POST', '/api/v1/packages', { manifest }, { session: this.admin });
398+
}
399+
400+
async mintAuthoringToken(scope: string): Promise<HttpAnswer & { token?: string }> {
401+
return mintAuthoringToken(this.baseUrl, this.admin.header(), scope);
402+
}
403+
404+
async listDrafts(packageId: string): Promise<HttpAnswer & { drafts: Array<{ type: string; name: string }> }> {
405+
const r = await this.call('GET', `/api/v1/meta/_drafts?package=${encodeURIComponent(packageId)}`, undefined, { session: this.admin });
406+
const body = r.body as { drafts?: unknown; data?: { drafts?: unknown } } | null;
407+
const raw = body?.drafts ?? body?.data?.drafts;
408+
const drafts = (Array.isArray(raw) ? raw : []).filter(isBag).map((d) => ({ type: String(d.type ?? ''), name: String(d.name ?? '') }));
409+
return { ...r, drafts };
410+
}
411+
412+
publishDrafts(packageId: string): Promise<HttpAnswer> {
413+
return this.call('POST', `/api/v1/packages/${encodeURIComponent(packageId)}/publish-drafts`, {}, { session: this.admin });
414+
}
415+
368416
async metadataAsArtifact(collections: readonly string[]): Promise<Record<string, unknown[]>> {
369417
const out: Record<string, unknown[]> = {};
370418
for (const plural of collections) {
@@ -377,3 +425,83 @@ export class HttpApp implements AppHarness {
377425
return out;
378426
}
379427
}
428+
429+
/** The redirect URI the runner registers for its token: never served, the code is read off the redirect itself. */
430+
const DOOR_REDIRECT_URI = 'http://127.0.0.1:33419/callback';
431+
432+
/**
433+
* An OAuth access token for the MCP door, the way a person's MCP client gets
434+
* one (OAuth 2.1 with PKCE, the flow `packages/qa/dogfood` drives in process):
435+
* read the protected resource the app advertises
436+
* (`GET /.well-known/oauth-protected-resource`), register a public client
437+
* (`POST /api/v1/auth/oauth2/register`), authorize it as the signed-in person
438+
* (`cookie`), consenting when asked (`POST /api/v1/auth/oauth2/consent`), and
439+
* trade the code for the token (`POST /api/v1/auth/oauth2/token`). Each step
440+
* that answers otherwise is the answer, naming the step: absence is loud, and
441+
* the mode records it instead of running a client that holds no door.
442+
*/
443+
export async function mintAuthoringToken(baseUrl: string, cookie: string, scope: string): Promise<HttpAnswer & { token?: string }> {
444+
const read = async (res: Response): Promise<unknown> => {
445+
const text = await res.text();
446+
try {
447+
return text ? JSON.parse(text) : null;
448+
} catch {
449+
return text;
450+
}
451+
};
452+
const refused = (step: string, res: Response, body: unknown): HttpAnswer => {
453+
const c = codeOf(body);
454+
const oauth = isBag(body) && typeof body.error === 'string' ? { code: body.error, message: String(body.error_description ?? '') } : {};
455+
return { ok: false, status: res.status, body: null, ...c, ...oauth, message: `${step}: ${c.message ?? (oauth as { message?: string }).message ?? res.statusText}`.slice(0, 500) };
456+
};
457+
const prm = await fetch(`${baseUrl}/.well-known/oauth-protected-resource`, { headers: { accept: 'application/json' } });
458+
const prmBody = await read(prm);
459+
const resource = isBag(prmBody) && typeof prmBody.resource === 'string' ? prmBody.resource : undefined;
460+
if (!prm.ok || resource === undefined) return refused('the app advertises no OAuth protected resource for its MCP door', prm, prmBody);
461+
462+
const reg = await fetch(`${baseUrl}/api/v1/auth/oauth2/register`, {
463+
method: 'POST',
464+
headers: { 'content-type': 'application/json', accept: 'application/json' },
465+
body: JSON.stringify({
466+
client_name: 'scenario runner (door mode)',
467+
redirect_uris: [DOOR_REDIRECT_URI],
468+
grant_types: ['authorization_code'],
469+
response_types: ['code'],
470+
token_endpoint_auth_method: 'none',
471+
application_type: 'native',
472+
scope,
473+
}),
474+
});
475+
const regBody = await read(reg);
476+
const clientId = isBag(regBody) && typeof regBody.client_id === 'string' ? regBody.client_id : undefined;
477+
if (!reg.ok || clientId === undefined) return refused('client registration', reg, regBody);
478+
479+
const verifier = randomBytes(32).toString('base64url');
480+
const challenge = createHash('sha256').update(verifier).digest('base64url');
481+
const qs = new URLSearchParams({ client_id: clientId, redirect_uri: DOOR_REDIRECT_URI, response_type: 'code', scope, state: 'scenario', code_challenge: challenge, code_challenge_method: 'S256', resource });
482+
const az = await fetch(`${baseUrl}/api/v1/auth/oauth2/authorize?${qs}`, { headers: { cookie }, redirect: 'manual' });
483+
const loc = az.headers.get('location') ?? '';
484+
let code = loc ? new URL(loc, baseUrl).searchParams.get('code') : null;
485+
if (!code) {
486+
if (!loc) return refused('authorization', az, await read(az));
487+
// The consent screen: the person accepts, as they would in the browser.
488+
const consent = await fetch(`${baseUrl}/api/v1/auth/oauth2/consent`, {
489+
method: 'POST',
490+
headers: { 'content-type': 'application/json', accept: 'application/json', cookie, origin: baseUrl },
491+
body: JSON.stringify({ accept: true, oauth_query: loc.slice(loc.indexOf('?') + 1) }),
492+
});
493+
const cb = await read(consent);
494+
const to = isBag(cb) ? (typeof cb.redirect_uri === 'string' ? cb.redirect_uri : typeof cb.url === 'string' ? cb.url : undefined) : undefined;
495+
code = to ? new URL(to, baseUrl).searchParams.get('code') : null;
496+
if (!consent.ok || !code) return refused('consent', consent, cb);
497+
}
498+
const tok = await fetch(`${baseUrl}/api/v1/auth/oauth2/token`, {
499+
method: 'POST',
500+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
501+
body: new URLSearchParams({ grant_type: 'authorization_code', code, redirect_uri: DOOR_REDIRECT_URI, client_id: clientId, code_verifier: verifier, resource }).toString(),
502+
});
503+
const tj = await read(tok);
504+
const token = isBag(tj) && typeof tj.access_token === 'string' ? tj.access_token : undefined;
505+
if (!tok.ok || token === undefined) return refused('token exchange', tok, tj);
506+
return { ok: true, status: tok.status, body: { scope: isBag(tj) && typeof tj.scope === 'string' ? tj.scope : scope }, token };
507+
}

0 commit comments

Comments
 (0)