diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index ece154fe2a4b8..50abe0d08151e 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -369,7 +369,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( ); yield* pairWithKey(); const [keyed] = (yield* serverAuth.listClientSessions(admin.sessionId)).filter( - (session) => session.subject !== "desktop-bootstrap" && session.founder === undefined, + (session) => + session.sessionId !== admin.sessionId && + session.subject !== "desktop-bootstrap" && + session.founder === undefined, ); yield* serverAuth.setClientSessionFounder(admin.sessionId, keyed!.sessionId, "jeff"); yield* pairWithKey(); @@ -411,6 +414,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( "kameron", "kameron", ]); + // Reassigning or clearing the device moves every live session on its key with it. + yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, "jeff"); + expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([ + "jeff", + "jeff", + ]); + yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, null); + expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([ + undefined, + undefined, + ]); + yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, "kameron"); yield* serverAuth.revokeClientSession(admin.sessionId, device!.sessionId); yield* signIn(); expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([undefined]); diff --git a/apps/server/src/auth/SessionStore.ts b/apps/server/src/auth/SessionStore.ts index cb8da66ba2beb..863af889acf87 100644 --- a/apps/server/src/auth/SessionStore.ts +++ b/apps/server/src/auth/SessionStore.ts @@ -1135,13 +1135,18 @@ const make = Effect.gen(function* () { const updated = yield* authSessions .setFounder({ sessionId, founder, now }) .pipe(Effect.mapError((cause) => new SessionFounderUpdateError({ sessionId, cause }))); - if (updated) { - const session = yield* loadActiveSession(sessionId).pipe( - Effect.mapError((cause) => new SessionFounderUpdateError({ sessionId, cause })), - ); - if (Option.isSome(session)) yield* emitUpsert(session.value); - } - return updated; + yield* Effect.forEach( + updated, + (updatedSessionId) => + loadActiveSession(updatedSessionId).pipe( + Effect.mapError( + (cause) => new SessionFounderUpdateError({ sessionId: updatedSessionId, cause }), + ), + Effect.flatMap(Option.match({ onNone: () => Effect.void, onSome: emitUpsert })), + ), + { discard: true }, + ); + return updated.length > 0; }, ); diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.ts index f9c228aeb418b..8069c4329c9a0 100644 --- a/apps/server/src/auth/utils.test.ts +++ b/apps/server/src/auth/utils.test.ts @@ -103,6 +103,18 @@ describe("deriveAuthClientMetadata", () => { }); expect(metadata.userAgent).toContain("Electron/36.3.2"); }); + + it("never lets a client present or look like a bot, which only the server issues", () => { + const presented = deriveAuthClientMetadata({ + request: { headers: { "user-agent": "node" }, source: {} } as never, + presented: { deviceType: "bot" }, + }); + const crawler = deriveAuthClientMetadata({ + request: { headers: { "user-agent": "curl/8.7.1" }, source: {} } as never, + }); + + expect([presented.deviceType, crawler.deviceType]).toEqual(["desktop", "unknown"]); + }); }); describe("session cookie isolation", () => { diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts index 12c27cc1fdf57..04f9b59a44d13 100644 --- a/apps/server/src/auth/utils.ts +++ b/apps/server/src/auth/utils.ts @@ -113,7 +113,7 @@ function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDevic const normalized = userAgent.toLowerCase(); if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) { - return "bot"; + return "unknown"; } if (/ipad|tablet/.test(normalized)) { return "tablet"; @@ -187,11 +187,16 @@ export function deriveAuthClientMetadata(input: { const ipAddress = resolveClientIpAddress(input.request); const os = input.presented?.os ?? inferOs(userAgent); const browser = inferBrowser(userAgent); + // Only the server issues bot sessions, which founder enforcement exempts; a client cannot claim one. + const presentedDeviceType = input.presented?.deviceType; return { ...(input.presented?.label ? { label: input.presented.label } : {}), ...(ipAddress ? { ipAddress } : {}), ...(userAgent ? { userAgent } : {}), - deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent), + deviceType: + presentedDeviceType === undefined || presentedDeviceType === "bot" + ? inferDeviceType(userAgent) + : presentedDeviceType, ...(os ? { os } : {}), ...(browser ? { browser } : {}), }; diff --git a/apps/server/src/persistence/AuthSessions.ts b/apps/server/src/persistence/AuthSessions.ts index c25430ea72c06..1f2cdd1da8cf9 100644 --- a/apps/server/src/persistence/AuthSessions.ts +++ b/apps/server/src/persistence/AuthSessions.ts @@ -149,10 +149,13 @@ export class AuthSessionRepository extends Context.Service< readonly setLastConnectedAt: ( input: SetAuthSessionLastConnectedAtInput, ) => Effect.Effect; - /** Records who uses a live session; false when it is revoked or unknown. */ + /** + * Records who uses a live session and its Connect device's other live sessions. Returns the + * sessions changed, the given one first; none when it is revoked, expired, a bot or unknown. + */ readonly setFounder: ( input: SetAuthSessionFounderInput, - ) => Effect.Effect; + ) => Effect.Effect, AuthSessionRepositoryError>; readonly getProofKeyThumbprint: ( input: GetAuthSessionByIdInput, ) => Effect.Effect, AuthSessionRepositoryError>; @@ -399,6 +402,29 @@ export const make = Effect.gen(function* () { `, }); + // The device's other live sessions follow its binding, or a renewal would keep the old founder. + const setConnectDeviceSiblingFounderRows = SqlSchema.findAll({ + Request: SetAuthSessionFounderInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ sessionId, founder, now }) => + sql` + UPDATE auth_sessions + SET founder = ${founder} + WHERE proof_key_thumbprint = ( + SELECT device.proof_key_thumbprint + FROM auth_connect_devices AS device + JOIN auth_sessions AS target + ON target.proof_key_thumbprint = device.proof_key_thumbprint + WHERE target.session_id = ${sessionId} + ) + AND session_id IS NOT ${sessionId} + AND revoked_at IS NULL + AND expires_at > ${now} + AND client_device_type IS NOT 'bot' + RETURNING session_id AS "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. @@ -638,11 +664,13 @@ export const make = Effect.gen(function* () { const setFounder: AuthSessionRepository["Service"]["setFounder"] = (input) => sql .withTransaction( - setFounderRows(input).pipe( - Effect.tap((rows) => - rows.length > 0 ? bindConnectDeviceFounderRow(input) : Effect.void, - ), - ), + Effect.gen(function* () { + const rows = yield* setFounderRows(input); + if (rows.length === 0) return rows; + yield* bindConnectDeviceFounderRow(input); + const siblings = yield* setConnectDeviceSiblingFounderRows(input); + return [...rows, ...siblings]; + }), ) .pipe( Effect.mapError( @@ -652,7 +680,7 @@ export const make = Effect.gen(function* () { { sessionId: input.sessionId }, ), ), - Effect.map((rows) => rows.length > 0), + Effect.map((rows) => rows.map((row) => row.sessionId)), ); const getProofKeyThumbprint: AuthSessionRepository["Service"]["getProofKeyThumbprint"] = ( diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index f8105f89daea6..08e41f32541db 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -106,6 +106,7 @@ 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"; +import Migration0099 from "./Migrations/099_FounderEnrollmentCorrections.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -207,6 +208,7 @@ const migrationEntries = [ [96, "RepairStaleTitleRegeneration", Migration0096], [97, "AuthSessionFounder", Migration0097], [98, "FounderEnrollmentBindings", Migration0098], + [99, "FounderEnrollmentCorrections", Migration0099], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/099_FounderEnrollmentCorrections.test.ts b/apps/server/src/persistence/Migrations/099_FounderEnrollmentCorrections.test.ts new file mode 100644 index 0000000000000..77597eb755652 --- /dev/null +++ b/apps/server/src/persistence/Migrations/099_FounderEnrollmentCorrections.test.ts @@ -0,0 +1,221 @@ +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:" })); + +const live = "2999-01-01T00:00:00.000Z"; +const expired = "2000-01-01T00:00:00.000Z"; + +interface SeedSession { + readonly id: string; + readonly key: string; + readonly founder: string | null; + readonly issuedAt: string; + readonly expiresAt?: string; + readonly revokedAt?: string; +} + +const seedFounders = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + for (const key of ["assigned", "lapsed", "unassigned"]) { + yield* sql` + INSERT INTO auth_connect_devices (proof_key_thumbprint, approved_at) + VALUES (${key}, '2026-11-01') + `; + } + yield* insertSessions([ + { id: "old", key: "assigned", founder: "kameron", issuedAt: "2026-11-01T00:00:00.000Z" }, + { + id: "revoked", + key: "assigned", + founder: "jeff", + issuedAt: "2026-11-02T00:00:00.000Z", + revokedAt: "2026-11-02T01:00:00.000Z", + }, + { + id: "stale", + key: "assigned", + founder: "jeff", + issuedAt: "2026-11-04T00:00:00.000Z", + expiresAt: expired, + }, + { id: "blank", key: "assigned", founder: null, issuedAt: "2026-11-03T00:00:00.000Z" }, + { id: "other", key: "unassigned", founder: null, issuedAt: "2026-11-03T00:00:00.000Z" }, + { + id: "lapsed", + key: "lapsed", + founder: "jeff", + issuedAt: "2026-11-03T00:00:00.000Z", + expiresAt: expired, + }, + ]); +}); + +const insertSessions = (sessions: ReadonlyArray) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + 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}, + ${session.expiresAt ?? live}, ${session.revokedAt ?? null}, ${session.key}, + ${session.founder}) + `; + } + }); + +layer("099_FounderEnrollmentCorrections fresh database", (it) => { + it.effect("binds each Connect device only from a live assigned session", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 97 }); + yield* seedFounders; + 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: "lapsed", founder: null }, + { proof_key_thumbprint: "unassigned", founder: null }, + ], + ); + }), + ); +}); + +layer("099_FounderEnrollmentCorrections after 098 applied", (it) => { + it.effect("undoes bindings 098 took from expired sessions and what inherited them since", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 97 }); + yield* seedFounders; + yield* sql` + INSERT INTO auth_connect_devices (proof_key_thumbprint, approved_at) + VALUES ('moved', '2026-11-01'), ('dropped', '2026-11-01') + `; + yield* insertSessions([ + { + id: "moved-live", + key: "moved", + founder: "kameron", + issuedAt: "2026-11-05T00:00:00.000Z", + }, + { + id: "dropped-lapsed", + key: "dropped", + founder: "jeff", + issuedAt: "2026-11-05T00:00:00.000Z", + expiresAt: expired, + }, + ]); + yield* runMigrations({ toMigrationInclusive: 98 }); + assert.deepStrictEqual( + yield* sql`SELECT proof_key_thumbprint, founder FROM auth_connect_devices ORDER BY 1`, + [ + { proof_key_thumbprint: "assigned", founder: "jeff" }, + { proof_key_thumbprint: "dropped", founder: "jeff" }, + { proof_key_thumbprint: "lapsed", founder: "jeff" }, + { proof_key_thumbprint: "moved", founder: "kameron" }, + { proof_key_thumbprint: "unassigned", founder: null }, + ], + ); + yield* sql` + UPDATE effect_sql_migrations SET created_at = '2026-11-10 00:00:00' WHERE migration_id = 98 + `; + + // Since 098 ran: renewals inherited its bindings, one device was reassigned and one revoked. + yield* insertSessions([ + { + id: "assigned-renewed", + key: "assigned", + founder: "jeff", + issuedAt: "2026-11-12T00:00:00.000Z", + }, + { + id: "lapsed-renewed", + key: "lapsed", + founder: "jeff", + issuedAt: "2026-11-12T00:00:00.000Z", + }, + ]); + yield* sql`UPDATE auth_sessions SET founder = 'jeff' WHERE session_id = 'moved-live'`; + yield* sql`UPDATE auth_connect_devices SET founder = 'jeff' WHERE proof_key_thumbprint = 'moved'`; + yield* sql` + UPDATE auth_connect_devices SET founder = NULL WHERE proof_key_thumbprint = 'dropped' + `; + yield* sql` + INSERT INTO auth_sessions + (session_id, subject, scopes, method, issued_at, expires_at, client_ip_address, + client_device_type) + VALUES ('claimed', 'one-time-token', '[]', 'bearer-access-token', '2026-11-12T00:00:00.000Z', ${live}, + '192.168.1.9', 'bot') + `; + + 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: "dropped", founder: null }, + { proof_key_thumbprint: "lapsed", founder: null }, + { proof_key_thumbprint: "moved", founder: "jeff" }, + { proof_key_thumbprint: "unassigned", founder: null }, + ], + ); + assert.deepStrictEqual( + yield* sql` + SELECT session_id, founder, client_device_type FROM auth_sessions + WHERE session_id IN ('assigned-renewed', 'lapsed-renewed', 'moved-live', 'stale', 'claimed') + ORDER BY 1 + `, + [ + { session_id: "assigned-renewed", founder: "kameron", client_device_type: "unknown" }, + { session_id: "claimed", founder: null, client_device_type: "unknown" }, + { session_id: "lapsed-renewed", founder: null, client_device_type: "unknown" }, + { session_id: "moved-live", founder: "jeff", client_device_type: "unknown" }, + { session_id: "stale", founder: "jeff", client_device_type: "unknown" }, + ], + ); + }), + ); +}); + +layer("099_FounderEnrollmentCorrections agent provenance", (it) => { + it.effect("keeps the bot type only on sessions the server issued to an agent", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 98 }); + const sessions = [ + { id: "cli", subject: "cli-issued-session", ipAddress: null, userAgent: null }, + { id: "mcp", subject: "mcp-client", ipAddress: "192.168.1.9", userAgent: "agent" }, + { id: "claimed", subject: "one-time-token", ipAddress: "192.168.1.9", userAgent: null }, + { id: "crawler", subject: "one-time-token", ipAddress: null, userAgent: "curl/8.7.1" }, + ]; + for (const session of sessions) { + yield* sql` + INSERT INTO auth_sessions + (session_id, subject, scopes, method, issued_at, expires_at, + client_ip_address, client_user_agent, client_device_type) + VALUES (${session.id}, ${session.subject}, '[]', 'bearer-access-token', '2026-11-01', + ${live}, ${session.ipAddress}, ${session.userAgent}, 'bot') + `; + } + yield* runMigrations(); + assert.deepStrictEqual( + yield* sql`SELECT session_id, client_device_type FROM auth_sessions ORDER BY 1`, + [ + { session_id: "claimed", client_device_type: "unknown" }, + { session_id: "cli", client_device_type: "bot" }, + { session_id: "crawler", client_device_type: "unknown" }, + { session_id: "mcp", client_device_type: "bot" }, + ], + ); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/099_FounderEnrollmentCorrections.ts b/apps/server/src/persistence/Migrations/099_FounderEnrollmentCorrections.ts new file mode 100644 index 0000000000000..813a5d18b2dce --- /dev/null +++ b/apps/server/src/persistence/Migrations/099_FounderEnrollmentCorrections.ts @@ -0,0 +1,89 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * Corrects two mistakes 098 made, on databases that already applied it as well as new ones. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Bot sessions skip founder enforcement, so only server-issued ones keep the type. CLI-issued + // sessions record no network metadata and MCP sessions have their own subject; any other bot was + // a client's own claim or a crawler-like user agent. + yield* sql` + UPDATE auth_sessions + SET client_device_type = 'unknown' + WHERE client_device_type = 'bot' + AND subject IS NOT 'mcp-client' + AND (client_ip_address IS NOT NULL OR client_user_agent IS NOT NULL) + `; + + // 098 bound each device to its newest unrevoked founder session even when that session had + // expired. Replay its choice as of when it ran, and where an expired session decided it, move the + // device and the sessions that inherited from it since to the live choice, or to no founder. + // setFounder only touches live sessions, so an expired session still holds the founder 098 read. + yield* sql` + CREATE TEMP TABLE founder_backfill_corrections AS + WITH ran AS ( + SELECT strftime('%Y-%m-%dT%H:%M:%fZ', created_at) AS at + FROM effect_sql_migrations + WHERE migration_id = 98 + ), + replayed AS ( + SELECT + device.proof_key_thumbprint AS key, + device.founder AS current, + ran.at AS ran_at, + ( + SELECT session.founder + FROM auth_sessions AS session + WHERE session.proof_key_thumbprint = device.proof_key_thumbprint + AND session.issued_at <= ran.at + AND (session.revoked_at IS NULL OR session.revoked_at > ran.at) + AND session.founder IS NOT NULL + ORDER BY session.issued_at DESC + LIMIT 1 + ) AS bound, + ( + SELECT session.founder + FROM auth_sessions AS session + WHERE session.proof_key_thumbprint = device.proof_key_thumbprint + AND session.issued_at <= ran.at + AND (session.revoked_at IS NULL OR session.revoked_at > ran.at) + AND session.expires_at > ran.at + AND session.founder IS NOT NULL + ORDER BY session.issued_at DESC + LIMIT 1 + ) AS live + FROM auth_connect_devices AS device, ran + ) + SELECT key, bound, live, ran_at + FROM replayed + WHERE bound IS NOT NULL AND current = bound AND live IS NOT bound + `; + yield* sql` + UPDATE auth_sessions + SET founder = ( + SELECT correction.live + FROM founder_backfill_corrections AS correction + WHERE correction.key = auth_sessions.proof_key_thumbprint + ) + WHERE EXISTS ( + SELECT 1 + FROM founder_backfill_corrections AS correction + WHERE correction.key = auth_sessions.proof_key_thumbprint + AND auth_sessions.issued_at > correction.ran_at + AND auth_sessions.founder = correction.bound + ) + `; + yield* sql` + UPDATE auth_connect_devices + SET founder = ( + SELECT correction.live + FROM founder_backfill_corrections AS correction + WHERE correction.key = auth_connect_devices.proof_key_thumbprint + ) + WHERE proof_key_thumbprint IN (SELECT key FROM founder_backfill_corrections) + `; + yield* sql`DROP TABLE founder_backfill_corrections`; +}); diff --git a/docs/internals/environment-auth.md b/docs/internals/environment-auth.md index eb69dedcaba54..63af5e4e01299 100644 --- a/docs/internals/environment-auth.md +++ b/docs/internals/environment-auth.md @@ -34,7 +34,13 @@ founder comes only from its pairing code, its approved T3 Connect device key, or an assignment made from another client. It is never inherited from an earlier session: a shared desktop bootstrap or a reused proof key would hand one founder's name to whoever holds the next session. Revoking a device drops its -founder with it. Agent sign-in codes and bot sessions never carry one. +founder with it, and reassigning one moves all of its live sessions. Agent +sign-in codes and bot sessions never carry one. + +Requiring enrolled founders exempts bots, so the bot device type is server +provenance: only CLI-issued tokens and MCP client sessions get it. A client's +presented device type or user agent never yields it, unlike the rest of its +display metadata. ### Guest links are not sessions