@coffre/client 0.15.0 → 0.16.1

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.
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { $ as RoleView, A as ConnectedApp, B as InheritResult, C as Api, D as AuthorizationView, E as AuthInfo, F as DryRunOutcome, G as MemberAccess, H as ListedReference, I as DryRunResult, J as PersonalConfig, K as MissingKey, L as EnvironmentView, M as Deletion, N as DeletionResult, O as BindingPlan, P as DismissedKey, Q as RoleImpact, R as IdentityRow, S as AccessValue, T as AuditEntryView, U as Me, V as KeysPlan, W as Member, X as ReferenceView, Y as ProjectSummary, Z as RemovedMember, _ as byFolder, a as Params, at as TokenPlan, b as ageInDays, c as RouteOutput, d as planImport, et as RolesView, f as Unreachable, g as shownMember, h as serviceName, i as ImportAction, it as SetResult, j as Decision, k as BindingView, l as Transport, m as apiMember, n as CoffreClient, nt as SecretVersion, o as RouteInput, ot as TokenRow, p as unreachable, q as OffboardingReport, r as CoffreError, rt as SessionRow, s as RouteKey, st as WorkloadIds, t as ClientOptions, tt as SecretKey, u as createClient, v as foldersOf, w as ApprovalView, x as olderThan, y as runLabel, z as ImpactLine } from "./index-B2UlVqL3.js";
2
- export { type AccessValue, type Api, type ApprovalView, type AuditEntryView, type AuthInfo, type AuthorizationView, type BindingPlan, type BindingView, ClientOptions, CoffreClient, CoffreError, type ConnectedApp, type Decision, type Deletion, type DeletionResult, type DismissedKey, type DryRunOutcome, type DryRunResult, type EnvironmentView, type IdentityRow, type ImpactLine, ImportAction, type InheritResult, type KeysPlan, type ListedReference, type Me, type Member, type MemberAccess, type MissingKey, type OffboardingReport, Params, type PersonalConfig, type ProjectSummary, type ReferenceView, type RemovedMember, type RoleImpact, type RoleView, type RolesView, RouteInput, RouteKey, RouteOutput, type SecretKey, type SecretVersion, type SessionRow, type SetResult, type TokenPlan, type TokenRow, Transport, Unreachable, type WorkloadIds, ageInDays, apiMember, byFolder, createClient, foldersOf, olderThan, planImport, runLabel, serviceName, shownMember, unreachable };
1
+ import { $ as RoleImpact, A as BindingView, B as ImpactLine, C as AccessValue, D as AuthInfo, E as AuditEntryView, F as DismissedKey, G as Member, H as KeysPlan, I as DryRunOutcome, J as OffboardingReport, K as MemberAccess, L as DryRunResult, M as Decision, N as Deletion, O as AuthorizationView, P as DeletionResult, Q as RemovedMember, R as EnvironmentView, S as olderThan, T as ApprovalView, U as ListedReference, V as InheritResult, W as Me, X as ProjectSummary, Y as PersonalConfig, Z as ReferenceView, _ as serviceName, a as Params, at as SetResult, b as foldersOf, c as RouteOutput, ct as WorkloadIds, d as planImport, et as RoleView, f as Unreachable, g as apiMember, h as judgeProofs, i as ImportAction, it as SessionRow, j as ConnectedApp, k as BindingPlan, l as Transport, m as ProofJudgment, n as CoffreClient, nt as SecretKey, o as RouteInput, ot as TokenPlan, p as unreachable, q as MissingKey, r as CoffreError, rt as SecretVersion, s as RouteKey, st as TokenRow, t as ClientOptions, tt as RolesView, u as createClient, v as shownMember, w as Api, x as ageInDays, y as byFolder, z as IdentityRow } from "./index-DZZ3DRTO.js";
2
+ export { type AccessValue, type Api, type ApprovalView, type AuditEntryView, type AuthInfo, type AuthorizationView, type BindingPlan, type BindingView, ClientOptions, CoffreClient, CoffreError, type ConnectedApp, type Decision, type Deletion, type DeletionResult, type DismissedKey, type DryRunOutcome, type DryRunResult, type EnvironmentView, type IdentityRow, type ImpactLine, ImportAction, type InheritResult, type KeysPlan, type ListedReference, type Me, type Member, type MemberAccess, type MissingKey, type OffboardingReport, Params, type PersonalConfig, type ProjectSummary, type ProofJudgment, type ReferenceView, type RemovedMember, type RoleImpact, type RoleView, type RolesView, RouteInput, RouteKey, RouteOutput, type SecretKey, type SecretVersion, type SessionRow, type SetResult, type TokenPlan, type TokenRow, Transport, Unreachable, type WorkloadIds, ageInDays, apiMember, byFolder, createClient, foldersOf, judgeProofs, olderThan, planImport, serviceName, shownMember, unreachable };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as serviceName, c as foldersOf, d as olderThan, f as Unreachable, i as apiMember, l as runLabel, n as createClient, o as shownMember, p as unreachable, r as planImport, s as byFolder, t as CoffreError, u as ageInDays } from "./src-Dwhw_Cc4.js";
2
- export { CoffreError, Unreachable, ageInDays, apiMember, byFolder, createClient, foldersOf, olderThan, planImport, runLabel, serviceName, shownMember, unreachable };
1
+ import { a as apiMember, c as byFolder, d as olderThan, f as Unreachable, i as judgeProofs, l as foldersOf, n as createClient, o as serviceName, p as unreachable, r as planImport, s as shownMember, t as CoffreError, u as ageInDays } from "./src-JtgcfCXD.js";
2
+ export { CoffreError, Unreachable, ageInDays, apiMember, byFolder, createClient, foldersOf, judgeProofs, olderThan, planImport, serviceName, shownMember, unreachable };
package/dist/routes.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Params, o as RouteInput, s as RouteKey } from "./index-B2UlVqL3.js";
1
+ import { a as Params, o as RouteInput, s as RouteKey } from "./index-DZZ3DRTO.js";
2
2
  //#region src/routes.d.ts
3
3
  export type GetKey = Extract<RouteKey, `GET ${string}`>;
4
4
  /** Each GET route, with what to ask it. */
package/dist/routes.js CHANGED
@@ -58,12 +58,6 @@ function getCalls({ places, secrets, members, services }) {
58
58
  detail: "1"
59
59
  }
60
60
  }],
61
- "GET /audit/verification": [{ params: {} }],
62
- "GET /audit/trees": [{ params: {} }],
63
- "GET /audit/reads": [{
64
- params: {},
65
- input: { from: "start" }
66
- }],
67
61
  "GET /audit/keys": [{ params: {} }]
68
62
  };
69
63
  }
@@ -146,11 +140,7 @@ const EVERY_ROUTE = {
146
140
  "GET /apps": true,
147
141
  "DELETE /apps/:id": true,
148
142
  "GET /audit": true,
149
- "GET /audit/verification": true,
150
- "GET /audit/trees": true,
151
- "GET /audit/reads": true,
152
- "GET /audit/keys": true,
153
- "POST /audit/loss": true
143
+ "GET /audit/keys": true
154
144
  };
155
145
  /**
156
146
  * Every route as a method and a URL, each parameter a made-up value: what
@@ -65,23 +65,6 @@ function olderThan(entry, days, now = Date.now()) {
65
65
  return !entry.archived && age !== null && age > days;
66
66
  }
67
67
  //#endregion
68
- //#region src/audit.ts
69
- /** How the audit log's entries are said, to people: by the pages and the CLI alike. */
70
- /**
71
- * The CI run an entry was written for, as its issuer stated it at the
72
- * exchange: `acme/api run 7001 at 3f2a9c1`, a GitLab pipeline, or the
73
- * token's subject. Null for an entry no trust binding's credential wrote.
74
- */
75
- function runLabel(run) {
76
- if (run === null) return null;
77
- const { claims } = run;
78
- const text = (name) => typeof claims[name] === "string" || typeof claims[name] === "number" ? String(claims[name]) : null;
79
- const at = text("sha") === null ? "" : ` at ${text("sha").slice(0, 7)}`;
80
- if (text("repository") !== null && text("run_id") !== null) return `${text("repository")} run ${text("run_id")}${at}`;
81
- if (text("project_path") !== null && text("pipeline_id") !== null) return `${text("project_path")} pipeline ${text("pipeline_id")}${at}`;
82
- return text("sub") === null ? "a CI run" : `CI run ${text("sub")}`;
83
- }
84
- //#endregion
85
68
  //#region src/folders.ts
86
69
  /**
87
70
  * Rows grouped by folder, as every list shows them: those in no folder
@@ -121,6 +104,23 @@ function serviceName(member) {
121
104
  return member.replace(/^(?:service|token):/, "");
122
105
  }
123
106
  //#endregion
107
+ //#region src/proofs.ts
108
+ function judgeProofs(page) {
109
+ const { head, entries } = page;
110
+ const within = (entry) => head !== null && entry.seq < head.size;
111
+ const numbered = entries.filter(within).length;
112
+ const pruned = page.holes !== null && page.holes.length > 0 && page.holes.every((hole) => hole.kept === 0);
113
+ return {
114
+ head,
115
+ numbered,
116
+ proven: entries.filter((entry) => entry.proof === "proven").length,
117
+ failed: entries.filter((entry) => entry.proof === "failed"),
118
+ misplaced: entries.filter((entry) => entry.proof !== "failed" && within(entry) !== (entry.proof === "proven")),
119
+ missing: page.holes,
120
+ racing: numbered === 0 || pruned
121
+ };
122
+ }
123
+ //#endregion
124
124
  //#region src/index.ts
125
125
  /** The API's error shape, `{ error, message }`, with the HTTP status. */
126
126
  var CoffreError = class extends Error {
@@ -128,15 +128,12 @@ var CoffreError = class extends Error {
128
128
  code;
129
129
  /** The vault's own code when it refused: `no_grant`, `removed`, `bulk_limit`, ... */
130
130
  reason;
131
- /** When to ask again, in seconds, when the answer says (`Retry-After`): a 503's, a 429's. */
132
- retryAfter;
133
- constructor(status, code, message, reason, retryAfter) {
131
+ constructor(status, code, message, reason) {
134
132
  super(message);
135
133
  this.name = "CoffreError";
136
134
  this.status = status;
137
135
  this.code = code;
138
136
  this.reason = reason;
139
- this.retryAfter = retryAfter;
140
137
  }
141
138
  };
142
139
  /** `market/prod/KEY` as route parameters. */
@@ -179,7 +176,7 @@ function createClient(options) {
179
176
  const payload = await response.json().catch(() => null);
180
177
  if (!response.ok) {
181
178
  const error = payload;
182
- throw new CoffreError(response.status, typeof error?.error === "string" ? error.error : "http_error", typeof error?.message === "string" ? error.message : `request failed with status ${response.status}`, typeof error?.reason === "string" ? error.reason : void 0, response.headers.get("retry-after") ?? void 0);
179
+ throw new CoffreError(response.status, typeof error?.error === "string" ? error.error : "http_error", typeof error?.message === "string" ? error.message : `request failed with status ${response.status}`, typeof error?.reason === "string" ? error.reason : void 0);
183
180
  }
184
181
  return payload;
185
182
  }
@@ -269,7 +266,7 @@ function createClient(options) {
269
266
  update: (path, patch) => call("PATCH /secrets/:project/:environment/:key", place(path), patch),
270
267
  /**
271
268
  * In a fork, a key back to its parent's value (`true`), its own kept,
272
- * or its own served again (`false`); `from` holds the parent's.
269
+ * or its own served again (`false`); the answer says which, `inherit`.
273
270
  */
274
271
  inherit: (path, inherit) => call("PATCH /secrets/:project/:environment/:key", place(path), { inherit })
275
272
  },
@@ -331,7 +328,7 @@ function createClient(options) {
331
328
  return send(method, `${route}?dryRun=1`, input);
332
329
  },
333
330
  create: (member, input) => call("POST /members/:member/bindings", { member }, input),
334
- /** The service's bindings on an issuer that new keys would replace, and the keys as checked; writes nothing. */
331
+ /** The service's bindings on an issuer that new keys would replace, the keys as checked, and the places they would withhold; writes nothing. */
335
332
  previewKeys: (member, input) => {
336
333
  const [method, route] = address("POST /members/:member/bindings/keys", { member });
337
334
  return send(method, `${route}?dryRun=1`, input);
@@ -347,6 +344,21 @@ function createClient(options) {
347
344
  /** The repositories the deployment's GitHub App is installed on, private ones too; `{ app: null }` without one. */
348
345
  repositories: () => call("GET /workloads/repositories", {})
349
346
  },
347
+ /**
348
+ * Freezes: every use under a target refused from its next request, its
349
+ * sessions kept, until lifted. A target is `instance`, `service:<name>`,
350
+ * `binding:<id>` or `session:<id>`.
351
+ */
352
+ freezes: {
353
+ /** The freezes standing that you may know of: the instance's, and those of the service accounts you manage. */
354
+ list: () => call("GET /freezes", {}),
355
+ freeze: (target, reason) => call("POST /freezes", {}, {
356
+ target,
357
+ reason
358
+ }),
359
+ /** Lifts it; a target that is not frozen stays so. */
360
+ unfreeze: (target) => call("DELETE /freezes/:target", { target })
361
+ },
350
362
  access: {
351
363
  /** What they should hold at each place; the server applies the difference. `null` revokes. */
352
364
  set: (member, access) => call("PATCH /access/:member", { member }, access) },
@@ -454,61 +466,8 @@ set: (member, access) => call("PATCH /access/:member", { member }, access) },
454
466
  },
455
467
  audit: {
456
468
  list: (query = {}) => call("GET /audit", {}, query),
457
- /**
458
- * Whether the log holds, from the newest checkpoint; or, with `from`, a
459
- * stretch of the walk from the first entry: `start`, then each `next`
460
- * until it is null (`verifyWhole`).
461
- */
462
- verify: (query = {}) => call("GET /audit/verification", {}, query),
463
- /**
464
- * The walk from the first entry to the head, a stretch a request, each
465
- * as long as the server walks in one: the first stretch that fails, or
466
- * the last. `onStretch` sees each verdict as it comes.
467
- */
468
- verifyWhole: async (onStretch = () => {}) => {
469
- for (let from = "start";;) {
470
- const verdict = await call("GET /audit/verification", {}, { from });
471
- onStretch(verdict);
472
- if (!verdict.ok || verdict.next === void 0 || verdict.next === null) return verdict;
473
- from = verdict.next;
474
- }
475
- },
476
- /**
477
- * Whether 0.15's log holds (the vault's `verifyTrees`): its newest signed
478
- * checkpoint and every entry since. `kept` false where the instance
479
- * keeps 0.14's log alone, a server older than 0.15 (no such route)
480
- * included.
481
- */
482
- verifyTrees: () => call("GET /audit/trees", {}).catch((error) => {
483
- if (error instanceof CoffreError && error.status === 404) return { kept: false };
484
- throw error;
485
- }),
486
- /**
487
- * The reads the audit pages list held to the uses 0.15's log sealed, a
488
- * stretch a request, from the first to as far as the projector has
489
- * listed: the first stretch that fails, or the last. `kept` false where
490
- * the instance keeps 0.14's log alone, a server older than 0.15 (no
491
- * such route) included.
492
- */
493
- verifyReads: async (onStretch = () => {}) => {
494
- for (let from = "start";;) {
495
- const verdict = await call("GET /audit/reads", {}, { from }).catch((error) => {
496
- if (error instanceof CoffreError && error.status === 404) return { kept: false };
497
- throw error;
498
- });
499
- onStretch(verdict);
500
- if (!verdict.kept || !verdict.ok || verdict.next === null) return verdict;
501
- from = verdict.next;
502
- }
503
- },
504
469
  /** What an escrowed key is checked against: public material, for admins and owners of the whole instance. */
505
- keys: () => call("GET /audit/keys", {}),
506
- /**
507
- * Accept that entries `from` to `to` are lost for good, as an Owner of
508
- * the whole instance: the audit watch's finding, inside the range, stays
509
- * in the log, and its anchor goes on past them.
510
- */
511
- acceptLoss: (range) => call("POST /audit/loss", {}, range)
470
+ keys: () => call("GET /audit/keys", {})
512
471
  }
513
472
  };
514
473
  }
@@ -544,4 +503,4 @@ async function planImport(coffre, path, entries) {
544
503
  };
545
504
  }
546
505
  //#endregion
547
- export { serviceName as a, foldersOf as c, olderThan as d, Unreachable as f, apiMember as i, runLabel as l, createClient as n, shownMember as o, unreachable as p, planImport as r, byFolder as s, CoffreError as t, ageInDays as u };
506
+ export { apiMember as a, byFolder as c, olderThan as d, Unreachable as f, judgeProofs as i, foldersOf as l, createClient as n, serviceName as o, unreachable as p, planImport as r, shownMember as s, CoffreError as t, ageInDays as u };
@@ -1,4 +1,5 @@
1
- import { s as PublicJwk } from "./dpop-CYJtAnvD.js";
1
+ import { n as Sealed } from "./credential-DyAuH0om.js";
2
+ import { c as PublicJwk } from "./dpop-C9EOdNCi.js";
2
3
  //#region src/workload-proofs.d.ts
3
4
  /**
4
5
  * How a workload proves who it is, once per session (docs/design/workload-access.md,
@@ -61,6 +62,8 @@ interface Proof {
61
62
  * has it.
62
63
  */
63
64
  spent?(context: ProofContext): Promise<boolean>;
65
+ /** After the exchange took the proof (200): one whose platform's tokens are each taken once sends it no more. */
66
+ accepted?(): void;
64
67
  }
65
68
  /** `<audience>#jkt=<thumbprint>`: an audience only this key can use (section 4.2). */
66
69
  declare function keyAudience(context: ProofContext): string;
@@ -69,14 +72,16 @@ declare const KUBERNETES_TOKEN = "/var/run/secrets/coffre/token";
69
72
  /**
70
73
  * A Kubernetes projected service account token, read from its file before
71
74
  * each exchange: the pod spec's `serviceAccountToken` with coffre's URL as
72
- * its `audience`. Such a token is spent once used, so a file still holding
73
- * the token this process exchanged last is never sent again: the proof
74
- * waits for the kubelet's next, which it writes at 80% of the token's life,
75
- * watching the file for up to 10 minutes. That is the normal renewal in a
76
- * long-running pod (the session re-proves at 90% of its life, and the
77
- * kubelet's next volume sync can land after that), and so is the other
78
- * case: a restarted process finds the token an earlier one used, which the
79
- * exchange says (`replayed`), and `spent()` waits the same way.
75
+ * its `audience`. Such a token is spent once coffre took it, so a file
76
+ * still holding the token coffre took last (`accepted()`) is never sent
77
+ * again: the proof waits for the kubelet's next, which it writes at 80% of
78
+ * the token's life, watching the file for up to 10 minutes. That is the
79
+ * normal renewal in a long-running pod (the session re-proves at 90% of its
80
+ * life, and the kubelet's next volume sync can land after that), and so is
81
+ * the other case: a restarted process finds the token an earlier one used,
82
+ * which the exchange says (`replayed`), and `spent()` waits the same way.
83
+ * A token coffre did not take (503 while its database is out, a network
84
+ * failure) is not spent: the next try sends it again.
80
85
  */
81
86
  declare function kubernetes(path?: string): Proof;
82
87
  /** AWS credentials, as the AWS SDK's providers give them. */
@@ -201,10 +206,17 @@ interface Workload {
201
206
  interface UsedCredential {
202
207
  /** `<credential's URL>/<path>`, signed: the proxy forwards it to the upstream with the real key. */
203
208
  fetch(path: string, init?: RequestInit): Promise<Response>;
204
- /** A signature by a signer's key, which stays in coffre: a private key's base64url, an HMAC secret's as its `hmac()` writes it. */
209
+ /**
210
+ * A signature by a signer's key, which stays in coffre: a private key's base64url, an HMAC secret's as its `hmac()` writes it.
211
+ * A message past 1 MiB goes raw, its bytes as the body, signed as they come and never held: an `hmac()` signer's whose `maxBytes` takes it.
212
+ */
205
213
  sign(message: string | Uint8Array): Promise<string>;
206
214
  /** Whether `signature`, as its header carried it, is a verifier's HMAC of `message`, an inbound webhook's body as it came: checked without reading its secret. */
207
215
  verify(message: string | Uint8Array, signature: string): Promise<boolean>;
216
+ /** `plaintext` encrypted with a cipher's AES-256-GCM key, which stays in coffre, under `aad` if given and an IV coffre draws. */
217
+ encrypt(plaintext: string | Uint8Array, aad?: string | Uint8Array): Promise<Sealed>;
218
+ /** The plaintext `sealed` holds under the cipher's key and `aad`, or null when it does not decrypt. */
219
+ decrypt(sealed: Sealed, aad?: string | Uint8Array): Promise<Uint8Array | null>;
208
220
  /** A presigned GET or HEAD of `path` under an AWS-signed credential's upstream: the upstream's own URL, for anyone until `expiresAt`. */
209
221
  presign(path: string, options?: {
210
222
  expiresIn?: number;
@@ -1,5 +1,5 @@
1
- import { t as CoffreError } from "./src-Dwhw_Cc4.js";
2
- import { base64url, bodyDigest, bodyLine, contentDigest, createProof, declaredDigest, generateProofKey, thumbprint } from "./dpop.js";
1
+ import { t as CoffreError } from "./src-JtgcfCXD.js";
2
+ import { base64url, bodyDigest, bodyLine, contentDigest, createProof, declaredDigest, fromBase64url, generateProofKey, thumbprint } from "./dpop.js";
3
3
  //#region src/workload-proofs.ts
4
4
  /** `<audience>#jkt=<thumbprint>`: an audience only this key can use (section 4.2). */
5
5
  function keyAudience(context) {
@@ -22,17 +22,21 @@ const KUBERNETES_TOKEN = "/var/run/secrets/coffre/token";
22
22
  /**
23
23
  * A Kubernetes projected service account token, read from its file before
24
24
  * each exchange: the pod spec's `serviceAccountToken` with coffre's URL as
25
- * its `audience`. Such a token is spent once used, so a file still holding
26
- * the token this process exchanged last is never sent again: the proof
27
- * waits for the kubelet's next, which it writes at 80% of the token's life,
28
- * watching the file for up to 10 minutes. That is the normal renewal in a
29
- * long-running pod (the session re-proves at 90% of its life, and the
30
- * kubelet's next volume sync can land after that), and so is the other
31
- * case: a restarted process finds the token an earlier one used, which the
32
- * exchange says (`replayed`), and `spent()` waits the same way.
25
+ * its `audience`. Such a token is spent once coffre took it, so a file
26
+ * still holding the token coffre took last (`accepted()`) is never sent
27
+ * again: the proof waits for the kubelet's next, which it writes at 80% of
28
+ * the token's life, watching the file for up to 10 minutes. That is the
29
+ * normal renewal in a long-running pod (the session re-proves at 90% of its
30
+ * life, and the kubelet's next volume sync can land after that), and so is
31
+ * the other case: a restarted process finds the token an earlier one used,
32
+ * which the exchange says (`replayed`), and `spent()` waits the same way.
33
+ * A token coffre did not take (503 while its database is out, a network
34
+ * failure) is not spent: the next try sends it again.
33
35
  */
34
36
  function kubernetes(path = KUBERNETES_TOKEN) {
35
37
  /** The token this process sent last. */
38
+ let sent = null;
39
+ /** The last token coffre took, or said was spent: never sent again. */
36
40
  let last = null;
37
41
  const read = async () => (await (await import("node:fs/promises")).readFile(path, "utf8")).trim();
38
42
  /** The file's next token once it differs from `last`, polled every second, or null after 10 minutes. */
@@ -55,9 +59,13 @@ function kubernetes(path = KUBERNETES_TOKEN) {
55
59
  });
56
60
  const fresh = token === last || token === "" ? await next(context) : token;
57
61
  if (fresh === null) throw new Error(`the kubelet wrote no new token at ${path} in 10 minutes: check the projected volume and its expirationSeconds`);
58
- return { oidc: last = fresh };
62
+ return { oidc: sent = fresh };
59
63
  },
60
- spent: async (context) => await next(context) !== null
64
+ accepted: () => void (last = sent),
65
+ spent: async (context) => {
66
+ last = sent;
67
+ return await next(context) !== null;
68
+ }
61
69
  };
62
70
  }
63
71
  /** A region as STS's regional hosts name one, in the commercial partition: the exchange takes no other. */
@@ -338,7 +346,7 @@ function oidc(token, name = "oidc") {
338
346
  * longer show it; the platform's store still holds it.
339
347
  */
340
348
  function enrollment(code) {
341
- if (code === void 0 || !code.startsWith("coffre_enr_")) throw new Error("enrollment(): no enrollment code: CI sets one each deploy, from `coffre enroll <service>`");
349
+ if (code === void 0 || !code.startsWith("coffre_enr_")) throw new Error("enrollment(): no enrollment code: no release issues one yet (docs/workloads.md)");
342
350
  const vars = globalThis.process?.env;
343
351
  for (const [name, value] of Object.entries(vars ?? {})) if (value === code) delete vars[name];
344
352
  return {
@@ -350,36 +358,6 @@ function enrollment(code) {
350
358
  const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
351
359
  //#endregion
352
360
  //#region src/workload.ts
353
- /**
354
- * A workload's session with coffre (docs/design/workload-access.md, section
355
- * 9.1): it proves who it is once, gets a session bound to a key that never
356
- * leaves this process, and from then on uses its credentials through coffre,
357
- * every request signed. The app holds no secret that works anywhere else.
358
- *
359
- * import { workload, enrollment } from '@coffre/client/workload';
360
- *
361
- * const coffre = await workload({ url: 'https://secrets.acme.example', service: 'api-prod', proof: enrollment(process.env.COFFRE_ENROLL) });
362
- * const openai = new OpenAI({ apiKey: 'coffre', baseURL: coffre.url('openai'), fetch: coffre.fetch });
363
- * const charge = await coffre.credential('stripe').fetch('/v1/charges', { method: 'POST', body: new URLSearchParams({ amount: '2000' }) });
364
- *
365
- * What it does for the app, so the app does nothing:
366
- *
367
- * - a P-256 key made here, non-extractable; the key, the session's token
368
- * and the gate's nonce live in this closure only, never on disk or in
369
- * the environment;
370
- * - the exchange, retried while an enrollment code is `full` (5 minutes)
371
- * or its session awaits approval (10), and after a spent projected token,
372
- * once the kubelet writes the next;
373
- * - renewal at half-life, every 30 seconds for an enrollment session, whose
374
- * expiry is its liveness, and none for a session already at its hard end
375
- * (a projected token's), which only a new proof outlives; a fresh proof, with the same key, before the
376
- * session's hard end, `notAfter`; and a new session whenever the old one
377
- * is lost (revoked, frozen, expired while the process slept);
378
- * - each request under `<url>/use/` signed whole (method, URL, query, the
379
- * headers it was given, the body), with the newest nonce, and sent again
380
- * once if the gate asks for a fresh one;
381
- * - logout on `close()`, and on SIGTERM.
382
- */
383
361
  const dispatch = (nonces) => ({
384
362
  seq: ++nonces.sent,
385
363
  at: Date.now()
@@ -479,6 +457,7 @@ async function workload(options) {
479
457
  const body = await response.json().catch(() => null);
480
458
  const [expiresAt, notAfter] = [Date.parse(String(body?.expiresAt)), Date.parse(String(body?.notAfter))];
481
459
  if (response.status === 200 && typeof body?.token === "string" && Number.isFinite(expiresAt) && Number.isFinite(notAfter)) {
460
+ options.proof.accepted?.();
482
461
  const places = Array.isArray(body.places) ? body.places.filter((place) => typeof place === "string") : [];
483
462
  return {
484
463
  token: body.token,
@@ -536,15 +515,10 @@ async function workload(options) {
536
515
  timers[which] = setTimeout(() => void run(), Math.max(0, when - Date.now()));
537
516
  timers[which].unref?.();
538
517
  };
539
- /** Renew at half-life, or every 30 seconds for an enrollment, while the session's end can still move: one already at its hard end, as a projected token's is, only the next proof replaces. */
540
- const planRenewal = (held) => {
541
- if (held.expiresAt >= held.notAfter) return clearTimeout(timers.renew);
518
+ /** Renew at half-life, or every 30 seconds for an enrollment; prove again at 90% of the way to `notAfter`. */
519
+ const plan = (held) => {
542
520
  const now = Date.now();
543
521
  at("renew", enrolled ? now + ENROLLMENT_RENEW_MS : now + Math.max(1e3, (held.expiresAt - now) / 2), renew);
544
- };
545
- /** Renew as `planRenewal` says; prove again at 90% of the way to `notAfter`. */
546
- const plan = (held) => {
547
- planRenewal(held);
548
522
  if (!enrolled) at("prove", held.notAfter - (held.notAfter - held.issuedAt) / 10, () => prove().catch(() => void 0));
549
523
  };
550
524
  /** A new session, with a fresh proof and the same key: requests in flight finish on the old one. Retried with backoff while it fails, unless it cannot change. */
@@ -583,7 +557,7 @@ async function workload(options) {
583
557
  const { response, body } = await api("/api/auth/workload/renew", held.token);
584
558
  if (response.ok && typeof body?.expiresAt === "string") {
585
559
  held.expiresAt = Date.parse(body.expiresAt);
586
- if (session === held) planRenewal(held);
560
+ if (session === held) at("renew", enrolled ? Date.now() + ENROLLMENT_RENEW_MS : Date.now() + Math.max(1e3, (held.expiresAt - Date.now()) / 2), renew);
587
561
  return;
588
562
  }
589
563
  if (response.status !== 401 && response.status !== 403 || askedNonce(response)) throw new Error(`renewal answered ${response.status}`);
@@ -760,14 +734,15 @@ function surface(core) {
760
734
  const placeUrl = () => `${origin}/use/${placeOf().split("/").map(encodeURIComponent).join("/")}`;
761
735
  const url = (name) => core.places().length === 1 ? `${origin}/use/${encodeURIComponent(name)}` : `${placeUrl()}/${encodeURIComponent(name)}`;
762
736
  /** What coffre makes with the environment's values, at the environment's URL: a signature, a verdict, a presigned URL, a minted child. */
763
- const compute = async (asked, what) => {
764
- const response = await signed(placeUrl(), {
737
+ const compute = (asked, what) => computed(placeUrl(), { "content-type": "application/json" }, JSON.stringify(asked), what);
738
+ const computed = async (at, headers, sent, what) => {
739
+ const response = await signed(at, {
765
740
  method: "POST",
766
741
  headers: {
767
- "content-type": "application/json",
742
+ ...headers,
768
743
  accept: "application/json"
769
744
  },
770
- body: JSON.stringify(asked)
745
+ body: sent
771
746
  });
772
747
  const body = await response.json().catch(() => null);
773
748
  if (!response.ok || body === null) throw refusal(response.status, body, `coffre ${what} nothing`);
@@ -789,10 +764,11 @@ function surface(core) {
789
764
  return signed(target.href, init);
790
765
  },
791
766
  sign: async (message) => {
792
- const body = await compute({ sign: {
767
+ const bytes = typeof message === "string" ? new TextEncoder().encode(message) : message;
768
+ const body = await (bytes.length > 1048576 ? computed(`${placeUrl()}?sign=${encodeURIComponent(name)}`, { "content-type": "application/octet-stream" }, bytes, "signed") : compute({ sign: {
793
769
  credential: name,
794
- message: bytesOf(message)
795
- } }, "signed");
770
+ message: bytesOf(bytes)
771
+ } }, "signed"));
796
772
  if (typeof body.signature !== "string") throw new Error("coffre signed nothing");
797
773
  return body.signature;
798
774
  },
@@ -801,6 +777,38 @@ function surface(core) {
801
777
  message: bytesOf(message),
802
778
  signature
803
779
  } }, "verified")).valid === true,
780
+ encrypt: async (plaintext, aad) => {
781
+ const body = await compute({ encrypt: {
782
+ credential: name,
783
+ plaintext: bytesOf(plaintext),
784
+ ...aad === void 0 ? {} : { aad: bytesOf(aad) }
785
+ } }, "encrypted");
786
+ const [iv, ciphertext, tag] = [
787
+ body.iv,
788
+ body.ciphertext,
789
+ body.tag
790
+ ].map((part) => typeof part === "string" ? fromBase64url(part) : null);
791
+ if (!iv || !ciphertext || !tag) throw new Error("coffre encrypted nothing");
792
+ return {
793
+ iv,
794
+ ciphertext,
795
+ tag
796
+ };
797
+ },
798
+ decrypt: async ({ iv, ciphertext, tag }, aad) => {
799
+ const body = await compute({ decrypt: {
800
+ credential: name,
801
+ iv: bytesOf(iv),
802
+ ciphertext: bytesOf(ciphertext),
803
+ tag: bytesOf(tag),
804
+ ...aad === void 0 ? {} : { aad: bytesOf(aad) }
805
+ } }, "decrypted");
806
+ if (body.plaintext !== null && typeof body.plaintext !== "string") throw new Error("coffre decrypted nothing");
807
+ if (body.plaintext === null) return null;
808
+ const plaintext = fromBase64url(body.plaintext);
809
+ if (plaintext === null) throw new Error("coffre decrypted nothing: its answer is no base64url");
810
+ return plaintext;
811
+ },
804
812
  presign: async (path, options = {}) => {
805
813
  const body = await compute({ presign: {
806
814
  credential: name,
@@ -1,4 +1,4 @@
1
- import { r as Workload } from "./workload-DwWrQQg1.js";
1
+ import { r as Workload } from "./workload-3gHR2coV.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { Duplex } from "node:stream";
4
4
  //#region src/workload-postgres.d.ts
@@ -25,7 +25,7 @@ export type WebSocketClass = new (url: string, options: {
25
25
  headers: Record<string, string>;
26
26
  }) => TunnelSocket;
27
27
  /**
28
- * A stream to the database behind the tunnel `name`, which the app's driver
28
+ * A stream to the database behind the tunnel `name`, which node-postgres
29
29
  * connects, writes and ends as it would a socket.
30
30
  */
31
31
  export declare function connect(coffre: Workload, name: string, options?: {
@@ -1,19 +1,17 @@
1
- import { i as upgradeRefused, r as upgradeHeaders } from "./workload-BsyIQcko.js";
1
+ import { i as upgradeRefused, r as upgradeHeaders } from "./workload-CizRrO4x.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { Duplex } from "node:stream";
4
4
  //#region src/workload-postgres.ts
5
5
  /**
6
6
  * Postgres from a workload, through coffre's tunnel (docs/design/workload-access.md,
7
- * section 9.1): a stream the app's driver takes as its socket, carried over
8
- * the tunnel's WebSocket and signed by the session. No listener, no password,
7
+ * section 9.1): a stream node-postgres takes as its socket, carried over the
8
+ * tunnel's WebSocket and signed by the session. No listener, no password,
9
9
  * and no database URL in the app: coffre logs in to the database.
10
10
  *
11
- * import postgres from 'postgres';
11
+ * import pg from 'pg';
12
12
  * import { connect } from '@coffre/client/workload/postgres';
13
13
  *
14
- * const sql = postgres({ socket: () => connect(coffre, 'db') });
15
- *
16
- * node-postgres takes it as its stream: `new pg.Pool({ stream: () => connect(coffre, 'db') })`.
14
+ * const pool = new pg.Pool({ stream: () => connect(coffre, 'db') });
17
15
  *
18
16
  * The WebSocket is the runtime's own (`globalThis.WebSocket`: Node 22 and
19
17
  * later, Deno, Bun), which takes the upgrade's headers; on Node 20, pass the
@@ -37,7 +35,7 @@ const FRAME = 65536;
37
35
  /** How often an open connection says it is there, so that an idle one outlives Cloudflare's 100-second timeout. */
38
36
  const KEEPALIVE_MS = 3e4;
39
37
  /**
40
- * A stream to the database behind the tunnel `name`, which the app's driver
38
+ * A stream to the database behind the tunnel `name`, which node-postgres
41
39
  * connects, writes and ends as it would a socket.
42
40
  */
43
41
  function connect(coffre, name, options = {}) {
@@ -1,3 +1,4 @@
1
- import { r as CoffreError } from "./index-B2UlVqL3.js";
2
- import { C as oidc, S as kubernetes, _ as enrollment, a as askedNonce, b as github, c as upgradeRefused, d as KUBERNETES_TOKEN, f as PlatformProof, g as azure, h as aws, i as WorkloadOptions, l as workload, m as ProofContext, n as UsedCredential, o as fromCoffre, p as Proof, r as Workload, s as upgradeHeaders, t as NarrowOptions, u as AwsCredentials, v as fly, w as vercel, x as keyAudience, y as gcp } from "./workload-DwWrQQg1.js";
3
- export { type AwsCredentials, CoffreError, KUBERNETES_TOKEN, NarrowOptions, type PlatformProof, type Proof, type ProofContext, UsedCredential, Workload, WorkloadOptions, askedNonce, aws, azure, enrollment, fly, fromCoffre, gcp, github, keyAudience, kubernetes, oidc, upgradeHeaders, upgradeRefused, vercel, workload };
1
+ import { n as Sealed } from "./credential-DyAuH0om.js";
2
+ import { r as CoffreError } from "./index-DZZ3DRTO.js";
3
+ import { C as oidc, S as kubernetes, _ as enrollment, a as askedNonce, b as github, c as upgradeRefused, d as KUBERNETES_TOKEN, f as PlatformProof, g as azure, h as aws, i as WorkloadOptions, l as workload, m as ProofContext, n as UsedCredential, o as fromCoffre, p as Proof, r as Workload, s as upgradeHeaders, t as NarrowOptions, u as AwsCredentials, v as fly, w as vercel, x as keyAudience, y as gcp } from "./workload-3gHR2coV.js";
4
+ export { type AwsCredentials, CoffreError, KUBERNETES_TOKEN, NarrowOptions, type PlatformProof, type Proof, type ProofContext, type Sealed, UsedCredential, Workload, WorkloadOptions, askedNonce, aws, azure, enrollment, fly, fromCoffre, gcp, github, keyAudience, kubernetes, oidc, upgradeHeaders, upgradeRefused, vercel, workload };
package/dist/workload.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as CoffreError } from "./src-Dwhw_Cc4.js";
2
- import { a as workload, c as azure, d as gcp, f as github, g as vercel, h as oidc, i as upgradeRefused, l as enrollment, m as kubernetes, n as fromCoffre, o as KUBERNETES_TOKEN, p as keyAudience, r as upgradeHeaders, s as aws, t as askedNonce, u as fly } from "./workload-BsyIQcko.js";
1
+ import { t as CoffreError } from "./src-JtgcfCXD.js";
2
+ import { a as workload, c as azure, d as gcp, f as github, g as vercel, h as oidc, i as upgradeRefused, l as enrollment, m as kubernetes, n as fromCoffre, o as KUBERNETES_TOKEN, p as keyAudience, r as upgradeHeaders, s as aws, t as askedNonce, u as fly } from "./workload-CizRrO4x.js";
3
3
  export { CoffreError, KUBERNETES_TOKEN, askedNonce, aws, azure, enrollment, fly, fromCoffre, gcp, github, keyAudience, kubernetes, oidc, upgradeHeaders, upgradeRefused, vercel, workload };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coffre/client",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "description": "The coffre API as typed function calls.",
5
5
  "license": "MIT",
6
6
  "repository": {