Skip to content

Commit 543ee4b

Browse files
feat(server): owner-approved external MCP clients over DPoP device grants (#1636)
## Problem An external agent (another machine, another harness) had no safe way to coordinate T3 threads. The only options were the provider-session `/mcp` token or a broad admin credential. ## Change The owner approves a DPoP device grant with an MCP policy instead of scopes. The client then uses `/api/mcp/external`, a second MCP server with its own `t3_external_*` tools. | Aspect | Rule | | --- | --- | | Credential | DPoP device session, scopes `[]` | | Policy | `auth_external_mcp_grants`, keyed by session | | Reads | projects, threads, timelines, waits | | Mutations | create, send/steer, interrupt with `--mcp-coordinate` | | Boundary | granted projects only | | Ceilings | default `approval-required` and `plan` | | Retries | `auth_external_mcp_requests` binds key to request and result | | Lost result | retry recovers the committed message and its run | | Interrupt retry | pins its run, or no run, before dispatch | | Steering | a capped grant joins only the provider attempt it vetted | | Dispatch | refuses a capped send or create prompt once its attempt or the thread modes changed | | Later owner changes | apply to turns that start afterwards, as for any queued message | | Reused key, new payload | `invalid_request` | | Failures | MCP `isError: true`, text led by the code | | Provenance | `createdBy: agent`, `creationSource: mcp` | | Revocation | `t3 auth session revoke` ends it at once | | Isolation | own `Layer.fresh`; `/mcp` is unchanged | ```bash t3 auth device approve <code> --mcp-project <id> --mcp-coordinate ``` The token endpoint also omits `scope` for a scopeless grant. It used to fail with `500` after it had issued the session. ## Head | Commit | Content | | --- | --- | | `77023d822ba173f4be58619469f2ae16179f0750` | head; one docs-only commit | | `657bd5cf7f29aa63a04b13c6421baeac2618afba` | last code commit; the recordings and VM transcript ran here | `git diff 657bd5c 77023d8`: `docs/fork/internals/fork-delta.md` only, +2 −1. The recordings stand for the head; a reviewer confirms that equivalence. ```diff -| Credential | DPoP device session only; scopes `[]`, so no RPC or route accepts it | +| Credential | DPoP device session only; scopes `[]`, so scope-checked routes and RPCs refuse it | +| WebSocket | `/api/auth/websocket-ticket` needs only authentication; each socket RPC refuses it | ``` ## Recordings Recorded on an isolated QA VM against `657bd5c`. Left: the guest's standalone client. Right: the host owner terminal and a separate observer browser. **1. Pair and connect.** Provenance, device start, owner approve, poll, tool list, whoami. https://github.com/user-attachments/assets/e875e8fd-9854-4ad1-b339-6ea7e5744f13 **2. Create a thread.** `t3_external_thread_create` with a prompt; the observer shows the thread, "Sent by another agent", and the reply. https://github.com/user-attachments/assets/c10b2b05-a493-4ada-b7b2-c52420ed8611 **3. Send a message.** `t3_external_thread_send`; the observer shows the second reply; wait completes. https://github.com/user-attachments/assets/fefce4d0-e894-4fb9-a6d8-35dd0cb5c7e3 **4. Refusals.** Ceiling escalation, a foreign project, then a read-only grant: read `200`, create `capability_denied`. https://github.com/user-attachments/assets/c4759ebf-b594-4564-99ee-7770ea14d98a **5. Credential probes.** Another key's proof, replayed proof, no credential, Bearer, no proof, forged: `401`; browser origin: `403`. https://github.com/user-attachments/assets/01bd3ace-de56-4b68-b546-27d6b69a05d5 **6. Revoke.** A new grant creates a thread; the owner revokes it; send and whoami `401`; the reader grant still `200`. https://github.com/user-attachments/assets/969f08c2-d9df-4dc3-8676-55cc9a3cb713 | Provenance | Value | | --- | --- | | Commit | `657bd5cf7f29aa63a04b13c6421baeac2618afba`, tree clean | | Server | `node apps/server/src/bin.ts serve --host 192.168.122.1 --port 38917 --base-dir <worktree>/.t3` | | Web | `vp build` of the same tree | | State | the worktree's own `.t3`; libvirt bridge only | | Guest | `qa-desktop`, 1360x768; Python client, own P-256 key | | Guest credentials | none from T3, the host, or a provider | | Observer | host Chrome, paired by a one-time token | | Harness `extmcp.py` sha256 | `bf43970fc04cebd0b70e665898a606ff74fb4c180cb7640740e917df2d06eef5` | | Recorder | `donjor hypr record`, takes `rec-e058` (clips 1-5), `rec-27c5` (clip 6) | | Harness | Claude Code 2.1.289, Claude Opus 5.5 | Clip 1 shows the commit, the dirty count, and the harness hash on screen. <details> <summary>Clip hashes and cuts</summary> Each upload was downloaded again; every sha256 matched. | Clip | Length | sha256 | | --- | --- | --- | | 1 pair | 46.0s | `806a7b69d060f522ed5c02fa6d44c6377f2c2b01769589d78ca4f88224046078` | | 2 create | 16.0s | `bf4b2f50a179297b376b55994c431bf73df65065e1cd8dcde3cf820e8b777bf0` | | 3 send | 13.0s | `fb277d317e6a2b0947e6788ba18cdab73e4a362900ab1d285c6389ba4545c53b` | | 4 refusals | 31.0s | `5f81329a7e822985712a1b3771d0cc29b7a8b8af8a23d916c9a90d920839f768` | | 5 probes | 10.0s | `87c32f67053e439052b65bbbc7dc6714c4eb3c509488c2bb54581b823e52f52e` | | 6 revoke | 40.0s | `6a0459303d15ea8715dd1f32b3d33213aa192f5ba54ab13aa4d8e0008ba5fc9d` | | Clip | Span | Real | Clip | | --- | --- | --- | --- | | 1 | provenance hold | 13s | cut | | 1 | idle after approve | 9s | cut | | 1 | tools hold, overflowing whoami | 18s | cut | | 2 | observer navigation | 9s | 3x | | 2 | idle, reply already shown | 15s | cut | | 3 | idle until wait | 13s | cut | | 4 | first refusal attempt, truncated output | 28s | outside the trim | | 4 | four idle gaps | 3s, 9s, 8s, 9s | cut | | 6 | three idle gaps | 5s, 6s, 13s | cut | | 6 | observer route detour | 24s | cut | | 6 | tail after reader `200` | 8s | cut | No secret is on screen. The client never prints its access token or device code. The pairing token never left the host files. User codes appear by design: single use, consumed, now expired. </details> ## Blast radius | Surface | Change | Existing behavior | | --- | --- | --- | | Device grant | `--mcp-*` approve stores a policy, scopes `[]` | scope approvals unchanged; tests | | Token endpoint | omits `scope` when empty | scoped grants still carry it | | Routes | adds `/api/mcp/external` | other routes untouched | | Provider `/mcp` | none | own bearer registry; probe below | | Orchestrator | `message.dispatch` checks two optional fields | absent fields: no-op | | `sendToThread` | optional `steerTarget`, `expectedModes` | absent: same dispatch mode | | Contracts | two optional command fields | existing commands decode unchanged | | Schema | two fork tables, two columns | idempotent; upgrade test | | Clients | none | desktop, web, mobile unchanged | Upstream code files take 42 added lines and lose none; every hook carries a `fork-hook` tag. One upstream doc, `orchestrator-mcp-server.md`, is corrected to the shipped provider credential lifetime. Probe from the guest with the read-only external credential: ```diff + /api/mcp/external → 200 - provider /mcp, DPoP or Bearer → 401 invalid_mcp_credential - /api/auth/clients, pairing-links → 403 insufficient_scope - /api/auth/pairing-token → 403 insufficient_scope ! /api/auth/websocket-ticket → 200 ``` The ticket route only requires authentication upstream; this PR leaves it unchanged. Every RPC on that socket requires a scope ([`RpcAuthorization.ts`](https://github.com/RSI-Software/t3code-hyprws/blob/77023d822ba173f4be58619469f2ae16179f0750/apps/server/src/auth/RpcAuthorization.ts)). Live probe through that ticket, same branch server, a fresh read-only external grant: ```diff + POST /api/auth/websocket-ticket → 200, ticket issued + GET /ws?wsTicket=…&orchestrationProtocol=2 → socket open - server.getConfig → EnvironmentAuthorizationError orchestration:read - orchestration.subscribeShell → EnvironmentAuthorizationError orchestration:read - subscribeAuthAccess → EnvironmentAuthorizationError access:read - orchestration.dispatchCommand → EnvironmentAuthorizationError orchestration:operate - terminal.open → EnvironmentAuthorizationError terminal:operate - after revoke: websocket-ticket → 401 ``` No call returned a value or a stream chunk. Payloads were valid but aimed at ids that do not exist, so even an accepted call could touch nothing. Opening the socket records only the session's own connection, as for any client. <details> <summary>Probe method</summary> | Item | Value | | --- | --- | | Server | `657bd5c` source, own `.t3`, `192.168.122.1:38917` | | Client | host Node script, own P-256 key; DPoP with `ath` | | Grant | `--mcp-project` one project, no `--mcp-coordinate` | | Output | reply tag, exit tag, scope, error tag; never the token or ticket | Effect RPC decodes a payload before the scope check, so an invalid payload fails decoding first. The probe sends valid payloads so the scope check is what answers. </details> ## Verification ```text npx tsc --noEmit -p apps/server → exit 0 vp test run <ForkSchema, mcp/external, ThreadManagementService, SelectionRestart> → exit 0 (43 tests) vp lint <changed .ts> → exit 0 vp run fork:ci → exit 0 vp run build (apps/server) → exit 0 ``` Transcript proof, round 4, on an isolated VM. The branch server ran with its own `.t3` and listened on the libvirt bridge only. The guest client was standalone Python with its own P-256 key, and had no T3, host, or provider credentials. ```diff + A, B, C: three grants, three keys, one guest + whoami: each client's own session and policy + one mcp-session-id, two credentials: each call answers as its sender + create K, retry K as sent → same thread + create with prompt → real Codex turn; retry → same run + steer → joins the vetted provider attempt + interrupt → interrupted + steer retry after the run ended → recorded result + owner clears every recorded result while run 3 is live: + interrupt retry → run 2, interrupted; run 3 untouched + steer and send retries → run 2, original delivery + create retry → run 1 - create K or send s1 retried with a changed payload → invalid_request - full-access create → runtime_mode_escalation_denied - reader create → capability_denied - no proof, Bearer, forged, another key's proof → 401 DPoP - replayed proof → 401 DPoP; browser origin → 403 - C after its 1m lifetime → 401 - A revoked → 401; B unaffected ``` Real-orchestrator regression: `ExternalMcpService.orchestrator.fork.test.ts` (owner elevates a thread under a used key; lost result for create, send, interrupt, idle interrupt; owner mode change during a running or starting turn; a send joins only its vetted attempt, also across an owner restart; dispatch refuses a send vetted under older modes; an owner raise that wins the lock mid-create keeps the prompt from starting). Auth: `ExternalMcpServer.auth.fork.test.ts` (real session store and DPoP verifier). Schema: `ForkSchema.fork.test.ts` adds the interrupt pin to an existing request table. The VM run caught that upgrade gap on a round-1 database. | Evidence | Value | | --- | --- | | Head | `77023d822ba173f4be58619469f2ae16179f0750` | | VM run | `657bd5cf7f2`, the last code commit, from source | | Not on the VM | an owner mode change racing a capped send or create; regressions own it | | Harness `extmcp.py` sha256 | `bf43970f…6eef5` | | Transcript sha256 | `4af1dec3…7ccf03` | Transcript: [external-mcp-vm-proof-r4.txt](https://github.com/user-attachments/files/33043476/external-mcp-vm-proof-r4.txt), harness: [extmcp.py](https://github.com/user-attachments/files/33041290/extmcp.py) ### Internal compatibility The external rejection above is a negative test; this section is the positive one. | Check | Result | | --- | --- | | Native Electron | `vp run dev:desktop:agent --home-dir <worktree>/.t3`, head `77023d8`, virtual monitor; backend ready, window connected, threads listed | | Provider MCP call | Codex thread asked to call `t3_project_list`: item `dynamic_tool` `t3-code.t3_project_list` completed, reply `6` = 6 projects | | Provider `/mcp` traffic | initialize `200`, tools/list `200`, tool call `200` | | Existing tests, CI on head | `McpHttpServer`, `McpProviderSession`, `McpSessionRegistry`, `OrchestratorMcpToolkit.integration` in Test Server 1-3 | ![Electron smoke](https://github.com/user-attachments/assets/e75ad50b-fd46-4c94-93e4-e0cb594765ae) Screenshot sha256 `e0c474c6625dc16855e3174840f85d210d032d90bcc08b23479ad8f317ca0712`. Not checked: mobile UI (no client change), relay and tunnel modes. ### Checks Artifact Kit is not configured here: no `./ak`, no `.agents/skills/ak`; none was added. The repository has no aftercare review workflow; its fork checks are below. ```text vp run fork:ci → exit 0 (head 77023d8) ghb pr checks 1636 → exit 0 (head 77023d8, 9/9: Check, Test, Test Web, Test Scripts, Test Server 1-3, Body, merge-tree) ``` ## Upstream baseline Fork-only. Nothing is posted upstream; this is a rebase and retirement baseline. | Item | State, 2026-10-05 | | --- | --- | | Fork base | `v0.0.46-nightly.20261004.2652` | | Latest stable | `v0.0.45` | | `pingdotgg#15219` explicit MCP targets | merged 2026-10-05, untagged | | `pingdotgg#15220` MCP OAuth for outside agents | open, not draft | | Concern | Baseline | | --- | --- | | Scope | external MCP only; no client change | | Reuse | device grant, `SessionStore`, DPoP verifier, five `OrchestratorMcpService` helpers | | Fork-owned | 17 `.fork` files; schema in `ForkSchema.ts` | | Rebase | the five helpers survive `pingdotgg#15219`; this PR's files auto-merge onto `upstream/main` `cf3e714b0f5` | | Retire | when a tag ships `pingdotgg#15220`, feed its authenticator from device grants; keep only project and mode policy | The auto-merge is textual; no typecheck ran on that tree. <details> <summary>Follow-ups, out of scope</summary> | Follow-up | Note | | --- | --- | | Stale grant and request rows | remain after the session ends | </details> Claude Opus 5.5 in Claude Code, inside T3 Code. ## Fork trailers Squashes: - 3f58ba7 feat(server): owner-approved external MCP clients over DPoP device grants (#1636) (#1636) - 2844353 fixup! feat(server): owner-approved external MCP clients over DPoP device grants (#1636) (#1636) Fork-Domain: device-auth Fork-Tier: core Co-authored-by: donjor <[email protected]>
1 parent 0c1d1aa commit 543ee4b

25 files changed

Lines changed: 3675 additions & 26 deletions

‎apps/server/src/auth/DeviceAuthorization.fork.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,46 @@ it.live("delivers a DPoP-bound token over the HTTP routes after owner approval",
417417
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
418418
);
419419

420+
it.live("delivers an external MCP grant's scopeless token without a scope field", () =>
421+
Effect.gen(function* () {
422+
const { send, store, sessions } = yield* makeHarness;
423+
const now = Math.floor((yield* Clock.currentTimeMillis) / 1_000);
424+
const key = makeKey(now);
425+
const tokenUrl = `${ORIGIN}${DeviceAuthorization.DEVICE_TOKEN_PATH}`;
426+
const started = yield* send(
427+
form(
428+
DeviceAuthorization.DEVICE_AUTHORIZATION_PATH,
429+
{ client_label: "dot cloud" },
430+
{ dpop: key.proof("POST", `${ORIGIN}${DeviceAuthorization.DEVICE_AUTHORIZATION_PATH}`) },
431+
),
432+
);
433+
yield* store.approve({
434+
userCode: started.body.user_code as string,
435+
mcpPolicy: {
436+
projectIds: "*",
437+
coordinate: false,
438+
maxRuntimeMode: "approval-required",
439+
maxInteractionMode: "plan",
440+
},
441+
});
442+
443+
const issued = yield* send(
444+
form(
445+
DeviceAuthorization.DEVICE_TOKEN_PATH,
446+
{
447+
grant_type: DeviceAuthorization.DEVICE_CODE_GRANT_TYPE,
448+
device_code: started.body.device_code as string,
449+
},
450+
{ dpop: key.proof("POST", tokenUrl) },
451+
),
452+
);
453+
expect(issued.status).toBe(200);
454+
expect(issued.body.token_type).toBe("DPoP");
455+
expect(issued.body).not.toHaveProperty("scope");
456+
expect((yield* sessions.verify(issued.body.access_token as string)).scopes).toEqual([]);
457+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
458+
);
459+
420460
it.live("keeps unauthenticated callers from growing state past the request cap", () =>
421461
Effect.gen(function* () {
422462
const { send, markerCount, rowCount } = yield* makeHarness;

‎apps/server/src/auth/DeviceAuthorization.fork.ts‎

Lines changed: 48 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import * as HttpRouter from "effect/unstable/http/HttpRouter";
2222
import * as UrlParams from "effect/unstable/http/UrlParams";
2323
import * as SqlClient from "effect/unstable/sql/SqlClient";
2424

25+
import * as ExternalMcpGrant from "./ExternalMcpGrant.fork.ts";
2526
import * as SessionStore from "./SessionStore.ts";
2627
import { deriveAuthClientMetadata } from "./utils.ts";
2728

@@ -91,6 +92,16 @@ export class DeviceAuthorizationScopeError extends Data.TaggedError(
9192
readonly allowedScopes: ReadonlyArray<AuthEnvironmentScope>;
9293
}> {}
9394

95+
/**
96+
* An external MCP policy needs a key-bound request: the endpoint only accepts
97+
* DPoP, so a bearer grant would be unusable, and scopes would widen it.
98+
*/
99+
export class DeviceAuthorizationMcpPolicyError extends Data.TaggedError(
100+
"DeviceAuthorizationMcpPolicyError",
101+
)<{
102+
readonly reason: "unbound-request" | "scopes-with-policy";
103+
}> {}
104+
94105
export interface DeviceAuthorizationStart {
95106
readonly deviceCode: string;
96107
readonly userCode: string;
@@ -114,6 +125,7 @@ export interface DeviceAuthorizationApproval {
114125
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
115126
readonly ttl: Duration.Duration;
116127
readonly proofKeyThumbprint: string | null;
128+
readonly mcpPolicy: ExternalMcpGrant.ExternalMcpPolicy | null;
117129
}
118130

119131
export type DeviceAuthorizationPollResult =
@@ -141,14 +153,20 @@ export class DeviceAuthorizationStore extends Context.Service<
141153
* Grants `scopes` when given, else the requested scopes, else the standard
142154
* client scopes. `scopes` may narrow a request but never widen it; with no
143155
* request it may name any environment scope.
156+
*
157+
* `mcpPolicy` instead grants an external MCP client: no scopes, and the
158+
* policy as the session's only authority.
144159
*/
145160
readonly approve: (input: {
146161
readonly userCode: string;
147162
readonly ttl?: Duration.Duration;
148163
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
164+
readonly mcpPolicy?: ExternalMcpGrant.ExternalMcpPolicy;
149165
}) => Effect.Effect<
150166
Option.Option<DeviceAuthorizationApproval>,
151-
DeviceAuthorizationStoreError | DeviceAuthorizationScopeError
167+
| DeviceAuthorizationStoreError
168+
| DeviceAuthorizationScopeError
169+
| DeviceAuthorizationMcpPolicyError
152170
>;
153171
readonly deny: (userCode: string) => Effect.Effect<boolean, DeviceAuthorizationStoreError>;
154172
readonly poll: (input: {
@@ -175,6 +193,7 @@ interface DeviceAuthorizationRow {
175193
readonly lastPolledAt: string | null;
176194
readonly grantedScopes: string | null;
177195
readonly grantedTtlMs: number | null;
196+
readonly mcpPolicyJson: string | null;
178197
}
179198

180199
const ScopesJson = Schema.fromJsonString(AuthEnvironmentScopes);
@@ -204,7 +223,8 @@ const ROW_COLUMNS = `
204223
expires_at AS "expiresAt",
205224
last_polled_at AS "lastPolledAt",
206225
granted_scopes AS "grantedScopes",
207-
granted_ttl_ms AS "grantedTtlMs"
226+
granted_ttl_ms AS "grantedTtlMs",
227+
mcp_policy_json AS "mcpPolicyJson"
208228
`;
209229

210230
const isoNow = DateTime.now.pipe(Effect.map((now) => DateTime.formatIso(DateTime.toUtc(now))));
@@ -307,16 +327,29 @@ const make = Effect.gen(function* () {
307327
`;
308328
if (row === undefined) return Option.none<DeviceAuthorizationApproval>();
309329
const request = toRequest(row);
310-
const allowedScopes = request.requestedScopes ?? AuthAdministrativeScopes;
330+
const mcpPolicy = input.mcpPolicy ?? null;
331+
if (mcpPolicy !== null && input.scopes !== undefined) {
332+
return yield* new DeviceAuthorizationMcpPolicyError({ reason: "scopes-with-policy" });
333+
}
334+
if (mcpPolicy !== null && request.proofKeyThumbprint === null) {
335+
return yield* new DeviceAuthorizationMcpPolicyError({ reason: "unbound-request" });
336+
}
337+
const allowedScopes = request.requestedScopes ?? AuthStandardClientScopes;
311338
if (input.scopes?.some((scope) => !allowedScopes.includes(scope))) {
312339
return yield* new DeviceAuthorizationScopeError({ allowedScopes });
313340
}
314-
const scopes = input.scopes ?? request.requestedScopes ?? AuthStandardClientScopes;
341+
const scopes: ReadonlyArray<AuthEnvironmentScope> =
342+
mcpPolicy !== null
343+
? []
344+
: (input.scopes ?? request.requestedScopes ?? AuthStandardClientScopes);
315345
const updated = yield* sql<{ readonly userCode: string }>`
316346
UPDATE auth_device_authorizations
317347
SET status = 'approved',
318348
granted_scopes = ${encodeScopes(scopes)},
319349
granted_ttl_ms = ${Duration.toMillis(ttl)},
350+
mcp_policy_json = ${
351+
mcpPolicy === null ? null : ExternalMcpGrant.encodeExternalMcpPolicy(mcpPolicy)
352+
},
320353
decided_at = ${nowIso}
321354
WHERE user_code = ${row.userCode} AND status = 'pending'
322355
RETURNING user_code AS "userCode"
@@ -328,6 +361,7 @@ const make = Effect.gen(function* () {
328361
scopes,
329362
ttl,
330363
proofKeyThumbprint: request.proofKeyThumbprint,
364+
mcpPolicy,
331365
});
332366
}).pipe(
333367
Effect.catchTag("SqlError", (cause) => Effect.fail(fail("approve")(cause))),
@@ -409,6 +443,14 @@ const make = Effect.gen(function* () {
409443
UPDATE auth_device_authorizations SET session_id = ${session.sessionId}
410444
WHERE device_code_hash = ${deviceCodeHash}
411445
`;
446+
if (claimed.mcpPolicyJson !== null) {
447+
yield* ExternalMcpGrant.recordExternalMcpGrant({
448+
sessionId: session.sessionId,
449+
policy: ExternalMcpGrant.decodeExternalMcpPolicy(claimed.mcpPolicyJson),
450+
clientLabel: session.client.label ?? null,
451+
createdAt: nowIso,
452+
}).pipe(Effect.provideService(SqlClient.SqlClient, sql));
453+
}
412454
return { _tag: "Issued", session } as const;
413455
}).pipe(sql.withTransaction);
414456
}).pipe(
@@ -565,7 +607,8 @@ const deviceTokenRoute = (store: DeviceAuthorizationStore["Service"]) =>
565607
0,
566608
Math.floor((session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1_000),
567609
),
568-
scope: encodeOAuthScope(session.scopes),
610+
// An external MCP grant carries no scopes, and OAuth has no empty scope.
611+
...(session.scopes.length > 0 ? { scope: encodeOAuthScope(session.scopes) } : {}),
569612
},
570613
{ headers: CREDENTIAL_HEADERS },
571614
);
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { expect, it } from "@effect/vitest";
3+
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
4+
import * as Effect from "effect/Effect";
5+
import * as Layer from "effect/Layer";
6+
import * as Option from "effect/Option";
7+
8+
import { externalMcpPolicyFromFlags } from "../cli/authDevice.fork.ts";
9+
import * as ServerConfig from "../config.ts";
10+
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
11+
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
12+
import * as DeviceAuthorization from "./DeviceAuthorization.fork.ts";
13+
import * as ExternalMcpGrant from "./ExternalMcpGrant.fork.ts";
14+
import * as ServerSecretStore from "./ServerSecretStore.ts";
15+
import * as SessionStore from "./SessionStore.ts";
16+
17+
const storeLayer = Layer.mergeAll(DeviceAuthorization.layer, ExternalMcpGrant.layer).pipe(
18+
Layer.provideMerge(SessionStore.layer),
19+
Layer.provideMerge(Layer.mergeAll(SqlitePersistenceMemory, ServerSecretStore.layer)),
20+
Layer.provideMerge(
21+
Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
22+
getEnvironmentId: Effect.succeed(EnvironmentId.make("external-mcp-grant-test")),
23+
}),
24+
),
25+
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-external-mcp-test-" })),
26+
);
27+
28+
const client = { label: "dot cloud", deviceType: "bot" } as const;
29+
const policy: ExternalMcpGrant.ExternalMcpPolicy = {
30+
projectIds: [ProjectId.make("project:granted")],
31+
coordinate: true,
32+
maxRuntimeMode: "approval-required",
33+
maxInteractionMode: "plan",
34+
};
35+
36+
it.layer(NodeServices.layer)("external MCP device grants", (it) => {
37+
it.effect("issues a scopeless session whose only authority is the policy", () =>
38+
Effect.gen(function* () {
39+
const store = yield* DeviceAuthorization.DeviceAuthorizationStore;
40+
const grants = yield* ExternalMcpGrant.ExternalMcpGrantStore;
41+
const sessions = yield* SessionStore.SessionStore;
42+
const started = Option.getOrThrow(
43+
yield* store.start({
44+
client,
45+
requestedScopes: ["orchestration:read"],
46+
proofKeyThumbprint: "client-key",
47+
}),
48+
);
49+
const approved = Option.getOrThrow(
50+
yield* store.approve({ userCode: started.userCode, mcpPolicy: policy }),
51+
);
52+
expect(approved).toMatchObject({ scopes: [], mcpPolicy: policy });
53+
54+
const issued = yield* store.poll({
55+
deviceCode: started.deviceCode,
56+
proof: { thumbprint: "client-key", issuedAt: 1 },
57+
});
58+
if (issued._tag !== "Issued") throw new Error(`expected Issued, got ${issued._tag}`);
59+
const verified = yield* sessions.verify(issued.session.token);
60+
expect(verified.scopes).toEqual([]);
61+
expect(yield* grants.getBySession(verified.sessionId)).toEqual(
62+
Option.some({ policy, clientLabel: "dot cloud" }),
63+
);
64+
}).pipe(Effect.provide(storeLayer)),
65+
);
66+
67+
it.effect("leaves an ordinary device grant without an MCP grant", () =>
68+
Effect.gen(function* () {
69+
const store = yield* DeviceAuthorization.DeviceAuthorizationStore;
70+
const grants = yield* ExternalMcpGrant.ExternalMcpGrantStore;
71+
const started = Option.getOrThrow(
72+
yield* store.start({ client, proofKeyThumbprint: "client-key" }),
73+
);
74+
yield* store.approve({ userCode: started.userCode });
75+
const issued = yield* store.poll({
76+
deviceCode: started.deviceCode,
77+
proof: { thumbprint: "client-key", issuedAt: 1 },
78+
});
79+
if (issued._tag !== "Issued") throw new Error(`expected Issued, got ${issued._tag}`);
80+
expect(Option.isNone(yield* grants.getBySession(issued.session.sessionId))).toBe(true);
81+
}).pipe(Effect.provide(storeLayer)),
82+
);
83+
84+
it.effect("refuses a policy on a bearer request or beside scopes", () =>
85+
Effect.gen(function* () {
86+
const store = yield* DeviceAuthorization.DeviceAuthorizationStore;
87+
const bearer = Option.getOrThrow(yield* store.start({ client }));
88+
const unbound = yield* store
89+
.approve({ userCode: bearer.userCode, mcpPolicy: policy })
90+
.pipe(Effect.flip);
91+
expect(unbound).toMatchObject({ reason: "unbound-request" });
92+
93+
const bound = Option.getOrThrow(
94+
yield* store.start({ client, proofKeyThumbprint: "client-key" }),
95+
);
96+
const scoped = yield* store
97+
.approve({ userCode: bound.userCode, mcpPolicy: policy, scopes: ["orchestration:read"] })
98+
.pipe(Effect.flip);
99+
expect(scoped).toMatchObject({ reason: "scopes-with-policy" });
100+
// Neither refusal decided the request.
101+
expect(yield* store.listOpen()).toHaveLength(2);
102+
}).pipe(Effect.provide(storeLayer)),
103+
);
104+
});
105+
106+
it("reads the approve flags into a policy with conservative ceilings", () => {
107+
const none = {
108+
mcpProject: [],
109+
mcpAllProjects: false,
110+
mcpCoordinate: false,
111+
mcpMaxRuntimeMode: Option.none(),
112+
mcpMaxInteractionMode: Option.none(),
113+
scope: Option.none(),
114+
} as const;
115+
expect(externalMcpPolicyFromFlags(none)).toBeUndefined();
116+
expect(externalMcpPolicyFromFlags({ ...none, mcpProject: ["a", "b"] })).toEqual({
117+
projectIds: ["a", "b"],
118+
coordinate: false,
119+
maxRuntimeMode: "approval-required",
120+
maxInteractionMode: "plan",
121+
});
122+
expect(
123+
externalMcpPolicyFromFlags({
124+
...none,
125+
mcpAllProjects: true,
126+
mcpCoordinate: true,
127+
mcpMaxRuntimeMode: Option.some("full-access"),
128+
mcpMaxInteractionMode: Option.some("default"),
129+
}),
130+
).toEqual({
131+
projectIds: "*",
132+
coordinate: true,
133+
maxRuntimeMode: "full-access",
134+
maxInteractionMode: "default",
135+
});
136+
// A coordinate flag alone names no project, and a policy never carries scopes.
137+
expect(typeof externalMcpPolicyFromFlags({ ...none, mcpCoordinate: true })).toBe("string");
138+
expect(
139+
typeof externalMcpPolicyFromFlags({ ...none, mcpProject: ["a"], mcpAllProjects: true }),
140+
).toBe("string");
141+
expect(
142+
typeof externalMcpPolicyFromFlags({
143+
...none,
144+
mcpProject: ["a"],
145+
scope: Option.some("orchestration:read"),
146+
}),
147+
).toBe("string");
148+
});

0 commit comments

Comments
 (0)