refactor(web-push): merge codec primitives into one module and inject the page document (Q-6.6-12)
web-push/codec-primitives.ts now owns OPAQUE_ID/validOpaqueId, isRecord,
hasExactKeys, exactRecord, validAuthority, base64UrlDecode and (to share the
alphabet) base64UrlEncode. push-codec,
push-registration-gateway, push-association-fence-store,
push-subscription-adapter and service-worker-runtime import them instead of
carrying their own copies (the fence store's control/association key checks
now use exactRecord/hasExactKeys with the same key lists). The duplicate-key
JSON scan in push-codec.ts is untouched (realtime lane, T76).
Where the copies differed, the stricter validated behavior is kept:
- validAuthority: the fence store's null guard. The gateway's copy threw a
TypeError for a null authority, so register()/reconcile() rejected instead
of returning INVALID_INPUT; they now return INVALID_INPUT (the only change a
caller can observe; characterization test was RED before the merge).
Non-record values (arrays) are also refused.
- base64UrlDecode: the gateway's decoder, which refuses a lone trailing
character (length % 4 == 1). The window adapter's copy accepted it when the
spare bits were zero; its only caller pre-checks an 87-char VAPID key, so
that difference was not reachable. `>>` vs `>>>` gave identical bytes.
- OPAQUE_ID, isRecord/hasExactKeys/exactRecord were already identical.
Page controller: PageControllerDependencies gains optional `document`; the
6-hour update check reads it (falling back to the global document), and
bootstrap/register-service-worker.ts now passes host.document through.
New adapter file: INVENTORY.md row 126 + renumber, total 137/137; detail row in
docs/reviews/adapters/05-service-worker-and-web-push.md.
Verified: characterization tests pinned the caller-visible behavior of every
copy before the merge (spare-bit keys, VAPID key, null authority in fence
store and gateway, array/extra-key backend answers, opaque ids); all pass
after, plus direct base64UrlDecode tests and an encode round-trip against
Node's base64url for lengths 0..66. Document injection test was RED
(update() ran while the injected document was hidden), green after. Gates:
check:architecture, types app/test/service-worker, lint, test:unit (only
pre-existing removal-fixture failure), test:component,
check:realtime-boundaries, check:adapter-inventory.
Realtime reference bundle (check:optional-recipes:source, already over budget
at b953142): 40139 -> 40097 gzip bytes after T89+T90.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
9e70ae2d6c
commit
ec71b0b0a2
@@ -38,6 +38,8 @@ export type PageControllerDependencies = Readonly<{
|
||||
buildId: string;
|
||||
container?: ServiceWorkerContainer;
|
||||
caches?: CacheStorage;
|
||||
/** Q-6.6-12. The host page; without it the global `document`, if any. */
|
||||
document?: Pick<Document, "visibilityState">;
|
||||
/** §17.10. Any blocker returning true rejects automatic activation. */
|
||||
blockers?: readonly ActivationBlocker[];
|
||||
now?: () => number;
|
||||
@@ -349,10 +351,11 @@ export function createServiceWorkerPageController(
|
||||
function scheduleUpdateChecks(): void {
|
||||
// §17.14. At most one check per 6 hours, and none while the page is hidden.
|
||||
if (updateTimer) return;
|
||||
const page =
|
||||
dependencies.document ??
|
||||
(typeof document === "undefined" ? undefined : document);
|
||||
updateTimer = setInterval(() => {
|
||||
if (typeof document !== "undefined" && document.visibilityState === "hidden") {
|
||||
return;
|
||||
}
|
||||
if (page?.visibilityState === "hidden") return;
|
||||
void registration?.update().catch(() => {
|
||||
// A failed update check never fails a product flow.
|
||||
});
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { PushAuthoritySnapshot } from "../../contracts/web-push.ts";
|
||||
|
||||
/**
|
||||
* Q-6.6-12. The validation primitives every web-push codec shares. Each file
|
||||
* used to carry its own copy, and the copies had drifted: one authority check
|
||||
* threw on `null`, one base64url decoder accepted a lone trailing character.
|
||||
* Where they differed, the stricter behavior is the one kept here.
|
||||
*/
|
||||
|
||||
/** Opaque ids: bounded, ASCII, starting with an alphanumeric. */
|
||||
export const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
||||
|
||||
export function validOpaqueId(value: unknown): value is string {
|
||||
return typeof value === "string" && OPAQUE_ID.test(value);
|
||||
}
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** `expected` must be sorted; the record's own keys must equal it exactly. */
|
||||
export function hasExactKeys(
|
||||
value: Record<string, unknown>,
|
||||
expected: readonly string[],
|
||||
): boolean {
|
||||
const actual = Object.keys(value).sort();
|
||||
return (
|
||||
actual.length === expected.length &&
|
||||
actual.every((key, index) => key === expected[index])
|
||||
);
|
||||
}
|
||||
|
||||
export function exactRecord(
|
||||
value: unknown,
|
||||
expected: readonly string[],
|
||||
): value is Record<string, unknown> {
|
||||
return isRecord(value) && hasExactKeys(value, expected);
|
||||
}
|
||||
|
||||
/** A missing or non-object authority is invalid input, never a TypeError. */
|
||||
export function validAuthority(value: unknown): value is PushAuthoritySnapshot {
|
||||
return (
|
||||
isRecord(value) &&
|
||||
validOpaqueId(value.fenceGeneration) &&
|
||||
validOpaqueId(value.sessionBindingEpoch) &&
|
||||
validOpaqueId(value.releaseEpoch)
|
||||
);
|
||||
}
|
||||
|
||||
const BASE64URL_ALPHABET =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
|
||||
/**
|
||||
* Unpadded base64url. Rejects non-strings, characters outside the alphabet,
|
||||
* a lone trailing character (6 bits cannot finish a byte) and non-zero spare
|
||||
* bits, so every accepted string has exactly one decoding.
|
||||
*/
|
||||
export function base64UrlDecode(value: unknown): Uint8Array<ArrayBuffer> | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const output = new Uint8Array(
|
||||
new ArrayBuffer(Math.floor((value.length * 6) / 8)),
|
||||
);
|
||||
let accumulator = 0;
|
||||
let bitCount = 0;
|
||||
let outputIndex = 0;
|
||||
for (const character of value) {
|
||||
const digit = BASE64URL_ALPHABET.indexOf(character);
|
||||
if (digit < 0) return null;
|
||||
accumulator = (accumulator << 6) | digit;
|
||||
bitCount += 6;
|
||||
if (bitCount >= 8) {
|
||||
bitCount -= 8;
|
||||
output[outputIndex] = (accumulator >>> bitCount) & 0xff;
|
||||
outputIndex += 1;
|
||||
}
|
||||
}
|
||||
return bitCount < 6 &&
|
||||
outputIndex === output.length &&
|
||||
(accumulator & ((1 << bitCount) - 1)) === 0
|
||||
? output
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Unpadded base64url with zero spare bits: the inverse of the decoder. */
|
||||
export function base64UrlEncode(bytes: Uint8Array): string {
|
||||
let output = "";
|
||||
let accumulator = 0;
|
||||
let bitCount = 0;
|
||||
for (const byte of bytes) {
|
||||
accumulator = (accumulator << 8) | byte;
|
||||
bitCount += 8;
|
||||
while (bitCount >= 6) {
|
||||
bitCount -= 6;
|
||||
output += BASE64URL_ALPHABET[(accumulator >>> bitCount) & 63];
|
||||
}
|
||||
}
|
||||
if (bitCount > 0) {
|
||||
output += BASE64URL_ALPHABET[(accumulator << (6 - bitCount)) & 63];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
@@ -10,13 +10,27 @@ import {
|
||||
type WebPushOperation,
|
||||
type WebPushResult,
|
||||
} from "../../contracts/web-push.ts";
|
||||
import {
|
||||
exactRecord,
|
||||
hasExactKeys,
|
||||
isRecord,
|
||||
validAuthority,
|
||||
validOpaqueId,
|
||||
} from "./codec-primitives.ts";
|
||||
import {
|
||||
withAbortableDeadline,
|
||||
type TimeoutScheduler,
|
||||
} from "./runtime-support.ts";
|
||||
|
||||
const CONTROL_KEY = "push-control-v1";
|
||||
const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
||||
const CONTROL_KEYS = Object.freeze([
|
||||
"association",
|
||||
"fenceGeneration",
|
||||
"protocol",
|
||||
"releaseEpoch",
|
||||
"sessionBindingEpoch",
|
||||
"updatedAt",
|
||||
]);
|
||||
const ISO_INSTANT =
|
||||
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u;
|
||||
|
||||
@@ -621,13 +635,9 @@ function controlSnapshot(value: PushControlV1): PushControlV1 {
|
||||
}
|
||||
|
||||
function decodeControl(value: unknown): PushControlV1 | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const keys = Object.keys(record).sort();
|
||||
if (!exactRecord(value, CONTROL_KEYS)) return null;
|
||||
const record = value;
|
||||
if (
|
||||
keys.length !== 6 ||
|
||||
keys.join("|") !==
|
||||
"association|fenceGeneration|protocol|releaseEpoch|sessionBindingEpoch|updatedAt" ||
|
||||
record.protocol !== WEB_PUSH_PROTOCOLS.control ||
|
||||
!validOpaqueId(record.fenceGeneration) ||
|
||||
!validOpaqueId(record.sessionBindingEpoch) ||
|
||||
@@ -650,29 +660,12 @@ function decodeControl(value: unknown): PushControlV1 | null {
|
||||
function validAssociation(
|
||||
value: unknown,
|
||||
): value is PushControlAssociationV1 {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
const keys = Object.keys(record).sort();
|
||||
if (record.state === "UNASSOCIATED") {
|
||||
return keys.length === 1 && keys[0] === "state";
|
||||
}
|
||||
if (!isRecord(value)) return false;
|
||||
if (value.state === "UNASSOCIATED") return hasExactKeys(value, ["state"]);
|
||||
return (
|
||||
(record.state === "ACTIVE" || record.state === "REVOKED") &&
|
||||
keys.length === 2 &&
|
||||
keys[0] === "associationEpoch" &&
|
||||
keys[1] === "state" &&
|
||||
validOpaqueId(record.associationEpoch)
|
||||
);
|
||||
}
|
||||
|
||||
function validAuthority(
|
||||
value: PushAuthoritySnapshot,
|
||||
): value is PushAuthoritySnapshot {
|
||||
return (
|
||||
Boolean(value) &&
|
||||
validOpaqueId(value.fenceGeneration) &&
|
||||
validOpaqueId(value.sessionBindingEpoch) &&
|
||||
validOpaqueId(value.releaseEpoch)
|
||||
(value.state === "ACTIVE" || value.state === "REVOKED") &&
|
||||
hasExactKeys(value, ["associationEpoch", "state"]) &&
|
||||
validOpaqueId(value.associationEpoch)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -720,10 +713,6 @@ function validIdempotencyKey(value: unknown): value is string {
|
||||
);
|
||||
}
|
||||
|
||||
function validOpaqueId(value: unknown): value is string {
|
||||
return typeof value === "string" && OPAQUE_ID.test(value);
|
||||
}
|
||||
|
||||
function validRevision(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === "number" &&
|
||||
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
type WebPushHintV1,
|
||||
type WebPushResult,
|
||||
} from "../../contracts/web-push.ts";
|
||||
import { hasExactKeys, isRecord, validOpaqueId } from "./codec-primitives.ts";
|
||||
|
||||
const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
||||
const REGISTRY_ID = /^[A-Z][A-Z0-9_]{0,63}$/u;
|
||||
const ISO_INSTANT =
|
||||
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u;
|
||||
@@ -31,25 +31,6 @@ const CLICK_KEYS = Object.freeze([
|
||||
"routeIntent",
|
||||
] as const);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function hasExactKeys(
|
||||
value: Record<string, unknown>,
|
||||
expected: readonly string[],
|
||||
): boolean {
|
||||
const actual = Object.keys(value).sort();
|
||||
return (
|
||||
actual.length === expected.length &&
|
||||
actual.every((key, index) => key === expected[index])
|
||||
);
|
||||
}
|
||||
|
||||
function validOpaqueId(value: unknown): value is string {
|
||||
return typeof value === "string" && OPAQUE_ID.test(value);
|
||||
}
|
||||
|
||||
function instant(value: unknown): number | null {
|
||||
if (typeof value !== "string" || !ISO_INSTANT.test(value)) return null;
|
||||
const parsed = Date.parse(value);
|
||||
|
||||
@@ -5,8 +5,12 @@ import {
|
||||
type PushAuthoritySnapshot,
|
||||
type WebPushResult,
|
||||
} from "../../contracts/web-push.ts";
|
||||
|
||||
const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
|
||||
import {
|
||||
base64UrlDecode,
|
||||
exactRecord,
|
||||
validAuthority,
|
||||
validOpaqueId,
|
||||
} from "./codec-primitives.ts";
|
||||
|
||||
export const WEB_PUSH_REGISTRATION_OPERATIONS = Object.freeze({
|
||||
register: "REGISTER_WEB_PUSH_SUBSCRIPTION",
|
||||
@@ -228,30 +232,6 @@ function decodeRevoke(
|
||||
: null;
|
||||
}
|
||||
|
||||
function exactRecord(
|
||||
value: unknown,
|
||||
keys: readonly string[],
|
||||
): value is Record<string, unknown> {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
||||
const actual = Object.keys(value).sort();
|
||||
return (
|
||||
actual.length === keys.length &&
|
||||
actual.every((key, index) => key === keys[index])
|
||||
);
|
||||
}
|
||||
|
||||
function validOpaqueId(value: unknown): value is string {
|
||||
return typeof value === "string" && OPAQUE_ID.test(value);
|
||||
}
|
||||
|
||||
function validAuthority(value: PushAuthoritySnapshot): boolean {
|
||||
return (
|
||||
validOpaqueId(value.fenceGeneration) &&
|
||||
validOpaqueId(value.sessionBindingEpoch) &&
|
||||
validOpaqueId(value.releaseEpoch)
|
||||
);
|
||||
}
|
||||
|
||||
function validMaterial(value: NativePushSubscriptionMaterial): boolean {
|
||||
const p256dh = base64UrlDecode(value?.p256dh);
|
||||
const auth = base64UrlDecode(value?.auth);
|
||||
@@ -294,32 +274,3 @@ function snapshotMaterial(
|
||||
expirationTime: value.expirationTime,
|
||||
});
|
||||
}
|
||||
|
||||
function base64UrlDecode(value: unknown): Uint8Array | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const alphabet =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
const output = new Uint8Array(
|
||||
new ArrayBuffer(Math.floor((value.length * 6) / 8)),
|
||||
);
|
||||
let accumulator = 0;
|
||||
let bitCount = 0;
|
||||
let outputIndex = 0;
|
||||
for (const character of value) {
|
||||
const digit = alphabet.indexOf(character);
|
||||
if (digit < 0) return null;
|
||||
accumulator = (accumulator << 6) | digit;
|
||||
bitCount += 6;
|
||||
if (bitCount >= 8) {
|
||||
bitCount -= 8;
|
||||
output[outputIndex] = (accumulator >> bitCount) & 0xff;
|
||||
outputIndex += 1;
|
||||
}
|
||||
}
|
||||
return bitCount < 6 &&
|
||||
outputIndex === output.length &&
|
||||
(bitCount === 0 ||
|
||||
(accumulator & ((1 << bitCount) - 1)) === 0)
|
||||
? output
|
||||
: null;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type WebPushResult,
|
||||
type WebPushUnavailableReason,
|
||||
} from "../../contracts/web-push.ts";
|
||||
import { base64UrlDecode, base64UrlEncode } from "./codec-primitives.ts";
|
||||
import type {
|
||||
PushAssociationFenceStore,
|
||||
PushControlReceipt,
|
||||
@@ -1112,51 +1113,3 @@ function decodeVapidPublicKey(
|
||||
const decoded = base64UrlDecode(value);
|
||||
return decoded?.byteLength === 65 && decoded[0] === 4 ? decoded : null;
|
||||
}
|
||||
|
||||
function base64UrlDecode(value: string): Uint8Array<ArrayBuffer> | null {
|
||||
const alphabet =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
const outputLength = Math.floor((value.length * 6) / 8);
|
||||
const output = new Uint8Array(new ArrayBuffer(outputLength));
|
||||
let accumulator = 0;
|
||||
let bitCount = 0;
|
||||
let outputIndex = 0;
|
||||
for (const character of value) {
|
||||
const digit = alphabet.indexOf(character);
|
||||
if (digit < 0) return null;
|
||||
accumulator = (accumulator << 6) | digit;
|
||||
bitCount += 6;
|
||||
if (bitCount >= 8) {
|
||||
bitCount -= 8;
|
||||
output[outputIndex] = (accumulator >>> bitCount) & 0xff;
|
||||
outputIndex += 1;
|
||||
}
|
||||
}
|
||||
if (
|
||||
outputIndex !== outputLength ||
|
||||
(bitCount > 0 && (accumulator & ((1 << bitCount) - 1)) !== 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function base64UrlEncode(bytes: Uint8Array): string {
|
||||
const alphabet =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
||||
let output = "";
|
||||
let accumulator = 0;
|
||||
let bitCount = 0;
|
||||
for (const byte of bytes) {
|
||||
accumulator = (accumulator << 8) | byte;
|
||||
bitCount += 8;
|
||||
while (bitCount >= 6) {
|
||||
bitCount -= 6;
|
||||
output += alphabet[(accumulator >>> bitCount) & 63];
|
||||
}
|
||||
}
|
||||
if (bitCount > 0) {
|
||||
output += alphabet[(accumulator << (6 - bitCount)) & 63];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
webPushSuccess,
|
||||
type WebPushObserver,
|
||||
} from "../../contracts/web-push.ts";
|
||||
import { isRecord } from "./codec-primitives.ts";
|
||||
import type { PushAssociationFenceStore } from "./push-association-fence-store.ts";
|
||||
import {
|
||||
createPushEventAdapter,
|
||||
@@ -290,7 +291,3 @@ function windowClientFacade(value: unknown): WindowClientFacade | null {
|
||||
}
|
||||
return value as WindowClientFacade;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
@@ -51,6 +51,7 @@ export function createServiceWorkerRuntimeHost(
|
||||
buildId: input.buildId,
|
||||
...(container ? { container } : {}),
|
||||
...(host?.caches ? { caches: host.caches } : {}),
|
||||
...(host?.document ? { document: host.document } : {}),
|
||||
...(input.blockers ? { blockers: input.blockers } : {}),
|
||||
...(input.observe ? { observe: input.observe } : {}),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user