@johnhenry/browsermesh-primitives 0.1.0 → 0.3.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/README.md CHANGED
@@ -25,7 +25,7 @@ Every other package in this monorepo depends on `browsermesh-primitives` directl
25
25
 
26
26
  ## Provenance
27
27
 
28
- Previously maintained as an independent, standalone repository and published to npm, unscoped, as `browsermesh-primitives@0.1.1` (initial release `0.1.0`, 2026-03-15), with its own CI already wired up (tests, CodeQL, dependency review). Imported into the `@johnhenry/browsermesh` monorepo via `git subtree` -- preserving its full commit history -- and rescoped to `@johnhenry/browsermesh-primitives`; the version restarts at `0.0.0` per family convention.
28
+ Previously maintained as an independent, standalone repository and published to npm, unscoped, as `browsermesh-primitives@0.1.1` (initial release `0.2.0`, 2026-03-15), with its own CI already wired up (tests, CodeQL, dependency review). Imported into the `@johnhenry/browsermesh` monorepo via `git subtree` -- preserving its full commit history -- and rescoped to `@johnhenry/browsermesh-primitives`; the version restarts at `0.0.0` per family convention.
29
29
 
30
30
  ## Install
31
31
 
@@ -61,17 +61,10 @@ console.log(identity.podId) // base64url-encoded SHA-256 of public key
61
61
  // Sign and verify data
62
62
  const data = new TextEncoder().encode('hello mesh')
63
63
  const sig = await identity.sign(data)
64
- // Canonical object form (preferred): named fields, no argument-order pitfalls
65
- const ok = await PodIdentity.verify({
66
- publicKey: identity.keyPair.publicKey,
67
- signature: sig,
68
- message: data,
69
- })
70
- // Positional form still works, but NOTE its order is (publicKey, data, signature)
71
- // -- unlike WebCrypto/wsh (key, signature, data) and raijin (message, signature, key).
72
- // Swapping data/signature returns false instead of throwing.
73
- const ok2 = await PodIdentity.verify(identity.keyPair.publicKey, data, sig)
74
- // sign also accepts the object form: identity.sign({ message: data })
64
+ // Argument order is (publicKey, signature, data) -- same as crypto.subtle.verify.
65
+ // BREAKING in 0.2.0: earlier versions took (publicKey, data, signature); the old
66
+ // order now throws a TypeError instead of silently returning false.
67
+ const ok = await PodIdentity.verify(identity.keyPair.publicKey, sig, data)
75
68
 
76
69
  // CRDTs -- merge state across peers
77
70
  const clockA = new VectorClock()
@@ -107,7 +100,7 @@ console.log(set.has('item')) // true
107
100
 
108
101
  ### Capabilities
109
102
 
110
- - `CapabilityToken` -- scoped capability with expiry
103
+ - `CapabilityToken` -- signed-by-issuer capability with scopes and expiry (see [Capability tokens vs ACL grants](#capability-tokens-vs-acl-grants))
111
104
  - `parseScope(str)` / `matchScope(pattern, target)` -- scope parsing and matching
112
105
 
113
106
  ### Trust
@@ -123,6 +116,26 @@ console.log(set.has('item')) // true
123
116
  - `AccessGrant` -- grant struct with resource pattern, permission, and principal
124
117
  - `matchResourcePattern(pattern, resource)` -- glob-style resource matching
125
118
  - `generateGrantId()` -- unique grant ID generator
119
+ - `grantFromToken(token, { grantor?, id? })` -- map a `CapabilityToken` onto an `AccessGrant` (does not verify the token)
120
+
121
+ `AccessGrant.check()` / `ACLEngine.check()` report a denial as one of:
122
+
123
+ | `reason` | Meaning |
124
+ | --- | --- |
125
+ | `grant_revoked` | The grant was revoked (`grant.revoke()`, `ACLEngine.revokeGrant()`, `revokeAll()`) |
126
+ | `grant_expired` | `conditions.expires` has passed or `conditions.maxUses` is exhausted |
127
+ | `outside_time_window` | None of `conditions.timeWindows` covers the current time |
128
+ | `no_matching_permission` | The grant is live but no permission covers the resource + action |
129
+ | `no_grants` | (`ACLEngine` only) the grantee has no grants at all |
130
+
131
+ With several grants for one grantee, the engine returns the reason from the last grant it examined.
132
+
133
+ ### Padding
134
+
135
+ - `padTo(bytes, { buckets? })` / `unpad(padded)` -- round a payload up to a size bucket (default 256 / 1024 / 4096 / 16384; larger payloads round up to a multiple of the largest) with a length trailer, and strip it again
136
+ - `paddedLength(length, { buckets? })`, `DEFAULT_PAD_BUCKETS`, `PAD_TRAILER_BYTES`
137
+
138
+ Apply `padTo()` before sealing (encrypting) a message, so a relay that only sees ciphertext learns the bucket rather than the exact length; the trailer is plaintext, so padding already-encrypted bytes hides nothing. Size only, no timing or cover traffic.
126
139
 
127
140
  ### CRDTs
128
141
 
@@ -136,6 +149,47 @@ console.log(set.has('item')) // true
136
149
 
137
150
  All CRDTs support `merge()`, `toJSON()`, and `fromJSON()` for serialization.
138
151
 
152
+ `LWWMap`'s `value`, `toJSON()`, `keys()`, `values()` and `entries()` yield keys in sorted order (UTF-16 code unit order), not insertion order. Replicas that have converged therefore serialize identically, so hashing or signing `JSON.stringify(map.value)` agrees across peers.
153
+
154
+ ### Capability tokens vs ACL grants
155
+
156
+ The package ships two authorization models. They are not interchangeable and nothing converts between them implicitly.
157
+
158
+ | | `CapabilityToken` | `AccessGrant` / `ACLEngine` |
159
+ | --- | --- | --- |
160
+ | Shape | `scopes: ['namespace:resource:action']`, `issuer`, `subject`, `expiresAt` (seconds) | `permissions: [{ resource: 'mesh://ns/resource', actions }]`, `grantee`, `grantor`, `conditions` |
161
+ | Matching | `covers()` / `matchScope()`, `*` per part | glob patterns (`*`, `**`, `?`), `*`/`admin` actions |
162
+ | Signed | Yes, the issuer signs it | No, it is local state |
163
+ | Revocable | No (only expires) | Yes, plus `maxUses`, time windows, usage counting |
164
+ | Lives | travels with the holder, handed to a peer | in the enforcing pod, never leaves it |
165
+
166
+ Use a token as the portable, verifiable thing you hand to another pod ("the issuer says you may do X"). Use grants as the local, revocable policy a pod keeps about who may touch what. To enforce a received token while keeping revocation, verify it, then convert it to a grant in your engine:
167
+
168
+ ```js
169
+ import { ACLEngine, grantFromToken } from '@johnhenry/browsermesh-primitives';
170
+
171
+ const acl = new ACLEngine();
172
+
173
+ // `token` is a CapabilityToken a peer presented; `sender` is the pod ID the
174
+ // transport authenticated for that peer.
175
+ function accept(token, sender) {
176
+ // 1. Verify the issuer's signature over token.toJSON() yourself
177
+ // (PodIdentity), then check it is addressed to the sender and live.
178
+ if (token.subject !== sender || token.isExpired()) throw new Error('rejected');
179
+ // 2. Mirror it into the ACL. Scope 'memory:notes:write' becomes
180
+ // resource 'mesh://memory/notes', actions ['write'].
181
+ const grant = grantFromToken(token);
182
+ acl.addGrant(grant);
183
+ return grant.id; // keep it to revoke later
184
+ }
185
+
186
+ accept(token, sender);
187
+ acl.check(sender, 'mesh://memory/notes', 'write'); // { allowed: true, grant }
188
+ acl.revokeAll(sender);
189
+ acl.check(sender, 'mesh://memory/notes', 'write'); // { allowed: false, reason: 'grant_revoked' }
190
+ ```
191
+
192
+
139
193
  ### Test Utilities
140
194
 
141
195
  - `DeterministicRNG` -- seeded RNG for reproducible tests
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-primitives",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Shared primitives for browser mesh networking — wire format, identity (Ed25519), CRDTs, capabilities, trust model, and ACL engine",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/acl.mjs CHANGED
@@ -7,6 +7,8 @@
7
7
  * Pure module — no I/O, no browser APIs, no crypto.
8
8
  */
9
9
 
10
+ import { parseScope } from './capability.mjs';
11
+
10
12
  // ─── Glob-style resource pattern matching ────────────────────────────
11
13
 
12
14
  /**
@@ -149,8 +151,9 @@ export class AccessGrant {
149
151
  /**
150
152
  * Check whether this grant has expired.
151
153
  *
152
- * A grant is expired if:
153
- * - It has been revoked
154
+ * A grant is treated as expired (not usable) if:
155
+ * - It has been revoked (use {@link AccessGrant#isRevoked} to tell the
156
+ * difference; {@link AccessGrant#check} reports `grant_revoked`)
154
157
  * - The `expires` timestamp has passed
155
158
  * - The `maxUses` limit has been reached
156
159
  *
@@ -164,6 +167,15 @@ export class AccessGrant {
164
167
  return false;
165
168
  }
166
169
 
170
+ /**
171
+ * Check whether this grant has been revoked.
172
+ *
173
+ * @returns {boolean}
174
+ */
175
+ isRevoked() {
176
+ return Boolean(this.revoked);
177
+ }
178
+
167
179
  /**
168
180
  * Check whether the current time falls within any allowed time window.
169
181
  *
@@ -187,9 +199,16 @@ export class AccessGrant {
187
199
  * @param {string} resource - Resource identifier
188
200
  * @param {string} action - Action being attempted
189
201
  * @param {number} [now=Date.now()] - Current time in milliseconds
202
+ * Denial reasons: `grant_revoked` (revoked via `revoke()`),
203
+ * `grant_expired` (`conditions.expires` passed or `maxUses` reached),
204
+ * `outside_time_window`, `no_matching_permission`.
205
+ *
190
206
  * @returns {{ allowed: boolean, grant?: AccessGrant, reason?: string }}
191
207
  */
192
208
  check(resource, action, now = Date.now()) {
209
+ if (this.isRevoked()) {
210
+ return { allowed: false, reason: 'grant_revoked' };
211
+ }
193
212
  if (this.isExpired(now)) {
194
213
  return { allowed: false, reason: 'grant_expired' };
195
214
  }
@@ -469,3 +488,43 @@ let _grantSeq = 0;
469
488
  export function generateGrantId() {
470
489
  return `grant_${Date.now().toString(36)}_${(++_grantSeq).toString(36)}`;
471
490
  }
491
+
492
+ /**
493
+ * Map a {@link CapabilityToken} onto an {@link AccessGrant} so the enforcing
494
+ * pod can revoke, count and audit it through its {@link ACLEngine}.
495
+ *
496
+ * Each scope `namespace:resource:action` becomes a permission on
497
+ * `mesh://<namespace>/<resource>` with `[action]` (a `*` part stays `*`);
498
+ * scopes naming the same resource are merged into one permission. The
499
+ * token's `expiresAt` (seconds) becomes `conditions.expires` (milliseconds).
500
+ *
501
+ * This does NOT verify the token. Check the signature, `subject` and
502
+ * `isExpired()` first, then add the returned grant to your engine. See the
503
+ * README ("Capability tokens vs ACL grants").
504
+ *
505
+ * @param {{ issuer: string, subject: string, scopes: string[], expiresAt: number }} token
506
+ * @param {object} [opts]
507
+ * @param {string} [opts.grantor=token.issuer]
508
+ * @param {string} [opts.id] - Grant ID (default: generated)
509
+ * @param {number} [opts.created=Date.now()]
510
+ * @returns {AccessGrant}
511
+ */
512
+ export function grantFromToken(token, { grantor = token.issuer, id = generateGrantId(), created = Date.now() } = {}) {
513
+ /** @type {Map<string, string[]>} */
514
+ const byResource = new Map();
515
+ for (const scope of token.scopes) {
516
+ const { namespace, resource, action } = parseScope(scope);
517
+ const target = `mesh://${namespace}/${resource}`;
518
+ if (!byResource.has(target)) byResource.set(target, []);
519
+ const actions = byResource.get(target);
520
+ if (!actions.includes(action)) actions.push(action);
521
+ }
522
+ return new AccessGrant({
523
+ id,
524
+ grantee: token.subject,
525
+ grantor,
526
+ permissions: [...byResource].map(([resource, actions]) => ({ resource, actions })),
527
+ conditions: token.expiresAt > 0 ? { expires: token.expiresAt * 1000 } : {},
528
+ created,
529
+ });
530
+ }
package/src/crdt.mjs CHANGED
@@ -764,10 +764,24 @@ export class LWWMap {
764
764
  this.#entries = new Map();
765
765
  }
766
766
 
767
- /** @returns {Record<string, *>} Plain object of live key-value pairs */
767
+ /**
768
+ * Entries in canonical (sorted by key, UTF-16 code unit order) order.
769
+ * Insertion order differs per replica after a merge; every serialising
770
+ * or iterating accessor goes through this so converged replicas agree.
771
+ * @returns {Array<[string, LWWRegister]>}
772
+ */
773
+ #sorted() {
774
+ return [...this.#entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
775
+ }
776
+
777
+ /**
778
+ * Plain object of live key-value pairs. Keys are in sorted order, so
779
+ * converged replicas produce identical `JSON.stringify` output.
780
+ * @returns {Record<string, *>}
781
+ */
768
782
  get value() {
769
783
  const obj = {};
770
- for (const [key, reg] of this.#entries) {
784
+ for (const [key, reg] of this.#sorted()) {
771
785
  if (reg.value !== TOMBSTONE) {
772
786
  obj[key] = reg.value;
773
787
  }
@@ -862,23 +876,23 @@ export class LWWMap {
862
876
  return merged;
863
877
  }
864
878
 
865
- /** @returns {IterableIterator<string>} Live keys */
879
+ /** @returns {IterableIterator<string>} Live keys, sorted */
866
880
  *keys() {
867
- for (const [key, reg] of this.#entries) {
881
+ for (const [key, reg] of this.#sorted()) {
868
882
  if (reg.value !== TOMBSTONE) yield key;
869
883
  }
870
884
  }
871
885
 
872
- /** @returns {IterableIterator<*>} Live values */
886
+ /** @returns {IterableIterator<*>} Live values, in sorted key order */
873
887
  *values() {
874
- for (const reg of this.#entries.values()) {
888
+ for (const [, reg] of this.#sorted()) {
875
889
  if (reg.value !== TOMBSTONE) yield reg.value;
876
890
  }
877
891
  }
878
892
 
879
- /** @returns {IterableIterator<[string, *]>} Live entries */
893
+ /** @returns {IterableIterator<[string, *]>} Live entries, sorted by key */
880
894
  *entries() {
881
- for (const [key, reg] of this.#entries) {
895
+ for (const [key, reg] of this.#sorted()) {
882
896
  if (reg.value !== TOMBSTONE) yield [key, reg.value];
883
897
  }
884
898
  }
@@ -890,9 +904,10 @@ export class LWWMap {
890
904
  return new Map(this.#entries);
891
905
  }
892
906
 
907
+ /** Entries are emitted in sorted key order (canonical across replicas). */
893
908
  toJSON() {
894
909
  const entries = {};
895
- for (const [key, reg] of this.#entries) {
910
+ for (const [key, reg] of this.#sorted()) {
896
911
  const s = reg.state();
897
912
  entries[key] = {
898
913
  value: s.value === TOMBSTONE ? null : s.value,
package/src/identity.mjs CHANGED
@@ -147,22 +147,10 @@ export class PodIdentity {
147
147
  /**
148
148
  * Sign data with this identity's private key.
149
149
  *
150
- * Two call forms:
151
- * - `sign(data)` -- positional (original form).
152
- * - `sign({ message })` -- canonical object form shared with the sibling
153
- * libraries.
154
- *
155
- * @param {BufferSource | { message: BufferSource }} data - Data to sign, or
156
- * an object carrying it as `message`
150
+ * @param {BufferSource} data - Data to sign
157
151
  * @returns {Promise<Uint8Array>} Ed25519 signature
158
152
  */
159
153
  async sign(data) {
160
- if (isPlainObject(data)) {
161
- if (data.message === undefined) {
162
- throw new TypeError('PodIdentity.sign({ message }) requires `message`');
163
- }
164
- data = data.message;
165
- }
166
154
  return new Uint8Array(
167
155
  await crypto.subtle.sign('Ed25519', this.keyPair.privateKey, data)
168
156
  );
@@ -171,43 +159,40 @@ export class PodIdentity {
171
159
  /**
172
160
  * Verify a signature against a public key.
173
161
  *
174
- * Two call forms:
162
+ * Argument order is `(publicKey, signature, data)`, the same as WebCrypto's
163
+ * `crypto.subtle.verify('Ed25519', publicKey, signature, data)`.
175
164
  *
176
- * - **Canonical (preferred):** `verify({ publicKey, signature, message })`.
177
- * Named fields, so argument order cannot be confused.
178
- * - **Positional (kept for compatibility):** `verify(publicKey, data, signature)`.
179
- * WARNING: this order is (key, DATA, SIGNATURE), the odd one out. WebCrypto's
180
- * own `crypto.subtle.verify` and wsh use (key, SIGNATURE, DATA); raijin uses
181
- * (message, signature, key). Swapping data and signature here silently
182
- * returns `false` rather than throwing. Prefer the object form.
165
+ * BREAKING (primitives 0.2.0): releases before this took
166
+ * `(publicKey, data, signature)`. A guard throws a TypeError when the old
167
+ * order is detected (Ed25519 signatures are exactly 64 bytes) rather than
168
+ * silently returning false.
183
169
  *
184
- * @param {CryptoKey | { publicKey: CryptoKey, signature: BufferSource, message: BufferSource }} publicKey
185
- * Ed25519 public key, or the canonical options object
186
- * @param {BufferSource} [data] - Original data (positional form only)
187
- * @param {BufferSource} [signature] - Signature to verify (positional form only)
170
+ * @param {CryptoKey} publicKey - Ed25519 public key
171
+ * @param {BufferSource} signature - Signature to verify (64 bytes)
172
+ * @param {BufferSource} data - Original data
188
173
  * @returns {Promise<boolean>}
189
174
  */
190
- static async verify(publicKey, data, signature) {
191
- if (isPlainObject(publicKey)) {
192
- ({ publicKey, signature, message: data } = publicKey);
193
- if (!publicKey || signature === undefined || data === undefined) {
194
- throw new TypeError(
195
- 'PodIdentity.verify({ publicKey, signature, message }) requires all three fields'
196
- );
197
- }
175
+ static async verify(publicKey, signature, data) {
176
+ if (
177
+ byteLengthOf(signature) !== ED25519_SIGNATURE_BYTES &&
178
+ byteLengthOf(data) === ED25519_SIGNATURE_BYTES
179
+ ) {
180
+ throw new TypeError(
181
+ 'PodIdentity.verify: argument order changed to (publicKey, signature, data) ' +
182
+ 'in this version (previously (publicKey, data, signature)); ' +
183
+ 'the signature argument is not 64 bytes but the data argument is'
184
+ );
198
185
  }
199
186
  return crypto.subtle.verify('Ed25519', publicKey, signature, data);
200
187
  }
201
188
  }
202
189
 
190
+ const ED25519_SIGNATURE_BYTES = 64;
191
+
203
192
  /**
204
- * True for a plain `{...}` options object (not a CryptoKey, TypedArray,
205
- * ArrayBuffer, etc.).
206
- * @param {unknown} v
207
- * @returns {boolean}
193
+ * @param {BufferSource} v
194
+ * @returns {number}
208
195
  */
209
- function isPlainObject(v) {
210
- if (v === null || typeof v !== 'object') return false;
211
- const proto = Object.getPrototypeOf(v);
212
- return proto === Object.prototype || proto === null;
196
+ function byteLengthOf(v) {
197
+ return v && typeof v.byteLength === 'number' ? v.byteLength : -1;
213
198
  }
package/src/index.d.ts CHANGED
@@ -43,19 +43,12 @@ export declare class PodIdentity {
43
43
  constructor(opts: { keyPair: CryptoKeyPair; podId: string });
44
44
  static generate(): Promise<PodIdentity>;
45
45
  sign(data: BufferSource): Promise<Uint8Array>;
46
- sign(opts: { message: BufferSource }): Promise<Uint8Array>;
47
- /** Canonical form (preferred): named fields, no argument-order pitfalls. */
48
- static verify(opts: {
49
- publicKey: CryptoKey;
50
- signature: BufferSource;
51
- message: BufferSource;
52
- }): Promise<boolean>;
53
46
  /**
54
- * Positional form, kept for compatibility. WARNING: order is
55
- * (publicKey, DATA, SIGNATURE) -- unlike WebCrypto/wsh (key, signature, data)
56
- * and raijin (message, signature, key). Prefer the object form.
47
+ * Argument order is (publicKey, signature, data), matching WebCrypto.
48
+ * BREAKING in 0.2.0: previously (publicKey, data, signature). Throws a
49
+ * TypeError if the old order is detected (64-byte data, non-64-byte signature).
57
50
  */
58
- static verify(publicKey: CryptoKey, data: BufferSource, signature: BufferSource): Promise<boolean>;
51
+ static verify(publicKey: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>;
59
52
  }
60
53
 
61
54
  export declare const messageTypeRegistry: Map<number, string>;
@@ -205,6 +198,7 @@ export declare class AccessGrant {
205
198
  usageCount?: number;
206
199
  });
207
200
  isExpired(now?: number): boolean;
201
+ isRevoked(): boolean;
208
202
  isWithinTimeWindow(now?: Date): boolean;
209
203
  check(resource: string, action: string, now?: number): CheckResult;
210
204
  consumeUse(): void;
@@ -262,6 +256,11 @@ export declare class ACLEngine {
262
256
 
263
257
  export declare function generateGrantId(): string;
264
258
 
259
+ export declare function grantFromToken(
260
+ token: { issuer: string; subject: string; scopes: string[]; expiresAt: number },
261
+ opts?: { grantor?: string; id?: string; created?: number }
262
+ ): AccessGrant;
263
+
265
264
  // CRDTs
266
265
 
267
266
  export declare class VectorClock {
@@ -374,3 +373,11 @@ export declare class LWWMap<T = unknown> {
374
373
  }>;
375
374
  }): LWWMap<T>;
376
375
  }
376
+
377
+ // Size-bucket padding
378
+
379
+ export declare const DEFAULT_PAD_BUCKETS: readonly number[];
380
+ export declare const PAD_TRAILER_BYTES: 4;
381
+ export declare function paddedLength(length: number, opts?: { buckets?: number[] }): number;
382
+ export declare function padTo(bytes: Uint8Array, opts?: { buckets?: number[] }): Uint8Array;
383
+ export declare function unpad(padded: Uint8Array): Uint8Array;
package/src/index.mjs CHANGED
@@ -17,7 +17,7 @@ export { parseScope, matchScope, CapabilityToken } from "./capability.mjs";
17
17
  export { TRUST_CATEGORIES, createTrustEdge, computeTransitiveTrust } from "./trust.mjs";
18
18
 
19
19
  // ACL
20
- export { matchResourcePattern, Permission, AccessGrant, ACLEngine, generateGrantId } from "./acl.mjs";
20
+ export { matchResourcePattern, Permission, AccessGrant, ACLEngine, generateGrantId, grantFromToken } from "./acl.mjs";
21
21
 
22
22
  // CRDTs
23
23
  export { VectorClock, LWWRegister, GCounter, PNCounter, ORSet, RGA, LWWMap } from "./crdt.mjs";
@@ -30,3 +30,6 @@ export {
30
30
  TestMesh,
31
31
  TESTMESH_LIMITS,
32
32
  } from "./test-transport.mjs";
33
+
34
+ // Size-bucket padding (relay-blind envelopes)
35
+ export { DEFAULT_PAD_BUCKETS, PAD_TRAILER_BYTES, paddedLength, padTo, unpad } from "./padding.mjs";
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Size-bucket padding for relay-blind envelopes.
3
+ *
4
+ * A relay that only ever sees ciphertext still learns exact payload sizes,
5
+ * and for short agent messages (tool calls, chat turns, presence) size alone
6
+ * distinguishes message types. `padTo()` rounds a payload up to one of a few
7
+ * bucket sizes so every message in a bucket looks the same length; `unpad()`
8
+ * strips it again.
9
+ *
10
+ * Wire layout of a padded payload (total length is always the bucket size):
11
+ *
12
+ * [ payload (n bytes) ][ random fill ][ n as uint32 big-endian ]
13
+ *
14
+ * The trailer is plaintext, so pad BEFORE sealing (encrypt the padded bytes)
15
+ * and unpad AFTER opening. Padding applied to already-encrypted bytes leaves
16
+ * the length trailer readable and hides nothing from whoever reads those
17
+ * bytes. Padding hides size, not timing; there is no cover traffic.
18
+ *
19
+ * Pure module: no I/O. Uses `crypto.getRandomValues` for the fill.
20
+ */
21
+
22
+ /** Default bucket sizes in bytes. */
23
+ export const DEFAULT_PAD_BUCKETS = Object.freeze([256, 1024, 4096, 16384]);
24
+
25
+ /** Bytes the length trailer occupies; a payload needs `length + 4` bytes of bucket. */
26
+ export const PAD_TRAILER_BYTES = 4;
27
+
28
+ /** `crypto.getRandomValues` accepts at most 65536 bytes per call. */
29
+ const RANDOM_CHUNK = 65536;
30
+
31
+ /**
32
+ * @param {number[]|undefined} buckets
33
+ * @returns {number[]} ascending, de-duplicated copy
34
+ */
35
+ function normalizeBuckets(buckets) {
36
+ const list = buckets === undefined ? DEFAULT_PAD_BUCKETS : buckets;
37
+ if (!Array.isArray(list) || list.length === 0) {
38
+ throw new TypeError('buckets must be a non-empty array of positive integers');
39
+ }
40
+ for (const b of list) {
41
+ if (!Number.isSafeInteger(b) || b <= PAD_TRAILER_BYTES) {
42
+ throw new TypeError(`bucket sizes must be integers greater than ${PAD_TRAILER_BYTES}, got ${b}`);
43
+ }
44
+ }
45
+ return [...new Set(list)].sort((a, b) => a - b);
46
+ }
47
+
48
+ /**
49
+ * The padded length a payload of `length` bytes will have.
50
+ *
51
+ * The smallest bucket that fits `length + 4`; a payload larger than the
52
+ * largest bucket pads up to the next multiple of the largest bucket.
53
+ *
54
+ * @param {number} length - Payload length in bytes
55
+ * @param {{ buckets?: number[] }} [opts]
56
+ * @returns {number}
57
+ */
58
+ export function paddedLength(length, { buckets } = {}) {
59
+ if (!Number.isSafeInteger(length) || length < 0) {
60
+ throw new TypeError('length must be a non-negative integer');
61
+ }
62
+ const sorted = normalizeBuckets(buckets);
63
+ const needed = length + PAD_TRAILER_BYTES;
64
+ for (const b of sorted) {
65
+ if (needed <= b) return b;
66
+ }
67
+ const largest = sorted[sorted.length - 1];
68
+ return Math.ceil(needed / largest) * largest;
69
+ }
70
+
71
+ /**
72
+ * Pad `bytes` up to a size bucket.
73
+ *
74
+ * @param {Uint8Array} bytes
75
+ * @param {object} [opts]
76
+ * @param {number[]} [opts.buckets=DEFAULT_PAD_BUCKETS] - Bucket sizes in bytes
77
+ * @returns {Uint8Array} A new array whose length is a bucket size
78
+ */
79
+ export function padTo(bytes, { buckets } = {}) {
80
+ if (!(bytes instanceof Uint8Array)) throw new TypeError('padTo: bytes must be a Uint8Array');
81
+ if (bytes.length > 0xffffffff) throw new RangeError('padTo: payload too large');
82
+ const total = paddedLength(bytes.length, { buckets });
83
+ const out = new Uint8Array(total);
84
+ out.set(bytes, 0);
85
+ const fillEnd = total - PAD_TRAILER_BYTES;
86
+ for (let off = bytes.length; off < fillEnd; off += RANDOM_CHUNK) {
87
+ crypto.getRandomValues(out.subarray(off, Math.min(off + RANDOM_CHUNK, fillEnd)));
88
+ }
89
+ new DataView(out.buffer).setUint32(fillEnd, bytes.length, false);
90
+ return out;
91
+ }
92
+
93
+ /**
94
+ * Strip the padding added by {@link padTo}.
95
+ *
96
+ * @param {Uint8Array} padded
97
+ * @returns {Uint8Array} The original payload (a view into `padded`)
98
+ * @throws {RangeError} If `padded` is too short or its trailer is inconsistent
99
+ */
100
+ export function unpad(padded) {
101
+ if (!(padded instanceof Uint8Array)) throw new TypeError('unpad: padded must be a Uint8Array');
102
+ if (padded.length < PAD_TRAILER_BYTES) throw new RangeError('unpad: input shorter than the length trailer');
103
+ const fillEnd = padded.length - PAD_TRAILER_BYTES;
104
+ const length = new DataView(padded.buffer, padded.byteOffset, padded.byteLength).getUint32(fillEnd, false);
105
+ if (length > fillEnd) throw new RangeError('unpad: length trailer exceeds the padded size');
106
+ return padded.subarray(0, length);
107
+ }