Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion apps/server/src/auth/EnvironmentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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]);
Expand Down
19 changes: 12 additions & 7 deletions apps/server/src/auth/SessionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},
);

Expand Down
12 changes: 12 additions & 0 deletions apps/server/src/auth/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
9 changes: 7 additions & 2 deletions apps/server/src/auth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 } : {}),
};
Expand Down
44 changes: 36 additions & 8 deletions apps/server/src/persistence/AuthSessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,13 @@ export class AuthSessionRepository extends Context.Service<
readonly setLastConnectedAt: (
input: SetAuthSessionLastConnectedAtInput,
) => Effect.Effect<void, AuthSessionRepositoryError>;
/** 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<boolean, AuthSessionRepositoryError>;
) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;
readonly getProofKeyThumbprint: (
input: GetAuthSessionByIdInput,
) => Effect.Effect<Option.Option<string>, AuthSessionRepositoryError>;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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(
Expand All @@ -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"] = (
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/persistence/Migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading