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

ServerAuth.ts

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