@johnhenry/browsermesh-primitives 0.2.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 +62 -1
- package/package.json +1 -1
- package/src/acl.mjs +61 -2
- package/src/crdt.mjs +24 -9
- package/src/index.d.ts +14 -6
- package/src/index.mjs +4 -1
- package/src/padding.mjs +107 -0
package/README.md
CHANGED
|
@@ -100,7 +100,7 @@ console.log(set.has('item')) // true
|
|
|
100
100
|
|
|
101
101
|
### Capabilities
|
|
102
102
|
|
|
103
|
-
- `CapabilityToken` --
|
|
103
|
+
- `CapabilityToken` -- signed-by-issuer capability with scopes and expiry (see [Capability tokens vs ACL grants](#capability-tokens-vs-acl-grants))
|
|
104
104
|
- `parseScope(str)` / `matchScope(pattern, target)` -- scope parsing and matching
|
|
105
105
|
|
|
106
106
|
### Trust
|
|
@@ -116,6 +116,26 @@ console.log(set.has('item')) // true
|
|
|
116
116
|
- `AccessGrant` -- grant struct with resource pattern, permission, and principal
|
|
117
117
|
- `matchResourcePattern(pattern, resource)` -- glob-style resource matching
|
|
118
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.
|
|
119
139
|
|
|
120
140
|
### CRDTs
|
|
121
141
|
|
|
@@ -129,6 +149,47 @@ console.log(set.has('item')) // true
|
|
|
129
149
|
|
|
130
150
|
All CRDTs support `merge()`, `toJSON()`, and `fromJSON()` for serialization.
|
|
131
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
|
+
|
|
132
193
|
### Test Utilities
|
|
133
194
|
|
|
134
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.
|
|
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
|
-
/**
|
|
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.#
|
|
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.#
|
|
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.#
|
|
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.#
|
|
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.#
|
|
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,11 @@ 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;
|
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";
|
package/src/padding.mjs
ADDED
|
@@ -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
|
+
}
|