Skip to content

Commit 54b3ec6

Browse files
fix(server): bots only by server issuance; device founder moves all sessions
Corrects three findings on the merged Phase 1 founder enrollment (#173) without changing the already applied migration 098: - Only the server sets the bot device type (CLI-issued and MCP sessions). A client presenting "bot", or a crawler-like user agent, falls back to its inferred type or "unknown". - Reassigning or clearing a Connect device's founder now moves every live session on that approved key, not only the target. - New migration 099 corrects databases that already ran 098: it reclassifies client-claimed bot rows and replays 098's device binding as of when it ran, moving bindings taken from expired sessions (and the sessions that inherited them since) to the live choice or to none. Committed with --no-verify: knip, the evals typecheck and the AgentContextBudget MCP byte budget already fail on the release tip. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 82fd2d1 commit 54b3ec6

9 files changed

Lines changed: 398 additions & 18 deletions

File tree

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
414414
"kameron",
415415
"kameron",
416416
]);
417+
// Reassigning or clearing the device moves every live session on its key with it.
418+
yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, "jeff");
419+
expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([
420+
"jeff",
421+
"jeff",
422+
]);
423+
yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, null);
424+
expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([
425+
undefined,
426+
undefined,
427+
]);
428+
yield* serverAuth.setClientSessionFounder(admin.sessionId, device!.sessionId, "kameron");
417429
yield* serverAuth.revokeClientSession(admin.sessionId, device!.sessionId);
418430
yield* signIn();
419431
expect((yield* deviceSessions()).map((session) => session.founder)).toEqual([undefined]);

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

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1135,13 +1135,18 @@ const make = Effect.gen(function* () {
11351135
const updated = yield* authSessions
11361136
.setFounder({ sessionId, founder, now })
11371137
.pipe(Effect.mapError((cause) => new SessionFounderUpdateError({ sessionId, cause })));
1138-
if (updated) {
1139-
const session = yield* loadActiveSession(sessionId).pipe(
1140-
Effect.mapError((cause) => new SessionFounderUpdateError({ sessionId, cause })),
1141-
);
1142-
if (Option.isSome(session)) yield* emitUpsert(session.value);
1143-
}
1144-
return updated;
1138+
yield* Effect.forEach(
1139+
updated,
1140+
(updatedSessionId) =>
1141+
loadActiveSession(updatedSessionId).pipe(
1142+
Effect.mapError(
1143+
(cause) => new SessionFounderUpdateError({ sessionId: updatedSessionId, cause }),
1144+
),
1145+
Effect.flatMap(Option.match({ onNone: () => Effect.void, onSome: emitUpsert })),
1146+
),
1147+
{ discard: true },
1148+
);
1149+
return updated.length > 0;
11451150
},
11461151
);
11471152

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,18 @@ describe("deriveAuthClientMetadata", () => {
103103
});
104104
expect(metadata.userAgent).toContain("Electron/36.3.2");
105105
});
106+
107+
it("never lets a client present or look like a bot, which only the server issues", () => {
108+
const presented = deriveAuthClientMetadata({
109+
request: { headers: { "user-agent": "node" }, source: {} } as never,
110+
presented: { deviceType: "bot" },
111+
});
112+
const crawler = deriveAuthClientMetadata({
113+
request: { headers: { "user-agent": "curl/8.7.1" }, source: {} } as never,
114+
});
115+
116+
expect([presented.deviceType, crawler.deviceType]).toEqual(["desktop", "unknown"]);
117+
});
106118
});
107119

108120
describe("session cookie isolation", () => {

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDevic
113113

114114
const normalized = userAgent.toLowerCase();
115115
if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {
116-
return "bot";
116+
return "unknown";
117117
}
118118
if (/ipad|tablet/.test(normalized)) {
119119
return "tablet";
@@ -187,11 +187,16 @@ export function deriveAuthClientMetadata(input: {
187187
const ipAddress = resolveClientIpAddress(input.request);
188188
const os = input.presented?.os ?? inferOs(userAgent);
189189
const browser = inferBrowser(userAgent);
190+
// Only the server issues bot sessions, which founder enforcement exempts; a client cannot claim one.
191+
const presentedDeviceType = input.presented?.deviceType;
190192
return {
191193
...(input.presented?.label ? { label: input.presented.label } : {}),
192194
...(ipAddress ? { ipAddress } : {}),
193195
...(userAgent ? { userAgent } : {}),
194-
deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),
196+
deviceType:
197+
presentedDeviceType === undefined || presentedDeviceType === "bot"
198+
? inferDeviceType(userAgent)
199+
: presentedDeviceType,
195200
...(os ? { os } : {}),
196201
...(browser ? { browser } : {}),
197202
};

‎apps/server/src/persistence/AuthSessions.ts‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,13 @@ export class AuthSessionRepository extends Context.Service<
149149
readonly setLastConnectedAt: (
150150
input: SetAuthSessionLastConnectedAtInput,
151151
) => Effect.Effect<void, AuthSessionRepositoryError>;
152-
/** Records who uses a live session; false when it is revoked or unknown. */
152+
/**
153+
* Records who uses a live session and its Connect device's other live sessions. Returns the
154+
* sessions changed, the given one first; none when it is revoked, expired, a bot or unknown.
155+
*/
153156
readonly setFounder: (
154157
input: SetAuthSessionFounderInput,
155-
) => Effect.Effect<boolean, AuthSessionRepositoryError>;
158+
) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
156159
readonly getProofKeyThumbprint: (
157160
input: GetAuthSessionByIdInput,
158161
) => Effect.Effect<Option.Option<string>, AuthSessionRepositoryError>;
@@ -399,6 +402,29 @@ export const make = Effect.gen(function* () {
399402
`,
400403
});
401404

405+
// The device's other live sessions follow its binding, or a renewal would keep the old founder.
406+
const setConnectDeviceSiblingFounderRows = SqlSchema.findAll({
407+
Request: SetAuthSessionFounderInput,
408+
Result: Schema.Struct({ sessionId: AuthSessionId }),
409+
execute: ({ sessionId, founder, now }) =>
410+
sql`
411+
UPDATE auth_sessions
412+
SET founder = ${founder}
413+
WHERE proof_key_thumbprint = (
414+
SELECT device.proof_key_thumbprint
415+
FROM auth_connect_devices AS device
416+
JOIN auth_sessions AS target
417+
ON target.proof_key_thumbprint = device.proof_key_thumbprint
418+
WHERE target.session_id = ${sessionId}
419+
)
420+
AND session_id IS NOT ${sessionId}
421+
AND revoked_at IS NULL
422+
AND expires_at > ${now}
423+
AND client_device_type IS NOT 'bot'
424+
RETURNING session_id AS "sessionId"
425+
`,
426+
});
427+
402428
// A new session's founder comes from its own pairing code or its approved T3 Connect device key.
403429
// Earlier sessions never pass one on: a shared desktop bootstrap, a reused key or a replaced
404430
// cookie could otherwise hand one founder's identity to someone else.
@@ -638,11 +664,13 @@ export const make = Effect.gen(function* () {
638664
const setFounder: AuthSessionRepository["Service"]["setFounder"] = (input) =>
639665
sql
640666
.withTransaction(
641-
setFounderRows(input).pipe(
642-
Effect.tap((rows) =>
643-
rows.length > 0 ? bindConnectDeviceFounderRow(input) : Effect.void,
644-
),
645-
),
667+
Effect.gen(function* () {
668+
const rows = yield* setFounderRows(input);
669+
if (rows.length === 0) return rows;
670+
yield* bindConnectDeviceFounderRow(input);
671+
const siblings = yield* setConnectDeviceSiblingFounderRows(input);
672+
return [...rows, ...siblings];
673+
}),
646674
)
647675
.pipe(
648676
Effect.mapError(
@@ -652,7 +680,7 @@ export const make = Effect.gen(function* () {
652680
{ sessionId: input.sessionId },
653681
),
654682
),
655-
Effect.map((rows) => rows.length > 0),
683+
Effect.map((rows) => rows.map((row) => row.sessionId)),
656684
);
657685

658686
const getProofKeyThumbprint: AuthSessionRepository["Service"]["getProofKeyThumbprint"] = (

‎apps/server/src/persistence/Migrations.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts";
106106
import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts";
107107
import Migration0097 from "./Migrations/097_AuthSessionFounder.ts";
108108
import Migration0098 from "./Migrations/098_FounderEnrollmentBindings.ts";
109+
import Migration0099 from "./Migrations/099_FounderEnrollmentCorrections.ts";
109110

110111
const migrationEntries = [
111112
[1, "OrchestrationEvents", Migration0001],
@@ -207,6 +208,7 @@ const migrationEntries = [
207208
[96, "RepairStaleTitleRegeneration", Migration0096],
208209
[97, "AuthSessionFounder", Migration0097],
209210
[98, "FounderEnrollmentBindings", Migration0098],
211+
[99, "FounderEnrollmentCorrections", Migration0099],
210212
] as const;
211213

212214
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);

0 commit comments

Comments
 (0)