After an account switch without logout the new session could not name the stored authority, so enable and reconcile stayed STALE_AUTHORITY. The port gains revokeForeign: it rotates a fence another fence generation holds and revokes its association, and leaves the caller's own fence alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1204 lines
37 KiB
TypeScript
1204 lines
37 KiB
TypeScript
import type { WebPushControlPort } from "../../application/ports/out/web-push-control.ts";
|
|
import {
|
|
webPushCountBucket,
|
|
WEB_PUSH_LIMITS,
|
|
samePushAuthority,
|
|
webPushFailure,
|
|
webPushSuccess,
|
|
type PushAuthoritySnapshot,
|
|
type PushControlV1,
|
|
type WebPushObserver,
|
|
type WebPushReadiness,
|
|
type WebPushResult,
|
|
type WebPushUnavailableReason,
|
|
} from "../../contracts/web-push.ts";
|
|
import { base64UrlDecode, base64UrlEncode } from "./codec-primitives.ts";
|
|
import type {
|
|
PushAssociationFenceStore,
|
|
PushControlReceipt,
|
|
} from "./push-association-fence-store.ts";
|
|
import {
|
|
decodeNotificationClickDataForCleanup,
|
|
} from "./push-codec.ts";
|
|
import type {
|
|
NativePushSubscriptionMaterial,
|
|
WebPushRegistrationCommit,
|
|
WebPushRegistrationGateway,
|
|
} from "./push-registration-gateway.ts";
|
|
import {
|
|
createLinkedAbortController,
|
|
observeWebPush,
|
|
withAbortableDeadline,
|
|
type TimeoutScheduler,
|
|
} from "./runtime-support.ts";
|
|
|
|
type PermissionState = "default" | "denied" | "granted";
|
|
|
|
type CapturedNativeSubscription =
|
|
| Readonly<{
|
|
captured: true;
|
|
subscription: WindowPushSubscriptionFacade | null;
|
|
}>
|
|
| Readonly<{ captured: false }>;
|
|
|
|
export type NotificationPermissionFacade = Readonly<{
|
|
permission(): PermissionState;
|
|
requestPermission(): Promise<PermissionState>;
|
|
}>;
|
|
|
|
export type WindowPushSubscriptionFacade = Readonly<{
|
|
endpoint: string;
|
|
expirationTime: number | null;
|
|
options: Readonly<{ applicationServerKey: ArrayBuffer | null }>;
|
|
getKey(name: "p256dh" | "auth"): ArrayBuffer | null;
|
|
unsubscribe(): Promise<boolean>;
|
|
}>;
|
|
|
|
export type WindowPushManagerFacade = Readonly<{
|
|
getSubscription(): Promise<WindowPushSubscriptionFacade | null>;
|
|
subscribe(input: Readonly<{
|
|
userVisibleOnly: true;
|
|
applicationServerKey: Uint8Array<ArrayBuffer>;
|
|
}>): Promise<WindowPushSubscriptionFacade>;
|
|
}>;
|
|
|
|
export type OwnedNotificationFacade = Readonly<{
|
|
data: unknown;
|
|
close(): void;
|
|
}>;
|
|
|
|
export type WindowServiceWorkerRegistrationFacade = Readonly<{
|
|
active: boolean;
|
|
pushManager: WindowPushManagerFacade;
|
|
getNotifications(): Promise<readonly OwnedNotificationFacade[]>;
|
|
}>;
|
|
|
|
export function createWebPushSubscriptionAdapter(
|
|
dependencies: Readonly<{
|
|
secureContext: boolean;
|
|
userActivationIsActive(): boolean;
|
|
permission: NotificationPermissionFacade;
|
|
registration: WindowServiceWorkerRegistrationFacade;
|
|
fenceStore: PushAssociationFenceStore;
|
|
gateway: WebPushRegistrationGateway;
|
|
vapidPublicKey: string;
|
|
now?: () => number;
|
|
idempotencyKeyFactory?: () => string;
|
|
nativeOperationDeadlineMs?: number;
|
|
backendOperationDeadlineMs?: number;
|
|
scheduler?: TimeoutScheduler;
|
|
observer?: WebPushObserver;
|
|
/**
|
|
* 06-02 (D-4). The composition passes `navigator.locks`. Every tab shares
|
|
* one native subscription and one origin fence, so enable, reconcile and
|
|
* revoke run under the origin-wide `web-push-control` lock. Without Web
|
|
* Locks the adapter reports `PUSH_UNSUPPORTED`.
|
|
*/
|
|
lockManager?: Pick<LockManager, "request">;
|
|
}>,
|
|
): WebPushControlPort {
|
|
const decodedVapidPublicKey = decodeVapidPublicKey(
|
|
dependencies.vapidPublicKey,
|
|
);
|
|
if (!decodedVapidPublicKey) {
|
|
throw new TypeError("Web Push VAPID public key is invalid.");
|
|
}
|
|
const vapidPublicKey: Uint8Array<ArrayBuffer> =
|
|
decodedVapidPublicKey;
|
|
const now = dependencies.now ?? Date.now;
|
|
const nativeOperationDeadlineMs =
|
|
dependencies.nativeOperationDeadlineMs ??
|
|
WEB_PUSH_LIMITS.nativeOperationDeadlineMs;
|
|
const backendOperationDeadlineMs =
|
|
dependencies.backendOperationDeadlineMs ??
|
|
WEB_PUSH_LIMITS.backendOperationDeadlineMs;
|
|
if (
|
|
!validDeadline(
|
|
nativeOperationDeadlineMs,
|
|
WEB_PUSH_LIMITS.nativeOperationDeadlineMs,
|
|
) ||
|
|
!validDeadline(
|
|
backendOperationDeadlineMs,
|
|
WEB_PUSH_LIMITS.backendOperationDeadlineMs,
|
|
)
|
|
) {
|
|
throw new TypeError("Web Push operation deadline is invalid.");
|
|
}
|
|
const idempotencyKeyFactory =
|
|
dependencies.idempotencyKeyFactory ?? (() => globalThis.crypto.randomUUID());
|
|
const lockManager = dependencies.lockManager;
|
|
const requestLock =
|
|
typeof lockManager?.request === "function"
|
|
? lockManager.request.bind(lockManager)
|
|
: null;
|
|
let closed = false;
|
|
let busy = false;
|
|
let lifecycleGeneration = 0;
|
|
const inFlight = new Set<
|
|
ReturnType<typeof createLinkedAbortController>
|
|
>();
|
|
|
|
const adapter: WebPushControlPort = {
|
|
inspect(input) {
|
|
return exclusive(
|
|
"SUBSCRIPTION_INSPECT",
|
|
input.signal,
|
|
(generation, operationSignal) =>
|
|
inspectReadiness(input.authority, generation, operationSignal),
|
|
);
|
|
},
|
|
|
|
enable(input) {
|
|
return exclusive(
|
|
"SUBSCRIPTION_CREATE",
|
|
input.signal,
|
|
async (generation, operationSignal) => {
|
|
const supported = supportReadiness();
|
|
if (supported) return webPushSuccess(supported);
|
|
let permission = dependencies.permission.permission();
|
|
if (permission === "denied") {
|
|
await disableCurrentAssociation(
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
return webPushSuccess(readiness("PUSH_DENIED"));
|
|
}
|
|
if (permission === "default") {
|
|
if (!dependencies.userActivationIsActive()) {
|
|
await disableCurrentAssociation(
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
return webPushFailure(
|
|
"PERMISSION_DENIED",
|
|
"PERMISSION_REQUEST",
|
|
);
|
|
}
|
|
const requested = await boundedNative(
|
|
"PERMISSION_REQUEST",
|
|
operationSignal,
|
|
async (signal) => {
|
|
const value =
|
|
await dependencies.permission.requestPermission();
|
|
return signal.aborted
|
|
? webPushFailure("ABORTED", "PERMISSION_REQUEST")
|
|
: webPushSuccess(value);
|
|
},
|
|
);
|
|
if (!requested.ok) return requested;
|
|
permission = requested.value;
|
|
observeWebPush(dependencies.observer, {
|
|
event: "web_push_permission_finished",
|
|
outcome: permission === "granted" ? "SUCCEEDED" : "DEGRADED",
|
|
...(permission === "default"
|
|
? { reason: "PERMISSION_DISMISSED" }
|
|
: {}),
|
|
});
|
|
}
|
|
if (permission === "denied") {
|
|
await disableCurrentAssociation(
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
return webPushSuccess(readiness("PUSH_DENIED"));
|
|
}
|
|
if (permission !== "granted") {
|
|
await disableCurrentAssociation(
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
return webPushSuccess(
|
|
unavailable("PERMISSION_DISMISSED"),
|
|
);
|
|
}
|
|
|
|
const prepared = await dependencies.fenceStore.prepare({
|
|
authority: input.authority,
|
|
updatedAt: instantNow(),
|
|
signal: operationSignal,
|
|
});
|
|
if (!prepared.ok) return prepared;
|
|
|
|
const existing = await getSubscription(
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
if (!existing.ok) return existing;
|
|
let subscription: WindowPushSubscriptionFacade;
|
|
let created = false;
|
|
if (existing.value) {
|
|
if (!subscriptionUsesKey(existing.value, vapidPublicKey)) {
|
|
await disableReceipt(
|
|
prepared.value,
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
existing.value,
|
|
);
|
|
return webPushSuccess(
|
|
unavailable("SUBSCRIPTION_KEY_MISMATCH"),
|
|
);
|
|
}
|
|
subscription = existing.value;
|
|
} else {
|
|
const subscribed = await createSubscription(operationSignal);
|
|
if (!subscribed.ok) return subscribed;
|
|
subscription = subscribed.value;
|
|
created = true;
|
|
}
|
|
if (stale(operationSignal, generation)) {
|
|
if (created) void safeUnsubscribe(subscription);
|
|
return webPushFailure("ABORTED", "SUBSCRIPTION_CREATE");
|
|
}
|
|
return await registerAndActivate({
|
|
subscription,
|
|
prepared: prepared.value,
|
|
authority: input.authority,
|
|
signal: operationSignal,
|
|
generation,
|
|
created,
|
|
});
|
|
},
|
|
);
|
|
},
|
|
|
|
reconcile(input) {
|
|
return exclusive(
|
|
"SUBSCRIPTION_RECONCILE",
|
|
input.signal,
|
|
async (generation, operationSignal) => {
|
|
const supported = supportReadiness();
|
|
if (supported) return webPushSuccess(supported);
|
|
const permission = permissionReadiness();
|
|
if (permission) {
|
|
await disableCurrentAssociation(
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
return webPushSuccess(permission);
|
|
}
|
|
const prepared = await dependencies.fenceStore.prepare({
|
|
authority: input.authority,
|
|
updatedAt: instantNow(),
|
|
signal: operationSignal,
|
|
});
|
|
if (!prepared.ok) return prepared;
|
|
|
|
const native = await getSubscription(
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
if (!native.ok) return native;
|
|
if (!native.value) {
|
|
const revoked = await revokeMissingNative(
|
|
prepared.value,
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
return revoked.ok
|
|
? webPushSuccess(
|
|
unavailable("NATIVE_SUBSCRIPTION_MISSING"),
|
|
)
|
|
: revoked;
|
|
}
|
|
if (!subscriptionUsesKey(native.value, vapidPublicKey)) {
|
|
await disableReceipt(
|
|
prepared.value,
|
|
input.authority,
|
|
operationSignal,
|
|
generation,
|
|
native.value,
|
|
);
|
|
return webPushSuccess(
|
|
unavailable("SUBSCRIPTION_KEY_MISMATCH"),
|
|
);
|
|
}
|
|
const material = captureNativeMaterial(native.value);
|
|
if (!material.ok) return material;
|
|
const reconciled = await boundedBackendReconcile({
|
|
material: material.value,
|
|
authority: input.authority,
|
|
signal: operationSignal,
|
|
});
|
|
if (!reconciled.ok) return reconciled;
|
|
if (stale(operationSignal, generation)) {
|
|
return webPushFailure("ABORTED", "SUBSCRIPTION_RECONCILE");
|
|
}
|
|
if (reconciled.value.state === "ABSENT") {
|
|
// R-6.7. Only a local ACTIVE association (the server lost it) is
|
|
// re-registered. A REVOKED or UNASSOCIATED fence with a leftover
|
|
// native subscription is a failed logout cleanup or an unfinished
|
|
// opt-in; registering it would sign the current account up without
|
|
// its own consent, so the native subscription is removed instead.
|
|
const association = prepared.value.control.association;
|
|
if (association.state !== "ACTIVE") {
|
|
const nativeClean = await cleanupNative(
|
|
association.state === "UNASSOCIATED"
|
|
? null
|
|
: association.associationEpoch,
|
|
generation,
|
|
Object.freeze({ captured: true, subscription: native.value }),
|
|
prepared.value,
|
|
);
|
|
return webPushSuccess(
|
|
unavailable(
|
|
nativeClean
|
|
? "BACKEND_ASSOCIATION_MISSING"
|
|
: "NATIVE_UNSUBSCRIBE_AMBIGUOUS",
|
|
),
|
|
);
|
|
}
|
|
return await registerAndActivate({
|
|
subscription: native.value,
|
|
prepared: prepared.value,
|
|
authority: input.authority,
|
|
signal: operationSignal,
|
|
generation,
|
|
created: false,
|
|
});
|
|
}
|
|
return await activateCommit({
|
|
subscription: native.value,
|
|
prepared: prepared.value,
|
|
authority: input.authority,
|
|
commit: reconciled.value,
|
|
signal: operationSignal,
|
|
generation,
|
|
created: false,
|
|
});
|
|
},
|
|
);
|
|
},
|
|
|
|
revoke(input) {
|
|
return exclusive(
|
|
"SUBSCRIPTION_REVOKE",
|
|
input.signal,
|
|
async (generation, operationSignal) => {
|
|
const current = await dependencies.fenceStore.read({
|
|
signal: operationSignal,
|
|
});
|
|
if (!current.ok) {
|
|
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
|
}
|
|
if (
|
|
!current.value ||
|
|
!samePushAuthority(
|
|
current.value.control,
|
|
input.previousAuthority,
|
|
)
|
|
) {
|
|
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
|
}
|
|
return await revokeReceipt(
|
|
current.value,
|
|
input.previousAuthority,
|
|
input.nextAuthority,
|
|
generation,
|
|
operationSignal,
|
|
);
|
|
},
|
|
);
|
|
},
|
|
|
|
revokeForeign(input) {
|
|
return exclusive(
|
|
"SUBSCRIPTION_REVOKE",
|
|
input.signal,
|
|
async (generation, operationSignal) => {
|
|
const current = await dependencies.fenceStore.read({
|
|
signal: operationSignal,
|
|
});
|
|
if (!current.ok) {
|
|
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
|
}
|
|
// 06-06. Only another session generation's fence is foreign. The
|
|
// next authority's own fence (another tab of the same session opted
|
|
// in, or a new release of it) keeps its association.
|
|
if (
|
|
!current.value ||
|
|
current.value.control.fenceGeneration ===
|
|
input.nextAuthority.fenceGeneration
|
|
) {
|
|
return await inspectReadiness(
|
|
input.nextAuthority,
|
|
generation,
|
|
operationSignal,
|
|
);
|
|
}
|
|
const stored = current.value.control;
|
|
return await revokeReceipt(
|
|
current.value,
|
|
Object.freeze({
|
|
fenceGeneration: stored.fenceGeneration,
|
|
sessionBindingEpoch: stored.sessionBindingEpoch,
|
|
releaseEpoch: stored.releaseEpoch,
|
|
}),
|
|
input.nextAuthority,
|
|
generation,
|
|
operationSignal,
|
|
);
|
|
},
|
|
);
|
|
},
|
|
|
|
dispose() {
|
|
if (closed) return;
|
|
closed = true;
|
|
lifecycleGeneration += 1;
|
|
for (const operation of inFlight) operation.abort();
|
|
inFlight.clear();
|
|
try {
|
|
dependencies.fenceStore.close();
|
|
} catch {
|
|
// The lifecycle is terminal even if host cleanup throws.
|
|
}
|
|
},
|
|
};
|
|
|
|
return Object.freeze(adapter);
|
|
|
|
async function exclusive(
|
|
failureOperation:
|
|
| "SUBSCRIPTION_INSPECT"
|
|
| "SUBSCRIPTION_CREATE"
|
|
| "SUBSCRIPTION_RECONCILE"
|
|
| "SUBSCRIPTION_REVOKE",
|
|
signal: AbortSignal | undefined,
|
|
task: (
|
|
generation: number,
|
|
operationSignal: AbortSignal,
|
|
) => Promise<WebPushResult<WebPushReadiness>>,
|
|
): Promise<WebPushResult<WebPushReadiness>> {
|
|
if (closed) return webPushSuccess(unavailable("CLOSED"));
|
|
if (busy) return webPushSuccess(unavailable("BUSY"));
|
|
if (signal?.aborted) {
|
|
// WP-05. A pre-aborted command is recorded as the operation the caller
|
|
// actually requested, not always as an inspection.
|
|
return webPushFailure("ABORTED", failureOperation);
|
|
}
|
|
busy = true;
|
|
const generation = lifecycleGeneration;
|
|
const operation = createLinkedAbortController(signal);
|
|
inFlight.add(operation);
|
|
const run = () => task(generation, operation.signal);
|
|
try {
|
|
try {
|
|
// 06-02 (D-4). Inspection only reads; mutations wait for other tabs.
|
|
return failureOperation === "SUBSCRIPTION_INSPECT" || !requestLock
|
|
? await run()
|
|
: await requestLock(
|
|
WEB_PUSH_CONTROL_LOCK,
|
|
{ signal: operation.signal },
|
|
run,
|
|
);
|
|
} catch {
|
|
// An abort while waiting for the lock rejects the request.
|
|
return operation.signal.aborted
|
|
? webPushFailure("ABORTED", failureOperation)
|
|
: webPushFailure("NATIVE_FAILURE", failureOperation, true);
|
|
}
|
|
} finally {
|
|
operation.dispose();
|
|
inFlight.delete(operation);
|
|
busy = false;
|
|
}
|
|
}
|
|
|
|
async function inspectReadiness(
|
|
authority: PushAuthoritySnapshot,
|
|
generation: number,
|
|
operationSignal: AbortSignal,
|
|
): Promise<WebPushResult<WebPushReadiness>> {
|
|
const supported = supportReadiness();
|
|
if (supported) return webPushSuccess(supported);
|
|
const permission = permissionReadiness();
|
|
if (permission) return webPushSuccess(permission);
|
|
const native = await getSubscription(operationSignal, generation);
|
|
if (!native.ok) return native;
|
|
if (!native.value) {
|
|
return webPushSuccess(unavailable("NATIVE_SUBSCRIPTION_MISSING"));
|
|
}
|
|
if (!subscriptionUsesKey(native.value, vapidPublicKey)) {
|
|
return webPushSuccess(unavailable("SUBSCRIPTION_KEY_MISMATCH"));
|
|
}
|
|
const control = await dependencies.fenceStore.read({
|
|
signal: operationSignal,
|
|
});
|
|
if (!control.ok) return control;
|
|
return webPushSuccess(
|
|
isActiveFor(control.value?.control ?? null, authority)
|
|
? readiness("PUSH_READY")
|
|
: unavailable("SESSION_AUTHORITY_CHANGED"),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Logout order: rotate the fence to REVOKED first, then revoke the captured
|
|
* association, unsubscribe the captured native subscription and close its
|
|
* notifications.
|
|
*/
|
|
async function revokeReceipt(
|
|
current: PushControlReceipt,
|
|
previousAuthority: PushAuthoritySnapshot,
|
|
nextAuthority: PushAuthoritySnapshot,
|
|
generation: number,
|
|
operationSignal: AbortSignal,
|
|
): Promise<WebPushResult<WebPushReadiness>> {
|
|
const capturedNative = await captureNativeForCleanup(
|
|
operationSignal,
|
|
generation,
|
|
);
|
|
const previousAssociation =
|
|
current.control.association.state === "UNASSOCIATED"
|
|
? null
|
|
: current.control.association.associationEpoch;
|
|
const fenced = await dependencies.fenceStore.rotateAndRevoke({
|
|
expectedRevision: current.revision,
|
|
previousAuthority,
|
|
nextAuthority,
|
|
updatedAt: instantNow(),
|
|
signal: operationSignal,
|
|
});
|
|
if (!fenced.ok) {
|
|
if (previousAssociation) {
|
|
await boundedBackendRevoke(previousAssociation);
|
|
}
|
|
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
|
}
|
|
|
|
let revokeAmbiguous = false;
|
|
if (previousAssociation) {
|
|
const backend = await boundedBackendRevoke(previousAssociation);
|
|
revokeAmbiguous = !backend.ok;
|
|
}
|
|
const nativeClean = await cleanupNative(
|
|
previousAssociation,
|
|
generation,
|
|
capturedNative,
|
|
fenced.value,
|
|
);
|
|
observeWebPush(dependencies.observer, {
|
|
event: "web_push_association_revoked",
|
|
outcome: revokeAmbiguous || !nativeClean ? "DEGRADED" : "SUCCEEDED",
|
|
...(revokeAmbiguous
|
|
? { reason: "BACKEND_REVOKE_AMBIGUOUS" }
|
|
: !nativeClean
|
|
? { reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS" }
|
|
: {}),
|
|
});
|
|
if (revokeAmbiguous) {
|
|
return webPushSuccess(unavailable("BACKEND_REVOKE_AMBIGUOUS"));
|
|
}
|
|
if (!nativeClean) {
|
|
return webPushSuccess(unavailable("NATIVE_UNSUBSCRIBE_AMBIGUOUS"));
|
|
}
|
|
return webPushSuccess(unavailable("REVOKED"));
|
|
}
|
|
|
|
function supportReadiness(): WebPushReadiness | null {
|
|
if (!dependencies.secureContext || !requestLock) {
|
|
return readiness("PUSH_UNSUPPORTED");
|
|
}
|
|
if (!dependencies.registration.active) {
|
|
return unavailable("REGISTRATION_NOT_ACTIVE");
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function permissionReadiness(): WebPushReadiness | null {
|
|
const permission = dependencies.permission.permission();
|
|
if (permission === "denied") return readiness("PUSH_DENIED");
|
|
if (permission === "default") {
|
|
return readiness("PUSH_PERMISSION_REQUIRED");
|
|
}
|
|
return null;
|
|
}
|
|
|
|
async function getSubscription(
|
|
signal: AbortSignal | undefined,
|
|
generation: number,
|
|
): Promise<WebPushResult<WindowPushSubscriptionFacade | null>> {
|
|
return await boundedNative(
|
|
"SUBSCRIPTION_INSPECT",
|
|
signal,
|
|
async (boundedSignal) => {
|
|
const subscription =
|
|
await dependencies.registration.pushManager.getSubscription();
|
|
return boundedSignal.aborted || stale(signal, generation)
|
|
? webPushFailure("ABORTED", "SUBSCRIPTION_INSPECT")
|
|
: webPushSuccess(subscription);
|
|
},
|
|
);
|
|
}
|
|
|
|
async function createSubscription(
|
|
signal: AbortSignal,
|
|
): Promise<WebPushResult<WindowPushSubscriptionFacade>> {
|
|
return await boundedNative(
|
|
"SUBSCRIPTION_CREATE",
|
|
signal,
|
|
async (boundedSignal) => {
|
|
const subscription =
|
|
await dependencies.registration.pushManager.subscribe({
|
|
userVisibleOnly: true,
|
|
applicationServerKey: vapidPublicKey,
|
|
});
|
|
if (boundedSignal.aborted) {
|
|
void safeUnsubscribe(subscription);
|
|
return webPushFailure("ABORTED", "SUBSCRIPTION_CREATE");
|
|
}
|
|
return webPushSuccess(subscription);
|
|
},
|
|
);
|
|
}
|
|
|
|
async function boundedNative<Value>(
|
|
operation:
|
|
| "PERMISSION_REQUEST"
|
|
| "SUBSCRIPTION_INSPECT"
|
|
| "SUBSCRIPTION_CREATE",
|
|
signal: AbortSignal | undefined,
|
|
task: (
|
|
boundedSignal: AbortSignal,
|
|
) => Promise<WebPushResult<Value>>,
|
|
): Promise<WebPushResult<Value>> {
|
|
return await withAbortableDeadline(task, {
|
|
deadlineMs: nativeOperationDeadlineMs,
|
|
operation,
|
|
signal,
|
|
scheduler: dependencies.scheduler,
|
|
});
|
|
}
|
|
|
|
async function boundedBackendRegister(
|
|
input: Parameters<WebPushRegistrationGateway["register"]>[0],
|
|
): ReturnType<WebPushRegistrationGateway["register"]> {
|
|
return await withAbortableDeadline(
|
|
async (signal) => {
|
|
const registered = await dependencies.gateway.register({
|
|
...input,
|
|
signal,
|
|
});
|
|
if (signal.aborted && registered.ok) {
|
|
void boundedBackendRevoke(
|
|
registered.value.associationEpoch,
|
|
);
|
|
return webPushFailure("ABORTED", "SUBSCRIPTION_CREATE");
|
|
}
|
|
return registered;
|
|
},
|
|
{
|
|
deadlineMs: backendOperationDeadlineMs,
|
|
operation: "SUBSCRIPTION_CREATE",
|
|
signal: input.signal,
|
|
scheduler: dependencies.scheduler,
|
|
},
|
|
);
|
|
}
|
|
|
|
async function boundedBackendReconcile(
|
|
input: Parameters<WebPushRegistrationGateway["reconcile"]>[0],
|
|
): ReturnType<WebPushRegistrationGateway["reconcile"]> {
|
|
return await withAbortableDeadline(
|
|
(signal) =>
|
|
dependencies.gateway.reconcile({
|
|
...input,
|
|
signal,
|
|
}),
|
|
{
|
|
deadlineMs: backendOperationDeadlineMs,
|
|
operation: "SUBSCRIPTION_RECONCILE",
|
|
signal: input.signal,
|
|
scheduler: dependencies.scheduler,
|
|
},
|
|
);
|
|
}
|
|
|
|
async function boundedBackendRevoke(
|
|
associationEpoch: string,
|
|
signal?: AbortSignal,
|
|
): ReturnType<WebPushRegistrationGateway["revoke"]> {
|
|
return await withAbortableDeadline(
|
|
(boundedSignal) =>
|
|
dependencies.gateway.revoke({
|
|
associationEpoch,
|
|
signal: boundedSignal,
|
|
}),
|
|
{
|
|
deadlineMs: backendOperationDeadlineMs,
|
|
operation: "SUBSCRIPTION_REVOKE",
|
|
signal,
|
|
scheduler: dependencies.scheduler,
|
|
},
|
|
);
|
|
}
|
|
|
|
async function registerAndActivate(input: Readonly<{
|
|
subscription: WindowPushSubscriptionFacade;
|
|
prepared: PushControlReceipt;
|
|
authority: PushAuthoritySnapshot;
|
|
signal: AbortSignal | undefined;
|
|
generation: number;
|
|
created: boolean;
|
|
}>): Promise<WebPushResult<WebPushReadiness>> {
|
|
const material = captureNativeMaterial(input.subscription);
|
|
if (!material.ok) {
|
|
if (input.created) void safeUnsubscribe(input.subscription);
|
|
return material;
|
|
}
|
|
let idempotencyKey: string;
|
|
try {
|
|
idempotencyKey = idempotencyKeyFactory();
|
|
} catch {
|
|
if (input.created) void safeUnsubscribe(input.subscription);
|
|
return webPushFailure("NATIVE_FAILURE", "SUBSCRIPTION_CREATE");
|
|
}
|
|
const registered = await boundedBackendRegister({
|
|
material: material.value,
|
|
authority: input.authority,
|
|
idempotencyKey,
|
|
signal: input.signal,
|
|
});
|
|
if (!registered.ok) {
|
|
if (input.created) void safeUnsubscribe(input.subscription);
|
|
return registered;
|
|
}
|
|
observeWebPush(dependencies.observer, {
|
|
event: "web_push_registration_finished",
|
|
outcome: "SUCCEEDED",
|
|
});
|
|
return await activateCommit({
|
|
subscription: input.subscription,
|
|
prepared: input.prepared,
|
|
authority: input.authority,
|
|
commit: registered.value,
|
|
signal: input.signal,
|
|
generation: input.generation,
|
|
created: input.created,
|
|
});
|
|
}
|
|
|
|
async function activateCommit(input: Readonly<{
|
|
subscription: WindowPushSubscriptionFacade;
|
|
prepared: PushControlReceipt;
|
|
authority: PushAuthoritySnapshot;
|
|
commit: WebPushRegistrationCommit;
|
|
signal: AbortSignal | undefined;
|
|
generation: number;
|
|
created: boolean;
|
|
}>): Promise<WebPushResult<WebPushReadiness>> {
|
|
// 06-02 (D-4). A subscription this call did not create may carry another
|
|
// tab's association, so compensation leaves it in place.
|
|
const createdSubscription = input.created ? input.subscription : null;
|
|
if (
|
|
input.commit.sessionBindingEpoch !==
|
|
input.authority.sessionBindingEpoch ||
|
|
stale(input.signal, input.generation)
|
|
) {
|
|
await compensate(createdSubscription, input.commit.associationEpoch);
|
|
return webPushSuccess(
|
|
unavailable("SESSION_AUTHORITY_CHANGED"),
|
|
);
|
|
}
|
|
const activated = await dependencies.fenceStore.activate({
|
|
expectedRevision: input.prepared.revision,
|
|
authority: input.authority,
|
|
associationEpoch: input.commit.associationEpoch,
|
|
updatedAt: instantNow(),
|
|
signal: input.signal,
|
|
});
|
|
if (!activated.ok) {
|
|
await compensate(createdSubscription, input.commit.associationEpoch);
|
|
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
|
}
|
|
return webPushSuccess(readiness("PUSH_READY"));
|
|
}
|
|
|
|
async function compensate(
|
|
createdSubscription: WindowPushSubscriptionFacade | null,
|
|
associationEpoch: string,
|
|
): Promise<void> {
|
|
await withAbortableDeadline(
|
|
async (signal) => {
|
|
await Promise.allSettled([
|
|
boundedBackendRevoke(associationEpoch, signal),
|
|
createdSubscription
|
|
? safeUnsubscribe(createdSubscription)
|
|
: Promise.resolve(true),
|
|
]);
|
|
return webPushSuccess(undefined);
|
|
},
|
|
{
|
|
deadlineMs: WEB_PUSH_LIMITS.notificationCleanupDeadlineMs,
|
|
operation: "SUBSCRIPTION_REVOKE",
|
|
scheduler: dependencies.scheduler,
|
|
},
|
|
);
|
|
}
|
|
|
|
async function revokeMissingNative(
|
|
current: PushControlReceipt,
|
|
authority: PushAuthoritySnapshot,
|
|
signal: AbortSignal | undefined,
|
|
generation: number,
|
|
): Promise<WebPushResult<void>> {
|
|
if (current.control.association.state === "UNASSOCIATED") {
|
|
return webPushSuccess(undefined);
|
|
}
|
|
let fenced = current;
|
|
if (current.control.association.state === "ACTIVE") {
|
|
const marked = await dependencies.fenceStore.markRevoked({
|
|
expectedRevision: current.revision,
|
|
authority,
|
|
updatedAt: instantNow(),
|
|
signal,
|
|
});
|
|
if (!marked.ok) {
|
|
await boundedBackendRevoke(
|
|
current.control.association.associationEpoch,
|
|
);
|
|
return marked;
|
|
}
|
|
fenced = marked.value;
|
|
}
|
|
const backend = await boundedBackendRevoke(
|
|
current.control.association.associationEpoch,
|
|
);
|
|
await cleanupNative(
|
|
current.control.association.associationEpoch,
|
|
generation,
|
|
Object.freeze({
|
|
captured: true,
|
|
subscription: null,
|
|
}),
|
|
fenced,
|
|
);
|
|
return backend.ok ? webPushSuccess(undefined) : backend;
|
|
}
|
|
|
|
async function disableCurrentAssociation(
|
|
authority: PushAuthoritySnapshot,
|
|
signal: AbortSignal | undefined,
|
|
generation: number,
|
|
): Promise<boolean> {
|
|
const current = await dependencies.fenceStore.read({ signal });
|
|
if (
|
|
!current.ok ||
|
|
!current.value ||
|
|
!samePushAuthority(current.value.control, authority)
|
|
) {
|
|
return false;
|
|
}
|
|
return await disableReceipt(
|
|
current.value,
|
|
authority,
|
|
signal,
|
|
generation,
|
|
);
|
|
}
|
|
|
|
async function disableReceipt(
|
|
current: PushControlReceipt,
|
|
authority: PushAuthoritySnapshot,
|
|
signal: AbortSignal | undefined,
|
|
generation: number,
|
|
knownSubscription?: WindowPushSubscriptionFacade,
|
|
): Promise<boolean> {
|
|
const association =
|
|
current.control.association.state === "UNASSOCIATED"
|
|
? null
|
|
: current.control.association.associationEpoch;
|
|
const capturedNative =
|
|
knownSubscription === undefined
|
|
? await captureNativeForCleanup(signal, generation)
|
|
: Object.freeze({
|
|
captured: true as const,
|
|
subscription: knownSubscription,
|
|
});
|
|
let fenced = current;
|
|
if (current.control.association.state === "ACTIVE") {
|
|
const marked = await dependencies.fenceStore.markRevoked({
|
|
expectedRevision: current.revision,
|
|
authority,
|
|
updatedAt: instantNow(),
|
|
signal,
|
|
});
|
|
if (!marked.ok) {
|
|
if (association) await boundedBackendRevoke(association);
|
|
return false;
|
|
}
|
|
fenced = marked.value;
|
|
}
|
|
const backendSafe = association
|
|
? (await boundedBackendRevoke(association)).ok
|
|
: true;
|
|
const nativeSafe = await cleanupNative(
|
|
association,
|
|
generation,
|
|
capturedNative,
|
|
fenced,
|
|
);
|
|
return backendSafe && nativeSafe;
|
|
}
|
|
|
|
async function captureNativeForCleanup(
|
|
signal: AbortSignal | undefined,
|
|
generation: number,
|
|
): Promise<CapturedNativeSubscription> {
|
|
const native = await getSubscription(signal, generation);
|
|
return native.ok
|
|
? Object.freeze({
|
|
captured: true as const,
|
|
subscription: native.value,
|
|
})
|
|
: Object.freeze({ captured: false as const });
|
|
}
|
|
|
|
async function cleanupNative(
|
|
associationEpoch: string | null,
|
|
generation: number,
|
|
capturedNative: CapturedNativeSubscription,
|
|
expectedFence: PushControlReceipt,
|
|
): Promise<boolean> {
|
|
const cleanup = await withAbortableDeadline(
|
|
async (signal) => {
|
|
if (stale(signal, generation)) {
|
|
return webPushSuccess(false);
|
|
}
|
|
const currentFence = await dependencies.fenceStore.read({
|
|
signal,
|
|
});
|
|
if (
|
|
stale(signal, generation) ||
|
|
!currentFence.ok ||
|
|
!sameCleanupFence(currentFence.value, expectedFence)
|
|
) {
|
|
return webPushSuccess(false);
|
|
}
|
|
const unsubscribe = !capturedNative.captured
|
|
? Promise.resolve(false)
|
|
: capturedNative.subscription
|
|
? safeUnsubscribe(capturedNative.subscription)
|
|
: Promise.resolve(true);
|
|
const [nativeResult, notificationResult] =
|
|
await Promise.allSettled([
|
|
unsubscribe,
|
|
associationEpoch === null
|
|
? Promise.resolve(
|
|
webPushSuccess(Object.freeze({ complete: true })),
|
|
)
|
|
: closeOwnedNotifications(
|
|
associationEpoch,
|
|
signal,
|
|
generation,
|
|
),
|
|
]);
|
|
const nativeClean =
|
|
nativeResult.status === "fulfilled" &&
|
|
nativeResult.value;
|
|
const notificationsClean =
|
|
notificationResult.status === "fulfilled" &&
|
|
notificationResult.value.ok &&
|
|
notificationResult.value.value.complete;
|
|
return webPushSuccess(
|
|
nativeClean && notificationsClean,
|
|
);
|
|
},
|
|
{
|
|
deadlineMs: WEB_PUSH_LIMITS.notificationCleanupDeadlineMs,
|
|
operation: "NOTIFICATION_CLEANUP",
|
|
scheduler: dependencies.scheduler,
|
|
},
|
|
);
|
|
return cleanup.ok && cleanup.value;
|
|
}
|
|
|
|
/**
|
|
* WP-06. Notification cleanup is bounded best effort and is reported
|
|
* separately from revoke authority: an incomplete pass returns
|
|
* `{ complete: false }` and is observed as DEGRADED rather than success.
|
|
*/
|
|
async function closeOwnedNotifications(
|
|
associationEpoch: string,
|
|
signal: AbortSignal | undefined,
|
|
generation: number,
|
|
): Promise<WebPushResult<Readonly<{ complete: boolean }>>> {
|
|
let notifications: readonly OwnedNotificationFacade[];
|
|
try {
|
|
notifications = await dependencies.registration.getNotifications();
|
|
} catch {
|
|
return webPushFailure(
|
|
"NATIVE_FAILURE",
|
|
"NOTIFICATION_CLEANUP",
|
|
true,
|
|
);
|
|
}
|
|
if (stale(signal, generation)) {
|
|
return webPushFailure("ABORTED", "NOTIFICATION_CLEANUP");
|
|
}
|
|
const truncated =
|
|
notifications.length > WEB_PUSH_LIMITS.notificationCleanupCount;
|
|
observeWebPush(dependencies.observer, {
|
|
event: "web_push_notification_finished",
|
|
outcome: truncated ? "DEGRADED" : "SUCCEEDED",
|
|
...(truncated ? { reason: "LIMIT_EXCEEDED" as const } : {}),
|
|
countBucket: webPushCountBucket(notifications.length),
|
|
truncated,
|
|
});
|
|
for (const notification of notifications.slice(
|
|
0,
|
|
WEB_PUSH_LIMITS.notificationCleanupCount,
|
|
)) {
|
|
const decoded = decodeNotificationClickDataForCleanup(
|
|
notification.data,
|
|
);
|
|
if (
|
|
decoded.ok &&
|
|
decoded.value.associationEpoch === associationEpoch
|
|
) {
|
|
try {
|
|
notification.close();
|
|
} catch {
|
|
// Closing an OS notification is best effort.
|
|
}
|
|
}
|
|
}
|
|
return webPushSuccess(Object.freeze({ complete: !truncated }));
|
|
}
|
|
|
|
function stale(
|
|
signal: AbortSignal | undefined,
|
|
generation: number,
|
|
): boolean {
|
|
return (
|
|
Boolean(signal?.aborted) ||
|
|
closed ||
|
|
generation !== lifecycleGeneration
|
|
);
|
|
}
|
|
|
|
function instantNow(): string {
|
|
const value = now();
|
|
return Number.isFinite(value)
|
|
? new Date(value).toISOString()
|
|
: new Date(0).toISOString();
|
|
}
|
|
}
|
|
|
|
/** 06-02 (D-4). Origin-wide Web Lock name shared by every tab. */
|
|
const WEB_PUSH_CONTROL_LOCK = "web-push-control";
|
|
|
|
function readiness(
|
|
state: WebPushReadiness["state"],
|
|
): WebPushReadiness {
|
|
return Object.freeze({ state });
|
|
}
|
|
|
|
function unavailable(
|
|
reason: WebPushUnavailableReason,
|
|
): WebPushReadiness {
|
|
return Object.freeze({ state: "PUSH_UNAVAILABLE", reason });
|
|
}
|
|
|
|
function sameCleanupFence(
|
|
current: PushControlReceipt | null,
|
|
expected: PushControlReceipt,
|
|
): boolean {
|
|
if (
|
|
!current ||
|
|
current.revision !== expected.revision ||
|
|
!samePushAuthority(current.control, expected.control) ||
|
|
current.control.association.state !==
|
|
expected.control.association.state
|
|
) {
|
|
return false;
|
|
}
|
|
return current.control.association.state === "UNASSOCIATED"
|
|
? true
|
|
: expected.control.association.state !== "UNASSOCIATED" &&
|
|
current.control.association.associationEpoch ===
|
|
expected.control.association.associationEpoch;
|
|
}
|
|
|
|
function validDeadline(value: number, ceiling: number): boolean {
|
|
return (
|
|
Number.isSafeInteger(value) &&
|
|
value >= 1 &&
|
|
value <= ceiling
|
|
);
|
|
}
|
|
|
|
function isActiveFor(
|
|
value: PushControlV1 | null,
|
|
authority: PushAuthoritySnapshot,
|
|
): boolean {
|
|
return (
|
|
Boolean(value) &&
|
|
value?.association.state === "ACTIVE" &&
|
|
samePushAuthority(value, authority)
|
|
);
|
|
}
|
|
|
|
function captureNativeMaterial(
|
|
subscription: WindowPushSubscriptionFacade,
|
|
): WebPushResult<NativePushSubscriptionMaterial> {
|
|
let p256dh: ArrayBuffer | null;
|
|
let auth: ArrayBuffer | null;
|
|
try {
|
|
p256dh = subscription.getKey("p256dh");
|
|
auth = subscription.getKey("auth");
|
|
} catch {
|
|
return webPushFailure("NATIVE_FAILURE", "SUBSCRIPTION_INSPECT");
|
|
}
|
|
if (!p256dh || !auth || p256dh.byteLength !== 65 || auth.byteLength !== 16) {
|
|
return webPushFailure("CONTRACT_REJECTED", "SUBSCRIPTION_INSPECT");
|
|
}
|
|
return webPushSuccess(
|
|
Object.freeze({
|
|
endpoint: subscription.endpoint,
|
|
p256dh: base64UrlEncode(new Uint8Array(p256dh)),
|
|
auth: base64UrlEncode(new Uint8Array(auth)),
|
|
expirationTime: subscription.expirationTime,
|
|
}),
|
|
);
|
|
}
|
|
|
|
function subscriptionUsesKey(
|
|
subscription: WindowPushSubscriptionFacade,
|
|
expected: Uint8Array<ArrayBuffer>,
|
|
): boolean {
|
|
const current = subscription.options.applicationServerKey;
|
|
if (!current || current.byteLength !== expected.byteLength) return false;
|
|
const bytes = new Uint8Array(current);
|
|
let difference = 0;
|
|
for (let index = 0; index < bytes.length; index += 1) {
|
|
difference |= bytes[index]! ^ expected[index]!;
|
|
}
|
|
return difference === 0;
|
|
}
|
|
|
|
async function safeUnsubscribe(
|
|
subscription: WindowPushSubscriptionFacade,
|
|
): Promise<boolean> {
|
|
try {
|
|
return await subscription.unsubscribe();
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function decodeVapidPublicKey(
|
|
value: string,
|
|
): Uint8Array<ArrayBuffer> | null {
|
|
if (!/^[A-Za-z0-9_-]{87}$/u.test(value)) return null;
|
|
const decoded = base64UrlDecode(value);
|
|
return decoded?.byteLength === 65 && decoded[0] === 4 ? decoded : null;
|
|
}
|