Skip to content

Commit c44437e

Browse files
feat(auth): pairing grants access and T3 Connect management by default
Ordinary pairing codes, T3 Connect sign-ins and the hosted app got a standard grant without access:read, access:write and relay:write, so phones and Connect sessions could not see Connections, approve an outside agent without a pairing code, or mint pairing codes. The split was not a boundary: the same grant holds terminal:operate and orchestration:operate, and a shell or a full-access agent can mint a session with every scope through `t3 auth session issue`. The standard set now includes access and relay management, and the separate administrative preset is gone; its uses point at the standard set. Explicit --scope and the Connections scope picker still narrow a grant, and stored grants are never widened. Creating a pairing link without scopes now delegates the standard set narrowed to what the creating session holds, so a session with access:write but not relay:write can still create a default link. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 51f7382 commit c44437e

18 files changed

Lines changed: 166 additions & 99 deletions

File tree

‎apps/server/src/auth/EnvironmentAuth.test.ts‎

Lines changed: 35 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import {
33
authScopeResponse,
4-
AuthAdministrativeScopes,
4+
AuthAccessWriteScope,
5+
AuthRelayWriteScope,
56
AuthStandardClientScopes,
67
} from "@t3tools/contracts";
78
import { expect, it } from "@effect/vitest";
@@ -103,7 +104,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
103104
const authenticated = yield* serverAuth.authenticateHttpRequest(request);
104105
expect(devExchange.cookieName).toMatch(/^t3_dev_session_/);
105106
expect(devExchange.expireNormalCookie).toBe(true);
106-
expect(devExchange.response).toMatchObject(authScopeResponse(AuthAdministrativeScopes));
107+
expect(devExchange.response).toMatchObject(authScopeResponse(AuthStandardClientScopes));
107108
expect(authenticated.scopes).toEqual(["orchestration:read"]);
108109
}).pipe(
109110
Effect.provide(
@@ -253,7 +254,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
253254
expect((yield* Effect.flip(sessions.verify(token)))._tag).toBe("SessionTokenRevokedError");
254255
expect(
255256
(yield* serverAuth.createBrowserSession(recovery.credential, requestMetadata)).response,
256-
).toMatchObject({ authenticated: true, ...authScopeResponse(AuthAdministrativeScopes) });
257+
).toMatchObject({ authenticated: true, ...authScopeResponse(AuthStandardClientScopes) });
257258
}).pipe(
258259
Effect.provide(
259260
layerEnvironmentAuth({
@@ -325,23 +326,36 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
325326
}),
326327
);
327328

328-
it.effect("issues standard pairing credentials by default", () =>
329+
it.effect("pairs with access and T3 Connect management unless scopes are narrowed", () =>
329330
Effect.gen(function* () {
330331
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
331332
const sessions = yield* SessionStore.SessionStore;
333+
const pairAndVerify = (input?: Parameters<typeof serverAuth.issuePairingCredential>[0]) =>
334+
Effect.gen(function* () {
335+
const pairingCredential = yield* serverAuth.issuePairingCredential(input);
336+
const exchanged = yield* serverAuth.createBrowserSession(
337+
pairingCredential.credential,
338+
requestMetadata,
339+
);
340+
return yield* serverAuth.authenticateHttpRequest(
341+
makeCookieRequest(sessions.cookieName, exchanged.sessionToken),
342+
);
343+
});
332344

333-
const pairingCredential = yield* serverAuth.issuePairingCredential();
334-
const exchanged = yield* serverAuth.createBrowserSession(
335-
pairingCredential.credential,
336-
requestMetadata,
337-
);
338-
const verified = yield* serverAuth.authenticateHttpRequest(
339-
makeCookieRequest(sessions.cookieName, exchanged.sessionToken),
340-
);
345+
const standard = yield* pairAndVerify();
346+
expect(standard.scopes).toEqual(AuthStandardClientScopes);
347+
expect(standard.scopes).toContain(AuthAccessWriteScope);
348+
expect(standard.scopes).toContain(AuthRelayWriteScope);
349+
expect(standard.subject).toBe("one-time-token");
341350

342-
expect(verified.sessionId.length).toBeGreaterThan(0);
343-
expect(verified.scopes).toEqual(AuthStandardClientScopes);
344-
expect(verified.subject).toBe("one-time-token");
351+
const narrowed = yield* pairAndVerify({
352+
scopes: ["orchestration:read", "orchestration:operate", "terminal:read"],
353+
});
354+
expect(narrowed.scopes).toEqual([
355+
"orchestration:read",
356+
"orchestration:operate",
357+
"terminal:read",
358+
]);
345359
}).pipe(Effect.provide(layerEnvironmentAuth())),
346360
);
347361

@@ -362,7 +376,9 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
362376
it.effect("preserves pairing grants after rejecting scopes they do not grant", () =>
363377
Effect.gen(function* () {
364378
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
365-
const pairingCredential = yield* serverAuth.issuePairingCredential();
379+
const pairingCredential = yield* serverAuth.issuePairingCredential({
380+
scopes: ["orchestration:read", "orchestration:operate"],
381+
});
366382

367383
const error = yield* serverAuth
368384
.exchangeBootstrapCredentialForAccessToken(
@@ -510,12 +526,10 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
510526
),
511527
);
512528

513-
it.effect("keeps user-issued administrative pairing links manageable", () =>
529+
it.effect("keeps user-issued pairing links with access management manageable", () =>
514530
Effect.gen(function* () {
515531
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
516-
const pairingCredential = yield* serverAuth.issuePairingCredential({
517-
scopes: AuthAdministrativeScopes,
518-
});
532+
const pairingCredential = yield* serverAuth.issuePairingCredential();
519533
const listedPairingLinks = yield* serverAuth.listPairingLinks();
520534

521535
expect(
@@ -544,7 +558,7 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
544558
makeCookieRequest(sessions.cookieName, exchanged.sessionToken),
545559
);
546560

547-
expect(verified.scopes).toEqual(AuthAdministrativeScopes);
561+
expect(verified.scopes).toEqual(AuthStandardClientScopes);
548562
expect(verified.subject).toBe("administrative-bootstrap");
549563
}).pipe(Effect.provide(layerEnvironmentAuth())),
550564
);

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import {
22
AuthAccessTokenType,
33
AuthAccessWriteScope,
4-
AuthAdministrativeScopes,
54
AuthOrchestrationOperateScope,
65
AuthOrchestrationReadScope,
76
AuthSettingsWriteScope,
@@ -1096,7 +1095,7 @@ export const make = Effect.gen(function* () {
10961095
.issue({
10971096
subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
10981097
method: "bearer-access-token",
1099-
scopes: input?.scopes ?? AuthAdministrativeScopes,
1098+
scopes: input?.scopes ?? AuthStandardClientScopes,
11001099
client: {
11011100
...(input?.label ? { label: input.label } : {}),
11021101
deviceType: "bot",
@@ -1151,7 +1150,7 @@ export const make = Effect.gen(function* () {
11511150
const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
11521151
() => {
11531152
const fallback = issuePairingCredentialForSubject({
1154-
scopes: AuthAdministrativeScopes,
1153+
scopes: AuthStandardClientScopes,
11551154
subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
11561155
purpose: "startup",
11571156
});

‎apps/server/src/auth/EnvironmentAuthAdmin.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AuthAdministrativeScopes } from "@t3tools/contracts";
1+
import { AuthStandardClientScopes } from "@t3tools/contracts";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import { expect, it } from "@effect/vitest";
44
import * as Effect from "effect/Effect";
@@ -80,11 +80,11 @@ it.layer(NodeServices.layer)("EnvironmentAuth administrative operations", (it) =
8080
const listedAfterRevoke = yield* environmentAuth.listSessions();
8181

8282
expect(issued.method).toBe("bearer-access-token");
83-
expect(issued.scopes).toEqual(AuthAdministrativeScopes);
83+
expect(issued.scopes).toEqual(AuthStandardClientScopes);
8484
expect(issued.client.deviceType).toBe("bot");
8585
expect(issued.client.label).toBe("deploy-bot");
8686
expect(verified.sessionId).toBe(issued.sessionId);
87-
expect(verified.scopes).toEqual(AuthAdministrativeScopes);
87+
expect(verified.scopes).toEqual(AuthStandardClientScopes);
8888
expect(verified.method).toBe("bearer-access-token");
8989
expect(listedBeforeRevoke).toHaveLength(1);
9090
expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId);

‎apps/server/src/auth/McpOAuth.test.ts‎

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
2-
import {
3-
AuthAdministrativeScopes,
4-
type AuthCreatePairingCredentialInput,
5-
EnvironmentHttpApi,
6-
} from "@t3tools/contracts";
2+
import { type AuthCreatePairingCredentialInput, EnvironmentHttpApi } from "@t3tools/contracts";
73
import { expect, it } from "@effect/vitest";
84
import * as Context from "effect/Context";
95
import * as Crypto from "effect/Crypto";
@@ -485,9 +481,9 @@ it.live("one-click approves only access the browser session holds the scopes for
485481
Effect.gen(function* () {
486482
const clientId = yield* registeredClientId(handler);
487483
const params = authorizeParams(clientId);
488-
const browserCookie = (scopes: NonNullable<AuthCreatePairingCredentialInput["scopes"]>) =>
484+
const browserCookie = (scopes?: AuthCreatePairingCredentialInput["scopes"]) =>
489485
Effect.gen(function* () {
490-
const pairing = yield* auth.issuePairingCredential({ scopes });
486+
const pairing = yield* auth.issuePairingCredential(scopes ? { scopes } : undefined);
491487
const response = yield* handler(
492488
at("/api/auth/browser-session", {
493489
method: "POST",
@@ -502,10 +498,10 @@ it.live("one-click approves only access the browser session holds the scopes for
502498
Effect.flatMap(json<{ csrfToken?: string; oneClickAccess?: ReadonlyArray<string> }>),
503499
);
504500

505-
const admin = yield* browserCookie([...AuthAdministrativeScopes]);
506-
const adminDetails = yield* details(admin);
507-
expect(adminDetails.csrfToken).toEqual(expect.any(String));
508-
expect(adminDetails.oneClickAccess).toEqual([
501+
const paired = yield* browserCookie();
502+
const pairedDetails = yield* details(paired);
503+
expect(pairedDetails.csrfToken).toEqual(expect.any(String));
504+
expect(pairedDetails.oneClickAccess).toEqual([
509505
"read-only",
510506
"approval-required",
511507
"auto-accept-edits",
@@ -515,8 +511,8 @@ it.live("one-click approves only access the browser session holds the scopes for
515511
const oneClick = yield* decide(
516512
handler,
517513
params,
518-
{ _tag: "browser-session", access: "auto", csrfToken: adminDetails.csrfToken! },
519-
admin,
514+
{ _tag: "browser-session", access: "auto", csrfToken: pairedDetails.csrfToken! },
515+
paired,
520516
);
521517
expect(new URL(oneClick.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
522518

‎apps/server/src/auth/PairingGrantStore.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { AuthAdministrativeScopes, AuthStandardClientScopes } from "@t3tools/contracts";
1+
import { AuthStandardClientScopes } from "@t3tools/contracts";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import { expect, it } from "@effect/vitest";
44
import * as Duration from "effect/Duration";
@@ -163,7 +163,7 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
163163
const third = yield* bootstrapCredentials.consume("desktop-bootstrap-token");
164164

165165
expect(first.method).toBe("desktop-bootstrap");
166-
expect(first.scopes).toEqual(AuthAdministrativeScopes);
166+
expect(first.scopes).toEqual(AuthStandardClientScopes);
167167
expect(first.subject).toBe("desktop-bootstrap");
168168
expect(second.method).toBe("desktop-bootstrap");
169169
expect(third.method).toBe("desktop-bootstrap");

‎apps/server/src/auth/PairingGrantStore.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import {
2-
AuthAdministrativeScopes,
32
AuthStandardClientScopes,
43
type AuthEnvironmentScope,
54
type AuthPairingLink,
@@ -316,7 +315,7 @@ export const make = Effect.gen(function* () {
316315
const now = yield* DateTime.now;
317316
yield* seedGrant(config.desktopBootstrapToken, {
318317
method: "desktop-bootstrap",
319-
scopes: AuthAdministrativeScopes,
318+
scopes: AuthStandardClientScopes,
320319
subject: "desktop-bootstrap",
321320
expiresAt: DateTime.add(now, {
322321
milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
@@ -441,7 +440,7 @@ export const make = Effect.gen(function* () {
441440
if (consumeRotatingDesktopToken(credential, now.epochMilliseconds)) {
442441
return {
443442
method: "desktop-bootstrap",
444-
scopes: AuthAdministrativeScopes,
443+
scopes: AuthStandardClientScopes,
445444
subject: "desktop-bootstrap",
446445
expiresAt: DateTime.add(now, {
447446
milliseconds: DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS,

‎apps/server/src/auth/SessionStore.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import {
22
AuthSessionId,
3-
AuthAdministrativeScopes,
43
AuthStandardClientScopes,
54
AuthEnvironmentScopes,
65
type AuthClientMetadata,
@@ -508,7 +507,7 @@ export const make = Effect.gen(function* () {
508507
.createIfAbsent({
509508
sessionId: devAuth.sessionId,
510509
subject: "reusable-dev-token",
511-
scopes: AuthAdministrativeScopes,
510+
scopes: AuthStandardClientScopes,
512511
method: "browser-session-cookie",
513512
client: {
514513
label: "Reusable dev token",

‎apps/server/src/auth/http.test.ts‎

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -75,19 +75,23 @@ const postJson = (path: string, body: unknown, headers?: Readonly<Record<string,
7575
body: encodeJson(body),
7676
});
7777

78+
const makeRequestContext = Effect.gen(function* () {
79+
const crypto = yield* Crypto.Crypto;
80+
const unusedSecretStore = ServerSecretStore.ServerSecretStore.of({
81+
get: () => Effect.succeedNone,
82+
set: () => Effect.void,
83+
create: () => Effect.void,
84+
getOrCreateRandom: () => Effect.die("Not used by these routes."),
85+
remove: () => Effect.void,
86+
});
87+
return Context.make(Crypto.Crypto, crypto).pipe(
88+
Context.add(ServerSecretStore.ServerSecretStore, unusedSecretStore),
89+
);
90+
});
91+
7892
it.effect("sets the selected browser session cookies through the HTTP route", () =>
7993
Effect.gen(function* () {
80-
const crypto = yield* Crypto.Crypto;
81-
const unusedSecretStore = ServerSecretStore.ServerSecretStore.of({
82-
get: () => Effect.succeedNone,
83-
set: () => Effect.void,
84-
create: () => Effect.void,
85-
getOrCreateRandom: () => Effect.die("Not used by these routes."),
86-
remove: () => Effect.void,
87-
});
88-
const requestContext = Context.make(Crypto.Crypto, crypto).pipe(
89-
Context.add(ServerSecretStore.ServerSecretStore, unusedSecretStore),
90-
);
94+
const requestContext = yield* makeRequestContext;
9195
return yield* Effect.acquireUseRelease(
9296
Effect.sync(
9397
() =>
@@ -162,6 +166,61 @@ it.effect("sets the selected browser session cookies through the HTTP route", ()
162166
}).pipe(Effect.provide(NodeServices.layer)),
163167
);
164168

169+
it.effect("narrows a default pairing link to the scopes its creator holds", () =>
170+
Effect.gen(function* () {
171+
const requestContext = yield* makeRequestContext;
172+
return yield* Effect.acquireUseRelease(
173+
Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
174+
(environment) =>
175+
Effect.tryPromise(async () => {
176+
const browserCookie = async (credential: string) => {
177+
const response = await environment.handler(
178+
postJson("/api/auth/browser-session", { credential }),
179+
requestContext,
180+
);
181+
const cookie = response.headers.getSetCookie().find((value) => !value.includes("=;"));
182+
return cookie?.split(";", 1)[0] ?? "";
183+
};
184+
const createPairing = (cookie: string, body: unknown) =>
185+
environment.handler(
186+
postJson("/api/auth/pairing-token", body, { cookie }),
187+
requestContext,
188+
);
189+
190+
const creatorScopes = ["orchestration:read", "access:read", "access:write"];
191+
const creatorPairing = await createPairing(await browserCookie(DEV_TOKEN), {
192+
scopes: creatorScopes,
193+
});
194+
const creatorCookie = await browserCookie(
195+
((await creatorPairing.json()) as { credential: string }).credential,
196+
);
197+
198+
const widened = await createPairing(creatorCookie, {
199+
scopes: ["orchestration:read", "relay:write"],
200+
});
201+
expect(widened.status).toBe(403);
202+
expect(await widened.json()).toMatchObject({ requiredPermission: "relay:write" });
203+
204+
const created = await createPairing(creatorCookie, {});
205+
expect(created.status).toBe(200);
206+
const { id } = (await created.json()) as { id: string };
207+
const links = await environment.handler(
208+
new Request("http://127.0.0.1/api/auth/pairing-links", {
209+
headers: { cookie: creatorCookie },
210+
}),
211+
requestContext,
212+
);
213+
const listed = (await links.json()) as ReadonlyArray<{
214+
id: string;
215+
permissions?: ReadonlyArray<string>;
216+
}>;
217+
expect(listed.find((link) => link.id === id)?.permissions).toEqual(creatorScopes);
218+
}),
219+
(environment) => Effect.promise(() => environment.dispose()),
220+
);
221+
}).pipe(Effect.provide(NodeServices.layer)),
222+
);
223+
165224
it.effect("exports only verified T3 Connect requests", () =>
166225
Effect.gen(function* () {
167226
const productSpans: Array<string> = [];

‎apps/server/src/auth/http.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,11 @@ export const layer = HttpApiBuilder.group(
430430
function* (args) {
431431
yield* annotateEnvironmentRequest(args.endpoint.name);
432432
const session = yield* requireEnvironmentScope(AuthAccessWriteScope);
433-
const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;
433+
// A default link delegates what the creator holds of the standard
434+
// set, so a session narrowed below it can still create one.
435+
const delegatedScopes =
436+
args.payload.scopes ??
437+
AuthStandardClientScopes.filter((scope) => session.scopes.has(scope));
434438
if (
435439
delegatedScopes.length === 0 ||
436440
new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length
@@ -442,7 +446,10 @@ export const layer = HttpApiBuilder.group(
442446
return yield* failEnvironmentScopeRequired(delegatedScope);
443447
}
444448
}
445-
return yield* serverAuth.issuePairingCredential(args.payload);
449+
return yield* serverAuth.issuePairingCredential({
450+
...args.payload,
451+
scopes: delegatedScopes,
452+
});
446453
},
447454
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>
448455
failEnvironmentInternal("pairing_credential_issuance_failed", error),

0 commit comments

Comments
 (0)