@johnhenry/browsermesh-sync 0.2.1 → 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
@@ -26,10 +26,26 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
26
26
  | delta-sync | `SyncCoordinator`, `DeltaLog`, `DeltaEncoder`, `DeltaDecoder`, `DeltaBranch` |
27
27
  | migration | `MigrationEngine`, `MigrationPlan`, `DualActiveWindow` |
28
28
  | files | `MeshFileTransfer`, `ChunkStore`, `FileDescriptor`, `TransferOffer` |
29
+ | cidv1 | `computeCidV1`, `buildUnixfsFile`, `buildUnixfsDirectory`, `verifyBlock`, `parseCid`, `cidV1FromSha256Hex`, `sha256HexFromCid` |
29
30
  | collab | `CollabSession`, `YjsAdapter`, `AwarenessState` |
30
31
  | collab-bridge | `CollabBridge`, `CollabManager` |
31
32
  | memory-sync | `AgentMemorySync`, `MemoryEntry`, `ConflictEntry` |
32
33
 
34
+ ## IPFS CIDv1 / UnixFS addressing (opt-in)
35
+
36
+ `ChunkStore.computeCid(data)` still returns a SHA-256 hex digest by default.
37
+ For real IPFS addresses (CIDv1, sha2-256, base32, raw leaves, dag-pb/UnixFS):
38
+
39
+ ```js
40
+ await ChunkStore.computeCid(bytes, { format: 'cidv1' }); // raw-leaf CIDv1
41
+ const { cid, blocks, files } = await buildUnixfsDirectory({ 'index.html': bytes });
42
+ await verifyBlock(someCid, blockBytes); // accepts SHA-256 hex or CIDv1
43
+ ```
44
+
45
+ Output matches `ipfs add -r --cid-version=1 --raw-leaves` (256 KiB fixed
46
+ chunks, balanced layout, 174 links max). Directories needing HAMT sharding
47
+ (serialized node over 256 KiB) are rejected.
48
+
33
49
  ## Install
34
50
 
35
51
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-sync",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "CRDT sync engine, delta sync, file transfer, and collaboration for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/cidv1.mjs ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Real IPFS CIDv1 / UnixFS addressing (opt-in, alongside ChunkStore's
3
+ * SHA-256-hex "cid").
4
+ *
5
+ * Layout parameters match `ipfs add -r --cid-version=1 --raw-leaves` and the
6
+ * defaults of `ipfs-unixfs-importer`: fixed-size 256 KiB chunker, balanced
7
+ * DAG layout with at most 174 links per node, raw leaves (codec 0x55),
8
+ * dag-pb (0x70) for file-interior and directory nodes, sha2-256 multihash,
9
+ * base32 lowercase multibase ("b" prefix). Zero dependencies.
10
+ *
11
+ * Limitation: directories are always flat dag-pb nodes. Directories whose
12
+ * serialized node exceeds 256 KiB (IPFS would HAMT-shard them) are rejected.
13
+ */
14
+
15
+ export const CIDV1_DEFAULTS = Object.freeze({ chunkSize: 262144, maxLinks: 174 });
16
+
17
+ const CODEC_RAW = 0x55;
18
+ const CODEC_DAG_PB = 0x70;
19
+ const MH_SHA256 = 0x12;
20
+ const MAX_DIR_NODE_BYTES = 256 * 1024;
21
+ const B32 = 'abcdefghijklmnopqrstuvwxyz234567';
22
+ const encoder = new TextEncoder();
23
+
24
+ async function sha256(data) {
25
+ if (typeof crypto !== 'undefined' && crypto.subtle) {
26
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', data));
27
+ }
28
+ const { createHash } = await import('node:crypto');
29
+ return new Uint8Array(createHash('sha256').update(data).digest());
30
+ }
31
+
32
+ function base32Encode(bytes) {
33
+ let out = '';
34
+ let bits = 0;
35
+ let acc = 0;
36
+ for (const b of bytes) {
37
+ acc = (acc << 8) | b;
38
+ bits += 8;
39
+ while (bits >= 5) {
40
+ out += B32[(acc >>> (bits - 5)) & 31];
41
+ bits -= 5;
42
+ }
43
+ acc &= (1 << bits) - 1;
44
+ }
45
+ if (bits > 0) out += B32[(acc << (5 - bits)) & 31];
46
+ return out;
47
+ }
48
+
49
+ function base32Decode(str) {
50
+ const out = [];
51
+ let bits = 0;
52
+ let acc = 0;
53
+ for (const ch of str) {
54
+ const v = B32.indexOf(ch);
55
+ if (v < 0) throw new Error('invalid base32 character');
56
+ acc = (acc << 5) | v;
57
+ bits += 5;
58
+ if (bits >= 8) {
59
+ out.push((acc >>> (bits - 8)) & 255);
60
+ bits -= 8;
61
+ }
62
+ acc &= (1 << bits) - 1;
63
+ }
64
+ return Uint8Array.from(out);
65
+ }
66
+
67
+ function cidFromDigest(codec, digest) {
68
+ const bytes = new Uint8Array(4 + digest.length);
69
+ bytes.set([1, codec, MH_SHA256, digest.length]);
70
+ bytes.set(digest, 4);
71
+ return 'b' + base32Encode(bytes);
72
+ }
73
+
74
+ /**
75
+ * Parse a base32 CIDv1 string with a sha2-256 multihash.
76
+ * @param {string} cid
77
+ * @returns {{version: 1, codec: 'raw'|'dag-pb', codecCode: number, digest: Uint8Array}}
78
+ */
79
+ export function parseCid(cid) {
80
+ if (typeof cid !== 'string' || cid[0] !== 'b') throw new Error('unsupported CID: expected base32 CIDv1 ("b" prefix)');
81
+ const bytes = base32Decode(cid.slice(1));
82
+ if (bytes.length !== 36 || bytes[0] !== 1 || bytes[2] !== MH_SHA256 || bytes[3] !== 32) {
83
+ throw new Error('unsupported CID: expected CIDv1 with sha2-256 multihash');
84
+ }
85
+ const codecCode = bytes[1];
86
+ if (codecCode !== CODEC_RAW && codecCode !== CODEC_DAG_PB) throw new Error('unsupported CID codec');
87
+ return { version: 1, codec: codecCode === CODEC_RAW ? 'raw' : 'dag-pb', codecCode, digest: bytes.slice(4) };
88
+ }
89
+
90
+ const toHex = (u8) => Array.from(u8, (b) => b.toString(16).padStart(2, '0')).join('');
91
+
92
+ /** Raw-leaf CIDv1 (codec raw, sha2-256, base32) of `data`. */
93
+ export async function computeCidV1(data) {
94
+ return cidFromDigest(CODEC_RAW, await sha256(data));
95
+ }
96
+
97
+ /** Convert a SHA-256 hex digest (ChunkStore default form) to a raw-leaf CIDv1. */
98
+ export function cidV1FromSha256Hex(hex) {
99
+ if (typeof hex !== 'string' || !/^[0-9a-f]{64}$/.test(hex)) throw new Error('expected a 64-char lowercase sha-256 hex digest');
100
+ return cidFromDigest(CODEC_RAW, Uint8Array.from(hex.match(/../g), (h) => parseInt(h, 16)));
101
+ }
102
+
103
+ /** SHA-256 hex digest of a raw-leaf CIDv1, or null if the CID is not a raw leaf. */
104
+ export function sha256HexFromCid(cid) {
105
+ const p = parseCid(cid);
106
+ return p.codec === 'raw' ? toHex(p.digest) : null;
107
+ }
108
+
109
+ /**
110
+ * Verify block bytes against either address form: SHA-256 hex or a CIDv1
111
+ * (raw or dag-pb). Never throws; malformed addresses yield false.
112
+ * @returns {Promise<boolean>}
113
+ */
114
+ export async function verifyBlock(address, bytes) {
115
+ try {
116
+ const digest = await sha256(bytes);
117
+ if (typeof address === 'string' && /^[0-9a-f]{64}$/.test(address)) return toHex(digest) === address;
118
+ const p = parseCid(address);
119
+ return toHex(p.digest) === toHex(digest);
120
+ } catch {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ // --- minimal protobuf / dag-pb / UnixFS encoding ---------------------------
126
+
127
+ function varint(n) {
128
+ const out = [];
129
+ while (n >= 0x80) {
130
+ out.push((n % 0x80) | 0x80);
131
+ n = Math.floor(n / 0x80);
132
+ }
133
+ out.push(n);
134
+ return out;
135
+ }
136
+
137
+ function concat(parts) {
138
+ const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0));
139
+ let o = 0;
140
+ for (const p of parts) { out.set(p, o); o += p.length; }
141
+ return out;
142
+ }
143
+
144
+ const lenDelimited = (tag, bytes) => [Uint8Array.from([tag, ...varint(bytes.length)]), bytes];
145
+
146
+ /** dag-pb PBNode: links first (field 2), then Data (field 1). */
147
+ function encodePBNode(links, data) {
148
+ const parts = [];
149
+ for (const l of links) {
150
+ const name = encoder.encode(l.name);
151
+ const hash = l.hash;
152
+ const link = concat([
153
+ ...lenDelimited(0x0a, hash),
154
+ ...lenDelimited(0x12, name),
155
+ Uint8Array.from([0x18, ...varint(l.tsize)]),
156
+ ]);
157
+ parts.push(...lenDelimited(0x12, link));
158
+ }
159
+ if (data) parts.push(...lenDelimited(0x0a, data));
160
+ return concat(parts);
161
+ }
162
+
163
+ const unixfsDirData = () => Uint8Array.from([0x08, 1]);
164
+
165
+ function unixfsFileData(filesize, blocksizes) {
166
+ const b = [0x08, 2, 0x18, ...varint(filesize)];
167
+ for (const s of blocksizes) b.push(0x20, ...varint(s));
168
+ return Uint8Array.from(b);
169
+ }
170
+
171
+ function cidBytes(cid) {
172
+ const p = parseCid(cid);
173
+ return concat([Uint8Array.from([1, p.codecCode, MH_SHA256, 32]), p.digest]);
174
+ }
175
+
176
+ async function putBlock(blocks, codec, bytes) {
177
+ const cid = cidFromDigest(codec, await sha256(bytes));
178
+ blocks.set(cid, bytes);
179
+ return cid;
180
+ }
181
+
182
+ /**
183
+ * Build a UnixFS file DAG (raw leaves, balanced layout).
184
+ * @param {Uint8Array} bytes
185
+ * @param {{chunkSize?: number, maxLinks?: number, blocks?: Map<string, Uint8Array>}} [opts]
186
+ * @returns {Promise<{cid: string, size: number, blocks: Map<string, Uint8Array>}>}
187
+ * `size` is the cumulative DAG size (dag-pb Tsize).
188
+ */
189
+ export async function buildUnixfsFile(bytes, opts = {}) {
190
+ const chunkSize = opts.chunkSize ?? CIDV1_DEFAULTS.chunkSize;
191
+ const maxLinks = opts.maxLinks ?? CIDV1_DEFAULTS.maxLinks;
192
+ const blocks = opts.blocks ?? new Map();
193
+ // level entries: { cid, tsize, filesize }
194
+ let level = [];
195
+ if (bytes.length === 0) {
196
+ level.push({ cid: await putBlock(blocks, CODEC_RAW, bytes), tsize: 0, filesize: 0 });
197
+ } else {
198
+ for (let off = 0; off < bytes.length; off += chunkSize) {
199
+ const chunk = bytes.subarray(off, Math.min(off + chunkSize, bytes.length));
200
+ level.push({ cid: await putBlock(blocks, CODEC_RAW, chunk), tsize: chunk.length, filesize: chunk.length });
201
+ }
202
+ }
203
+ while (level.length > 1) {
204
+ const next = [];
205
+ for (let i = 0; i < level.length; i += maxLinks) {
206
+ const group = level.slice(i, i + maxLinks);
207
+ if (group.length === 1) { next.push(group[0]); continue; }
208
+ const filesize = group.reduce((s, g) => s + g.filesize, 0);
209
+ const node = encodePBNode(
210
+ group.map((g) => ({ name: '', hash: cidBytes(g.cid), tsize: g.tsize })),
211
+ unixfsFileData(filesize, group.map((g) => g.filesize)),
212
+ );
213
+ const tsize = node.length + group.reduce((s, g) => s + g.tsize, 0);
214
+ next.push({ cid: await putBlock(blocks, CODEC_DAG_PB, node), tsize, filesize });
215
+ }
216
+ level = next;
217
+ }
218
+ return { cid: level[0].cid, size: level[0].tsize, blocks };
219
+ }
220
+
221
+ function normalisePath(p) {
222
+ const segs = String(p).split('/').filter((s) => s !== '');
223
+ if (segs.length === 0 || segs.some((s) => s === '.' || s === '..')) throw new Error(`invalid path: ${JSON.stringify(p)}`);
224
+ return segs;
225
+ }
226
+
227
+ /**
228
+ * Build a UnixFS directory DAG from a path -> bytes map.
229
+ * @param {Map<string, Uint8Array>|Record<string, Uint8Array>} files
230
+ * @param {{chunkSize?: number, maxLinks?: number}} [opts]
231
+ * @returns {Promise<{cid: string, size: number, blocks: Map<string, Uint8Array>, files: Map<string, string>}>}
232
+ * `cid` is the root directory CID; `blocks` maps every block CID to its bytes
233
+ * (files, interior nodes, directories); `files` maps each (normalised) path to its file CID.
234
+ */
235
+ export async function buildUnixfsDirectory(files, opts = {}) {
236
+ const entries = files instanceof Map ? [...files] : Object.entries(files);
237
+ if (entries.length === 0) throw new Error('cannot build an empty directory tree');
238
+ const root = new Map();
239
+ const paths = [];
240
+ for (const [path, data] of entries) {
241
+ const segs = normalisePath(path);
242
+ paths.push([segs.join('/'), data]);
243
+ let dir = root;
244
+ for (let i = 0; i < segs.length - 1; i++) {
245
+ let next = dir.get(segs[i]);
246
+ if (next === undefined) { next = new Map(); dir.set(segs[i], next); }
247
+ if (!(next instanceof Map)) throw new Error(`path conflict at ${segs.slice(0, i + 1).join('/')}`);
248
+ dir = next;
249
+ }
250
+ const leaf = segs[segs.length - 1];
251
+ if (dir.has(leaf)) throw new Error(`path conflict at ${segs.join('/')}`);
252
+ dir.set(leaf, { data, path: segs.join('/') });
253
+ }
254
+ const blocks = new Map();
255
+ const fileCids = new Map();
256
+
257
+ async function build(dir) {
258
+ const links = [];
259
+ const names = [...dir.keys()].sort((a, b) => {
260
+ const x = encoder.encode(a), y = encoder.encode(b);
261
+ for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
262
+ return x.length - y.length;
263
+ });
264
+ for (const name of names) {
265
+ const child = dir.get(name);
266
+ let r;
267
+ if (child instanceof Map) {
268
+ r = await build(child);
269
+ } else {
270
+ r = await buildUnixfsFile(child.data, { ...opts, blocks });
271
+ fileCids.set(child.path, r.cid);
272
+ }
273
+ links.push({ name, hash: cidBytes(r.cid), tsize: r.size });
274
+ }
275
+ const node = encodePBNode(links, unixfsDirData());
276
+ if (node.length > MAX_DIR_NODE_BYTES) throw new Error('directory too large: HAMT sharding is not supported');
277
+ const cid = await putBlock(blocks, CODEC_DAG_PB, node);
278
+ return { cid, size: node.length + links.reduce((s, l) => s + l.tsize, 0) };
279
+ }
280
+
281
+ const r = await build(root);
282
+ return { cid: r.cid, size: r.size, blocks, files: fileCids };
283
+ }
package/src/files.mjs CHANGED
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { MESH_TYPE, MESH_ERROR } from '@johnhenry/browsermesh-primitives';
12
+ import { computeCidV1 } from './cidv1.mjs';
12
13
 
13
14
  // ── Constants ────────────────────────────────────────────────────────
14
15
 
@@ -103,11 +104,17 @@ export class ChunkStore {
103
104
  #chunks = new Map();
104
105
 
105
106
  /**
106
- * Compute a content ID (SHA-256 hex) for data.
107
+ * Compute a content ID for data. Default: SHA-256 hex. Pass
108
+ * `{ format: 'cidv1' }` for a real IPFS raw-leaf CIDv1 (base32); see
109
+ * `cidv1.mjs` for directory / multi-chunk UnixFS DAGs.
107
110
  * @param {Uint8Array} data
111
+ * @param {{format?: 'sha256-hex'|'cidv1'}} [opts]
108
112
  * @returns {Promise<string>}
109
113
  */
110
- static async computeCid(data) {
114
+ static async computeCid(data, opts = {}) {
115
+ const format = opts?.format ?? 'sha256-hex';
116
+ if (format === 'cidv1') return computeCidV1(data);
117
+ if (format !== 'sha256-hex') throw new Error(`unknown CID format: ${format}`);
111
118
  let hash;
112
119
  if (typeof crypto !== 'undefined' && crypto.subtle) {
113
120
  hash = await crypto.subtle.digest('SHA-256', data);
package/src/index.mjs CHANGED
@@ -8,3 +8,4 @@ export * from './files.mjs';
8
8
  export * from './collab.mjs';
9
9
  export * from './collab-bridge.mjs';
10
10
  export * from './memory-sync.mjs';
11
+ export * from './cidv1.mjs';
@@ -36,6 +36,12 @@
36
36
  * pointed at the same database — exactly the kind of caveat you'd expect
37
37
  * from making a synchronous view onto async storage.
38
38
  *
39
+ * Torrent service: this class is a supported `chunkStore` for
40
+ * `createTorrentService()` / `TorrentManager` in `@johnhenry/browsermesh-apps`
41
+ * (those await every store call, so the Promise-returning methods are fine).
42
+ * Pair it with a persistent `manifestStore` so a reloaded seeder keeps serving.
43
+ * Covered by `mesh-torrent-hooks.test.mjs` in that package.
44
+ *
39
45
  * Usage:
40
46
  * const store = new IndexedDBChunkStore({ dbName: 'my-app-chunks' });
41
47
  * const cid = await IndexedDBChunkStore.computeCid(data);
@@ -90,8 +96,8 @@ export class IndexedDBChunkStore {
90
96
  * @param {Uint8Array} data
91
97
  * @returns {Promise<string>}
92
98
  */
93
- static computeCid(data) {
94
- return ChunkStore.computeCid(data);
99
+ static computeCid(data, opts) {
100
+ return ChunkStore.computeCid(data, opts);
95
101
  }
96
102
 
97
103
  /**