Open History to see the last commit
1import {
2 AuthAdministrativeScopes,
3 AuthStandardClientScopes,
4 type AuthEnvironmentScope,
5 type AuthPairingLink,
6 type ServerAuthBootstrapMethod,
7} from "@t3tools/contracts";
8import * as Context from "effect/Context";
9import * as Crypto from "effect/Crypto";
10import * as DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as PubSub from "effect/PubSub";
16import * as Ref from "effect/Ref";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19
20import * as ServerConfig from "../config.ts";
21import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
22
23export interface BootstrapGrant {
24 readonly method: ServerAuthBootstrapMethod;
25 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
26 readonly subject: string;
27 readonly label?: string;
28 readonly proofKeyThumbprint?: string;
29 readonly expiresAt: DateTime.DateTime;
30}
31
32export class UnknownBootstrapCredentialError extends Schema.TaggedErrorClass<UnknownBootstrapCredentialError>()(
33 "UnknownBootstrapCredentialError",
34 {},
35) {
36 override get message(): string {
37 return "Unknown bootstrap credential.";
38 }
39}
40
41export class ExpiredBootstrapCredentialError extends Schema.TaggedErrorClass<ExpiredBootstrapCredentialError>()(
42 "ExpiredBootstrapCredentialError",
43 {},
44) {
45 override get message(): string {
46 return "Bootstrap credential expired.";
47 }
48}
49
50export class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedErrorClass<BootstrapCredentialProofKeyMismatchError>()(
51 "BootstrapCredentialProofKeyMismatchError",
52 {},
53) {
54 override get message(): string {
55 return "Bootstrap credential proof key mismatch.";
56 }
57}
58
59export class UnavailableBootstrapCredentialError extends Schema.TaggedErrorClass<UnavailableBootstrapCredentialError>()(
60 "UnavailableBootstrapCredentialError",
61 {},
62) {
63 override get message(): string {
64 return "Bootstrap credential is no longer available.";
65 }
66}
67
68export const BootstrapCredentialInvalidError = Schema.Union([
69 UnknownBootstrapCredentialError,
70 ExpiredBootstrapCredentialError,
71 BootstrapCredentialProofKeyMismatchError,
72 UnavailableBootstrapCredentialError,
73]);
74export type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;
75export const isBootstrapCredentialInvalidError = Schema.is(BootstrapCredentialInvalidError);
76
77export class ActivePairingLinksLoadError extends Schema.TaggedErrorClass<ActivePairingLinksLoadError>()(
78 "ActivePairingLinksLoadError",
79 {
80 cause: Schema.Defect(),
81 },
82) {
83 override get message(): string {
84 return "Failed to load active pairing links.";
85 }
86}
87
88export class PairingLinkRevokeError extends Schema.TaggedErrorClass<PairingLinkRevokeError>()(
89 "PairingLinkRevokeError",
90 {
91 pairingLinkId: Schema.String,
92 cause: Schema.Defect(),
93 },
94) {
95 override get message(): string {
96 return `Failed to revoke pairing link '${this.pairingLinkId}'.`;
97 }
98}
99
100export class PairingCredentialIssueError extends Schema.TaggedErrorClass<PairingCredentialIssueError>()(
101 "PairingCredentialIssueError",
102 {
103 pairingLinkId: Schema.String,
104 subject: Schema.String,
105 label: Schema.optional(Schema.String),
106 cause: Schema.Defect(),
107 },
108) {
109 override get message(): string {
110 return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;
111 }
112}
113
114export class PairingCredentialRandomGenerationError extends Schema.TaggedErrorClass<PairingCredentialRandomGenerationError>()(
115 "PairingCredentialRandomGenerationError",
116 {
117 operation: Schema.Literals(["generate-id", "generate-token"]),
118 cause: Schema.Defect(),
119 },
120) {
121 override get message(): string {
122 return `Failed to generate pairing credential data during '${this.operation}'.`;
123 }
124}
125
126export class BootstrapCredentialConsumeError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeError>()(
127 "BootstrapCredentialConsumeError",
128 {
129 cause: Schema.Defect(),
130 },
131) {
132 override get message(): string {
133 return "Failed to consume bootstrap credential.";
134 }
135}
136
137export class BootstrapCredentialConsumeAvailableError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeAvailableError>()(
138 "BootstrapCredentialConsumeAvailableError",
139 {
140 cause: Schema.Defect(),
141 },
142) {
143 override get message(): string {
144 return "Failed to atomically consume an available bootstrap credential.";
145 }
146}
147
148export class BootstrapCredentialLookupError extends Schema.TaggedErrorClass<BootstrapCredentialLookupError>()(
149 "BootstrapCredentialLookupError",
150 {
151 cause: Schema.Defect(),
152 },
153) {
154 override get message(): string {
155 return "Failed to look up bootstrap credential state.";
156 }
157}
158
159export const BootstrapCredentialInternalError = Schema.Union([
160 ActivePairingLinksLoadError,
161 PairingLinkRevokeError,
162 PairingCredentialIssueError,
163 PairingCredentialRandomGenerationError,
164 BootstrapCredentialConsumeError,
165 BootstrapCredentialConsumeAvailableError,
166 BootstrapCredentialLookupError,
167]);
168export type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;
169export const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);
170
171export const BootstrapCredentialError = Schema.Union([
172 BootstrapCredentialInvalidError,
173 BootstrapCredentialInternalError,
174]);
175export type BootstrapCredentialError = typeof BootstrapCredentialError.Type;
176export const isBootstrapCredentialError = Schema.is(BootstrapCredentialError);
177
178export interface IssuedBootstrapCredential {
179 readonly id: string;
180 readonly credential: string;
181 readonly label?: string;
182 readonly proofKeyThumbprint?: string;
183 readonly expiresAt: DateTime.Utc;
184}
185
186export type BootstrapCredentialChange =
187 | {
188 readonly type: "pairingLinkUpserted";
189 readonly pairingLink: AuthPairingLink;
190 }
191 | {
192 readonly type: "pairingLinkRemoved";
193 readonly id: string;
194 };
195
196export class PairingGrantStore extends Context.Service<
197 PairingGrantStore,
198 {
199 readonly issueOneTimeToken: (input?: {
200 readonly ttl?: Duration.Duration;
201 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
202 readonly subject?: string;
203 readonly label?: string;
204 readonly proofKeyThumbprint?: string;
205 }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;
206 readonly listActive: () => Effect.Effect<
207 ReadonlyArray<AuthPairingLink>,
208 BootstrapCredentialInternalError
209 >;
210 readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;
211 readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;
212 readonly consume: (
213 credential: string,
214 input?: {
215 readonly proofKeyThumbprint?: string;
216 },
217 ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
218 }
219>()("t3/auth/PairingGrantStore") {}
220
221interface StoredBootstrapGrant extends BootstrapGrant {
222 readonly remainingUses: number | "unbounded";
223}
224
225type ConsumeResult =
226 | {
227 readonly _tag: "error";
228 readonly reason: "not-found" | "expired";
229 readonly error: BootstrapCredentialError;
230 }
231 | {
232 readonly _tag: "success";
233 readonly grant: BootstrapGrant;
234 };
235
236const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
237const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
238const PAIRING_TOKEN_LENGTH = 12;
239const PAIRING_TOKEN_REJECTION_LIMIT =
240 Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;
241
242export const make = Effect.gen(function* () {
243 const crypto = yield* Crypto.Crypto;
244 const config = yield* ServerConfig.ServerConfig;
245 const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;
246 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
247 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
248 const generatePairingToken = Effect.gen(function* () {
249 let credential = "";
250 while (credential.length < PAIRING_TOKEN_LENGTH) {
251 const bytes = yield* crypto
252 .randomBytes(PAIRING_TOKEN_LENGTH)
253 .pipe(
254 Effect.mapError(
255 (cause) =>
256 new PairingCredentialRandomGenerationError({ operation: "generate-token", cause }),
257 ),
258 );
259 for (const byte of bytes) {
260 if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {
261 continue;
262 }
263 credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;
264 if (credential.length === PAIRING_TOKEN_LENGTH) {
265 return credential;
266 }
267 }
268 }
269 return credential;
270 });
271
272 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
273 Ref.update(seededGrantsRef, (current) => {
274 const next = new Map(current);
275 next.set(credential, grant);
276 return next;
277 });
278
279 const emitUpsert = (pairingLink: AuthPairingLink) =>
280 PubSub.publish(changesPubSub, {
281 type: "pairingLinkUpserted",
282 pairingLink,
283 }).pipe(Effect.asVoid);
284
285 const emitRemoved = (id: string) =>
286 PubSub.publish(changesPubSub, {
287 type: "pairingLinkRemoved",
288 id,
289 }).pipe(Effect.asVoid);
290
291 if (config.desktopBootstrapToken) {
292 const now = yield* DateTime.now;
293 yield* seedGrant(config.desktopBootstrapToken, {
294 method: "desktop-bootstrap",
295 scopes: AuthAdministrativeScopes,
296 subject: "desktop-bootstrap",
297 expiresAt: DateTime.add(now, {
298 milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
299 }),
300 remainingUses: 1,
301 });
302 }
303
304 const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
305 "PairingGrantStore.listActive",
306 )(
307 function* () {
308 const now = yield* DateTime.now;
309 const rows = yield* pairingLinks.listActive({ now });
310
311 return rows.map((row) =>
312 row.label
313 ? ({
314 id: row.id,
315 credential: row.credential,
316 scopes: row.scopes,
317 subject: row.subject,
318 label: row.label,
319 createdAt: row.createdAt,
320 expiresAt: row.expiresAt,
321 } satisfies AuthPairingLink)
322 : ({
323 id: row.id,
324 credential: row.credential,
325 scopes: row.scopes,
326 subject: row.subject,
327 createdAt: row.createdAt,
328 expiresAt: row.expiresAt,
329 } satisfies AuthPairingLink),
330 );
331 },
332 Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),
333 );
334
335 const revoke: PairingGrantStore["Service"]["revoke"] = Effect.fn("PairingGrantStore.revoke")(
336 function* (id) {
337 const revokedAt = yield* DateTime.now;
338 const revoked = yield* pairingLinks
339 .revoke({
340 id,
341 revokedAt,
342 })
343 .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));
344 if (revoked) {
345 yield* emitRemoved(id);
346 }
347 return revoked;
348 },
349 );
350
351 const issueOneTimeToken: PairingGrantStore["Service"]["issueOneTimeToken"] = Effect.fn(
352 "PairingGrantStore.issueOneTimeToken",
353 )(function* (input) {
354 const id = yield* crypto.randomUUIDv4.pipe(
355 Effect.mapError(
356 (cause) => new PairingCredentialRandomGenerationError({ operation: "generate-id", cause }),
357 ),
358 );
359 const credential = yield* generatePairingToken;
360 const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
361 const now = yield* DateTime.now;
362 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
363 const issued: IssuedBootstrapCredential = {
364 id,
365 credential,
366 ...(input?.label ? { label: input.label } : {}),
367 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
368 expiresAt,
369 };
370 const subject = input?.subject ?? "one-time-token";
371 yield* pairingLinks
372 .create({
373 id,
374 credential,
375 method: "one-time-token",
376 scopes: input?.scopes ?? AuthStandardClientScopes,
377 subject,
378 label: input?.label ?? null,
379 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
380 createdAt: now,
381 expiresAt: expiresAt,
382 })
383 .pipe(
384 Effect.mapError(
385 (cause) =>
386 new PairingCredentialIssueError({
387 pairingLinkId: id,
388 subject,
389 ...(input?.label ? { label: input.label } : {}),
390 cause,
391 }),
392 ),
393 );
394 yield* emitUpsert({
395 id,
396 credential,
397 scopes: input?.scopes ?? AuthStandardClientScopes,
398 subject: input?.subject ?? "one-time-token",
399 ...(input?.label ? { label: input.label } : {}),
400 createdAt: now,
401 expiresAt,
402 });
403 return issued;
404 });
405
406 const consume: PairingGrantStore["Service"]["consume"] = Effect.fn("PairingGrantStore.consume")(
407 function* (credential, input) {
408 const now = yield* DateTime.now;
409 const seededResult: ConsumeResult = yield* Ref.modify(
410 seededGrantsRef,
411 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
412 const grant = current.get(credential);
413 if (!grant) {
414 return [
415 {
416 _tag: "error",
417 reason: "not-found",
418 error: new UnknownBootstrapCredentialError({}),
419 },
420 current,
421 ];
422 }
423
424 const next = new Map(current);
425 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
426 next.delete(credential);
427 return [
428 {
429 _tag: "error",
430 reason: "expired",
431 error: new ExpiredBootstrapCredentialError({}),
432 },
433 next,
434 ];
435 }
436
437 if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {
438 return [
439 {
440 _tag: "error",
441 reason: "not-found",
442 error: new BootstrapCredentialProofKeyMismatchError({}),
443 },
444 next,
445 ];
446 }
447
448 const remainingUses = grant.remainingUses;
449 if (typeof remainingUses === "number") {
450 if (remainingUses <= 1) {
451 next.delete(credential);
452 } else {
453 next.set(credential, {
454 ...grant,
455 remainingUses: remainingUses - 1,
456 });
457 }
458 }
459
460 return [
461 {
462 _tag: "success",
463 grant: {
464 method: grant.method,
465 scopes: grant.scopes,
466 subject: grant.subject,
467 ...(grant.label ? { label: grant.label } : {}),
468 ...(grant.proofKeyThumbprint
469 ? { proofKeyThumbprint: grant.proofKeyThumbprint }
470 : {}),
471 expiresAt: grant.expiresAt,
472 } satisfies BootstrapGrant,
473 },
474 next,
475 ];
476 },
477 );
478
479 if (seededResult._tag === "success") {
480 return seededResult.grant;
481 }
482 if (seededResult.reason !== "not-found") {
483 return yield* seededResult.error;
484 }
485
486 const consumed = yield* pairingLinks
487 .consumeAvailable({
488 credential,
489 proofKeyThumbprint: input?.proofKeyThumbprint ?? null,
490 consumedAt: now,
491 now,
492 })
493 .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));
494
495 if (Option.isSome(consumed)) {
496 yield* emitRemoved(consumed.value.id);
497 return {
498 method: consumed.value.method,
499 scopes: consumed.value.scopes,
500 subject: consumed.value.subject,
501 ...(consumed.value.label ? { label: consumed.value.label } : {}),
502 ...(consumed.value.proofKeyThumbprint
503 ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }
504 : {}),
505 expiresAt: consumed.value.expiresAt,
506 } satisfies BootstrapGrant;
507 }
508
509 const matching = yield* pairingLinks
510 .getByCredential({ credential })
511 .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));
512 if (Option.isNone(matching)) {
513 return yield* new UnknownBootstrapCredentialError({});
514 }
515
516 if (matching.value.revokedAt !== null) {
517 return yield* new UnavailableBootstrapCredentialError({});
518 }
519
520 if (matching.value.consumedAt !== null) {
521 return yield* new UnknownBootstrapCredentialError({});
522 }
523
524 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
525 return yield* new ExpiredBootstrapCredentialError({});
526 }
527
528 if (
529 matching.value.proofKeyThumbprint !== null &&
530 matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint
531 ) {
532 return yield* new BootstrapCredentialProofKeyMismatchError({});
533 }
534
535 return yield* new UnavailableBootstrapCredentialError({});
536 },
537 );
538
539 return PairingGrantStore.of({
540 issueOneTimeToken,
541 listActive,
542 get streamChanges() {
543 return Stream.fromPubSub(changesPubSub);
544 },
545 revoke,
546 consume,
547 });
548});
549
550export const layer = Layer.effect(PairingGrantStore, make).pipe(
551 Layer.provideMerge(AuthPairingLinks.layer),
552);