Skip to content

Commit 40a99a5

Browse files
saphidcodex
andcommitted
refactor(server): move auth access streaming into the auth service
Co-Authored-By: GPT-6.1 Sol <[email protected]>
1 parent d82e8f3 commit 40a99a5

3 files changed

Lines changed: 150 additions & 131 deletions

File tree

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

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
type AuthAccessStreamEvent,
23
AuthAccessTokenType,
34
AuthAccessWriteScope,
45
AuthAdministrativeScopes,
@@ -33,7 +34,10 @@ import * as Duration from "effect/Duration";
3334
import * as Effect from "effect/Effect";
3435
import * as Layer from "effect/Layer";
3536
import * as Option from "effect/Option";
37+
import * as Ref from "effect/Ref";
3638
import * as Schema from "effect/Schema";
39+
import * as Scope from "effect/Scope";
40+
import * as Stream from "effect/Stream";
3741
import * as HttpServerRequest from "effect/http/HttpServerRequest";
3842

3943
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
@@ -538,6 +542,15 @@ export class EnvironmentAuth extends Context.Service<
538542
readonly listClientSessions: (
539543
currentSessionId: AuthSessionId,
540544
) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
545+
/** Acquires both live subscriptions before reading the request's snapshot. */
546+
readonly streamAccess: (currentSessionId: AuthSessionId) => Effect.Effect<
547+
{
548+
readonly snapshot: Extract<AuthAccessStreamEvent, { readonly type: "snapshot" }>;
549+
readonly changes: Stream.Stream<AuthAccessStreamEvent>;
550+
},
551+
ServerAuthInternalError,
552+
Scope.Scope
553+
>;
541554
readonly revokeClientSession: (
542555
currentSessionId: AuthSessionId,
543556
targetSessionId: AuthSessionId,
@@ -586,6 +599,47 @@ export class EnvironmentAuth extends Context.Service<
586599
}
587600
>()("t3/auth/EnvironmentAuth") {}
588601

602+
function toAuthAccessStreamEvent(
603+
change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,
604+
revision: number,
605+
currentSessionId: AuthSessionId,
606+
): AuthAccessStreamEvent {
607+
switch (change.type) {
608+
case "pairingLinkUpserted":
609+
return {
610+
version: 1,
611+
revision,
612+
type: "pairingLinkUpserted",
613+
payload: { ...change.pairingLink, ...authScopeResponse(change.pairingLink.scopes) },
614+
};
615+
case "pairingLinkRemoved":
616+
return {
617+
version: 1,
618+
revision,
619+
type: "pairingLinkRemoved",
620+
payload: { id: change.id },
621+
};
622+
case "clientUpserted":
623+
return {
624+
version: 1,
625+
revision,
626+
type: "clientUpserted",
627+
payload: {
628+
...change.clientSession,
629+
...authScopeResponse(change.clientSession.scopes),
630+
current: change.clientSession.sessionId === currentSessionId,
631+
},
632+
};
633+
case "clientRemoved":
634+
return {
635+
version: 1,
636+
revision,
637+
type: "clientRemoved",
638+
payload: { sessionId: change.sessionId },
639+
};
640+
}
641+
}
642+
589643
type BootstrapExchangeResult = {
590644
readonly response: AuthBrowserSessionResult;
591645
readonly sessionToken: string;
@@ -1136,6 +1190,42 @@ export const make = Effect.gen(function* () {
11361190
Effect.withSpan("EnvironmentAuth.listClientSessions"),
11371191
);
11381192

1193+
const streamAccess: EnvironmentAuth["Service"]["streamAccess"] = Effect.fn(
1194+
"EnvironmentAuth.streamAccess",
1195+
)(function* (currentSessionId) {
1196+
// Buffer both stores before reading; consumers may hold the snapshot before
1197+
// starting the live tail (for example, while waiting for an RPC ACK).
1198+
const pairingLinkChanges = yield* bootstrapCredentials.subscribeChanges;
1199+
const clientChanges = yield* sessions.subscribeChanges;
1200+
const initialSnapshot = yield* Effect.all({
1201+
pairingLinks: listPairingLinks(),
1202+
clientSessions: listClientSessions(currentSessionId),
1203+
});
1204+
const revisionRef = yield* Ref.make(1);
1205+
const accessChanges: Stream.Stream<
1206+
PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange
1207+
> = Stream.merge(
1208+
Stream.fromSubscription(pairingLinkChanges),
1209+
Stream.fromSubscription(clientChanges),
1210+
);
1211+
const changes = accessChanges.pipe(
1212+
Stream.mapEffect((change) =>
1213+
Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(
1214+
Effect.map((revision) => toAuthAccessStreamEvent(change, revision, currentSessionId)),
1215+
),
1216+
),
1217+
);
1218+
return {
1219+
snapshot: {
1220+
version: 1 as const,
1221+
revision: 1,
1222+
type: "snapshot" as const,
1223+
payload: initialSnapshot,
1224+
},
1225+
changes,
1226+
};
1227+
});
1228+
11391229
const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
11401230
"EnvironmentAuth.revokeClientSession",
11411231
)(function* (currentSessionId, targetSessionId) {
@@ -1300,6 +1390,7 @@ export const make = Effect.gen(function* () {
13001390
revokeSession,
13011391
revokeOtherSessionsExcept,
13021392
listClientSessions,
1393+
streamAccess,
13031394
revokeClientSession,
13041395
revokeOtherClientSessions,
13051396
authenticateHttpRequest,

‎apps/server/src/ws.authAccess.test.ts‎

Lines changed: 51 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
2626
import * as ServerConfig from "./config.ts";
2727
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
2828
import * as SqlitePersistence from "./persistence/Sqlite.ts";
29-
import { subscribeAuthAccess, WS_RPC_SERVER_OPTIONS } from "./ws.ts";
29+
import { rpcInitialItems } from "./rpcInitialItems.ts";
30+
import { WS_RPC_SERVER_OPTIONS } from "./ws.ts";
3031

3132
const group = WsRpcGroup.omit(
3233
...[...WsRpcGroup.requests.keys()].filter(
@@ -41,7 +42,9 @@ const layerAuth = EnvironmentAuth.layer.pipe(
4142
Layer.provideMerge(ServerSecretStore.layer),
4243
Layer.provideMerge(SqlitePersistence.layerMemory),
4344
Layer.provide(ServerEnvironment.layerIdentity),
44-
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-access-stream-test-" })),
45+
Layer.provideMerge(
46+
ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-access-stream-test-" }),
47+
),
4548
);
4649

4750
const makeProtocol = Effect.gen(function* () {
@@ -115,18 +118,25 @@ it.layer(NodeServices.layer)("subscribeAuthAccess snapshot handoff", (it) => {
115118
const snapshotRead = yield* Deferred.make<void>();
116119
const releaseSnapshot = yield* Deferred.make<void>();
117120
const { responses, receive, protocol } = yield* makeProtocol;
118-
const snapshotAuth = EnvironmentAuth.EnvironmentAuth.of({
119-
...auth,
120-
listClientSessions: (sessionId) =>
121-
auth.listClientSessions(sessionId).pipe(
122-
Effect.tap(() => Deferred.succeed(snapshotRead, undefined)),
123-
Effect.flatMap((snapshot) => Deferred.await(releaseSnapshot).pipe(Effect.as(snapshot))),
124-
),
125-
});
121+
const snapshotAuth = yield* EnvironmentAuth.make.pipe(
122+
Effect.provideService(SessionStore.SessionStore, {
123+
...sessions,
124+
listActive: () =>
125+
sessions.listActive().pipe(
126+
Effect.tap(() => Deferred.succeed(snapshotRead, undefined)),
127+
Effect.flatMap((snapshot) =>
128+
Deferred.await(releaseSnapshot).pipe(Effect.as(snapshot)),
129+
),
130+
),
131+
}),
132+
);
126133
const { write } = yield* startRpc(
127134
Stream.unwrap(
128-
subscribeAuthAccess(current.sessionId).pipe(
129-
Effect.provideService(EnvironmentAuth.EnvironmentAuth, snapshotAuth),
135+
snapshotAuth.streamAccess(current.sessionId).pipe(
136+
Effect.map(({ snapshot, changes }) =>
137+
Stream.concat(rpcInitialItems([snapshot]), changes),
138+
),
139+
Effect.mapError((error) => new AuthAccessStreamError({ message: error.message })),
130140
),
131141
),
132142
{ responses, receive, protocol },
@@ -212,48 +222,47 @@ it.layer(NodeServices.layer)("subscribeAuthAccess snapshot handoff", (it) => {
212222
"releases both subscriptions on cancellation or failure during %s",
213223
(milestone) =>
214224
Effect.gen(function* () {
215-
const auth = yield* EnvironmentAuth.EnvironmentAuth;
216225
const pairingLinks = yield* PairingGrantStore.PairingGrantStore;
217226
const sessions = yield* SessionStore.SessionStore;
218227
const current = yield* sessions.issue({ subject: "current-client" });
219228
const acquired = yield* Queue.unbounded<PubSub.Subscription<unknown>>();
220229
const snapshotRead = yield* Deferred.make<void>();
221230
const releaseSnapshot = yield* Deferred.make<void>();
222-
const snapshotAuth = EnvironmentAuth.EnvironmentAuth.of({
223-
...auth,
224-
listClientSessions: (sessionId) =>
225-
auth.listClientSessions(sessionId).pipe(
226-
Effect.tap(() => Deferred.succeed(snapshotRead, undefined)),
227-
Effect.flatMap((snapshot) =>
228-
Deferred.await(releaseSnapshot).pipe(
229-
Effect.andThen(
230-
milestone === "snapshot failure"
231-
? Effect.fail(
232-
new EnvironmentAuth.ServerAuthSessionsListError({ cause: "test" }),
233-
)
234-
: Effect.succeed(snapshot),
231+
const snapshotAuth = yield* EnvironmentAuth.make.pipe(
232+
Effect.provideService(PairingGrantStore.PairingGrantStore, {
233+
...pairingLinks,
234+
subscribeChanges: pairingLinks.subscribeChanges.pipe(
235+
Effect.tap((subscription) => Queue.offer(acquired, subscription)),
236+
),
237+
}),
238+
Effect.provideService(SessionStore.SessionStore, {
239+
...sessions,
240+
subscribeChanges: sessions.subscribeChanges.pipe(
241+
Effect.tap((subscription) => Queue.offer(acquired, subscription)),
242+
),
243+
listActive: () =>
244+
sessions.listActive().pipe(
245+
Effect.tap(() => Deferred.succeed(snapshotRead, undefined)),
246+
Effect.flatMap((snapshot) =>
247+
Deferred.await(releaseSnapshot).pipe(
248+
Effect.andThen(
249+
milestone === "snapshot failure"
250+
? Effect.fail(new SessionStore.ActiveSessionsListError({ cause: "test" }))
251+
: Effect.succeed(snapshot),
252+
),
235253
),
236254
),
237255
),
238-
),
239-
});
256+
}),
257+
);
240258
const { responses, receive, protocol } = yield* makeProtocol;
241259
const { write } = yield* startRpc(
242260
Stream.unwrap(
243-
subscribeAuthAccess(current.sessionId).pipe(
244-
Effect.provideService(EnvironmentAuth.EnvironmentAuth, snapshotAuth),
245-
Effect.provideService(PairingGrantStore.PairingGrantStore, {
246-
...pairingLinks,
247-
subscribeChanges: pairingLinks.subscribeChanges.pipe(
248-
Effect.tap((subscription) => Queue.offer(acquired, subscription)),
249-
),
250-
}),
251-
Effect.provideService(SessionStore.SessionStore, {
252-
...sessions,
253-
subscribeChanges: sessions.subscribeChanges.pipe(
254-
Effect.tap((subscription) => Queue.offer(acquired, subscription)),
255-
),
256-
}),
261+
snapshotAuth.streamAccess(current.sessionId).pipe(
262+
Effect.map(({ snapshot, changes }) =>
263+
Stream.concat(rpcInitialItems([snapshot]), changes),
264+
),
265+
Effect.mapError((error) => new AuthAccessStreamError({ message: error.message })),
257266
),
258267
),
259268
{ responses, receive, protocol },

0 commit comments

Comments
 (0)