@noy-db/to-browser-local 0.1.0-pre.10
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/LICENSE +21 -0
- package/README.md +33 -0
- package/dist/index.cjs +244 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +62 -0
- package/dist/index.d.ts +62 -0
- package/dist/index.js +219 -0
- package/dist/index.js.map +1 -0
- package/package.json +70 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 vLannaAi
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# @noy-db/to-browser-local
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@noy-db/to-browser-local)
|
|
4
|
+
|
|
5
|
+
> localStorage adapter for noy-db with optional key obfuscation
|
|
6
|
+
|
|
7
|
+
Part of [**`@noy-db/hub`**](https://www.npmjs.com/package/@noy-db/hub) — the zero-knowledge, offline-first, encrypted document store.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm add @noy-db/hub @noy-db/to-browser-local
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## What it is
|
|
16
|
+
|
|
17
|
+
localStorage adapter for noy-db with optional key obfuscation
|
|
18
|
+
|
|
19
|
+
## Status
|
|
20
|
+
|
|
21
|
+
**Pre-release** (`0.1.0-pre.1`). API may change before `1.0`.
|
|
22
|
+
|
|
23
|
+
## Documentation
|
|
24
|
+
|
|
25
|
+
See the [main repository](https://github.com/vLannaAi/noy-db#readme) for setup, examples, and the full subsystem catalog.
|
|
26
|
+
|
|
27
|
+
- Source — [`packages/to-browser-local`](https://github.com/vLannaAi/noy-db/tree/main/packages/to-browser-local)
|
|
28
|
+
- Issues — [github.com/vLannaAi/noy-db/issues](https://github.com/vLannaAi/noy-db/issues)
|
|
29
|
+
- Spec — [`SPEC.md`](https://github.com/vLannaAi/noy-db/blob/main/SPEC.md)
|
|
30
|
+
|
|
31
|
+
## License
|
|
32
|
+
|
|
33
|
+
[MIT](./LICENSE) © vLannaAi
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
browserLocalStore: () => browserLocalStore
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
var import_hub = require("@noy-db/hub");
|
|
27
|
+
function browserLocalStore(options = {}) {
|
|
28
|
+
const prefix = options.prefix ?? "noydb";
|
|
29
|
+
const obfuscate = options.obfuscate ?? false;
|
|
30
|
+
const obfKey = obfuscate ? makeObfKey(prefix) : "";
|
|
31
|
+
return createLocalStorageAdapter(prefix, obfuscate, obfKey);
|
|
32
|
+
}
|
|
33
|
+
function fnv1a(str) {
|
|
34
|
+
let hash = 2166136261;
|
|
35
|
+
for (let i = 0; i < str.length; i++) {
|
|
36
|
+
hash ^= str.charCodeAt(i);
|
|
37
|
+
hash = Math.imul(hash, 16777619);
|
|
38
|
+
}
|
|
39
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
40
|
+
}
|
|
41
|
+
function hashComponent(value, obfuscate) {
|
|
42
|
+
return obfuscate ? fnv1a(value) : value;
|
|
43
|
+
}
|
|
44
|
+
function xorEncode(plaintext, key) {
|
|
45
|
+
const bytes = new TextEncoder().encode(plaintext);
|
|
46
|
+
const keyBytes = new TextEncoder().encode(key);
|
|
47
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
48
|
+
bytes[i] = bytes[i] ^ keyBytes[i % keyBytes.length];
|
|
49
|
+
}
|
|
50
|
+
let binary = "";
|
|
51
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
52
|
+
binary += String.fromCharCode(bytes[i]);
|
|
53
|
+
}
|
|
54
|
+
return btoa(binary);
|
|
55
|
+
}
|
|
56
|
+
function xorDecode(encoded, key) {
|
|
57
|
+
const binary = atob(encoded);
|
|
58
|
+
const bytes = new Uint8Array(binary.length);
|
|
59
|
+
const keyBytes = new TextEncoder().encode(key);
|
|
60
|
+
for (let i = 0; i < binary.length; i++) {
|
|
61
|
+
bytes[i] = binary.charCodeAt(i) ^ keyBytes[i % keyBytes.length];
|
|
62
|
+
}
|
|
63
|
+
return new TextDecoder().decode(bytes);
|
|
64
|
+
}
|
|
65
|
+
function makeObfKey(prefix) {
|
|
66
|
+
return prefix + ":noydb-obf-key";
|
|
67
|
+
}
|
|
68
|
+
function wrapValue(envelope, collection, id, obfuscate, obfKey) {
|
|
69
|
+
if (!obfuscate) return JSON.stringify(envelope);
|
|
70
|
+
let safeEnvelope = envelope;
|
|
71
|
+
if (!envelope._iv && envelope._data) {
|
|
72
|
+
safeEnvelope = { ...safeEnvelope, _data: xorEncode(envelope._data, obfKey) };
|
|
73
|
+
}
|
|
74
|
+
if (envelope._by) {
|
|
75
|
+
safeEnvelope = { ...safeEnvelope, _by: xorEncode(envelope._by, obfKey) };
|
|
76
|
+
}
|
|
77
|
+
const stored = {
|
|
78
|
+
_oi: xorEncode(id, obfKey),
|
|
79
|
+
_oc: xorEncode(collection, obfKey),
|
|
80
|
+
_e: safeEnvelope
|
|
81
|
+
};
|
|
82
|
+
return JSON.stringify(stored);
|
|
83
|
+
}
|
|
84
|
+
function unwrapValue(raw, obfuscate, obfKey) {
|
|
85
|
+
const parsed = JSON.parse(raw);
|
|
86
|
+
if (!obfuscate || !("_e" in parsed)) {
|
|
87
|
+
const env = parsed;
|
|
88
|
+
return { envelope: env, origId: "", origCol: "" };
|
|
89
|
+
}
|
|
90
|
+
let envelope = parsed._e;
|
|
91
|
+
if (!envelope._iv && envelope._data) {
|
|
92
|
+
envelope = { ...envelope, _data: xorDecode(envelope._data, obfKey) };
|
|
93
|
+
}
|
|
94
|
+
if (envelope._by) {
|
|
95
|
+
envelope = { ...envelope, _by: xorDecode(envelope._by, obfKey) };
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
envelope,
|
|
99
|
+
origId: xorDecode(parsed._oi, obfKey),
|
|
100
|
+
origCol: xorDecode(parsed._oc, obfKey)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function createLocalStorageAdapter(prefix, obfuscate, obfKey) {
|
|
104
|
+
function key(vault, collection, id) {
|
|
105
|
+
return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:${hashComponent(id, obfuscate)}`;
|
|
106
|
+
}
|
|
107
|
+
function collectionPrefix(vault, collection) {
|
|
108
|
+
return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:`;
|
|
109
|
+
}
|
|
110
|
+
function compartmentPrefix(vault) {
|
|
111
|
+
return `${prefix}:${hashComponent(vault, obfuscate)}:`;
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
name: "browser:localStorage",
|
|
115
|
+
async get(vault, collection, id) {
|
|
116
|
+
const data = localStorage.getItem(key(vault, collection, id));
|
|
117
|
+
if (!data) return null;
|
|
118
|
+
return unwrapValue(data, obfuscate, obfKey).envelope;
|
|
119
|
+
},
|
|
120
|
+
async put(vault, collection, id, envelope, expectedVersion) {
|
|
121
|
+
const k = key(vault, collection, id);
|
|
122
|
+
if (expectedVersion !== void 0) {
|
|
123
|
+
const existing = localStorage.getItem(k);
|
|
124
|
+
if (existing) {
|
|
125
|
+
const current = unwrapValue(existing, obfuscate, obfKey).envelope;
|
|
126
|
+
if (current._v !== expectedVersion) {
|
|
127
|
+
throw new import_hub.ConflictError(current._v, `Version conflict: expected ${expectedVersion}, found ${current._v}`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
localStorage.setItem(k, wrapValue(envelope, collection, id, obfuscate, obfKey));
|
|
132
|
+
},
|
|
133
|
+
async delete(vault, collection, id) {
|
|
134
|
+
localStorage.removeItem(key(vault, collection, id));
|
|
135
|
+
},
|
|
136
|
+
async list(vault, collection) {
|
|
137
|
+
const pfx = collectionPrefix(vault, collection);
|
|
138
|
+
const ids = [];
|
|
139
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
140
|
+
const k = localStorage.key(i);
|
|
141
|
+
if (!k?.startsWith(pfx)) continue;
|
|
142
|
+
if (obfuscate) {
|
|
143
|
+
const raw = localStorage.getItem(k);
|
|
144
|
+
if (raw) {
|
|
145
|
+
const { origId } = unwrapValue(raw, true, obfKey);
|
|
146
|
+
ids.push(origId);
|
|
147
|
+
}
|
|
148
|
+
} else {
|
|
149
|
+
ids.push(k.slice(pfx.length));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return ids;
|
|
153
|
+
},
|
|
154
|
+
async loadAll(vault) {
|
|
155
|
+
const pfx = compartmentPrefix(vault);
|
|
156
|
+
const snapshot = {};
|
|
157
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
158
|
+
const k = localStorage.key(i);
|
|
159
|
+
if (!k?.startsWith(pfx)) continue;
|
|
160
|
+
const raw = localStorage.getItem(k);
|
|
161
|
+
if (!raw) continue;
|
|
162
|
+
let collection;
|
|
163
|
+
let id;
|
|
164
|
+
if (obfuscate) {
|
|
165
|
+
const { envelope, origId, origCol } = unwrapValue(raw, true, obfKey);
|
|
166
|
+
if (origCol.startsWith("_")) continue;
|
|
167
|
+
collection = origCol;
|
|
168
|
+
id = origId;
|
|
169
|
+
if (!snapshot[collection]) snapshot[collection] = {};
|
|
170
|
+
snapshot[collection][id] = envelope;
|
|
171
|
+
} else {
|
|
172
|
+
const rest = k.slice(pfx.length);
|
|
173
|
+
const colonIdx = rest.indexOf(":");
|
|
174
|
+
if (colonIdx < 0) continue;
|
|
175
|
+
collection = rest.slice(0, colonIdx);
|
|
176
|
+
id = rest.slice(colonIdx + 1);
|
|
177
|
+
if (collection.startsWith("_")) continue;
|
|
178
|
+
if (!snapshot[collection]) snapshot[collection] = {};
|
|
179
|
+
snapshot[collection][id] = JSON.parse(raw);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return snapshot;
|
|
183
|
+
},
|
|
184
|
+
async saveAll(vault, data) {
|
|
185
|
+
for (const [collection, records] of Object.entries(data)) {
|
|
186
|
+
for (const [id, envelope] of Object.entries(records)) {
|
|
187
|
+
localStorage.setItem(
|
|
188
|
+
key(vault, collection, id),
|
|
189
|
+
wrapValue(envelope, collection, id, obfuscate, obfKey)
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
async ping() {
|
|
195
|
+
try {
|
|
196
|
+
const testKey = `${prefix}:__ping__`;
|
|
197
|
+
localStorage.setItem(testKey, "1");
|
|
198
|
+
localStorage.removeItem(testKey);
|
|
199
|
+
return true;
|
|
200
|
+
} catch {
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
/**
|
|
205
|
+
* Paginate over a collection. Cursor is a numeric offset (as a string)
|
|
206
|
+
* into the sorted localStorage key list. Sorting by key gives stable
|
|
207
|
+
* ordering across page fetches even when other code is mutating
|
|
208
|
+
* unrelated keys in the same prefix.
|
|
209
|
+
*
|
|
210
|
+
* Note: localStorage's `length` and `key(i)` are O(N) per call in some
|
|
211
|
+
* browsers, so listing the matching keys upfront is faster than
|
|
212
|
+
* iterating in slices.
|
|
213
|
+
*/
|
|
214
|
+
async listPage(vault, collection, cursor, limit = 100) {
|
|
215
|
+
const pfx = collectionPrefix(vault, collection);
|
|
216
|
+
const matchedKeys = [];
|
|
217
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
218
|
+
const k = localStorage.key(i);
|
|
219
|
+
if (k?.startsWith(pfx)) matchedKeys.push(k);
|
|
220
|
+
}
|
|
221
|
+
matchedKeys.sort();
|
|
222
|
+
const start = cursor ? parseInt(cursor, 10) : 0;
|
|
223
|
+
const end = Math.min(start + limit, matchedKeys.length);
|
|
224
|
+
const items = [];
|
|
225
|
+
for (let i = start; i < end; i++) {
|
|
226
|
+
const k = matchedKeys[i];
|
|
227
|
+
const raw = localStorage.getItem(k);
|
|
228
|
+
if (!raw) continue;
|
|
229
|
+
const { envelope, origId } = unwrapValue(raw, obfuscate, obfKey);
|
|
230
|
+
const id = obfuscate ? origId : k.slice(pfx.length);
|
|
231
|
+
items.push({ id, envelope });
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
items,
|
|
235
|
+
nextCursor: end < matchedKeys.length ? String(end) : null
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
241
|
+
0 && (module.exports = {
|
|
242
|
+
browserLocalStore
|
|
243
|
+
});
|
|
244
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-browser-local** — `localStorage`-backed NOYDB store.\n *\n * All data is stored under `localStorage` with keys of the form\n * `{prefix}:{vault}:{collection}:{id}`. CAS checks are synchronous and\n * inherently atomic within a single JS thread.\n *\n * ## When to use\n *\n * Use `@noy-db/to-browser-idb` for most browser applications — it supports\n * larger storage quotas and true atomic transactions. Prefer this store only\n * when IndexedDB is unavailable (rare) or when you need storage that survives\n * across `sessionStorage` clears but is inspectable without DevTools.\n *\n * ## Obfuscation mode\n *\n * Setting `obfuscate: true` replaces each key component with an FNV-1a hash\n * and XOR-encodes metadata (vault name, collection name, record ID, `_by`\n * attribution) so that the logical structure of the data is not visible to\n * browser extensions or DevTools. This is **not** encryption — the envelope\n * `_data` field is always AES-GCM ciphertext regardless of this setting.\n *\n * ## Capabilities\n *\n * | Capability | Value |\n * |---|---|\n * | `casAtomic` | `true` — synchronous single-threaded JS |\n * | `listPage` | ✓ — cursor-based pagination |\n * | `ping` | ✓ — round-trips a sentinel key |\n *\n * @packageDocumentation\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\n\n/**\n * Options for `browserLocalStore()`.\n *\n * All NOYDB data is stored in `localStorage` under `{prefix}:{vault}:{collection}:{id}`.\n * Enable `obfuscate` to replace each path component with an FNV-1a hash and\n * XOR-encode metadata so vault/collection/record names are not visible to\n * browser extensions or DevTools inspecting `localStorage`.\n */\nexport interface BrowserLocalOptions {\n /** Storage key prefix. Default: 'noydb'. */\n prefix?: string\n /** Obfuscate storage keys so collection/record names are not readable. Default: false. */\n obfuscate?: boolean\n}\n\n/**\n * Create a localStorage-backed store adapter.\n *\n * Key scheme (normal): `{prefix}:{vault}:{collection}:{id}`\n * Key scheme (obfuscated): `{prefix}:{hash}:{hash}:{hash}`\n *\n * StoreCapabilities:\n * casAtomic: true — localStorage ops are synchronous and inherently atomic\n * auth: { kind: 'browser-origin', flow: 'implicit', required: false }\n */\nexport function browserLocalStore(options: BrowserLocalOptions = {}): NoydbStore {\n const prefix = options.prefix ?? 'noydb'\n const obfuscate = options.obfuscate ?? false\n const obfKey = obfuscate ? makeObfKey(prefix) : ''\n\n return createLocalStorageAdapter(prefix, obfuscate, obfKey)\n}\n\n// ─── Key Obfuscation ───────────────────────────────────────────────────\n\n/**\n * FNV-1a 32-bit hash → 8-char hex string.\n * Not cryptographic — just makes keys opaque to casual inspection.\n */\nfunction fnv1a(str: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\nfunction hashComponent(value: string, obfuscate: boolean): string {\n return obfuscate ? fnv1a(value) : value\n}\n\n// ─── XOR Encode/Decode (makes metadata unreadable in storage) ──────────\n\n/** XOR-encode a string with a repeating key, return base64. */\nfunction xorEncode(plaintext: string, key: string): string {\n const bytes = new TextEncoder().encode(plaintext)\n const keyBytes = new TextEncoder().encode(key)\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = bytes[i]! ^ keyBytes[i % keyBytes.length]!\n }\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!)\n }\n return btoa(binary)\n}\n\n/** Decode a base64 XOR-encoded string. */\nfunction xorDecode(encoded: string, key: string): string {\n const binary = atob(encoded)\n const bytes = new Uint8Array(binary.length)\n const keyBytes = new TextEncoder().encode(key)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i) ^ keyBytes[i % keyBytes.length]!\n }\n return new TextDecoder().decode(bytes)\n}\n\n/** Stored value wraps envelope + encoded original key parts. */\ninterface StoredValue {\n /** Encoded original record ID. */\n _oi: string\n /** Encoded original collection name. */\n _oc: string\n /** The encrypted envelope. */\n _e: EncryptedEnvelope\n}\n\nfunction makeObfKey(prefix: string): string {\n return prefix + ':noydb-obf-key'\n}\n\nfunction wrapValue(envelope: EncryptedEnvelope, collection: string, id: string, obfuscate: boolean, obfKey: string): string {\n if (!obfuscate) return JSON.stringify(envelope)\n\n let safeEnvelope = envelope\n\n // If _data is plaintext (e.g. keyring: _iv is empty), XOR-encode it\n if (!envelope._iv && envelope._data) {\n safeEnvelope = { ...safeEnvelope, _data: xorEncode(envelope._data, obfKey) }\n }\n\n // XOR-encode _by (user attribution) if present\n if (envelope._by) {\n safeEnvelope = { ...safeEnvelope, _by: xorEncode(envelope._by, obfKey) }\n }\n\n const stored: StoredValue = {\n _oi: xorEncode(id, obfKey),\n _oc: xorEncode(collection, obfKey),\n _e: safeEnvelope,\n }\n return JSON.stringify(stored)\n}\n\nfunction unwrapValue(raw: string, obfuscate: boolean, obfKey: string): { envelope: EncryptedEnvelope; origId: string; origCol: string } {\n const parsed = JSON.parse(raw) as StoredValue | EncryptedEnvelope\n if (!obfuscate || !('_e' in parsed)) {\n const env = parsed as EncryptedEnvelope\n return { envelope: env, origId: '', origCol: '' }\n }\n\n let envelope = parsed._e\n // Decode _data if it was XOR-encoded (keyring entries with empty _iv)\n if (!envelope._iv && envelope._data) {\n envelope = { ...envelope, _data: xorDecode(envelope._data, obfKey) }\n }\n // Decode _by if it was XOR-encoded\n if (envelope._by) {\n envelope = { ...envelope, _by: xorDecode(envelope._by, obfKey) }\n }\n\n return {\n envelope,\n origId: xorDecode(parsed._oi, obfKey),\n origCol: xorDecode(parsed._oc, obfKey),\n }\n}\n\n// ─── localStorage Backend ──────────────────────────────────────────────\n\nfunction createLocalStorageAdapter(prefix: string, obfuscate: boolean, obfKey: string): NoydbStore {\n function key(vault: string, collection: string, id: string): string {\n return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:${hashComponent(id, obfuscate)}`\n }\n\n function collectionPrefix(vault: string, collection: string): string {\n return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:`\n }\n\n function compartmentPrefix(vault: string): string {\n return `${prefix}:${hashComponent(vault, obfuscate)}:`\n }\n\n return {\n name: 'browser:localStorage',\n\n async get(vault, collection, id) {\n const data = localStorage.getItem(key(vault, collection, id))\n if (!data) return null\n return unwrapValue(data, obfuscate, obfKey).envelope\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n const k = key(vault, collection, id)\n\n if (expectedVersion !== undefined) {\n const existing = localStorage.getItem(k)\n if (existing) {\n const current = unwrapValue(existing, obfuscate, obfKey).envelope\n if (current._v !== expectedVersion) {\n throw new ConflictError(current._v, `Version conflict: expected ${expectedVersion}, found ${current._v}`)\n }\n }\n }\n\n localStorage.setItem(k, wrapValue(envelope, collection, id, obfuscate, obfKey))\n },\n\n async delete(vault, collection, id) {\n localStorage.removeItem(key(vault, collection, id))\n },\n\n async list(vault, collection) {\n const pfx = collectionPrefix(vault, collection)\n const ids: string[] = []\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i)\n if (!k?.startsWith(pfx)) continue\n\n if (obfuscate) {\n const raw = localStorage.getItem(k)\n if (raw) {\n const { origId } = unwrapValue(raw, true, obfKey)\n ids.push(origId)\n }\n } else {\n ids.push(k.slice(pfx.length))\n }\n }\n return ids\n },\n\n async loadAll(vault) {\n const pfx = compartmentPrefix(vault)\n const snapshot: VaultSnapshot = {}\n\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i)\n if (!k?.startsWith(pfx)) continue\n\n const raw = localStorage.getItem(k)\n if (!raw) continue\n\n let collection: string\n let id: string\n\n if (obfuscate) {\n const { envelope, origId, origCol } = unwrapValue(raw, true, obfKey)\n if (origCol.startsWith('_')) continue\n collection = origCol\n id = origId\n if (!snapshot[collection]) snapshot[collection] = {}\n snapshot[collection]![id] = envelope\n } else {\n const rest = k.slice(pfx.length)\n const colonIdx = rest.indexOf(':')\n if (colonIdx < 0) continue\n collection = rest.slice(0, colonIdx)\n id = rest.slice(colonIdx + 1)\n if (collection.startsWith('_')) continue\n if (!snapshot[collection]) snapshot[collection] = {}\n snapshot[collection]![id] = JSON.parse(raw) as EncryptedEnvelope\n }\n }\n\n return snapshot\n },\n\n async saveAll(vault, data) {\n for (const [collection, records] of Object.entries(data)) {\n for (const [id, envelope] of Object.entries(records)) {\n localStorage.setItem(\n key(vault, collection, id),\n wrapValue(envelope, collection, id, obfuscate, obfKey),\n )\n }\n }\n },\n\n async ping() {\n try {\n const testKey = `${prefix}:__ping__`\n localStorage.setItem(testKey, '1')\n localStorage.removeItem(testKey)\n return true\n } catch {\n return false\n }\n },\n\n /**\n * Paginate over a collection. Cursor is a numeric offset (as a string)\n * into the sorted localStorage key list. Sorting by key gives stable\n * ordering across page fetches even when other code is mutating\n * unrelated keys in the same prefix.\n *\n * Note: localStorage's `length` and `key(i)` are O(N) per call in some\n * browsers, so listing the matching keys upfront is faster than\n * iterating in slices.\n */\n async listPage(vault, collection, cursor, limit = 100) {\n const pfx = collectionPrefix(vault, collection)\n const matchedKeys: string[] = []\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i)\n if (k?.startsWith(pfx)) matchedKeys.push(k)\n }\n matchedKeys.sort()\n\n const start = cursor ? parseInt(cursor, 10) : 0\n const end = Math.min(start + limit, matchedKeys.length)\n\n const items: Array<{ id: string; envelope: EncryptedEnvelope }> = []\n for (let i = start; i < end; i++) {\n const k = matchedKeys[i]!\n const raw = localStorage.getItem(k)\n if (!raw) continue\n const { envelope, origId } = unwrapValue(raw, obfuscate, obfKey)\n const id = obfuscate ? origId : k.slice(pfx.length)\n items.push({ id, envelope })\n }\n\n return {\n items,\n nextCursor: end < matchedKeys.length ? String(end) : null,\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAkCA,iBAA8B;AA2BvB,SAAS,kBAAkB,UAA+B,CAAC,GAAe;AAC/E,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,SAAS,YAAY,WAAW,MAAM,IAAI;AAEhD,SAAO,0BAA0B,QAAQ,WAAW,MAAM;AAC5D;AAQA,SAAS,MAAM,KAAqB;AAClC,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,YAAQ,IAAI,WAAW,CAAC;AACxB,WAAO,KAAK,KAAK,MAAM,QAAU;AAAA,EACnC;AACA,UAAQ,SAAS,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAClD;AAEA,SAAS,cAAc,OAAe,WAA4B;AAChE,SAAO,YAAY,MAAM,KAAK,IAAI;AACpC;AAKA,SAAS,UAAU,WAAmB,KAAqB;AACzD,QAAM,QAAQ,IAAI,YAAY,EAAE,OAAO,SAAS;AAChD,QAAM,WAAW,IAAI,YAAY,EAAE,OAAO,GAAG;AAC7C,WAAS,IAAI,GAAG,IAAI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;AAAA;AAAA;AAAA;AAAA,IAYA,MAAM,SAAS,OAAO,YAAY,QAAQ,QAAQ,KAAK;AACrD,YAAM,MAAM,iBAAiB,OAAO,UAAU;AAC9C,YAAM,cAAwB,CAAC;AAC/B,eAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,cAAM,IAAI,aAAa,IAAI,CAAC;AAC5B,YAAI,GAAG,WAAW,GAAG,EAAG,aAAY,KAAK,CAAC;AAAA,MAC5C;AACA,kBAAY,KAAK;AAEjB,YAAM,QAAQ,SAAS,SAAS,QAAQ,EAAE,IAAI;AAC9C,YAAM,MAAM,KAAK,IAAI,QAAQ,OAAO,YAAY,MAAM;AAEtD,YAAM,QAA4D,CAAC;AACnE,eAAS,IAAI,OAAO,IAAI,KAAK,KAAK;AAChC,cAAM,IAAI,YAAY,CAAC;AACvB,cAAM,MAAM,aAAa,QAAQ,CAAC;AAClC,YAAI,CAAC,IAAK;AACV,cAAM,EAAE,UAAU,OAAO,IAAI,YAAY,KAAK,WAAW,MAAM;AAC/D,cAAM,KAAK,YAAY,SAAS,EAAE,MAAM,IAAI,MAAM;AAClD,cAAM,KAAK,EAAE,IAAI,SAAS,CAAC;AAAA,MAC7B;AAEA,aAAO;AAAA,QACL;AAAA,QACA,YAAY,MAAM,YAAY,SAAS,OAAO,GAAG,IAAI;AAAA,MACvD;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { NoydbStore } from '@noy-db/hub';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* **@noy-db/to-browser-local** — `localStorage`-backed NOYDB store.
|
|
5
|
+
*
|
|
6
|
+
* All data is stored under `localStorage` with keys of the form
|
|
7
|
+
* `{prefix}:{vault}:{collection}:{id}`. CAS checks are synchronous and
|
|
8
|
+
* inherently atomic within a single JS thread.
|
|
9
|
+
*
|
|
10
|
+
* ## When to use
|
|
11
|
+
*
|
|
12
|
+
* Use `@noy-db/to-browser-idb` for most browser applications — it supports
|
|
13
|
+
* larger storage quotas and true atomic transactions. Prefer this store only
|
|
14
|
+
* when IndexedDB is unavailable (rare) or when you need storage that survives
|
|
15
|
+
* across `sessionStorage` clears but is inspectable without DevTools.
|
|
16
|
+
*
|
|
17
|
+
* ## Obfuscation mode
|
|
18
|
+
*
|
|
19
|
+
* Setting `obfuscate: true` replaces each key component with an FNV-1a hash
|
|
20
|
+
* and XOR-encodes metadata (vault name, collection name, record ID, `_by`
|
|
21
|
+
* attribution) so that the logical structure of the data is not visible to
|
|
22
|
+
* browser extensions or DevTools. This is **not** encryption — the envelope
|
|
23
|
+
* `_data` field is always AES-GCM ciphertext regardless of this setting.
|
|
24
|
+
*
|
|
25
|
+
* ## Capabilities
|
|
26
|
+
*
|
|
27
|
+
* | Capability | Value |
|
|
28
|
+
* |---|---|
|
|
29
|
+
* | `casAtomic` | `true` — synchronous single-threaded JS |
|
|
30
|
+
* | `listPage` | ✓ — cursor-based pagination |
|
|
31
|
+
* | `ping` | ✓ — round-trips a sentinel key |
|
|
32
|
+
*
|
|
33
|
+
* @packageDocumentation
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Options for `browserLocalStore()`.
|
|
38
|
+
*
|
|
39
|
+
* All NOYDB data is stored in `localStorage` under `{prefix}:{vault}:{collection}:{id}`.
|
|
40
|
+
* Enable `obfuscate` to replace each path component with an FNV-1a hash and
|
|
41
|
+
* XOR-encode metadata so vault/collection/record names are not visible to
|
|
42
|
+
* browser extensions or DevTools inspecting `localStorage`.
|
|
43
|
+
*/
|
|
44
|
+
interface BrowserLocalOptions {
|
|
45
|
+
/** Storage key prefix. Default: 'noydb'. */
|
|
46
|
+
prefix?: string;
|
|
47
|
+
/** Obfuscate storage keys so collection/record names are not readable. Default: false. */
|
|
48
|
+
obfuscate?: boolean;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Create a localStorage-backed store adapter.
|
|
52
|
+
*
|
|
53
|
+
* Key scheme (normal): `{prefix}:{vault}:{collection}:{id}`
|
|
54
|
+
* Key scheme (obfuscated): `{prefix}:{hash}:{hash}:{hash}`
|
|
55
|
+
*
|
|
56
|
+
* StoreCapabilities:
|
|
57
|
+
* casAtomic: true — localStorage ops are synchronous and inherently atomic
|
|
58
|
+
* auth: { kind: 'browser-origin', flow: 'implicit', required: false }
|
|
59
|
+
*/
|
|
60
|
+
declare function browserLocalStore(options?: BrowserLocalOptions): NoydbStore;
|
|
61
|
+
|
|
62
|
+
export { type BrowserLocalOptions, browserLocalStore };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { NoydbStore } from '@noy-db/hub';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* **@noy-db/to-browser-local** — `localStorage`-backed NOYDB store.
|
|
5
|
+
*
|
|
6
|
+
* All data is stored under `localStorage` with keys of the form
|
|
7
|
+
* `{prefix}:{vault}:{collection}:{id}`. CAS checks are synchronous and
|
|
8
|
+
* inherently atomic within a single JS thread.
|
|
9
|
+
*
|
|
10
|
+
* ## When to use
|
|
11
|
+
*
|
|
12
|
+
* Use `@noy-db/to-browser-idb` for most browser applications — it supports
|
|
13
|
+
* larger storage quotas and true atomic transactions. Prefer this store only
|
|
14
|
+
* when IndexedDB is unavailable (rare) or when you need storage that survives
|
|
15
|
+
* across `sessionStorage` clears but is inspectable without DevTools.
|
|
16
|
+
*
|
|
17
|
+
* ## Obfuscation mode
|
|
18
|
+
*
|
|
19
|
+
* Setting `obfuscate: true` replaces each key component with an FNV-1a hash
|
|
20
|
+
* and XOR-encodes metadata (vault name, collection name, record ID, `_by`
|
|
21
|
+
* attribution) so that the logical structure of the data is not visible to
|
|
22
|
+
* browser extensions or DevTools. This is **not** encryption — the envelope
|
|
23
|
+
* `_data` field is always AES-GCM ciphertext regardless of this setting.
|
|
24
|
+
*
|
|
25
|
+
* ## Capabilities
|
|
26
|
+
*
|
|
27
|
+
* | Capability | Value |
|
|
28
|
+
* |---|---|
|
|
29
|
+
* | `casAtomic` | `true` — synchronous single-threaded JS |
|
|
30
|
+
* | `listPage` | ✓ — cursor-based pagination |
|
|
31
|
+
* | `ping` | ✓ — round-trips a sentinel key |
|
|
32
|
+
*
|
|
33
|
+
* @packageDocumentation
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Options for `browserLocalStore()`.
|
|
38
|
+
*
|
|
39
|
+
* All NOYDB data is stored in `localStorage` under `{prefix}:{vault}:{collection}:{id}`.
|
|
40
|
+
* Enable `obfuscate` to replace each path component with an FNV-1a hash and
|
|
41
|
+
* XOR-encode metadata so vault/collection/record names are not visible to
|
|
42
|
+
* browser extensions or DevTools inspecting `localStorage`.
|
|
43
|
+
*/
|
|
44
|
+
interface BrowserLocalOptions {
|
|
45
|
+
/** Storage key prefix. Default: 'noydb'. */
|
|
46
|
+
prefix?: string;
|
|
47
|
+
/** Obfuscate storage keys so collection/record names are not readable. Default: false. */
|
|
48
|
+
obfuscate?: boolean;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Create a localStorage-backed store adapter.
|
|
52
|
+
*
|
|
53
|
+
* Key scheme (normal): `{prefix}:{vault}:{collection}:{id}`
|
|
54
|
+
* Key scheme (obfuscated): `{prefix}:{hash}:{hash}:{hash}`
|
|
55
|
+
*
|
|
56
|
+
* StoreCapabilities:
|
|
57
|
+
* casAtomic: true — localStorage ops are synchronous and inherently atomic
|
|
58
|
+
* auth: { kind: 'browser-origin', flow: 'implicit', required: false }
|
|
59
|
+
*/
|
|
60
|
+
declare function browserLocalStore(options?: BrowserLocalOptions): NoydbStore;
|
|
61
|
+
|
|
62
|
+
export { type BrowserLocalOptions, browserLocalStore };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { ConflictError } from "@noy-db/hub";
|
|
3
|
+
function browserLocalStore(options = {}) {
|
|
4
|
+
const prefix = options.prefix ?? "noydb";
|
|
5
|
+
const obfuscate = options.obfuscate ?? false;
|
|
6
|
+
const obfKey = obfuscate ? makeObfKey(prefix) : "";
|
|
7
|
+
return createLocalStorageAdapter(prefix, obfuscate, obfKey);
|
|
8
|
+
}
|
|
9
|
+
function fnv1a(str) {
|
|
10
|
+
let hash = 2166136261;
|
|
11
|
+
for (let i = 0; i < str.length; i++) {
|
|
12
|
+
hash ^= str.charCodeAt(i);
|
|
13
|
+
hash = Math.imul(hash, 16777619);
|
|
14
|
+
}
|
|
15
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
16
|
+
}
|
|
17
|
+
function hashComponent(value, obfuscate) {
|
|
18
|
+
return obfuscate ? fnv1a(value) : value;
|
|
19
|
+
}
|
|
20
|
+
function xorEncode(plaintext, key) {
|
|
21
|
+
const bytes = new TextEncoder().encode(plaintext);
|
|
22
|
+
const keyBytes = new TextEncoder().encode(key);
|
|
23
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
24
|
+
bytes[i] = bytes[i] ^ keyBytes[i % keyBytes.length];
|
|
25
|
+
}
|
|
26
|
+
let binary = "";
|
|
27
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
28
|
+
binary += String.fromCharCode(bytes[i]);
|
|
29
|
+
}
|
|
30
|
+
return btoa(binary);
|
|
31
|
+
}
|
|
32
|
+
function xorDecode(encoded, key) {
|
|
33
|
+
const binary = atob(encoded);
|
|
34
|
+
const bytes = new Uint8Array(binary.length);
|
|
35
|
+
const keyBytes = new TextEncoder().encode(key);
|
|
36
|
+
for (let i = 0; i < binary.length; i++) {
|
|
37
|
+
bytes[i] = binary.charCodeAt(i) ^ keyBytes[i % keyBytes.length];
|
|
38
|
+
}
|
|
39
|
+
return new TextDecoder().decode(bytes);
|
|
40
|
+
}
|
|
41
|
+
function makeObfKey(prefix) {
|
|
42
|
+
return prefix + ":noydb-obf-key";
|
|
43
|
+
}
|
|
44
|
+
function wrapValue(envelope, collection, id, obfuscate, obfKey) {
|
|
45
|
+
if (!obfuscate) return JSON.stringify(envelope);
|
|
46
|
+
let safeEnvelope = envelope;
|
|
47
|
+
if (!envelope._iv && envelope._data) {
|
|
48
|
+
safeEnvelope = { ...safeEnvelope, _data: xorEncode(envelope._data, obfKey) };
|
|
49
|
+
}
|
|
50
|
+
if (envelope._by) {
|
|
51
|
+
safeEnvelope = { ...safeEnvelope, _by: xorEncode(envelope._by, obfKey) };
|
|
52
|
+
}
|
|
53
|
+
const stored = {
|
|
54
|
+
_oi: xorEncode(id, obfKey),
|
|
55
|
+
_oc: xorEncode(collection, obfKey),
|
|
56
|
+
_e: safeEnvelope
|
|
57
|
+
};
|
|
58
|
+
return JSON.stringify(stored);
|
|
59
|
+
}
|
|
60
|
+
function unwrapValue(raw, obfuscate, obfKey) {
|
|
61
|
+
const parsed = JSON.parse(raw);
|
|
62
|
+
if (!obfuscate || !("_e" in parsed)) {
|
|
63
|
+
const env = parsed;
|
|
64
|
+
return { envelope: env, origId: "", origCol: "" };
|
|
65
|
+
}
|
|
66
|
+
let envelope = parsed._e;
|
|
67
|
+
if (!envelope._iv && envelope._data) {
|
|
68
|
+
envelope = { ...envelope, _data: xorDecode(envelope._data, obfKey) };
|
|
69
|
+
}
|
|
70
|
+
if (envelope._by) {
|
|
71
|
+
envelope = { ...envelope, _by: xorDecode(envelope._by, obfKey) };
|
|
72
|
+
}
|
|
73
|
+
return {
|
|
74
|
+
envelope,
|
|
75
|
+
origId: xorDecode(parsed._oi, obfKey),
|
|
76
|
+
origCol: xorDecode(parsed._oc, obfKey)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function createLocalStorageAdapter(prefix, obfuscate, obfKey) {
|
|
80
|
+
function key(vault, collection, id) {
|
|
81
|
+
return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:${hashComponent(id, obfuscate)}`;
|
|
82
|
+
}
|
|
83
|
+
function collectionPrefix(vault, collection) {
|
|
84
|
+
return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:`;
|
|
85
|
+
}
|
|
86
|
+
function compartmentPrefix(vault) {
|
|
87
|
+
return `${prefix}:${hashComponent(vault, obfuscate)}:`;
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
name: "browser:localStorage",
|
|
91
|
+
async get(vault, collection, id) {
|
|
92
|
+
const data = localStorage.getItem(key(vault, collection, id));
|
|
93
|
+
if (!data) return null;
|
|
94
|
+
return unwrapValue(data, obfuscate, obfKey).envelope;
|
|
95
|
+
},
|
|
96
|
+
async put(vault, collection, id, envelope, expectedVersion) {
|
|
97
|
+
const k = key(vault, collection, id);
|
|
98
|
+
if (expectedVersion !== void 0) {
|
|
99
|
+
const existing = localStorage.getItem(k);
|
|
100
|
+
if (existing) {
|
|
101
|
+
const current = unwrapValue(existing, obfuscate, obfKey).envelope;
|
|
102
|
+
if (current._v !== expectedVersion) {
|
|
103
|
+
throw new ConflictError(current._v, `Version conflict: expected ${expectedVersion}, found ${current._v}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
localStorage.setItem(k, wrapValue(envelope, collection, id, obfuscate, obfKey));
|
|
108
|
+
},
|
|
109
|
+
async delete(vault, collection, id) {
|
|
110
|
+
localStorage.removeItem(key(vault, collection, id));
|
|
111
|
+
},
|
|
112
|
+
async list(vault, collection) {
|
|
113
|
+
const pfx = collectionPrefix(vault, collection);
|
|
114
|
+
const ids = [];
|
|
115
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
116
|
+
const k = localStorage.key(i);
|
|
117
|
+
if (!k?.startsWith(pfx)) continue;
|
|
118
|
+
if (obfuscate) {
|
|
119
|
+
const raw = localStorage.getItem(k);
|
|
120
|
+
if (raw) {
|
|
121
|
+
const { origId } = unwrapValue(raw, true, obfKey);
|
|
122
|
+
ids.push(origId);
|
|
123
|
+
}
|
|
124
|
+
} else {
|
|
125
|
+
ids.push(k.slice(pfx.length));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return ids;
|
|
129
|
+
},
|
|
130
|
+
async loadAll(vault) {
|
|
131
|
+
const pfx = compartmentPrefix(vault);
|
|
132
|
+
const snapshot = {};
|
|
133
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
134
|
+
const k = localStorage.key(i);
|
|
135
|
+
if (!k?.startsWith(pfx)) continue;
|
|
136
|
+
const raw = localStorage.getItem(k);
|
|
137
|
+
if (!raw) continue;
|
|
138
|
+
let collection;
|
|
139
|
+
let id;
|
|
140
|
+
if (obfuscate) {
|
|
141
|
+
const { envelope, origId, origCol } = unwrapValue(raw, true, obfKey);
|
|
142
|
+
if (origCol.startsWith("_")) continue;
|
|
143
|
+
collection = origCol;
|
|
144
|
+
id = origId;
|
|
145
|
+
if (!snapshot[collection]) snapshot[collection] = {};
|
|
146
|
+
snapshot[collection][id] = envelope;
|
|
147
|
+
} else {
|
|
148
|
+
const rest = k.slice(pfx.length);
|
|
149
|
+
const colonIdx = rest.indexOf(":");
|
|
150
|
+
if (colonIdx < 0) continue;
|
|
151
|
+
collection = rest.slice(0, colonIdx);
|
|
152
|
+
id = rest.slice(colonIdx + 1);
|
|
153
|
+
if (collection.startsWith("_")) continue;
|
|
154
|
+
if (!snapshot[collection]) snapshot[collection] = {};
|
|
155
|
+
snapshot[collection][id] = JSON.parse(raw);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return snapshot;
|
|
159
|
+
},
|
|
160
|
+
async saveAll(vault, data) {
|
|
161
|
+
for (const [collection, records] of Object.entries(data)) {
|
|
162
|
+
for (const [id, envelope] of Object.entries(records)) {
|
|
163
|
+
localStorage.setItem(
|
|
164
|
+
key(vault, collection, id),
|
|
165
|
+
wrapValue(envelope, collection, id, obfuscate, obfKey)
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
async ping() {
|
|
171
|
+
try {
|
|
172
|
+
const testKey = `${prefix}:__ping__`;
|
|
173
|
+
localStorage.setItem(testKey, "1");
|
|
174
|
+
localStorage.removeItem(testKey);
|
|
175
|
+
return true;
|
|
176
|
+
} catch {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
},
|
|
180
|
+
/**
|
|
181
|
+
* Paginate over a collection. Cursor is a numeric offset (as a string)
|
|
182
|
+
* into the sorted localStorage key list. Sorting by key gives stable
|
|
183
|
+
* ordering across page fetches even when other code is mutating
|
|
184
|
+
* unrelated keys in the same prefix.
|
|
185
|
+
*
|
|
186
|
+
* Note: localStorage's `length` and `key(i)` are O(N) per call in some
|
|
187
|
+
* browsers, so listing the matching keys upfront is faster than
|
|
188
|
+
* iterating in slices.
|
|
189
|
+
*/
|
|
190
|
+
async listPage(vault, collection, cursor, limit = 100) {
|
|
191
|
+
const pfx = collectionPrefix(vault, collection);
|
|
192
|
+
const matchedKeys = [];
|
|
193
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
194
|
+
const k = localStorage.key(i);
|
|
195
|
+
if (k?.startsWith(pfx)) matchedKeys.push(k);
|
|
196
|
+
}
|
|
197
|
+
matchedKeys.sort();
|
|
198
|
+
const start = cursor ? parseInt(cursor, 10) : 0;
|
|
199
|
+
const end = Math.min(start + limit, matchedKeys.length);
|
|
200
|
+
const items = [];
|
|
201
|
+
for (let i = start; i < end; i++) {
|
|
202
|
+
const k = matchedKeys[i];
|
|
203
|
+
const raw = localStorage.getItem(k);
|
|
204
|
+
if (!raw) continue;
|
|
205
|
+
const { envelope, origId } = unwrapValue(raw, obfuscate, obfKey);
|
|
206
|
+
const id = obfuscate ? origId : k.slice(pfx.length);
|
|
207
|
+
items.push({ id, envelope });
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
items,
|
|
211
|
+
nextCursor: end < matchedKeys.length ? String(end) : null
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
export {
|
|
217
|
+
browserLocalStore
|
|
218
|
+
};
|
|
219
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * **@noy-db/to-browser-local** — `localStorage`-backed NOYDB store.\n *\n * All data is stored under `localStorage` with keys of the form\n * `{prefix}:{vault}:{collection}:{id}`. CAS checks are synchronous and\n * inherently atomic within a single JS thread.\n *\n * ## When to use\n *\n * Use `@noy-db/to-browser-idb` for most browser applications — it supports\n * larger storage quotas and true atomic transactions. Prefer this store only\n * when IndexedDB is unavailable (rare) or when you need storage that survives\n * across `sessionStorage` clears but is inspectable without DevTools.\n *\n * ## Obfuscation mode\n *\n * Setting `obfuscate: true` replaces each key component with an FNV-1a hash\n * and XOR-encodes metadata (vault name, collection name, record ID, `_by`\n * attribution) so that the logical structure of the data is not visible to\n * browser extensions or DevTools. This is **not** encryption — the envelope\n * `_data` field is always AES-GCM ciphertext regardless of this setting.\n *\n * ## Capabilities\n *\n * | Capability | Value |\n * |---|---|\n * | `casAtomic` | `true` — synchronous single-threaded JS |\n * | `listPage` | ✓ — cursor-based pagination |\n * | `ping` | ✓ — round-trips a sentinel key |\n *\n * @packageDocumentation\n */\n\nimport type { NoydbStore, EncryptedEnvelope, VaultSnapshot } from '@noy-db/hub'\nimport { ConflictError } from '@noy-db/hub'\n\n/**\n * Options for `browserLocalStore()`.\n *\n * All NOYDB data is stored in `localStorage` under `{prefix}:{vault}:{collection}:{id}`.\n * Enable `obfuscate` to replace each path component with an FNV-1a hash and\n * XOR-encode metadata so vault/collection/record names are not visible to\n * browser extensions or DevTools inspecting `localStorage`.\n */\nexport interface BrowserLocalOptions {\n /** Storage key prefix. Default: 'noydb'. */\n prefix?: string\n /** Obfuscate storage keys so collection/record names are not readable. Default: false. */\n obfuscate?: boolean\n}\n\n/**\n * Create a localStorage-backed store adapter.\n *\n * Key scheme (normal): `{prefix}:{vault}:{collection}:{id}`\n * Key scheme (obfuscated): `{prefix}:{hash}:{hash}:{hash}`\n *\n * StoreCapabilities:\n * casAtomic: true — localStorage ops are synchronous and inherently atomic\n * auth: { kind: 'browser-origin', flow: 'implicit', required: false }\n */\nexport function browserLocalStore(options: BrowserLocalOptions = {}): NoydbStore {\n const prefix = options.prefix ?? 'noydb'\n const obfuscate = options.obfuscate ?? false\n const obfKey = obfuscate ? makeObfKey(prefix) : ''\n\n return createLocalStorageAdapter(prefix, obfuscate, obfKey)\n}\n\n// ─── Key Obfuscation ───────────────────────────────────────────────────\n\n/**\n * FNV-1a 32-bit hash → 8-char hex string.\n * Not cryptographic — just makes keys opaque to casual inspection.\n */\nfunction fnv1a(str: string): string {\n let hash = 0x811c9dc5\n for (let i = 0; i < str.length; i++) {\n hash ^= str.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\nfunction hashComponent(value: string, obfuscate: boolean): string {\n return obfuscate ? fnv1a(value) : value\n}\n\n// ─── XOR Encode/Decode (makes metadata unreadable in storage) ──────────\n\n/** XOR-encode a string with a repeating key, return base64. */\nfunction xorEncode(plaintext: string, key: string): string {\n const bytes = new TextEncoder().encode(plaintext)\n const keyBytes = new TextEncoder().encode(key)\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = bytes[i]! ^ keyBytes[i % keyBytes.length]!\n }\n let binary = ''\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!)\n }\n return btoa(binary)\n}\n\n/** Decode a base64 XOR-encoded string. */\nfunction xorDecode(encoded: string, key: string): string {\n const binary = atob(encoded)\n const bytes = new Uint8Array(binary.length)\n const keyBytes = new TextEncoder().encode(key)\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i) ^ keyBytes[i % keyBytes.length]!\n }\n return new TextDecoder().decode(bytes)\n}\n\n/** Stored value wraps envelope + encoded original key parts. */\ninterface StoredValue {\n /** Encoded original record ID. */\n _oi: string\n /** Encoded original collection name. */\n _oc: string\n /** The encrypted envelope. */\n _e: EncryptedEnvelope\n}\n\nfunction makeObfKey(prefix: string): string {\n return prefix + ':noydb-obf-key'\n}\n\nfunction wrapValue(envelope: EncryptedEnvelope, collection: string, id: string, obfuscate: boolean, obfKey: string): string {\n if (!obfuscate) return JSON.stringify(envelope)\n\n let safeEnvelope = envelope\n\n // If _data is plaintext (e.g. keyring: _iv is empty), XOR-encode it\n if (!envelope._iv && envelope._data) {\n safeEnvelope = { ...safeEnvelope, _data: xorEncode(envelope._data, obfKey) }\n }\n\n // XOR-encode _by (user attribution) if present\n if (envelope._by) {\n safeEnvelope = { ...safeEnvelope, _by: xorEncode(envelope._by, obfKey) }\n }\n\n const stored: StoredValue = {\n _oi: xorEncode(id, obfKey),\n _oc: xorEncode(collection, obfKey),\n _e: safeEnvelope,\n }\n return JSON.stringify(stored)\n}\n\nfunction unwrapValue(raw: string, obfuscate: boolean, obfKey: string): { envelope: EncryptedEnvelope; origId: string; origCol: string } {\n const parsed = JSON.parse(raw) as StoredValue | EncryptedEnvelope\n if (!obfuscate || !('_e' in parsed)) {\n const env = parsed as EncryptedEnvelope\n return { envelope: env, origId: '', origCol: '' }\n }\n\n let envelope = parsed._e\n // Decode _data if it was XOR-encoded (keyring entries with empty _iv)\n if (!envelope._iv && envelope._data) {\n envelope = { ...envelope, _data: xorDecode(envelope._data, obfKey) }\n }\n // Decode _by if it was XOR-encoded\n if (envelope._by) {\n envelope = { ...envelope, _by: xorDecode(envelope._by, obfKey) }\n }\n\n return {\n envelope,\n origId: xorDecode(parsed._oi, obfKey),\n origCol: xorDecode(parsed._oc, obfKey),\n }\n}\n\n// ─── localStorage Backend ──────────────────────────────────────────────\n\nfunction createLocalStorageAdapter(prefix: string, obfuscate: boolean, obfKey: string): NoydbStore {\n function key(vault: string, collection: string, id: string): string {\n return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:${hashComponent(id, obfuscate)}`\n }\n\n function collectionPrefix(vault: string, collection: string): string {\n return `${prefix}:${hashComponent(vault, obfuscate)}:${hashComponent(collection, obfuscate)}:`\n }\n\n function compartmentPrefix(vault: string): string {\n return `${prefix}:${hashComponent(vault, obfuscate)}:`\n }\n\n return {\n name: 'browser:localStorage',\n\n async get(vault, collection, id) {\n const data = localStorage.getItem(key(vault, collection, id))\n if (!data) return null\n return unwrapValue(data, obfuscate, obfKey).envelope\n },\n\n async put(vault, collection, id, envelope, expectedVersion) {\n const k = key(vault, collection, id)\n\n if (expectedVersion !== undefined) {\n const existing = localStorage.getItem(k)\n if (existing) {\n const current = unwrapValue(existing, obfuscate, obfKey).envelope\n if (current._v !== expectedVersion) {\n throw new ConflictError(current._v, `Version conflict: expected ${expectedVersion}, found ${current._v}`)\n }\n }\n }\n\n localStorage.setItem(k, wrapValue(envelope, collection, id, obfuscate, obfKey))\n },\n\n async delete(vault, collection, id) {\n localStorage.removeItem(key(vault, collection, id))\n },\n\n async list(vault, collection) {\n const pfx = collectionPrefix(vault, collection)\n const ids: string[] = []\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i)\n if (!k?.startsWith(pfx)) continue\n\n if (obfuscate) {\n const raw = localStorage.getItem(k)\n if (raw) {\n const { origId } = unwrapValue(raw, true, obfKey)\n ids.push(origId)\n }\n } else {\n ids.push(k.slice(pfx.length))\n }\n }\n return ids\n },\n\n async loadAll(vault) {\n const pfx = compartmentPrefix(vault)\n const snapshot: VaultSnapshot = {}\n\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i)\n if (!k?.startsWith(pfx)) continue\n\n const raw = localStorage.getItem(k)\n if (!raw) continue\n\n let collection: string\n let id: string\n\n if (obfuscate) {\n const { envelope, origId, origCol } = unwrapValue(raw, true, obfKey)\n if (origCol.startsWith('_')) continue\n collection = origCol\n id = origId\n if (!snapshot[collection]) snapshot[collection] = {}\n snapshot[collection]![id] = envelope\n } else {\n const rest = k.slice(pfx.length)\n const colonIdx = rest.indexOf(':')\n if (colonIdx < 0) continue\n collection = rest.slice(0, colonIdx)\n id = rest.slice(colonIdx + 1)\n if (collection.startsWith('_')) continue\n if (!snapshot[collection]) snapshot[collection] = {}\n snapshot[collection]![id] = JSON.parse(raw) as EncryptedEnvelope\n }\n }\n\n return snapshot\n },\n\n async saveAll(vault, data) {\n for (const [collection, records] of Object.entries(data)) {\n for (const [id, envelope] of Object.entries(records)) {\n localStorage.setItem(\n key(vault, collection, id),\n wrapValue(envelope, collection, id, obfuscate, obfKey),\n )\n }\n }\n },\n\n async ping() {\n try {\n const testKey = `${prefix}:__ping__`\n localStorage.setItem(testKey, '1')\n localStorage.removeItem(testKey)\n return true\n } catch {\n return false\n }\n },\n\n /**\n * Paginate over a collection. Cursor is a numeric offset (as a string)\n * into the sorted localStorage key list. Sorting by key gives stable\n * ordering across page fetches even when other code is mutating\n * unrelated keys in the same prefix.\n *\n * Note: localStorage's `length` and `key(i)` are O(N) per call in some\n * browsers, so listing the matching keys upfront is faster than\n * iterating in slices.\n */\n async listPage(vault, collection, cursor, limit = 100) {\n const pfx = collectionPrefix(vault, collection)\n const matchedKeys: string[] = []\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i)\n if (k?.startsWith(pfx)) matchedKeys.push(k)\n }\n matchedKeys.sort()\n\n const start = cursor ? parseInt(cursor, 10) : 0\n const end = Math.min(start + limit, matchedKeys.length)\n\n const items: Array<{ id: string; envelope: EncryptedEnvelope }> = []\n for (let i = start; i < end; i++) {\n const k = matchedKeys[i]!\n const raw = localStorage.getItem(k)\n if (!raw) continue\n const { envelope, origId } = unwrapValue(raw, obfuscate, obfKey)\n const id = obfuscate ? origId : k.slice(pfx.length)\n items.push({ id, envelope })\n }\n\n return {\n items,\n nextCursor: end < matchedKeys.length ? String(end) : null,\n }\n },\n }\n}\n"],"mappings":";AAkCA,SAAS,qBAAqB;AA2BvB,SAAS,kBAAkB,UAA+B,CAAC,GAAe;AAC/E,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,SAAS,YAAY,WAAW,MAAM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M,KAAK,EAAE,IAAI,SAAS,CAAC;AAAA,MAC7B;AAEA,aAAO;AAAA,QACL;AAAA,QACA,YAAY,MAAM,YAAY,SAAS,OAAO,GAAG,IAAI;AAAA,MACvD;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@noy-db/to-browser-local",
|
|
3
|
+
"version": "0.1.0-pre.10",
|
|
4
|
+
"description": "localStorage adapter for noy-db with optional key obfuscation",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "vLannaAi <vicio@lanna.ai>",
|
|
7
|
+
"homepage": "https://github.com/vLannaAi/noy-db/tree/main/packages/to-browser-local#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/vLannaAi/noy-db.git",
|
|
11
|
+
"directory": "packages/to-browser-local"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/vLannaAi/noy-db/issues"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"import": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"require": {
|
|
25
|
+
"types": "./dist/index.d.cts",
|
|
26
|
+
"default": "./dist/index.cjs"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"main": "./dist/index.cjs",
|
|
31
|
+
"module": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"README.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"engines": {
|
|
39
|
+
"node": ">=18.0.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@noy-db/hub": "0.1.0-pre.10"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"happy-dom": "^18.0.0",
|
|
46
|
+
"@noy-db/hub": "0.1.0-pre.10",
|
|
47
|
+
"@noy-db/test-adapter-conformance": "0.0.0"
|
|
48
|
+
},
|
|
49
|
+
"keywords": [
|
|
50
|
+
"noy-db",
|
|
51
|
+
"adapter",
|
|
52
|
+
"browser",
|
|
53
|
+
"localstorage",
|
|
54
|
+
"web",
|
|
55
|
+
"offline-first",
|
|
56
|
+
"encryption",
|
|
57
|
+
"zero-knowledge",
|
|
58
|
+
"obfuscation"
|
|
59
|
+
],
|
|
60
|
+
"publishConfig": {
|
|
61
|
+
"access": "public",
|
|
62
|
+
"tag": "latest"
|
|
63
|
+
},
|
|
64
|
+
"scripts": {
|
|
65
|
+
"build": "tsup",
|
|
66
|
+
"test": "vitest run",
|
|
67
|
+
"lint": "eslint src/",
|
|
68
|
+
"typecheck": "tsc --noEmit"
|
|
69
|
+
}
|
|
70
|
+
}
|