Skip to content

Commit 363cde4

Browse files
fix(connect): refresh HTTP credentials without reconnecting (#9594)
1 parent ac90950 commit 363cde4

30 files changed

Lines changed: 2086 additions & 825 deletions

‎apps/mobile/src/connection/platform.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,9 @@ const capabilitiesLayer = Layer.effectContext(
118118
return Context.make(
119119
CloudSession,
120120
CloudSession.of({
121+
identity: Effect.sync(() =>
122+
Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
123+
),
121124
clerkToken: Effect.gen(function* () {
122125
const session = appAtomRegistry.get(managedRelaySessionAtom);
123126
if (session === null) {

‎apps/mobile/src/connection/runtime.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,8 @@ type ConnectionLayerSource =
3030
| typeof mobileBackgroundActivityObserverLayer
3131
| typeof mobileBackgroundActivityReporterLayer;
3232

33-
const providedClientConnectionLayer = Layer.merge(
34-
Connection.layerWithOptions({ usageLimitSources: true }),
35-
snapshotLoaderLayer,
36-
).pipe(
33+
const providedClientConnectionLayer = snapshotLoaderLayer.pipe(
34+
Layer.provideMerge(Connection.layerWithOptions({ usageLimitSources: true })),
3735
Layer.provideMerge(
3836
Layer.mergeAll(
3937
runtimeContextLayer,

‎apps/mobile/src/connection/storage.ts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
ConnectionPersistenceError,
33
ConnectionRegistrationStore,
44
ConnectionTargetStore,
5+
putRemoteDpopTokenInCatalog,
56
registerConnectionInCatalog,
67
removeConnectionFromCatalog,
78
removeCatalogValue,
@@ -109,15 +110,7 @@ export const connectionStorageLayer = Layer.effectContext(
109110
),
110111
),
111112
),
112-
put: (token) =>
113-
catalog.update((document) => ({
114-
...document,
115-
remoteDpopTokens: replaceCatalogValue(
116-
document.remoteDpopTokens,
117-
(value) => value.environmentId,
118-
token,
119-
),
120-
})),
113+
put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
121114
remove: (environmentId) =>
122115
catalog.update((document) => ({
123116
...document,

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

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import * as Duration from "effect/Duration";
55
import * as Effect from "effect/Effect";
66
import * as Layer from "effect/Layer";
77
import * as Option from "effect/Option";
8+
import * as Queue from "effect/Queue";
9+
import * as Stream from "effect/Stream";
810
import * as TestClock from "effect/testing/TestClock";
911
import * as SqlClient from "effect/unstable/sql/SqlClient";
1012

@@ -44,6 +46,14 @@ const makeSessionStoreLayer = (
4446
Layer.provide(makeServerConfigLayer(overrides)),
4547
);
4648

49+
const relaySessionInput = {
50+
subject: "managed-relay-bootstrap",
51+
method: "dpop-access-token",
52+
proofKeyThumbprint: "relay-proof-key",
53+
ttl: Duration.hours(1),
54+
client: { label: "Relay desktop", deviceType: "desktop" },
55+
} as const;
56+
4757
const repositoryFailure = new PersistenceSqlError({
4858
operation: "AuthSessionRepository.getById:query",
4959
detail: "sqlite is unavailable",
@@ -420,6 +430,124 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
420430
expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString());
421431
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
422432
);
433+
434+
it.effect("keeps connected relay sessions visible through expiry and HTTP renewal", () =>
435+
Effect.gen(function* () {
436+
const sessions = yield* SessionStore.SessionStore;
437+
const original = yield* sessions.issue(relaySessionInput);
438+
const websocket = yield* sessions.issueWebSocketToken(original.sessionId, {
439+
ttl: Duration.hours(2),
440+
});
441+
yield* sessions.verifyWebSocketToken(websocket.token);
442+
yield* sessions.markConnected(original.sessionId);
443+
const beforeExpiry = yield* sessions.listActive();
444+
expect(beforeExpiry).toHaveLength(1);
445+
expect(beforeExpiry[0]?.connected).toBe(true);
446+
447+
yield* TestClock.adjust(Duration.minutes(61));
448+
449+
expect(yield* sessions.listActive()).toEqual(beforeExpiry);
450+
expect(yield* Effect.flip(sessions.verify(original.token))).toMatchObject({
451+
_tag: "SessionTokenExpiredError",
452+
});
453+
expect(yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token))).toMatchObject({
454+
_tag: "WebSocketSessionExpiredError",
455+
});
456+
457+
const renewed = yield* sessions.issue(relaySessionInput);
458+
const afterRenewal = yield* sessions.listActive();
459+
expect(renewed.sessionId).not.toBe(original.sessionId);
460+
expect(afterRenewal).toHaveLength(2);
461+
expect(afterRenewal).toEqual(
462+
expect.arrayContaining([
463+
beforeExpiry[0],
464+
expect.objectContaining({
465+
sessionId: renewed.sessionId,
466+
connected: false,
467+
lastConnectedAt: null,
468+
}),
469+
]),
470+
);
471+
}).pipe(Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer()))),
472+
);
473+
474+
it.effect.each([1, 2])(
475+
"removes an expired session from listings and updates after its last of %s sockets closes",
476+
(socketCount) =>
477+
Effect.gen(function* () {
478+
const sessions = yield* SessionStore.SessionStore;
479+
const issued = yield* sessions.issue(relaySessionInput);
480+
const changes = yield* Queue.unbounded<SessionStore.SessionCredentialChange>();
481+
yield* sessions.streamChanges.pipe(
482+
Stream.runForEach((change) => Queue.offer(changes, change)),
483+
Effect.forkScoped({ startImmediately: true }),
484+
);
485+
for (let index = 0; index < socketCount; index += 1) {
486+
yield* sessions.markConnected(issued.sessionId);
487+
expect(yield* Queue.take(changes)).toMatchObject({
488+
type: "clientUpserted",
489+
clientSession: { sessionId: issued.sessionId, connected: true },
490+
});
491+
}
492+
493+
yield* TestClock.adjust(Duration.minutes(61));
494+
495+
for (let remaining = socketCount - 1; remaining >= 0; remaining -= 1) {
496+
yield* sessions.markDisconnected(issued.sessionId);
497+
const change = yield* Queue.take(changes);
498+
const listed = yield* sessions.listActive();
499+
if (remaining > 0) {
500+
expect(change).toMatchObject({
501+
type: "clientUpserted",
502+
clientSession: { sessionId: issued.sessionId, connected: true },
503+
});
504+
expect(listed).toHaveLength(1);
505+
expect(listed[0]?.connected).toBe(true);
506+
} else {
507+
expect(change).toEqual({ type: "clientRemoved", sessionId: issued.sessionId });
508+
expect(listed).toEqual([]);
509+
}
510+
}
511+
}).pipe(
512+
Effect.scoped,
513+
Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer())),
514+
),
515+
);
516+
517+
it.effect.each(["revoke", "revokeAllExcept"] as const)(
518+
"removes expired connected sessions with %s",
519+
(operation) =>
520+
Effect.gen(function* () {
521+
const sessions = yield* SessionStore.SessionStore;
522+
const administrative = yield* sessions.issue({ subject: "desktop-bootstrap" });
523+
const client = yield* sessions.issue(relaySessionInput);
524+
yield* sessions.markConnected(client.sessionId);
525+
yield* TestClock.adjust(Duration.minutes(61));
526+
const changes = yield* Queue.unbounded<SessionStore.SessionCredentialChange>();
527+
yield* sessions.streamChanges.pipe(
528+
Stream.runForEach((change) => Queue.offer(changes, change)),
529+
Effect.forkScoped({ startImmediately: true }),
530+
);
531+
532+
if (operation === "revoke") {
533+
expect(yield* sessions.revoke(client.sessionId)).toBe(true);
534+
} else {
535+
expect(yield* sessions.revokeAllExcept(administrative.sessionId)).toBe(1);
536+
}
537+
538+
expect(yield* Queue.take(changes)).toEqual({
539+
type: "clientRemoved",
540+
sessionId: client.sessionId,
541+
});
542+
const listed = yield* sessions.listActive();
543+
expect(listed).toHaveLength(1);
544+
expect(listed[0]?.sessionId).toBe(administrative.sessionId);
545+
}).pipe(
546+
Effect.scoped,
547+
Effect.provide(Layer.merge(makeSessionStoreLayer(), TestClock.layer())),
548+
),
549+
);
550+
423551
it.effect("records client connection metadata without clearing prior values", () =>
424552
Effect.gen(function* () {
425553
const sessions = yield* SessionStore.SessionStore;

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

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ export const make = Effect.gen(function* () {
482482
const secretStore = yield* ServerSecretStore.ServerSecretStore;
483483
const authSessions = yield* AuthSessions.AuthSessionRepository;
484484
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
485-
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
485+
const connectedSessionsRef = yield* Ref.make(new Map<AuthSessionId, number>());
486486
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
487487
const cookieInput = {
488488
mode: serverConfig.mode,
@@ -515,6 +515,11 @@ export const make = Effect.gen(function* () {
515515
}
516516

517517
const connectedSessions = yield* Ref.get(connectedSessionsRef);
518+
const connected = connectedSessions.has(row.value.sessionId);
519+
const now = yield* DateTime.now;
520+
if (!connected && row.value.expiresAt.epochMilliseconds <= now.epochMilliseconds) {
521+
return Option.none<AuthClientSession>();
522+
}
518523
return Option.some(
519524
toAuthClientSession({
520525
sessionId: row.value.sessionId,
@@ -525,7 +530,7 @@ export const make = Effect.gen(function* () {
525530
issuedAt: row.value.issuedAt,
526531
expiresAt: row.value.expiresAt,
527532
lastConnectedAt: row.value.lastConnectedAt,
528-
connected: connectedSessions.has(row.value.sessionId),
533+
connected,
529534
}),
530535
);
531536
});
@@ -599,7 +604,7 @@ export const make = Effect.gen(function* () {
599604
}).pipe(
600605
Effect.flatMap(() => loadActiveSession(sessionId)),
601606
Effect.flatMap((session) =>
602-
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
607+
Option.isSome(session) ? emitUpsert(session.value) : emitRemoved(sessionId),
603608
),
604609
Effect.catchCause((cause) =>
605610
Effect.logError("Failed to publish disconnected-session auth update.").pipe(
@@ -882,7 +887,10 @@ export const make = Effect.gen(function* () {
882887
function* () {
883888
const now = yield* DateTime.now;
884889
const connectedSessions = yield* Ref.get(connectedSessionsRef);
885-
const rows = yield* authSessions.listActive({ now });
890+
const rows = yield* authSessions.listActive({
891+
now,
892+
connectedSessionIds: Array.from(connectedSessions.keys()),
893+
});
886894

887895
return rows.map((row) =>
888896
toAuthClientSession({

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;
6969

7070
export const ListActiveAuthSessionsInput = Schema.Struct({
7171
now: Schema.DateTimeUtcFromString,
72+
connectedSessionIds: Schema.optionalKey(Schema.Array(AuthSessionId)),
7273
});
7374
export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;
7475

@@ -282,7 +283,7 @@ export const make = Effect.gen(function* () {
282283
const listActiveSessionRows = SqlSchema.findAll({
283284
Request: ListActiveAuthSessionsInput,
284285
Result: AuthSessionRawDbRow,
285-
execute: ({ now }) =>
286+
execute: ({ now, connectedSessionIds = [] }) =>
286287
sql`
287288
SELECT
288289
session_id AS "sessionId",
@@ -301,7 +302,7 @@ export const make = Effect.gen(function* () {
301302
revoked_at AS "revokedAt"
302303
FROM auth_sessions
303304
WHERE revoked_at IS NULL
304-
AND expires_at > ${now}
305+
AND (expires_at > ${now} OR ${sql.in("session_id", connectedSessionIds)})
305306
ORDER BY issued_at DESC, session_id DESC
306307
`,
307308
});

‎apps/web/src/connection/platform.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,9 @@ const capabilitiesLayer = Layer.effectContext(
182182
scopes: AuthStandardClientScopes,
183183
});
184184
const cloudSession = CloudSession.of({
185+
identity: Effect.sync(() =>
186+
Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)),
187+
),
185188
clerkToken: Effect.gen(function* () {
186189
const session = appAtomRegistry.get(managedRelaySessionAtom);
187190
if (session === null) {

‎apps/web/src/connection/runtime.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@ type ConnectionLayerSource =
3030
| typeof backgroundActivityObserverLayer
3131
| typeof backgroundActivityReporterLayer;
3232

33-
const providedClientConnectionLayer = Layer.merge(
34-
Connection.layerWithOptions({ environmentThemes: true, usageLimitSources: true }),
35-
snapshotLoaderLayer,
36-
).pipe(
33+
const providedClientConnectionLayer = snapshotLoaderLayer.pipe(
34+
Layer.provideMerge(
35+
Connection.layerWithOptions({ environmentThemes: true, usageLimitSources: true }),
36+
),
3737
Layer.provideMerge(
3838
Layer.mergeAll(
3939
runtimeContextLayer,

‎apps/web/src/connection/storage.ts‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
ConnectionTargetStore,
77
EMPTY_CONNECTION_CATALOG_DOCUMENT,
88
EnvironmentCacheStore,
9+
putRemoteDpopTokenInCatalog,
910
registerConnectionInCatalog,
1011
removeCatalogValue,
1112
removeConnectionFromCatalog,
@@ -446,15 +447,7 @@ export const connectionStorageLayer = Layer.effectContext(
446447
),
447448
),
448449
),
449-
put: (token) =>
450-
catalog.update((document) => ({
451-
...document,
452-
remoteDpopTokens: replaceCatalogValue(
453-
document.remoteDpopTokens,
454-
(value) => value.environmentId,
455-
token,
456-
),
457-
})),
450+
put: (token) => catalog.update((document) => putRemoteDpopTokenInCatalog(document, token)),
458451
remove: (environmentId) =>
459452
catalog.update((document) => ({
460453
...document,

‎docs/internals/connection-runtime.md‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ signals, and application lifecycle events. React views consume the runtime.
66
Keeping retries and session lifetime here prevents competing reconnect loops when
77
several views need the same environment.
88

9-
## One retry owner
9+
## One transport retry owner
1010

1111
The [supervisor](../../packages/client-runtime/src/connection/supervisor.ts) owns
12-
retry policy; resolving an endpoint and opening an RPC session are single
12+
transport retry policy; resolving an endpoint and opening an RPC session are single
1313
attempts. Transient failures retry with capped backoff. Offline states and
1414
authentication failures wait for a wakeup instead of spending attempts on
1515
unchanged conditions.
@@ -27,6 +27,20 @@ and cached data. Explicit removal closes the scope and clears credentials,
2727
projections, and platform-owned state such as drafts. Cloud-account changes apply
2828
to relay registrations; they must not discard directly paired environments.
2929

30+
## HTTP authorization
31+
32+
RPC sessions authenticate at socket upgrade, while HTTP requests need current
33+
credentials from the
34+
[authorization service](../../packages/client-runtime/src/authorization/service.ts).
35+
Replacing a healthy socket for HTTP renewal would interrupt conversations and
36+
change the transport generation without a transport failure. Credential expiry
37+
does not close the socket, and refresh failure belongs to the HTTP operation.
38+
39+
Session listings must retain unrevoked connected sessions after credential expiry
40+
so an open connection does not disappear from connection management. This does
41+
not extend the credential's lifetime. New HTTP requests and socket upgrades still
42+
require valid credentials.
43+
3044
## Transport health and data freshness are separate
3145

3246
A socket opening is insufficient evidence that the environment is usable. The

0 commit comments

Comments
 (0)