diff --git a/.agents/skills/test-t3-app/references/feature-map.md b/.agents/skills/test-t3-app/references/feature-map.md index 106a343211f2c..bb8b58cfc1e61 100644 --- a/.agents/skills/test-t3-app/references/feature-map.md +++ b/.agents/skills/test-t3-app/references/feature-map.md @@ -209,7 +209,7 @@ Code: Connections: - **settings.connections** — `/settings/connections`, "Environments": "This machine", "Linked environments", "Network access", "Tailscale HTTPS", "T3 Connect", "Load balancing". -- **settings.access** — `/settings/access`, "Sharing & access": paired devices, "Guest links", "Require approval for new devices". +- **settings.access** — `/settings/access`, "Sharing & access": paired devices, "Guest links", "Require approval for new devices", "Require enrolled founders". - **settings.secrets** — `/settings/secrets`, "Secrets" (only when secrets are enabled). More: diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 30bba243af9ea..ece154fe2a4b8 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -321,6 +321,102 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), ); + it.effect("binds a founder only from its pairing code or its approved Connect device", () => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const sessions = yield* SessionStore.SessionStore; + const founderOf = (sessionId: Parameters[0]) => + serverAuth.messageSenderOf(sessionId).pipe(Effect.map((sender) => sender.founder)); + const admin = yield* serverAuth.issueSession({ label: "Owner" }); + + const enrolled = yield* serverAuth.issuePairingCredential({ founder: "kameron" }); + const phone = yield* serverAuth.createBrowserSession(enrolled.credential, requestMetadata); + expect(yield* founderOf((yield* sessions.verify(phone.sessionToken)).sessionId)).toBe( + "kameron", + ); + // An agent sign-in code never names a person. + const agentCode = yield* serverAuth.issuePairingCredential({ + access: "auto", + founder: "jeff", + }); + expect( + (yield* serverAuth.listPairingLinks()).find((link) => link.id === agentCode.id)?.founder, + ).toBeUndefined(); + + // Earlier sessions are not evidence of who holds a new one. + const desktop = () => + sessions.issue({ + subject: "desktop-bootstrap", + method: "browser-session-cookie", + client: { label: "Desktop", deviceType: "desktop" }, + }); + const firstDesktop = yield* desktop(); + yield* serverAuth.setClientSessionFounder(admin.sessionId, firstDesktop.sessionId, "jeff"); + expect(yield* founderOf((yield* desktop()).sessionId)).toBeNull(); + const reusedKey = "reused-proof-key"; + const pairWithKey = () => + serverAuth + .issuePairingCredential() + .pipe( + Effect.flatMap((code) => + serverAuth.exchangeBootstrapCredentialForAccessToken( + code.credential, + undefined, + requestMetadata, + { proofKeyThumbprint: reusedKey }, + ), + ), + ); + yield* pairWithKey(); + const [keyed] = (yield* serverAuth.listClientSessions(admin.sessionId)).filter( + (session) => session.subject !== "desktop-bootstrap" && session.founder === undefined, + ); + yield* serverAuth.setClientSessionFounder(admin.sessionId, keyed!.sessionId, "jeff"); + yield* pairWithKey(); + expect( + (yield* serverAuth.listClientSessions(admin.sessionId)).filter( + (session) => session.founder === "jeff" && session.subject !== "desktop-bootstrap", + ), + ).toHaveLength(1); + + // An approved Connect device keeps its founder through renewal, until it is revoked. + const deviceKey = "Hn4wT7qZpL2xV9cRb6mYs3kDf8gJa5eUo1iWt0zQrNE"; + const signIn = () => + serverAuth + .issueConnectCredential({ proofKeyThumbprint: deviceKey, requireApproval: false }) + .pipe( + Effect.flatMap((code) => + serverAuth.exchangeBootstrapCredentialForAccessToken( + code.credential, + undefined, + requestMetadata, + { proofKeyThumbprint: deviceKey }, + ), + ), + ); + const deviceSessions = () => + serverAuth + .listClientSessions(admin.sessionId) + .pipe( + Effect.map((all) => + all.filter((session) => session.subject === EnvironmentAuth.CLOUD_CONNECT_SUBJECT), + ), + ); + yield* signIn(); + const [device] = yield* deviceSessions(); + expect(device?.founder).toBeUndefined(); + yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, "kameron"); + yield* signIn(); + expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([ + "kameron", + "kameron", + ]); + yield* serverAuth.revokeClientSession(admin.sessionId, device!.sessionId); + yield* signIn(); + expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([undefined]); + }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))), + ); + it.effect("prefers a bearer token over an empty primary cookie", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 5798cd3076924..d00e607b3bccf 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -535,6 +535,7 @@ export class EnvironmentAuth extends Context.Service< readonly purpose?: "startup"; readonly mcpApproval?: AuthMcpClientAccess; readonly requiresConnectApproval?: boolean; + readonly founder?: Founder; }) => Effect.Effect< IssuedPairingLink, ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError @@ -1004,6 +1005,7 @@ export const make = Effect.gen(function* () { ...requestMetadata, ...(grant.label ? { label: grant.label } : {}), }, + ...(grant.founder === undefined ? {} : { founder: grant.founder }), }) .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))); return { @@ -1019,7 +1021,7 @@ export const make = Effect.gen(function* () { type ResolvedBootstrapGrant = Pick< PairingGrantStore.BootstrapGrant, - "scopes" | "subject" | "label" + "scopes" | "subject" | "label" | "founder" > & { readonly method: PairingGrantStore.BootstrapGrant["method"] | "reusable-dev-token"; }; @@ -1124,6 +1126,7 @@ export const make = Effect.gen(function* () { ...requestMetadata, ...(grant.label ? { label: grant.label } : {}), }, + ...(grant.founder === undefined ? {} : { founder: grant.founder }), }) .pipe( Effect.mapError( @@ -1176,6 +1179,7 @@ export const make = Effect.gen(function* () { ...(input?.purpose ? { purpose: input.purpose } : {}), ...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}), ...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}), + ...(input?.founder === undefined ? {} : { founder: input.founder }), }); return { id: issued.id, @@ -1386,6 +1390,8 @@ export const make = Effect.gen(function* () { subject: "one-time-token", ...(input?.label ? { label: input.label } : {}), ...(input?.access ? { mcpApproval: input.access } : {}), + // An agent sign-in is never a founder. + ...(input?.founder === undefined || input.access ? {} : { founder: input.founder }), }).pipe( Effect.map((issued) => ({ ...toPairingCredential(issued), diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index 62d78d3495013..c8382e2c2ce83 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -11,6 +11,7 @@ import { parseMcpApprovalCode, type ServerAuthBootstrapMethod, connectDeviceVerificationCode, + type Founder, } from "@t3tools/contracts"; import { DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS, @@ -39,6 +40,8 @@ export interface BootstrapGrant { readonly subject: string; readonly label?: string; readonly proofKeyThumbprint?: string; + /** The founder whose client this code enrolls. */ + readonly founder?: Founder; readonly expiresAt: DateTime.DateTime; } @@ -257,6 +260,8 @@ export class PairingGrantStore extends Context.Service< readonly mcpApproval?: AuthMcpClientAccess; /** Spendable only after someone trusts `proofKeyThumbprint` as a T3 Connect device. */ readonly requiresConnectApproval?: boolean; + /** Sessions this code starts belong to this founder. */ + readonly founder?: Founder; }) => Effect.Effect; /** A device's open or denied request, reused so retries keep one request and one code. */ readonly findPendingConnect: ( @@ -330,6 +335,7 @@ const toPairingLink = (row: AuthPairingLinks.AuthPairingLinkRecord): AuthPairing scopes: row.scopes, subject: row.subject, ...(row.label ? { label: row.label } : {}), + ...(row.founder === null ? {} : { founder: row.founder }), createdAt: row.createdAt, expiresAt: row.expiresAt, ...(row.requiresConnectApproval === 1 && row.proofKeyThumbprint @@ -495,6 +501,7 @@ const make = Effect.gen(function* () { label: input?.label ?? null, proofKeyThumbprint: input?.proofKeyThumbprint ?? null, ...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}), + ...(input?.founder === undefined ? {} : { founder: input.founder }), createdAt: now, expiresAt: expiresAt, }) @@ -516,6 +523,7 @@ const make = Effect.gen(function* () { scopes: input?.scopes ?? AuthStandardClientScopes, subject, ...(input?.label ? { label: input.label } : {}), + ...(input?.founder === undefined ? {} : { founder: input.founder }), createdAt: now, expiresAt, ...(input?.requiresConnectApproval && input.proofKeyThumbprint @@ -674,6 +682,7 @@ const make = Effect.gen(function* () { ...(consumed.value.proofKeyThumbprint ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint } : {}), + ...(consumed.value.founder === null ? {} : { founder: consumed.value.founder }), expiresAt: consumed.value.expiresAt, } satisfies BootstrapGrant; } diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index c03d4c686a1a5..cb8da66ba2beb 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -417,6 +417,8 @@ export class SessionStore extends Context.Service< readonly peerLink?: boolean; readonly replaceActiveForSubjectAndMethod?: boolean; readonly replaceSessionId?: AuthSessionId; + /** The founder the client's pairing code enrolled. */ + readonly founder?: Founder; }) => Effect.Effect; readonly verify: (token: string) => Effect.Effect; /** @@ -762,6 +764,7 @@ const make = Effect.gen(function* () { issuedAt, expiresAt, ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}), + ...(input?.founder === undefined ? {} : { founder: input.founder }), } satisfies AuthSessions.CreateAuthSessionInput; const replacedSessionIds = yield* ( input?.replaceSessionId !== undefined || input?.replaceActiveForSubjectAndMethod @@ -788,6 +791,17 @@ const make = Effect.gen(function* () { discard: true, }); } + // An approved T3 Connect device key can supply the founder, so read back what was stored. + const founder = + client.deviceType === "bot" + ? null + : (input?.founder ?? + (claims.jkt === undefined + ? null + : yield* authSessions.getById({ sessionId }).pipe( + Effect.map((row) => (Option.isSome(row) ? row.value.founder : null)), + Effect.orElseSucceed(() => null), + ))); yield* emitUpsert( toAuthClientSession({ sessionId, @@ -799,6 +813,7 @@ const make = Effect.gen(function* () { expiresAt, lastConnectedAt: null, connected: false, + ...(founder === null ? {} : { founder }), }), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index b5d0c845d242d..359e517c5e5c9 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1760,7 +1760,7 @@ const shellAttentionMentions = (text: string | null | undefined) => { }; const shellInbox = ( - inbox: ThreadInbox | undefined, + { inbox, standing }: { readonly inbox?: ThreadInbox | undefined; readonly standing?: unknown }, pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null, latestUserAuthoredMessageAt: DateTime.Utc | null, ) => @@ -1768,6 +1768,7 @@ const shellInbox = ( ? {} : { inbox: projectThreadInbox(inbox, { + standing: standing != null, pendingHumanRequest: pendingRuntimeRequest !== null, latestHumanMessageAt: latestUserAuthoredMessageAt === null @@ -1861,7 +1862,7 @@ export function threadShellFromProjection( }); return { createdBy: projection.thread.createdBy, - ...shellInbox(projection.thread.inbox, pendingRuntimeRequest, latestUserAuthoredMessageAt), + ...shellInbox(projection.thread, pendingRuntimeRequest, latestUserAuthoredMessageAt), creationSource: projection.thread.creationSource, id: projection.thread.id, projectId: projection.thread.projectId, @@ -2215,7 +2216,7 @@ function shellFromState(input: { ? {} : { historyOrigin: input.state.thread.historyOrigin }), ...shellInbox( - input.state.thread.inbox, + input.state.thread, input.state.pendingRuntimeRequest, input.state.latestUserAuthoredMessageAt, ), @@ -8644,7 +8645,7 @@ export const layer: Layer.Layer = pendingRuntimeRequest: null, // The same projected inbox the shell carries, so an answered ask is already gone. ...shellInbox( - thread.inbox, + thread, null, row.latest_user_authored_message_at === null ? null diff --git a/apps/server/src/persistence/AuthPairingLinks.ts b/apps/server/src/persistence/AuthPairingLinks.ts index df513f9963ca6..b12802f0119ac 100644 --- a/apps/server/src/persistence/AuthPairingLinks.ts +++ b/apps/server/src/persistence/AuthPairingLinks.ts @@ -7,7 +7,7 @@ import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlSchema from "effect/sql/SqlSchema"; -import { AuthClientMetadata, AuthEnvironmentScopes } from "@t3tools/contracts"; +import { AuthClientMetadata, AuthEnvironmentScopes, Founder } from "@t3tools/contracts"; import { type AuthPairingLinkRepositoryError, @@ -40,6 +40,8 @@ export const AuthPairingLinkRecord = Schema.Struct({ requiresConnectApproval: SqliteFlag, connectApproved: SqliteFlag, requestedClient: Schema.NullOr(Schema.fromJsonString(AuthClientMetadata)), + /** The founder whose client this code enrolls. */ + founder: Schema.NullOr(Founder), }); export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type; @@ -52,6 +54,7 @@ export const CreateAuthPairingLinkInput = Schema.Struct({ label: Schema.NullOr(Schema.String), proofKeyThumbprint: Schema.NullOr(Schema.String), requiresConnectApproval: Schema.optionalKey(Schema.Boolean), + founder: Schema.optionalKey(Founder), createdAt: Schema.DateTimeUtcFromString, expiresAt: Schema.DateTimeUtcFromString, }); @@ -126,6 +129,7 @@ const AuthPairingLinkRawDbRow = Schema.Struct({ requiresConnectApproval: Schema.Unknown, connectApproved: Schema.Unknown, requestedClient: Schema.Unknown, + founder: Schema.Unknown, }); const decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord); @@ -197,6 +201,7 @@ export const make = Effect.gen(function* () { label, proof_key_thumbprint, requires_connect_approval, + founder, created_at, expires_at, consumed_at, @@ -211,6 +216,7 @@ export const make = Effect.gen(function* () { ${input.label}, ${input.proofKeyThumbprint}, ${input.requiresConnectApproval ? 1 : 0}, + ${input.founder ?? null}, ${input.createdAt}, ${input.expiresAt}, NULL, @@ -281,7 +287,8 @@ export const make = Effect.gen(function* () { SELECT 1 FROM auth_connect_devices WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint ) AS "connectApproved", - requested_client_json AS "requestedClient" + requested_client_json AS "requestedClient", + founder AS "founder" `, }); @@ -307,7 +314,8 @@ export const make = Effect.gen(function* () { SELECT 1 FROM auth_connect_devices WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint ) AS "connectApproved", - requested_client_json AS "requestedClient" + requested_client_json AS "requestedClient", + founder AS "founder" FROM auth_pairing_links WHERE revoked_at IS NULL AND consumed_at IS NULL @@ -354,7 +362,8 @@ export const make = Effect.gen(function* () { SELECT 1 FROM auth_connect_devices WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint ) AS "connectApproved", - requested_client_json AS "requestedClient" + requested_client_json AS "requestedClient", + founder AS "founder" FROM auth_pairing_links WHERE credential = ${credential} `, @@ -378,7 +387,8 @@ export const make = Effect.gen(function* () { SELECT 1 FROM auth_connect_devices WHERE auth_connect_devices.proof_key_thumbprint = auth_pairing_links.proof_key_thumbprint ) AS "connectApproved", - requested_client_json AS "requestedClient" + requested_client_json AS "requestedClient", + founder AS "founder" FROM auth_pairing_links `; diff --git a/apps/server/src/persistence/AuthSessions.ts b/apps/server/src/persistence/AuthSessions.ts index 7ef35c10e433c..c25430ea72c06 100644 --- a/apps/server/src/persistence/AuthSessions.ts +++ b/apps/server/src/persistence/AuthSessions.ts @@ -56,6 +56,8 @@ export const CreateAuthSessionInput = Schema.Struct({ issuedAt: Schema.DateTimeUtcFromString, expiresAt: Schema.DateTimeUtcFromString, proofKeyThumbprint: Schema.optionalKey(Schema.String), + /** The founder the session's pairing code enrolled. */ + founder: Schema.optionalKey(Founder), }); export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type; @@ -160,9 +162,6 @@ export class AuthSessionRepository extends Context.Service< } >()("t3/persistence/AuthSessions/AuthSessionRepository") {} -/** The subject of the local desktop app's sessions; there is one such app per server. */ -const DESKTOP_BOOTSTRAP_SUBJECT = "desktop-bootstrap"; - const AuthSessionDbRow = Schema.Struct({ sessionId: AuthSessionId, subject: Schema.String, @@ -261,7 +260,8 @@ export const make = Effect.gen(function* () { issued_at, expires_at, revoked_at, - proof_key_thumbprint + proof_key_thumbprint, + founder ) VALUES ( ${input.sessionId}, @@ -277,7 +277,8 @@ export const make = Effect.gen(function* () { ${input.issuedAt}, ${input.expiresAt}, NULL, - ${input.proofKeyThumbprint ?? null} + ${input.proofKeyThumbprint ?? null}, + ${input.client.deviceType === "bot" ? null : (input.founder ?? null)} ) ${ignoreExisting ? sql`ON CONFLICT(session_id) DO NOTHING` : sql``} `, @@ -313,7 +314,7 @@ export const make = Effect.gen(function* () { const revokeActiveSessionsForReplacement = SqlSchema.findAll({ Request: CreateReplacingActiveAuthSessionInput, - Result: Schema.Struct({ sessionId: AuthSessionId, founder: Schema.NullOr(Founder) }), + Result: Schema.Struct({ sessionId: AuthSessionId }), execute: ({ session, revokedAt, replaceSessionId }) => sql` UPDATE auth_sessions @@ -326,7 +327,7 @@ export const make = Effect.gen(function* () { AND method = ${session.method} AND revoked_at IS NULL AND expires_at > ${revokedAt} - RETURNING session_id AS "sessionId", founder AS "founder" + RETURNING session_id AS "sessionId" `, }); @@ -384,36 +385,42 @@ export const make = Effect.gen(function* () { `, }); - // A device keeps its person across new sessions only where the server can tell it is the same - // device: one proof key (a T3 Connect device renewing hourly) or the local desktop app's - // bootstrap. Other subjects can span several devices, so they never inherit a person. - const inheritFounderRow = SqlSchema.void({ + // Assigning a T3 Connect device's session binds the approved device key, so its hourly + // sessions keep that founder until the device is revoked. + const bindConnectDeviceFounderRow = SqlSchema.void({ + Request: SetAuthSessionFounderInput, + execute: ({ sessionId, founder }) => + sql` + UPDATE auth_connect_devices + SET founder = ${founder} + WHERE proof_key_thumbprint = ( + SELECT proof_key_thumbprint FROM auth_sessions WHERE session_id = ${sessionId} + ) + `, + }); + + // A new session's founder comes from its own pairing code or its approved T3 Connect device key. + // Earlier sessions never pass one on: a shared desktop bootstrap, a reused key or a replaced + // cookie could otherwise hand one founder's identity to someone else. + const inheritDeviceFounderRow = SqlSchema.void({ Request: CreateAuthSessionInput, execute: (input) => sql` UPDATE auth_sessions SET founder = ( - SELECT prior.founder - FROM auth_sessions AS prior - WHERE prior.session_id <> ${input.sessionId} - AND ${ - input.proofKeyThumbprint === undefined - ? sql`prior.subject = ${DESKTOP_BOOTSTRAP_SUBJECT} - AND prior.proof_key_thumbprint IS NULL` - : sql`prior.proof_key_thumbprint = ${input.proofKeyThumbprint}` - } - ORDER BY prior.issued_at DESC - LIMIT 1 + SELECT device.founder + FROM auth_connect_devices AS device + WHERE device.proof_key_thumbprint = ${input.proofKeyThumbprint ?? null} ) WHERE session_id = ${input.sessionId} AND founder IS NULL AND client_device_type IS NOT 'bot' `, }); - const inheritFounder = (input: CreateAuthSessionInput) => - input.proofKeyThumbprint !== undefined || input.subject === DESKTOP_BOOTSTRAP_SUBJECT - ? inheritFounderRow(input) - : Effect.void; + const inheritDeviceFounder = (input: CreateAuthSessionInput) => + input.proofKeyThumbprint === undefined || input.founder !== undefined + ? Effect.void + : inheritDeviceFounderRow(input); const revokeSessionRows = SqlSchema.findAll({ Request: RevokeAuthSessionInput, @@ -482,7 +489,7 @@ export const make = Effect.gen(function* () { const create: AuthSessionRepository["Service"]["create"] = (input) => sql - .withTransaction(createSessionRow(input).pipe(Effect.andThen(inheritFounder(input)))) + .withTransaction(createSessionRow(input).pipe(Effect.andThen(inheritDeviceFounder(input)))) .pipe( Effect.mapError( toPersistenceSqlOrDecodeError( @@ -501,23 +508,7 @@ export const make = Effect.gen(function* () { revokeActiveSessionsForReplacement(input).pipe( Effect.flatMap((revokedRows) => createSessionRow(input.session).pipe( - Effect.andThen(inheritFounder(input.session)), - Effect.andThen(() => { - // Re-pairing one named client keeps who uses it. Replacing every session for a - // subject could span several devices, so that never carries a person over. - const founders = new Set(revokedRows.map((row) => row.founder)); - const [founder] = founders; - return input.replaceSessionId !== undefined && - founders.size === 1 && - founder !== null && - founder !== undefined - ? setFounderRows({ - sessionId: input.session.sessionId, - founder, - now: input.revokedAt, - }) - : Effect.void; - }), + Effect.andThen(inheritDeviceFounder(input.session)), Effect.as(revokedRows.map((row) => row.sessionId)), ), ), @@ -645,16 +636,24 @@ export const make = Effect.gen(function* () { ); const setFounder: AuthSessionRepository["Service"]["setFounder"] = (input) => - setFounderRows(input).pipe( - Effect.mapError( - toPersistenceSqlOrDecodeError( - "AuthSessionRepository.setFounder:query", - "AuthSessionRepository.setFounder:decodeRows", - { sessionId: input.sessionId }, + sql + .withTransaction( + setFounderRows(input).pipe( + Effect.tap((rows) => + rows.length > 0 ? bindConnectDeviceFounderRow(input) : Effect.void, + ), ), - ), - Effect.map((rows) => rows.length > 0), - ); + ) + .pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.setFounder:query", + "AuthSessionRepository.setFounder:decodeRows", + { sessionId: input.sessionId }, + ), + ), + Effect.map((rows) => rows.length > 0), + ); const getProofKeyThumbprint: AuthSessionRepository["Service"]["getProofKeyThumbprint"] = ( input, diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 6118c51093f9c..f8105f89daea6 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -105,6 +105,7 @@ import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts"; import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts"; import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts"; import Migration0097 from "./Migrations/097_AuthSessionFounder.ts"; +import Migration0098 from "./Migrations/098_FounderEnrollmentBindings.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -205,6 +206,7 @@ const migrationEntries = [ [95, "TurnItemInlineWorkOutput", Migration0095], [96, "RepairStaleTitleRegeneration", Migration0096], [97, "AuthSessionFounder", Migration0097], + [98, "FounderEnrollmentBindings", Migration0098], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/098_FounderEnrollmentBindings.test.ts b/apps/server/src/persistence/Migrations/098_FounderEnrollmentBindings.test.ts new file mode 100644 index 0000000000000..f845e3499fe49 --- /dev/null +++ b/apps/server/src/persistence/Migrations/098_FounderEnrollmentBindings.test.ts @@ -0,0 +1,47 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); + +layer("098_FounderEnrollmentBindings", (it) => { + it.effect("binds each Connect device to the founder of its newest live assigned session", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 97 }); + for (const key of ["assigned", "unassigned"]) { + yield* sql` + INSERT INTO auth_connect_devices (proof_key_thumbprint, approved_at) + VALUES (${key}, '2026-11-01') + `; + } + const sessions = [ + { id: "old", key: "assigned", founder: "kameron", issuedAt: "2026-11-01", revokedAt: null }, + { id: "revoked", key: "assigned", founder: "jeff", issuedAt: "2026-11-02", revokedAt: "x" }, + { id: "blank", key: "assigned", founder: null, issuedAt: "2026-11-03", revokedAt: null }, + { id: "other", key: "unassigned", founder: null, issuedAt: "2026-11-03", revokedAt: null }, + ]; + for (const session of sessions) { + yield* sql` + INSERT INTO auth_sessions + (session_id, subject, scopes, method, issued_at, expires_at, revoked_at, + proof_key_thumbprint, founder) + VALUES (${session.id}, 't3-connect', '[]', 'bearer-session-token', ${session.issuedAt}, + '2026-12-01', ${session.revokedAt}, ${session.key}, ${session.founder}) + `; + } + yield* runMigrations(); + assert.deepStrictEqual( + yield* sql`SELECT proof_key_thumbprint, founder FROM auth_connect_devices ORDER BY 1`, + [ + { proof_key_thumbprint: "assigned", founder: "kameron" }, + { proof_key_thumbprint: "unassigned", founder: null }, + ], + ); + yield* sql`UPDATE auth_pairing_links SET founder = 'jeff'`; + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/098_FounderEnrollmentBindings.ts b/apps/server/src/persistence/Migrations/098_FounderEnrollmentBindings.ts new file mode 100644 index 0000000000000..63e347bbb5ebd --- /dev/null +++ b/apps/server/src/persistence/Migrations/098_FounderEnrollmentBindings.ts @@ -0,0 +1,34 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * The founder a pairing code enrolls, and the founder an approved T3 Connect device key belongs + * to. New sessions take their founder only from these, never from earlier sessions. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const hasFounder = (columns: ReadonlyArray<{ readonly name: string }>) => + columns.some((column) => column.name === "founder"); + if (!hasFounder(yield* sql<{ readonly name: string }>`PRAGMA table_info(auth_pairing_links)`)) { + yield* sql`ALTER TABLE auth_pairing_links ADD COLUMN founder TEXT`; + } + if (!hasFounder(yield* sql<{ readonly name: string }>`PRAGMA table_info(auth_connect_devices)`)) { + yield* sql`ALTER TABLE auth_connect_devices ADD COLUMN founder TEXT`; + } + + // A device someone already assigned keeps that founder through its next hourly renewal. + yield* sql` + UPDATE auth_connect_devices + SET founder = ( + SELECT session.founder + FROM auth_sessions AS session + WHERE session.proof_key_thumbprint = auth_connect_devices.proof_key_thumbprint + AND session.revoked_at IS NULL + AND session.founder IS NOT NULL + ORDER BY session.issued_at DESC + LIMIT 1 + ) + WHERE founder IS NULL + `; +}); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index e9034c13dd600..dea49bf13069f 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -2,6 +2,7 @@ import { deriveProviderInstanceConfigMap } from "./provider/ProviderInstanceRegi import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { + AuthAccessWriteScope, AuthSettingsWriteScope, DEFAULT_SERVER_SETTINGS, globalIdleCompaction, @@ -267,6 +268,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" assert.deepEqual(requiredScopesForServerSettingsPatch({ ownerFounder: "jeff" }), [ AuthSettingsWriteScope, ]); + // Requiring enrolled founders decides who may act, so it is an access change. + assert.deepEqual(requiredScopesForServerSettingsPatch({ requireFounderIdentity: true }), [ + AuthAccessWriteScope, + ]); yield* service.updateSettings({ ownerFounder: "kameron" }); const persisted = yield* decodeServerSettingsJson( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 0ccf7fb913a3e..5a0ccf6c675fa 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2,7 +2,6 @@ import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- A synchronous digest inside the pure provider mapping. import * as NodeCrypto from "node:crypto"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { creditUnassignedSender } from "@t3tools/shared/seenMarker"; import * as Context from "effect/Context"; import * as NodeHttpServerRequest from "@effect/platform-node/NodeHttpServerRequest"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -115,6 +114,9 @@ import { type PullRequestRef, WS_METHODS, WsRpcGroup, + type InboxActor, + creatorInboxOrigin, + refusesUnenrolledSender, } from "@t3tools/contracts"; import { HttpRouter, @@ -2050,19 +2052,41 @@ export const layerWsRpc = ( return yield* mutateProjectWithClone(projectService, projectCloneTracker, mutation); }); - // A session names a person only when another client assigned it. A person's unassigned - // client credits this machine's owner; a bot never does, and a null owner stays unnamed. - const messageSender = serverAuth.messageSenderOf(currentSessionId).pipe( - Effect.filterOrElse( - (sentBy) => sentBy.founder !== null || sentBy.deviceType === "bot", - (sentBy) => - serverSettings.getSettings.pipe( - Effect.map((settings) => creditUnassignedSender(sentBy, settings.ownerFounder)), - // A settings read must not fail the send. Leave the sender unassigned. - Effect.orElseSucceed(() => sentBy), - ), - ), - ); + // A session names a founder only when another client assigned it. An unassigned session + // stays unnamed: guessing this machine's owner can credit the wrong founder. + const messageSender = serverAuth.messageSenderOf(currentSessionId); + + // A person's new thread files under their session's founder; a failed read keeps the claim. + const creatorOrigin = (claimed: InboxActor | undefined) => + messageSender.pipe( + Effect.map((sender) => creatorInboxOrigin(claimed, sender)), + Effect.orElseSucceed(() => claimed), + ); + // Checked before anything is queued. A settings or sender read that fails refuses too. + const refusesUnenrolled = (commandType: string) => + serverSettings.getSettings.pipe( + Effect.flatMap((settings) => + settings.requireFounderIdentity + ? messageSender.pipe( + Effect.map((sender) => refusesUnenrolledSender(true, commandType, sender)), + ) + : Effect.succeed(false), + ), + Effect.orElseSucceed(() => true), + ); + const UNENROLLED_SENDER_MESSAGE = + "This client is not enrolled as a founder. Pair it with a founder's pairing code, or have another client assign it in Settings → Connections."; + const fileUnderCreator = ( + command: OrchestrationV2Command, + ): Effect.Effect => { + if (command.type !== "thread.create") return Effect.succeed(command); + const { inboxOrigin: claimed, ...rest } = command; + return creatorOrigin(claimed).pipe( + Effect.map((inboxOrigin) => + inboxOrigin === undefined ? rest : { ...rest, inboxOrigin }, + ), + ); + }; const handlers = ServerWsRpcGroup.of({ [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => @@ -2083,7 +2107,18 @@ export const layerWsRpc = ( ? { "orchestration_v2.source_thread_id": command.sourceThreadId } : {}), }).pipe( - Effect.andThen(() => { + Effect.andThen(() => refusesUnenrolled(command.type)), + Effect.flatMap((refused) => { + if (refused) { + return Effect.fail( + new OrchestrationV2DispatchCommandError({ + commandId: command.commandId, + commandType: command.type, + message: UNENROLLED_SENDER_MESSAGE, + detail: UNENROLLED_SENDER_MESSAGE, + }), + ); + } const dispatched = startup .enqueueCommand( (command.type === "prepared-run.retry" @@ -2095,8 +2130,13 @@ export const layerWsRpc = ( : Effect.succeed(Option.none()) ).pipe( Effect.flatMap((sentBy) => + fileUnderCreator(command).pipe( + Effect.map((filed) => ({ filed, sentBy })), + ), + ), + Effect.flatMap(({ filed, sentBy }) => ThreadMessageIntake.dispatchCommand( - ThreadManagementService.withCreationProvenance(command, { + ThreadManagementService.withCreationProvenance(filed, { createdBy: "user", creationSource: "creationSource" in command ? command.creationSource : "web", @@ -2297,6 +2337,18 @@ export const layerWsRpc = ( "orchestration_v2.command_id": input.commandId, "orchestration_v2.project_id": input.projectId, }).pipe( + Effect.andThen(refusesUnenrolled("thread.create")), + Effect.flatMap((refused) => + refused + ? Effect.fail( + new OrchestrationV2ThreadLaunchError({ + commandId: input.commandId, + projectId: input.projectId, + message: UNENROLLED_SENDER_MESSAGE, + }), + ) + : Effect.void, + ), Effect.andThen( startup .enqueueCommand( @@ -2308,14 +2360,15 @@ export const layerWsRpc = ( }) .pipe( Effect.andThen( - input.initialMessage === undefined ? Effect.undefined : messageSender, + Effect.all([ + input.initialMessage === undefined ? Effect.undefined : messageSender, + creatorOrigin(input.inboxOrigin), + ]), ), - Effect.flatMap((sentBy) => + Effect.flatMap(([sentBy, inboxOrigin]) => ThreadMessageIntake.launchThread({ commandId: input.commandId, - ...(input.inboxOrigin === undefined - ? {} - : { inboxOrigin: input.inboxOrigin }), + ...(inboxOrigin === undefined ? {} : { inboxOrigin }), ...(input.inboxRouting === undefined ? {} : { inboxRouting: input.inboxRouting }), diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx index 282e27ee1df33..c98c804331865 100644 --- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx +++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx @@ -549,26 +549,30 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({ {onSetFounder && clientSession.client.deviceType !== "bot" ? ( // Messages sent from this client show this person's name. The server refuses a client // naming itself, so the current one is set from another trusted client. - { + const value = event.target.value; + onSetFounder(clientSession.sessionId, value === "" ? null : (value as Founder)); + }} + > + + + + + + + {clientSession.current ? "Set from another client: a client cannot name the person using it" - : "Messages sent from this client show this person's name" - } - data-client-session-founder - className="h-6 rounded-md border border-border/60 bg-transparent px-1 text-xs text-foreground disabled:opacity-60" - disabled={!canRevoke || clientSession.current} - value={clientSession.founder ?? ""} - onChange={(event) => { - const value = event.target.value; - onSetFounder(clientSession.sessionId, value === "" ? null : (value as Founder)); - }} - > - - - - + : "Messages sent from this client show this person's name"} + + ) : null} {!clientSession.current ? (