Storage reads return a Result: the browser pack's getItem, key, removeItem and clear catch what Storage throws #158

Merged
sionzee merged 2 commits from storage-pack-catches into main 2026-11-24 14:07:54 +01:00
Owner

Adopter feedback (marked serious): the browser pack's getItem let Storage's exceptions through. An adopter moved unsafe(() => localStorage.getItem(key)) to the pack's getItem, as the escape-hatch policy asks, and a page with blocked storage failed to boot.

What was wrong

safe/storage.js had

export function getItem(self, ...args) {
  return self.getItem(...args) ?? undefined;   // typed Option<string>
}

and key the same. browser-api.json had Storage#getItem, #removeItem and #clear as never and #key as args. The HTML spec says only setItem throws (and the localStorage getter), but the engines do throw from the other members. I made each one fail in Playwright, on the localStorage of a removed frame:

getItem key removeItem clear setItem length
Chromium SecurityError SecurityError SecurityError SecurityError SecurityError SecurityError
Firefox Exception [NS_ERROR_FAILURE] same same same same same
WebKit null null InvalidAccessError InvalidAccessError InvalidAccessError 0

Chromium's message is "Access is denied for this document", from the same per-call access check that refuses blocked site data. Firefox also throws NS_ERROR_FILE_CORRUPTED from a damaged store; no trigger makes that one. Reduced example of the bug:

const theme = getItem(localStorage, "theme"); // typed Option<string>, but throws in Chromium/Firefox

What changed

  • browser-api.json: Storage#getItem, #key, #removeItem and #clear are now throws, each with its own error text, and setItem gains the same alternatives:
    • getItem, key: DOMException [SecurityError] @Chromium | Exception [NS_ERROR_*] @Firefox
    • removeItem, clear: also DOMException [InvalidAccessError] @WebKit
  • Regenerated with npm run generate:safe:
    • getItem and key are now Result<Option<string>, DOMError<"SecurityError"> | FirefoxException<`NS_ERROR_${string}`>>.
    • removeItem and clear are new safe versions returning Result<void, … | DOMError<"InvalidAccessError"> | …>.
    • safe-api.json and safe-ts.json follow: storage's option entry is gone, and they are now results.
    • The error types come from the same notation and guards setItem already used (DOMError, FirefoxException), so they stay consistent.
  • The checker now reports localStorage.getItem(), key(), removeItem() and clear() (also on sessionStorage and on values typed Storage) as unhandled-failure, with Use the safe version.
  • no-undefined-check-for-null no longer offers the storage safe version for getItem(k) !== undefined, because a Result compared with undefined would treat an Err as a value. It still offers Compare with null. Nothing in the crate was hard-coded to the old type: the change is all in the pack data.
  • Audit of the other wrappers in safe/ (every wrapper not returning a Result, checked against its category and spec): one more clear case. The Push API spec says PushManager#getSubscription() rejects with an AbortError ("If there is an error with subscription, … reject promise with an AbortError"). It was never and returned Promise<Option<PushSubscription>>. Now it is rejects and returns Promise<Result<Option<PushSubscription>, DOMError<"AbortError">>>. No trigger can make it fail, so it is in specOnly. The rest are never/args/returns/propagates by design: the null lookups, TreeWalker (which rethrows your filter's error), window.open/getContext returning null, and popErrorScope. The hand-written IndexedDB wrappers all return Results already.

Still reported / not changed

  • setItem's quota errors and their guards are unchanged; the new alternatives are added to its union.
  • The localStorage/sessionStorage getters throw SecurityError themselves where storage is blocked when the page loads, or in an opaque origin. getItem(localStorage, k) evaluates the getter before the safe version runs. A property read has no safe version and isn't reported, so the guide and the migrate skill now say to read the object inside unsafe(() => localStorage) where that must not crash. The adopter already does this. A safe accessor (or reporting the getter) would be a new kind of pack entry, so I left it as an open question.
  • Storage#length is a getter too (it throws in Chromium/Firefox, as in the table). Same open question.

Migrating (CHANGELOG, under Changed)

Unwrap first, then compare the Option:

  • In a function that returns a Result: const saved = q(getItem(localStorage, k)).
  • Where a refused store has a default of its own: if (isErr(saved)) return fallback;.
  • removeItem/clear values that are dropped are now must-use-result: q(...) them or void them.

Tests

  • packages/feature-browser/test/browsers/triggers.ts: a trigger per member, on a removed frame's localStorage, given this page's Storage.prototype so the error is made in this realm and the call goes through the routed safe version. npm run test:browsers: all pass.
    • Chromium 224, Firefox 210, WebKit 186 of 312 failing members verified (230 in at least one; 82 in specOnly).
    • Every verified member with a safe version returned an Err that passes its guard (159/147/126).
    • Firefox's storage triggers fail every time when run alone (run.ts firefox Storage, and a Firefox-only run of every trigger). In the three-engine run they came out "did not fail" for Firefox, so only Chromium and WebKit verified them there.
  • test/safe-api.test.ts: a stub Storage whose members throw a SecurityError (each safe version returns it as an Err that passes isDOMException), and a working stub (values, undefined for null, undefined from the writers).
  • test/types/infer.ts: the new types of getItem, removeItem, setItem and getSubscription.
  • crates/safe_ts_core/tests/fixes.rs:
    • The Option safe-version tests now use get(params, k) (URLSearchParams#get, still a plain Option).
    • New storage_reads_fail_and_their_safe_version_is_a_result: localStorage.getItem(...) !== undefined gets both no-undefined-check-for-null (with Compare with null only) and unhandled-failure. q(getItem(...)) then compared is clean. A dropped removeItem/clear/getItem is must-use-result. sessionStorage.removeItem, localStorage.clear() and storage.key(0) are reported.
  • Results:
    • npm run test:std: 456 pass, 0 fail.
    • cargo nextest run -p safe_ts_core: 364 pass.
    • npm run test:soundness: pass, with no change in the escaping classes.
    • npm run test:docs: pass (the docs examples run with the browser pack on).
    • npm run test:rewrites (full): fails on two lines that this change doesn't touch: new missing-mut hoist-const 226 → 229 and text aliased-mut call 14 → 16. misses.txt was last updated in #144, before #150 changed how mut lends, so they come from main. I left misses.txt as it is; they need their own fix.

Adopter tree

safe-ts check apps/client/{src,tests} apps/admin/{src,tests} --idiomatic, with main's browser pack against this branch's: 2381 diagnostics in both runs, with no differences. Their code already passes unsafe(() => localStorage) to the safe versions. Their two raw calls (localStorage.removeItem and localStorage.clear() in test helpers) aren't reported, because their client lists @evobug_com/safe-ts-feature-node before the browser pack in "features". As documented, the first pack that describes a global decides, and the Node pack's Storage has no failing getItem/clear. With the browser pack first, both are reported. The type change will show up for them in tsc: their getItem(...) uses treat the value as an Option.

Docs:

  • docs/guide/libraries.md: counts, the storage paragraph with an example, the getter note, the modules table.
  • docs/guide/absence.md.
  • docs/rules/no-undefined-check-for-null.md, no-null-check-for-undefined.md, must-use-result.md.
  • README, the migrate skill's references.
  • CHANGELOG.

🤖 Generated with Claude Code

Adopter feedback (marked serious): the browser pack's `getItem` let `Storage`'s exceptions through. An adopter moved `unsafe(() => localStorage.getItem(key))` to the pack's `getItem`, as the escape-hatch policy asks, and a page with blocked storage failed to boot. ## What was wrong `safe/storage.js` had ```js export function getItem(self, ...args) { return self.getItem(...args) ?? undefined; // typed Option<string> } ``` and `key` the same. `browser-api.json` had `Storage#getItem`, `#removeItem` and `#clear` as `never` and `#key` as `args`. The HTML spec says only `setItem` throws (and the `localStorage` getter), but the engines do throw from the other members. I made each one fail in Playwright, on the `localStorage` of a removed frame: | | getItem | key | removeItem | clear | setItem | `length` | |---|---|---|---|---|---|---| | Chromium | SecurityError | SecurityError | SecurityError | SecurityError | SecurityError | SecurityError | | Firefox | `Exception [NS_ERROR_FAILURE]` | same | same | same | same | same | | WebKit | `null` | `null` | InvalidAccessError | InvalidAccessError | InvalidAccessError | `0` | Chromium's message is "Access is denied for this document", from the same per-call access check that refuses blocked site data. Firefox also throws `NS_ERROR_FILE_CORRUPTED` from a damaged store; no trigger makes that one. Reduced example of the bug: ```ts const theme = getItem(localStorage, "theme"); // typed Option<string>, but throws in Chromium/Firefox ``` ## What changed - `browser-api.json`: `Storage#getItem`, `#key`, `#removeItem` and `#clear` are now `throws`, each with its own error text, and `setItem` gains the same alternatives: - getItem, key: `DOMException [SecurityError] @Chromium | Exception [NS_ERROR_*] @Firefox` - removeItem, clear: also `DOMException [InvalidAccessError] @WebKit` - Regenerated with `npm run generate:safe`: - `getItem` and `key` are now ``Result<Option<string>, DOMError<"SecurityError"> | FirefoxException<`NS_ERROR_${string}`>>``. - `removeItem` and `clear` are new safe versions returning `Result<void, … | DOMError<"InvalidAccessError"> | …>`. - `safe-api.json` and `safe-ts.json` follow: storage's `option` entry is gone, and they are now `results`. - The error types come from the same notation and guards `setItem` already used (`DOMError`, `FirefoxException`), so they stay consistent. - The checker now reports `localStorage.getItem()`, `key()`, `removeItem()` and `clear()` (also on `sessionStorage` and on values typed `Storage`) as `unhandled-failure`, with *Use the safe version*. - `no-undefined-check-for-null` no longer offers the storage safe version for `getItem(k) !== undefined`, because a `Result` compared with `undefined` would treat an `Err` as a value. It still offers *Compare with null*. Nothing in the crate was hard-coded to the old type: the change is all in the pack data. - **Audit of the other wrappers in `safe/`** (every wrapper not returning a `Result`, checked against its category and spec): one more clear case. The Push API spec says `PushManager#getSubscription()` rejects with an `AbortError` ("If there is an error with subscription, … reject promise with an AbortError"). It was `never` and returned `Promise<Option<PushSubscription>>`. Now it is `rejects` and returns `Promise<Result<Option<PushSubscription>, DOMError<"AbortError">>>`. No trigger can make it fail, so it is in `specOnly`. The rest are `never`/`args`/`returns`/`propagates` by design: the null lookups, `TreeWalker` (which rethrows your filter's error), `window.open`/`getContext` returning `null`, and `popErrorScope`. The hand-written IndexedDB wrappers all return `Result`s already. ## Still reported / not changed - `setItem`'s quota errors and their guards are unchanged; the new alternatives are added to its union. - **The `localStorage`/`sessionStorage` getters throw `SecurityError` themselves** where storage is blocked when the page loads, or in an opaque origin. `getItem(localStorage, k)` evaluates the getter before the safe version runs. A property read has no safe version and isn't reported, so the guide and the migrate skill now say to read the object inside `unsafe(() => localStorage)` where that must not crash. The adopter already does this. A safe accessor (or reporting the getter) would be a new kind of pack entry, so I left it as an open question. - `Storage#length` is a getter too (it throws in Chromium/Firefox, as in the table). Same open question. ## Migrating (CHANGELOG, under Changed) Unwrap first, then compare the `Option`: - In a function that returns a `Result`: `const saved = q(getItem(localStorage, k))`. - Where a refused store has a default of its own: `if (isErr(saved)) return fallback;`. - `removeItem`/`clear` values that are dropped are now `must-use-result`: `q(...)` them or `void` them. ## Tests - `packages/feature-browser/test/browsers/triggers.ts`: a trigger per member, on a removed frame's `localStorage`, given this page's `Storage.prototype` so the error is made in this realm and the call goes through the routed safe version. `npm run test:browsers`: all pass. - Chromium 224, Firefox 210, WebKit 186 of 312 failing members verified (230 in at least one; 82 in `specOnly`). - Every verified member with a safe version returned an `Err` that passes its guard (159/147/126). - Firefox's storage triggers fail every time when run alone (`run.ts firefox Storage`, and a Firefox-only run of every trigger). In the three-engine run they came out "did not fail" for Firefox, so only Chromium and WebKit verified them there. - `test/safe-api.test.ts`: a stub `Storage` whose members throw a `SecurityError` (each safe version returns it as an `Err` that passes `isDOMException`), and a working stub (values, `undefined` for `null`, `undefined` from the writers). - `test/types/infer.ts`: the new types of `getItem`, `removeItem`, `setItem` and `getSubscription`. - `crates/safe_ts_core/tests/fixes.rs`: - The `Option` safe-version tests now use `get(params, k)` (`URLSearchParams#get`, still a plain `Option`). - New `storage_reads_fail_and_their_safe_version_is_a_result`: `localStorage.getItem(...) !== undefined` gets both `no-undefined-check-for-null` (with *Compare with null* only) and `unhandled-failure`. `q(getItem(...))` then compared is clean. A dropped `removeItem`/`clear`/`getItem` is `must-use-result`. `sessionStorage.removeItem`, `localStorage.clear()` and `storage.key(0)` are reported. - Results: - `npm run test:std`: 456 pass, 0 fail. - `cargo nextest run -p safe_ts_core`: 364 pass. - `npm run test:soundness`: pass, with no change in the escaping classes. - `npm run test:docs`: pass (the docs examples run with the browser pack on). - `npm run test:rewrites` (full): fails on two lines that this change doesn't touch: `new missing-mut hoist-const` 226 → 229 and `text aliased-mut call` 14 → 16. `misses.txt` was last updated in #144, before #150 changed how `mut` lends, so they come from main. I left `misses.txt` as it is; they need their own fix. ## Adopter tree `safe-ts check apps/client/{src,tests} apps/admin/{src,tests} --idiomatic`, with main's browser pack against this branch's: 2381 diagnostics in both runs, with no differences. Their code already passes `unsafe(() => localStorage)` to the safe versions. Their two raw calls (`localStorage.removeItem` and `localStorage.clear()` in test helpers) aren't reported, because their client lists `@evobug_com/safe-ts-feature-node` before the browser pack in `"features"`. As documented, the first pack that describes a global decides, and the Node pack's `Storage` has no failing `getItem`/`clear`. With the browser pack first, both are reported. The type change will show up for them in `tsc`: their `getItem(...)` uses treat the value as an `Option`. Docs: - `docs/guide/libraries.md`: counts, the storage paragraph with an example, the getter note, the modules table. - `docs/guide/absence.md`. - `docs/rules/no-undefined-check-for-null.md`, `no-null-check-for-undefined.md`, `must-use-result.md`. - README, the migrate skill's references. - CHANGELOG. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Storage reads return a Result: getItem, key, removeItem and clear catch what the browser throws
Some checks failed
Benchmarks / bench (pull_request) Successful in 4m28s
Tests / test (pull_request) Failing after 14m24s
f3ea58e9ee
Chromium throws SecurityError from every Storage member of a store it no longer lets the page
use, WebKit InvalidAccessError from the writers, Firefox NS_ERROR_* (also NS_ERROR_FILE_CORRUPTED
from a damaged store). The browser pack's getItem and key returned a plain Option and let those
through, so code moved to them from unsafe(...) crashed on a page with blocked storage.

browser-api.json now lists getItem, key, removeItem and clear as throws with their errors per
engine (triggered in Playwright on a removed frame's localStorage); the regenerated safe
versions return Result<Option<string>, E> and Result<void, E>, and setItem's error gains the
same alternatives. PushManager#getSubscription, which the Push API rejects with an AbortError,
is now a rejecting member with a Result (specOnly). Docs, the migrate skill and CHANGELOG
(Changed, with how callers migrate) follow; the localStorage getter itself still throws and has
no safe version, which the guide now says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Merge main into storage-pack-catches
Some checks failed
Tests / test (pull_request) Has been cancelled
Benchmarks / bench (pull_request) Has been cancelled
df127f37c0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch storage-pack-catches 2026-11-24 14:07:54 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!158
No description provided.