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:
DongHyeonka
2026-09-24 13:37:56 +09:00
co-authored by Claude Opus 5.5
parent 9e70ae2d6c
commit ec71b0b0a2
12 changed files with 330 additions and 175 deletions
@@ -30,6 +30,7 @@ Web Push는 현재 `AVAILABLE_NOT_COMPOSED`이고 제품 선택도 `NOT_SELECTED
| `service-worker-protocol.ts` | page-worker strict message codec/nonce | CONTRACT_GAP | `SW-06`, `SW-10` |
| `service-worker-removal.ts` | exact registration/cache ownership cleanup | VERIFIED_DEFECT | `SW-03` |
| `service-worker-static-assets.ts` | static manifest/install/cache policy | KEEP/REFACTOR | `SW-01`, `SW-05`, `SW-09` |
| `web-push/codec-primitives.ts` | 공유 검증 primitive(base64url decode, opaque id, authority, exact record) | KEEP | Q-6.6-12에서 4개 파일의 복사본을 합침. 복사본이 다르던 곳은 더 엄격한 쪽을 유지 |
| `web-push/index.ts` | public exports | KEEP | product selection 전 surface 확대 금지 |
| `web-push/notification-registry.ts` | closed copy/route registry | KEEP | arbitrary copy/URL 허용 금지 |
| `web-push/push-association-fence-store.ts` | durable authority state machine | VERIFIED_DEFECT | `WP-01`, `WP-02` |
+13 -12
View File
@@ -137,17 +137,18 @@
| 127 | `src/adapters/telemetry/best-effort-telemetry.ts` | [Network/state](./01-network-and-state.md) |
| 128 | `src/adapters/telemetry/feature-telemetry.ts` | [Network/state](./01-network-and-state.md) |
| 129 | `src/adapters/telemetry/index.ts` | [Network/state](./01-network-and-state.md) |
| 130 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 131 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 132 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 133 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 134 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 135 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 136 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 137 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 138 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 139 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 140 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 130 | `src/adapters/web-push/codec-primitives.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 131 | `src/adapters/web-push/inbound/notification-click-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 132 | `src/adapters/web-push/inbound/push-event-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 133 | `src/adapters/web-push/index.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 134 | `src/adapters/web-push/notification-registry.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 135 | `src/adapters/web-push/push-association-fence-store.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 136 | `src/adapters/web-push/push-codec.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 137 | `src/adapters/web-push/push-registration-gateway.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 138 | `src/adapters/web-push/push-subscription-adapter.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 139 | `src/adapters/web-push/runtime-support.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 140 | `src/adapters/web-push/service-worker-runtime.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
| 141 | `src/adapters/web-push/service-worker-scope-host.ts` | [Worker/push](./05-service-worker-and-web-push.md) |
합계: **140/140**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
합계: **141/141**. 새 adapter 파일이 추가되면 이 ledger와 해당 상세 리뷰 inventory를 같은 변경에서 갱신한다.
@@ -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.
});
+101
View File
@@ -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" &&
+1 -20
View File
@@ -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);
}
+1
View File
@@ -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 } : {}),
});
+37
View File
@@ -4,6 +4,7 @@ import { createServiceWorkerPageController } from "../../src/adapters/service-wo
import { createServiceWorkerRuntime } from "../../src/adapters/service-worker/service-worker-lifecycle.ts";
import { createServiceWorkerMessage } from "../../src/adapters/service-worker/service-worker-protocol.ts";
import { installStaticAssets } from "../../src/adapters/service-worker/service-worker-static-assets.ts";
import { createServiceWorkerRuntimeHost } from "../../src/bootstrap/register-service-worker.ts";
import {
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
@@ -1205,6 +1206,42 @@ describe("service worker static asset install", () => {
await controller.stop();
});
it("skips update checks while the injected host document is hidden (Q-6.6-12)", async () => {
vi.useFakeTimers();
try {
const browser = pageContainer({ controlled: true });
const hostDocument = { visibilityState: "hidden" as DocumentVisibilityState };
const host = createServiceWorkerRuntimeHost({
capabilities: {
serviceWorker: {
mode: "ACTIVE",
scriptPath: SERVICE_WORKER_SCRIPT_PATH,
handlers: [],
},
serviceWorkerDisabledCleanup: false,
} as never,
routerBasePath: "/",
buildId: "page-build",
host: {
location: { origin: ORIGIN },
navigator: { serviceWorker: browser.container },
document: hostDocument,
},
});
await expect(host?.start()).resolves.toMatchObject({ kind: "ACTIVE" });
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs);
expect(browser.registration.update).not.toHaveBeenCalled();
hostDocument.visibilityState = "visible";
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs);
expect(browser.registration.update).toHaveBeenCalledOnce();
await host?.stop();
} finally {
vi.useRealTimers();
}
});
it("announces an update that finished installing as waiting (R-6.3)", async () => {
const browser = pageContainer({ controlled: true });
const controller = pageController(browser.container);
+140
View File
@@ -18,6 +18,13 @@ import {
createWebPushRegistrationGateway,
type WebPushRegistrationExecutor,
} from "../../src/adapters/web-push/push-registration-gateway.ts";
import { createPushAssociationFenceStore } from "../../src/adapters/web-push/push-association-fence-store.ts";
import { createWebPushSubscriptionAdapter } from "../../src/adapters/web-push/push-subscription-adapter.ts";
import { createFakePushControlStoreDependencies } from "../helpers/fake-push-control-repository.ts";
import {
base64UrlDecode,
base64UrlEncode,
} from "../../src/adapters/web-push/codec-primitives.ts";
const now = Date.parse("2026-07-28T00:00:00.000Z");
@@ -253,3 +260,136 @@ describe("Web Push contracts", () => {
});
});
});
/**
* Q-6.6-12. The web-push files each carried their own base64url decoder,
* opaque-id pattern, authority check and exact-record check. These pin what
* every caller observes, so merging them into one module cannot loosen any.
*/
describe("web-push codec primitives as seen by their callers (Q-6.6-12)", () => {
const authority = {
fenceGeneration: "fence_01",
sessionBindingEpoch: "session_01",
releaseEpoch: "release_01",
};
const p256dhBytes = new Uint8Array(65);
p256dhBytes[0] = 4;
const material = {
endpoint: "https://push.example.test/subscription/opaque",
p256dh: Buffer.from(p256dhBytes).toString("base64url"),
auth: Buffer.from(new Uint8Array(16)).toString("base64url"),
expirationTime: null,
};
/** 87 chars carry 2 spare bits and 22 chars carry 4; they must be zero. */
const withSpareBitSet = (encoded: string) =>
`${encoded.slice(0, -1)}${encoded.endsWith("A") ? "B" : "A"}`;
const registered: WebPushRegistrationExecutor = {
async execute() {
return webPushSuccess({
protocol: WEB_PUSH_PROTOCOLS.registration,
associationEpoch: "association_01",
sessionBindingEpoch: "session_01",
});
},
};
it("rejects subscription keys whose spare base64url bits are set", async () => {
const gateway = createWebPushRegistrationGateway(registered);
for (const broken of [
{ ...material, p256dh: withSpareBitSet(material.p256dh) },
{ ...material, auth: withSpareBitSet(material.auth) },
]) {
expect(
await gateway.register({
material: broken,
authority,
idempotencyKey: "idempotency_01",
}),
).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
}
});
it("rejects a VAPID key whose spare base64url bits are set", () => {
const key = new Uint8Array(65);
key[0] = 4;
const valid = Buffer.from(key).toString("base64url");
expect(() =>
createWebPushSubscriptionAdapter({
vapidPublicKey: withSpareBitSet(valid),
} as never),
).toThrow(TypeError);
});
it("rejects a null authority as invalid input in the fence store", async () => {
const store = createPushAssociationFenceStore(
createFakePushControlStoreDependencies(),
);
expect(
await store.prepare({
authority: null as never,
updatedAt: "2026-07-28T00:00:00.000Z",
}),
).toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
});
it("rejects a null authority as invalid input in the gateway", async () => {
const gateway = createWebPushRegistrationGateway(registered);
await expect(
gateway.register({
material,
authority: null as never,
idempotencyKey: "idempotency_01",
}),
).resolves.toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
await expect(
gateway.reconcile({ material, authority: null as never }),
).resolves.toMatchObject({ ok: false, error: { code: "INVALID_INPUT" } });
});
it("rejects backend answers that are arrays or carry extra keys", async () => {
for (const answer of [
[WEB_PUSH_PROTOCOLS.revoke, "REVOKED"],
{ protocol: WEB_PUSH_PROTOCOLS.revoke, state: "REVOKED", extra: 1 },
]) {
const gateway = createWebPushRegistrationGateway({
execute: async () => webPushSuccess(answer),
});
expect(
await gateway.revoke({ associationEpoch: "association_01" }),
).toMatchObject({ ok: false, error: { code: "CONTRACT_REJECTED" } });
}
});
it("gives every accepted base64url string exactly one decoding", () => {
expect([...base64UrlDecode("AQID")!]).toEqual([1, 2, 3]);
expect([...base64UrlDecode("AQ")!]).toEqual([1]);
expect(base64UrlDecode("")?.byteLength).toBe(0);
// "AQIDA": a lone trailing character cannot finish a byte. The window
// adapter's old copy accepted it because its spare bits were zero.
for (const invalid of ["A", "AQIDA", "AR", "AQ==", "AQ+/", null, 7]) {
expect(base64UrlDecode(invalid), String(invalid)).toBeNull();
}
});
it("encodes base64url exactly like Node and round-trips through the decoder", () => {
for (let length = 0; length <= 66; length += 1) {
const bytes = Uint8Array.from({ length }, (_, index) => (index * 37 + 11) & 255);
const encoded = base64UrlEncode(bytes);
expect(encoded).toBe(Buffer.from(bytes).toString("base64url"));
expect([...base64UrlDecode(encoded)!]).toEqual([...bytes]);
}
});
it("rejects opaque ids outside the shared pattern", async () => {
const gateway = createWebPushRegistrationGateway(registered);
for (const associationEpoch of ["", "-leading", "a b", "a".repeat(129)]) {
expect(await gateway.revoke({ associationEpoch })).toMatchObject({
ok: false,
error: { code: "INVALID_INPUT" },
});
}
expect(
decodeWebPushHint(encoded(hint({ notificationId: "a b" })), now),
).toMatchObject({ ok: false });
});
});