@johnhenry/browsermesh-primitives 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -95,12 +95,16 @@ console.log(set.has('item')) // true
95
95
 
96
96
  ### Wire Format
97
97
 
98
+ - `parseMeshRequest(url)` — shared browser-safe parsing of `mesh://` and
99
+ `*.mesh.local` addresses into `{ podId, path }`, preserving ID case and
100
+ query strings and excluding fragments. Discovery re-exports the same helper.
101
+
98
102
  - `messageTypeRegistry` -- extensible registry of message types
99
103
  - `encodeMeshMessage(msg)` / `decodeMeshMessage(bytes)` -- binary serialization
100
104
 
101
105
  ### Capabilities
102
106
 
103
- - `CapabilityToken` -- scoped capability with expiry
107
+ - `CapabilityToken` -- signed-by-issuer capability with scopes and expiry (see [Capability tokens vs ACL grants](#capability-tokens-vs-acl-grants))
104
108
  - `parseScope(str)` / `matchScope(pattern, target)` -- scope parsing and matching
105
109
 
106
110
  ### Trust
@@ -116,6 +120,26 @@ console.log(set.has('item')) // true
116
120
  - `AccessGrant` -- grant struct with resource pattern, permission, and principal
117
121
  - `matchResourcePattern(pattern, resource)` -- glob-style resource matching
118
122
  - `generateGrantId()` -- unique grant ID generator
123
+ - `grantFromToken(token, { grantor?, id? })` -- map a `CapabilityToken` onto an `AccessGrant` (does not verify the token)
124
+
125
+ `AccessGrant.check()` / `ACLEngine.check()` report a denial as one of:
126
+
127
+ | `reason` | Meaning |
128
+ | --- | --- |
129
+ | `grant_revoked` | The grant was revoked (`grant.revoke()`, `ACLEngine.revokeGrant()`, `revokeAll()`) |
130
+ | `grant_expired` | `conditions.expires` has passed or `conditions.maxUses` is exhausted |
131
+ | `outside_time_window` | None of `conditions.timeWindows` covers the current time |
132
+ | `no_matching_permission` | The grant is live but no permission covers the resource + action |
133
+ | `no_grants` | (`ACLEngine` only) the grantee has no grants at all |
134
+
135
+ With several grants for one grantee, the engine returns the reason from the last grant it examined.
136
+
137
+ ### Padding
138
+
139
+ - `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
140
+ - `paddedLength(length, { buckets? })`, `DEFAULT_PAD_BUCKETS`, `PAD_TRAILER_BYTES`
141
+
142
+ 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.
119
143
 
120
144
  ### CRDTs
121
145
 
@@ -129,6 +153,47 @@ console.log(set.has('item')) // true
129
153
 
130
154
  All CRDTs support `merge()`, `toJSON()`, and `fromJSON()` for serialization.
131
155
 
156
+ `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.
157
+
158
+ ### Capability tokens vs ACL grants
159
+
160
+ The package ships two authorization models. They are not interchangeable and nothing converts between them implicitly.
161
+
162
+ | | `CapabilityToken` | `AccessGrant` / `ACLEngine` |
163
+ | --- | --- | --- |
164
+ | Shape | `scopes: ['namespace:resource:action']`, `issuer`, `subject`, `expiresAt` (seconds) | `permissions: [{ resource: 'mesh://ns/resource', actions }]`, `grantee`, `grantor`, `conditions` |
165
+ | Matching | `covers()` / `matchScope()`, `*` per part | glob patterns (`*`, `**`, `?`), `*`/`admin` actions |
166
+ | Signed | Yes, the issuer signs it | No, it is local state |
167
+ | Revocable | No (only expires) | Yes, plus `maxUses`, time windows, usage counting |
168
+ | Lives | travels with the holder, handed to a peer | in the enforcing pod, never leaves it |
169
+
170
+ 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:
171
+
172
+ ```js
173
+ import { ACLEngine, grantFromToken } from '@johnhenry/browsermesh-primitives';
174
+
175
+ const acl = new ACLEngine();
176
+
177
+ // `token` is a CapabilityToken a peer presented; `sender` is the pod ID the
178
+ // transport authenticated for that peer.
179
+ function accept(token, sender) {
180
+ // 1. Verify the issuer's signature over token.toJSON() yourself
181
+ // (PodIdentity), then check it is addressed to the sender and live.
182
+ if (token.subject !== sender || token.isExpired()) throw new Error('rejected');
183
+ // 2. Mirror it into the ACL. Scope 'memory:notes:write' becomes
184
+ // resource 'mesh://memory/notes', actions ['write'].
185
+ const grant = grantFromToken(token);
186
+ acl.addGrant(grant);
187
+ return grant.id; // keep it to revoke later
188
+ }
189
+
190
+ accept(token, sender);
191
+ acl.check(sender, 'mesh://memory/notes', 'write'); // { allowed: true, grant }
192
+ acl.revokeAll(sender);
193
+ acl.check(sender, 'mesh://memory/notes', 'write'); // { allowed: false, reason: 'grant_revoked' }
194
+ ```
195
+
196
+
132
197
  ### Test Utilities
133
198
 
134
199
  - `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.2.0",
3
+ "version": "0.3.1",
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/index.d.ts CHANGED
@@ -49,12 +49,6 @@ export declare class PodIdentity {
49
49
  * TypeError if the old order is detected (64-byte data, non-64-byte signature).
50
50
  */
51
51
  static verify(publicKey: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>;
52
- /**
53
- * Positional form, kept for compatibility. WARNING: order is
54
- * (publicKey, DATA, SIGNATURE) -- unlike WebCrypto/wsh (key, signature, data)
55
- * and raijin (message, signature, key). Prefer the object form.
56
- */
57
- static verify(publicKey: CryptoKey, data: BufferSource, signature: BufferSource): Promise<boolean>;
58
52
  }
59
53
 
60
54
  export declare const messageTypeRegistry: Map<number, string>;
@@ -204,6 +198,7 @@ export declare class AccessGrant {
204
198
  usageCount?: number;
205
199
  });
206
200
  isExpired(now?: number): boolean;
201
+ isRevoked(): boolean;
207
202
  isWithinTimeWindow(now?: Date): boolean;
208
203
  check(resource: string, action: string, now?: number): CheckResult;
209
204
  consumeUse(): void;
@@ -261,6 +256,11 @@ export declare class ACLEngine {
261
256
 
262
257
  export declare function generateGrantId(): string;
263
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
+
264
264
  // CRDTs
265
265
 
266
266
  export declare class VectorClock {
@@ -373,3 +373,14 @@ export declare class LWWMap<T = unknown> {
373
373
  }>;
374
374
  }): LWWMap<T>;
375
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;
384
+
385
+ /** Parse a case-sensitive mesh:// or *.mesh.local address. */
386
+ export declare function parseMeshRequest(url: string): { podId: string; path: string } | null;
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,9 @@ 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";
36
+
37
+ // Mesh addressing
38
+ export { parseMeshRequest } from './mesh-address.mjs';
@@ -0,0 +1,56 @@
1
+ // Shared browser-safe mesh address parsing. Pod IDs are case sensitive.
2
+ const MESH_PROTOCOL = 'mesh://'
3
+ const MESH_LOCAL_SUFFIX = '.mesh.local'
4
+
5
+ /**
6
+ * Parse a mesh URL into { podId, path } or null.
7
+ * Supports:
8
+ * - mesh://podId/path
9
+ * - https://podId.mesh.local/path
10
+ * - http://podId.mesh.local/path
11
+ *
12
+ * @param {string} urlStr
13
+ * @returns {{ podId: string, path: string } | null}
14
+ */
15
+ export function parseMeshRequest(urlStr) {
16
+ if (!urlStr || typeof urlStr !== 'string') return null
17
+
18
+ // --- mesh:// protocol ---
19
+ if (urlStr.startsWith(MESH_PROTOCOL)) {
20
+ const rest = urlStr.slice(MESH_PROTOCOL.length)
21
+ if (!rest) return null
22
+
23
+ const fragment = rest.indexOf('#')
24
+ const address = fragment < 0 ? rest : rest.slice(0, fragment)
25
+ const slashIdx = address.search(/[/?]/)
26
+ let podId, path
27
+ if (slashIdx === -1) {
28
+ podId = address
29
+ path = '/'
30
+ } else {
31
+ podId = address.slice(0, slashIdx)
32
+ path = address.slice(slashIdx) || '/'
33
+ if (path.startsWith('?')) path = '/' + path
34
+ }
35
+
36
+ if (!podId) return null
37
+ return { podId, path }
38
+ }
39
+
40
+ // --- https://podId.mesh.local/path or http://podId.mesh.local/path ---
41
+ // Extract hostname from the raw string to preserve case (URL() lowercases hostnames).
42
+ const httpMatch = urlStr.match(/^https?:\/\/([^/?#]+)([^#]*)/)
43
+ if (!httpMatch) return null
44
+
45
+ const rawHost = httpMatch[1] // preserves original case
46
+ const lowerHost = rawHost.toLowerCase()
47
+ if (!lowerHost.endsWith(MESH_LOCAL_SUFFIX)) return null
48
+
49
+ const podId = rawHost.slice(0, -MESH_LOCAL_SUFFIX.length)
50
+ if (!podId) return null
51
+
52
+ const suffix = httpMatch[2] || '/'
53
+ const path = suffix.startsWith('?') ? '/' + suffix : suffix
54
+ return { podId, path }
55
+ }
56
+
@@ -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
+ }