@coffre/client 0.14.2 → 0.14.3

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.
@@ -35,10 +35,18 @@ export type ProxiedCredential = {
35
35
  }>;
36
36
  /**
37
37
  * A signature of `message` (a string signs as its UTF-8) by a signer's
38
- * private key, which stays in coffre: what Node's `crypto.sign(undefined,
39
- * message, key)` gives, base64url. Each is one use in coffre's log.
38
+ * key, which stays in coffre: a private key's, what Node's
39
+ * `crypto.sign(undefined, message, key)` gives, base64url, each one use
40
+ * in coffre's log; an HMAC secret's, as its `hmac()` writes it.
40
41
  */
41
42
  sign(message: Uint8Array | string): Promise<string>;
43
+ /**
44
+ * Whether `signature`, as its header carried it (`sha256=…`), is a
45
+ * verifier's HMAC of `message`: an inbound webhook's body, the bytes as
46
+ * they came, never the JSON parsed and written again. The secret stays
47
+ * in coffre, which compares in constant time and says only yes or no.
48
+ */
49
+ verify(message: Uint8Array | string, signature: string): Promise<boolean>;
42
50
  };
43
51
  type Env = Record<string, string | undefined>;
44
52
  /** The credential `name`, as `coffre run` gave the app it; `env` and `fetcher` for tests and odd runtimes. */
@@ -25,6 +25,12 @@ function credential(name, env = globalThis.process?.env ?? {}, fetcher = (input,
25
25
  body: await answer.json()
26
26
  };
27
27
  };
28
+ const bytesOf = (message) => {
29
+ const bytes = typeof message === "string" ? new TextEncoder().encode(message) : message;
30
+ let binary = "";
31
+ for (const byte of bytes) binary += String.fromCharCode(byte);
32
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
33
+ };
28
34
  return {
29
35
  url,
30
36
  fetch: (path, init = {}) => {
@@ -48,15 +54,21 @@ function credential(name, env = globalThis.process?.env ?? {}, fetcher = (input,
48
54
  };
49
55
  },
50
56
  sign: async (message) => {
51
- const bytes = typeof message === "string" ? new TextEncoder().encode(message) : message;
52
- let binary = "";
53
- for (const byte of bytes) binary += String.fromCharCode(byte);
54
57
  const { answer, body } = await compute({ sign: {
55
58
  credential: name,
56
- message: btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
59
+ message: bytesOf(message)
57
60
  } });
58
61
  if (!answer.ok || body.signature === void 0) throw new Error(`coffre signed nothing: ${body.message ?? answer.status}`);
59
62
  return body.signature;
63
+ },
64
+ verify: async (message, signature) => {
65
+ const { answer, body } = await compute({ verify: {
66
+ credential: name,
67
+ message: bytesOf(message),
68
+ signature
69
+ } });
70
+ if (!answer.ok || typeof body.valid !== "boolean") throw new Error(`coffre verified nothing: ${body.message ?? answer.status}`);
71
+ return body.valid;
60
72
  }
61
73
  };
62
74
  }
@@ -444,9 +444,12 @@ async function workload(options) {
444
444
  key,
445
445
  nonces
446
446
  });
447
+ /** How long the last exchange refused was told to wait before asking again (`Retry-After`): the least a retry waits. */
448
+ let toldToWait = 0;
447
449
  /** Trade a fresh proof for a session, waiting out what the design says to wait out; throws a refusal, with the server's words. */
448
450
  const exchange = async () => {
449
451
  const start = Date.now();
452
+ toldToWait = 0;
450
453
  const said = /* @__PURE__ */ new Set();
451
454
  const say = (line) => void (said.has(line) || (said.add(line), log(line)));
452
455
  for (;;) {
@@ -496,6 +499,7 @@ async function workload(options) {
496
499
  continue;
497
500
  }
498
501
  if (reason === "replayed" && options.proof.spent !== void 0 && await options.proof.spent(context)) continue;
502
+ toldToWait = retryAfter(response, 0);
499
503
  throw refusal(response.status, body, `${origin} would not sign ${options.service} in with its ${options.proof.name} proof`);
500
504
  }
501
505
  };
@@ -557,7 +561,7 @@ async function workload(options) {
557
561
  const spent = error instanceof CoffreError && error.reason === "replayed" && options.proof.spent === void 0;
558
562
  if (spent) log(`coffre: ${options.service}'s ${options.proof.name} proof was spent, and it gives no fresh one: the session ends at its expiry`);
559
563
  if (spent || error instanceof CoffreError && FINAL.has(error.reason ?? "")) final = error;
560
- else if (!closed) at("retry", Date.now() + backoff(tries++), () => prove().catch(() => void 0));
564
+ else if (!closed) at("retry", Date.now() + Math.max(backoff(tries++), toldToWait * (1 + Math.random() / 2)), () => prove().catch(() => void 0));
561
565
  throw error;
562
566
  }).finally(() => attempt = null);
563
567
  return attempt;
@@ -201,9 +201,9 @@ interface Workload {
201
201
  interface UsedCredential {
202
202
  /** `<credential's URL>/<path>`, signed: the proxy forwards it to the upstream with the real key. */
203
203
  fetch(path: string, init?: RequestInit): Promise<Response>;
204
- /** A signature by a signer's private key, which stays in coffre: base64url, as `credential.sign` gives. */
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
205
  sign(message: string | Uint8Array): Promise<string>;
206
- /** Whether `signature` is a verifier's over `message`: an inbound webhook's, checked without reading its secret. */
206
+ /** 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
207
  verify(message: string | Uint8Array, signature: string): Promise<boolean>;
208
208
  /** A presigned GET or HEAD of `path` under an AWS-signed credential's upstream: the upstream's own URL, for anyone until `expiresAt`. */
209
209
  presign(path: string, options?: {
@@ -1,4 +1,4 @@
1
- import { r as Workload } from "./workload-Bdav1f7J.js";
1
+ import { r as Workload } from "./workload-DwWrQQg1.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { Duplex } from "node:stream";
4
4
  //#region src/workload-postgres.d.ts
@@ -1,4 +1,4 @@
1
- import { i as upgradeRefused, r as upgradeHeaders } from "./workload-Chp14zs7.js";
1
+ import { i as upgradeRefused, r as upgradeHeaders } from "./workload-BuKb9O4W.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  import { Duplex } from "node:stream";
4
4
  //#region src/workload-postgres.ts
@@ -1,3 +1,3 @@
1
1
  import { r as CoffreError } from "./index-CURF99SB.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-Bdav1f7J.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
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 };
package/dist/workload.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import { t as CoffreError } from "./src-BCKSeCER.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-Chp14zs7.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-BuKb9O4W.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.14.2",
3
+ "version": "0.14.3",
4
4
  "description": "The coffre API as typed function calls.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/credential.ts CHANGED
@@ -27,10 +27,18 @@ export type ProxiedCredential = {
27
27
  presign(path: string, options?: { method?: 'GET' | 'HEAD'; expiresIn?: number; query?: Record<string, string> }): Promise<{ url: string; expiresAt: string }>;
28
28
  /**
29
29
  * A signature of `message` (a string signs as its UTF-8) by a signer's
30
- * private key, which stays in coffre: what Node's `crypto.sign(undefined,
31
- * message, key)` gives, base64url. Each is one use in coffre's log.
30
+ * key, which stays in coffre: a private key's, what Node's
31
+ * `crypto.sign(undefined, message, key)` gives, base64url, each one use
32
+ * in coffre's log; an HMAC secret's, as its `hmac()` writes it.
32
33
  */
33
34
  sign(message: Uint8Array | string): Promise<string>;
35
+ /**
36
+ * Whether `signature`, as its header carried it (`sha256=…`), is a
37
+ * verifier's HMAC of `message`: an inbound webhook's body, the bytes as
38
+ * they came, never the JSON parsed and written again. The secret stays
39
+ * in coffre, which compares in constant time and says only yes or no.
40
+ */
41
+ verify(message: Uint8Array | string, signature: string): Promise<boolean>;
34
42
  };
35
43
 
36
44
  type Env = Record<string, string | undefined>;
@@ -59,7 +67,13 @@ export function credential(
59
67
  headers: { authorization: `Bearer ${handle}`, 'content-type': 'application/json' },
60
68
  body: JSON.stringify(asked),
61
69
  });
62
- return { answer, body: (await answer.json()) as { url?: string; expiresAt?: string; signature?: string; message?: string } };
70
+ return { answer, body: (await answer.json()) as { url?: string; expiresAt?: string; signature?: string; valid?: boolean; message?: string } };
71
+ };
72
+ const bytesOf = (message: Uint8Array | string) => {
73
+ const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;
74
+ let binary = '';
75
+ for (const byte of bytes) binary += String.fromCharCode(byte);
76
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
63
77
  };
64
78
  return {
65
79
  url,
@@ -74,12 +88,14 @@ export function credential(
74
88
  return { url: body.url, expiresAt: body.expiresAt! };
75
89
  },
76
90
  sign: async (message) => {
77
- const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;
78
- let binary = '';
79
- for (const byte of bytes) binary += String.fromCharCode(byte);
80
- const { answer, body } = await compute({ sign: { credential: name, message: btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') } });
91
+ const { answer, body } = await compute({ sign: { credential: name, message: bytesOf(message) } });
81
92
  if (!answer.ok || body.signature === undefined) throw new Error(`coffre signed nothing: ${body.message ?? answer.status}`);
82
93
  return body.signature;
83
94
  },
95
+ verify: async (message, signature) => {
96
+ const { answer, body } = await compute({ verify: { credential: name, message: bytesOf(message), signature } });
97
+ if (!answer.ok || typeof body.valid !== 'boolean') throw new Error(`coffre verified nothing: ${body.message ?? answer.status}`);
98
+ return body.valid;
99
+ },
84
100
  };
85
101
  }
package/src/workload.ts CHANGED
@@ -94,9 +94,9 @@ export interface Workload {
94
94
  export interface UsedCredential {
95
95
  /** `<credential's URL>/<path>`, signed: the proxy forwards it to the upstream with the real key. */
96
96
  fetch(path: string, init?: RequestInit): Promise<Response>;
97
- /** A signature by a signer's private key, which stays in coffre: base64url, as `credential.sign` gives. */
97
+ /** 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. */
98
98
  sign(message: string | Uint8Array): Promise<string>;
99
- /** Whether `signature` is a verifier's over `message`: an inbound webhook's, checked without reading its secret. */
99
+ /** 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. */
100
100
  verify(message: string | Uint8Array, signature: string): Promise<boolean>;
101
101
  /** A presigned GET or HEAD of `path` under an AWS-signed credential's upstream: the upstream's own URL, for anyone until `expiresAt`. */
102
102
  presign(path: string, options?: { expiresIn?: number; method?: 'GET' | 'HEAD'; query?: Record<string, string> }): Promise<{ url: string; expiresAt: string }>;
@@ -164,9 +164,13 @@ export async function workload(options: WorkloadOptions): Promise<Workload> {
164
164
  const enrolled = options.proof.kind === 'enrollment';
165
165
  const api = apiOf({ origin, base, key, nonces });
166
166
 
167
+ /** How long the last exchange refused was told to wait before asking again (`Retry-After`): the least a retry waits. */
168
+ let toldToWait = 0;
169
+
167
170
  /** Trade a fresh proof for a session, waiting out what the design says to wait out; throws a refusal, with the server's words. */
168
171
  const exchange = async (): Promise<Session> => {
169
172
  const start = Date.now();
173
+ toldToWait = 0;
170
174
  const said = new Set<string>();
171
175
  const say = (line: string) => void (said.has(line) || (said.add(line), log(line)));
172
176
  for (;;) {
@@ -201,6 +205,7 @@ export async function workload(options: WorkloadOptions): Promise<Workload> {
201
205
  continue;
202
206
  }
203
207
  if (reason === 'replayed' && options.proof.spent !== undefined && (await options.proof.spent(context))) continue;
208
+ toldToWait = retryAfter(response, 0);
204
209
  throw refusal(response.status, body, `${origin} would not sign ${options.service} in with its ${options.proof.name} proof`);
205
210
  }
206
211
  };
@@ -269,7 +274,8 @@ export async function workload(options: WorkloadOptions): Promise<Workload> {
269
274
  const spent = error instanceof CoffreError && error.reason === 'replayed' && options.proof.spent === undefined;
270
275
  if (spent) log(`coffre: ${options.service}'s ${options.proof.name} proof was spent, and it gives no fresh one: the session ends at its expiry`);
271
276
  if (spent || (error instanceof CoffreError && FINAL.has(error.reason ?? ''))) final = error;
272
- else if (!closed) at('retry', Date.now() + backoff(tries++), () => prove().catch(() => undefined));
277
+ // At least what coffre said, spread past it as the backoff is, so that a fleet refused together does not come back together.
278
+ else if (!closed) at('retry', Date.now() + Math.max(backoff(tries++), toldToWait * (1 + Math.random() / 2)), () => prove().catch(() => undefined));
273
279
  throw error;
274
280
  })
275
281
  .finally(() => (attempt = null));