@johnhenry/browsermesh-apps 0.2.0 → 0.4.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 +232 -1
- package/package.json +7 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +859 -0
- package/src/compat.mjs +98 -0
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +34 -2
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1131 -12
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +33 -2
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/serverless-executor-andbox.mjs +136 -0
- package/src/serverless-fetch.mjs +70 -0
- package/src/serverless-functions.mjs +67 -0
- package/src/serverless-peer-select.mjs +69 -0
- package/src/serverless-proxy.mjs +127 -0
- package/src/serverless-router.mjs +115 -0
- package/src/serverless-sites.mjs +116 -0
- package/src/serverless-static.mjs +202 -0
- package/src/serverless-wire.mjs +87 -0
- package/src/peer-session.mjs +0 -937
|
@@ -0,0 +1,932 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cloud-storage-backend.mjs -- Phase B of the mesh-native-services plan
|
|
3
|
+
* ("CloudStorage: S3-like object storage"): a `browsermesh-netway` `Backend`
|
|
4
|
+
* that provides a durable, encrypted-at-rest, single-peer object store.
|
|
5
|
+
*
|
|
6
|
+
* No mesh dependency yet -- this phase is explicitly local-only, single-peer
|
|
7
|
+
* (see the plan's Phase B section). Cross-peer replication (chunk transfer),
|
|
8
|
+
* authorization (the signed GrantLog), and cross-peer manifest sync are all
|
|
9
|
+
* later phases (D/F/G) layered on top of what this file builds.
|
|
10
|
+
*
|
|
11
|
+
* The one other file in this package that imports *from* `browsermesh-netway`
|
|
12
|
+
* besides `mesh-relay-backend.mjs` -- same rationale: `browsermesh-netway`
|
|
13
|
+
* is deliberately dependency-free, so all mesh/storage awareness lives here
|
|
14
|
+
* in `-apps`, which already depends on both `browsermesh-netway` and
|
|
15
|
+
* `browsermesh-sync` (verified against the real `package.json`
|
|
16
|
+
* `peerDependencies` before writing this file -- see the plan's Phase B
|
|
17
|
+
* parenthetical for the full reasoning).
|
|
18
|
+
*
|
|
19
|
+
* Protocol: JSON-command-over-socket, modeled directly on
|
|
20
|
+
* `fs-service-backend.mjs` -- the client writes a UTF-8 JSON command object
|
|
21
|
+
* to the socket returned by `connect()`, the server writes back a single
|
|
22
|
+
* UTF-8 JSON response object per command. Binary payloads are base64.
|
|
23
|
+
* Errors come back as `{ error: message }` without closing the socket
|
|
24
|
+
* (exact same convention as `fs-service-backend.mjs`).
|
|
25
|
+
*
|
|
26
|
+
* Ops (S3-like semantics):
|
|
27
|
+
* - put { key, data (base64), contentType?, metadata? } -> { stored: true, key, size }
|
|
28
|
+
* - get { key } -> { data (base64), size, contentType, metadata } | { error: 'not found' }
|
|
29
|
+
* - delete { key } -> { deleted: true }
|
|
30
|
+
* - list { prefix? } -> { keys: [{ key, size, updatedAt }] }
|
|
31
|
+
* - head { key } -> { size, contentType, metadata, updatedAt, version } | { error: 'not found' }
|
|
32
|
+
*
|
|
33
|
+
* Encryption (per the plan's "Design decisions" section -- this is the core
|
|
34
|
+
* design constraint of this phase, not an incidental detail):
|
|
35
|
+
* - Encryption is a `CloudStorageBackend`-level concern, not a chunk-store
|
|
36
|
+
* concern. `IndexedDBChunkStore` stays completely unaware of encryption:
|
|
37
|
+
* it stores/serves whatever opaque bytes it is handed.
|
|
38
|
+
* - On first use, this backend generates a random AES-256-GCM key for the
|
|
39
|
+
* bucket and persists it to its own small, local-only key store (a
|
|
40
|
+
* dedicated `IndexedDBSyncStorage` instance, pointed at a database
|
|
41
|
+
* distinct from the manifest's). This key never goes through the
|
|
42
|
+
* CRDT-synced manifest path -- a later phase (E) handles cross-peer key
|
|
43
|
+
* distribution separately, over a dedicated point-to-point channel, and
|
|
44
|
+
* deliberately does not reuse the manifest sync channel for the key
|
|
45
|
+
* itself.
|
|
46
|
+
* - `put()` encrypts the plaintext BEFORE chunking, reusing
|
|
47
|
+
* `files.mjs`'s `MeshFileTransfer` 256KB chunking convention
|
|
48
|
+
* (`TRANSFER_DEFAULTS.chunkSize`, imported directly so the two stay in
|
|
49
|
+
* sync rather than duplicating the literal). `MeshFileTransfer` itself is
|
|
50
|
+
* transfer-session-oriented (offers/accepts/progress), not a generic
|
|
51
|
+
* "slice this buffer" utility, so the slicing loop is replicated inline
|
|
52
|
+
* here rather than reused.
|
|
53
|
+
* - The CID (`IndexedDBChunkStore.computeCid`, which delegates to
|
|
54
|
+
* `ChunkStore.computeCid` -- byte-identical) is computed over each
|
|
55
|
+
* CIPHERTEXT chunk, not the plaintext, and each ciphertext chunk is
|
|
56
|
+
* stored via `IndexedDBChunkStore.save(cid, ciphertextChunk)`.
|
|
57
|
+
* - Every chunk gets a fresh random IV (AES-GCM requires a unique IV per
|
|
58
|
+
* encryption under the same key). The IV is not secret and is stored
|
|
59
|
+
* alongside the CID in the manifest entry.
|
|
60
|
+
* - `peekKeyRaw()`/`exportKeyRaw()`/`importKeyRaw()` (added for Phase E,
|
|
61
|
+
* `key-distribution.mjs`) let a caller read this backend's raw 32-byte
|
|
62
|
+
* bucket key (to hand to a newly-granted peer over Phase E's dedicated
|
|
63
|
+
* encrypted channel) and let a *different* `CloudStorageBackend` instance
|
|
64
|
+
* (a newly-granted peer's own local instance for the same bucket) adopt
|
|
65
|
+
* received key material instead of generating its own. See each method's
|
|
66
|
+
* own doc comment for exactly how they avoid the auto-create-on-first-use
|
|
67
|
+
* behavior below stepping on a receive-only instance.
|
|
68
|
+
*
|
|
69
|
+
* PERMANENT LIMITATION (Phase E's own documented constraint, restated
|
|
70
|
+
* here since this is the file whose data a leaked/undeleted key actually
|
|
71
|
+
* protects): revoking a peer's grant (the replicated `GrantLog`, Phase D)
|
|
72
|
+
* stops FUTURE key distribution and future chunk replication (Phase G) to
|
|
73
|
+
* that peer, but cannot retroactively erase a key -- or any plaintext
|
|
74
|
+
* already decrypted with it -- already delivered to that peer before the
|
|
75
|
+
* revoke. This bucket's AES key is never rotated on revoke in this plan;
|
|
76
|
+
* a since-revoked peer that retained the key (or any chunk ciphertext
|
|
77
|
+
* plus the key) can still decrypt it offline forever. This is a
|
|
78
|
+
* fundamental property of any such scheme (the same is true of, say, a
|
|
79
|
+
* downloaded-then-access-revoked S3 object), not a bug to fix later.
|
|
80
|
+
*
|
|
81
|
+
* Manifest: an `LWWMap` (`@johnhenry/browsermesh-primitives`) persisted via
|
|
82
|
+
* `IndexedDBSyncStorage`'s `save(docs)`/`load()` for local durability of this
|
|
83
|
+
* single peer's state. Manifest value shape:
|
|
84
|
+
* { chunks: [{ cid, iv }], size, contentType, metadata, version, updatedAt }
|
|
85
|
+
* Deletes are tombstoned via `LWWMap.delete()`, never a chunk-store removal
|
|
86
|
+
* (another key might reference the same content-addressed chunk; garbage
|
|
87
|
+
* collection of orphaned chunks is out of scope for the whole plan).
|
|
88
|
+
*
|
|
89
|
+
* Phase F (`manifest-sync.mjs`) wires this manifest into `MeshSyncEngine` for
|
|
90
|
+
* cross-peer replication. This file's contribution to that phase is a small,
|
|
91
|
+
* deliberately narrow surface -- `getManifestSnapshot()`,
|
|
92
|
+
* `mergeManifestEntries()`, `onManifestChange()` -- that hands the *raw*
|
|
93
|
+
* `LWWMap` wire shape (`{entries: {key: {value, timestamp, nodeId,
|
|
94
|
+
* tombstone}}}`) up to the caller and accepts already-vetted entries back
|
|
95
|
+
* down. This file performs NO authorization itself: `manifest-sync.mjs` is
|
|
96
|
+
* responsible for filtering out any remote entry whose implied writer
|
|
97
|
+
* (`entry.nodeId`) fails `PeerRegistry.checkAccess()` BEFORE ever calling
|
|
98
|
+
* `mergeManifestEntries()` -- by the time an entry reaches this file's merge
|
|
99
|
+
* path, trusting it is assumed to already be correct. See that file's module
|
|
100
|
+
* doc comment for the full ACL-gate design and the reasoning for why the
|
|
101
|
+
* gate lives one layer up, not here.
|
|
102
|
+
*
|
|
103
|
+
* IMPORTANT for cross-peer use: local writes are attributed to this
|
|
104
|
+
* instance's `#nodeId` (the LWWMap tiebreak/attribution field for that
|
|
105
|
+
* write). For a bucket's manifest to be meaningfully ACL-checked by other
|
|
106
|
+
* peers, `nodeId` MUST be constructed as the local peer's own identity
|
|
107
|
+
* (`peerNode.podId`), not the random-UUID default this class falls back to
|
|
108
|
+
* when unset -- a receiving peer's `checkAccess(nodeId, ...)` call is
|
|
109
|
+
* meaningless against a random UUID that matches no real identity. Single-
|
|
110
|
+
* peer (Phase B) callers are unaffected either way since nothing ever reads
|
|
111
|
+
* that attribution back out locally.
|
|
112
|
+
*
|
|
113
|
+
* Crypto conventions match `peer-encrypted-store.mjs`'s established
|
|
114
|
+
* AES-256-GCM usage exactly (small, self-contained per-file helpers,
|
|
115
|
+
* `crypto.getRandomValues` for key/IV generation, Node's `node:crypto`
|
|
116
|
+
* `aes-256-gcm` cipher first with the 16-byte auth tag appended to the
|
|
117
|
+
* ciphertext, falling back to WebCrypto `crypto.subtle` when `node:crypto`
|
|
118
|
+
* isn't available) so a later phase relying on the same bucket-key byte
|
|
119
|
+
* format (Phase E's key distribution) can interoperate without translation.
|
|
120
|
+
*
|
|
121
|
+
* Phase G (`chunk-replication.mjs`) additions, kept narrow and additive
|
|
122
|
+
* exactly like Phase E's/F's own surfaces above:
|
|
123
|
+
* - `hasChunkRaw()`/`getChunkRaw()`/`putChunkRaw()` -- opaque ciphertext
|
|
124
|
+
* chunk read/write access (bypassing encryption/decryption and the
|
|
125
|
+
* manifest entirely), so a replica peer can serve/store/verify chunk
|
|
126
|
+
* bytes it may not even hold the bucket key for yet. `putChunkRaw()`
|
|
127
|
+
* verifies the supplied bytes actually hash to the claimed CID before
|
|
128
|
+
* ever writing them, exactly like `#encryptAndChunk()`'s own
|
|
129
|
+
* content-addressing -- a chunk-replication peer must never persist a
|
|
130
|
+
* wire-supplied (cid, bytes) pair without that check.
|
|
131
|
+
* - `setReplicationHook()` -- a post-construction setter (not a
|
|
132
|
+
* constructor option, since a backend is always constructed standalone
|
|
133
|
+
* and mesh concerns wire themselves in afterward, matching how
|
|
134
|
+
* `manifest-sync.mjs`/`key-distribution.mjs` both already compose on
|
|
135
|
+
* top of an already-constructed instance) that lets `#opPut()` await a
|
|
136
|
+
* real replication attempt before responding, populating `put()`'s
|
|
137
|
+
* JSON-command response with `{durability: 'local-only'|'replicated',
|
|
138
|
+
* replicatedTo: string[]}` per the plan's durability contract. When no
|
|
139
|
+
* hook is installed (every earlier phase's tests), `put()`'s response
|
|
140
|
+
* is byte-for-byte identical to before this phase existed.
|
|
141
|
+
*
|
|
142
|
+
* No browser-only imports at module level.
|
|
143
|
+
*/
|
|
144
|
+
|
|
145
|
+
import { Backend, StreamSocket } from '@johnhenry/browsermesh-netway'
|
|
146
|
+
import { IndexedDBChunkStore, IndexedDBSyncStorage, TRANSFER_DEFAULTS } from '@johnhenry/browsermesh-sync'
|
|
147
|
+
import { LWWMap } from '@johnhenry/browsermesh-primitives'
|
|
148
|
+
|
|
149
|
+
/** 256KB, matching `MeshFileTransfer`'s existing chunking convention exactly (imported, not duplicated as a literal). */
|
|
150
|
+
const CHUNK_SIZE = TRANSFER_DEFAULTS.chunkSize
|
|
151
|
+
|
|
152
|
+
/** Fixed document id for the single manifest record persisted via `IndexedDBSyncStorage`. */
|
|
153
|
+
const MANIFEST_DOC_ID = 'manifest'
|
|
154
|
+
|
|
155
|
+
/** Fixed document id for the single bucket-key record persisted via its own local-only `IndexedDBSyncStorage`. */
|
|
156
|
+
const KEY_DOC_ID = 'bucket-key'
|
|
157
|
+
|
|
158
|
+
// ---------------------------------------------------------------------------
|
|
159
|
+
// Crypto helpers -- same conventions as peer-encrypted-store.mjs (Node.js
|
|
160
|
+
// `node:crypto` first for testability, WebCrypto `crypto.subtle` fallback),
|
|
161
|
+
// duplicated locally rather than shared, matching this family's existing
|
|
162
|
+
// convention of small self-contained per-file crypto helpers.
|
|
163
|
+
// ---------------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Generate a random 256-bit AES key.
|
|
167
|
+
* @returns {Uint8Array}
|
|
168
|
+
*/
|
|
169
|
+
function generateKey() {
|
|
170
|
+
const key = new Uint8Array(32)
|
|
171
|
+
crypto.getRandomValues(key)
|
|
172
|
+
return key
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Generate a random 96-bit IV for GCM.
|
|
177
|
+
* @returns {Uint8Array}
|
|
178
|
+
*/
|
|
179
|
+
function generateIV() {
|
|
180
|
+
const iv = new Uint8Array(12)
|
|
181
|
+
crypto.getRandomValues(iv)
|
|
182
|
+
return iv
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Encrypt data with AES-256-GCM. Returns ciphertext with the 16-byte auth
|
|
187
|
+
* tag appended (matching `peer-encrypted-store.mjs`'s `aesEncrypt`).
|
|
188
|
+
* @param {Uint8Array} data - Plaintext bytes
|
|
189
|
+
* @param {Uint8Array} key - 32-byte AES key
|
|
190
|
+
* @param {Uint8Array} iv - 12-byte IV
|
|
191
|
+
* @returns {Promise<Uint8Array>} ciphertext || authTag
|
|
192
|
+
*/
|
|
193
|
+
async function aesEncrypt(data, key, iv) {
|
|
194
|
+
try {
|
|
195
|
+
const nodeCrypto = await import('node:crypto')
|
|
196
|
+
const cipher = nodeCrypto.createCipheriv('aes-256-gcm', key, iv)
|
|
197
|
+
const encrypted = cipher.update(data)
|
|
198
|
+
const final = cipher.final()
|
|
199
|
+
const authTag = cipher.getAuthTag()
|
|
200
|
+
|
|
201
|
+
const result = new Uint8Array(encrypted.length + final.length + authTag.length)
|
|
202
|
+
result.set(new Uint8Array(encrypted.buffer, encrypted.byteOffset, encrypted.length), 0)
|
|
203
|
+
if (final.length > 0) {
|
|
204
|
+
result.set(new Uint8Array(final.buffer, final.byteOffset, final.length), encrypted.length)
|
|
205
|
+
}
|
|
206
|
+
result.set(new Uint8Array(authTag.buffer, authTag.byteOffset, authTag.length), encrypted.length + final.length)
|
|
207
|
+
return result
|
|
208
|
+
} catch {
|
|
209
|
+
const subtle = globalThis.crypto?.subtle
|
|
210
|
+
if (!subtle) throw new Error('No crypto implementation available')
|
|
211
|
+
const cryptoKey = await subtle.importKey('raw', key, { name: 'AES-GCM' }, false, ['encrypt'])
|
|
212
|
+
const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv }, cryptoKey, data)
|
|
213
|
+
return new Uint8Array(encrypted)
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Decrypt AES-256-GCM ciphertext with a 16-byte auth tag appended.
|
|
219
|
+
* @param {Uint8Array} ciphertext - ciphertext || authTag
|
|
220
|
+
* @param {Uint8Array} key - 32-byte AES key
|
|
221
|
+
* @param {Uint8Array} iv - 12-byte IV
|
|
222
|
+
* @returns {Promise<Uint8Array>} plaintext
|
|
223
|
+
*/
|
|
224
|
+
async function aesDecrypt(ciphertext, key, iv) {
|
|
225
|
+
try {
|
|
226
|
+
const nodeCrypto = await import('node:crypto')
|
|
227
|
+
const authTag = ciphertext.slice(ciphertext.length - 16)
|
|
228
|
+
const data = ciphertext.slice(0, ciphertext.length - 16)
|
|
229
|
+
|
|
230
|
+
const decipher = nodeCrypto.createDecipheriv('aes-256-gcm', key, iv)
|
|
231
|
+
decipher.setAuthTag(authTag)
|
|
232
|
+
const decrypted = decipher.update(data)
|
|
233
|
+
const final = decipher.final()
|
|
234
|
+
|
|
235
|
+
const result = new Uint8Array(decrypted.length + final.length)
|
|
236
|
+
result.set(new Uint8Array(decrypted.buffer, decrypted.byteOffset, decrypted.length), 0)
|
|
237
|
+
if (final.length > 0) {
|
|
238
|
+
result.set(new Uint8Array(final.buffer, final.byteOffset, final.length), decrypted.length)
|
|
239
|
+
}
|
|
240
|
+
return result
|
|
241
|
+
} catch (err) {
|
|
242
|
+
if (err.message?.includes('Unsupported state') || err.code === 'ERR_OSSL_BAD_DECRYPT') {
|
|
243
|
+
throw new Error('Decryption failed: authentication tag mismatch')
|
|
244
|
+
}
|
|
245
|
+
const subtle = globalThis.crypto?.subtle
|
|
246
|
+
if (!subtle) throw err
|
|
247
|
+
const cryptoKey = await subtle.importKey('raw', key, { name: 'AES-GCM' }, false, ['decrypt'])
|
|
248
|
+
const decrypted = await subtle.decrypt({ name: 'AES-GCM', iv }, cryptoKey, ciphertext)
|
|
249
|
+
return new Uint8Array(decrypted)
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// ---------------------------------------------------------------------------
|
|
254
|
+
// Base64 helpers (same rationale/duplication as mesh-relay-backend.mjs / peer-encrypted-store.mjs)
|
|
255
|
+
// ---------------------------------------------------------------------------
|
|
256
|
+
|
|
257
|
+
/** @param {Uint8Array} bytes @returns {string} */
|
|
258
|
+
function toBase64(bytes) {
|
|
259
|
+
if (typeof Buffer !== 'undefined') {
|
|
260
|
+
return Buffer.from(bytes).toString('base64')
|
|
261
|
+
}
|
|
262
|
+
return btoa(String.fromCharCode(...bytes))
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** @param {string} str @returns {Uint8Array} */
|
|
266
|
+
function fromBase64(str) {
|
|
267
|
+
if (typeof Buffer !== 'undefined') {
|
|
268
|
+
return new Uint8Array(Buffer.from(str, 'base64'))
|
|
269
|
+
}
|
|
270
|
+
const bin = atob(str)
|
|
271
|
+
const bytes = new Uint8Array(bin.length)
|
|
272
|
+
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
|
273
|
+
return bytes
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Constant-time-ish byte equality (length-checked first; not a security-critical comparison, just correctness). @param {Uint8Array} a @param {Uint8Array} b @returns {boolean} */
|
|
277
|
+
function bytesEqual(a, b) {
|
|
278
|
+
if (a.length !== b.length) return false
|
|
279
|
+
for (let i = 0; i < a.length; i++) {
|
|
280
|
+
if (a[i] !== b[i]) return false
|
|
281
|
+
}
|
|
282
|
+
return true
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// ---------------------------------------------------------------------------
|
|
286
|
+
// CloudStorageBackend
|
|
287
|
+
// ---------------------------------------------------------------------------
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* A `Backend` exposing a durable, encrypted-at-rest, single-peer S3-like
|
|
291
|
+
* object store over a JSON-command-over-socket protocol.
|
|
292
|
+
*
|
|
293
|
+
* @extends Backend
|
|
294
|
+
*/
|
|
295
|
+
export class CloudStorageBackend extends Backend {
|
|
296
|
+
/** @type {string} */
|
|
297
|
+
#bucket
|
|
298
|
+
|
|
299
|
+
/** @type {import('@johnhenry/browsermesh-sync').IndexedDBChunkStore} */
|
|
300
|
+
#chunkStore
|
|
301
|
+
|
|
302
|
+
/** @type {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} */
|
|
303
|
+
#manifestStorage
|
|
304
|
+
|
|
305
|
+
/** @type {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} local-only, never CRDT-synced */
|
|
306
|
+
#keyStorage
|
|
307
|
+
|
|
308
|
+
/** @type {import('@johnhenry/browsermesh-primitives').LWWMap} */
|
|
309
|
+
#manifest = new LWWMap()
|
|
310
|
+
|
|
311
|
+
/** @type {Uint8Array|null} 32-byte AES-256-GCM bucket key */
|
|
312
|
+
#bucketKey = null
|
|
313
|
+
|
|
314
|
+
/** @type {Promise<void>|null} in-flight readiness bootstrap, shared by concurrent callers */
|
|
315
|
+
#ready = null
|
|
316
|
+
|
|
317
|
+
/** @type {string} node id used as the LWWMap tiebreak/attribution for local writes */
|
|
318
|
+
#nodeId
|
|
319
|
+
|
|
320
|
+
/** @type {number} monotonic clock backing manifest write timestamps (see #nextTimestamp) */
|
|
321
|
+
#clock = 0
|
|
322
|
+
|
|
323
|
+
/** @type {Set<Function>} subscribers to local/merged manifest changes -- see onManifestChange() */
|
|
324
|
+
#manifestChangeListeners = new Set()
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* @type {((info: {key: string, entry: object}) => Promise<{durability: string, replicatedTo: string[]}>)|null}
|
|
328
|
+
* Phase G (`chunk-replication.mjs`) replication hook -- see
|
|
329
|
+
* `setReplicationHook()`'s doc comment.
|
|
330
|
+
*/
|
|
331
|
+
#replicationHook = null
|
|
332
|
+
|
|
333
|
+
/** @type {Function} */
|
|
334
|
+
#onLog
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* @param {object} opts
|
|
338
|
+
* @param {string} opts.bucket - Bucket name. Used to derive default
|
|
339
|
+
* database names for the chunk store / manifest storage / key storage
|
|
340
|
+
* (each gets its own IndexedDB database, so the bucket key is never
|
|
341
|
+
* colocated with the CRDT-synced manifest storage).
|
|
342
|
+
* @param {string} [opts.dbName] - Override the derived database name
|
|
343
|
+
* prefix (defaults to `cloud-storage-${bucket}`).
|
|
344
|
+
* @param {import('@johnhenry/browsermesh-sync').IndexedDBChunkStore} [opts.chunkStore]
|
|
345
|
+
* @param {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} [opts.manifestStorage]
|
|
346
|
+
* @param {import('@johnhenry/browsermesh-sync').IndexedDBSyncStorage} [opts.keyStorage]
|
|
347
|
+
* @param {string} [opts.nodeId] - Defaults to a random UUID.
|
|
348
|
+
* @param {Function} [opts.onLog]
|
|
349
|
+
*/
|
|
350
|
+
constructor({ bucket, dbName, chunkStore, manifestStorage, keyStorage, nodeId, onLog } = {}) {
|
|
351
|
+
super()
|
|
352
|
+
if (!bucket || typeof bucket !== 'string') {
|
|
353
|
+
throw new Error('CloudStorageBackend: bucket is required')
|
|
354
|
+
}
|
|
355
|
+
this.#bucket = bucket
|
|
356
|
+
const prefix = dbName || `cloud-storage-${bucket}`
|
|
357
|
+
|
|
358
|
+
this.#chunkStore = chunkStore || new IndexedDBChunkStore({ dbName: `${prefix}-chunks` })
|
|
359
|
+
this.#manifestStorage = manifestStorage || new IndexedDBSyncStorage({ dbName: `${prefix}-manifest` })
|
|
360
|
+
// Deliberately a separate IndexedDB database from the manifest's, so the
|
|
361
|
+
// bucket key is never colocated with (or accidentally swept up by) the
|
|
362
|
+
// CRDT-synced manifest storage once Phase F wires that into
|
|
363
|
+
// MeshSyncEngine.
|
|
364
|
+
this.#keyStorage = keyStorage || new IndexedDBSyncStorage({ dbName: `${prefix}-keys` })
|
|
365
|
+
|
|
366
|
+
this.#nodeId = nodeId || (crypto.randomUUID ? crypto.randomUUID() : `node-${Math.random().toString(36).slice(2)}`)
|
|
367
|
+
this.#onLog = onLog || (() => {})
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The bucket name this backend serves. */
|
|
371
|
+
get bucket() { return this.#bucket }
|
|
372
|
+
|
|
373
|
+
// -----------------------------------------------------------------------
|
|
374
|
+
// Backend API
|
|
375
|
+
// -----------------------------------------------------------------------
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Connect to the bucket's command service. `host`/`port` are accepted for
|
|
379
|
+
* `Backend` interface compatibility but ignored -- one `CloudStorageBackend`
|
|
380
|
+
* instance always serves its one bound bucket (same precedent as
|
|
381
|
+
* `FsServiceBackend.connect()`).
|
|
382
|
+
*
|
|
383
|
+
* @param {string} [host]
|
|
384
|
+
* @param {number} [port]
|
|
385
|
+
* @returns {Promise<import('@johnhenry/browsermesh-netway').StreamSocket>}
|
|
386
|
+
*/
|
|
387
|
+
async connect(host, port) {
|
|
388
|
+
const [clientSocket, serverSocket] = StreamSocket.createPair()
|
|
389
|
+
|
|
390
|
+
this.#handleConnection(serverSocket).catch((err) => {
|
|
391
|
+
this.#onLog('cloud-storage-backend:connection-error', { error: err?.message || String(err) })
|
|
392
|
+
serverSocket.close().catch(() => {})
|
|
393
|
+
})
|
|
394
|
+
|
|
395
|
+
return clientSocket
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** @param {import('@johnhenry/browsermesh-netway').StreamSocket} socket */
|
|
399
|
+
async #handleConnection(socket) {
|
|
400
|
+
const decoder = new TextDecoder()
|
|
401
|
+
const encoder = new TextEncoder()
|
|
402
|
+
|
|
403
|
+
while (true) {
|
|
404
|
+
const chunk = await socket.read()
|
|
405
|
+
if (chunk === null) break
|
|
406
|
+
|
|
407
|
+
let cmd
|
|
408
|
+
try {
|
|
409
|
+
cmd = JSON.parse(decoder.decode(chunk))
|
|
410
|
+
} catch {
|
|
411
|
+
await socket.write(encoder.encode(JSON.stringify({ error: 'Invalid JSON' })))
|
|
412
|
+
continue
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
let result
|
|
416
|
+
try {
|
|
417
|
+
result = await this.#handleOp(cmd)
|
|
418
|
+
} catch (err) {
|
|
419
|
+
result = { error: err?.message || String(err) }
|
|
420
|
+
}
|
|
421
|
+
await socket.write(encoder.encode(JSON.stringify(result)))
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* @param {object} cmd
|
|
427
|
+
* @returns {Promise<object>}
|
|
428
|
+
*/
|
|
429
|
+
async #handleOp(cmd) {
|
|
430
|
+
if (!cmd || typeof cmd !== 'object') return { error: 'Invalid command' }
|
|
431
|
+
|
|
432
|
+
switch (cmd.op) {
|
|
433
|
+
case 'put':
|
|
434
|
+
return this.#opPut(cmd)
|
|
435
|
+
case 'get':
|
|
436
|
+
return this.#opGet(cmd)
|
|
437
|
+
case 'delete':
|
|
438
|
+
return this.#opDelete(cmd)
|
|
439
|
+
case 'list':
|
|
440
|
+
return this.#opList(cmd)
|
|
441
|
+
case 'head':
|
|
442
|
+
return this.#opHead(cmd)
|
|
443
|
+
default:
|
|
444
|
+
return { error: `Unknown op: ${cmd.op}` }
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// -----------------------------------------------------------------------
|
|
449
|
+
// Ops
|
|
450
|
+
// -----------------------------------------------------------------------
|
|
451
|
+
|
|
452
|
+
async #opPut(cmd) {
|
|
453
|
+
if (!cmd.key || typeof cmd.key !== 'string') return { error: 'key is required' }
|
|
454
|
+
if (typeof cmd.data !== 'string') return { error: 'data (base64) is required' }
|
|
455
|
+
|
|
456
|
+
await this.#ensureReady()
|
|
457
|
+
|
|
458
|
+
const plaintext = fromBase64(cmd.data)
|
|
459
|
+
const chunks = await this.#encryptAndChunk(plaintext)
|
|
460
|
+
|
|
461
|
+
const previous = this.#manifest.get(cmd.key)
|
|
462
|
+
const entry = {
|
|
463
|
+
chunks,
|
|
464
|
+
size: plaintext.length,
|
|
465
|
+
contentType: cmd.contentType ?? null,
|
|
466
|
+
metadata: cmd.metadata ?? {},
|
|
467
|
+
version: (previous?.version || 0) + 1,
|
|
468
|
+
updatedAt: Date.now(),
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
this.#manifest.set(cmd.key, entry, this.#nextTimestamp(), this.#nodeId)
|
|
472
|
+
await this.#saveManifest()
|
|
473
|
+
this.#fireManifestChange()
|
|
474
|
+
|
|
475
|
+
const response = { stored: true, key: cmd.key, size: entry.size }
|
|
476
|
+
|
|
477
|
+
// Phase G durability contract: the local write above is ALREADY durable
|
|
478
|
+
// by this point -- everything from here on is a best-effort attempt to
|
|
479
|
+
// also report replication status, and must never delay this response
|
|
480
|
+
// indefinitely or turn a successful local write into a thrown error.
|
|
481
|
+
if (this.#replicationHook) {
|
|
482
|
+
try {
|
|
483
|
+
const result = await this.#replicationHook({ key: cmd.key, entry })
|
|
484
|
+
response.durability = result?.durability === 'replicated' ? 'replicated' : 'local-only'
|
|
485
|
+
response.replicatedTo = Array.isArray(result?.replicatedTo) ? result.replicatedTo : []
|
|
486
|
+
} catch (err) {
|
|
487
|
+
this.#onLog('cloud-storage-backend:replication-hook-error', { key: cmd.key, error: err?.message || String(err) })
|
|
488
|
+
response.durability = 'local-only'
|
|
489
|
+
response.replicatedTo = []
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
return response
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async #opGet(cmd) {
|
|
497
|
+
if (!cmd.key || typeof cmd.key !== 'string') return { error: 'key is required' }
|
|
498
|
+
await this.#ensureReady()
|
|
499
|
+
|
|
500
|
+
const entry = this.#manifest.get(cmd.key)
|
|
501
|
+
if (!entry) return { error: 'not found' }
|
|
502
|
+
|
|
503
|
+
const plaintext = await this.#fetchAndDecrypt(entry)
|
|
504
|
+
return {
|
|
505
|
+
data: toBase64(plaintext),
|
|
506
|
+
size: entry.size,
|
|
507
|
+
contentType: entry.contentType,
|
|
508
|
+
metadata: entry.metadata,
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
async #opDelete(cmd) {
|
|
513
|
+
if (!cmd.key || typeof cmd.key !== 'string') return { error: 'key is required' }
|
|
514
|
+
await this.#ensureReady()
|
|
515
|
+
|
|
516
|
+
this.#manifest.delete(cmd.key, this.#nextTimestamp(), this.#nodeId)
|
|
517
|
+
await this.#saveManifest()
|
|
518
|
+
this.#fireManifestChange()
|
|
519
|
+
|
|
520
|
+
return { deleted: true }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
async #opList(cmd) {
|
|
524
|
+
await this.#ensureReady()
|
|
525
|
+
const prefix = cmd.prefix || ''
|
|
526
|
+
const keys = []
|
|
527
|
+
for (const [key, entry] of this.#manifest.entries()) {
|
|
528
|
+
if (prefix && !key.startsWith(prefix)) continue
|
|
529
|
+
keys.push({ key, size: entry.size, updatedAt: entry.updatedAt })
|
|
530
|
+
}
|
|
531
|
+
return { keys }
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
async #opHead(cmd) {
|
|
535
|
+
if (!cmd.key || typeof cmd.key !== 'string') return { error: 'key is required' }
|
|
536
|
+
await this.#ensureReady()
|
|
537
|
+
|
|
538
|
+
const entry = this.#manifest.get(cmd.key)
|
|
539
|
+
if (!entry) return { error: 'not found' }
|
|
540
|
+
|
|
541
|
+
return {
|
|
542
|
+
size: entry.size,
|
|
543
|
+
contentType: entry.contentType,
|
|
544
|
+
metadata: entry.metadata,
|
|
545
|
+
updatedAt: entry.updatedAt,
|
|
546
|
+
version: entry.version,
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// -----------------------------------------------------------------------
|
|
551
|
+
// Encryption / chunking
|
|
552
|
+
// -----------------------------------------------------------------------
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Encrypt plaintext before chunking (per the plan's Design Decisions),
|
|
556
|
+
* slicing into `CHUNK_SIZE` pieces (`MeshFileTransfer`'s existing 256KB
|
|
557
|
+
* convention). CIDs are computed over ciphertext, not plaintext. A
|
|
558
|
+
* zero-length input still produces exactly one (empty-plaintext) chunk,
|
|
559
|
+
* matching S3's support for zero-byte objects.
|
|
560
|
+
*
|
|
561
|
+
* @param {Uint8Array} plaintext
|
|
562
|
+
* @returns {Promise<Array<{cid: string, iv: string}>>}
|
|
563
|
+
*/
|
|
564
|
+
async #encryptAndChunk(plaintext) {
|
|
565
|
+
const chunks = []
|
|
566
|
+
let offset = 0
|
|
567
|
+
do {
|
|
568
|
+
const slice = plaintext.subarray(offset, Math.min(offset + CHUNK_SIZE, plaintext.length))
|
|
569
|
+
const iv = generateIV()
|
|
570
|
+
const ciphertext = await aesEncrypt(slice, this.#bucketKey, iv)
|
|
571
|
+
const cid = await IndexedDBChunkStore.computeCid(ciphertext)
|
|
572
|
+
await this.#chunkStore.save(cid, ciphertext)
|
|
573
|
+
chunks.push({ cid, iv: toBase64(iv) })
|
|
574
|
+
offset += CHUNK_SIZE
|
|
575
|
+
} while (offset < plaintext.length)
|
|
576
|
+
return chunks
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Fetch each chunk in order, decrypt, and concatenate.
|
|
581
|
+
* @param {{chunks: Array<{cid: string, iv: string}>}} entry
|
|
582
|
+
* @returns {Promise<Uint8Array>}
|
|
583
|
+
*/
|
|
584
|
+
async #fetchAndDecrypt(entry) {
|
|
585
|
+
const parts = []
|
|
586
|
+
let total = 0
|
|
587
|
+
for (const { cid, iv } of entry.chunks) {
|
|
588
|
+
const ciphertext = await this.#chunkStore.get(cid)
|
|
589
|
+
if (!ciphertext) throw new Error(`missing chunk ${cid}`)
|
|
590
|
+
const plaintext = await aesDecrypt(ciphertext, this.#bucketKey, fromBase64(iv))
|
|
591
|
+
parts.push(plaintext)
|
|
592
|
+
total += plaintext.length
|
|
593
|
+
}
|
|
594
|
+
const result = new Uint8Array(total)
|
|
595
|
+
let pos = 0
|
|
596
|
+
for (const part of parts) {
|
|
597
|
+
result.set(part, pos)
|
|
598
|
+
pos += part.length
|
|
599
|
+
}
|
|
600
|
+
return result
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// -----------------------------------------------------------------------
|
|
604
|
+
// Readiness: load manifest + load-or-create bucket key
|
|
605
|
+
// -----------------------------------------------------------------------
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* Load the persisted manifest and bucket key on first use. Concurrent
|
|
609
|
+
* callers share the same in-flight bootstrap.
|
|
610
|
+
* @returns {Promise<void>}
|
|
611
|
+
*/
|
|
612
|
+
async #ensureReady() {
|
|
613
|
+
if (!this.#ready) {
|
|
614
|
+
this.#ready = Promise.all([this.#loadManifest(), this.#loadOrCreateKey()]).then(() => {})
|
|
615
|
+
}
|
|
616
|
+
return this.#ready
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async #loadManifest() {
|
|
620
|
+
const docs = await this.#manifestStorage.load()
|
|
621
|
+
if (docs && docs.length > 0) {
|
|
622
|
+
const doc = docs.find((d) => d.id === MANIFEST_DOC_ID) || docs[0]
|
|
623
|
+
this.#manifest = LWWMap.fromJSON(doc)
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
async #saveManifest() {
|
|
628
|
+
const json = this.#manifest.toJSON()
|
|
629
|
+
await this.#manifestStorage.save([{ id: MANIFEST_DOC_ID, ...json }])
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
async #loadOrCreateKey() {
|
|
633
|
+
// Idempotent guard: if `importKeyRaw()` (Phase E) already populated
|
|
634
|
+
// `#bucketKey` directly -- deliberately bypassing this method entirely,
|
|
635
|
+
// see that method's own doc comment -- never overwrite it with a freshly
|
|
636
|
+
// generated key just because `#ensureReady()` also happened to run.
|
|
637
|
+
if (this.#bucketKey) return
|
|
638
|
+
const docs = await this.#keyStorage.load()
|
|
639
|
+
if (docs && docs.length > 0) {
|
|
640
|
+
const doc = docs.find((d) => d.id === KEY_DOC_ID) || docs[0]
|
|
641
|
+
this.#bucketKey = fromBase64(doc.key)
|
|
642
|
+
return
|
|
643
|
+
}
|
|
644
|
+
this.#bucketKey = generateKey()
|
|
645
|
+
await this.#keyStorage.save([{ id: KEY_DOC_ID, key: toBase64(this.#bucketKey) }])
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// -----------------------------------------------------------------------
|
|
649
|
+
// Key export/import (Phase E: cross-peer bucket-key distribution)
|
|
650
|
+
// -----------------------------------------------------------------------
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Read the currently-persisted bucket key WITHOUT the auto-create side
|
|
654
|
+
* effect `#ensureReady()`/`#loadOrCreateKey()` has on first use. Returns
|
|
655
|
+
* `null` if this backend has never created or received a key yet.
|
|
656
|
+
*
|
|
657
|
+
* This exists specifically so Phase E's key-distribution service can ask
|
|
658
|
+
* "do I already hold this bucket's key" (to decide whether it can help
|
|
659
|
+
* relay it onward to a newly-granted peer) without accidentally
|
|
660
|
+
* *originating* a brand-new key as a side effect on a peer that was only
|
|
661
|
+
* ever meant to *receive* one -- calling `exportKeyRaw()` (below) for that
|
|
662
|
+
* same question would silently mint and persist a fresh, never-to-be-
|
|
663
|
+
* reconciled key on any peer that hasn't been granted access yet, which is
|
|
664
|
+
* exactly the bug this method avoids.
|
|
665
|
+
*
|
|
666
|
+
* @returns {Promise<Uint8Array|null>}
|
|
667
|
+
*/
|
|
668
|
+
async peekKeyRaw() {
|
|
669
|
+
if (this.#bucketKey) return this.#bucketKey.slice()
|
|
670
|
+
const docs = await this.#keyStorage.load()
|
|
671
|
+
const doc = docs && docs.length > 0 ? (docs.find((d) => d.id === KEY_DOC_ID) || docs[0]) : null
|
|
672
|
+
return doc ? fromBase64(doc.key) : null
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/**
|
|
676
|
+
* Export this backend's raw 32-byte AES-256-GCM bucket key, generating one
|
|
677
|
+
* first via the normal `#ensureReady()` path if this backend has never
|
|
678
|
+
* been used yet (i.e. the same auto-create semantics every other op has).
|
|
679
|
+
* Intended for a peer that legitimately already owns/administers this
|
|
680
|
+
* bucket to hand its key to Phase E's key-distribution service for sending
|
|
681
|
+
* to a newly-granted peer -- NOT for a receive-only instance to call before
|
|
682
|
+
* it has ever received anything (use `peekKeyRaw()` for that question
|
|
683
|
+
* instead, so as to not auto-create a key that would then need reconciling
|
|
684
|
+
* with whatever arrives later).
|
|
685
|
+
*
|
|
686
|
+
* @returns {Promise<Uint8Array>}
|
|
687
|
+
*/
|
|
688
|
+
async exportKeyRaw() {
|
|
689
|
+
await this.#ensureReady()
|
|
690
|
+
return this.#bucketKey.slice()
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Adopt received raw key material (32 bytes), e.g. from Phase E's
|
|
695
|
+
* key-distribution service after it decrypts a delivered bucket key --
|
|
696
|
+
* WITHOUT going through `#ensureReady()`/`#loadOrCreateKey()`'s
|
|
697
|
+
* auto-generate path, so a fresh `CloudStorageBackend` instance
|
|
698
|
+
* constructed purely to receive a key never races its own local
|
|
699
|
+
* key-of-nothing generation against the key actually arriving. Persists
|
|
700
|
+
* the imported key to this backend's own local key storage exactly like a
|
|
701
|
+
* self-generated key, so it survives reload identically (see
|
|
702
|
+
* `#loadOrCreateKey`'s "reload" test coverage).
|
|
703
|
+
*
|
|
704
|
+
* Idempotent: importing the same key bytes that are already stored is a
|
|
705
|
+
* silent no-op. By default, importing DIFFERENT key bytes than whatever is
|
|
706
|
+
* already stored throws rather than silently clobbering local state that
|
|
707
|
+
* may already have encrypted chunks written under the existing key -- pass
|
|
708
|
+
* `{ overwrite: true }` to force replacement (there is no supported way to
|
|
709
|
+
* re-encrypt already-written chunks under the new key; this is an escape
|
|
710
|
+
* hatch for callers who know what they're doing, e.g. tests).
|
|
711
|
+
*
|
|
712
|
+
* @param {Uint8Array} rawKeyBytes - Exactly 32 bytes.
|
|
713
|
+
* @param {object} [opts]
|
|
714
|
+
* @param {boolean} [opts.overwrite=false]
|
|
715
|
+
* @returns {Promise<void>}
|
|
716
|
+
*/
|
|
717
|
+
async importKeyRaw(rawKeyBytes, { overwrite = false } = {}) {
|
|
718
|
+
if (!(rawKeyBytes instanceof Uint8Array) || rawKeyBytes.length !== 32) {
|
|
719
|
+
throw new Error('CloudStorageBackend.importKeyRaw: rawKeyBytes must be a 32-byte Uint8Array')
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
const existing = await this.peekKeyRaw()
|
|
723
|
+
if (existing && !overwrite) {
|
|
724
|
+
if (!bytesEqual(existing, rawKeyBytes)) {
|
|
725
|
+
throw new Error(
|
|
726
|
+
'CloudStorageBackend.importKeyRaw: a different bucket key is already stored locally ' +
|
|
727
|
+
'-- pass { overwrite: true } to replace it (existing encrypted chunks will not be re-encrypted)',
|
|
728
|
+
)
|
|
729
|
+
}
|
|
730
|
+
this.#bucketKey = existing
|
|
731
|
+
return
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
this.#bucketKey = rawKeyBytes.slice()
|
|
735
|
+
await this.#keyStorage.save([{ id: KEY_DOC_ID, key: toBase64(this.#bucketKey) }])
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// -----------------------------------------------------------------------
|
|
739
|
+
// Raw chunk access (Phase G: chunk-replication.mjs)
|
|
740
|
+
//
|
|
741
|
+
// Opaque ciphertext chunk read/write access, bypassing encryption/
|
|
742
|
+
// decryption and the manifest entirely -- a replica peer stores/serves
|
|
743
|
+
// ciphertext bytes it may not even hold the bucket key for yet (Phase E's
|
|
744
|
+
// key delivery and Phase G's chunk replication are independent and can
|
|
745
|
+
// complete in either order), and content-addressing (the CID is computed
|
|
746
|
+
// over ciphertext, per this file's Design Decisions) lets any peer verify
|
|
747
|
+
// a chunk's integrity without ever decrypting it.
|
|
748
|
+
// -----------------------------------------------------------------------
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Whether this backend's chunk store already holds ciphertext for `cid`,
|
|
752
|
+
* without touching the manifest or bucket key. Used by chunk-replication
|
|
753
|
+
* to answer "who has X" queries and to skip re-pushing chunks a replica
|
|
754
|
+
* already has.
|
|
755
|
+
* @param {string} cid
|
|
756
|
+
* @returns {Promise<boolean>}
|
|
757
|
+
*/
|
|
758
|
+
async hasChunkRaw(cid) {
|
|
759
|
+
return this.#chunkStore.has(cid)
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Read a chunk's raw ciphertext bytes by CID, or `null` if not held
|
|
764
|
+
* locally. Never decrypts -- callers (chunk-replication, serving a
|
|
765
|
+
* `chunk-fetch-request`, or eagerly pushing after a local `put()`) deal
|
|
766
|
+
* exclusively in opaque ciphertext bytes, exactly like `IndexedDBChunkStore`
|
|
767
|
+
* itself.
|
|
768
|
+
* @param {string} cid
|
|
769
|
+
* @returns {Promise<Uint8Array|null>}
|
|
770
|
+
*/
|
|
771
|
+
async getChunkRaw(cid) {
|
|
772
|
+
const bytes = await this.#chunkStore.get(cid)
|
|
773
|
+
return bytes ?? null
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Store received ciphertext bytes under `cid`, having first verified the
|
|
778
|
+
* bytes actually hash to the claimed CID (`IndexedDBChunkStore.computeCid`,
|
|
779
|
+
* the same content-addressing `#encryptAndChunk()` uses) -- a
|
|
780
|
+
* chunk-replication peer must never trust a wire-supplied (cid, bytes)
|
|
781
|
+
* pair blindly, or a malicious/buggy sender could poison this peer's
|
|
782
|
+
* chunk store with bytes that don't match the CID a manifest entry
|
|
783
|
+
* elsewhere points to. Idempotent: writing already-identical bytes for a
|
|
784
|
+
* CID this store already holds is a harmless no-op write.
|
|
785
|
+
* @param {string} cid
|
|
786
|
+
* @param {Uint8Array} bytes
|
|
787
|
+
* @returns {Promise<void>}
|
|
788
|
+
* @throws {Error} if `bytes` does not hash to `cid`, or the arguments are malformed.
|
|
789
|
+
*/
|
|
790
|
+
async putChunkRaw(cid, bytes) {
|
|
791
|
+
if (typeof cid !== 'string' || !cid) {
|
|
792
|
+
throw new Error('CloudStorageBackend.putChunkRaw: cid is required')
|
|
793
|
+
}
|
|
794
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
795
|
+
throw new Error('CloudStorageBackend.putChunkRaw: bytes must be a Uint8Array')
|
|
796
|
+
}
|
|
797
|
+
const computed = await IndexedDBChunkStore.computeCid(bytes)
|
|
798
|
+
if (computed !== cid) {
|
|
799
|
+
throw new Error(`CloudStorageBackend.putChunkRaw: bytes do not hash to claimed cid (expected ${cid}, computed ${computed})`)
|
|
800
|
+
}
|
|
801
|
+
await this.#chunkStore.save(cid, bytes)
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
// -----------------------------------------------------------------------
|
|
805
|
+
// Replication hook (Phase G: chunk-replication.mjs)
|
|
806
|
+
// -----------------------------------------------------------------------
|
|
807
|
+
|
|
808
|
+
/**
|
|
809
|
+
* Install (or clear, passing `null`/omitting) a hook that `put()`'s
|
|
810
|
+
* JSON-command response awaits before replying to the client, so `put()`'s
|
|
811
|
+
* returned `{durability, replicatedTo}` reflects a REAL attempt to push
|
|
812
|
+
* the just-written chunks to connected, admin-designated replica peers --
|
|
813
|
+
* not just "the local write succeeded". See `#opPut()`'s call site for the
|
|
814
|
+
* exact contract: the hook receives `{key, entry}` (the just-written
|
|
815
|
+
* manifest entry) and must resolve to `{durability:
|
|
816
|
+
* 'local-only'|'replicated', replicatedTo: string[]}`. The hook itself
|
|
817
|
+
* should never throw or hang indefinitely, but `#opPut()` also
|
|
818
|
+
* defensively catches a misbehaving hook and falls back to
|
|
819
|
+
* `{durability: 'local-only', replicatedTo: []}` regardless, so a
|
|
820
|
+
* replication-layer bug can never turn an already-durable local write
|
|
821
|
+
* into a thrown error or an indefinite hang.
|
|
822
|
+
*
|
|
823
|
+
* Deliberately a post-construction setter, not a constructor option: a
|
|
824
|
+
* `CloudStorageBackend` is constructed standalone (Phase B) and
|
|
825
|
+
* `chunk-replication.mjs`'s `MeshService.attach()` (Phase G) wires itself
|
|
826
|
+
* in afterward, exactly like every other cross-cutting mesh concern in
|
|
827
|
+
* this plan (manifest sync, key distribution) composes on top of an
|
|
828
|
+
* already-constructed backend instance, never inside it.
|
|
829
|
+
*
|
|
830
|
+
* @param {((info: {key: string, entry: object}) => Promise<{durability: string, replicatedTo: string[]}>)|null} [hook]
|
|
831
|
+
*/
|
|
832
|
+
setReplicationHook(hook) {
|
|
833
|
+
this.#replicationHook = typeof hook === 'function' ? hook : null
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* A monotonic millisecond-ish clock for manifest write timestamps. Plain
|
|
838
|
+
* `Date.now()` can return the same value for two writes issued in the
|
|
839
|
+
* same millisecond (very possible under `node --test`'s synchronous test
|
|
840
|
+
* bodies); `LWWRegister.set()` only accepts a same-timestamp write when
|
|
841
|
+
* the new writer's nodeId sorts strictly higher than the current one, so
|
|
842
|
+
* two same-millisecond writes from THIS SAME node/instance would silently
|
|
843
|
+
* be dropped without this. Not a substitute for the plan's documented
|
|
844
|
+
* caller-timestamp limitation (still a real limitation across peers) --
|
|
845
|
+
* only ensures a single backend instance's own sequential writes are
|
|
846
|
+
* always strictly ordered.
|
|
847
|
+
* @returns {number}
|
|
848
|
+
*/
|
|
849
|
+
#nextTimestamp() {
|
|
850
|
+
const now = Date.now()
|
|
851
|
+
this.#clock = now > this.#clock ? now : this.#clock + 1
|
|
852
|
+
return this.#clock
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// -----------------------------------------------------------------------
|
|
856
|
+
// Manifest sync surface (Phase F, `manifest-sync.mjs`)
|
|
857
|
+
//
|
|
858
|
+
// Deliberately narrow: this class hands out/accepts raw LWWMap wire JSON
|
|
859
|
+
// and never itself decides whether a remote entry is authorized -- see
|
|
860
|
+
// this file's module doc comment and `manifest-sync.mjs`'s module doc
|
|
861
|
+
// comment for the full design.
|
|
862
|
+
// -----------------------------------------------------------------------
|
|
863
|
+
|
|
864
|
+
/**
|
|
865
|
+
* The current manifest CRDT state, in the exact shape `LWWMap.toJSON()`/
|
|
866
|
+
* `LWWMap.fromJSON()` use (`{entries: {key: {value, timestamp, nodeId,
|
|
867
|
+
* tombstone}}}`), including tombstoned keys (needed so a peer merging this
|
|
868
|
+
* snapshot can correctly resolve a delete that raced a concurrent put on
|
|
869
|
+
* another peer).
|
|
870
|
+
* @returns {Promise<object>}
|
|
871
|
+
*/
|
|
872
|
+
async getManifestSnapshot() {
|
|
873
|
+
await this.#ensureReady()
|
|
874
|
+
return this.#manifest.toJSON()
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/**
|
|
878
|
+
* Merge externally-vetted manifest entries into the local manifest and
|
|
879
|
+
* persist the result. `sanitizedCrdtJSON` must already have had any
|
|
880
|
+
* unauthorized entries filtered out by the caller (`manifest-sync.mjs`) --
|
|
881
|
+
* this method performs the LWWMap merge and nothing else, exactly the same
|
|
882
|
+
* per-key last-write-wins resolution `LWWMap.merge()` always uses (see the
|
|
883
|
+
* module doc comment's "known limitation" note). Fires the same
|
|
884
|
+
* `onManifestChange()` notification a local `put`/`delete` does, so an
|
|
885
|
+
* accepted remote change is eligible to be re-broadcast onward (multi-hop
|
|
886
|
+
* propagation) exactly like a local write.
|
|
887
|
+
* @param {{entries: Record<string, {value: *, timestamp: number, nodeId: string, tombstone?: boolean}>}} sanitizedCrdtJSON
|
|
888
|
+
* @returns {Promise<void>}
|
|
889
|
+
*/
|
|
890
|
+
async mergeManifestEntries(sanitizedCrdtJSON) {
|
|
891
|
+
await this.#ensureReady()
|
|
892
|
+
const remote = LWWMap.fromJSON(sanitizedCrdtJSON)
|
|
893
|
+
this.#manifest = this.#manifest.merge(remote)
|
|
894
|
+
await this.#saveManifest()
|
|
895
|
+
this.#fireManifestChange()
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
/**
|
|
899
|
+
* Subscribe to manifest changes -- fired after every local `put`/`delete`
|
|
900
|
+
* AND after `mergeManifestEntries()`. `manifest-sync.mjs` uses this to
|
|
901
|
+
* know when to refresh its `MeshSyncEngine` copy and broadcast the
|
|
902
|
+
* bucket's current state to watching peers.
|
|
903
|
+
* @param {() => void} cb
|
|
904
|
+
* @returns {() => void} Unsubscribe.
|
|
905
|
+
*/
|
|
906
|
+
onManifestChange(cb) {
|
|
907
|
+
this.#manifestChangeListeners.add(cb)
|
|
908
|
+
return () => this.#manifestChangeListeners.delete(cb)
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** Notify all `onManifestChange()` subscribers. Never throws -- a subscriber's own error is swallowed. */
|
|
912
|
+
#fireManifestChange() {
|
|
913
|
+
for (const cb of this.#manifestChangeListeners) {
|
|
914
|
+
try { cb() } catch { /* subscriber errors do not propagate */ }
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// -----------------------------------------------------------------------
|
|
919
|
+
// Teardown
|
|
920
|
+
// -----------------------------------------------------------------------
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* Close the underlying IndexedDB connections. Safe to call even if
|
|
924
|
+
* `connect()` was never called.
|
|
925
|
+
* @returns {Promise<void>}
|
|
926
|
+
*/
|
|
927
|
+
async close() {
|
|
928
|
+
this.#chunkStore.close?.()
|
|
929
|
+
this.#manifestStorage.close?.()
|
|
930
|
+
this.#keyStorage.close?.()
|
|
931
|
+
}
|
|
932
|
+
}
|