@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 405 lines 13.4 KB
Raw
1 /**
2 * The ACME issuance flow shared by the `Certificate` resource (deploy time)
3 * and the `IssueCertificate` binding (runtime):
4 *
5 * order → DNS-01 per authorization (present → propagated → respond →
6 * poll) → finalize with a fresh key's CSR → download → parse.
7 *
8 * The wire is `@distilled.cloud/acme`; this file only sequences it.
9 */
10 import * as Acme from "@distilled.cloud/acme";
11 import * as acme from "@distilled.cloud/acme/acme";
12 import * as Effect from "effect/Effect";
13 import * as FetchHttpClient from "effect/http/FetchHttpClient";
14 import * as HttpClient from "effect/http/HttpClient";
15 import * as Layer from "effect/Layer";
16 import * as Redacted from "effect/Redacted";
17 import * as Schedule from "effect/Schedule";
18 import type { CertificateAuthority } from "./CertificateAuthority.ts";
19 import { waitForTxt, type PropagationOptions } from "./Dns.ts";
20 import type { DnsChallengeRecord, DnsSolver } from "./DnsSolver.ts";
21 import {
22 ChallengeFailed,
23 ChallengeUnsupported,
24 OrderInvalid,
25 OrderTimeout,
26 PkiError,
27 type DnsPropagationTimeout,
28 type DnsSolverError,
29 } from "./Errors.ts";
30 import {
31 createCsr,
32 csrToBase64Url,
33 fromPem,
34 generateKey,
35 parseCertificate,
36 privateKeyToJwk,
37 splitPemChain,
38 type KeyAlgorithm,
39 type ParsedCertificate,
40 } from "./Pki.ts";
41
42 /** Everything the flow needs to sign requests as an account. */
43 export interface AccountCredentials {
44 readonly ca: CertificateAuthority;
45 /** The account's private JWK (JSON). */
46 readonly accountKey: Redacted.Redacted<string>;
47 /** The account URL (`kid`), once the account exists. */
48 readonly accountUrl?: string | undefined;
49 readonly externalAccountBinding?:
50 | { readonly keyId: string; readonly hmacKey: Redacted.Redacted<string> }
51 | undefined;
52 }
53
54 /**
55 * The SDK's `Credentials` (+ a CA-trusting `HttpClient` for private CAs)
56 * for one account. Provide around any `@distilled.cloud/acme` call.
57 */
58 export const accountLayer = (
59 credentials: AccountCredentials,
60 ): Layer.Layer<Acme.Credentials | HttpClient.HttpClient> => {
61 const creds = Acme.layer({
62 directoryUrl: credentials.ca.directoryUrl,
63 accountKey: credentials.accountKey,
64 accountUrl: credentials.accountUrl,
65 externalAccountBinding: credentials.externalAccountBinding,
66 });
67 const http =
68 credentials.ca.trustedRoot === undefined
69 ? FetchHttpClient.layer
70 : FetchHttpClient.layer.pipe(
71 Layer.provideMerge(
72 Layer.succeed(FetchHttpClient.RequestInit, {
73 // Bun's fetch honours `tls`; the option is ignored elsewhere.
74 tls: { ca: credentials.ca.trustedRoot },
75 } as RequestInit),
76 ),
77 );
78 return Layer.merge(creds, http);
79 };
80
81 export interface IssueRequest<R = never> {
82 /** DNS names; the first is the subject CN. Wildcards allowed. */
83 readonly identifiers: ReadonlyArray<string>;
84 readonly solver: DnsSolver<R>;
85 /** @default "ES256" */
86 readonly keyAlgorithm?: KeyAlgorithm | undefined;
87 /** Issuer name (`CN=...` substring) to prefer when the CA offers alternate chains. */
88 readonly preferredChain?: string | undefined;
89 readonly propagation?: PropagationOptions | undefined;
90 }
91
92 export interface IssuedCertificate {
93 /** Leaf certificate PEM. */
94 readonly certificate: string;
95 /** Full chain PEM, leaf first. */
96 readonly chain: string;
97 /** PKCS#8 private key PEM. */
98 readonly privateKey: Redacted.Redacted<string>;
99 readonly identifiers: ReadonlyArray<string>;
100 readonly serial: string;
101 /** ISO 8601. */
102 readonly notBefore: string;
103 /** ISO 8601. */
104 readonly notAfter: string;
105 readonly issuer: string;
106 /** The CA's certificate URL (for re-download and revocation bookkeeping). */
107 readonly certificateUrl: string;
108 readonly orderUrl: string;
109 }
110
111 export type IssueError =
112 | OrderInvalid
113 | ChallengeFailed
114 | ChallengeUnsupported
115 | OrderTimeout
116 | DnsPropagationTimeout
117 | DnsSolverError
118 | PkiError
119 | Acme.JoseError
120 | acme.NewOrderError
121 | acme.GetAuthorizationError
122 | acme.RespondChallengeError
123 | acme.FinalizeOrderError
124 | acme.GetOrderError
125 | acme.DownloadCertificateError;
126
127 const PENDING = new Set(["pending", "processing", "ready"]);
128
129 const challengeFqdn = (identifier: string): string =>
130 `_acme-challenge.${identifier.replace(/^\*\./, "")}`;
131
132 const problemsOf = (
133 order: acme.OrderResponse,
134 authorizations: ReadonlyArray<acme.Authorization>,
135 ) => {
136 const problems: Array<{
137 identifier?: string;
138 type?: string;
139 detail?: string;
140 }> = [];
141 if (order.error) {
142 problems.push({ type: order.error.type, detail: order.error.detail });
143 }
144 for (const authorization of authorizations) {
145 for (const challenge of authorization.challenges) {
146 if (challenge.error) {
147 problems.push({
148 identifier: authorization.identifier.value,
149 type: challenge.error.type,
150 detail: challenge.error.detail,
151 });
152 }
153 }
154 }
155 return problems;
156 };
157
158 /**
159 * Complete one DNS-01 authorization and remove its TXT record on every exit.
160 */
161 const solveAuthorization = <R>(
162 authorizationUrl: string,
163 jwk: Acme.Jose.Jwk,
164 solver: DnsSolver<R>,
165 propagation: PropagationOptions,
166 ) =>
167 Effect.gen(function* () {
168 const authorization = yield* acme.getAuthorization({
169 url: authorizationUrl,
170 });
171 if (authorization.status === "valid") return authorization;
172 const identifier = authorization.identifier.value;
173 const challenge = authorization.challenges.find((c) => c.type === "dns-01");
174 if (challenge === undefined || challenge.token === undefined) {
175 return yield* new ChallengeUnsupported({
176 identifier,
177 offered: authorization.challenges.map((c) => c.type),
178 });
179 }
180 const record: DnsChallengeRecord = {
181 fqdn: challengeFqdn(identifier),
182 value: yield* Acme.Jose.dnsChallengeValue(challenge.token, jwk),
183 };
184 return yield* Effect.acquireUseRelease(
185 solver.present(record),
186 () =>
187 Effect.gen(function* () {
188 yield* solver.propagated === undefined
189 ? waitForTxt(record.fqdn, record.value, propagation)
190 : solver.propagated(record, propagation);
191 yield* acme.respondChallenge({ url: challenge.url });
192 const settled = yield* acme.getAuthorization({ url: authorizationUrl }).pipe(
193 Effect.repeat({
194 schedule: Schedule.spaced("2 seconds"),
195 until: (a) => !PENDING.has(a.status),
196 times: 8,
197 }),
198 );
199 if (settled.status !== "valid") {
200 const failed = settled.challenges.find((c) => c.type === "dns-01");
201 return yield* new ChallengeFailed({
202 identifier,
203 type: failed?.error?.type,
204 detail: failed?.error?.detail ?? `authorization is ${settled.status}`,
205 });
206 }
207 return settled;
208 }),
209 () => solver.cleanup(record),
210 );
211 });
212
213 const chooseChain = (
214 downloaded: { chain: string; alternates?: ReadonlyArray<string> },
215 preferredChain: string | undefined,
216 ) =>
217 Effect.gen(function* () {
218 const matches = (chain: string) =>
219 Effect.gen(function* () {
220 const blocks = splitPemChain(chain);
221 const top = blocks[blocks.length - 1];
222 if (top === undefined) return false;
223 const parsed = yield* parseCertificate(top).pipe(Effect.orElseSucceed(() => undefined));
224 return parsed?.issuer.includes(preferredChain!) === true;
225 });
226 if (preferredChain === undefined) return downloaded.chain;
227 if (yield* matches(downloaded.chain)) return downloaded.chain;
228 for (const url of downloaded.alternates ?? []) {
229 const alternate = yield* acme.downloadCertificate({ url });
230 if (yield* matches(alternate.chain)) return alternate.chain;
231 }
232 return downloaded.chain;
233 });
234
235 /**
236 * Issue a certificate for `identifiers` as the current `Credentials`
237 * account. Requires the SDK's `Credentials` and an `HttpClient` (see
238 * {@link accountLayer}) plus whatever the solver needs.
239 */
240 export const issueCertificate = <R = never>(
241 request: IssueRequest<R>,
242 ): Effect.Effect<IssuedCertificate, IssueError, Acme.Credentials | HttpClient.HttpClient | R> =>
243 Effect.gen(function* () {
244 const resolve = yield* Acme.Credentials;
245 const config = yield* resolve;
246 const jwk = yield* Acme.Jose.parseJwk(config.accountKey);
247 const propagation = request.propagation ?? {};
248
249 const order = yield* acme.newOrder({
250 identifiers: request.identifiers.map((value) => ({ type: "dns", value })),
251 });
252 if (order.location === undefined) {
253 return yield* new OrderInvalid({
254 orderUrl: order.finalize,
255 problems: [{ detail: "The CA omitted the order Location header." }],
256 });
257 }
258 const orderUrl = order.location;
259
260 // Each authorization removes its own TXT record on success or failure.
261 const authorizations = yield* Effect.forEach(
262 order.authorizations,
263 (url) => solveAuthorization(url, jwk, request.solver, propagation),
264 { concurrency: 4 },
265 );
266
267 const ready = yield* acme.getOrder({ url: orderUrl }).pipe(
268 Effect.repeat({
269 schedule: Schedule.spaced("2 seconds"),
270 until: (value) => value.status !== "pending",
271 times: 8,
272 }),
273 );
274 if (ready.status === "invalid") {
275 return yield* new OrderInvalid({
276 orderUrl,
277 problems: problemsOf(ready, authorizations),
278 });
279 }
280 if (ready.status !== "ready") {
281 return yield* new OrderTimeout({ orderUrl, status: ready.status });
282 }
283 const key = yield* generateKey(request.keyAlgorithm ?? "ES256");
284 const csr = yield* createCsr({ key, identifiers: request.identifiers });
285 yield* acme.finalizeOrder({ url: order.finalize, csr: csrToBase64Url(csr) }).pipe(
286 Effect.retry({
287 while: (error) => error._tag === "AcmeOrderNotReady",
288 schedule: Schedule.spaced("1 second"),
289 times: 8,
290 }),
291 );
292
293 const settled = yield* acme.getOrder({ url: orderUrl }).pipe(
294 Effect.repeat({
295 schedule: Schedule.spaced("2 seconds"),
296 until: (o) => o.status === "valid" || o.status === "invalid",
297 times: 8,
298 }),
299 );
300 if (settled.status === "invalid") {
301 return yield* new OrderInvalid({
302 orderUrl,
303 problems: problemsOf(settled, authorizations),
304 });
305 }
306 if (settled.status !== "valid" || settled.certificate === undefined) {
307 return yield* new OrderTimeout({ orderUrl, status: settled.status });
308 }
309
310 const downloaded = yield* acme.downloadCertificate({
311 url: settled.certificate,
312 });
313 const chain = yield* chooseChain(downloaded, request.preferredChain);
314 const certificate = splitPemChain(chain)[0] ?? chain;
315 const parsed = yield* parseCertificate(certificate);
316 return toIssued({
317 certificate,
318 chain,
319 privateKey: key.privateKeyPem,
320 identifiers: request.identifiers,
321 certificateUrl: settled.certificate,
322 orderUrl,
323 parsed,
324 });
325 });
326
327 const toIssued = (input: {
328 certificate: string;
329 chain: string;
330 privateKey: Redacted.Redacted<string>;
331 identifiers: ReadonlyArray<string>;
332 certificateUrl: string;
333 orderUrl: string;
334 parsed: ParsedCertificate;
335 }): IssuedCertificate => ({
336 certificate: input.certificate,
337 chain: input.chain,
338 privateKey: input.privateKey,
339 identifiers: input.identifiers,
340 serial: input.parsed.serial,
341 notBefore: input.parsed.notBefore.toISOString(),
342 notAfter: input.parsed.notAfter.toISOString(),
343 issuer: input.parsed.issuer,
344 certificateUrl: input.certificateUrl,
345 orderUrl: input.orderUrl,
346 });
347
348 /** RFC 5280 revocation reasons. */
349 export type RevocationReason =
350 | "unspecified"
351 | "keyCompromise"
352 | "affiliationChanged"
353 | "superseded"
354 | "cessationOfOperation";
355
356 const REASON_CODES: Record<RevocationReason, number> = {
357 unspecified: 0,
358 keyCompromise: 1,
359 affiliationChanged: 3,
360 superseded: 4,
361 cessationOfOperation: 5,
362 };
363
364 export interface RevokeRequest {
365 /** Leaf certificate PEM. */
366 readonly certificate: string;
367 /**
368 * The certificate's private key. When given, the request is signed with
369 * it (RFC 8555 §7.6) so no account is needed; otherwise the ambient
370 * account credentials sign.
371 */
372 readonly privateKey?: Redacted.Redacted<string> | string | undefined;
373 readonly reason?: RevocationReason | undefined;
374 }
375
376 export type RevokeError = PkiError | acme.RevokeCertificateError;
377
378 /** Revoke a certificate. `AcmeAlreadyRevoked` is folded into success. */
379 export const revokeCertificate = (
380 request: RevokeRequest,
381 ): Effect.Effect<void, RevokeError, Acme.Credentials | HttpClient.HttpClient> =>
382 Effect.gen(function* () {
383 const leaf = splitPemChain(request.certificate)[0] ?? request.certificate;
384 const der = yield* Effect.try({
385 try: () => fromPem(leaf),
386 catch: (cause) => new PkiError({ message: "The certificate is not PEM.", cause }),
387 });
388 const revoke = acme
389 .revokeCertificate({
390 certificate: Acme.Jose.base64url(der),
391 reason: request.reason === undefined ? undefined : REASON_CODES[request.reason],
392 })
393 .pipe(Effect.catchTag("AcmeAlreadyRevoked", () => Effect.void));
394 if (request.privateKey === undefined) {
395 return yield* revoke;
396 }
397 // Sign with the certificate key (RFC 8555 §7.6): swap the account key
398 // and drop the account URL so the protocol embeds the JWK.
399 const resolve = yield* Acme.Credentials;
400 const config = yield* resolve;
401 const jwk = yield* privateKeyToJwk(request.privateKey);
402 return yield* revoke.pipe(
403 Effect.provide(Acme.layer({ directoryUrl: config.directoryUrl, accountKey: jwk })),
404 );
405 });