@coffre/core 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.
Files changed (70) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-CgQTlUMz.js → access-CF8UG59J.js} +70 -95
  3. package/dist/{access-DqLJjnLM.d.ts → access-ERdGGHG7.d.ts} +45 -64
  4. package/dist/access.d.ts +2 -2
  5. package/dist/access.js +2 -2
  6. package/dist/envelope.d.ts +28 -9
  7. package/dist/envelope.js +25 -8
  8. package/dist/identity.d.ts +3 -1018
  9. package/dist/identity.js +885 -623
  10. package/dist/index-DuG9p3GH.d.ts +1233 -0
  11. package/dist/kek.d.ts +10 -16
  12. package/dist/kek.js +26 -41
  13. package/dist/log.d.ts +114 -0
  14. package/dist/log.js +291 -0
  15. package/dist/mcp.d.ts +27 -4
  16. package/dist/mcp.js +31 -10
  17. package/dist/recipe-BgJpmJum.d.ts +128 -0
  18. package/dist/recipe.d.ts +2 -127
  19. package/dist/{registry-D7X-x202.d.ts → registry-B7_LUDsJ.d.ts} +30 -5
  20. package/dist/schemas.d.ts +11 -9
  21. package/dist/schemas.js +16 -14
  22. package/dist/{types-Cp3lB_-W.js → types-DwTO_b4H.js} +17 -5
  23. package/dist/vault.d.ts +1771 -1419
  24. package/dist/vault.js +96 -302
  25. package/dist/{workloads-D049JH0M.d.ts → workloads-CW2dK4AW.d.ts} +1 -9
  26. package/dist/workloads.d.ts +2 -2
  27. package/dist/workloads.js +1 -9
  28. package/package.json +7 -7
  29. package/src/access.ts +63 -95
  30. package/src/changes/access.ts +140 -0
  31. package/src/changes/freezes.ts +40 -0
  32. package/src/changes/mcp.ts +150 -0
  33. package/src/changes/places.ts +219 -0
  34. package/src/changes/secrets.ts +235 -0
  35. package/src/changes/signin.ts +197 -0
  36. package/src/changes/workloads.ts +166 -0
  37. package/src/context.ts +18 -2
  38. package/src/envelope.ts +35 -12
  39. package/src/identity/auth.ts +11 -3
  40. package/src/identity/aws.ts +62 -0
  41. package/src/identity/github-app.ts +45 -24
  42. package/src/identity/index.ts +3 -2
  43. package/src/identity/{profile-rules.ts → profiles.ts} +1 -9
  44. package/src/identity/proofs.ts +306 -0
  45. package/src/identity/signin/config.ts +1 -1
  46. package/src/identity/tokens.ts +10 -3
  47. package/src/identity/verifier.ts +73 -14
  48. package/src/identity/workload-token.ts +4 -0
  49. package/src/identity/workloads.ts +0 -11
  50. package/src/kek/aws-kms.ts +18 -13
  51. package/src/kek/check.ts +16 -46
  52. package/src/kek/index.ts +2 -2
  53. package/src/kek/types.ts +15 -3
  54. package/src/log/index.ts +7 -0
  55. package/src/{audit → log}/tiles.ts +18 -49
  56. package/src/{audit → log}/tree.ts +2 -2
  57. package/src/mcp.ts +36 -9
  58. package/src/schemas.ts +15 -12
  59. package/src/vault.ts +251 -1150
  60. package/dist/merkle.d.ts +0 -456
  61. package/dist/merkle.js +0 -964
  62. package/src/answers.ts +0 -209
  63. package/src/audit/leaf.ts +0 -81
  64. package/src/audit/merkle.ts +0 -13
  65. package/src/audit/note.ts +0 -187
  66. package/src/audit/pair.ts +0 -86
  67. package/src/audit/verify.ts +0 -393
  68. package/src/audit/witness.ts +0 -50
  69. package/src/checkpoint.ts +0 -22
  70. package/src/identity/run-proof.ts +0 -159
package/dist/kek.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as KekProvider, c as WrappedDek, i as KekCancelledError, n as DEK_BYTES, o as KekUnavailableError, r as KekBadClaimError, s as KeyOperation, t as KekRegistry, u as SecretContext } from "./registry-D7X-x202.js";
1
+ import { a as KekProvider, c as KeyOperation, d as SecretContext, i as KekCancelledError, l as WrappedDek, n as DEK_BYTES, o as KekRefusedError, r as KekBadClaimError, s as KekUnavailableError, t as KekRegistry } from "./registry-B7_LUDsJ.js";
2
2
  //#region src/kek/local.d.ts
3
3
  /**
4
4
  * A KEK held in local process memory, loaded from configuration.
@@ -70,25 +70,19 @@ export declare class AwsKmsKekProvider implements KekProvider {
70
70
  }
71
71
  //#endregion
72
72
  //#region src/kek/check.d.ts
73
- /** The action of the vault's entry that holds a vault key's check. */
74
- export declare const KEY_CHECK = "key.check";
75
- /** The known value a check wraps: the size of a data key. */
76
- export declare const KEY_CHECK_VALUE: Buffer;
77
- /** The context a check is wrapped in, which no secret has: the nil UUID throughout. */
78
- export declare const KEY_CHECK_CONTEXT: SecretContext;
79
- /**
80
- * Whether `key`, a local vault key, is the one that wrapped `check`: it
81
- * opens it, under the vault ID the check names, to the known value. The ID
82
- * is bound into the wrap, so a match also says the ID is the escrowed one's.
83
- */
84
- export declare function opensKeyCheck(key: Buffer, check: WrappedDek): Promise<boolean>;
85
- /** The id the log records for entries the app signs with `key`, its APP_KEY. */
86
- export declare function appLogKeyId(key: Uint8Array): string;
87
73
  /**
88
74
  * The signing key a local vault key stands for, when the vault is given
89
75
  * none: HKDF-SHA-256 of the key. The vault MACs its log entries and member
90
76
  * rows with what it derives from this one (`vaultLogKey` in @coffre/vault).
91
77
  */
92
78
  export declare function derivedSigningKey(kek: Uint8Array): Buffer;
79
+ /**
80
+ * A signing key's check, hex: HKDF-SHA-256 of the key under a label of its
81
+ * own, as the vault's other keys are each derived from it under theirs
82
+ * (`keyOf` in @coffre/vault), so the check opens, signs and names nothing.
83
+ * Whoever holds a key tells whether it is the vault's by computing its
84
+ * check; whoever holds only the check learns nothing of the key.
85
+ */
86
+ export declare function keyCheckOf(seed: Uint8Array): string;
93
87
  //#endregion
94
- export { type AwsCredentials, type AwsKmsOptions, DEK_BYTES, KekBadClaimError, KekCancelledError, type KekProvider, KekRegistry, KekUnavailableError, type KeyOperation, type WrappedDek };
88
+ export { type AwsCredentials, type AwsKmsOptions, DEK_BYTES, KekBadClaimError, KekCancelledError, type KekProvider, KekRefusedError, KekRegistry, KekUnavailableError, type KeyOperation, type WrappedDek };
package/dist/kek.js CHANGED
@@ -1,5 +1,4 @@
1
- import { deriveLogKey } from "./audit.js";
2
- import { i as KekUnavailableError, n as KekBadClaimError, o as checkContext, r as KekCancelledError, s as encodeAad, t as DEK_BYTES } from "./types-Cp3lB_-W.js";
1
+ import { a as KekUnavailableError, c as encodeAad, i as KekRefusedError, n as KekBadClaimError, r as KekCancelledError, s as checkContext, t as DEK_BYTES } from "./types-DwTO_b4H.js";
3
2
  import { createCipheriv, createDecipheriv, createHash, createHmac, createSecretKey, hkdfSync, randomBytes, timingSafeEqual } from "node:crypto";
4
3
  //#region src/kek/cancellation.ts
5
4
  function checkOperation(operation, uncertain = false) {
@@ -312,11 +311,11 @@ var AwsKmsKekProvider = class {
312
311
  CiphertextBlob: base64(wrapped.bytes),
313
312
  EncryptionContext: encryptionContext(ctx)
314
313
  }, operation);
315
- if (KeyId !== this.keyId) throw new KekUnavailableError(`KMS decrypted under ${KeyId}, not ${this.keyId}`, true);
314
+ if (KeyId !== this.keyId) throw new KekRefusedError(`KMS decrypted under ${KeyId}, not ${this.keyId}`, true);
316
315
  const dek = Buffer.from(Plaintext, "base64");
317
316
  if (dek.length !== 32) {
318
317
  dek.fill(0);
319
- throw new KekUnavailableError("unwrapped DEK has the wrong length", true);
318
+ throw new KekRefusedError("unwrapped DEK has the wrong length", true);
320
319
  }
321
320
  return dek;
322
321
  }
@@ -324,7 +323,9 @@ var AwsKmsKekProvider = class {
324
323
  * One KMS call, tried up to three times while KMS throttles, fails on its
325
324
  * side or does not answer. Every failure but a ciphertext that does not
326
325
  * open is a `KekUnavailableError`, retried or not: a key KMS will not use
327
- * or credentials it refuses say nothing about the claim either.
326
+ * or credentials it refuses say nothing about the claim either. What KMS
327
+ * answered and will answer again, such as `AccessDeniedException` or
328
+ * `DisabledException`, is a `KekRefusedError`, which only its operator mends.
328
329
  */
329
330
  async #call(action, request, operation) {
330
331
  const body = JSON.stringify(request);
@@ -351,7 +352,7 @@ var AwsKmsKekProvider = class {
351
352
  if (uncertain) throw new KekUnavailableError(`KMS ${action}: ${answer.type} after an unanswered request`, true);
352
353
  throw new KekBadClaimError(`KMS ${action}: ${answer.type}`);
353
354
  }
354
- if (!answer.retry || attempt === ATTEMPTS) throw new KekUnavailableError(`KMS ${action} failed${attempt > 1 ? ` ${attempt} times` : ""}: ${answer.failure}`, uncertain);
355
+ if (!answer.retry || attempt === ATTEMPTS) throw new (answer.refused ? KekRefusedError : KekUnavailableError)(`KMS ${action} failed${attempt > 1 ? ` ${attempt} times` : ""}: ${answer.failure}`, uncertain);
355
356
  try {
356
357
  await delay(100 * 4 ** (attempt - 1) * (1 + Math.random()), signal);
357
358
  } catch (error) {
@@ -394,6 +395,7 @@ var AwsKmsKekProvider = class {
394
395
  type: "network",
395
396
  failure: messageOf(error),
396
397
  retry: sent,
398
+ refused: false,
397
399
  uncertain: sent
398
400
  };
399
401
  }
@@ -404,16 +406,19 @@ var AwsKmsKekProvider = class {
404
406
  type: "malformed",
405
407
  failure: `KMS answered ${response.status} without a result`,
406
408
  retry: true,
409
+ refused: false,
407
410
  uncertain: true
408
411
  };
409
412
  }
410
413
  const type = (response.headers.get("x-amzn-errortype") ?? (typeof parsed?.__type === "string" ? parsed.__type : "")).split(":")[0].split("#").pop() || `HTTP ${response.status}`;
411
414
  const message = parsed?.message ?? parsed?.Message;
415
+ const retry = response.status >= 500 || response.status === 429 || type === "ThrottlingException";
412
416
  return {
413
417
  type,
414
418
  failure: `${type}${typeof message === "string" ? `, ${message}` : ""}`,
415
419
  uncertain: false,
416
- retry: response.status >= 500 || response.status === 429 || type === "ThrottlingException"
420
+ retry,
421
+ refused: !retry
417
422
  };
418
423
  }
419
424
  };
@@ -428,7 +433,9 @@ function encryptionContext(ctx) {
428
433
  "coffre:environment": ctx.environmentId,
429
434
  "coffre:secret": ctx.secretId,
430
435
  ...ctx.owner === void 0 ? {} : { "coffre:owner": ctx.owner },
431
- ...ctx.sensitive === true ? { "coffre:sensitive": "true" } : {}
436
+ ...ctx.sensitive === true ? { "coffre:sensitive": "true" } : {},
437
+ ...ctx.plain === true ? { "coffre:plain": "true" } : {},
438
+ ...ctx.version === void 0 ? {} : { "coffre:version": String(ctx.version) }
432
439
  };
433
440
  }
434
441
  /**
@@ -488,38 +495,6 @@ var Slots = class {
488
495
  };
489
496
  //#endregion
490
497
  //#region src/kek/check.ts
491
- /** The action of the vault's entry that holds a vault key's check. */
492
- const KEY_CHECK = "key.check";
493
- /** The known value a check wraps: the size of a data key. */
494
- const KEY_CHECK_VALUE = createHash("sha256").update("coffre.kek.check.v1").digest();
495
- const NIL = "00000000-0000-0000-0000-000000000000";
496
- /** The context a check is wrapped in, which no secret has: the nil UUID throughout. */
497
- const KEY_CHECK_CONTEXT = {
498
- projectId: NIL,
499
- environmentId: NIL,
500
- secretId: NIL
501
- };
502
- /**
503
- * Whether `key`, a local vault key, is the one that wrapped `check`: it
504
- * opens it, under the vault ID the check names, to the known value. The ID
505
- * is bound into the wrap, so a match also says the ID is the escrowed one's.
506
- */
507
- async function opensKeyCheck(key, check) {
508
- if (check.kekProvider !== "local" || key.length !== 32) return false;
509
- try {
510
- const value = await new LocalKekProvider(key, check.kekId, check.kekVersion).unwrap(check, KEY_CHECK_CONTEXT);
511
- const right = equalBytes(value, KEY_CHECK_VALUE);
512
- value.fill(0);
513
- return right;
514
- } catch (error) {
515
- if (error instanceof KekBadClaimError) return false;
516
- throw error;
517
- }
518
- }
519
- /** The id the log records for entries the app signs with `key`, its APP_KEY. */
520
- function appLogKeyId(key) {
521
- return deriveLogKey("app", key).keyId;
522
- }
523
498
  /** The label no other use of a vault key shares: a local vault key is otherwise only ever an AES-256-GCM key. */
524
499
  const SIGNING_KEY_LABEL = "coffre.vault.signing-key.v1";
525
500
  /**
@@ -530,5 +505,15 @@ const SIGNING_KEY_LABEL = "coffre.vault.signing-key.v1";
530
505
  function derivedSigningKey(kek) {
531
506
  return Buffer.from(hkdfSync("sha256", kek, /* @__PURE__ */ new Uint8Array(0), SIGNING_KEY_LABEL, 32));
532
507
  }
508
+ /**
509
+ * A signing key's check, hex: HKDF-SHA-256 of the key under a label of its
510
+ * own, as the vault's other keys are each derived from it under theirs
511
+ * (`keyOf` in @coffre/vault), so the check opens, signs and names nothing.
512
+ * Whoever holds a key tells whether it is the vault's by computing its
513
+ * check; whoever holds only the check learns nothing of the key.
514
+ */
515
+ function keyCheckOf(seed) {
516
+ return Buffer.from(hkdfSync("sha256", seed, /* @__PURE__ */ new Uint8Array(0), "coffre.vault.key-check.v2", 32)).toString("hex");
517
+ }
533
518
  //#endregion
534
- export { AwsKmsKekProvider, DEK_BYTES, KEY_CHECK, KEY_CHECK_CONTEXT, KEY_CHECK_VALUE, KekBadClaimError, KekCancelledError, KekRegistry, KekUnavailableError, LocalKekProvider, appLogKeyId, awsKms, derivedSigningKey, equalBytes, opensKeyCheck };
519
+ export { AwsKmsKekProvider, DEK_BYTES, KekBadClaimError, KekCancelledError, KekRefusedError, KekRegistry, KekUnavailableError, LocalKekProvider, awsKms, derivedSigningKey, equalBytes, keyCheckOf };
package/dist/log.d.ts ADDED
@@ -0,0 +1,114 @@
1
+ //#region src/log/tree.d.ts
2
+ /**
3
+ * RFC 9162's Merkle tree (Certificate Transparency 2.0, the same tree as RFC
4
+ * 6962), byte for byte: a leaf hashes as SHA-256(0x00 || data), a node as
5
+ * SHA-256(0x01 || left || right), and a tree of n leaves splits at the largest
6
+ * power of two below n. The tests hold it to heads, proofs and tiles that
7
+ * Go's golang.org/x/mod/sumdb/tlog computed (test/vectors/log-tree-go.json).
8
+ *
9
+ * Every hash here comes from `Nodes`, which answers for perfect subtrees only
10
+ * (2^level leaves starting at leaf index·2^level). Tiles store those; a proof
11
+ * never needs another kind.
12
+ *
13
+ * Sizes and indexes are plain numbers: exact to 2^53 leaves, 285,000 years at
14
+ * 1,000 a second. No bitwise operator touches them, since JavaScript's cut to
15
+ * 32 bits, and a log passes 2^32 leaves in 50 days at that rate.
16
+ */
17
+ export type Hash = Buffer;
18
+ export declare const HASH_SIZE = 32;
19
+ export declare function leafHash(data: Uint8Array): Hash;
20
+ export declare function nodeHash(left: Hash, right: Hash): Hash;
21
+ /** The head of the empty tree: SHA-256 of nothing. */
22
+ export declare const EMPTY_ROOT: Hash;
23
+ /** The hash of the perfect subtree of 2^level leaves starting at leaf index·2^level. */
24
+ export type Nodes = (level: number, index: number) => Hash;
25
+ export declare const isPowerOfTwo: (n: number) => boolean;
26
+ /** MTH(D[start:start+n]): the hash of any range, from the perfect subtrees it decomposes into. */
27
+ export declare function rangeHash(nodes: Nodes, start: number, n: number): Hash;
28
+ /** The tree head: MTH of the first `size` leaves. */
29
+ export declare function treeHash(nodes: Nodes, size: number): Hash;
30
+ /** RFC 9162 2.1.3.1, PATH(m, D[n]): the inclusion proof of leaf m in the tree of n leaves, leaf to root. */
31
+ export declare function inclusionProof(nodes: Nodes, m: number, n: number): Hash[];
32
+ /** RFC 9162 2.1.4.1, PROOF(m, D[n]): that the tree of m leaves is a prefix of the tree of n. */
33
+ export declare function consistencyProof(nodes: Nodes, m: number, n: number): Hash[];
34
+ /** RFC 9162 2.1.3.2: whether `proof` shows `leaf` at index m of the tree of n leaves whose head is `root`. */
35
+ export declare function verifyInclusion(leaf: Hash, m: number, n: number, proof: readonly Hash[], root: Hash): boolean;
36
+ /** RFC 9162 2.1.4.2: whether `proof` shows the tree of m leaves (head `first`) a prefix of the tree of n (head `second`). */
37
+ export declare function verifyConsistency(m: number, n: number, first: Hash, second: Hash, proof: readonly Hash[]): boolean;
38
+ //#endregion
39
+ //#region src/log/tiles.d.ts
40
+ /**
41
+ * The tree's storage (docs/design/0.16.md, `log_tiles`): tiles, as Go's sumdb
42
+ * and C2SP tlog-tiles lay them out, of height 8. The tile at (level t, index
43
+ * i) holds up to 256 hashes: the nodes at tree level 8t numbered i·256
44
+ * onwards, concatenated. A level-0 tile holds leaf hashes; a level-1 tile,
45
+ * the roots of 256-leaf subtrees; and so on. Any perfect subtree's hash is in
46
+ * one tile or is at most 128 hashes away from one, so a proof reads at most
47
+ * two tiles per level of tiles, the entry's and the right edge's: 7 at 2^32
48
+ * leaves.
49
+ *
50
+ * A tile's hashes never change once written, only grow (the partial tile at
51
+ * the tree's right edge), so a tile is read for any older tree size by taking
52
+ * its prefix.
53
+ *
54
+ * Pruning a tree deletes level-0 tiles from its start, whole, with the 256
55
+ * entries each stands for. The level-1 tile above keeps each one's root, so
56
+ * the head still covers the pruned entries, and every entry that is kept
57
+ * proves from tiles that are kept.
58
+ *
59
+ * A full verify of a pruned tree is `Edge.load` at the first kept entry, then
60
+ * `append` of every kept entry's hash, which must arrive at the signed head.
61
+ * `nodesFrom` cannot do it: it answers for a block of 256 from the tile above
62
+ * and never reads the block's own hashes.
63
+ */
64
+ export declare const HEIGHT = 8;
65
+ export declare const WIDTH = 256;
66
+ export type TileKey = {
67
+ level: number;
68
+ index: number;
69
+ };
70
+ export type Tile = TileKey & {
71
+ hashes: Buffer;
72
+ };
73
+ export declare const tileKey: (level: number, index: number) => string;
74
+ /** Which tile, and where in it, holds what node (level, index) is computed from. */
75
+ export declare function tileOf(level: number, index: number): {
76
+ tile: TileKey;
77
+ offset: number;
78
+ count: number;
79
+ };
80
+ /** A `Nodes` over a set of tiles, keyed by `tileKey`: each node from the hashes of its tile. */
81
+ export declare function nodesFrom(tiles: ReadonlyMap<string, Buffer>): Nodes;
82
+ /** The tiles a computation over `Nodes` reads: run it once against a recorder, then fetch them all in one query. */
83
+ export declare function tilesFor(compute: (nodes: Nodes) => unknown): TileKey[];
84
+ export declare function tileMap(tiles: readonly Tile[]): Map<string, Buffer>;
85
+ /** The tiles at the right edge of a tree of `size` leaves, one per level, with their widths: all the state appending needs. */
86
+ export declare function edgeOf(size: number): (TileKey & {
87
+ width: number;
88
+ })[];
89
+ /**
90
+ * The tree's growing edge, in memory: the partial tile at each level.
91
+ * Appending leaves fills level 0; each tile that fills up pushes its root into
92
+ * the level above. What changed comes back as tiles to write: every tile
93
+ * filled, and every partial edge tile that grew.
94
+ */
95
+ export declare class Edge {
96
+ size: number;
97
+ private tiles;
98
+ private constructor();
99
+ static empty(): Edge;
100
+ /** From the stored edge tiles of a tree of `size` leaves (`edgeOf(size)`), each cut to its width. */
101
+ static load(size: number, stored: ReadonlyMap<string, Buffer>): Edge;
102
+ /** A copy to append to, so a failed write leaves this edge at the head it was. */
103
+ clone(): Edge;
104
+ append(leaves: readonly Hash[]): Tile[];
105
+ /** The tree head now. */
106
+ root(): Hash;
107
+ /**
108
+ * The tile at the right edge of each level, as it stands. With the tiles an append filled, they hold every node a
109
+ * proof of a leaf that append added reads: the tile of the leaf's ancestor at each level is one of them, and so is
110
+ * every tile to its right.
111
+ */
112
+ edgeTiles(): Tile[];
113
+ }
114
+ //#endregion
package/dist/log.js ADDED
@@ -0,0 +1,291 @@
1
+ import { createHash } from "node:crypto";
2
+ //#region src/log/tree.ts
3
+ const HASH_SIZE = 32;
4
+ const LEAF = Buffer.from([0]);
5
+ const NODE = Buffer.from([1]);
6
+ function leafHash(data) {
7
+ return createHash("sha256").update(LEAF).update(data).digest();
8
+ }
9
+ function nodeHash(left, right) {
10
+ return createHash("sha256").update(NODE).update(left).update(right).digest();
11
+ }
12
+ /** The head of the empty tree: SHA-256 of nothing. */
13
+ const EMPTY_ROOT = createHash("sha256").digest();
14
+ /** The largest power of two strictly below n (n ≥ 2). */
15
+ function split(n) {
16
+ let k = 1;
17
+ while (k * 2 < n) k *= 2;
18
+ return k;
19
+ }
20
+ const log2 = (n) => Math.round(Math.log2(n));
21
+ const isPowerOfTwo = (n) => n > 0 && 2 ** log2(n) === n;
22
+ /** MTH(D[start:start+n]): the hash of any range, from the perfect subtrees it decomposes into. */
23
+ function rangeHash(nodes, start, n) {
24
+ if (n === 0) return EMPTY_ROOT;
25
+ if (isPowerOfTwo(n) && start % n === 0) return nodes(log2(n), start / n);
26
+ const k = split(n);
27
+ return nodeHash(rangeHash(nodes, start, k), rangeHash(nodes, start + k, n - k));
28
+ }
29
+ /** The tree head: MTH of the first `size` leaves. */
30
+ function treeHash(nodes, size) {
31
+ return rangeHash(nodes, 0, size);
32
+ }
33
+ /** RFC 9162 2.1.3.1, PATH(m, D[n]): the inclusion proof of leaf m in the tree of n leaves, leaf to root. */
34
+ function inclusionProof(nodes, m, n) {
35
+ if (!Number.isSafeInteger(m) || m < 0 || m >= n) throw new Error(`leaf ${m} is not in a tree of ${n}`);
36
+ const path = [];
37
+ const walk = (m, start, n) => {
38
+ if (n === 1) return;
39
+ const k = split(n);
40
+ if (m < k) {
41
+ walk(m, start, k);
42
+ path.push(rangeHash(nodes, start + k, n - k));
43
+ } else {
44
+ walk(m - k, start + k, n - k);
45
+ path.push(rangeHash(nodes, start, k));
46
+ }
47
+ };
48
+ walk(m, 0, n);
49
+ return path;
50
+ }
51
+ /** RFC 9162 2.1.4.1, PROOF(m, D[n]): that the tree of m leaves is a prefix of the tree of n. */
52
+ function consistencyProof(nodes, m, n) {
53
+ if (!Number.isSafeInteger(m) || m < 0 || m > n) throw new Error(`no consistency from ${m} to ${n}`);
54
+ if (m === 0 || m === n) return [];
55
+ const path = [];
56
+ const sub = (m, start, n, whole) => {
57
+ if (m === n) {
58
+ if (!whole) path.push(rangeHash(nodes, start, n));
59
+ return;
60
+ }
61
+ const k = split(n);
62
+ if (m <= k) {
63
+ sub(m, start, k, whole);
64
+ path.push(rangeHash(nodes, start + k, n - k));
65
+ } else {
66
+ sub(m - k, start + k, n - k, false);
67
+ path.push(rangeHash(nodes, start, k));
68
+ }
69
+ };
70
+ sub(m, 0, n, true);
71
+ return path;
72
+ }
73
+ /** RFC 9162 2.1.3.2: whether `proof` shows `leaf` at index m of the tree of n leaves whose head is `root`. */
74
+ function verifyInclusion(leaf, m, n, proof, root) {
75
+ if (!Number.isSafeInteger(m) || !Number.isSafeInteger(n) || m < 0 || m >= n) return false;
76
+ let fn = m;
77
+ let sn = n - 1;
78
+ let r = leaf;
79
+ for (const p of proof) {
80
+ if (sn === 0) return false;
81
+ if (fn % 2 === 1 || fn === sn) {
82
+ r = nodeHash(p, r);
83
+ if (fn % 2 === 0) while (fn % 2 === 0 && fn !== 0) {
84
+ fn = Math.floor(fn / 2);
85
+ sn = Math.floor(sn / 2);
86
+ }
87
+ } else r = nodeHash(r, p);
88
+ fn = Math.floor(fn / 2);
89
+ sn = Math.floor(sn / 2);
90
+ }
91
+ return sn === 0 && r.equals(root);
92
+ }
93
+ /** RFC 9162 2.1.4.2: whether `proof` shows the tree of m leaves (head `first`) a prefix of the tree of n (head `second`). */
94
+ function verifyConsistency(m, n, first, second, proof) {
95
+ if (!Number.isSafeInteger(m) || !Number.isSafeInteger(n) || m < 0 || m > n) return false;
96
+ if (m === 0) return proof.length === 0 && first.equals(EMPTY_ROOT) && (n > 0 || second.equals(EMPTY_ROOT));
97
+ if (m === n) return proof.length === 0 && first.equals(second);
98
+ const path = isPowerOfTwo(m) ? [first, ...proof] : [...proof];
99
+ if (path.length === 0) return false;
100
+ let fn = m - 1;
101
+ let sn = n - 1;
102
+ while (fn % 2 === 1) {
103
+ fn = Math.floor(fn / 2);
104
+ sn = Math.floor(sn / 2);
105
+ }
106
+ let fr = path[0];
107
+ let sr = path[0];
108
+ for (const c of path.slice(1)) {
109
+ if (sn === 0) return false;
110
+ if (fn % 2 === 1 || fn === sn) {
111
+ fr = nodeHash(c, fr);
112
+ sr = nodeHash(c, sr);
113
+ if (fn % 2 === 0) while (fn % 2 === 0 && fn !== 0) {
114
+ fn = Math.floor(fn / 2);
115
+ sn = Math.floor(sn / 2);
116
+ }
117
+ } else sr = nodeHash(sr, c);
118
+ fn = Math.floor(fn / 2);
119
+ sn = Math.floor(sn / 2);
120
+ }
121
+ return sn === 0 && fr.equals(first) && sr.equals(second);
122
+ }
123
+ //#endregion
124
+ //#region src/log/tiles.ts
125
+ /**
126
+ * The tree's storage (docs/design/0.16.md, `log_tiles`): tiles, as Go's sumdb
127
+ * and C2SP tlog-tiles lay them out, of height 8. The tile at (level t, index
128
+ * i) holds up to 256 hashes: the nodes at tree level 8t numbered i·256
129
+ * onwards, concatenated. A level-0 tile holds leaf hashes; a level-1 tile,
130
+ * the roots of 256-leaf subtrees; and so on. Any perfect subtree's hash is in
131
+ * one tile or is at most 128 hashes away from one, so a proof reads at most
132
+ * two tiles per level of tiles, the entry's and the right edge's: 7 at 2^32
133
+ * leaves.
134
+ *
135
+ * A tile's hashes never change once written, only grow (the partial tile at
136
+ * the tree's right edge), so a tile is read for any older tree size by taking
137
+ * its prefix.
138
+ *
139
+ * Pruning a tree deletes level-0 tiles from its start, whole, with the 256
140
+ * entries each stands for. The level-1 tile above keeps each one's root, so
141
+ * the head still covers the pruned entries, and every entry that is kept
142
+ * proves from tiles that are kept.
143
+ *
144
+ * A full verify of a pruned tree is `Edge.load` at the first kept entry, then
145
+ * `append` of every kept entry's hash, which must arrive at the signed head.
146
+ * `nodesFrom` cannot do it: it answers for a block of 256 from the tile above
147
+ * and never reads the block's own hashes.
148
+ */
149
+ const HEIGHT = 8;
150
+ const WIDTH = 256;
151
+ const tileKey = (level, index) => `${level}/${index}`;
152
+ /** Which tile, and where in it, holds what node (level, index) is computed from. */
153
+ function tileOf(level, index) {
154
+ const t = Math.floor(level / 8);
155
+ const count = 2 ** (level - t * 8);
156
+ const first = index * count;
157
+ return {
158
+ tile: {
159
+ level: t,
160
+ index: Math.floor(first / 256)
161
+ },
162
+ offset: first % 256,
163
+ count
164
+ };
165
+ }
166
+ /** A `Nodes` over a set of tiles, keyed by `tileKey`: each node from the hashes of its tile. */
167
+ function nodesFrom(tiles) {
168
+ return (level, index) => {
169
+ const { tile, offset, count } = tileOf(level, index);
170
+ const hashes = tiles.get(tileKey(tile.level, tile.index));
171
+ if (hashes === void 0 || hashes.length < (offset + count) * 32) throw new Error(`tile ${tile.level}/${tile.index} lacks node ${level}/${index}`);
172
+ const layer = [];
173
+ for (let i = 0; i < count; i += 1) layer.push(hashes.subarray((offset + i) * 32, (offset + i + 1) * 32));
174
+ return hashUp(layer);
175
+ };
176
+ }
177
+ /** The root of a perfect subtree from its 2^k bottom hashes. */
178
+ function hashUp(hashes) {
179
+ let layer = hashes;
180
+ while (layer.length > 1) {
181
+ const up = [];
182
+ for (let i = 0; i < layer.length; i += 2) up.push(nodeHash(layer[i], layer[i + 1]));
183
+ layer = up;
184
+ }
185
+ return Buffer.from(layer[0]);
186
+ }
187
+ /** The tiles a computation over `Nodes` reads: run it once against a recorder, then fetch them all in one query. */
188
+ function tilesFor(compute) {
189
+ const seen = /* @__PURE__ */ new Map();
190
+ compute((level, index) => {
191
+ const { tile } = tileOf(level, index);
192
+ seen.set(tileKey(tile.level, tile.index), tile);
193
+ return Buffer.alloc(32);
194
+ });
195
+ return [...seen.values()];
196
+ }
197
+ function tileMap(tiles) {
198
+ return new Map(tiles.map((t) => [tileKey(t.level, t.index), t.hashes]));
199
+ }
200
+ /** The tiles at the right edge of a tree of `size` leaves, one per level, with their widths: all the state appending needs. */
201
+ function edgeOf(size) {
202
+ const edge = [];
203
+ for (let t = 0;; t += 1) {
204
+ const below = Math.floor(size / 2 ** (t * 8));
205
+ edge.push({
206
+ level: t,
207
+ index: Math.floor(below / 256),
208
+ width: below % 256
209
+ });
210
+ if (below < 256) return edge;
211
+ }
212
+ }
213
+ /**
214
+ * The tree's growing edge, in memory: the partial tile at each level.
215
+ * Appending leaves fills level 0; each tile that fills up pushes its root into
216
+ * the level above. What changed comes back as tiles to write: every tile
217
+ * filled, and every partial edge tile that grew.
218
+ */
219
+ var Edge = class Edge {
220
+ size;
221
+ tiles;
222
+ constructor(size, tiles) {
223
+ this.size = size;
224
+ this.tiles = tiles;
225
+ }
226
+ static empty() {
227
+ return new Edge(0, [[]]);
228
+ }
229
+ /** From the stored edge tiles of a tree of `size` leaves (`edgeOf(size)`), each cut to its width. */
230
+ static load(size, stored) {
231
+ const tiles = edgeOf(size).map(({ level, index, width }) => {
232
+ if (width === 0) return [];
233
+ const hashes = stored.get(tileKey(level, index));
234
+ if (hashes === void 0 || hashes.length < width * 32) throw new Error(`edge tile ${level}/${index} missing or short`);
235
+ return Array.from({ length: width }, (_, i) => Buffer.from(hashes.subarray(i * 32, (i + 1) * 32)));
236
+ });
237
+ return new Edge(size, tiles);
238
+ }
239
+ /** A copy to append to, so a failed write leaves this edge at the head it was. */
240
+ clone() {
241
+ return new Edge(this.size, this.tiles.map((t) => [...t]));
242
+ }
243
+ append(leaves) {
244
+ const changed = [];
245
+ const grew = /* @__PURE__ */ new Set();
246
+ for (const leaf of leaves) {
247
+ let hash = leaf;
248
+ for (let t = 0;; t += 1) {
249
+ const tile = this.tiles[t] ??= [];
250
+ tile.push(hash);
251
+ if (tile.length < 256) {
252
+ grew.add(t);
253
+ break;
254
+ }
255
+ changed.push({
256
+ level: t,
257
+ index: Math.floor(this.size / 2 ** ((t + 1) * 8)),
258
+ hashes: Buffer.concat(tile)
259
+ });
260
+ grew.delete(t);
261
+ hash = hashUp(tile);
262
+ this.tiles[t] = [];
263
+ }
264
+ this.size += 1;
265
+ }
266
+ for (const t of grew) changed.push({
267
+ level: t,
268
+ index: Math.floor(this.size / 2 ** ((t + 1) * 8)),
269
+ hashes: Buffer.concat(this.tiles[t])
270
+ });
271
+ return changed;
272
+ }
273
+ /** The tree head now. */
274
+ root() {
275
+ return treeHash(nodesFrom(tileMap(this.edgeTiles())), this.size);
276
+ }
277
+ /**
278
+ * The tile at the right edge of each level, as it stands. With the tiles an append filled, they hold every node a
279
+ * proof of a leaf that append added reads: the tile of the leaf's ancestor at each level is one of them, and so is
280
+ * every tile to its right.
281
+ */
282
+ edgeTiles() {
283
+ return edgeOf(this.size).map(({ level, index }) => ({
284
+ level,
285
+ index,
286
+ hashes: Buffer.concat(this.tiles[level] ?? [])
287
+ }));
288
+ }
289
+ };
290
+ //#endregion
291
+ export { EMPTY_ROOT, Edge, HASH_SIZE, HEIGHT, WIDTH, consistencyProof, edgeOf, inclusionProof, isPowerOfTwo, leafHash, nodeHash, nodesFrom, rangeHash, tileKey, tileMap, tileOf, tilesFor, treeHash, verifyConsistency, verifyInclusion };
package/dist/mcp.d.ts CHANGED
@@ -12,6 +12,22 @@ export declare const MCP_SCOPE_INFO: Record<McpScope, {
12
12
  label: string;
13
13
  description: string;
14
14
  }>;
15
+ /** How long a code waits for its client: long enough for a redirect, and no longer. */
16
+ export declare const CODE_SECONDS = 60;
17
+ /** An hour: what a leaked access token is good for, at most, unless its connection ends sooner. */
18
+ export declare const ACCESS_TOKEN_MINUTES = 60;
19
+ /** Connections a person may hold at once, codes waiting included, before Connected apps has to lose one. */
20
+ export declare const MAX_CONNECTIONS = 20;
21
+ /** Registered clients the instance keeps at most: anyone may register one, so the table has a ceiling. */
22
+ export declare const MAX_CLIENTS = 10000;
23
+ /** How long an approval waits for its person: a change an MCP client asks for that nobody decides by then expired. */
24
+ export declare const APPROVAL_SECONDS: number;
25
+ /** Approvals a connection holds waiting at once: no flood of prompts, and no more than this many entries an expiry. */
26
+ export declare const MAX_PENDING = 5;
27
+ /** The longest a call's arguments are, as canonical JSON, that an approval keeps: a few names, a note, a scope of some places. */
28
+ export declare const MAX_ASK_ARGUMENTS = 4096;
29
+ /** The tools whose Approve changes nothing but shows the person a value (`mcp.decide`): every other is approved by its change. */
30
+ export declare const MCP_SHOWS: readonly string[];
15
31
  export declare function isMcpScope(value: string): value is McpScope;
16
32
  /**
17
33
  * The scopes a space-separated `scope` asks for, in catalogue order, with
@@ -69,11 +85,18 @@ export type ClientMetadata = {
69
85
  redirectUris: string[];
70
86
  registration: 'cimd' | 'dcr';
71
87
  };
88
+ /** The longest client id the vault keeps (`text` in its ops). */
89
+ export declare const MAX_CLIENT_ID = 256;
90
+ /**
91
+ * Whether a client_id is one the vault and Postgres keep: 256 characters at
92
+ * most, with no NUL and no half of a surrogate pair. Any other is no
93
+ * client's, and is answered as such before it is read or sent anywhere.
94
+ */
95
+ export declare const clientIdKept: (value: string) => boolean;
72
96
  /**
73
97
  * Whether `value` is a Client ID Metadata Document's URL: HTTPS, with a
74
- * path, and nothing a document's address has no use for, no longer than
75
- * `MAX_CLIENT_ID`. On a loopback instance, a loopback one too, for
76
- * development and conformance.
98
+ * path, and nothing a document's address has no use for. On a loopback
99
+ * instance, a loopback one too, for development and conformance.
77
100
  */
78
101
  export declare function isClientIdUrl(value: string, options: {
79
102
  allowLoopback: boolean;
@@ -97,6 +120,6 @@ export declare function registrationRedirects(value: unknown): {
97
120
  kept: string[];
98
121
  dropped: string[];
99
122
  };
100
- /** A client's name as shown: its own, cut short, or its host when it gives none. */
123
+ /** A client's name as shown: its own, or its host when it gives none, cut short. */
101
124
  export declare function clientName(value: unknown, fallback: string): string;
102
125
  //#endregion