@open-e2ee/signal-protocol-sdk 0.1.0-alpha.13 → 0.1.0-alpha.14

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.
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Backend-conformance kit for application-supplied React Native storage.
3
+ *
4
+ * `ReactNativeSignalProtocolStore` delegates persistence to a
5
+ * `ReactNativeKeyValueStorage` backend the application provides, so the SDK
6
+ * cannot exercise that backend itself. This kit is the executable form of the
7
+ * backend contract: an application runs it against its own backend, and a
8
+ * clean result is the precondition for every durability and atomicity promise
9
+ * the store makes on top. The `atomicWrite` cases matter most — the store
10
+ * commits identity trust, session state, and one-time-prekey consumption
11
+ * through `atomicWrite` as one security transition, and a backend that
12
+ * reorders, interleaves, or partially applies those batches silently breaks
13
+ * that guarantee.
14
+ *
15
+ * The kit has no framework or platform dependencies and avoids class syntax,
16
+ * so it runs unchanged under jest, Node, a browser, or the Hermes engine that
17
+ * ships with React Native.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { assertBackendConformance } from '@open-e2ee/signal-protocol-sdk/local/store/react-native';
22
+ *
23
+ * await assertBackendConformance({
24
+ * createBackend: () => openMyBackend({ namespace: freshNamespace() }),
25
+ * reopen: (previous) => reopenMyBackend(previous),
26
+ * });
27
+ * ```
28
+ */
29
+ /**
30
+ * The session key prefix the store uses, so `removeSessionsForUser` cases
31
+ * exercise the exact keyspace shape a backend will see in production.
32
+ */
33
+ const SESSION_PREFIX = '@signal:sessions:';
34
+ /**
35
+ * Session values under the prefix are JSON envelopes whose plaintext routing
36
+ * metadata carries the exact userId; `removeSessionsForUser` must match on
37
+ * that field, never on the key. The `data` field is opaque to the backend.
38
+ */
39
+ function sessionEnvelope(userId, deviceId) {
40
+ return JSON.stringify({
41
+ userId: userId,
42
+ deviceId: deviceId,
43
+ data: 'b3BhcXVlLWNpcGhlcnRleHQ=',
44
+ updatedAt: 1,
45
+ });
46
+ }
47
+ function fail(message) {
48
+ throw new Error(message);
49
+ }
50
+ function assertEqual(actual, expected, context) {
51
+ const actualJson = JSON.stringify(actual);
52
+ const expectedJson = JSON.stringify(expected);
53
+ if (actualJson !== expectedJson) {
54
+ fail(context + ': expected ' + expectedJson + ', got ' + actualJson);
55
+ }
56
+ }
57
+ async function expectRejection(promise, context) {
58
+ let error = null;
59
+ let rejected = false;
60
+ await promise.then(function resolved() { }, function caught(reason) {
61
+ rejected = true;
62
+ error = reason;
63
+ });
64
+ if (!rejected)
65
+ fail(context + ': expected the call to reject, but it resolved');
66
+ return error;
67
+ }
68
+ const CASES = [
69
+ {
70
+ name: 'getItem returns null for a missing key',
71
+ async run(backend) {
72
+ assertEqual(await backend.getItem('missing'), null, 'missing key');
73
+ },
74
+ },
75
+ {
76
+ name: 'setItem stores, overwrites, and round-trips values',
77
+ async run(backend) {
78
+ await backend.setItem('plain', 'value-1');
79
+ assertEqual(await backend.getItem('plain'), 'value-1', 'first write');
80
+ await backend.setItem('plain', 'value-2');
81
+ assertEqual(await backend.getItem('plain'), 'value-2', 'overwrite');
82
+ const unicode = 'café 日本語 🔐 \u0000null-byte';
83
+ await backend.setItem('unicode', unicode);
84
+ assertEqual(await backend.getItem('unicode'), unicode, 'unicode round-trip');
85
+ let long = '';
86
+ while (long.length < 8192)
87
+ long += 'abcdefghijklmnop';
88
+ await backend.setItem('long', long);
89
+ assertEqual(await backend.getItem('long'), long, 'long value round-trip');
90
+ },
91
+ },
92
+ {
93
+ name: 'removeItem deletes and tolerates a missing key',
94
+ async run(backend) {
95
+ await backend.setItem('doomed', 'value');
96
+ await backend.removeItem('doomed');
97
+ assertEqual(await backend.getItem('doomed'), null, 'after removeItem');
98
+ await backend.removeItem('doomed');
99
+ assertEqual(await backend.getItem('doomed'), null, 'removeItem is idempotent');
100
+ },
101
+ },
102
+ {
103
+ name: 'getAllKeys lists exactly the stored keys',
104
+ async run(backend) {
105
+ assertEqual(await backend.getAllKeys(), [], 'empty backend');
106
+ await backend.setItem('b', '2');
107
+ await backend.setItem('a', '1');
108
+ await backend.setItem('c', '3');
109
+ await backend.removeItem('c');
110
+ const keys = (await backend.getAllKeys()).slice().sort();
111
+ assertEqual(keys, ['a', 'b'], 'stored keys');
112
+ },
113
+ },
114
+ {
115
+ name: 'removeMany removes listed keys and tolerates missing ones',
116
+ async run(backend) {
117
+ await backend.setItem('one', '1');
118
+ await backend.setItem('two', '2');
119
+ await backend.setItem('three', '3');
120
+ await backend.removeMany(['one', 'three', 'never-existed']);
121
+ assertEqual(await backend.getItem('one'), null, 'first removed key');
122
+ assertEqual(await backend.getItem('three'), null, 'second removed key');
123
+ assertEqual(await backend.getItem('two'), '2', 'unlisted key survives');
124
+ },
125
+ },
126
+ {
127
+ name: 'atomicWrite applies operations in order',
128
+ async run(backend) {
129
+ await backend.atomicWrite([
130
+ { type: 'set', key: 'ordered', value: 'first' },
131
+ { type: 'set', key: 'ordered', value: 'second' },
132
+ ]);
133
+ assertEqual(await backend.getItem('ordered'), 'second', 'later set wins');
134
+ await backend.atomicWrite([
135
+ { type: 'set', key: 'transient', value: 'created' },
136
+ { type: 'remove', key: 'transient' },
137
+ ]);
138
+ assertEqual(await backend.getItem('transient'), null, 'set then remove');
139
+ await backend.atomicWrite([
140
+ { type: 'remove', key: 'reborn' },
141
+ { type: 'set', key: 'reborn', value: 'alive' },
142
+ ]);
143
+ assertEqual(await backend.getItem('reborn'), 'alive', 'remove then set');
144
+ },
145
+ },
146
+ {
147
+ name: 'atomicWrite evaluates checks against pre-batch state',
148
+ async run(backend) {
149
+ await backend.setItem('guarded', 'old');
150
+ // The check follows a set of the same key in batch order. The contract
151
+ // evaluates every check before any write, so it must see 'old'.
152
+ await backend.atomicWrite([
153
+ { type: 'set', key: 'guarded', value: 'new' },
154
+ { type: 'check', key: 'guarded', expectedValue: 'old' },
155
+ ]);
156
+ assertEqual(await backend.getItem('guarded'), 'new', 'batch committed');
157
+ },
158
+ },
159
+ {
160
+ name: 'atomicWrite guards creation with an expectedValue of null',
161
+ async run(backend) {
162
+ await backend.atomicWrite([
163
+ { type: 'check', key: 'created', expectedValue: null },
164
+ { type: 'set', key: 'created', value: 'first-writer' },
165
+ ]);
166
+ assertEqual(await backend.getItem('created'), 'first-writer', 'first creation');
167
+ await expectRejection(backend.atomicWrite([
168
+ { type: 'check', key: 'created', expectedValue: null },
169
+ { type: 'set', key: 'created', value: 'second-writer' },
170
+ ]), 'creation of an existing key');
171
+ assertEqual(await backend.getItem('created'), 'first-writer', 'loser wrote nothing');
172
+ },
173
+ },
174
+ {
175
+ name: 'a failed check applies none of the batch',
176
+ async run(backend) {
177
+ await backend.setItem('anchor', 'anchored');
178
+ await expectRejection(backend.atomicWrite([
179
+ { type: 'set', key: 'before-check', value: 'must-not-appear' },
180
+ { type: 'check', key: 'anchor', expectedValue: 'something-else' },
181
+ { type: 'set', key: 'after-check', value: 'must-not-appear' },
182
+ ]), 'batch with a failing check');
183
+ assertEqual(await backend.getItem('before-check'), null, 'write before the check');
184
+ assertEqual(await backend.getItem('after-check'), null, 'write after the check');
185
+ assertEqual(await backend.getItem('anchor'), 'anchored', 'checked key');
186
+ },
187
+ },
188
+ {
189
+ name: 'removeSessionsForUser removes only exact userId matches under the prefix',
190
+ async run(backend) {
191
+ await backend.setItem(SESSION_PREFIX + 'alice:1', sessionEnvelope('alice', 1));
192
+ await backend.setItem(SESSION_PREFIX + 'alice:2', sessionEnvelope('alice', 2));
193
+ // 'alice2' begins with 'alice'; a substring or startsWith match on the
194
+ // userId would delete an unrelated user's session.
195
+ await backend.setItem(SESSION_PREFIX + 'alice2:1', sessionEnvelope('alice2', 1));
196
+ await backend.setItem(SESSION_PREFIX + 'bob:1', sessionEnvelope('bob', 1));
197
+ await backend.setItem('@signal:contacts:alice', sessionEnvelope('alice', 1));
198
+ await backend.atomicWrite([
199
+ { type: 'removeSessionsForUser', keyPrefix: SESSION_PREFIX, userId: 'alice' },
200
+ ]);
201
+ assertEqual(await backend.getItem(SESSION_PREFIX + 'alice:1'), null, 'alice device 1');
202
+ assertEqual(await backend.getItem(SESSION_PREFIX + 'alice:2'), null, 'alice device 2');
203
+ assertEqual(await backend.getItem(SESSION_PREFIX + 'alice2:1'), sessionEnvelope('alice2', 1), 'a userId that begins with the target');
204
+ assertEqual(await backend.getItem(SESSION_PREFIX + 'bob:1'), sessionEnvelope('bob', 1), 'an unrelated userId');
205
+ assertEqual(await backend.getItem('@signal:contacts:alice'), sessionEnvelope('alice', 1), 'a matching value outside the prefix');
206
+ },
207
+ },
208
+ {
209
+ name: 'removeSessionsForUser observes writes earlier in its batch',
210
+ async run(backend) {
211
+ // A session created inside the same transaction that rotates identity
212
+ // must be visible to the removal, or it survives trusted under the
213
+ // rotated identity. Enumeration snapshotted before the batch applies
214
+ // is the defect this case exists to catch.
215
+ await backend.atomicWrite([
216
+ { type: 'set', key: SESSION_PREFIX + 'carol:1', value: sessionEnvelope('carol', 1) },
217
+ { type: 'removeSessionsForUser', keyPrefix: SESSION_PREFIX, userId: 'carol' },
218
+ ]);
219
+ assertEqual(await backend.getItem(SESSION_PREFIX + 'carol:1'), null, 'session written earlier in the batch');
220
+ },
221
+ },
222
+ {
223
+ name: 'concurrent guarded batches have exactly one winner',
224
+ async run(backend) {
225
+ function attempt(value) {
226
+ return backend
227
+ .atomicWrite([
228
+ { type: 'check', key: 'contested', expectedValue: null },
229
+ { type: 'set', key: 'contested', value: value },
230
+ ])
231
+ .then(function won() {
232
+ return value;
233
+ }, function lost() {
234
+ return null;
235
+ });
236
+ }
237
+ const outcomes = await Promise.all([attempt('left'), attempt('right')]);
238
+ const winners = [];
239
+ for (const outcome of outcomes) {
240
+ if (outcome !== null)
241
+ winners.push(outcome);
242
+ }
243
+ if (winners.length !== 1) {
244
+ fail('expected exactly one of two concurrent guarded batches to commit, got ' +
245
+ winners.length);
246
+ }
247
+ assertEqual(await backend.getItem('contested'), winners[0], 'committed value');
248
+ },
249
+ },
250
+ {
251
+ name: 'committed writes survive reopen',
252
+ needsReopen: true,
253
+ async run(backend, options) {
254
+ await backend.setItem('durable-plain', 'kept');
255
+ await backend.atomicWrite([
256
+ { type: 'check', key: 'durable-batch', expectedValue: null },
257
+ { type: 'set', key: 'durable-batch', value: 'also-kept' },
258
+ ]);
259
+ // Deletions must be as durable as writes: a backend that persists sets
260
+ // but resurrects removed keys after reopen would leave sessions alive
261
+ // that the store deleted during an identity rotation.
262
+ await backend.setItem('durable-removed', 'doomed');
263
+ await backend.removeItem('durable-removed');
264
+ await backend.setItem(SESSION_PREFIX + 'carol:9', sessionEnvelope('carol', 9));
265
+ await backend.atomicWrite([
266
+ { type: 'removeSessionsForUser', keyPrefix: SESSION_PREFIX, userId: 'carol' },
267
+ ]);
268
+ const reopened = await options.reopen(backend);
269
+ assertEqual(await reopened.getItem('durable-plain'), 'kept', 'plain write after reopen');
270
+ assertEqual(await reopened.getItem('durable-batch'), 'also-kept', 'batched write after reopen');
271
+ assertEqual(await reopened.getItem('durable-removed'), null, 'removed key stays absent after reopen');
272
+ assertEqual(await reopened.getItem(SESSION_PREFIX + 'carol:9'), null, 'removed session stays absent after reopen');
273
+ },
274
+ },
275
+ ];
276
+ /**
277
+ * Run every conformance case against backends produced by
278
+ * `options.createBackend` and report the outcome without throwing.
279
+ */
280
+ export async function runBackendConformance(options) {
281
+ const result = {
282
+ total: CASES.length,
283
+ passed: [],
284
+ skipped: [],
285
+ failures: [],
286
+ };
287
+ for (const conformanceCase of CASES) {
288
+ if (conformanceCase.needsReopen && !options.reopen) {
289
+ result.skipped.push(conformanceCase.name);
290
+ continue;
291
+ }
292
+ try {
293
+ const backend = await options.createBackend();
294
+ await conformanceCase.run(backend, options);
295
+ result.passed.push(conformanceCase.name);
296
+ }
297
+ catch (error) {
298
+ const message = error !== null && typeof error === 'object' && 'message' in error
299
+ ? String(error.message)
300
+ : String(error);
301
+ result.failures.push({ name: conformanceCase.name, message: message });
302
+ }
303
+ }
304
+ return result;
305
+ }
306
+ /**
307
+ * Run the kit and throw with every failure listed when the backend does not
308
+ * conform. The intended form for an application's own automated checks.
309
+ */
310
+ export async function assertBackendConformance(options) {
311
+ const result = await runBackendConformance(options);
312
+ if (result.failures.length > 0) {
313
+ const lines = [];
314
+ for (const failure of result.failures) {
315
+ lines.push('- ' + failure.name + ': ' + failure.message);
316
+ }
317
+ throw new Error('Backend conformance failed (' +
318
+ result.failures.length +
319
+ ' of ' +
320
+ result.total +
321
+ ' cases):\n' +
322
+ lines.join('\n'));
323
+ }
324
+ return result;
325
+ }
326
+ //# sourceMappingURL=backend-conformance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend-conformance.js","sourceRoot":"","sources":["../../../../local/store/react-native/backend-conformance.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAmCH;;;GAGG;AACH,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAE3C;;;;GAIG;AACH,SAAS,eAAe,CAAC,MAAc,EAAE,QAAgB;IACvD,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,MAAM,EAAE,MAAM;QACd,QAAQ,EAAE,QAAQ;QAClB,IAAI,EAAE,0BAA0B;QAChC,SAAS,EAAE,CAAC;KACb,CAAC,CAAC;AACL,CAAC;AAED,SAAS,IAAI,CAAC,OAAe;IAC3B,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,WAAW,CAAC,MAAe,EAAE,QAAiB,EAAE,OAAe;IACtE,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,YAAY,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAC9C,IAAI,UAAU,KAAK,YAAY,EAAE,CAAC;QAChC,IAAI,CAAC,OAAO,GAAG,aAAa,GAAG,YAAY,GAAG,QAAQ,GAAG,UAAU,CAAC,CAAC;IACvE,CAAC;AACH,CAAC;AAED,KAAK,UAAU,eAAe,CAAC,OAAyB,EAAE,OAAe;IACvE,IAA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
  * React Native Storage Package (Bare Workflow)
3
3
  *
4
- * Experimental storage for React Native without Expo.
4
+ * Storage for React Native without Expo.
5
5
  * Consumers must provide their own persistent key-value backend and construct
6
6
  * the store with `await ReactNativeSignalProtocolStore.create({ storage })`.
7
- * The adapter implements the core store contract, but its durability and
8
- * platform-hardening depend on the injected backend.
7
+ * The adapter implements the core store contract; its durability rests on the
8
+ * injected backend, so verify the backend with the exported
9
+ * backend-conformance kit (`assertBackendConformance`).
9
10
  */
10
11
  export {};
11
12
  import { ReactNativeSignalProtocolStore } from './adapter.js';
12
13
  import type { ReactNativeKeyValueStorage } from './storage.js';
13
14
  export { ReactNativeSignalProtocolStore } from './adapter.js';
14
- export type { ReactNativeKeyValueStorage } from './storage.js';
15
+ export type { ReactNativeKeyValueOperation, ReactNativeKeyValueStorage } from './storage.js';
16
+ export { assertBackendConformance, runBackendConformance } from './backend-conformance.js';
17
+ export type { BackendConformanceFailure, BackendConformanceOptions, BackendConformanceResult, } from './backend-conformance.js';
18
+ export { createReferenceReactNativeBackend } from './reference-backend.js';
19
+ export type { ReferenceReactNativeBackendOptions } from './reference-backend.js';
15
20
  export interface ReactNativeStoreFactoryOptions {
16
21
  storage: ReactNativeKeyValueStorage;
17
22
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../local/store/react-native/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,CAAC;AACV,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AAE5D,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,YAAY,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AAE5D,MAAM,WAAW,8BAA8B;IAC7C,OAAO,EAAE,0BAA0B,CAAC;CACrC;AAED,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,8BAA8B,CAAC,CAEzC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../local/store/react-native/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,CAAC;AACV,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AAE5D,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAC3D,YAAY,EAAE,4BAA4B,EAAE,0BAA0B,EAAE,MAAM,WAAW,CAAC;AAC1F,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACxF,YAAY,EACV,yBAAyB,EACzB,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iCAAiC,EAAE,MAAM,qBAAqB,CAAC;AACxE,YAAY,EAAE,kCAAkC,EAAE,MAAM,qBAAqB,CAAC;AAE9E,MAAM,WAAW,8BAA8B;IAC7C,OAAO,EAAE,0BAA0B,CAAC;CACrC;AAED,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,8BAA8B,CAAC,CAEzC"}
@@ -1,5 +1,7 @@
1
1
  import { ReactNativeSignalProtocolStore } from './adapter.js';
2
2
  export { ReactNativeSignalProtocolStore } from './adapter.js';
3
+ export { assertBackendConformance, runBackendConformance } from './backend-conformance.js';
4
+ export { createReferenceReactNativeBackend } from './reference-backend.js';
3
5
  export function reactNativeStore(options) {
4
6
  return ReactNativeSignalProtocolStore.create(options);
5
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../local/store/react-native/index.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAG3D,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAO3D,MAAM,UAAU,gBAAgB,CAC9B,OAAuC;IAEvC,OAAO,8BAA8B,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACxD,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../local/store/react-native/index.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAG3D,OAAO,EAAE,8BAA8B,EAAE,MAAM,WAAW,CAAC;AAE3D,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAMxF,OAAO,EAAE,iCAAiC,EAAE,MAAM,qBAAqB,CAAC;AAOxE,MAAM,UAAU,gBAAgB,CAC9B,OAAuC;IAEvC,OAAO,8BAA8B,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACxD,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Reference implementation of `ReactNativeKeyValueStorage`.
3
+ *
4
+ * This backend is the executable specification the backend-conformance kit is
5
+ * written against: every semantic the contract requires — full serialization,
6
+ * checks evaluated against pre-batch state, in-order application with
7
+ * in-batch visibility, exact-userId session removal, and all-or-nothing
8
+ * commit including under quota exhaustion — is implemented here in the
9
+ * plainest form that satisfies it. It holds data in memory, so it is not a
10
+ * production backend: a real application supplies storage that survives
11
+ * process termination. Continuous integration runs the kit against this
12
+ * backend on the Hermes engine React Native ships with, which is why the
13
+ * module avoids class syntax.
14
+ *
15
+ * Passing `state` lets separate instances share one persistence medium, which
16
+ * models a process restart: create a second backend over the same map and the
17
+ * first instance's committed writes are visible to it. The model is
18
+ * sequential — the old instance stops before the new one starts, as a killed
19
+ * process stops before its replacement launches. Serialization is per
20
+ * instance, so two instances used concurrently over one map do not get the
21
+ * single-winner guarantee.
22
+ */
23
+ import type { ReactNativeKeyValueStorage } from './storage.js';
24
+ export interface ReferenceReactNativeBackendOptions {
25
+ /**
26
+ * Reject any write that would grow the total stored bytes (UTF-8 keys plus
27
+ * values) past this limit, with an error named `QuotaExceededError` and
28
+ * nothing committed — the quota signal the store's boundary maps to its
29
+ * typed `StorageQuotaExceededError`. Unlimited when omitted.
30
+ */
31
+ quotaBytes?: number;
32
+ /** The backing map. Supply the same map to a later instance to model reopening after a restart. */
33
+ state?: Map<string, string>;
34
+ }
35
+ /**
36
+ * Create a reference backend. Every method is serialized through one internal
37
+ * queue, so two in-flight `atomicWrite` calls can never interleave their
38
+ * check and apply phases — the exclusion the contract's compare-and-swap
39
+ * guard depends on.
40
+ */
41
+ export declare function createReferenceReactNativeBackend(options?: ReferenceReactNativeBackendOptions): ReactNativeKeyValueStorage;
42
+ //# sourceMappingURL=reference-backend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reference-backend.d.ts","sourceRoot":"","sources":["../../../../local/store/react-native/reference-backend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAAgC,0BAA0B,EAAE,MAAM,WAAW,CAAC;AAE1F,MAAM,WAAW,kCAAkC;IACjD;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,mGAAmG;IACnG,KAAK,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC7B;AA+CD;;;;;GAKG;AACH,wBAAgB,iCAAiC,CAC/C,OAAO,CAAC,EAAE,kCAAkC,GAC3C,0BAA0B,CAsG5B"}
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Reference implementation of `ReactNativeKeyValueStorage`.
3
+ *
4
+ * This backend is the executable specification the backend-conformance kit is
5
+ * written against: every semantic the contract requires — full serialization,
6
+ * checks evaluated against pre-batch state, in-order application with
7
+ * in-batch visibility, exact-userId session removal, and all-or-nothing
8
+ * commit including under quota exhaustion — is implemented here in the
9
+ * plainest form that satisfies it. It holds data in memory, so it is not a
10
+ * production backend: a real application supplies storage that survives
11
+ * process termination. Continuous integration runs the kit against this
12
+ * backend on the Hermes engine React Native ships with, which is why the
13
+ * module avoids class syntax.
14
+ *
15
+ * Passing `state` lets separate instances share one persistence medium, which
16
+ * models a process restart: create a second backend over the same map and the
17
+ * first instance's committed writes are visible to it. The model is
18
+ * sequential — the old instance stops before the new one starts, as a killed
19
+ * process stops before its replacement launches. Serialization is per
20
+ * instance, so two instances used concurrently over one map do not get the
21
+ * single-winner guarantee.
22
+ */
23
+ /**
24
+ * UTF-8 byte length without `TextEncoder` or `Buffer`, neither of which the
25
+ * Hermes CLI provides.
26
+ */
27
+ function utf8ByteLength(value) {
28
+ let bytes = 0;
29
+ for (let index = 0; index < value.length; index += 1) {
30
+ const code = value.charCodeAt(index);
31
+ if (code < 0x80) {
32
+ bytes += 1;
33
+ }
34
+ else if (code < 0x800) {
35
+ bytes += 2;
36
+ }
37
+ else if (code >= 0xd800 && code <= 0xdbff) {
38
+ // A surrogate pair encodes as 4 bytes; an unpaired surrogate encodes
39
+ // as the 3-byte replacement character either way.
40
+ const next = index + 1 < value.length ? value.charCodeAt(index + 1) : 0;
41
+ if (next >= 0xdc00 && next <= 0xdfff) {
42
+ bytes += 4;
43
+ index += 1;
44
+ }
45
+ else {
46
+ bytes += 3;
47
+ }
48
+ }
49
+ else {
50
+ bytes += 3;
51
+ }
52
+ }
53
+ return bytes;
54
+ }
55
+ function usedBytes(entries) {
56
+ let total = 0;
57
+ for (const entry of entries) {
58
+ total += utf8ByteLength(entry[0]) + utf8ByteLength(entry[1]);
59
+ }
60
+ return total;
61
+ }
62
+ function quotaError() {
63
+ const error = new Error('Reference backend storage quota exhausted');
64
+ // Signalled by name, not by a shared class: the store's boundary matches
65
+ // `error.name` so any backend can raise the same signal.
66
+ error.name = 'QuotaExceededError';
67
+ return error;
68
+ }
69
+ /**
70
+ * Create a reference backend. Every method is serialized through one internal
71
+ * queue, so two in-flight `atomicWrite` calls can never interleave their
72
+ * check and apply phases — the exclusion the contract's compare-and-swap
73
+ * guard depends on.
74
+ */
75
+ export function createReferenceReactNativeBackend(options) {
76
+ const committed = options?.state ?? new Map();
77
+ const quotaBytes = options?.quotaBytes ?? Infinity;
78
+ let queue = Promise.resolve();
79
+ function serialized(run) {
80
+ const next = queue.then(run);
81
+ queue = next.then(function settled() { }, function swallowedForQueue() { });
82
+ return next;
83
+ }
84
+ function ensureQuota(entries) {
85
+ if (usedBytes(entries) > quotaBytes)
86
+ throw quotaError();
87
+ }
88
+ async function applyAtomically(operations) {
89
+ // Phase 1: every check, against the committed pre-batch state.
90
+ for (const operation of operations) {
91
+ if (operation.type !== 'check')
92
+ continue;
93
+ const current = committed.get(operation.key) ?? null;
94
+ if (current !== operation.expectedValue) {
95
+ throw new Error('atomicWrite check failed for key ' + operation.key + '; nothing was applied');
96
+ }
97
+ }
98
+ // The yield keeps the serialization queue honest: without the mutex the
99
+ // conformance kit's concurrent-batch case would observe two winners here.
100
+ await Promise.resolve();
101
+ // Phase 2: apply in order over a snapshot, so a failure commits nothing
102
+ // and `removeSessionsForUser` sees writes from earlier in the batch.
103
+ const next = new Map(committed);
104
+ for (const operation of operations) {
105
+ if (operation.type === 'set') {
106
+ next.set(operation.key, operation.value);
107
+ }
108
+ else if (operation.type === 'remove') {
109
+ next.delete(operation.key);
110
+ }
111
+ else if (operation.type === 'removeSessionsForUser') {
112
+ const doomed = [];
113
+ for (const entry of next) {
114
+ if (!entry[0].startsWith(operation.keyPrefix))
115
+ continue;
116
+ let userId = null;
117
+ try {
118
+ const envelope = JSON.parse(entry[1]);
119
+ userId = envelope === null ? null : envelope.userId;
120
+ }
121
+ catch {
122
+ // A non-JSON value under the prefix is not a session envelope the
123
+ // store wrote; leave it for the owner to account for.
124
+ continue;
125
+ }
126
+ if (userId === operation.userId)
127
+ doomed.push(entry[0]);
128
+ }
129
+ for (const key of doomed)
130
+ next.delete(key);
131
+ }
132
+ }
133
+ ensureQuota(next);
134
+ // Phase 3: commit by swapping contents in place, so instances sharing
135
+ // the `state` map observe the batch all at once.
136
+ committed.clear();
137
+ for (const entry of next)
138
+ committed.set(entry[0], entry[1]);
139
+ }
140
+ return {
141
+ getItem(key) {
142
+ return serialized(async function getItem() {
143
+ return committed.get(key) ?? null;
144
+ });
145
+ },
146
+ setItem(key, value) {
147
+ return serialized(async function setItem() {
148
+ const next = new Map(committed);
149
+ next.set(key, value);
150
+ ensureQuota(next);
151
+ committed.set(key, value);
152
+ });
153
+ },
154
+ removeItem(key) {
155
+ return serialized(async function removeItem() {
156
+ committed.delete(key);
157
+ });
158
+ },
159
+ getAllKeys() {
160
+ return serialized(async function getAllKeys() {
161
+ return Array.from(committed.keys());
162
+ });
163
+ },
164
+ removeMany(keys) {
165
+ return serialized(async function removeMany() {
166
+ for (const key of keys)
167
+ committed.delete(key);
168
+ });
169
+ },
170
+ atomicWrite(operations) {
171
+ return serialized(function atomicWrite() {
172
+ return applyAtomically(operations);
173
+ });
174
+ },
175
+ };
176
+ }
177
+ //# sourceMappingURL=reference-backend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reference-backend.js","sourceRoot":"","sources":["../../../../local/store/react-native/reference-backend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAgBH;;;GAGG;AACH,SAAS,cAAc,CAAC,KAAa;IACnC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;QACrD,MAAM,IAAI,GAAG,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;QACrC,IAAI,IAAI,GAAG,IAAI,EAAE,CAAC;YAChB,KAAK,IAAI,CAAC,CAAC;QACb,CAAC;aAAM,IAAI,IAAI,GAAG,KAAK,EAAE,CAAC;YACxB,KAAK,IAAI,CAAC,CAAC;QACb,CAAC;aAAM,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,EAAE,CAAC;YAC5C,qEAAqE;YACrE,kDAAkD;YAClD,MAAM,IAAI,GAAG,KAAK,GAAG,C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O,UAAU,CAAC,KAAK,UAAU,OAAO;gBACtC,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC;gBAChC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;gBACrB,WAAW,CAAC,IAAI,CAAC,CAAC;gBAClB,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YAC5B,CAAC,CAAC,CAAC;QACL,CAAC;QACD,UAAU,CAAC,GAAW;YACpB,OAAO,UAAU,CAAC,KAAK,UAAU,UAAU;gBACzC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACxB,CAAC,CAAC,CAAC;QACL,CAAC;QACD,UAAU;YACR,OAAO,UAAU,CAAC,KAAK,UAAU,UAAU;gBACzC,OAAO,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,CAAC,CAAC;YACtC,CAAC,CAAC,CAAC;QACL,CAAC;QACD,UAAU,CAAC,IAAc;YACvB,OAAO,UAAU,CAAC,KAAK,UAAU,UAAU;gBACzC,KAAK,MAAM,GAAG,IAAI,IAAI;oBAAE,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YAChD,CAAC,CAAC,CAAC;QACL,CAAC;QACD,WAAW,CAAC,UAAmD;YAC7D,OAAO,UAAU,CAAC,SAAS,WAAW;gBACpC,OAAO,eAAe,CAAC,UAAU,CAAC,CAAC;YACrC,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -3,6 +3,15 @@
3
3
  *
4
4
  * Bare React Native consumers must provide their own implementation so the
5
5
  * Signal Protocol package does not hard-code a specific storage library.
6
+ * Verify an implementation with the backend-conformance kit exported from
7
+ * this package (`assertBackendConformance`); the store's guarantees hold
8
+ * only over a conforming backend.
9
+ *
10
+ * Quota signal: a backend that enforces a storage limit must reject the
11
+ * failing write with an error whose `name` is `'QuotaExceededError'` and
12
+ * commit nothing from that write. The store maps that failure to its typed
13
+ * `StorageQuotaExceededError` at the adapter boundary, so the application
14
+ * always sees a write that did not persist, never a partial one.
6
15
  */
7
16
  export interface ReactNativeKeyValueStorage {
8
17
  getItem(key: string): Promise<string | null>;