@johnhenry/browsermesh-primitives 0.0.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/src/errors.mjs ADDED
@@ -0,0 +1,46 @@
1
+ import { MESH_ERROR } from "./constants.mjs";
2
+
3
+ /**
4
+ * Base error class for all BrowserMesh errors.
5
+ */
6
+ export class MeshError extends Error {
7
+ /**
8
+ * @param {string} message
9
+ * @param {number} [code=MESH_ERROR.UNKNOWN]
10
+ */
11
+ constructor(message, code = MESH_ERROR.UNKNOWN) {
12
+ super(message);
13
+ this.name = "MeshError";
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Wire-format or protocol-level error.
20
+ */
21
+ export class MeshProtocolError extends MeshError {
22
+ /**
23
+ * @param {string} message
24
+ * @param {number} [code=MESH_ERROR.INVALID_FORMAT]
25
+ */
26
+ constructor(message, code = MESH_ERROR.INVALID_FORMAT) {
27
+ super(message, code);
28
+ this.name = "MeshProtocolError";
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Capability check failure.
34
+ */
35
+ export class MeshCapabilityError extends MeshError {
36
+ /**
37
+ * @param {string} message
38
+ * @param {string} [requiredScope]
39
+ */
40
+ constructor(message, requiredScope) {
41
+ super(message, MESH_ERROR.CAPABILITY_DENIED);
42
+ this.name = "MeshCapabilityError";
43
+ /** @type {string|undefined} */
44
+ this.requiredScope = requiredScope;
45
+ }
46
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Encode a Uint8Array as a base64url string (no padding).
3
+ *
4
+ * @param {Uint8Array} bytes
5
+ * @returns {string}
6
+ */
7
+ export function encodeBase64url(bytes) {
8
+ let binary = '';
9
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
10
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
11
+ }
12
+
13
+ /**
14
+ * Decode a base64url string (no padding) to a Uint8Array.
15
+ *
16
+ * @param {string} str
17
+ * @returns {Uint8Array}
18
+ */
19
+ export function decodeBase64url(str) {
20
+ let s = str.replace(/-/g, '+').replace(/_/g, '/');
21
+ while (s.length % 4) s += '=';
22
+ const binary = atob(s);
23
+ const bytes = new Uint8Array(binary.length);
24
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
25
+ return bytes;
26
+ }
27
+
28
+ /**
29
+ * Derive a pod ID from an Ed25519 public key.
30
+ * Pod ID = base64url(SHA-256(raw public key bytes)).
31
+ *
32
+ * @param {CryptoKey} publicKey - Ed25519 public key
33
+ * @returns {Promise<string>} Base64url-encoded pod ID
34
+ */
35
+ export async function derivePodId(publicKey) {
36
+ const raw = await crypto.subtle.exportKey('raw', publicKey);
37
+ const hash = await crypto.subtle.digest('SHA-256', raw);
38
+ return encodeBase64url(new Uint8Array(hash));
39
+ }
40
+
41
+ /**
42
+ * Represents a BrowserMesh pod identity (Ed25519 key pair).
43
+ *
44
+ * @class
45
+ */
46
+ export class PodIdentity {
47
+ /**
48
+ * @param {object} opts
49
+ * @param {CryptoKeyPair} opts.keyPair - Ed25519 key pair
50
+ * @param {string} opts.podId - Base64url-encoded public key hash
51
+ */
52
+ constructor({ keyPair, podId }) {
53
+ /** @type {CryptoKeyPair} */
54
+ this.keyPair = keyPair;
55
+ /** @type {string} */
56
+ this.podId = podId;
57
+ }
58
+
59
+ /**
60
+ * Generate a new PodIdentity with a fresh Ed25519 key pair.
61
+ *
62
+ * @returns {Promise<PodIdentity>}
63
+ */
64
+ static async generate() {
65
+ const keyPair = await crypto.subtle.generateKey(
66
+ { name: 'Ed25519' },
67
+ true, // extractable
68
+ ['sign', 'verify']
69
+ );
70
+ const podId = await derivePodId(keyPair.publicKey);
71
+ return new PodIdentity({ keyPair, podId });
72
+ }
73
+
74
+ /**
75
+ * Sign data with this identity's private key.
76
+ *
77
+ * @param {BufferSource} data - Data to sign
78
+ * @returns {Promise<Uint8Array>} Ed25519 signature
79
+ */
80
+ async sign(data) {
81
+ return new Uint8Array(
82
+ await crypto.subtle.sign('Ed25519', this.keyPair.privateKey, data)
83
+ );
84
+ }
85
+
86
+ /**
87
+ * Verify a signature against a public key.
88
+ *
89
+ * @param {CryptoKey} publicKey - Ed25519 public key
90
+ * @param {BufferSource} data - Original data
91
+ * @param {BufferSource} signature - Signature to verify
92
+ * @returns {Promise<boolean>}
93
+ */
94
+ static async verify(publicKey, data, signature) {
95
+ return crypto.subtle.verify('Ed25519', publicKey, signature, data);
96
+ }
97
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,346 @@
1
+ // Type definitions for mesh-primitives
2
+
3
+ export declare const MESH_TYPE: Readonly<Record<string, number>>;
4
+ export declare const MESH_ERROR: Readonly<Record<string, number>>;
5
+
6
+ export declare class MeshError extends Error {
7
+ code: number;
8
+ constructor(message: string, code?: number);
9
+ }
10
+ export declare class MeshProtocolError extends MeshError {
11
+ constructor(message: string, code?: number);
12
+ }
13
+ export declare class MeshCapabilityError extends MeshError {
14
+ requiredScope?: string;
15
+ constructor(message: string, requiredScope?: string);
16
+ }
17
+
18
+ export declare function encodeBase64url(bytes: Uint8Array): string;
19
+ export declare function decodeBase64url(str: string): Uint8Array;
20
+ export declare function derivePodId(publicKey: CryptoKey): Promise<string>;
21
+
22
+ export declare class PodIdentity {
23
+ keyPair: CryptoKeyPair;
24
+ podId: string;
25
+ constructor(opts: { keyPair: CryptoKeyPair; podId: string });
26
+ static generate(): Promise<PodIdentity>;
27
+ sign(data: BufferSource): Promise<Uint8Array>;
28
+ static verify(publicKey: CryptoKey, data: BufferSource, signature: BufferSource): Promise<boolean>;
29
+ }
30
+
31
+ export declare const messageTypeRegistry: Map<number, string>;
32
+ export declare function encodeMeshMessage(message: {
33
+ type: number;
34
+ from: string;
35
+ to?: string;
36
+ payload: unknown;
37
+ ttl?: number;
38
+ }): Uint8Array;
39
+ export declare function decodeMeshMessage(bytes: Uint8Array): {
40
+ type: number;
41
+ from: string;
42
+ to?: string;
43
+ payload: unknown;
44
+ ttl?: number;
45
+ };
46
+
47
+ export declare function parseScope(scope: string): {
48
+ namespace: string;
49
+ resource: string;
50
+ action: string;
51
+ };
52
+ export declare function matchScope(granted: string, required: string): boolean;
53
+
54
+ export declare class CapabilityToken {
55
+ issuer: string;
56
+ subject: string;
57
+ scopes: string[];
58
+ expiresAt: number;
59
+ signature?: Uint8Array;
60
+ constructor(opts: {
61
+ issuer: string;
62
+ subject: string;
63
+ scopes: string[];
64
+ expiresAt: number;
65
+ signature?: Uint8Array;
66
+ });
67
+ isExpired(now?: number): boolean;
68
+ covers(scope: string): boolean;
69
+ toJSON(): {
70
+ issuer: string;
71
+ subject: string;
72
+ scopes: string[];
73
+ expiresAt: number;
74
+ };
75
+ }
76
+
77
+ export declare const TRUST_CATEGORIES: Readonly<{
78
+ DIRECT: "direct";
79
+ TRANSITIVE: "transitive";
80
+ MEMBERSHIP: "membership";
81
+ REPUTATION: "reputation";
82
+ }>;
83
+
84
+ export interface TrustEdge {
85
+ from: string;
86
+ to: string;
87
+ category: string;
88
+ value: number;
89
+ timestamp: number;
90
+ }
91
+ export declare function createTrustEdge(opts: {
92
+ from: string;
93
+ to: string;
94
+ category: string;
95
+ value: number;
96
+ timestamp?: number;
97
+ }): TrustEdge;
98
+ export declare function computeTransitiveTrust(
99
+ edges: TrustEdge[],
100
+ source: string,
101
+ target: string,
102
+ maxDepth?: number
103
+ ): number;
104
+
105
+ // ACL
106
+
107
+ export declare function matchResourcePattern(pattern: string, resource: string): boolean;
108
+
109
+ export interface PermissionQuotas {
110
+ maxCalls?: number;
111
+ maxBytes?: number;
112
+ maxTokens?: number;
113
+ maxConcurrent?: number;
114
+ }
115
+
116
+ export declare class Permission {
117
+ resource: string;
118
+ actions: string[];
119
+ quotas: PermissionQuotas | null;
120
+ constructor(opts: {
121
+ resource: string;
122
+ actions: string[];
123
+ quotas?: PermissionQuotas | null;
124
+ });
125
+ matches(resource: string, action: string): boolean;
126
+ toJSON(): {
127
+ resource: string;
128
+ actions: string[];
129
+ quotas: PermissionQuotas | null;
130
+ };
131
+ static fromJSON(data: {
132
+ resource: string;
133
+ actions: string[];
134
+ quotas?: PermissionQuotas | null;
135
+ }): Permission;
136
+ }
137
+
138
+ export interface TimeWindow {
139
+ start: string;
140
+ end: string;
141
+ }
142
+
143
+ export interface GrantConditions {
144
+ expires?: number;
145
+ maxUses?: number;
146
+ timeWindows?: TimeWindow[];
147
+ }
148
+
149
+ export interface CheckResult {
150
+ allowed: boolean;
151
+ grant?: AccessGrant;
152
+ reason?: string;
153
+ }
154
+
155
+ export declare class AccessGrant {
156
+ id: string;
157
+ grantee: string;
158
+ grantor: string;
159
+ permissions: Permission[];
160
+ conditions: GrantConditions;
161
+ created: number;
162
+ revoked: number | null;
163
+ usageCount: number;
164
+ constructor(opts: {
165
+ id: string;
166
+ grantee: string;
167
+ grantor: string;
168
+ permissions: Array<Permission | {
169
+ resource: string;
170
+ actions: string[];
171
+ quotas?: PermissionQuotas | null;
172
+ }>;
173
+ conditions?: GrantConditions;
174
+ created?: number;
175
+ usageCount?: number;
176
+ });
177
+ isExpired(now?: number): boolean;
178
+ isWithinTimeWindow(now?: Date): boolean;
179
+ check(resource: string, action: string, now?: number): CheckResult;
180
+ consumeUse(): void;
181
+ revoke(timestamp?: number): void;
182
+ toJSON(): {
183
+ id: string;
184
+ grantee: string;
185
+ grantor: string;
186
+ permissions: Array<{
187
+ resource: string;
188
+ actions: string[];
189
+ quotas: PermissionQuotas | null;
190
+ }>;
191
+ conditions: GrantConditions;
192
+ created: number;
193
+ revoked: number | null;
194
+ usageCount: number;
195
+ };
196
+ static fromJSON(data: {
197
+ id: string;
198
+ grantee: string;
199
+ grantor: string;
200
+ permissions: Array<{
201
+ resource: string;
202
+ actions: string[];
203
+ quotas?: PermissionQuotas | null;
204
+ }>;
205
+ conditions?: GrantConditions;
206
+ created: number;
207
+ revoked?: number | null;
208
+ usageCount?: number;
209
+ }): AccessGrant;
210
+ }
211
+
212
+ export interface GranteeInfo {
213
+ grantee: string;
214
+ count: number;
215
+ }
216
+
217
+ export declare class ACLEngine {
218
+ constructor();
219
+ addGrant(grant: AccessGrant): void;
220
+ removeGrant(grantId: string): boolean;
221
+ revokeGrant(grantId: string, timestamp?: number): boolean;
222
+ revokeAll(grantee: string, timestamp?: number): number;
223
+ check(grantee: string, resource: string, action: string, now?: number): CheckResult;
224
+ listGrants(grantee?: string): AccessGrant[];
225
+ listGrantees(): GranteeInfo[];
226
+ getEffectivePermissions(grantee: string, now?: number): Permission[];
227
+ pruneExpired(now?: number): number;
228
+ toJSON(): { grants: Array<ReturnType<AccessGrant['toJSON']>> };
229
+ static fromJSON(data: { grants: Array<Parameters<typeof AccessGrant.fromJSON>[0]> }): ACLEngine;
230
+ get size(): number;
231
+ }
232
+
233
+ export declare function generateGrantId(): string;
234
+
235
+ // CRDTs
236
+
237
+ export declare class VectorClock {
238
+ constructor(entries?: Map<string, number>);
239
+ increment(nodeId: string): VectorClock;
240
+ get(nodeId: string): number;
241
+ merge(other: VectorClock): VectorClock;
242
+ compare(other: VectorClock): 'before' | 'after' | 'concurrent' | 'equal';
243
+ toJSON(): Record<string, number>;
244
+ static fromJSON(data: Record<string, number>): VectorClock;
245
+ }
246
+
247
+ export declare class LWWRegister<T = unknown> {
248
+ constructor(value?: T | null, timestamp?: number, nodeId?: string);
249
+ get value(): T | null;
250
+ set(value: T, timestamp: number, nodeId: string): void;
251
+ merge(other: LWWRegister<T>): LWWRegister<T>;
252
+ state(): { value: T | null; timestamp: number; nodeId: string };
253
+ toJSON(): { value: T | null; timestamp: number; nodeId: string };
254
+ static fromJSON<T>(data: { value: T | null; timestamp: number; nodeId: string }): LWWRegister<T>;
255
+ }
256
+
257
+ export declare class GCounter {
258
+ constructor(counts?: Map<string, number>);
259
+ get value(): number;
260
+ increment(nodeId: string, amount?: number): void;
261
+ merge(other: GCounter): GCounter;
262
+ state(): Map<string, number>;
263
+ toJSON(): Record<string, number>;
264
+ static fromJSON(data: Record<string, number>): GCounter;
265
+ }
266
+
267
+ export declare class PNCounter {
268
+ constructor(pos?: GCounter, neg?: GCounter);
269
+ get value(): number;
270
+ increment(nodeId: string, amount?: number): void;
271
+ decrement(nodeId: string, amount?: number): void;
272
+ merge(other: PNCounter): PNCounter;
273
+ state(): { pos: GCounter; neg: GCounter };
274
+ toJSON(): { pos: Record<string, number>; neg: Record<string, number> };
275
+ static fromJSON(data: { pos: Record<string, number>; neg: Record<string, number> }): PNCounter;
276
+ }
277
+
278
+ export declare class ORSet<T = unknown> {
279
+ constructor();
280
+ get value(): Set<T>;
281
+ add(element: T, nodeId: string): void;
282
+ remove(element: T): void;
283
+ has(element: T): boolean;
284
+ merge(other: ORSet<T>): ORSet<T>;
285
+ state(): { elements: Map<T, Set<string>>; tombstones: Set<string> };
286
+ toJSON(): {
287
+ elements: Array<{ element: T; tags: string[] }>;
288
+ tombstones: string[];
289
+ };
290
+ static fromJSON<T>(data: {
291
+ elements: Array<{ element: T; tags: string[] }>;
292
+ tombstones: string[];
293
+ }): ORSet<T>;
294
+ }
295
+
296
+ export interface RGANode<T = unknown> {
297
+ id: string;
298
+ value: T;
299
+ deleted: boolean;
300
+ }
301
+
302
+ export declare class RGA<T = unknown> {
303
+ constructor();
304
+ get value(): T[];
305
+ get length(): number;
306
+ insertAt(index: number, value: T, nodeId: string): void;
307
+ deleteAt(index: number): void;
308
+ merge(other: RGA<T>): RGA<T>;
309
+ state(): { nodes: RGANode<T>[]; vclock: VectorClock };
310
+ toJSON(): { nodes: RGANode<T>[]; vclock: Record<string, number> };
311
+ static fromJSON<T>(data: {
312
+ nodes: RGANode<T>[];
313
+ vclock: Record<string, number>;
314
+ }): RGA<T>;
315
+ }
316
+
317
+ export declare class LWWMap<T = unknown> {
318
+ constructor();
319
+ get value(): Record<string, T>;
320
+ get size(): number;
321
+ set(key: string, value: T, timestamp: number, nodeId: string): void;
322
+ delete(key: string, timestamp: number, nodeId: string): void;
323
+ get(key: string): T | undefined;
324
+ has(key: string): boolean;
325
+ merge(other: LWWMap<T>): LWWMap<T>;
326
+ keys(): IterableIterator<string>;
327
+ values(): IterableIterator<T>;
328
+ entries(): IterableIterator<[string, T]>;
329
+ state(): Map<string, LWWRegister<T>>;
330
+ toJSON(): {
331
+ entries: Record<string, {
332
+ value: T | null;
333
+ timestamp: number;
334
+ nodeId: string;
335
+ tombstone: boolean;
336
+ }>;
337
+ };
338
+ static fromJSON<T>(data: {
339
+ entries: Record<string, {
340
+ value: T | null;
341
+ timestamp: number;
342
+ nodeId: string;
343
+ tombstone?: boolean;
344
+ }>;
345
+ }): LWWMap<T>;
346
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,32 @@
1
+ // Constants
2
+ export { MESH_TYPE, MESH_ERROR } from "./constants.mjs";
3
+
4
+ // Errors
5
+ export { MeshError, MeshProtocolError, MeshCapabilityError } from "./errors.mjs";
6
+
7
+ // Identity
8
+ export { PodIdentity, derivePodId, encodeBase64url, decodeBase64url } from "./identity.mjs";
9
+
10
+ // Wire format
11
+ export { messageTypeRegistry, encodeMeshMessage, decodeMeshMessage } from "./wire.mjs";
12
+
13
+ // Capabilities
14
+ export { parseScope, matchScope, CapabilityToken } from "./capability.mjs";
15
+
16
+ // Trust
17
+ export { TRUST_CATEGORIES, createTrustEdge, computeTransitiveTrust } from "./trust.mjs";
18
+
19
+ // ACL
20
+ export { matchResourcePattern, Permission, AccessGrant, ACLEngine, generateGrantId } from "./acl.mjs";
21
+
22
+ // CRDTs
23
+ export { VectorClock, LWWRegister, GCounter, PNCounter, ORSet, RGA, LWWMap } from "./crdt.mjs";
24
+
25
+ // Test transport
26
+ export {
27
+ DeterministicRNG,
28
+ LocalChannel,
29
+ createLocalChannelPair,
30
+ TestMesh,
31
+ TESTMESH_LIMITS,
32
+ } from "./test-transport.mjs";