@coffre/client 0.15.0 → 0.16.0

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,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) {
@@ -338,7 +338,7 @@ function oidc(token, name = "oidc") {
338
338
  * longer show it; the platform's store still holds it.
339
339
  */
340
340
  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>`");
341
+ if (code === void 0 || !code.startsWith("coffre_enr_")) throw new Error("enrollment(): no enrollment code: no release issues one yet (docs/workloads.md)");
342
342
  const vars = globalThis.process?.env;
343
343
  for (const [name, value] of Object.entries(vars ?? {})) if (value === code) delete vars[name];
344
344
  return {
@@ -350,36 +350,6 @@ function enrollment(code) {
350
350
  const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
351
351
  //#endregion
352
352
  //#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
353
  const dispatch = (nonces) => ({
384
354
  seq: ++nonces.sent,
385
355
  at: Date.now()
@@ -536,15 +506,10 @@ async function workload(options) {
536
506
  timers[which] = setTimeout(() => void run(), Math.max(0, when - Date.now()));
537
507
  timers[which].unref?.();
538
508
  };
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);
509
+ /** Renew at half-life, or every 30 seconds for an enrollment; prove again at 90% of the way to `notAfter`. */
510
+ const plan = (held) => {
542
511
  const now = Date.now();
543
512
  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
513
  if (!enrolled) at("prove", held.notAfter - (held.notAfter - held.issuedAt) / 10, () => prove().catch(() => void 0));
549
514
  };
550
515
  /** 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 +548,7 @@ async function workload(options) {
583
548
  const { response, body } = await api("/api/auth/workload/renew", held.token);
584
549
  if (response.ok && typeof body?.expiresAt === "string") {
585
550
  held.expiresAt = Date.parse(body.expiresAt);
586
- if (session === held) planRenewal(held);
551
+ if (session === held) at("renew", enrolled ? Date.now() + ENROLLMENT_RENEW_MS : Date.now() + Math.max(1e3, (held.expiresAt - Date.now()) / 2), renew);
587
552
  return;
588
553
  }
589
554
  if (response.status !== 401 && response.status !== 403 || askedNonce(response)) throw new Error(`renewal answered ${response.status}`);
@@ -760,14 +725,15 @@ function surface(core) {
760
725
  const placeUrl = () => `${origin}/use/${placeOf().split("/").map(encodeURIComponent).join("/")}`;
761
726
  const url = (name) => core.places().length === 1 ? `${origin}/use/${encodeURIComponent(name)}` : `${placeUrl()}/${encodeURIComponent(name)}`;
762
727
  /** 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(), {
728
+ const compute = (asked, what) => computed(placeUrl(), { "content-type": "application/json" }, JSON.stringify(asked), what);
729
+ const computed = async (at, headers, sent, what) => {
730
+ const response = await signed(at, {
765
731
  method: "POST",
766
732
  headers: {
767
- "content-type": "application/json",
733
+ ...headers,
768
734
  accept: "application/json"
769
735
  },
770
- body: JSON.stringify(asked)
736
+ body: sent
771
737
  });
772
738
  const body = await response.json().catch(() => null);
773
739
  if (!response.ok || body === null) throw refusal(response.status, body, `coffre ${what} nothing`);
@@ -789,10 +755,11 @@ function surface(core) {
789
755
  return signed(target.href, init);
790
756
  },
791
757
  sign: async (message) => {
792
- const body = await compute({ sign: {
758
+ const bytes = typeof message === "string" ? new TextEncoder().encode(message) : message;
759
+ const body = await (bytes.length > 1048576 ? computed(`${placeUrl()}?sign=${encodeURIComponent(name)}`, { "content-type": "application/octet-stream" }, bytes, "signed") : compute({ sign: {
793
760
  credential: name,
794
- message: bytesOf(message)
795
- } }, "signed");
761
+ message: bytesOf(bytes)
762
+ } }, "signed"));
796
763
  if (typeof body.signature !== "string") throw new Error("coffre signed nothing");
797
764
  return body.signature;
798
765
  },
@@ -801,6 +768,38 @@ function surface(core) {
801
768
  message: bytesOf(message),
802
769
  signature
803
770
  } }, "verified")).valid === true,
771
+ encrypt: async (plaintext, aad) => {
772
+ const body = await compute({ encrypt: {
773
+ credential: name,
774
+ plaintext: bytesOf(plaintext),
775
+ ...aad === void 0 ? {} : { aad: bytesOf(aad) }
776
+ } }, "encrypted");
777
+ const [iv, ciphertext, tag] = [
778
+ body.iv,
779
+ body.ciphertext,
780
+ body.tag
781
+ ].map((part) => typeof part === "string" ? fromBase64url(part) : null);
782
+ if (!iv || !ciphertext || !tag) throw new Error("coffre encrypted nothing");
783
+ return {
784
+ iv,
785
+ ciphertext,
786
+ tag
787
+ };
788
+ },
789
+ decrypt: async ({ iv, ciphertext, tag }, aad) => {
790
+ const body = await compute({ decrypt: {
791
+ credential: name,
792
+ iv: bytesOf(iv),
793
+ ciphertext: bytesOf(ciphertext),
794
+ tag: bytesOf(tag),
795
+ ...aad === void 0 ? {} : { aad: bytesOf(aad) }
796
+ } }, "decrypted");
797
+ if (body.plaintext !== null && typeof body.plaintext !== "string") throw new Error("coffre decrypted nothing");
798
+ if (body.plaintext === null) return null;
799
+ const plaintext = fromBase64url(body.plaintext);
800
+ if (plaintext === null) throw new Error("coffre decrypted nothing: its answer is no base64url");
801
+ return plaintext;
802
+ },
804
803
  presign: async (path, options = {}) => {
805
804
  const body = await compute({ presign: {
806
805
  credential: name,
@@ -1,4 +1,4 @@
1
- import { r as Workload } from "./workload-DwWrQQg1.js";
1
+ import { r as Workload } from "./workload-w5EbGZgy.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-CkZoajvs.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,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,
@@ -201,10 +202,17 @@ interface Workload {
201
202
  interface UsedCredential {
202
203
  /** `<credential's URL>/<path>`, signed: the proxy forwards it to the upstream with the real key. */
203
204
  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. */
205
+ /**
206
+ * 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.
207
+ * 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.
208
+ */
205
209
  sign(message: string | Uint8Array): Promise<string>;
206
210
  /** 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
211
  verify(message: string | Uint8Array, signature: string): Promise<boolean>;
212
+ /** `plaintext` encrypted with a cipher's AES-256-GCM key, which stays in coffre, under `aad` if given and an IV coffre draws. */
213
+ encrypt(plaintext: string | Uint8Array, aad?: string | Uint8Array): Promise<Sealed>;
214
+ /** The plaintext `sealed` holds under the cipher's key and `aad`, or null when it does not decrypt. */
215
+ decrypt(sealed: Sealed, aad?: string | Uint8Array): Promise<Uint8Array | null>;
208
216
  /** A presigned GET or HEAD of `path` under an AWS-signed credential's upstream: the upstream's own URL, for anyone until `expiresAt`. */
209
217
  presign(path: string, options?: {
210
218
  expiresIn?: number;
@@ -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-w5EbGZgy.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-CkZoajvs.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.0",
4
4
  "description": "The coffre API as typed function calls.",
5
5
  "license": "MIT",
6
6
  "repository": {