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