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

BootstrapCredentialService.ts

296 lines9.4 KB

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