@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, 06:00 UTC

main
ts 254 lines 8.59 KB
Raw
1 import * as Acme from "@distilled.cloud/acme";
2 import * as acme from "@distilled.cloud/acme/acme";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Redacted from "effect/Redacted";
9 import type { CertificateAuthority } from "./CertificateAuthority.ts";
10 import { accountLayer, type AccountCredentials } from "./Client.ts";
11 import type { KeyAlgorithm } from "./Pki.ts";
12 import type { Providers } from "./Providers.ts";
13
14 export interface ExternalAccountBinding {
15 /** The key id the CA issued (ZeroSSL: `eab_kid`). */
16 keyId: string;
17 /** The base64url HMAC key the CA issued (ZeroSSL: `eab_hmac_key`). */
18 hmacKey: Redacted.Redacted<string> | string;
19 }
20
21 export interface AccountProps {
22 /**
23 * The certificate authority: a preset ({@link LetsEncrypt},
24 * {@link ZeroSSL}, …) or `{ directoryUrl }`. Changing it replaces the
25 * account.
26 */
27 ca: CertificateAuthority;
28 /**
29 * Contact URLs (`mailto:…`) the CA notifies about expiry and incidents.
30 * Updated in place.
31 */
32 contact?: string[];
33 /**
34 * You must agree to the CA's terms of service. Explicit on purpose —
35 * never defaulted.
36 */
37 termsOfServiceAgreed: true;
38 /**
39 * External Account Binding for CAs that require one (ZeroSSL, Google
40 * Trust Services). Changing the key id replaces the account.
41 */
42 eab?: ExternalAccountBinding;
43 /**
44 * Account key algorithm. Changing it replaces the account.
45 * @default "ES256"
46 */
47 keyAlgorithm?: KeyAlgorithm;
48 }
49
50 export interface Account extends Resource<
51 "ACME.Account",
52 AccountProps,
53 {
54 /** The CA's directory URL. */
55 directoryUrl: string;
56 /** PEM root trusted for the CA's HTTPS endpoint (private CAs only). */
57 trustedRoot: string | undefined;
58 /** The account URL the CA assigned — the `kid` on every later request. */
59 accountUrl: string;
60 /** Observed account status (`valid`, `deactivated`, `revoked`). */
61 status: string;
62 /** Observed contact URLs. */
63 contact: string[];
64 /** Account key algorithm. */
65 keyAlgorithm: KeyAlgorithm;
66 /** The account's private JWK (JSON). Sensitive; persisted in stack state. */
67 privateKey: Redacted.Redacted<string>;
68 },
69 never,
70 Providers
71 > {}
72
73 /**
74 * An ACME account with a certificate authority — the identity that every
75 * {@link Certificate} and every runtime {@link IssueCertificate} call
76 * signs with. One per CA per stack.
77 *
78 * The account key is generated on first reconcile and persisted as a
79 * redacted value alongside the CA's account URL. Protect the state store
80 * as secret material; redaction alone does not encrypt the storage backend.
81 *
82 * ### Let's Encrypt
83 * **Example:** An account with Let's Encrypt
84 * ```typescript
85 * export const LetsEncrypt = ACME.Account("LetsEncrypt", {
86 * ca: ACME.LetsEncrypt,
87 * contact: ["mailto:ops@example.com"],
88 * termsOfServiceAgreed: true,
89 * });
90 * ```
91 *
92 * ### External Account Binding
93 * ZeroSSL and Google Trust Services bind ACME accounts to an existing
94 * customer account with a key id + HMAC pair from their dashboard (ZeroSSL
95 * also mints them over its REST API — see `@distilled.cloud/zerossl`).
96 *
97 * **Example:** ZeroSSL
98 * ```typescript
99 * export const ZeroSsl = ACME.Account("ZeroSSL", {
100 * ca: ACME.ZeroSSL,
101 * eab: {
102 * keyId: Config.String("ZEROSSL_EAB_KID"),
103 * hmacKey: Config.Redacted("ZEROSSL_EAB_HMAC_KEY"),
104 * },
105 * termsOfServiceAgreed: true,
106 * });
107 * ```
108 *
109 * ### Private CAs
110 * A private CA (Pebble, step-ca) whose HTTPS certificate is not publicly
111 * trusted passes its root as `trustedRoot`.
112 *
113 * **Example:** Pebble
114 * ```typescript
115 * export const Pebble = ACME.Account("Pebble", {
116 * ca: { directoryUrl: "https://localhost:14000/dir", trustedRoot: pebbleRootPem },
117 * termsOfServiceAgreed: true,
118 * });
119 * ```
120 *
121 * @resource
122 * @product Account
123 * @category Certificates
124 */
125 export const Account = Resource<Account>("ACME.Account");
126
127 /** The CA answered `newAccount` without a `Location`, so the account has no URL. */
128 export class AccountUrlMissing extends Data.TaggedError("ACME.AccountUrlMissing")<{
129 readonly directoryUrl: string;
130 }> {}
131
132 /**
133 * Normalize to exactly one `Redacted` layer: a value that already came
134 * redacted (an SDK's sensitive field) wrapped again by the caller would
135 * otherwise sign with an object instead of the key.
136 */
137 const unwrap = (value: Redacted.Redacted<string> | string) => {
138 let inner: unknown = value;
139 while (Redacted.isRedacted(inner)) inner = Redacted.value(inner);
140 return Redacted.make(String(inner));
141 };
142
143 const credentialsOf = (
144 props: Pick<AccountProps, "ca" | "eab">,
145 accountKey: Redacted.Redacted<string>,
146 accountUrl: string | undefined,
147 ): AccountCredentials => ({
148 ca: props.ca,
149 accountKey,
150 accountUrl,
151 externalAccountBinding:
152 props.eab === undefined
153 ? undefined
154 : { keyId: props.eab.keyId, hmacKey: unwrap(props.eab.hmacKey) },
155 });
156
157 /** `newAccount` with `onlyReturnExisting` — the account, or `undefined`. */
158 const observeAccount = (credentials: AccountCredentials) =>
159 acme.newAccount({ onlyReturnExisting: true }).pipe(
160 Effect.catchTag("AcmeAccountDoesNotExist", () => Effect.undefined),
161 Effect.provide(accountLayer(credentials)),
162 );
163
164 const sameContacts = (
165 a: ReadonlyArray<string> | undefined,
166 b: ReadonlyArray<string> | undefined,
167 ) => {
168 const left = [...(a ?? [])].sort();
169 const right = [...(b ?? [])].sort();
170 return left.length === right.length && left.every((v, i) => v === right[i]);
171 };
172
173 export const AccountProvider = () =>
174 Provider.succeed(Account, {
175 stables: ["directoryUrl", "accountUrl", "keyAlgorithm", "privateKey"],
176
177 diff: Effect.fn(function* ({ news, olds, output }) {
178 if (news === undefined || !isResolved(news) || output === undefined) {
179 return undefined;
180 }
181 if (
182 news.ca.directoryUrl !== output.directoryUrl ||
183 (news.keyAlgorithm ?? "ES256") !== output.keyAlgorithm ||
184 news.eab?.keyId !== olds?.eab?.keyId
185 ) {
186 return { action: "replace" as const };
187 }
188 return undefined;
189 }),
190
191 read: Effect.fn(function* ({ olds, output }) {
192 if (output === undefined || olds === undefined) return undefined;
193 const credentials = credentialsOf(olds, output.privateKey, output.accountUrl);
194 const existing = yield* observeAccount(credentials);
195 if (existing === undefined) return undefined;
196 return {
197 ...output,
198 status: existing.status,
199 contact: existing.contact ?? [],
200 };
201 }),
202
203 reconcile: Effect.fn(function* ({ news, output }) {
204 const keyAlgorithm = news.keyAlgorithm ?? "ES256";
205 // Observe: the key is the identity; keep it across reconciles.
206 const accountKey = output?.privateKey ?? (yield* Acme.Jose.generateAccountKey(keyAlgorithm));
207 const credentials = credentialsOf(news, accountKey, output?.accountUrl);
208 let account = yield* observeAccount(credentials);
209
210 // Repeating newAccount with the same key returns the existing account.
211 if (account === undefined) {
212 account = yield* acme
213 .newAccount({
214 contact: news.contact,
215 termsOfServiceAgreed: true,
216 })
217 .pipe(Effect.provide(accountLayer(credentials)));
218 }
219 const accountUrl = account.location ?? output?.accountUrl;
220 if (accountUrl === undefined) {
221 return yield* new AccountUrlMissing({
222 directoryUrl: news.ca.directoryUrl,
223 });
224 }
225
226 // Sync: contacts are the only mutable aspect.
227 const withKid = accountLayer(credentialsOf(news, accountKey, accountUrl));
228 if (!sameContacts(news.contact, account.contact)) {
229 account = yield* acme
230 .updateAccount({ url: accountUrl, contact: news.contact ?? [] })
231 .pipe(Effect.provide(withKid));
232 }
233
234 return {
235 directoryUrl: news.ca.directoryUrl,
236 trustedRoot: news.ca.trustedRoot,
237 accountUrl,
238 status: account.status,
239 contact: account.contact ?? [],
240 keyAlgorithm,
241 privateKey: accountKey,
242 };
243 }),
244
245 delete: Effect.fn(function* ({ olds, output }) {
246 const credentials = credentialsOf(olds, output.privateKey, output.accountUrl);
247 // Deactivation is permanent and idempotent: a deactivated account
248 // answers `unauthorized`, a purged one `accountDoesNotExist`.
249 yield* acme.updateAccount({ url: output.accountUrl, status: "deactivated" }).pipe(
250 Effect.catchTag(["AcmeAccountDoesNotExist", "AcmeUnauthorized"], () => Effect.undefined),
251 Effect.provide(accountLayer(credentials)),
252 );
253 }),
254 });