Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ServerAuth.ts

395 lines12.1 KB

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