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

BootstrapCredentialService.ts

304 lines9.7 KB

1import type { AuthPairingLink } from "@t3tools/contracts";
2import * as Crypto from "effect/Crypto";
3import * as DateTime from "effect/DateTime";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as PubSub from "effect/PubSub";
8import * as Ref from "effect/Ref";
9import * as Stream from "effect/Stream";
10import * as Option from "effect/Option";
11​
12import { ServerConfig } from "../../config.ts";
13import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
14import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts";
15import {
16 BootstrapCredentialError,
17 BootstrapCredentialService,
18 type BootstrapCredentialChange,
19 type BootstrapCredentialServiceShape,
20 type BootstrapGrant,
21 type IssuedBootstrapCredential,
22} from "../Services/BootstrapCredentialService.ts";
23​
24interface StoredBootstrapGrant extends BootstrapGrant {
25 readonly remainingUses: number | "unbounded";
27​
28type ConsumeResult =
29 | {
30 readonly _tag: "error";
31 readonly reason: "not-found" | "expired";
32 readonly error: BootstrapCredentialError;
33 }
34 | {
35 readonly _tag: "success";
36 readonly grant: BootstrapGrant;
37 };
38​
39const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
40const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
41const PAIRING_TOKEN_LENGTH = 12;
42​
43const generatePairingToken = (): string => {
44 const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH));
45​
46 return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join("");
47};
48​
49export const makeBootstrapCredentialService = Effect.gen(function* () {
50 const crypto = yield* Crypto.Crypto;
51 const config = yield* ServerConfig;
52 const pairingLinks = yield* AuthPairingLinkRepository;
53 const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());
54 const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();
55​
56 const invalidBootstrapCredentialError = (message: string) =>
57 new BootstrapCredentialError({
58 message,
59 status: 401,
60 });
61​
62 const internalBootstrapCredentialError = (message: string, cause: unknown) =>
63 new BootstrapCredentialError({
64 message,
65 status: 500,
66 cause,
67 });
68​
69 const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>
70 Ref.update(seededGrantsRef, (current) => {
71 const next = new Map(current);
72 next.set(credential, grant);
73 return next;
74 });
75​
76 const emitUpsert = (pairingLink: AuthPairingLink) =>
77 PubSub.publish(changesPubSub, {
78 type: "pairingLinkUpserted",
79 pairingLink,
80 }).pipe(Effect.asVoid);
81​
82 const emitRemoved = (id: string) =>
83 PubSub.publish(changesPubSub, {
84 type: "pairingLinkRemoved",
85 id,
86 }).pipe(Effect.asVoid);
87​
88 if (config.desktopBootstrapToken) {
89 const now = yield* DateTime.now;
90 yield* seedGrant(config.desktopBootstrapToken, {
91 method: "desktop-bootstrap",
92 role: "owner",
93 subject: "desktop-bootstrap",
94 expiresAt: DateTime.add(now, {
95 milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES),
96 }),
97 remainingUses: 1,
98 });
99 }
100​
101 const toBootstrapCredentialError = (message: string) => (cause: unknown) =>
102 internalBootstrapCredentialError(message, cause);
103​
104 const listActive: BootstrapCredentialServiceShape["listActive"] = () =>
105 Effect.gen(function* () {
106 const now = yield* DateTime.now;
107 const rows = yield* pairingLinks.listActive({ now });
108​
109 return rows.map((row) =>
110 row.label
111 ? ({
112 id: row.id,
113 credential: row.credential,
114 role: row.role,
115 subject: row.subject,
116 label: row.label,
117 createdAt: row.createdAt,
118 expiresAt: row.expiresAt,
119 } satisfies AuthPairingLink)
120 : ({
121 id: row.id,
122 credential: row.credential,
123 role: row.role,
124 subject: row.subject,
125 createdAt: row.createdAt,
126 expiresAt: row.expiresAt,
127 } satisfies AuthPairingLink),
128 );
129 }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links.")));
130​
131 const revoke: BootstrapCredentialServiceShape["revoke"] = (id) =>
132 Effect.gen(function* () {
133 const revokedAt = yield* DateTime.now;
134 const revoked = yield* pairingLinks.revoke({
135 id,
136 revokedAt,
137 });
138 if (revoked) {
139 yield* emitRemoved(id);
140 }
141 return revoked;
142 }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link.")));
143​
144 const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) =>
145 Effect.gen(function* () {
146 const id = yield* crypto.randomUUIDv4;
147 const credential = generatePairingToken();
148 const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES;
149 const now = yield* DateTime.now;
150 const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });
151 const issued: IssuedBootstrapCredential = {
152 id,
153 credential,
154 ...(input?.label ? { label: input.label } : {}),
155 expiresAt,
156 };
157 yield* pairingLinks.create({
158 id,
159 credential,
160 method: "one-time-token",
161 role: input?.role ?? "client",
162 subject: input?.subject ?? "one-time-token",
163 label: input?.label ?? null,
164 createdAt: now,
165 expiresAt: expiresAt,
166 });
167 yield* emitUpsert({
168 id,
169 credential,
170 role: input?.role ?? "client",
171 subject: input?.subject ?? "one-time-token",
172 ...(input?.label ? { label: input.label } : {}),
173 createdAt: now,
174 expiresAt,
175 });
176 return issued;
177 }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential.")));
178​
179 const consume: BootstrapCredentialServiceShape["consume"] = (credential) =>
180 Effect.gen(function* () {
181 const now = yield* DateTime.now;
182 const seededResult: ConsumeResult = yield* Ref.modify(
183 seededGrantsRef,
184 (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {
185 const grant = current.get(credential);
186 if (!grant) {
187 return [
188 {
189 _tag: "error",
190 reason: "not-found",
191 error: invalidBootstrapCredentialError("Unknown bootstrap credential."),
192 },
193 current,
194 ];
195 }
196​
197 const next = new Map(current);
198 if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {
199 next.delete(credential);
200 return [
201 {
202 _tag: "error",
203 reason: "expired",
204 error: invalidBootstrapCredentialError("Bootstrap credential expired."),
205 },
206 next,
207 ];
208 }
209​
210 const remainingUses = grant.remainingUses;
211 if (typeof remainingUses === "number") {
212 if (remainingUses <= 1) {
213 next.delete(credential);
214 } else {
215 next.set(credential, {
216 ...grant,
217 remainingUses: remainingUses - 1,
218 });
219 }
220 }
221​
222 return [
223 {
224 _tag: "success",
225 grant: {
226 method: grant.method,
227 role: grant.role,
228 subject: grant.subject,
229 ...(grant.label ? { label: grant.label } : {}),
230 expiresAt: grant.expiresAt,
231 } satisfies BootstrapGrant,
232 },
233 next,
234 ];
235 },
236 );
237​
238 if (seededResult._tag === "success") {
239 return seededResult.grant;
240 }
241 if (seededResult.reason !== "not-found") {
242 return yield* seededResult.error;
243 }
244​
245 const consumed = yield* pairingLinks.consumeAvailable({
246 credential,
247 consumedAt: now,
248 now,
249 });
250​
251 if (Option.isSome(consumed)) {
252 yield* emitRemoved(consumed.value.id);
253 return {
254 method: consumed.value.method,
255 role: consumed.value.role,
256 subject: consumed.value.subject,
257 ...(consumed.value.label ? { label: consumed.value.label } : {}),
258 expiresAt: consumed.value.expiresAt,
259 } satisfies BootstrapGrant;
260 }
261​
262 const matching = yield* pairingLinks.getByCredential({ credential });
263 if (Option.isNone(matching)) {
264 return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
265 }
266​
267 if (matching.value.revokedAt !== null) {
268 return yield* invalidBootstrapCredentialError(
269 "Bootstrap credential is no longer available.",
270 );
271 }
272​
273 if (matching.value.consumedAt !== null) {
274 return yield* invalidBootstrapCredentialError("Unknown bootstrap credential.");
275 }
276​
277 if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {
278 return yield* invalidBootstrapCredentialError("Bootstrap credential expired.");
279 }
280​
281 return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available.");
282 }).pipe(
283 Effect.mapError((cause) =>
284 cause instanceof BootstrapCredentialError
285 ? cause
286 : internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause),
287 ),
288 );
289​
290 return {
291 issueOneTimeToken,
292 listActive,
293 get streamChanges() {
294 return Stream.fromPubSub(changesPubSub);
295 },
296 revoke,
297 consume,
298 } satisfies BootstrapCredentialServiceShape;
299});
300​
301export const BootstrapCredentialServiceLive = Layer.effect(
302 BootstrapCredentialService,
303 makeBootstrapCredentialService,
304).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive));