@distilled.cloud/acme 0.0.0-placeholder → 1.0.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +75 -0
  3. package/lib/credentials.d.ts +50 -0
  4. package/lib/credentials.d.ts.map +1 -0
  5. package/lib/credentials.js +57 -0
  6. package/lib/credentials.js.map +1 -0
  7. package/lib/errors.d.ts +73 -0
  8. package/lib/errors.d.ts.map +1 -0
  9. package/lib/errors.js +50 -0
  10. package/lib/errors.js.map +1 -0
  11. package/lib/index.d.ts +30 -0
  12. package/lib/index.d.ts.map +1 -0
  13. package/lib/index.js +30 -0
  14. package/lib/index.js.map +1 -0
  15. package/lib/jose.d.ts +66 -0
  16. package/lib/jose.d.ts.map +1 -0
  17. package/lib/jose.js +121 -0
  18. package/lib/jose.js.map +1 -0
  19. package/lib/protocol.d.ts +27 -0
  20. package/lib/protocol.d.ts.map +1 -0
  21. package/lib/protocol.js +404 -0
  22. package/lib/protocol.js.map +1 -0
  23. package/lib/protocol.test.d.ts +2 -0
  24. package/lib/protocol.test.d.ts.map +1 -0
  25. package/lib/protocol.test.js +533 -0
  26. package/lib/protocol.test.js.map +1 -0
  27. package/lib/retry.d.ts +33 -0
  28. package/lib/retry.d.ts.map +1 -0
  29. package/lib/retry.js +33 -0
  30. package/lib/retry.js.map +1 -0
  31. package/lib/services/acme.d.ts +509 -0
  32. package/lib/services/acme.d.ts.map +1 -0
  33. package/lib/services/acme.js +539 -0
  34. package/lib/services/acme.js.map +1 -0
  35. package/lib/services/index.d.ts +2 -0
  36. package/lib/services/index.d.ts.map +1 -0
  37. package/lib/services/index.js +3 -0
  38. package/lib/services/index.js.map +1 -0
  39. package/lib/traits.d.ts +13 -0
  40. package/lib/traits.d.ts.map +1 -0
  41. package/lib/traits.js +13 -0
  42. package/lib/traits.js.map +1 -0
  43. package/package.json +79 -6
  44. package/src/credentials.ts +100 -0
  45. package/src/errors.ts +91 -0
  46. package/src/index.ts +29 -0
  47. package/src/jose.ts +207 -0
  48. package/src/protocol.test.ts +806 -0
  49. package/src/protocol.ts +533 -0
  50. package/src/retry.ts +49 -0
  51. package/src/services/acme.ts +1096 -0
  52. package/src/services/index.ts +2 -0
  53. package/src/traits.ts +46 -0
@@ -0,0 +1,533 @@
1
+ import * as API from "@distilled.cloud/core/api";
2
+ import {
3
+ HTTP_STATUS_MAP,
4
+ InternalServerError,
5
+ type ConfigError,
6
+ } from "@distilled.cloud/core/errors";
7
+ import { getAnn, getProps, hasPropAnn, mapKeys } from "@distilled.cloud/core/protocol-http";
8
+ import { unwrapRedactedDeep } from "@distilled.cloud/core/protocol-rest";
9
+ /**
10
+ * AcmeProtocol — hand-written.
11
+ *
12
+ * ACME (RFC 8555) is JSON over HTTPS with two twists the generic REST
13
+ * protocol cannot express:
14
+ *
15
+ * signing: every POST body is a flattened JWS (RFC 8555 §6.2) signed by
16
+ * the account key from `Credentials`, carrying a fresh
17
+ * anti-replay nonce and the request URL in its protected
18
+ * header. `newAccount` embeds the public JWK; every later
19
+ * request references the account URL as `kid`. A CA-issued
20
+ * External Account Binding is attached to `newAccount` when
21
+ * the credentials carry one. Reads are "POST-as-GET" (empty
22
+ * payload).
23
+ *
24
+ * addressing: the provider endpoint is the CA's **directory URL**. The
25
+ * protocol fetches the directory once per CA and resolves
26
+ * `newNonce`/`newAccount`/`newOrder`/`revokeCert` from it;
27
+ * every other operation names its resource by the absolute
28
+ * URL the CA returned (`url` label).
29
+ *
30
+ * Responses are JSON; `Location` (account/order URL), `Replay-Nonce` and
31
+ * `Link` headers are folded into declared output members. Failures are
32
+ * RFC 7807 problem documents matched on their `type` URN against the
33
+ * operation's typed error classes; an unmatched URN is `UnknownAcmeError`.
34
+ */
35
+ import { isStrict, validateResponse } from "@distilled.cloud/core/response-validation";
36
+ import { parseRetryAfter, parseRetryAfterForStatus } from "@distilled.cloud/core/retry-after";
37
+ import { getErrorMatchers, httpSymbol, labelSymbol } from "@distilled.cloud/core/trait";
38
+ import * as Effect from "effect/Effect";
39
+ import type * as HttpBody from "effect/http/HttpBody";
40
+ import * as HttpClient from "effect/http/HttpClient";
41
+ import type * as HttpClientError from "effect/http/HttpClientError";
42
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
43
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
44
+ import * as Layer from "effect/Layer";
45
+ import * as Redacted from "effect/Redacted";
46
+ import * as Schema from "effect/Schema";
47
+ import type * as AST from "effect/SchemaAST";
48
+ import { Credentials, type Config } from "./credentials.ts";
49
+ import {
50
+ AcmeParseError,
51
+ DirectoryMissingResource,
52
+ JoseError,
53
+ UnknownAcmeError,
54
+ type DefaultErrors,
55
+ } from "./errors.ts";
56
+ import { parseJwk, signExternalAccountBinding, signRequest, type SignOptions } from "./jose.ts";
57
+
58
+ /**
59
+ * Error channel shared by every generated ACME operation. Generated service
60
+ * files annotate operations with `API.OperationMethod<I, O, AcmeOpError,
61
+ * AcmeOpContext>` explicitly so the compiler never infers these back out of
62
+ * the schema generics.
63
+ */
64
+ export type AcmeOpError = DefaultErrors | ConfigError | HttpClientError.HttpClientError;
65
+
66
+ /** Context (requirements) shared by every generated ACME operation. */
67
+ export type AcmeOpContext = Credentials | HttpClient.HttpClient;
68
+
69
+ // =============================================================================
70
+ // Directory + nonce caches (per CA, process-wide)
71
+ // =============================================================================
72
+
73
+ const DirectorySchema = Schema.Struct({
74
+ newNonce: Schema.String,
75
+ newAccount: Schema.String,
76
+ newOrder: Schema.String,
77
+ revokeCert: Schema.String,
78
+ newAuthz: Schema.optional(Schema.String),
79
+ keyChange: Schema.optional(Schema.String),
80
+ meta: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
81
+ });
82
+ type Directory = typeof DirectorySchema.Type;
83
+
84
+ const directories = new Map<string, Directory>();
85
+ /** The last unused `Replay-Nonce` per directory URL. Nonces are single-use. */
86
+ const nonces = new Map<string, string>();
87
+
88
+ type SigningContext = Omit<SignOptions, "nonce"> & {
89
+ readonly directoryUrl: string;
90
+ };
91
+ // HTTP request copies preserve the body identity; entries live only with a request.
92
+ const signedRequests = new WeakMap<HttpBody.HttpBody, SigningContext>();
93
+
94
+ const resolveCredentials = Effect.gen(function* () {
95
+ const resolve = yield* Credentials;
96
+ return yield* resolve as Effect.Effect<Config>;
97
+ });
98
+
99
+ const fetchDirectory = (directoryUrl: string) =>
100
+ Effect.gen(function* () {
101
+ const cached = directories.get(directoryUrl);
102
+ if (cached) return cached;
103
+ const client = yield* HttpClient.HttpClient;
104
+ const response = yield* client.get(directoryUrl);
105
+ rememberNonce(directoryUrl, response);
106
+ if (response.status >= 400) {
107
+ const text = yield* response.text;
108
+ return yield* fail(
109
+ new UnknownAcmeError({
110
+ message: `GET ${directoryUrl} answered ${response.status}`,
111
+ status: response.status,
112
+ body: Redacted.make(text),
113
+ }),
114
+ );
115
+ }
116
+ const text = yield* response.text;
117
+ const json = yield* parseJson(text);
118
+ const directory = yield* Schema.decodeUnknownEffect(DirectorySchema)(json).pipe(
119
+ Effect.mapError(() => parseError("Invalid ACME directory response")),
120
+ );
121
+ directories.set(directoryUrl, directory);
122
+ return directory;
123
+ });
124
+
125
+ const rememberNonce = (
126
+ directoryUrl: string,
127
+ response: HttpClientResponse.HttpClientResponse,
128
+ ): void => {
129
+ const nonce = response.headers["replay-nonce"];
130
+ if (typeof nonce === "string" && nonce.length > 0) {
131
+ nonces.set(directoryUrl, nonce);
132
+ }
133
+ };
134
+
135
+ /** Take the cached nonce for this CA, or fetch a fresh one from `newNonce`. */
136
+ const takeNonce = (directoryUrl: string, directory: Directory) =>
137
+ Effect.gen(function* () {
138
+ const cached = nonces.get(directoryUrl);
139
+ if (cached !== undefined) {
140
+ nonces.delete(directoryUrl);
141
+ return cached;
142
+ }
143
+ const client = yield* HttpClient.HttpClient;
144
+ const response = yield* client.execute(HttpClientRequest.head(directory.newNonce));
145
+ const nonce = response.headers["replay-nonce"];
146
+ if (typeof nonce !== "string" || nonce.length === 0) {
147
+ return yield* fail(
148
+ new UnknownAcmeError({
149
+ message: `HEAD ${directory.newNonce} returned no Replay-Nonce header`,
150
+ status: response.status,
151
+ body: undefined,
152
+ }),
153
+ );
154
+ }
155
+ return nonce;
156
+ });
157
+
158
+ // =============================================================================
159
+ // Encode
160
+ // =============================================================================
161
+
162
+ /**
163
+ * The generated operations carry no name at runtime; the input's `T.Http`
164
+ * uri (from the Smithy model) identifies which ACME resource an
165
+ * operation addresses.
166
+ */
167
+ const OPERATIONS_BY_URI: Record<string, string> = {
168
+ "/directory": "GetDirectory",
169
+ "/newNonce": "NewNonce",
170
+ "/newAccount": "NewAccount",
171
+ "/account/{url}": "UpdateAccount",
172
+ "/newOrder": "NewOrder",
173
+ "/order/{url}": "GetOrder",
174
+ "/finalize/{url}": "FinalizeOrder",
175
+ "/authz/{url}": "GetAuthorization",
176
+ "/authz/{url}/deactivate": "DeactivateAuthorization",
177
+ "/challenge/{url}": "RespondChallenge",
178
+ "/cert/{url}": "DownloadCertificate",
179
+ "/revokeCert": "RevokeCertificate",
180
+ };
181
+
182
+ const operationOf = (inputAst: AST.AST): string => {
183
+ const http = getAnn(inputAst, httpSymbol) as { uri?: string } | undefined;
184
+ return OPERATIONS_BY_URI[http?.uri ?? ""] ?? "";
185
+ };
186
+
187
+ /** Operations resolved from the directory rather than an input `url`. */
188
+ const DIRECTORY_OPERATIONS: Record<string, keyof Directory> = {
189
+ NewNonce: "newNonce",
190
+ NewAccount: "newAccount",
191
+ NewOrder: "newOrder",
192
+ RevokeCertificate: "revokeCert",
193
+ };
194
+
195
+ /** Operations whose payload is the empty POST-as-GET. */
196
+ const POST_AS_GET = new Set(["GetOrder", "GetAuthorization", "DownloadCertificate"]);
197
+
198
+ const JOSE_ACCEPT = "application/json, application/pem-certificate-chain";
199
+
200
+ const encode = ({
201
+ input,
202
+ inputAst,
203
+ }: {
204
+ readonly input: unknown;
205
+ readonly inputAst: AST.AST;
206
+ readonly config: API.ProtocolOperationConfig;
207
+ }) =>
208
+ Effect.gen(function* () {
209
+ const creds = yield* resolveCredentials;
210
+ const operation = operationOf(inputAst);
211
+ if (operation === "") {
212
+ return yield* fail(
213
+ new JoseError({
214
+ message: "The operation's input carries no known ACME `T.Http` uri.",
215
+ }),
216
+ );
217
+ }
218
+
219
+ if (operation === "GetDirectory") {
220
+ return HttpClientRequest.get(creds.directoryUrl).pipe(
221
+ HttpClientRequest.setHeader("Accept", "application/json"),
222
+ );
223
+ }
224
+
225
+ const directory = yield* fetchDirectory(creds.directoryUrl);
226
+
227
+ if (operation === "NewNonce") {
228
+ return HttpClientRequest.head(directory.newNonce);
229
+ }
230
+
231
+ // Resolve the request URL: from the directory for the well-known
232
+ // resources, else the absolute `url` label the CA handed back.
233
+ const inputObj = (unwrapRedactedDeep(input) ?? {}) as Record<string, unknown>;
234
+ const directoryKey = DIRECTORY_OPERATIONS[operation];
235
+ let url: string;
236
+ if (directoryKey !== undefined) {
237
+ const resolved = directory[directoryKey];
238
+ if (typeof resolved !== "string") {
239
+ return yield* fail(
240
+ new DirectoryMissingResource({
241
+ resource: directoryKey,
242
+ directoryUrl: creds.directoryUrl,
243
+ }),
244
+ );
245
+ }
246
+ url = resolved;
247
+ } else {
248
+ const label = getProps(inputAst).find((p) => hasPropAnn(p, labelSymbol));
249
+ const value = label ? inputObj[String(label.name)] : undefined;
250
+ if (typeof value !== "string") {
251
+ return yield* fail(
252
+ new JoseError({
253
+ message: `${operation} needs the resource URL the CA returned (\`url\`).`,
254
+ }),
255
+ );
256
+ }
257
+ url = value;
258
+ }
259
+
260
+ // The payload: every input member that isn't the URL label, or the
261
+ // empty POST-as-GET for reads.
262
+ let payload: unknown;
263
+ if (!POST_AS_GET.has(operation)) {
264
+ const body: Record<string, unknown> = {};
265
+ for (const prop of getProps(inputAst)) {
266
+ if (hasPropAnn(prop, labelSymbol)) continue;
267
+ const key = String(prop.name);
268
+ if (inputObj[key] !== undefined) body[key] = inputObj[key];
269
+ }
270
+ payload = body;
271
+ }
272
+
273
+ const jwk = yield* parseJwk(creds.accountKey);
274
+ // `newAccount` proves the key by embedding it; a CA that requires an
275
+ // External Account Binding gets it from the credentials unless the
276
+ // caller built one.
277
+ const embedKey = operation === "NewAccount" || creds.accountUrl === undefined;
278
+ if (
279
+ operation === "NewAccount" &&
280
+ creds.externalAccountBinding !== undefined &&
281
+ (payload as Record<string, unknown>).externalAccountBinding === undefined
282
+ ) {
283
+ (payload as Record<string, unknown>).externalAccountBinding =
284
+ yield* signExternalAccountBinding({
285
+ jwk,
286
+ url,
287
+ keyId: creds.externalAccountBinding.keyId,
288
+ hmacKey: creds.externalAccountBinding.hmacKey,
289
+ });
290
+ }
291
+
292
+ const nonce = yield* takeNonce(creds.directoryUrl, directory);
293
+ const signing: SigningContext = {
294
+ jwk,
295
+ url,
296
+ kid: embedKey ? undefined : creds.accountUrl,
297
+ payload,
298
+ directoryUrl: creds.directoryUrl,
299
+ };
300
+ const request = yield* signedRequest(signing, nonce);
301
+ signedRequests.set(request.body, signing);
302
+ return request;
303
+ });
304
+
305
+ const signedRequest = (signing: SigningContext, nonce: string) =>
306
+ Effect.gen(function* () {
307
+ const jws = yield* signRequest({ ...signing, nonce });
308
+ return HttpClientRequest.post(signing.url).pipe(
309
+ HttpClientRequest.setHeader("Accept", JOSE_ACCEPT),
310
+ HttpClientRequest.bodyText(JSON.stringify(jws), "application/jose+json"),
311
+ );
312
+ });
313
+
314
+ // =============================================================================
315
+ // Decode
316
+ // =============================================================================
317
+
318
+ interface Problem {
319
+ readonly type?: string;
320
+ readonly detail?: string;
321
+ readonly status?: number;
322
+ readonly subproblems?: ReadonlyArray<unknown>;
323
+ }
324
+
325
+ const isProblem = (value: unknown): value is Problem =>
326
+ isObject(value) && typeof value.type === "string";
327
+
328
+ /**
329
+ * Match a problem document against the operation's typed error classes by
330
+ * its `type` URN (the matcher's `message` rule is applied to the URN, so a
331
+ * patch writes `{ "message": { "matches": "^urn:ietf:params:acme:error:badNonce$" } }`).
332
+ */
333
+ const matchProblem = (
334
+ errorClasses: ReadonlyArray<unknown>,
335
+ status: number,
336
+ problem: Problem,
337
+ headers: Record<string, string | undefined>,
338
+ ): unknown | undefined => {
339
+ const urn = problem.type ?? "";
340
+ let best: { cls: unknown; specificity: number } | undefined;
341
+ for (const cls of errorClasses) {
342
+ const matchers = getErrorMatchers(cls);
343
+ if (!matchers) continue;
344
+ for (const m of matchers) {
345
+ if (m.status !== undefined && m.status !== status) continue;
346
+ if (m.code !== undefined && m.code !== status) continue;
347
+ const rule = m.message;
348
+ let hit = false;
349
+ if (rule === undefined) hit = true;
350
+ else if (typeof rule === "string") hit = rule === urn;
351
+ else if (rule.matches !== undefined) hit = new RegExp(rule.matches).test(urn);
352
+ else if (rule.includes !== undefined) hit = urn.includes(rule.includes);
353
+ if (!hit) continue;
354
+ const specificity = (m.status !== undefined ? 1 : 0) + (rule !== undefined ? 2 : 0);
355
+ if (!best || specificity > best.specificity) best = { cls, specificity };
356
+ }
357
+ }
358
+ if (!best) return undefined;
359
+ return new (best.cls as new (args: any) => unknown)({
360
+ code: status,
361
+ message: problem.detail ?? urn,
362
+ type: urn,
363
+ detail: problem.detail,
364
+ subproblems: problem.subproblems,
365
+ ...(urn === "urn:ietf:params:acme:error:rateLimited"
366
+ ? { retryAfter: parseRetryAfter(headers) }
367
+ : {}),
368
+ });
369
+ };
370
+
371
+ const parseLinkAlternates = (link: string | undefined): string[] => {
372
+ if (!link) return [];
373
+ const out: string[] = [];
374
+ for (const part of link.split(",")) {
375
+ const match = part.match(/<([^>]+)>\s*;\s*rel="?alternate"?/);
376
+ if (match) out.push(match[1]!);
377
+ }
378
+ return out;
379
+ };
380
+
381
+ const decode = ({
382
+ response,
383
+ outputAst,
384
+ errors: errorClasses,
385
+ }: {
386
+ readonly response: HttpClientResponse.HttpClientResponse;
387
+ readonly outputAst: AST.AST;
388
+ readonly errors: ReadonlyArray<unknown>;
389
+ readonly config: API.ProtocolOperationConfig;
390
+ }) =>
391
+ Effect.gen(function* () {
392
+ const signing = signedRequests.get(response.request.body);
393
+ signedRequests.delete(response.request.body);
394
+ const directoryUrl = signing?.directoryUrl ?? (yield* resolveCredentials).directoryUrl;
395
+
396
+ for (let retries = 0; ; retries++) {
397
+ const headers = response.headers as Record<string, string | undefined>;
398
+ const status = response.status;
399
+ const isNewNonce = response.request.method === "HEAD";
400
+ const isCertificate = (headers["content-type"] ?? "").includes("pem-certificate-chain");
401
+ const text = isNewNonce ? "" : yield* response.text;
402
+ const json =
403
+ isNewNonce || (isCertificate && status < 400)
404
+ ? undefined
405
+ : yield* parseJson(text).pipe(
406
+ // A non-JSON 2xx fails only in strict mode; lenient returns
407
+ // the text as read.
408
+ Effect.catchTag("AcmeParseError", (error) =>
409
+ status >= 400
410
+ ? Effect.succeed(undefined)
411
+ : Effect.flatMap(isStrict, (strict) =>
412
+ strict ? Effect.fail(error) : Effect.succeed<unknown>(text),
413
+ ),
414
+ ),
415
+ );
416
+ const problem = status >= 400 && isProblem(json) ? json : undefined;
417
+ const badNonce = problem?.type === "urn:ietf:params:acme:error:badNonce";
418
+ if (badNonce) {
419
+ const nonce = headers["replay-nonce"];
420
+ // Rejection nonces belong only to this request, never to the shared cache.
421
+ if (signing && nonce && retries < 2) {
422
+ const client = yield* HttpClient.HttpClient;
423
+ response = yield* client.execute(yield* signedRequest(signing, nonce));
424
+ continue;
425
+ }
426
+ } else {
427
+ rememberNonce(directoryUrl, response);
428
+ }
429
+
430
+ if (status >= 400) {
431
+ if (problem) {
432
+ const typed = matchProblem(errorClasses, status, problem, headers);
433
+ if (typed !== undefined) return yield* fail(typed);
434
+ return yield* fail(
435
+ new UnknownAcmeError({
436
+ type: problem.type,
437
+ detail: problem.detail,
438
+ subproblems: problem.subproblems,
439
+ message: problem.detail ?? problem.type,
440
+ status,
441
+ body: Redacted.make(json),
442
+ }),
443
+ );
444
+ }
445
+ const message = `HTTP ${status}`;
446
+ const StatusClass = (HTTP_STATUS_MAP as Record<number, unknown>)[status] as
447
+ | (new (args: {
448
+ message: string;
449
+ retryAfter?: ReturnType<typeof parseRetryAfterForStatus>;
450
+ }) => unknown)
451
+ | undefined;
452
+ if (StatusClass) {
453
+ return yield* fail(
454
+ new StatusClass({
455
+ message,
456
+ retryAfter: parseRetryAfterForStatus(status, headers),
457
+ }),
458
+ );
459
+ }
460
+ if (status >= 500) {
461
+ return yield* fail(
462
+ new InternalServerError({
463
+ message,
464
+ retryAfter: parseRetryAfterForStatus(status, headers),
465
+ }),
466
+ );
467
+ }
468
+ return yield* fail(
469
+ new UnknownAcmeError({
470
+ message,
471
+ status,
472
+ body: Redacted.make(json ?? text),
473
+ }),
474
+ );
475
+ }
476
+
477
+ let body: Record<string, unknown>;
478
+ if (isNewNonce) {
479
+ body = { replayNonce: headers["replay-nonce"] || undefined };
480
+ } else if (isCertificate) {
481
+ body = {
482
+ chain: text,
483
+ alternates: parseLinkAlternates(headers["link"]),
484
+ };
485
+ } else if (isObject(json)) {
486
+ body = json;
487
+ const location = headers["location"];
488
+ if (location) body = { ...body, location };
489
+ } else {
490
+ // Lenient mode returns a non-object body as read.
491
+ if (!(yield* isStrict)) return json;
492
+ return yield* fail(parseError("Expected a JSON object"));
493
+ }
494
+ // Strict mode (core/response-validation) checks the output schema.
495
+ return yield* validateResponse(outputAst, mapKeys(outputAst, body, "decode"), () =>
496
+ parseError("Response does not match the output schema"),
497
+ );
498
+ }
499
+ });
500
+
501
+ const isObject = (value: unknown): value is Record<string, unknown> =>
502
+ typeof value === "object" && value !== null && !Array.isArray(value);
503
+
504
+ const parseError = (cause: string) =>
505
+ new AcmeParseError({
506
+ body: "[REDACTED]",
507
+ cause,
508
+ });
509
+
510
+ const parseJson = (text: string) =>
511
+ Effect.try({
512
+ try: (): unknown => (text.trim().length > 0 ? JSON.parse(text) : {}),
513
+ catch: () => parseError("Invalid JSON response"),
514
+ });
515
+
516
+ const fail = <E>(error: E) => Effect.fail(error) as Effect.Effect<never, E>;
517
+
518
+ export const AcmeProtocol: Layer.Layer<API.Protocol> = Layer.succeed(
519
+ API.Protocol,
520
+ API.Protocol.of({
521
+ encode: (args) => encode(args) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
522
+ decode: (args) => decode(args) as Effect.Effect<unknown>,
523
+ }),
524
+ );
525
+
526
+ /** Forget cached directories and nonces (tests, CA switches). */
527
+ export const resetProtocolCaches = (): void => {
528
+ directories.clear();
529
+ nonces.clear();
530
+ };
531
+
532
+ /** @internal re-exported for tests */
533
+ export const _internal = { getAnn, Redacted };
package/src/retry.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { type Policy, throttlingFactory, transientFactory } from "@distilled.cloud/core/retry";
2
+ /**
3
+ * ACME retry configuration.
4
+ *
5
+ * Defines the per-SDK `Retry` Context.Service tag that generated operations
6
+ * wire into `API.make({ retry: Retry.Retry })`. Callers can install a
7
+ * blanket retry policy at the layer level and have every ACME call
8
+ * below it pick it up:
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import * as Acme from "@distilled.cloud/acme";
13
+ *
14
+ * myEffect.pipe(Acme.Retry.transient);
15
+ * Effect.provide(myEffect, Layer.succeed(Acme.Retry.Retry, customPolicy));
16
+ * ```
17
+ */
18
+ import * as Context from "effect/Context";
19
+ import * as Effect from "effect/Effect";
20
+ import * as Layer from "effect/Layer";
21
+
22
+ export {
23
+ type Options,
24
+ type Factory,
25
+ type Policy,
26
+ makeDefault,
27
+ jittered,
28
+ capped,
29
+ throttlingOptions,
30
+ transientOptions,
31
+ throttlingFactory,
32
+ transientFactory,
33
+ } from "@distilled.cloud/core/retry";
34
+
35
+ /** Context tag for configuring retry behavior of ACME calls. */
36
+ export class Retry extends Context.Service<Retry, Policy>()("AcmeRetry") {}
37
+
38
+ /** Provides a custom retry policy to every ACME call below it. */
39
+ export const policy = (optionsOrFactory: Policy) =>
40
+ Effect.provide(Layer.succeed(Retry, optionsOrFactory));
41
+
42
+ /** Disables all automatic retries. */
43
+ export const none = Effect.provide(Layer.succeed(Retry, { while: () => false }));
44
+
45
+ /** Apply the throttling retry policy (retries throttling errors indefinitely). */
46
+ export const throttling = policy(throttlingFactory);
47
+
48
+ /** Apply the transient retry policy (retries all transient errors indefinitely). */
49
+ export const transient = policy(transientFactory);