Open History to see the last commit
1import {
2 type AuthBearerBootstrapResult,
3 type AuthClientSession,
4 type AuthBootstrapResult,
5 type AuthPairingCredentialResult,
6 type AuthSessionState,
7 type AuthWebSocketTokenResult,
8} from "@t3tools/contracts";
9import { DateTime, Effect, Layer, Option } from "effect";
10import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
11
12import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
13import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts";
14import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts";
15import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts";
16import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts";
17import {
18 ServerAuth,
19 type AuthenticatedSession,
20 AuthError,
21 type ServerAuthShape,
22} from "../Services/ServerAuth.ts";
23import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
24import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
25
26type BootstrapExchangeResult = {
27 readonly response: AuthBootstrapResult;
28 readonly sessionToken: string;
29};
30
31const AUTHORIZATION_PREFIX = "Bearer ";
32const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken";
33
34export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError {
35 if (cause.status === 500) {
36 return new AuthError({
37 message: "Failed to validate bootstrap credential.",
38 status: 500,
39 cause,
40 });
41 }
42
43 return new AuthError({
44 message: "Invalid bootstrap credential.",
45 status: 401,
46 cause,
47 });
48}
49
50function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
51 const header = request.headers["authorization"];
52 if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
53 return null;
54 }
55 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
56 return token.length > 0 ? token : null;
57}
58
59export const makeServerAuth = Effect.gen(function* () {
60 const policy = yield* ServerAuthPolicy;
61 const bootstrapCredentials = yield* BootstrapCredentialService;
62 const authControlPlane = yield* AuthControlPlane;
63 const sessions = yield* SessionCredentialService;
64 const descriptor = yield* policy.getDescriptor();
65
66 const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
67 sessions.verify(token).pipe(
68 Effect.map((session) => ({
69 sessionId: session.sessionId,
70 subject: session.subject,
71 method: session.method,
72 role: session.role,
73 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
74 })),
75 Effect.mapError(
76 (cause) =>
77 new AuthError({
78 message: "Unauthorized request.",
79 status: 401,
80 cause,
81 }),
82 ),
83 );
84
85 const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => {
86 const cookieToken = request.cookies[sessions.cookieName];
87 const bearerToken = parseBearerToken(request);
88 const credential = cookieToken ?? bearerToken;
89 if (!credential) {
90 return Effect.fail(
91 new AuthError({
92 message: "Authentication required.",
93 status: 401,
94 }),
95 );
96 }
97 return authenticateToken(credential);
98 };
99
100 const getSessionState: ServerAuthShape["getSessionState"] = (request) =>
101 authenticateRequest(request).pipe(
102 Effect.map(
103 (session) =>
104 ({
105 authenticated: true,
106 auth: descriptor,
107 role: session.role,
108 sessionMethod: session.method,
109 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
110 }) satisfies AuthSessionState,
111 ),
112 Effect.catchTag("AuthError", () =>
113 Effect.succeed({
114 authenticated: false,
115 auth: descriptor,
116 } satisfies AuthSessionState),
117 ),
118 );
119
120 const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = (
121 credential,
122 requestMetadata,
123 ) =>
124 bootstrapCredentials.consume(credential).pipe(
125 Effect.mapError(toBootstrapExchangeAuthError),
126 Effect.flatMap((grant) =>
127 sessions
128 .issue({
129 method: "browser-session-cookie",
130 subject: grant.subject,
131 role: grant.role,
132 client: {
133 ...requestMetadata,
134 ...(grant.label ? { label: grant.label } : {}),
135 },
136 })
137 .pipe(
138 Effect.mapError(
139 (cause) =>
140 new AuthError({
141 message: "Failed to issue authenticated session.",
142 cause,
143 }),
144 ),
145 ),
146 ),
147 Effect.map(
148 (session) =>
149 ({
150 response: {
151 authenticated: true,
152 role: session.role,
153 sessionMethod: session.method,
154 expiresAt: DateTime.toUtc(session.expiresAt),
155 } satisfies AuthBootstrapResult,
156 sessionToken: session.token,
157 }) satisfies BootstrapExchangeResult,
158 ),
159 );
160
161 const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] =
162 (credential, requestMetadata) =>
163 bootstrapCredentials.consume(credential).pipe(
164 Effect.mapError(toBootstrapExchangeAuthError),
165 Effect.flatMap((grant) =>
166 sessions
167 .issue({
168 method: "bearer-session-token",
169 subject: grant.subject,
170 role: grant.role,
171 client: {
172 ...requestMetadata,
173 ...(grant.label ? { label: grant.label } : {}),
174 },
175 })
176 .pipe(
177 Effect.mapError(
178 (cause) =>
179 new AuthError({
180 message: "Failed to issue authenticated session.",
181 cause,
182 }),
183 ),
184 ),
185 ),
186 Effect.map(
187 (session) =>
188 ({
189 authenticated: true,
190 role: session.role,
191 sessionMethod: "bearer-session-token",
192 expiresAt: DateTime.toUtc(session.expiresAt),
193 sessionToken: session.token,
194 }) satisfies AuthBearerBootstrapResult,
195 ),
196 );
197
198 const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) =>
199 authControlPlane
200 .createPairingLink({
201 role: input?.role ?? "client",
202 subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token",
203 ...(input?.label ? { label: input.label } : {}),
204 })
205 .pipe(
206 Effect.mapError(
207 (cause) =>
208 new AuthError({
209 message: "Failed to issue pairing credential.",
210 cause,
211 }),
212 ),
213 Effect.map(
214 (issued) =>
215 ({
216 id: issued.id,
217 credential: issued.credential,
218 ...(issued.label ? { label: issued.label } : {}),
219 expiresAt: issued.expiresAt,
220 }) satisfies AuthPairingCredentialResult,
221 ),
222 );
223
224 const listPairingLinks: ServerAuthShape["listPairingLinks"] = () =>
225 authControlPlane
226 .listPairingLinks({
227 role: "client",
228 excludeSubjects: ["owner-bootstrap"],
229 })
230 .pipe(
231 Effect.mapError(
232 (cause) =>
233 new AuthError({
234 message: "Failed to load pairing links.",
235 cause,
236 }),
237 ),
238 );
239
240 const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) =>
241 authControlPlane.revokePairingLink(id).pipe(
242 Effect.mapError(
243 (cause) =>
244 new AuthError({
245 message: "Failed to revoke pairing link.",
246 cause,
247 }),
248 ),
249 );
250
251 const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) =>
252 authControlPlane.listSessions().pipe(
253 Effect.mapError(
254 (cause) =>
255 new AuthError({
256 message: "Failed to load paired clients.",
257 cause,
258 }),
259 ),
260 Effect.map((clientSessions) =>
261 clientSessions.map(
262 (clientSession): AuthClientSession => ({
263 ...clientSession,
264 current: clientSession.sessionId === currentSessionId,
265 }),
266 ),
267 ),
268 );
269
270 const revokeClientSession: ServerAuthShape["revokeClientSession"] = (
271 currentSessionId,
272 targetSessionId,
273 ) =>
274 Effect.gen(function* () {
275 if (currentSessionId === targetSessionId) {
276 return yield* new AuthError({
277 message: "Use revoke other clients to keep the current owner session active.",
278 status: 403,
279 });
280 }
281 return yield* authControlPlane.revokeSession(targetSessionId).pipe(
282 Effect.mapError(
283 (cause) =>
284 new AuthError({
285 message: "Failed to revoke client session.",
286 cause,
287 }),
288 ),
289 );
290 });
291
292 const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = (
293 currentSessionId,
294 ) =>
295 authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe(
296 Effect.mapError(
297 (cause) =>
298 new AuthError({
299 message: "Failed to revoke other client sessions.",
300 cause,
301 }),
302 ),
303 );
304
305 const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) =>
306 issuePairingCredential({ role: "owner" }).pipe(
307 Effect.map((issued) => {
308 const url = new URL(baseUrl);
309 url.pathname = "/pair";
310 url.searchParams.delete("token");
311 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
312 return url.toString();
313 }),
314 );
315
316 const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) =>
317 sessions.issueWebSocketToken(session.sessionId).pipe(
318 Effect.mapError(
319 (cause) =>
320 new AuthError({
321 message: "Failed to issue websocket token.",
322 cause,
323 }),
324 ),
325 Effect.map(
326 (issued) =>
327 ({
328 token: issued.token,
329 expiresAt: DateTime.toUtc(issued.expiresAt),
330 }) satisfies AuthWebSocketTokenResult,
331 ),
332 );
333
334 const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) =>
335 Effect.gen(function* () {
336 const requestUrl = HttpServerRequest.toURL(request);
337 if (Option.isSome(requestUrl)) {
338 const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM);
339 if (websocketToken && websocketToken.trim().length > 0) {
340 return yield* sessions.verifyWebSocketToken(websocketToken).pipe(
341 Effect.map((session) => ({
342 sessionId: session.sessionId,
343 subject: session.subject,
344 method: session.method,
345 role: session.role,
346 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
347 })),
348 Effect.mapError(
349 (cause) =>
350 new AuthError({
351 message: "Unauthorized request.",
352 status: 401,
353 cause,
354 }),
355 ),
356 );
357 }
358 }
359
360 return yield* authenticateRequest(request);
361 });
362
363 return {
364 getDescriptor: () => Effect.succeed(descriptor),
365 getSessionState,
366 exchangeBootstrapCredential,
367 exchangeBootstrapCredentialForBearerSession,
368 issuePairingCredential,
369 listPairingLinks,
370 revokePairingLink,
371 listClientSessions,
372 revokeClientSession,
373 revokeOtherClientSessions,
374 authenticateHttpRequest: authenticateRequest,
375 authenticateWebSocketUpgrade,
376 issueWebSocketToken,
377 issueStartupPairingUrl,
378 } satisfies ServerAuthShape;
379});
380
381export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe(
382 Layer.provideMerge(AuthControlPlaneLive),
383 Layer.provideMerge(AuthCoreLive),
384 Layer.provideMerge(ServerAuthPolicyLive),
385);