@webex/storage-adapter-local-storage 3.13.0-next.3 → 3.13.0-next.5

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,756 @@
1
+ ---
2
+ type: Module Spec
3
+ title: 'storage-adapter-local-storage src specification'
4
+ description: Responsibilities, boundaries, design, invariants, and verification for the localStorage bounded storage adapter.
5
+ tags: [module, specification]
6
+ ---
7
+ <!-- sdd-generated-metadata
8
+ doc_kind: module-spec
9
+ generated_from: module-spec@0.3.0
10
+ generated_by: claude-code
11
+ approved_by: rsarika@cisco.com
12
+ updated_at: 2026-11-09T10:36:32Z
13
+ validation_status: pass-with-warnings
14
+ -->
15
+
16
+ # storage-adapter-local-storage `src`
17
+
18
+ This source-local document at `src/docs/README.md` owns the stable specification for the
19
+ **localStorage bounded storage adapter**. Ground every claim in repository evidence and link to the
20
+ [repository architecture](../../docs/architecture.md) instead of repeating broader facts.
21
+
22
+ Related context: [documentation index](../../docs/index.md) ·
23
+ [documentation agent instructions](../../AGENTS.md)
24
+
25
+ ## Metadata
26
+
27
+ | Field | Value |
28
+ | ------------- | ------------------------------------------------------------ |
29
+ | Owner | `@webex/web-client`, assigned in `.github/CODEOWNERS` |
30
+ | Source path | `src` |
31
+ | Resource kind | package (published npm library) |
32
+ | Status | Active |
33
+ | Last verified | 2026-11-09 at `94f94f516b` |
34
+ | Module id | `src` |
35
+ | Parent spec | — |
36
+ | Doc kind | Module spec |
37
+ | Coverage score | 96% (26/27 mandatory fields PRESENT) assessed 2026-11-09; all critical fields PRESENT, test and characterization coverage WEAK because no route executes a case |
38
+ | Validation status | pass-with-warnings — validated 2026-11-09 by Codex runtime `01a1bf1a-7e46-7451-9bed-7ebfbdc56def`; 0 Blocking, 1 Important verification warning. Report: `.generated/sdd/validation/2026-11-09.md`. |
39
+
40
+ ## Applicability
41
+
42
+ Sections preceded by an `Include if` comment are conditional. Retain a conditional section only when
43
+ source evidence or a confirmed developer answer satisfies its condition. Record `Unresolved` instead
44
+ of guessing.
45
+
46
+ | Condition ID | Status | Evidence or reason | Owned section |
47
+ | ------------------------------------ | ---------- | ------------------ | ----------------------------- |
48
+ | `module.has_tiers` | N/A | No tier annotation or per-module SLO config; .github/CODEOWNERS assigns an owner but no tier | Tier |
49
+ | `module.has_ui` | N/A | No components, templates, or stylesheets in src/ | UI use-case flow |
50
+ | `module.crosses_service_boundaries` | N/A | No HTTP, RPC, or queue client; the only external call target is the same-origin localStorage API | Cross-boundary use-case flow |
51
+ | `module.holds_client_state` | N/A | src/index.js holds only WeakMap binding metadata, not application state | Client state model |
52
+ | `module.enforces_domain_rules` | Applicable | src/index.js | Business rules and invariants |
53
+ | `module.is_concurrent_async` | Applicable | Every public method is Promise-returning on its normal path, with clear and bind able to throw synchronously instead (see MOD-015); read-modify-write in src/index.js | Concurrency and reactive flow |
54
+ | `module.owns_persistence` | Applicable | Owns the localStorage[basekey] document layout — src/index.js | Data, schema, and migration |
55
+ | `module.stateful_transitions` | N/A | No lifecycle enum, status field, or transition guard | State machine |
56
+ | `module.exposes_wire_protocol` | N/A | Owner decision: the at-rest JSON encoding is documented under persistence to avoid two overlapping sections for one document shape | Protocol and wire format |
57
+ | `module.ui_multi_screen` | N/A | Gated on module.has_ui, which is N/A | UI flow |
58
+ | `module.large_data_model` | N/A | One document shape; no entity relationships | Data model |
59
+ | `module.returns_caller_errors` | Applicable | src/index.js | Caller-visible failure modes |
60
+ | `module.module_specific_conventions` | Applicable | Package-local `.eslintrc.js`, the /* eslint-env browser */ directive in src/index.js, the `process` shim | Module-specific rules |
61
+ | `module.published_package` | Applicable | `package.json` main, devMain, deploy:npm | Export stability |
62
+ | `module.embedded_in_host` | Applicable | Injected as config.storage.boundedAdapter and driven by webex-core | Host integration and theming |
63
+ | `module.has_design_tradeoff` | Applicable | Synchronous storage behind a Promise API; whole-document read-modify-write; basekey-scoped clear() | Key design trade-off |
64
+ | `module.has_submodules` | N/A | Computed by scripts/module_tree.py: no manifest module path is a child of src | Sub-modules |
65
+
66
+ ## Evidence register
67
+
68
+ List the code, tests, schemas, configuration, and prior decisions used to verify this specification.
69
+ Mark unresolved statements as `[NEEDS HUMAN INPUT]`; do not infer missing behavior.
70
+
71
+ | Evidence | What it establishes |
72
+ | ---------------- | ------------------- |
73
+ | `src/index.js` | The entire implementation: constructor, `bind`, and the `Bound` class with `get`, `put`, `del`, `clear` and the private `_getRawData`, `_load`, `_save`. |
74
+ | `package.json` | Published package identity, entry points (`main: dist/index.js`, `devMain: src/index.js`), scripts, and workspace dependencies. |
75
+ | `test/unit/spec/storage-adapter-local-storage.js` | The only test file. It wraps the suite in `skipInNode`, so the Node route declares but never executes the contract. |
76
+ | Sibling package storage-adapter-spec, spec src/docs/README.md and source src/index.js | Module spec consulted first, then source. The shared abstract adapter contract (21 declared cases) this module is expected to satisfy, including the falsey-value, concurrency, and write-`undefined` cases. The spec records the same suite gaps this document relies on: namespace-wide `clear` scope is asserted nowhere, `clear` is called both with and without an argument, and the suite calls the Jest `beforeAll` global. |
77
+ | Sibling package webex-core, spec src/lib/storage/docs/README.md and source src/lib/storage/make-webex-store.js | Module spec consulted first, then source. How the host drives the adapter: `WebexStore._getBinding` calls `bind(namespace, {logger})` once per namespace behind `oneFlight` and caches the binding, and its `clear()` fans out only to bindings created in that store instance. |
78
+ | Sibling package webex-core, source src/lib/storage/errors.js (storage spec consulted first) | `NotFoundError extends StorageError extends Exception` — the rejection type this module imports. |
79
+ | Sibling package webex-core, source src/lib/storage/decorators.js (storage spec consulted first) | `@persist` writes decorated state through `boundedStorage.put`, which is what routes credentials into this adapter in a browser. |
80
+ | Sibling package webex-core, source src/webex-core.js | `logout()` clears both the bounded and the unbounded store, which is the purge path `MOD-010` serves. |
81
+ | Sibling package webex, source src/config-storage.shim.js (no module spec exists) | The shim wires `new LocalStorageStoreAdapter('webex')` as the browser `boundedAdapter`. |
82
+ | Sibling package webex, source package.json (no module spec exists) | The `browser` field substitutes the shim for `config-storage.js`, so the wiring above applies only to browser bundles. |
83
+ | Repository root .github/CODEOWNERS | Ownership by `@webex/web-client`, on the entry matching this package path. |
84
+ | Measured command run, 2026-11-09, Node v22.14.0 | `test:style` exit 0 (0 errors, 1 warning: the Markdown spec under `src/` reported as ignored); `build:src` exit 0 (1 file emitted); `test:unit` exit 0 with 21 skipped / 0 executed; `test` exit 1 on the undefined `test:integration` script. `test:browser` exit 1 with 0 tests completed: `ReferenceError: beforeAll is not defined` in Chrome Headless 156 and Firefox 159, then an unhandled promise rejection from the runner. |
85
+ | Ad-hoc behavior probe, 2026-11-09, Node v22.14.0 | Characterization of the freshly built `dist/index.js` against a `localStorage` stand-in and against a bare Node process: missing-global and incomplete-logger failures, storage access counts, falsey and `undefined` values, `clear()` scope, `Object.prototype` names, `__proto__` pollution with object and array roots, non-JSON values, corrupt-document recovery, and sibling round trips. Earlier dated measurements cited below were made the same way. Not a committed artifact and not a regression guard; used only to confirm observable behavior that source reading already implies. |
86
+
87
+ Two subsections extend the template within its own canonical sections, both grounded in the evidence
88
+ above: `Operation sequences` under `Data flow and sequence coverage`, which traces call ordering and
89
+ storage-access count per operation from `src/index.js`, and `Defects recorded, not repaired` under
90
+ `Verification`, which records the measured command runs and the `README.md`/JSDoc conflicts found
91
+ while specifying. Neither introduces a concern the template already homes elsewhere.
92
+
93
+ ## Purpose and boundary
94
+
95
+ - Responsibility: persist a webex-core bounded-storage namespace to the browser `localStorage` API,
96
+ presenting a Promise-based key/value interface over a single JSON document.
97
+ - In scope: the `localStorage[basekey]` document layout; namespace partitioning within that
98
+ document; JSON serialization of stored values; argument validation in `bind`; the not-found
99
+ rejection contract; per-operation logging through an injected logger.
100
+ - Out of scope: deciding *which* adapter a webex instance uses (that is host configuration, see
101
+ `src/config-storage.shim.js` in the sibling package webex); the binding cache and the decision to call
102
+ `clear()` (both owned by `webex-core`'s `WebexStore`); encryption, expiry, quota management, and
103
+ cross-tab coordination — none are implemented here.
104
+ - Consumers: `@webex/webex-core`'s storage layer at runtime; configured by `@webex/webex`
105
+ (browser bundle), `@webex/recipe-private-web-client`, and the automation fixtures in
106
+ `@webex/plugin-authorization-browser` and `@webex/plugin-authorization-browser-first-party`.
107
+
108
+ ## Structure and key files
109
+
110
+ | Path | Responsibility |
111
+ | -------- | ---------------------------------- |
112
+ | `src/index.js` | The whole module. Default-exports `StorageAdapterLocalStorage`; the constructor closes over `basekey` and defines the inner `Bound` class, so every binding created by one adapter instance shares that key. |
113
+ | `package.json` | The module's ecosystem-native declaration and the authoritative source for the published contract. |
114
+ | `.eslintrc.js` | Package-local lint root extending `@webex/eslint-config-legacy`. |
115
+ | `babel.config.js` / `jest.config.js` | Thin re-exports of the shared legacy configs; `jest.config.js` is what imposes `testEnvironment: 'node'` on the unit route. |
116
+ | `process` | A one-line CommonJS file exporting `{browser: true}`, consumed by the browserify/envify transform declared in `package.json`. |
117
+ | `test/unit/spec/storage-adapter-local-storage.js` | Delegates entirely to the shared abstract suite and skips it under Node. |
118
+
119
+ ## Public surface
120
+
121
+ Describe exported APIs, events, commands, files, or UI boundaries. Link exact schemas or
122
+ declarations instead of copying them.
123
+
124
+ | Surface | Consumer | Compatibility commitment | Source |
125
+ | -------- | ---------- | ------------------------ | -------- |
126
+ | `StorageAdapterLocalStorage` (default export) | `@webex/webex`, `@webex/recipe-private-web-client`, authorization-browser automation fixtures | Published npm surface; the constructor signature `(basekey)` and the adapter shape are what host configuration depends on | `package.json`, implemented at src/index.js |
127
+ | `new StorageAdapterLocalStorage(basekey)` | Host configuration code | `basekey` selects the single `localStorage` entry holding every namespace for this instance; changing it orphans previously written data | src/index.js |
128
+ | `adapter.bind(namespace, options)` | `webex-core` `WebexStore._getBinding` | Resolves a new bound store without touching storage; rejects when `namespace` is falsy or `options.logger` is missing, but **throws synchronously** when a supplied logger lacks `debug` (`MOD-015`). Namespaces must not be `Object.prototype` property names (`MOD-016`) | src/index.js |
129
+ | `bound.get(key)` | `webex-core` `WebexStore.get` | Resolves any stored value, including `0`, `false`, `null`, and `''`; rejects `NotFoundError` when the key is absent. Two preconditions: the key must not be an `Object.prototype` property name (`MOD-016`), and the stored document must be schema-conforming (`MOD-017`). Outside them `get` may resolve a value that was never stored | src/index.js |
130
+ | `bound.put(key, value)` | `webex-core` `WebexStore.put` | Stores a JSON-serializable value and resolves with no value; rewrites the whole document, so sibling namespaces are preserved only across a lossless JSON round trip (`INV-003`) | src/index.js |
131
+ | `bound.del(key)` | `webex-core` `WebexStore.del` | Targets one key in the bound namespace only, under the same whole-document rewrite and round-trip caveat as `put` | src/index.js |
132
+ | `bound.clear()` | `webex-core` `WebexStore.clear` | Removes the entire `basekey` entry — every namespace, not only the bound one — by owner-confirmed intent (`MOD-010`). Takes no parameter; the JSDoc `@param key` is stale (`MOD-011`) | src/index.js |
133
+
134
+ The adapter is registered in `.sdd/manifest.json` as contract `storage-adapter-local-storage-sdk`
135
+ (published) with `package.json` as its ecosystem-native source, and the at-rest document as
136
+ `local-storage-bounded-document` (internal, but committed to stay readable across releases —
137
+ `MOD-018`). It consumes `webex-core-store-adapter-interface`.
138
+
139
+ ## Dependencies
140
+
141
+ | Dependency | Why it is required | Failure behavior |
142
+ | --------------------- | ------------------ | ----------------------------------- |
143
+ | `@webex/webex-core` | Supplies `NotFoundError` (imported at the top of `src/index.js`), the rejection type the host's storage layer and `@persist` decorators branch on | A different error type would break caller `catch` branches that distinguish "absent" from "failed"; the dependency is a workspace package resolved at build time |
144
+ | Browser `localStorage` global | The only backing store: `src/index.js` reads it in `_getRawData`, writes it in `_save`, and removes the entry in `clear` | Absent in Node. Measured 2026-11-09: `get`/`put`/`del` reject with `ReferenceError: localStorage is not defined`; `clear()` **throws synchronously** because its argument is evaluated before `Promise.resolve`. `bind()` still resolves because it never touches the global. |
145
+ | Caller-supplied `options.logger` | Captured at bind time and called by every operation, but the *method* required differs per operation: `bind`, `get`, and `put` call `logger.debug`; `del` and `clear` call `logger.info` | `bind` rejects when `options.logger` is absent entirely. A logger that is present but incomplete passes that check and fails later, per method and in two different ways. Measured 2026-11-09: an `info`-only logger makes `bind` **throw synchronously** (`TypeError: options.logger.debug is not a function`), because that call sits outside any Promise. A `debug`-only logger binds fine, `get` and `put` work, `del` **rejects** with `TypeError`, and `clear` **throws synchronously** with `TypeError`. See the failure-mode table. |
146
+ | `@webex/storage-adapter-spec` (declared under `dependencies`, used only by the test file) | Declares the shared abstract adapter contract this module is expected to satisfy | Neither execution route runs it here — see Verification |
147
+
148
+ ## Requirements
149
+
150
+ Separate source evidence, test/example evidence, assumptions, and gaps so a future contributor can
151
+ distinguish verified behavior from approved unknowns.
152
+
153
+ | ID | WHAT | WHY | Source evidence | Test or example evidence | Assumptions or gaps | Confidence |
154
+ | --------- | ---- | --- | --------------- | ------------------------ | ------------------- | ---------- |
155
+ | `MOD-001` | All namespaces for one adapter instance live in a single `localStorage` entry named by the constructor `basekey`. | A single entry lets `clear()` purge the adapter's whole dataset in one `removeItem`, and lets any binding see sibling namespaces through one parse. | src/index.js | None executing | No committed test pins the entry name | Present |
156
+ | `MOD-002` | `bind()` rejects with ``Error('`namespace` is required')`` when `namespace` is falsy. | A falsy namespace would partition data under `undefined` and silently collide across callers. | src/index.js | Declared in the storage-adapter-spec suite; not executed | — | Present |
157
+ | `MOD-003` | `bind()` rejects with ``Error('`options.logger` is required')`` when no logger is supplied; `options` itself defaults to `{}`. | Every operation calls the logger unconditionally, so a missing logger would fail later at an unrelated point instead of at bind time. | src/index.js | Declared in the storage-adapter-spec suite; not executed | — | Present |
158
+ | `MOD-004` | `bind()` resolves a **new** `Bound` instance on every call; this module performs no binding cache or deduplication. | Caching is the host's concern — `WebexStore._getBinding` already memoizes one binding per namespace behind `@oneFlight`. | src/index.js | None executing | Callers that bind repeatedly will accumulate instances; harmless because all state lives in the shared document | Present |
159
+ | `MOD-005` | `get()` resolves any value that is not `undefined`, including the falsey values `0`, `false`, `null`, and `''`. | The shared contract explicitly declares falsey primitives as legitimate stored values, so a truthiness test would corrupt them into not-found. | src/index.js | Declared in the storage-adapter-spec suite; not executed | — | Present |
160
+ | `MOD-006` | `get()` rejects with `NotFoundError` carrying the message `No value found for <key>` — the key is interpolated without quoting — when the key is absent. Two preconditions bound this, both because the lookup is the bare expression `typeof data[key] !== 'undefined'` with no own-property test and no shape check: the key must not be an `Object.prototype` property name (`MOD-016`), and the stored document must conform to the `{ namespace: { key: value } }` schema (`MOD-017`). Outside those preconditions the result is unspecified (`MOD-017`): `get` may resolve a value that was never stored, or reject a different error type. | Callers, including `@persist` rehydration, branch on the not-found type to distinguish "never stored" from "storage failed". | src/index.js | Declared in the storage-adapter-spec suite; not executed | The declared cases use ordinary key names, so they would not detect the prototype-name exception even if they ran | Present |
161
+ | `MOD-007` | Against a schema-conforming document, `put()` stores the value under the bound namespace and resolves with no value. Both halves hold only within the `MOD-017` precondition **and only for JSON-serializable values**. Even inside the precondition, resolution does not imply storage, and some values reject outright. Measured 2026-10-04 against the built `dist/index.js` with a valid document: `undefined`, a `Symbol`, and a function each made `put` **resolve while omitting the key**, so the following `get` rejected `NotFoundError`; a `BigInt` rejected `TypeError: Do not know how to serialize a BigInt` and a cyclic object rejected `TypeError: Converting circular structure to JSON`, both **before `setItem`**; and a value whose `toJSON` throws propagates that error verbatim, so an arbitrary caller-supplied exception can surface from `put`. Lossy-but-successful conversions are covered by `MOD-013`. Outside the `MOD-017` precondition the behavior is unspecified: `put` may reject `TypeError` before `setItem`, or resolve and call `setItem` without storing the value. | The host treats the resolution as a write acknowledgement; `WebexStore.put` supplies its own return value. | src/index.js | Declared in the storage-adapter-spec suite; not executed | — | Present |
162
+ | `MOD-008` | Writing `undefined` through `put()` leaves the key **absent** rather than present-with-undefined, so a following `get()` rejects `NotFoundError` — **provided the key is not an `Object.prototype` property name** (`MOD-016`). Both halves require the `MOD-017` precondition, and the read half additionally requires a non-prototype key. Measured 2026-10-04 against the built `dist/index.js`: on `{"a":{}}`, `put('ordinary', undefined)` wrote `{"a":{}}` and the following `get('ordinary')` rejected `NotFoundError` as stated; but `put('toString', undefined)` wrote the same `{"a":{}}` and the following `get('toString')` **resolved the inherited function** (`MOD-016`). Outside the precondition the write may not reach `setItem` at all. | `_save` serializes with `JSON.stringify`, which omits properties whose value is `undefined`; the removal is a consequence of the chosen encoding, not an explicit branch. | src/index.js | Declared in the storage-adapter-spec suite, but that case also calls del(), so it would not isolate the behavior even if it ran | No test isolates this; it is an emergent property of JSON encoding and could regress silently if the encoding changed | Present |
163
+ | `MOD-009` | Against a schema-conforming document, `del()` removes one key from the bound namespace. It targets no other key or namespace, but it does rewrite the whole document, so siblings are preserved only up to a JSON parse/stringify round trip — see the qualifier in `INV-003`. Like `put`, this holds only within the `MOD-017` precondition; outside it `del` may reject `TypeError` or mutate the stored value in a way that is not a key removal. | Deleting one credential or device record must not disturb unrelated namespaces sharing the document, and the rewrite makes that a round-trip guarantee rather than an untouched-bytes guarantee. | src/index.js | Declared in the storage-adapter-spec suite; not executed | The declared case stores only round-trip-stable values, so it would not detect the `INV-003` edge cases even if it ran | Present |
164
+ | `MOD-010` | `clear()` removes the entire `basekey` entry, destroying **every** namespace stored under it — not only the bound namespace. | Owner-confirmed intent: logout must remove all persisted SDK state under the basekey, including namespaces that were not bound in the current session. `WebexStore.clear()` reaches only bindings created in its own store instance, so a namespace-scoped `clear()` would leave earlier sessions' namespaces behind. | src/index.js | Declared in the storage-adapter-spec suite, but every declared case writes and checks a single key, so namespace-wide scope is never observed; not executed either way | Diverges from `MemoryStoreAdapter`, whose `clear()` affects only its own map (webex-core storage spec). `README.md` describes the namespace-scoped behavior, which is wrong. | Present |
165
+ | `MOD-011` | `clear()` accepts no parameter; any argument a caller passes is ignored. | Owner-confirmed contract: the host calls `clear()` with no argument (webex-core `WebexStore.clear()`), and the purge is basekey-wide by design (`MOD-010`), so a key argument has nothing to select. | src/index.js | None executing. Measured 2026-11-09: calling clear with an argument removed every namespace, identically to calling it with none. | The JSDoc in src/index.js still declares `@param {string} key`, which is stale — a defect recorded under Verification, not a second contract. The shared suite calls clear both with and without an argument; this contract tolerates both because the argument is ignored. | Present |
166
+ | `MOD-012` | *Logically*, `get`, `put`, and `del` address only `allData[namespace]`, so two bindings of the same adapter can hold the same key with different values. *Physically*, all three parse the entire shared document; only `put` and `del` rewrite it with `setItem`. `get` never writes, `bind` touches no storage, and `clear` neither parses nor serializes — it calls `removeItem` alone. Three qualifiers apply to the logical partition: the document shape is a precondition the code never validates, so none of this holds outside it (`MOD-017`); the rewrite is a parse/stringify round trip, so sibling values are preserved only as far as that round trip is lossless (`INV-003`); and namespace selection is a plain property read with no own-property check, so inherited `Object.prototype` names do not partition as distinct namespaces (`MOD-016`). | Namespaces are the host's isolation unit; webex-core binds one namespace per plugin. The physical scope is what makes write cost and the cross-context race document-wide rather than namespace-wide. | src/index.js | Declared in the storage-adapter-spec suite, but that case does not return its inner promise chain, so its assertions would never be awaited even if it ran | — | Present |
167
+ | `MOD-013` | Only JSON-serializable data survives a write/read round trip; values pass through `JSON.stringify` on write and `JSON.parse` on read. Non-serializable values split three ways rather than failing uniformly: `undefined`, `Symbol`, and functions are **silently omitted** while `put` resolves; `BigInt` and cyclic structures **reject** `TypeError`; a throwing `toJSON` propagates its own error (all three detailed in `MOD-007`). `Date` and `Map` convert lossily and resolve. | The backing store holds strings only, so encoding is mandatory and lossy for non-JSON types. | src/index.js | None executing | Functions, `Symbol`, `undefined` members, `Date`, and `Map` do not round-trip; nothing warns the caller | Present |
168
+ | `MOD-014` | Every operation logs through the logger captured at bind time: `get` and `put` at `debug`, `del` and `clear` at `info`, and `bind` itself at `debug`. | Storage reads and writes are a common source of auth and device bugs, so each operation is traceable through the host logger. | src/index.js | None executing | The `info` level on `del`/`clear` versus `debug` elsewhere is inconsistent; no stated reason | Present |
169
+ | `MOD-015` | The Promise contract has two synchronous-throw holes. Without a `localStorage` global, `get`, `put`, and `del` reject with `ReferenceError` while `clear()` throws **synchronously**. The same split applies to an incomplete logger: `del` rejects while `clear` and `bind` throw synchronously. | `get`/`put`/`del` do their work inside a `new Promise` executor, which converts a throw into a rejection; `clear()` evaluates `localStorage.removeItem(basekey)` as an argument to `Promise.resolve`, before any promise exists. | src/index.js | None executing. Measured 2026-11-09 in a bare Node process. | `adapter.clear().catch(...)` does not catch this failure, unlike the other three methods. No guard or feature detection exists. | Present |
170
+ | `MOD-016` | **Within the `MOD-017` precondition on document shape**, neither key lookup nor namespace lookup checks *own* properties, so `Object.prototype` property names leak through as if they were stored data. The empty-slice defaults `_getRawData`/`_load` substitute are object literals `{}`, and a conforming `JSON.parse` result is likewise an ordinary object; all of them inherit from `Object.prototype`, and nothing uses `Object.create(null)` or an own-property test. Measured 2026-10-04 against the built `dist/index.js` with **empty** storage: `get('toString')` and `get('constructor')` resolved inherited functions instead of rejecting `NotFoundError`, while `get('missing')` rejected correctly; `bind('toString')` made `_load` return `Object.prototype.toString` itself, so `get('name')` resolved the string `'toString'` and `get('call')` resolved a function; and namespace `__proto__` is **not merely a lost write — it is prototype pollution**. `_load` evaluates `allData['__proto__']`; when the root has no own property of that name this invokes the inherited getter and returns **the root's prototype**, and because that is truthy the `\|\| {}` fallback never fires, so `data` *is* that prototype object and `data[key] = value` installs an own property on it. **Which prototype is polluted depends on the stored root, not on this module** — it is `Object.getPrototypeOf(root)`, and for a primitive root it is the boxed wrapper's prototype. The key matters as well as the root. An **ordinary** key is installed as an own property. The key `__proto__` instead routes through the inherited accessor and attempts to **re-parent** the target, which is a second and more damaging class: it succeeds for every built-in prototype except `Object.prototype`, the one immutable prototype exotic object. Measured 2026-10-05: with an object root carrying no own `__proto__` key the target is `Object.prototype`, so an object value rejects `TypeError` and other values no-op; with root `[]` an object value re-parented `Array.prototype` so that `[].probe` read the supplied value, and a `null` value severed `Array.prototype` from `Object.prototype`. Two narrower cases do nothing at all: a root carrying an object-valued own `__proto__` key re-parents only that stored object and resolves, and this key under an *ordinary* namespace re-parents only the transient per-namespace object — so **key `__proto__` is a pollution vector only in combination with namespace `__proto__`**. All of these are in the failure-mode table. Measured 2026-10-05 against the built `dist/index.js`, calling `bind('__proto__').put('polluted', 'PWNED')`: absent storage, `{}`, and `{"a":{}}` polluted **`Object.prototype`**; `[]` and `[1,2]` polluted **`Array.prototype`**; `5` polluted **`Number.prototype`**; `"s"` polluted **`String.prototype`**; `true` polluted **`Boolean.prototype`**. Two roots are exceptions. A `null` root **rejects** `TypeError` and pollutes nothing, because `_load` cannot read a property of `null`. A root with an own `__proto__` key pollutes nothing and **persists** the write instead — `JSON.parse` creates that key as an ordinary own property rather than invoking the setter, so with `{"__proto__":{"k":1}}` the same call wrote `{"__proto__":{"k":1,"polluted":"PWNED"}}`. The storage write is separately lost in the polluting cases: `_save` assigns `allData['__proto__'] = <prototype>`, which only re-invokes the setter — and silently no-ops entirely for a primitive root, since the `__proto__` setter returns without effect when its receiver is not an object — after which `JSON.stringify` emits the root unchanged. Measured 2026-10-04: `bind('__proto__').put('polluted', 'PWNED')` resolved, and afterwards `({}).polluted`, `[].polluted`, and `(function(){}).polluted` all returned `'PWNED'` — every object in the realm, not just this adapter's data — with `Object.prototype.hasOwnProperty('polluted')` true. The storage write is lost separately: `_save` assigns `allData['__proto__'] = Object.prototype`, which only re-invokes the setter, and `JSON.stringify` then emits `{}`. The in-memory effect persists for the lifetime of the realm and is not undone by `clear()`. An *explicitly stored* own key of the same name shadows the inherited one and reads back correctly — `put('toString', 'mine')` then `get('toString')` resolved `'mine'`. **Accepted constraint:** callers must use key and namespace names that are not `Object.prototype` properties — in practice `constructor`, `hasOwnProperty`, `isPrototypeOf`, `propertyIsEnumerable`, `toLocaleString`, `toString`, `valueOf`, and `__proto__`. Every host-supplied name observed in this repo (webex-core namespaces, `@persist` attribute names) satisfies it, which is why the defect has not surfaced. | This records current behavior, not intended behavior. `get` promises `NotFoundError` for absent keys (`MOD-006`) and namespaces are meant to partition values (`MOD-012`); both break on these names. The `__proto__` case is a different and more serious class from the rest of this requirement: it is prototype pollution (CWE-1321) reachable through a caller-supplied namespace, in a module whose documented job is persisting OAuth tokens in a browser. Because the target is the stored root's prototype, a co-resident script that controls the document also controls which built-in prototype is hit — or, by writing an own `__proto__` key, neutralizes the path entirely. The reachable vector is a caller-supplied **namespace**; a caller-supplied key can cause lost writes and inherited-member reads but does not mutate a built-in prototype under an ordinary namespace. It escapes the module entirely — nothing about it is scoped to storage. It is recorded here because this pass is spec-only, not because documenting it is an adequate response; see the security note under Pitfalls. Hardening is a code change with tests, deliberately out of scope for this spec-only pass, and it is larger than it first looks: a complete fix has to cover **all four** read and write paths — the namespace lookup in `_load`, the key lookup in `get`, the namespace assignment in `_save` (the `__proto__` write path), and the objects `JSON.parse` returns. Switching only the `{}` defaults to `Object.create(null)` does not help, because a parsed document still carries `Object.prototype`; and adding a `hasOwnProperty` test only in `get` leaves `_load` and `_save` unfixed. The workable combinations are an own-property test at every lookup plus a prototype-stripping step applied to each parse result, or a reviver/`Object.setPrototypeOf(..., null)` pass in `_getRawData` plus a guarded assignment in `_save`. | src/index.js | None executing. Measured 2026-10-04 and 2026-10-05 against the built dist with a localStorage stand-in; the object-root and array-root pollution, the inherited-member reads, and the toString namespace read were re-measured 2026-11-09. | No committed test pins any of this; a hardening change would alter every observed behavior above and nothing would catch a regression in either direction. The intended handling is an unfixed code defect, not an accepted contract | Present (observed behavior) |
171
+ | `MOD-017` | **The adapter states a precondition on its input and validates none of it.** It requires (a) a document matching `{ "<namespace>": { "<key>": <json-value> } }` and (b) namespace and key names that are not `Object.prototype` property names. `_getRawData` returns whatever `JSON.parse` yields and `_load` applies only `allData[namespace] \|\| {}`, so nothing checks either condition. **Behavior on input outside this precondition is unspecified.** Three consequence classes are guaranteed only in the negative — the adapter does not prevent them: a read may resolve a value that was never stored; a write may resolve, and call `setItem`, without storing the value given; and a rejection may carry a type other than the documented `NotFoundError`/`SyntaxError`, typically `TypeError`. **Violations are not uniformly silent.** The third class is visible — the caller gets a rejection, just an undocumented one — while the first two give no signal at all. Which class applies to a given input is itself unspecified, so a caller can neither rely on a violation surfacing nor assume one will stay hidden; the split is shown per-condition in the failure-mode table. `clear()` is the only method outside this precondition, because it parses nothing. No guarantee is made about which input produces which outcome, and none should be inferred from the examples below. | `localStorage` is origin-wide, so any script can write a conflicting shape, and the reserved-name hazard is reachable through any caller-chosen name. Stating a precondition plus unspecified behavior is deliberate: the code validates nothing, so the behavior space is the product of document shape, namespace name, and key name, and any enumeration of it is both unbounded and non-binding. A caller cannot rely on observed behavior here, so the specification does not offer it as a contract. Shape validation, own-property tests, and failing closed are the implementation decisions that would let this requirement make positive guarantees; none has been made. | src/index.js | None executing. Characterized 2026-10-04 against the built dist and spot-checked 2026-11-09 (a string namespace slice, read and write); see the non-normative examples below. | The precondition is undocumented in `README.md` and unenforced in code, so nothing stops a caller or a co-resident script from violating it. No test covers any violation, and no decision to validate input has been made | Present (precondition and non-guarantee) |
172
+ | `MOD-018` | A release must read a `localStorage[basekey]` document written by any earlier release. A change to the `{ "<namespace>": { "<key>": <json-value> } }` layout or to its JSON encoding must ship with a migration that still reads the previous layout, and is a breaking change. | Owner-confirmed compatibility promise: the document holds persisted Credentials, Device, and User records, and `_load` returns `{}` for anything it cannot find, so an unreadable older document would silently drop sign-in and device state on upgrade instead of surfacing as a detected incompatibility. | src/index.js | None executing | The document carries no version field and the code has no migration step, so nothing enforces the promise; it is held by review. No test reads a document written by a previous release | Present |
173
+
174
+ The examples below characterize the **current build only** for input that violates the `MOD-017` precondition. They are **non-normative**: they are observations of `dist/index.js` as built on 2026-10-04, not a contract, and they may change without notice because no test pins them and no code enforces them. They are recorded so a future contributor can recognize the symptoms, not so a caller can depend on them.
175
+
176
+ - Reads that fabricate: with `{"a":"hi"}`, `bind('a').get('0')` resolved `"h"` and `get('length')` resolved `2`. With empty storage, `get('toString')` and `get('constructor')` resolved inherited functions, and `bind('toString').get('name')` resolved `'toString'`. An explicitly stored own key of the same name shadows the inherited one and reads back correctly.
177
+ - Writes that resolve without storing: under an array namespace slice or array document root, a non-index name resolved and called `setItem` while `JSON.stringify` dropped the value; an index name mutated the array instead (`put('0', 1)` on `{"a":[7,8]}` wrote `{"a":[1,8]}`). A `put` under namespace `__proto__` left the stored root unchanged and, when that root had no own `__proto__` key, **installed the key on the root's prototype** — that part is a normative defect, not a characterization, and is stated in `MOD-016`.
178
+ - Rejections of an unexpected type: a truthy primitive namespace slice, or a primitive or `null` root, rejected `TypeError` before `setItem` — the practical determinant was whether the value `_load` returned was assignable, not whether any container was an array.
179
+ - Writes do not reliably repair or preserve a non-conforming document (`INV-004`): `{"a":0}` became the conforming `{"a":{"x":1}}`, while `[1,2]` was re-persisted unchanged.
180
+
181
+ ## Design overview
182
+
183
+ The module is one file and one idea: present webex-core's asynchronous storage-adapter interface on
184
+ top of a synchronous, string-only browser API.
185
+
186
+ The outer `StorageAdapterLocalStorage` class is essentially a factory. Its constructor
187
+ (`src/index.js`) takes `basekey` and immediately defines an inner `Bound` class that closes over
188
+ it. This is the module's central structural choice: `basekey` is never stored as
189
+ an instance property and never passed to a binding, so every `Bound` produced by one adapter is
190
+ permanently tied to the same `localStorage` entry, and the value cannot be reassigned after
191
+ construction. The cost is that a new `Bound` class object is created per adapter instance rather
192
+ than shared on a prototype.
193
+
194
+ Per-binding state — the namespace string and the logger — is held outside the instance in two
195
+ module-level `WeakMap`s declared at the top of `src/index.js` and filled by the `Bound` constructor. Both are effectively private: nothing exposes
196
+ them, and entries disappear when a binding is collected. The practical consequence is that a binding
197
+ carries no enumerable own properties, so it cannot be serialized or inspected to discover which
198
+ namespace it serves.
199
+
200
+ Document access is per-method, not uniform. `_getRawData` reads the single entry and parses it,
201
+ substituting `{}` when absent; `_load` narrows that to the binding's own
202
+ namespace; `_save` re-reads the whole document, replaces this namespace's slice, and
203
+ writes everything back (all in `src/index.js`). The four public methods therefore divide into four distinct
204
+ access patterns:
205
+
206
+ | Method | `getItem` + parse | `setItem` + serialize | `removeItem` |
207
+ | ------ | ----------------- | --------------------- | ------------ |
208
+ | `bind` | no | no | no — it touches no storage at all |
209
+ | `get` | once, via `_load` | no | no |
210
+ | `put` / `del` | twice — once in `_load`, once inside `_save` | once, whole document | no |
211
+ | `clear` | no | no | once, on `basekey` |
212
+
213
+ Measured 2026-11-09: `get` issued one `getItem` and zero `setItem`/`removeItem` calls, while `clear`
214
+ issued zero `getItem`/`setItem` and one `removeItem`. So `get` pays the parse cost of all namespaces
215
+ combined and the two write methods pay parse plus serialize, rather than the cost of the value alone
216
+ — acceptable for credentials and device records. `bind` and `clear` pay neither, which is why
217
+ `clear()` can be a single `removeItem` with no parse at all and still works on a document this
218
+ adapter cannot parse (`INV-004`).
219
+
220
+ Three of the four bound methods wrap their work in `new Promise(executor)`; `clear()` instead
221
+ returns `Promise.resolve(<expression>)`, whose argument is evaluated first. That difference is not
222
+ cosmetic: it is why `clear()` alone fails synchronously when the backing global is missing.
223
+ `bind()` has the same shape of hole for a different reason — it calls `options.logger.debug`
224
+ directly, outside any promise — so the Promise contract has two synchronous-throw exits, not one
225
+ (see `MOD-015`).
226
+
227
+ ## Data flow and sequence coverage
228
+
229
+ The transport is the synchronous same-origin `localStorage` API; there is no network, worker, or IPC
230
+ boundary. Operations fall into four groups, separated because their document access patterns and
231
+ failure behavior genuinely differ: binding setup touches no storage, reads parse only, writes
232
+ read-modify-write, and the purge bypasses the document entirely.
233
+
234
+ | Operation group | Entry and outcome | Diagram or evidence | Failure and recovery coverage |
235
+ | --------------- | ----------------- | ------------------- | ----------------------------- |
236
+ | Bind | `bind(namespace, options)` → resolved `Bound`, or rejection on a missing argument | Flowchart and operation sequence below; src/index.js | Both argument rejections covered; no storage access, so it cannot fail on a missing backing store. Not covered: a *present* logger lacking `debug`, which throws synchronously past `.catch()` (`MOD-015`) |
237
+ | Read | `get(key)` → stored value, or `NotFoundError` | Flowchart and operation sequence below; src/index.js | Absent key covered; missing-global rejection covered. Not covered: `Object.prototype` key names, which resolve inherited members instead of rejecting (`MOD-016`) |
238
+ | Write / delete | `put(key, value)` or `del(key)` → resolved, document rewritten | Flowchart and operation sequence below; src/index.js | Missing-global rejection covered; no quota-exceeded handling exists |
239
+ | Purge | `clear()` → whole `basekey` entry removed | Flowchart and operation sequence below; src/index.js | Synchronous throw on a missing global — the only method that fails this way on an absent backing store, though `bind` throws the same way on an incomplete logger, so `.catch()` has holes on both paths |
240
+
241
+ ```mermaid
242
+ flowchart LR
243
+ Caller[webex-core WebexStore] -->|bind namespace, logger| Bind{namespace and logger present?}
244
+ Bind -->|no| Rej[reject Error]
245
+ Bind -->|yes| Bound[new Bound, namespace and logger in WeakMaps]
246
+
247
+ Bound -->|get key| Load[_load: getItem basekey, JSON.parse, select namespace]
248
+ Load --> Found{value !== undefined?}
249
+ Found -->|yes| Val[resolve value]
250
+ Found -->|no| NF[reject NotFoundError]
251
+
252
+ Bound -->|put / del key| RMW[_load, mutate slice, _save: re-read, merge, setItem]
253
+ RMW --> Ok[resolve]
254
+
255
+ Bound -->|clear| Purge[removeItem basekey - ALL namespaces]
256
+ Purge --> Ok2[resolve]
257
+ ```
258
+
259
+ Failure path when the backing global is absent — note that the purge branch leaves the promise
260
+ contract entirely:
261
+
262
+ ```mermaid
263
+ flowchart LR
264
+ NoLS[localStorage undefined] --> G[get / put / del]
265
+ NoLS --> C[clear]
266
+ G -->|throw inside Promise executor| GR[promise REJECTS with ReferenceError]
267
+ C -->|argument evaluated before Promise.resolve| CT[throws SYNCHRONOUSLY - .catch never runs]
268
+ ```
269
+
270
+ ### Operation sequences
271
+
272
+ The flowcharts above show which branch each operation takes. The sequences below show the ordering
273
+ that the branches hide: how many times a single call reads the backing store, where in the call the
274
+ logger is touched, and at which point a failure escapes. Participants are the host, the `Bound`
275
+ instance, its two private helpers, and the `localStorage` global. All evidence is `src/index.js`
276
+ unless noted.
277
+
278
+ **Bind — no storage access.** The only operation that cannot fail on an absent backing store,
279
+ because it never reaches one:
280
+
281
+ ```mermaid
282
+ sequenceDiagram
283
+ autonumber
284
+ participant Host as webex-core WebexStore
285
+ participant Adapter as StorageAdapterLocalStorage
286
+ participant Logger as options.logger
287
+ participant Bound
288
+
289
+ Host->>Adapter: bind(namespace, options)
290
+ Adapter->>Adapter: options = options || {}
291
+ alt namespace is falsy
292
+ Adapter-->>Host: reject Error "`namespace` is required"
293
+ else options.logger is falsy
294
+ Adapter-->>Host: reject Error "`options.logger` is required"
295
+ else both present
296
+ Adapter->>Logger: debug "returning binding"
297
+ Note over Adapter,Logger: MOD-015 — a logger without `debug`<br/>throws here, outside the promise —<br/>the caller's .catch never runs
298
+ Adapter->>Bound: new this.Bound(namespace, options)
299
+ Bound->>Bound: namespaces.set(this, namespace)
300
+ Bound->>Bound: loggers.set(this, options.logger)
301
+ Adapter-->>Host: resolve Bound
302
+ end
303
+ ```
304
+
305
+ **Read — one parse, two outcomes.** `get` resolves or rejects entirely inside the promise executor,
306
+ which runs synchronously; the asynchrony is in the settlement, not the storage access:
307
+
308
+ ```mermaid
309
+ sequenceDiagram
310
+ autonumber
311
+ participant Host
312
+ participant Bound
313
+ participant Load as _load / _getRawData
314
+ participant LS as localStorage
315
+
316
+ Host->>Bound: get(key)
317
+ Bound->>Bound: logger.debug "reading key"
318
+ Bound->>Load: _load()
319
+ Load->>LS: getItem(basekey)
320
+ alt entry absent
321
+ LS-->>Load: null
322
+ Load->>Load: substitute {} without parsing
323
+ else entry present
324
+ LS-->>Load: raw JSON string
325
+ Load->>Load: JSON.parse(raw)
326
+ Note over Load: foreign or truncated content throws<br/>SyntaxError here — thrown inside the<br/>executor, so the promise REJECTS
327
+ end
328
+ Load-->>Bound: allData[namespace] || {}
329
+ alt typeof value !== "undefined"
330
+ Bound-->>Host: resolve value
331
+ Note over Bound,Host: presence, not truthiness —<br/>false, 0 and "" survive (MOD-005)
332
+ else key absent
333
+ Bound-->>Host: reject NotFoundError
334
+ end
335
+ ```
336
+
337
+ **Write and delete — read twice, write once.** `put` and `del` differ only in how they mutate the
338
+ namespace slice; both then re-enter storage through `_save`, which performs its own independent
339
+ read rather than reusing the document `_load` just produced. What that second read does and does
340
+ not protect is set out after the diagram:
341
+
342
+ ```mermaid
343
+ sequenceDiagram
344
+ autonumber
345
+ participant Host
346
+ participant Bound
347
+ participant Load as _load / _getRawData
348
+ participant Save as _save
349
+ participant LS as localStorage
350
+
351
+ Host->>Bound: put(key, value) or del(key)
352
+ Bound->>Bound: logger.debug "writing" / logger.info "deleting"
353
+ Bound->>Load: _load()
354
+ Load->>LS: getItem(basekey)
355
+ LS-->>Load: raw JSON string or null
356
+ Load-->>Bound: namespace slice
357
+ alt put
358
+ Bound->>Bound: data[key] = value
359
+ else del
360
+ Bound->>Bound: Reflect.deleteProperty(data, key)
361
+ Note over Bound: absent key is not an error —<br/>deleteProperty returns true
362
+ end
363
+ Bound->>Save: _save(data)
364
+ Save->>LS: getItem(basekey)
365
+ Note over Save,LS: SECOND read of the full document.<br/>It re-reads OTHER namespaces, but the next<br/>line replaces this namespace wholesale<br/>from the stale _load snapshot
366
+ LS-->>Save: raw JSON string or null
367
+ Save->>Save: allData[namespace] = data
368
+ Note over Save: the slice written back is the read-1<br/>snapshot plus one mutation — a same-namespace<br/>write that landed in between is discarded here
369
+ Save->>LS: setItem(basekey, JSON.stringify(allData))
370
+ Note over Save,LS: no quota handling — a QuotaExceededError<br/>propagates out of the executor and<br/>rejects the promise unlabelled
371
+ Bound-->>Host: resolve undefined
372
+ ```
373
+
374
+ The second read is the subtlest part of the sequence: it refreshes sibling namespaces but not this
375
+ binding's own slice, which is written back from the read-1 snapshot. What that does and does not
376
+ protect against a concurrent writer is analysed once, in
377
+ [Concurrency and reactive flow](#concurrency-and-reactive-flow).
378
+
379
+ **Purge — the one path that bypasses the document.** `clear` neither reads nor parses, which makes
380
+ it the only in-adapter recovery from a corrupted entry, and the only method whose failure escapes
381
+ the promise contract:
382
+
383
+ ```mermaid
384
+ sequenceDiagram
385
+ autonumber
386
+ participant Host as WebexStore.clear fan-out
387
+ participant Bound
388
+ participant LS as localStorage
389
+
390
+ Host->>Bound: clear()
391
+ Bound->>Bound: logger.info "clearing localStorage"
392
+ Bound->>LS: removeItem(basekey)
393
+ Note over Bound,LS: the argument is evaluated BEFORE<br/>Promise.resolve wraps it — an absent<br/>global throws SYNCHRONOUSLY and<br/>.catch never runs (MOD-015)
394
+ LS-->>Bound: undefined
395
+ Bound-->>Host: resolve (Promise.resolve of removeItem)
396
+ Note over Host,LS: removes the whole basekey entry —<br/>every namespace, not just this binding.<br/>Later fan-out calls are no-ops (MOD-010)
397
+ ```
398
+
399
+ ## Class and component relationships
400
+
401
+ ```mermaid
402
+ classDiagram
403
+ class StorageAdapterLocalStorage {
404
+ +constructor(basekey)
405
+ +Bound : class
406
+ +bind(namespace, options) Promise~Bound~
407
+ }
408
+ class Bound {
409
+ -_getRawData() Object
410
+ -_load() Object
411
+ -_save(data) void
412
+ +get(key) Promise
413
+ +put(key, value) Promise
414
+ +del(key) Promise
415
+ +clear() Promise
416
+ }
417
+ class WeakMapRegistry["namespaces / loggers WeakMaps"] {
418
+ module-level per-binding state
419
+ }
420
+ class NotFoundError {
421
+ from @webex/webex-core
422
+ }
423
+ class WebexStore["webex-core WebexStore (host, not owned here)"] {
424
+ +_getBinding(namespace)
425
+ }
426
+ StorageAdapterLocalStorage --> Bound : defines per instance, closes over basekey
427
+ Bound --> WeakMapRegistry : namespace and logger
428
+ Bound --> NotFoundError : rejects with
429
+ WebexStore --> StorageAdapterLocalStorage : calls bind()
430
+ ```
431
+
432
+ ## Use cases and flows
433
+
434
+ | Use case | Actor or caller | Primary steps and outcome | Failure or boundary behavior | Evidence |
435
+ | -------- | --------------- | ----------------------------- | ---------------------------- | ------------------------- |
436
+ | `UC-001` | `webex-core` `WebexStore._getBinding` | Host resolves a binding for a plugin namespace once and caches it; `bind` resolves a `Bound` without touching storage | Rejects on falsy namespace or missing logger | src/index.js; webex-core/src/lib/storage/make-webex-store.js |
437
+ | `UC-002` | `@persist`-decorated state (Credentials, Device, User) | On change, the host serializes the model and calls `put`; the value is merged into the namespace slice and the whole document is rewritten | Rejects with `ReferenceError` outside a browser; no quota handling | webex-core/src/lib/storage/decorators.js; src/index.js |
438
+ | `UC-003` | Host rehydration on construction | `get` is called per persisted key; absent keys reject `NotFoundError` and the host falls back to an unset attribute | Falsey stored values must survive, which `MOD-005` guarantees | webex-core/src/lib/storage/decorators.js; src/index.js |
439
+ | `UC-004` | Logout / credential purge | Host calls `WebexStore.clear()`, which fans out `clear()` to every cached binding; the first call already removes the whole `basekey` entry, so later calls are no-ops on an absent entry | Destroys unrelated namespaces by design (`MOD-010`); throws synchronously outside a browser (`MOD-015`) | webex-core/src/lib/storage/make-webex-store.js; src/index.js |
440
+
441
+ ## Business rules and invariants
442
+
443
+ | ID | Invariant | WHY | Enforcement source | Test evidence |
444
+ | --------- | ------------------------------------ | ----------- | ------------------ | ------------- |
445
+ | `INV-001` | A binding is never created without both a truthy namespace and a logger. | Both are read unconditionally afterwards; validating at bind time keeps the failure at the point of misuse. | src/index.js | Declared in the storage-adapter-spec suite; not executed |
446
+ | `INV-002` | Only `undefined` means "absent"; every other value *reachable* at `data[key]` is a hit. "Reachable" is the precise word, and it is weaker than "stored": the test is `typeof data[key] !== 'undefined'` with no own-property check and no shape check, so it reports a hit on anything that expression can reach. It reaches an inherited `Object.prototype` member (`MOD-016`), and outside the `MOD-017` precondition it can reach a property of whatever non-object value is stored. Read as an absence contract, the invariant holds only within that precondition and for non-prototype keys; read as a presence contract — no stored value is ever mistaken for absent — it holds unconditionally. | Guarantees `0`, `false`, `null`, and `''` round-trip rather than degrading to `NotFoundError` — the reason truthiness is not used. The false-hit cases are the cost of that same unguarded property read. | src/index.js | Declared in the storage-adapter-spec suite; not executed |
447
+ | `INV-003` | `get`, `put`, and `del` never *target* a value outside `allData[namespace]`, but `put`/`del` do rewrite the whole document, so the preservation guarantee for sibling namespaces is exactly this: **a sibling value survives a write in another namespace if, and only if, it is unchanged by a `JSON.parse` → `JSON.stringify` round trip.** Preservation is neither byte-for-byte nor universally value-for-value. Measured 2026-10-04 (byte-level): a hand-formatted sibling kept value `2` while its whitespace was stripped, `1e3` was rewritten as `1000`, and key order changed. Measured 2026-10-04 (value-level): given the externally written document `{"b":{"neg":-0,"big":1e400}}`, a `put` in namespace `a` left namespace `b` holding `neg: 0` — `Object.is(-0, 0)` is `false`, so the parsed value changed — and `big: null`, because `1e400` parses to `Infinity` and `JSON.stringify(Infinity)` is `null`. A sibling value that `JSON.parse` already degrades on read (`1e-400` → `0`, integers beyond 2^53) is lost on first read regardless of any write. | Namespace isolation is the only partitioning the shared document has, and it is enforced by key selection, not by storage-level separation. Anything that depends on the exact bytes of another namespace's region — a hash, a signature, a formatting convention — or on a value outside the JSON number/value model is not preserved. Callers storing only values this adapter itself wrote are unaffected, because `_save` already emitted them through `JSON.stringify`; the exposure is to documents written by another script on the origin. | src/index.js | Declared in the storage-adapter-spec suite, but that case never awaits its assertions; not executed |
448
+ | `INV-004` | **Validity (conditional):** within the `MOD-017` precondition, and provided the realm's JSON serialization is unmodified — in particular, no callable `toJSON` is reachable from the document root, as one installed on `Object.prototype` would be — whenever `_save` reaches `setItem`, the string it writes is valid JSON: `JSON.stringify` output over a value that came from `JSON.parse` or a fresh object literal. Within those conditions no stored value can break this: whatever it serializes to, the root still serializes to a JSON object, or `JSON.stringify` throws before `setItem` (`MOD-007`). Neither condition is checked: `_save` passes whatever `JSON.stringify` returns straight to `setItem`, and `JSON.stringify` returns `undefined`, not a string, when a `toJSON` reachable from the root returns `undefined`. Measured 2026-10-06 with empty storage: `bind('__proto__').put('toJSON', () => undefined)` resolved after installing `toJSON` on `Object.prototype` through the `MOD-016` pollution path; `setItem` received `undefined`, storage coerced it to the string `"undefined"`, and the next `get`, `put`, and `del` rejected `SyntaxError`. Because the inherited `toJSON` outlives `clear()` (`MOD-016`), `clear()` removed the entry but the next write resolved and stored `"undefined"` again, and so did a write through a second adapter instance under a different basekey in the same realm. This is recorded current behavior, not a contract; outside these conditions validity is unspecified (`MOD-017`). **Conformance does not follow from validity, in either direction.** `_save` mutates the parsed existing document in place and re-stringifies it; it neither validates nor normalizes the result. So a write carries no guarantee that a non-conforming entry will be repaired, and no guarantee that it will be left alone — both outcomes occur, and which one applies is unspecified (`MOD-017`). The adapter can therefore re-persist a non-conforming document it did not create. Nothing at all is guaranteed for an entry the adapter never wrote: `localStorage` is origin-wide, so any script may replace the key. | Validity and conformance fail separately and are handled differently. Invalid JSON rejects loudly with `SyntaxError` on the next `get`/`put`/`del`, which is recoverable and visible. A document that is valid but violates the `MOD-017` precondition is not reliably signalled: some violations reject visibly with `TypeError` — a truthy primitive namespace slice, a primitive root, a `null` root — while others are processed with no signal at all, such as an array slice. Because writes additionally make no normalization promise, a caller can neither assume the adapter will clean up after a foreign writer nor that it will preserve what that writer left. `clear()` is the only operation that removes such a document unconditionally. The silent case is the more dangerous of the two precisely because nothing signals it. `_getRawData` parses unconditionally, so externally corrupted content makes `get`, `put`, and `del` reject with `SyntaxError`. `clear()` is exempt — it calls `removeItem` without parsing — which makes it the in-adapter recovery operation, at the cost of destroying every namespace. Measured 2026-10-04. | src/index.js | None |
449
+ | `INV-005` | `clear()` is scoped to the `basekey` entry, never to a namespace. | Stated here as the actual contract so callers do not assume the namespace scope that `README.md` describes. | src/index.js | Declared cases never observe namespace-wide scope; not executed |
450
+
451
+ ## Concurrency and reactive flow
452
+
453
+ - Execution model: browser event loop, single-threaded. Every public method is Promise-returning on
454
+ its normal path — with two synchronous-throw exceptions, `bind` and `clear`, detailed in
455
+ `MOD-015` and the failure-mode table — but
456
+ all storage work inside it is synchronous — there is no `await`, callback, or microtask boundary
457
+ between a read and its matching write (`_save` in `src/index.js`).
458
+ - Ordering guarantees: within one JS context, each `put`/`del` read-modify-write cycle runs to
459
+ completion without interleaving, so concurrent writes to the same key resolve last-write-wins and
460
+ concurrent writes to *different* namespaces both survive. Measured 2026-10-01: three concurrent
461
+ `put`s to one key yield the last value; concurrent puts to two namespaces leave both intact.
462
+ - Idempotency and retry: `put`, `del`, and `clear` are idempotent for a given argument. The module
463
+ performs no retries and owns no deduplication key; `WebexStore._getBinding` applies `@oneFlight`
464
+ on the bind path only.
465
+ - Shared-state protection: **none that detects a conflict**. There is no lock, version check, or
466
+ compare-and-set. There is a second read, but it is a fresh snapshot, not a check: `put` and `del`
467
+ read and parse the document in `_load` (read 1), read and parse it again in
468
+ `_save` (read 2), then write it once at `setItem` — the three boundaries marked
469
+ in the write sequence diagram (`src/index.js`). Measured 2026-11-09: a normal `put` and a normal `del`
470
+ each issued two `getItem` calls and one `setItem`. Nothing compares the two reads. `_save` takes
471
+ sibling namespaces from the second read but writes back the bound namespace's slice built from
472
+ the first. At most, the second read carries forward a sibling change it observes. It cannot
473
+ preserve a concurrent change to the bound namespace, and anything another context writes after
474
+ that read is still overwritten by the `setItem`. Within a single context nothing yields to the
475
+ event loop between the reads and the write, so the read-modify-write cycle is safe there only
476
+ because it is uninterrupted. Across browser contexts sharing the origin — a second tab, or an
477
+ iframe — two cycles can interleave at the `localStorage` level and the later `setItem` silently
478
+ discards the other's changes. Nothing in this module detects or mitigates that.
479
+ - Blocking restrictions: `localStorage` is synchronous and blocks the main thread. The cost is
480
+ method-specific. `put` and `del` parse and re-serialize the *whole* document, so their cost grows
481
+ with total stored size across all namespaces, not with the value being written; a large value in
482
+ one namespace therefore slows every other namespace's writes. `get` pays the parse half of that
483
+ cost but never serializes. `bind` and `clear` pay neither — `bind` touches no storage and `clear`
484
+ is a single `removeItem`.
485
+
486
+ ## Data, schema, and migration discipline
487
+
488
+ | Store or schema | Owned entities or keys | Source of truth | Migration and compatibility rule |
489
+ | --------------- | ---------------------- | --------------- | -------------------------------- |
490
+ | `localStorage[basekey]` — one JSON document shaped `{ "<namespace>": { "<key>": <json-value> } }` | Every namespace the host binds through this adapter. In the browser `webex` bundle the basekey is `webex` and the entities are the `@persist`ed Credentials (including `supertoken`), Device, and User records. | src/index.js | Registered as contract `local-storage-bounded-document` (internal). Current behavior only: the document persists across page loads and across releases, and the code carries no version field, no migration step, and no schema validation. `_getRawData` parses whatever is present and `_load` returns `{}` for an unknown namespace, so changing the encoding would surface as missing or malformed values at read time rather than as a detected upgrade. The absence of schema validation is not only a migration concern: because the shape is never checked, a valid-but-non-conforming document from any other script on the origin is processed silently and can fabricate reads or swallow writes — see `MOD-017` for the measured matrix. Remaining readable across releases is a committed promise (`MOD-018`): a newer release must read a document written by an older one, and any change to the layout or its JSON encoding needs a migration and is a breaking change. Nothing in the code enforces that today — there is no version field to branch on — so the promise is held by review, not by a guard. |
491
+
492
+ Retention, deletion, backfill, rollback, and cache behavior:
493
+
494
+ - Retention is indefinite. Nothing expires entries; data lives until `del`, `clear`, or the user
495
+ clears site data.
496
+ - Deletion has two scopes and they are easy to confuse: `del(key)` removes one key from one
497
+ namespace, while `clear()` removes the whole entry for every namespace (`MOD-010`).
498
+ - There is no backfill or rollback mechanism. A write is immediately durable; nothing journals the
499
+ prior value.
500
+ - The adapter caches nothing. `_getRawData` re-reads and re-parses the entry on every operation
501
+ that touches the document — `get`, `put`, and `del`; `bind` and `clear` never call it — so a
502
+ subsequent `get` returns whatever is in storage at that moment, including a value written by
503
+ another tab. Measured 2026-10-04: a binding created before an external write returned the new
504
+ value on its next `get`. What `webex-core` caches is the *binding object*, not stored values
505
+ (webex-core `src/lib/storage/make-webex-store.js`). What the module does not do is *notify*: it registers no
506
+ `storage` event listener, so a consumer holding a previously read value is never told it changed
507
+ and will only see the update when it reads again.
508
+ - Cross-release compatibility is an owner-confirmed promise (`MOD-018`). Because the document has no
509
+ version field, a future migration has to recognize the older layout from its shape; adding a
510
+ version field is itself a layout change and needs the same migration discipline.
511
+
512
+ ## Caller-visible failure modes
513
+
514
+ | Condition | Signal or result | Caller behavior | Retry or recovery | Evidence |
515
+ | ----------- | ---------------- | --------------- | ----------------- | -------- |
516
+ | Falsy `namespace` passed to `bind` | Rejected promise, ``Error('`namespace` is required')`` | Fix the call site; this is programmer error | Not retryable | src/index.js |
517
+ | `options.logger` missing | Rejected promise, ``Error('`options.logger` is required')`` | Supply the host logger | Not retryable | src/index.js |
518
+ | Key absent on `get`, for any key that is not an `Object.prototype` property name | Rejected promise, `NotFoundError` with `No value found for <key>` | Treat as "never stored" and fall back to a default; this is the expected cold-start path | Not an error condition | src/index.js |
519
+ | `get` called with an `Object.prototype` property name (`toString`, `constructor`, `valueOf`, `hasOwnProperty`, …) | **No rejection.** Resolves the inherited `Object.prototype` member even when nothing was ever stored — `get('toString')` and `get('constructor')` resolve functions | Caller receives a function where it expected stored data or a `NotFoundError`, and a `catch`-based "not stored" branch never runs | Not retryable; avoid these key names. No guard exists (`MOD-016`). Measured 2026-11-09 against empty storage. | src/index.js |
520
+ | `bind` called with an `Object.prototype` property name as the namespace | **No rejection from `bind`.** `_load` can return an inherited member instead of `{}`, so `get` reads properties of that member — `bind('toString').get('name')` resolves `'toString'` with nothing stored. For namespace `__proto__`, `put` depends on both the key and the stored root: an ordinary key can mutate a built-in prototype while losing the storage write; key `__proto__` with an object value can reject or re-parent a built-in prototype; and an object-valued own `__proto__` root key can make an ordinary write persist (detailed rows below) | Reads can return fabricated values. Writes can lose data, reject, mutate a built-in prototype, or persist under an own root key; no single silent-loss outcome covers them | Not retryable; avoid these namespace names. No guard exists (`MOD-016`). Measured cases are scoped in the dedicated rows below. | src/index.js |
521
+ | No `localStorage` global, on `get`/`put`/`del` | Rejected promise, `ReferenceError: localStorage is not defined` | Indicates the adapter was configured outside a browser; use `MemoryStoreAdapter` instead | Not retryable | src/index.js; measured 2026-11-09 |
522
+ | No `localStorage` global, on `clear` | **Synchronous throw**, `ReferenceError` | A caller using `adapter.clear().catch(...)` will not catch it and the exception escapes | Not retryable; requires `try`/`catch` rather than `.catch()` | src/index.js; measured 2026-11-09 |
523
+ | `options.logger` lacks `debug` | **Synchronous throw** from `bind`, `TypeError: options.logger.debug is not a function` | Supply a logger implementing `debug`; `bind().catch(...)` will not catch this | Not retryable. Unlike the missing-logger case, which rejects, an incomplete logger escapes the promise. Measured 2026-11-09. | src/index.js |
524
+ | `options.logger` lacks `info`, on `del` | Rejected promise, `TypeError` | Supply a logger implementing `info` | Not retryable. `bind`, `get`, and `put` succeed with such a logger, so the defect surfaces only on first delete. Measured 2026-11-09. | src/index.js |
525
+ | `options.logger` lacks `info`, on `clear` | **Synchronous throw**, `TypeError` | Supply a logger implementing `info`; `.catch()` will not see it | Not retryable. Measured 2026-11-09. | src/index.js |
526
+ | Entry contains non-JSON content | `SyntaxError` from `JSON.parse` inside the executor, surfacing as a rejected promise from `get`, `put`, and `del` | Call `clear()` to recover | `clear()` removes the entry without parsing it, so it succeeds on a corrupt document and the adapter is usable again immediately afterwards. Measured 2026-11-09. The recovery lasts only while the `INV-004` serialization condition holds: `clear()` does not remove a `toJSON` installed on `Object.prototype`, so a later write can corrupt the entry again (`INV-004`). The cost is its scope: recovery destroys every namespace under the basekey, so it trades all persisted state for a working store. | src/index.js |
527
+ | Entry is valid JSON but violates the `MOD-017` precondition — **visibly** | Rejected promise carrying `TypeError` rather than the documented `NotFoundError`. Measured 2026-10-04: a truthy primitive namespace slice (`{"a":"hi"}`), a primitive document root (`5`), and a `null` root all rejected `TypeError` with **zero `setItem` calls** | The caller sees an error, but not one this module documents as part of its contract, and the message names an internal expression rather than the real cause | Not retryable. `clear()` recovers unconditionally because it parses nothing | src/index.js |
528
+ | Entry is valid JSON but violates the `MOD-017` precondition — **silently** | No signal at all. A read may resolve a value that was never stored; a write may resolve *and* call `setItem` without storing the value given. Measured 2026-10-04: an array namespace slice and a reserved `Object.prototype` namespace both resolved a `put` with one `setItem` and no stored result | Indistinguishable from success at the call site, so the caller cannot detect it from the adapter's result and must avoid violating the precondition rather than handle it | Not retryable and not detectable. Treat stored data as untrustworthy if any other script writes the origin's `basekey` | src/index.js |
529
+ | Namespace `__proto__` passed to `bind`, then a `put` with an **ordinary key**, with no own `__proto__` key in the stored root | **Prototype pollution**, plus a lost storage write. `put` resolves and the key is installed as an own property of the stored root's prototype — `Object.prototype` for an absent or object root, `Array.prototype` for an array root, `Number.prototype`/`String.prototype`/`Boolean.prototype` for the matching primitive root. Measured 2026-10-05 and again 2026-11-09: after `bind('__proto__').put('polluted', 'PWNED')` on empty storage, `Object.prototype` gained the own property `polluted`. A `null` root rejects `TypeError` and pollutes nothing | **Blast radius follows the polluted prototype, not “every object”.** Only values that inherit from it are affected, and the cases are asymmetric: `Object.prototype` is in every chain, so `({}).polluted`, `[].polluted`, and `(5).polluted` all read `'PWNED'`; `Array.prototype` pollution is visible to arrays only, so `[].x` is affected while `({}).x` stays `undefined`. In every case the caller gets a successful write acknowledgement | **Not recoverable through this module.** `clear()` removes the storage entry but does not undo the prototype mutation, which lasts for the realm's lifetime. A root that does contain an own `__proto__` key instead persists the write and does not pollute (`MOD-016`). See the security note under Pitfalls | src/index.js |
530
+ | Namespace `__proto__` **and** key `__proto__`, with an **object** document root that has **no own `__proto__` key** (`{}`, `{"a":{}}`), or no document | This key does not create a property: the assignment routes through the inherited `__proto__` **accessor**, so it attempts to re-parent the target instead. Under this root shape the target is `Object.prototype`, an *immutable prototype exotic object*, so the attempt cannot succeed. An object value **rejects** `TypeError` (`Immutable prototype object 'Object.prototype' cannot have their prototype set`); a string, number, or `null` value resolves with **no effect**. Measured 2026-10-05: in every case `Object.prototype` gained no own property and its prototype chain was unchanged. **Carve-out:** when the root *does* carry an own `__proto__` key, the target is that stored object rather than `Object.prototype`, so the call **resolves instead of rejecting** — measured with `{"__proto__":{"k":1}}`, an object value and a `null` value both resolved, nothing built-in was touched, and the document was left unchanged because setting a prototype adds no own property to serialize | The reject case is visible; every resolving case is a silent no-op that looks like a successful write | Not retryable. For these root shapes the outcome is a lost write rather than pollution — but that safety comes from `Object.prototype`'s immutability, or from the target being ordinary stored data, not from any guard in this module, and it does **not** extend to other roots (next row) | src/index.js |
531
+ | Namespace `__proto__` **and** key `__proto__`, with a **non-object** document root | Unspecified (`MOD-017`), and measurably more damaging than the own-property pollution above, because every built-in prototype other than `Object.prototype` is mutable. Measured 2026-10-05 as a characterization, not a contract: with root `[]`, an object value **resolved and re-parented `Array.prototype`**, after which `[].probe` read the attacker-supplied value; a `null` value **severed `Array.prototype` from `Object.prototype`**, so array instances lose inherited members such as `hasOwnProperty`; with root `5`, an object value re-parented `Number.prototype`. A string value was a no-op | Worse than an injected property: an entire caller-supplied object is spliced into the prototype chain of a built-in type, or the chain is cut. `put` resolves in each case | **Not recoverable through this module**, and not undone by `clear()`. No guard exists (`MOD-016`) | src/index.js |
532
+ | Value is not JSON-serializable, inside a valid document | Three outcomes, not one. `undefined`, `Symbol`, and functions make `put` **resolve while omitting the key**, so the next `get` rejects `NotFoundError`. `BigInt` and cyclic structures **reject** `TypeError` before `setItem`. A value whose `toJSON` throws propagates that error verbatim | The omitting cases look like successful writes and lose data silently; the rejecting cases are visible | Not retryable. Serialize to a JSON-safe form before calling `put` (`MOD-007`, `MOD-013`) | src/index.js |
533
+ | `localStorage` quota exceeded on write | Browser throws `QuotaExceededError` from `setItem`, surfacing as a rejected promise | Unhandled by this module | None implemented | src/index.js |
534
+
535
+ ## Pitfalls and constraints
536
+
537
+ - `clear()` is not namespace-scoped. It removes the whole `basekey` entry, so one binding's `clear()`
538
+ destroys every other namespace's data (`src/index.js`). That scope is the owner-confirmed intent for
539
+ logout (`MOD-010`), but it is easy to trip over from any other caller. `WebexStore.clear()` calls
540
+ `clear()` on every cached binding (webex-core storage spec), where the first call has already
541
+ removed everything.
542
+ - `README.md` contradicts the code here, describing `clear()` as clearing "all data for this
543
+ namespace". Treat this specification as authoritative; the README is registered as reference-only.
544
+ - The Promise contract has **two** synchronous-throw holes, not one, so code that relies on
545
+ `.catch()` for storage errors has a hole on both the bind path and the purge path (`MOD-015`):
546
+ - `clear()` evaluates `localStorage.removeItem(basekey)` as an argument to `Promise.resolve`
547
+ (`src/index.js`), before any promise exists. It therefore throws synchronously on a missing
548
+ `localStorage` global and on a logger missing `info`. A missing global is the one failure unique
549
+ to `clear()`: `get`/`put`/`del` reject on it because their work runs inside a
550
+ `new Promise` executor.
551
+ - `bind()` calls `options.logger.debug(...)` directly (`src/index.js`), outside any promise.
552
+ A *present* logger that lacks `debug` therefore throws `TypeError` synchronously, even though a
553
+ *missing* logger on the line above rejects. `bind().catch(...)` will not see it.
554
+
555
+ Treat `try`/`catch` around `bind()` and `clear()` as the only complete handling; `.catch()` alone
556
+ is sufficient only for `get`, `put`, and `del`.
557
+ - `MemoryStoreAdapter`, the default adapter, scopes `clear()` to its own map
558
+ (webex-core storage spec). Behavior that passes with the default adapter can therefore
559
+ destroy data with this one.
560
+ - Cost differs per method. `get` parses the entire document; `put` and `del` parse it twice and
561
+ re-serialize all of it, so writing one small key costs the size of all namespaces combined, on the
562
+ main thread. `bind` and `clear` are the cheap exceptions: `bind` touches no storage and `clear`
563
+ calls `removeItem` without parsing or serializing anything.
564
+ - Namespace isolation is not value-exact. Because `put` and `del` rewrite the whole document, a
565
+ sibling namespace's values survive only as far as a `JSON.parse` → `JSON.stringify` round trip is
566
+ lossless. A write in one namespace turns an externally written `-0` into `0` and `1e400` into
567
+ `null` in another (`INV-003`). This only bites when another script on the origin writes the entry;
568
+ values this adapter wrote have already been through `JSON.stringify`.
569
+ - The document shape and the key/namespace naming rule are a **precondition the code never checks**
570
+ (`MOD-017`). `_getRawData` hands back whatever `JSON.parse` returns and `_load` only applies
571
+ `allData[namespace] || {}`, so a conflicting shape written by any other script on the origin is
572
+ processed rather than rejected. Behavior there is unspecified: a read can resolve a value that was
573
+ never stored, a write can resolve without storing one, and neither is visible at the call site.
574
+ Only `clear()` is immune, because it parses nothing. Do not read `MOD-006`'s not-found contract or
575
+ `MOD-012`'s partitioning as holding outside the precondition, and do not rely on the characterized
576
+ examples — they are non-normative.
577
+ - Do not use `Object.prototype` property names — `toString`, `constructor`, `valueOf`,
578
+ `hasOwnProperty`, `__proto__`, and the rest — as keys or namespaces. Nothing checks own
579
+ properties, so `get('toString')` resolves an inherited function instead of rejecting
580
+ `NotFoundError`, and `bind('toString')` reads properties off that function. Under namespace
581
+ `__proto__`, `put` depends on the key and stored root: it can mutate a built-in prototype while
582
+ losing the stored write, reject, or persist under an object-valued own `__proto__` root key
583
+ (`MOD-016`). The names webex-core actually supplies avoid this, so the hazard is latent rather
584
+ than active.
585
+ - There is no cross-tab safety. Two tabs on the same origin can interleave read-modify-write cycles
586
+ and silently lose updates; no `storage` event is observed.
587
+ - Only JSON-serializable values survive. A `Date` returns as a string and a `Map` returns as `{}`,
588
+ with no warning.
589
+ - **Security — prototype pollution (CWE-1321).** Binding namespace `__proto__` and calling `put` installs
590
+ the key as an own property of **the stored document root's prototype**, whenever that root has no own
591
+ `__proto__` key (`MOD-016`). The target is not fixed: an absent or object root hits `Object.prototype`, an
592
+ array root hits `Array.prototype`, and a primitive root hits `Number.prototype`, `String.prototype`, or
593
+ `Boolean.prototype`. The injected property is then visible only on values that inherit from the
594
+ polluted prototype, which makes the cases asymmetric: `Object.prototype` is in every chain, while
595
+ `Array.prototype` pollution reaches arrays but not ordinary objects. `clear()` does not undo it. The key `__proto__` is a
596
+ second, worse class rather than an exception: it routes through the accessor and tries to **re-parent** the
597
+ target. That fails only for `Object.prototype`, which is immutable; for any other built-in prototype it
598
+ succeeds, splicing a caller-supplied object into the chain of a whole built-in type or severing the chain
599
+ outright. The apparent safety of the common object-root case is a property of `Object.prototype`, not of
600
+ this module. A `null` root rejects instead and pollutes nothing. Because the target follows
601
+ the stored document, a co-resident script that can write the origin's `basekey` also chooses which built-in
602
+ prototype is hit.
603
+ - **The vector is the namespace, not the key.** The namespace reaches `bind` from the host, and today
604
+ `webex-core` supplies fixed plugin names, so there is no known exploit path in this repository as
605
+ configured — but the module applies no guard, so a call site that derives the *namespace* from untrusted
606
+ input makes this reachable. Treat the absence of a current exploit path as a property of the callers, not
607
+ of this adapter.
608
+ - An untrusted **key** alone does not reach a built-in prototype. Measured 2026-10-05 with the fixed
609
+ namespace `credentials`: `put('__proto__', {probe: 'PWNED'})` and `put('__proto__', null)` both resolved
610
+ while leaving every built-in prototype's own properties and chain unchanged, and left the document
611
+ unchanged. Under an ordinary namespace `_load` returns the per-namespace data object, so this key sets the
612
+ prototype of that short-lived object and the write is simply lost. An untrusted key is still a correctness
613
+ problem — lost writes and the inherited-member reads in `MOD-016` — but not a pollution vector.
614
+ - A remedy is **not** a one-liner, and the obvious shortcuts do not work: switching only `_getRawData`'s
615
+ empty-document fallback to `Object.create(null)` leaves every *existing* document exposed, because
616
+ `JSON.parse('{}')` returns an ordinary `Object.prototype`-backed object; and an own-property guard in
617
+ `_load` alone still leaves inherited **key** reads in `get`. A complete fix has to cover all four paths
618
+ named in `MOD-016` — namespace lookup in `_load`, key lookup in `get`, the objects `JSON.parse` returns,
619
+ and the namespace assignment in `_save` — with tests. **This is a code defect that warrants a fix, not only
620
+ a specification entry**, and no code change has been made.
621
+ - **Security:** in the browser `webex` bundle this adapter is the `boundedAdapter`
622
+ (`src/config-storage.shim.js` in the sibling package webex), and `@persist` routes Credentials —
623
+ including `supertoken` access and refresh tokens — through it (webex-core `src/lib/storage/decorators.js`
624
+ and the `@persist('@')` decoration in `src/lib/credentials/credentials.js`). Those tokens are stored as plaintext JSON under the `webex` key, readable
625
+ by any script running on the origin. This module performs no encryption and is not a safe place
626
+ for secrets that must survive XSS.
627
+ - The module is browser-only by construction (`/* eslint-env browser */` at the top of `src/index.js`), and it
628
+ performs no feature detection before using the global.
629
+
630
+ ## Module-specific rules
631
+
632
+ - Do: keep `basekey` captured in the constructor closure. Promoting it to an instance property would
633
+ let callers mutate it after bindings exist and orphan previously written data (`src/index.js`).
634
+ - Do: keep per-binding state in the module-level `WeakMap`s rather than on the instance, so bindings
635
+ expose no enumerable own properties (`src/index.js`).
636
+ - Do: keep the browser assumption explicit with `/* eslint-env browser */` at the top of `src/index.js`; the
637
+ package-local `.eslintrc.js` roots lint at this package and extends `@webex/eslint-config-legacy`.
638
+ - Do: treat `test:browser` as the only route that can actually execute this module's behavior, and
639
+ check its reported test count — it currently completes zero tests and exits 1 because the shared
640
+ suite throws while being defined.
641
+ - Do not: add a `test:unit` case that assumes `localStorage`. The shared jest config pins
642
+ `testEnvironment: 'node'` (workspace package `packages/legacy/jest`, file `static/index.js`, reached
643
+ through `jest.config.js`), which is why the existing
644
+ suite is wrapped in `skipInNode`.
645
+ - Do not: use truthiness to decide whether a stored value exists. Only `typeof value !== 'undefined'`
646
+ preserves `0`, `false`, `null`, and `''` (`src/index.js`).
647
+ - Do not: assume `clear()` is namespace-scoped, and do not rely on `.catch()` to handle its failures.
648
+ - Do not: give `clear()` a key parameter. Its owner-confirmed contract takes none (`MOD-011`).
649
+ - Do not: change the at-rest document layout or encoding without a migration that still reads the
650
+ previous layout (`MOD-018`).
651
+
652
+ ## Export stability
653
+
654
+ | Export or entry point | Consumer | Stability | Versioning and deprecation rule | Declaration or API report |
655
+ | --------------------- | ---------- | --------- | ------------------------------- | ------------------------- |
656
+ | Default export `StorageAdapterLocalStorage` | `@webex/webex` browser bundle, `@webex/recipe-private-web-client`, authorization-browser automation fixtures | Stable published surface | Released with the monorepo's automated versioning; the constructor signature and the `bind`/`get`/`put`/`del`/`clear` shape are what host configuration binds to | `package.json` (main: dist/index.js) |
657
+ | `src/index.js` via `devMain` | Workspace consumers building from source | Internal to the workspace | Follows the same source; not an independent compatibility surface | `package.json` (devMain) |
658
+ | `dist/index.js` + `dist/index.js.map` | npm consumers | Build output, regenerated by `build:src` | Not version-controlled — the repository-root `.gitignore` ignores `dist`; emitted at publish time | `package.json` build:src |
659
+
660
+ The package ships no `.d.ts` and no API report, so `package.json` is the only machine-readable
661
+ declaration of the published surface. Any change to the constructor signature or the bound-store
662
+ method set is a breaking change for every consumer listed above.
663
+
664
+ ## Host integration and theming
665
+
666
+ - Mount or entry contract: the host receives an *instance*, not the class. Configuration assigns
667
+ `new StorageAdapterLocalStorage(basekey)` to `config.storage.boundedAdapter`
668
+ (the sibling package webex, file `src/config-storage.shim.js`, uses basekey `webex`; the sibling
669
+ package recipe-private-web-client, file `src/config.js`, uses `web-client-internal`). `WebexStore` then
670
+ reads it through the `adapter` getter and calls `adapter.bind(namespace, {logger: webex.logger})`
671
+ (webex-core `src/lib/storage/make-webex-store.js`).
672
+ - Required providers, peers, or host versions: a workspace `@webex/webex-core` supplying
673
+ `NotFoundError`, and a host logger exposing at least `debug` and `info`. The host must be a
674
+ browser context; `@webex/webex` selects this adapter only through the `browser` field substitution
675
+ in its `package.json`, so Node bundles keep `MemoryStoreAdapter`.
676
+ - Theme and design-token contract: not applicable — the module renders nothing.
677
+ - Accessibility and lifecycle obligations: none of its own. The host owns binding lifetime (one
678
+ cached binding per namespace) and decides when `clear()` runs; this module holds no teardown hook
679
+ and registers no listeners, so nothing needs disposing.
680
+
681
+ ## Key design trade-off
682
+
683
+ | Chosen trade-off | Preserved invariant or benefit | Cost or limitation | Decision evidence |
684
+ | ---------------- | ------------------------------ | ------------------ | ----------------- |
685
+ | One `localStorage` entry holds every namespace as a single JSON document | `clear()` can purge the adapter's entire dataset with one `removeItem` — the owner-confirmed logout intent (`MOD-010`) — and namespace isolation needs no key-naming scheme | Reads pay the parse cost of the whole document and writes pay parse plus serialize; a corrupt entry breaks `get`, `put`, and `del` for all namespaces at once | src/index.js |
686
+ | `basekey` captured in a constructor closure rather than stored on the instance | Immutable after construction; no caller can repoint an existing adapter and orphan its data | A fresh `Bound` class object is created per adapter instance instead of being shared on a prototype | src/index.js |
687
+ | Synchronous `localStorage` work wrapped in a Promise-returning interface | Satisfies the shared asynchronous adapter contract, letting the host treat all adapters uniformly | The asynchrony is cosmetic: the main thread blocks for the full document round trip, and `clear()`'s construction leaks the synchrony as a thrown error (`MOD-015`) | src/index.js |
688
+ | Presence tested with `typeof value !== 'undefined'` rather than truthiness | `0`, `false`, `null`, and `''` round-trip correctly instead of degrading to `NotFoundError` | A value explicitly stored as `undefined` is indistinguishable from an absent key, because JSON encoding drops it (`MOD-008`) | src/index.js |
689
+ | Per-binding state held in module-level `WeakMap`s | Bindings expose no enumerable own properties and the state is collected with them | The namespace a binding serves cannot be inspected or logged from the binding itself | src/index.js |
690
+
691
+ ## Verification
692
+
693
+ | Requirement or invariant | Test level | Positive evidence | Negative or boundary evidence | Gap |
694
+ | ------------------------ | ---------- | ----------------- | ----------------------------- | --- |
695
+ | `MOD-001` | — | none found | none found | No executing test pins the single-entry layout |
696
+ | `MOD-002`, `MOD-003` / `INV-001` | Contract (declared, not executed) | the storage-adapter-spec suite | same | Declared only; neither route runs it |
697
+ | `MOD-005` / `INV-002` | Contract (declared, not executed) | the storage-adapter-spec suite | falsey cases 0, false, null declared in the storage-adapter-spec suite | Declared only |
698
+ | `MOD-006` | Contract (declared, not executed) | — | the storage-adapter-spec suite | Declared only |
699
+ | `MOD-007` | Contract (declared, not executed) | the storage-adapter-spec suite | — | Declared only |
700
+ | `MOD-008` | — | none found | the storage-adapter-spec suite also calls del(), so it would not isolate the behavior | Wholly unverified even if the suite ran |
701
+ | `MOD-009` | Contract (declared, not executed) | the storage-adapter-spec suite | — | Declared only |
702
+ | `MOD-010` / `INV-005` | — | none found | the storage-adapter-spec suite writes and checks one key only, so namespace-wide scope is never observed | Wholly unverified; the highest-impact behavior in the module |
703
+ | `MOD-011` | — | none found | the suite calls clear() once without an argument and twice with one | Owner-confirmed contract is no parameter; the JSDoc `@param key` is stale |
704
+ | `MOD-012` / `INV-003` | — | the storage-adapter-spec suite | — | The case does not return its inner promise chain, so its assertions are never awaited; it could not fail |
705
+ | `MOD-013` / `INV-004` | — | none found | none found | No test covers non-JSON values or a corrupt document |
706
+ | `MOD-014` | — | none found | none found | Logging is unobserved |
707
+ | `MOD-015` | — | none found | none found | No test covers the missing-global path; the synchronous-throw asymmetry is unguarded |
708
+ | `MOD-018` | — | none found | none found | No test reads a document written by a previous release |
709
+ | `MOD-016` | — | none found | none found | No test uses an `Object.prototype` name as a key or namespace, so neither the inherited-value reads nor the discarded `__proto__` write would be caught; hardening would also go unnoticed |
710
+ | `MOD-017` | — | none found | none found | No test violates the precondition in either direction, so nothing would catch a change in the unspecified behavior — or confirm that validation had been added. The widest unverified area in the module after `MOD-010` |
711
+
712
+ **The decisive gap: neither of this package's own test routes executes a single case.** Measured
713
+ with Node v22.14.0:
714
+
715
+ - `yarn workspace @webex/storage-adapter-local-storage test:unit` exits 0 having **skipped all 21
716
+ cases** (2026-11-09). `test/unit/spec/storage-adapter-local-storage.js` wraps the suite in `skipInNode`
717
+ because the shared jest config pins `testEnvironment: 'node'` (workspace package
718
+ `packages/legacy/jest`, reached through `jest.config.js`) and `localStorage` does not exist there.
719
+ - `yarn workspace @webex/storage-adapter-local-storage test:browser` — the only environment where
720
+ the module can run — **completes 0 tests and exits 1** (2026-11-09). Both Firefox 159 and Chrome
721
+ Headless 156 report `ReferenceError: beforeAll is not defined`, and the runner then fails on an
722
+ unhandled promise rejection, because
723
+ the storage-adapter-spec suite calls the Jest `beforeAll` global under karma's mocha runner, so the
724
+ suite throws while being defined.
725
+ - `yarn workspace @webex/storage-adapter-local-storage test` exits 1 with
726
+ `Couldn't find a script named "test:integration"` (2026-11-09).
727
+
728
+ The unit route reports success while verifying nothing and the browser route fails before any case
729
+ runs, so no regression in any requirement above would be detected by CI. Closing this gap requires a runner change in
730
+ `@webex/storage-adapter-spec` (replacing the Jest global with a mocha-compatible hook) or a
731
+ browser-capable unit route in this package; neither is a documentation change, and both lie outside
732
+ this module's boundary. Until then this specification — not the test suite — is the only record of
733
+ the module's contract, and `coverage_status` is held at `Partial` for that reason. Generator-side
734
+ field measurement is complete (96%); promotion still waits on independent validation and a clean
735
+ drift record across the PRs that next touch this module.
736
+
737
+ ### Defects recorded, not repaired
738
+
739
+ Follow-up owed to `@webex/web-client`. Each defect below was surfaced while specifying the module
740
+ and is reported, not fixed, because repairing it changes package behavior or shared test wiring and
741
+ so falls outside a spec-only change. They are listed here, in the versioned spec.
742
+
743
+ 1. **The module has no executing automated test coverage anywhere in this package.** The unit route is
744
+ green while verifying nothing and the browser route fails before any case runs — see the three
745
+ measurements above. Closing it requires a runner
746
+ change in `@webex/storage-adapter-spec` or a browser-capable unit route here.
747
+ 2. **The aggregate `test` script is broken.** `package.json` chains `test:integration`, which this
748
+ package does not define, so the script exits 1 before reaching `test:browser`.
749
+ 3. **`README.md` misdescribes `clear()`.** It says the call clears data for the bound namespace;
750
+ `src/index.js` removes the whole `basekey`, affecting every namespace (`MOD-010`). The README is
751
+ reference-only context and is left unchanged; this specification is authoritative for behavior.
752
+ 4. **`clear()` carries a stale JSDoc `@param {string} key`** (`src/index.js`). The owner-confirmed
753
+ contract takes no parameter (`MOD-011`); correcting the JSDoc is a code change.
754
+ 5. **`WebexStore.clear()` amplifies the blast radius.** It iterates every cached binding and calls
755
+ `clear()` on each (`webex-core/src/lib/storage/make-webex-store.js`); because each call removes
756
+ the entire `basekey`, the first already destroys the others' data (`UC-004`).