Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -28,10 +28,14 @@ export function resetWebMetricsForTests(): void {
function buildWebMetrics(): WebMetricsBundle {
const revision = process.env.APP_REVISION?.trim() ?? "";
const runtimeSurface = resolveMetricsRuntimeSurface(process.env);
const registry = createMetricsRegistry({
serviceName: "web",
collectDefaultProcessMetrics: true,
...(revision ? { defaultLabels: { revision } } : {}),
defaultLabels: {
runtime_surface: runtimeSurface,
...(revision ? { revision } : {}),
},
});
const metrics = createDefaultMetrics(registry);
// Wire BullMQ enqueue events into queue_jobs_enqueued_total. See
@@ -41,3 +45,14 @@ function buildWebMetrics(): WebMetricsBundle {
});
return { registry, metrics };
}
function resolveMetricsRuntimeSurface(env: Readonly<{ NODE_ENV?: string; VITEST?: string; WEB_RUNTIME_SURFACE?: string }>): "core" | "admin" | "portal" {
const surface = env.WEB_RUNTIME_SURFACE;
if (surface === "core" || surface === "admin" || surface === "portal") {
return surface;
}
if (surface === undefined && (env.NODE_ENV === "test" || env.VITEST === "true")) {
return "core";
}
throw new Error("WEB_RUNTIME_SURFACE must be explicitly set to core, admin, or portal before web metrics initialization");
}
@@ -0,0 +1,84 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getWebMetrics, resetWebMetricsForTests } from "./registry.js";
import { recordAuthorizedStorageDownload } from "./storage-traffic.js";
beforeEach(() => {
resetWebMetricsForTests();
});
describe("recordAuthorizedStorageDownload", () => {
it("records a bounded authorization count and known whole-object bytes", async () => {
recordAuthorizedStorageDownload({
surface: "files",
delivery: "signed_redirect",
objectSizeBytes: 1_048_576,
});
const text = await getWebMetrics().registry.metrics();
expect(text).toContain(
'storage_authorized_downloads_total{surface="files",delivery="signed_redirect",size_known="known",service="web",runtime_surface="core"} 1'
);
expect(text).toContain(
'storage_authorized_download_object_bytes_total{surface="files",delivery="signed_redirect",service="web",runtime_surface="core"} 1048576'
);
});
it.each([undefined, null, -1, Number.NaN, 1.5])("records an unknown size without inventing byte volume for %s", async (objectSizeBytes) => {
recordAuthorizedStorageDownload({ surface: "portal_document", delivery: "signed_redirect", objectSizeBytes });
const text = await getWebMetrics().registry.metrics();
expect(text).toContain(
'storage_authorized_downloads_total{surface="portal_document",delivery="signed_redirect",size_known="unknown",service="web",runtime_surface="core"} 1'
);
expect(text).not.toContain("storage_authorized_download_object_bytes_total{");
});
it("separates portal download counters from the Core runtime", async () => {
const previousSurface = process.env.WEB_RUNTIME_SURFACE;
process.env.WEB_RUNTIME_SURFACE = "portal";
resetWebMetricsForTests();
try {
recordAuthorizedStorageDownload({ surface: "portal_document", delivery: "signed_redirect", objectSizeBytes: 512 });
const text = await getWebMetrics().registry.metrics();
expect(text).toContain('runtime_surface="portal"');
expect(text).not.toContain('runtime_surface="core"');
} finally {
if (previousSurface === undefined) delete process.env.WEB_RUNTIME_SURFACE;
else process.env.WEB_RUNTIME_SURFACE = previousSurface;
resetWebMetricsForTests();
}
});
it("folds impossible runtime label values into other and never exports them", async () => {
recordAuthorizedStorageDownload({
surface: "tenant-secret" as "files",
delivery: "https://objects.example.test/signed" as "signed_redirect",
objectSizeBytes: 10,
});
const text = await getWebMetrics().registry.metrics();
expect(text).toContain('delivery="other"');
expect(text).toContain('surface="other"');
expect(text).not.toContain("tenant-secret");
expect(text).not.toContain("objects.example.test");
});
it("stays fail-open when either counter rejects an observation", () => {
const throwingCounter = {
labels: vi.fn(() => ({
inc: vi.fn(() => {
throw new Error("metrics down");
}),
})),
};
const metrics = {
storageAuthorizedDownloadsTotal: throwingCounter,
storageAuthorizedDownloadObjectBytesTotal: throwingCounter,
} as unknown as NonNullable<Parameters<typeof recordAuthorizedStorageDownload>[1]>["metrics"];
expect(() => recordAuthorizedStorageDownload({ surface: "files", delivery: "signed_redirect", objectSizeBytes: 42 }, { metrics })).not.toThrow();
expect(throwingCounter.labels).toHaveBeenCalledTimes(2);
});
});
@@ -0,0 +1,74 @@
/**
* Low-cardinality storage-delivery telemetry for BILL-25.
*
* The counters deliberately describe an authorization/delivery decision, not
* provider egress: a presigned URL can remain unused, be reused before expiry,
* or serve byte ranges without another application request. Never add tenant,
* file, object-key, filename, or URL labels here.
*/
import type { DefaultMetrics } from "@hivegrid/metrics";
import { getWebMetrics } from "./registry.js";
const STORAGE_DOWNLOAD_SURFACES = ["files", "portal_document"] as const;
const STORAGE_DOWNLOAD_DELIVERIES = ["signed_redirect"] as const;
export type StorageDownloadSurface = (typeof STORAGE_DOWNLOAD_SURFACES)[number];
export type StorageDownloadDelivery = (typeof STORAGE_DOWNLOAD_DELIVERIES)[number];
type StorageTrafficMetrics = Pick<
DefaultMetrics,
"storageAuthorizedDownloadsTotal" | "storageAuthorizedDownloadObjectBytesTotal"
>;
export type AuthorizedStorageDownloadInput = {
readonly surface: StorageDownloadSurface;
readonly delivery: StorageDownloadDelivery;
/** Whole-object size when the authorization boundary has a trustworthy value. */
readonly objectSizeBytes?: number | null;
};
type RecordAuthorizedStorageDownloadOptions = {
/** Test seam; production always uses the web service-scoped registry. */
readonly metrics?: StorageTrafficMetrics;
};
export function recordAuthorizedStorageDownload(
input: AuthorizedStorageDownloadInput,
options: RecordAuthorizedStorageDownloadOptions = {}
): void {
let metrics: StorageTrafficMetrics;
try {
metrics = options.metrics ?? getWebMetrics().metrics;
} catch {
return;
}
const surface = boundedLabel(input.surface, STORAGE_DOWNLOAD_SURFACES);
const delivery = boundedLabel(input.delivery, STORAGE_DOWNLOAD_DELIVERIES);
const objectSizeBytes = knownObjectSize(input.objectSizeBytes);
try {
metrics.storageAuthorizedDownloadsTotal
.labels({ surface, delivery, size_known: objectSizeBytes === null ? "unknown" : "known" })
.inc();
} catch {
// Observability must never block a valid download.
}
if (objectSizeBytes !== null) {
try {
metrics.storageAuthorizedDownloadObjectBytesTotal.labels({ surface, delivery }).inc(objectSizeBytes);
} catch {
// Keep the authorization path fail-open even when one metric is broken.
}
}
}
function boundedLabel<TValue extends string>(value: TValue, allowed: readonly TValue[]): TValue | "other" {
return allowed.includes(value) ? value : "other";
}
function knownObjectSize(value: number | null | undefined): number | null {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
}
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { registerServiceWorker } from "./registerServiceWorker";
import { SERVICE_WORKER_SCRIPT_URL, registerServiceWorker } from "./registerServiceWorker";
describe("registerServiceWorker", () => {
it("returns null when navigator has no service worker", async () => {
@@ -16,22 +16,33 @@ describe("registerServiceWorker", () => {
expect(register).not.toHaveBeenCalled();
});
it("registers /sw.js by default", async () => {
it("registers the versioned worker URL by default", async () => {
const fakeRegistration = { scope: "/" } as ServiceWorkerRegistration;
const register = vi.fn().mockResolvedValue(fakeRegistration);
const navigatorRef = { serviceWorker: { register } } as unknown as Navigator;
const result = await registerServiceWorker({ navigatorRef });
expect(register).toHaveBeenCalledWith("/sw.js", { scope: "/" });
expect(register).toHaveBeenCalledWith(SERVICE_WORKER_SCRIPT_URL, { scope: "/" });
expect(result).toBe(fakeRegistration);
});
it("allows an explicit script URL and scope override", async () => {
const fakeRegistration = { scope: "/preview/" } as ServiceWorkerRegistration;
const register = vi.fn().mockResolvedValue(fakeRegistration);
const navigatorRef = { serviceWorker: { register } } as unknown as Navigator;
const result = await registerServiceWorker({ navigatorRef, scriptUrl: "/preview-sw.js", scope: "/preview/" });
expect(register).toHaveBeenCalledWith("/preview-sw.js", { scope: "/preview/" });
expect(result).toBe(fakeRegistration);
});
it("swallows registration errors and returns null", async () => {
const register = vi.fn().mockRejectedValue(new Error("boom"));
const error = new Error("boom");
const register = vi.fn().mockRejectedValue(error);
const navigatorRef = { serviceWorker: { register } } as unknown as Navigator;
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const result = await registerServiceWorker({ navigatorRef });
const onError = vi.fn();
const result = await registerServiceWorker({ navigatorRef, onError });
expect(result).toBeNull();
expect(warn).toHaveBeenCalled();
warn.mockRestore();
expect(onError).toHaveBeenCalledWith(error);
});
});
@@ -11,6 +11,10 @@
*
* Refs: docs/improvement-plan/10-compliance-polish/lighthouse.md (Step (d)).
*/
import { SERVICE_WORKER_VERSION } from "./serviceWorkerRecoveryBootstrap";
export const SERVICE_WORKER_SCRIPT_URL = `/sw.js?v=${encodeURIComponent(SERVICE_WORKER_VERSION)}`;
export type RegisterServiceWorkerOptions = {
scriptUrl?: string;
scope?: string;
@@ -18,6 +22,8 @@ export type RegisterServiceWorkerOptions = {
navigatorRef?: Navigator;
/** Inject an override container so tests can disable DEV gating. */
isDev?: boolean;
/** Optional client-side telemetry hook; registration failure remains non-fatal. */
onError?: (error: unknown) => void;
};
export async function registerServiceWorker(options: RegisterServiceWorkerOptions = {}): Promise<ServiceWorkerRegistration | null> {
@@ -31,14 +37,11 @@ export async function registerServiceWorker(options: RegisterServiceWorkerOption
}
try {
return await navigatorRef.serviceWorker.register(options.scriptUrl ?? "/sw.js", {
return await navigatorRef.serviceWorker.register(options.scriptUrl ?? SERVICE_WORKER_SCRIPT_URL, {
scope: options.scope ?? "/",
});
} catch (err) {
// Swallow but log — a failed SW must never break the app render.
if (typeof console !== "undefined") {
console.warn("[pwa] service worker registration failed", err);
}
options.onError?.(err);
return null;
}
}
@@ -0,0 +1,359 @@
// @vitest-environment node
import { runInNewContext } from "node:vm";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SERVICE_WORKER_RECOVERY_BOOTSTRAP, SERVICE_WORKER_VERSION } from "./serviceWorkerRecoveryBootstrap";
type RecoveryHarnessOptions = {
controlled?: boolean;
controllerScriptUrl?: string;
existingMarker?: string;
registrationAvailable?: boolean;
registerError?: Error;
storageError?: Error;
unregisterError?: Error;
updateError?: Error;
updateThrows?: Error;
waitingWorker?: boolean;
};
type ServiceWorkerEvent = { data?: unknown; source?: unknown };
type ServiceWorkerListener = (event: ServiceWorkerEvent) => void;
function createRecoveryHarness(options: RecoveryHarnessOptions = {}) {
const storageValues = new Map<string, string>();
if (options.existingMarker) {
storageValues.set("service-worker-recovery:v4", options.existingMarker);
}
const listeners = new Map<string, Set<ServiceWorkerListener>>();
const reload = vi.fn();
const controller = {
postMessage: vi.fn(),
scriptURL: options.controllerScriptUrl ?? "https://app.example.test/sw.js",
};
const waitingWorker = { postMessage: vi.fn() };
const update = options.updateThrows
? vi.fn(() => {
throw options.updateThrows;
})
: options.updateError
? vi.fn().mockRejectedValue(options.updateError)
: vi.fn().mockResolvedValue(undefined);
const unregister = options.unregisterError ? vi.fn().mockRejectedValue(options.unregisterError) : vi.fn().mockResolvedValue(true);
const registration = {
update,
unregister,
waiting: options.waitingWorker ? waitingWorker : null,
};
const replacementRegistration = { waiting: null };
const getRegistration = vi.fn().mockResolvedValue(options.registrationAvailable === false ? undefined : registration);
const register = options.registerError ? vi.fn().mockRejectedValue(options.registerError) : vi.fn().mockResolvedValue(replacementRegistration);
const addEventListener = vi.fn((type: string, listener: ServiceWorkerListener) => {
const typedListeners = listeners.get(type) ?? new Set<ServiceWorkerListener>();
typedListeners.add(listener);
listeners.set(type, typedListeners);
});
const removeEventListener = vi.fn((type: string, listener: ServiceWorkerListener) => {
listeners.get(type)?.delete(listener);
});
const sessionStorage = {
getItem: vi.fn((key: string) => {
if (options.storageError) throw options.storageError;
return storageValues.get(key) ?? null;
}),
setItem: vi.fn((key: string, value: string) => {
if (options.storageError) throw options.storageError;
storageValues.set(key, value);
}),
removeItem: vi.fn((key: string) => {
if (options.storageError) throw options.storageError;
return storageValues.delete(key);
}),
};
const serviceWorker = {
controller: options.controlled === false ? null : controller,
addEventListener,
removeEventListener,
getRegistration,
register,
};
const context = {
Date,
JSON,
Math,
Promise,
clearTimeout,
encodeURIComponent,
location: { origin: "https://app.example.test", reload },
navigator: { serviceWorker },
sessionStorage,
setTimeout,
};
function emit(type: string, event: ServiceWorkerEvent = {}) {
for (const listener of [...(listeners.get(type) ?? [])]) listener(event);
}
function answerVersion(version = SERVICE_WORKER_VERSION) {
const request = controller.postMessage.mock.lastCall?.[0] as { requestId?: string } | undefined;
emit("message", {
data: {
type: "HIVEGRID_SW_VERSION_RESPONSE",
requestId: request?.requestId,
version,
},
source: controller,
});
}
return {
addEventListener,
answerVersion,
context,
controller,
emitControllerChange: () => emit("controllerchange"),
getRegistration,
register,
reload,
removeEventListener,
sessionStorage,
storageValues,
unregister,
update,
waitingWorker,
};
}
async function runBootstrap(harness: ReturnType<typeof createRecoveryHarness>) {
runInNewContext(SERVICE_WORKER_RECOVERY_BOOTSTRAP, harness.context);
await Promise.resolve();
}
describe("service-worker recovery bootstrap", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("uses the versioned controller URL as a synchronous healthy fast path", async () => {
const marker = JSON.stringify({ expiresAt: Date.now() + 60_000 });
const harness = createRecoveryHarness({
controllerScriptUrl: `https://app.example.test/sw.js?v=${encodeURIComponent(SERVICE_WORKER_VERSION)}`,
existingMarker: marker,
});
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(10_000);
expect(harness.controller.postMessage).not.toHaveBeenCalled();
expect(harness.getRegistration).not.toHaveBeenCalled();
expect(harness.update).not.toHaveBeenCalled();
expect(harness.unregister).not.toHaveBeenCalled();
expect(harness.register).not.toHaveBeenCalled();
expect(harness.reload).not.toHaveBeenCalled();
expect(harness.storageValues.size).toBe(0);
});
it("uses a version handshake and skips update checks for the current worker", async () => {
const harness = createRecoveryHarness();
await runBootstrap(harness);
expect(harness.controller.postMessage).toHaveBeenCalledWith({
type: "HIVEGRID_SW_VERSION_REQUEST",
requestId: expect.any(String),
});
harness.answerVersion();
await vi.advanceTimersByTimeAsync(10_000);
expect(harness.getRegistration).not.toHaveBeenCalled();
expect(harness.update).not.toHaveBeenCalled();
expect(harness.register).not.toHaveBeenCalled();
expect(harness.reload).not.toHaveBeenCalled();
});
it("clears an interrupted recovery marker after a healthy handshake", async () => {
const marker = JSON.stringify({ expiresAt: Date.now() + 60_000 });
const harness = createRecoveryHarness({ existingMarker: marker });
await runBootstrap(harness);
harness.answerVersion();
await Promise.resolve();
expect(harness.sessionStorage.removeItem).toHaveBeenCalledWith("service-worker-recovery:v4");
expect(harness.storageValues.size).toBe(0);
});
it("updates a legacy worker that does not answer the handshake", async () => {
const harness = createRecoveryHarness();
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(300);
expect(harness.getRegistration).toHaveBeenCalledTimes(1);
expect(harness.update).toHaveBeenCalledTimes(1);
expect(harness.storageValues.has("service-worker-recovery:v4")).toBe(true);
harness.emitControllerChange();
harness.emitControllerChange();
expect(harness.reload).toHaveBeenCalledTimes(1);
expect(harness.storageValues.size).toBe(0);
});
it("updates immediately when a worker reports an obsolete version", async () => {
const harness = createRecoveryHarness();
await runBootstrap(harness);
harness.answerVersion("v3-obsolete");
await Promise.resolve();
await Promise.resolve();
expect(harness.update).toHaveBeenCalledTimes(1);
});
it("accepts a late healthy response during recovery without unregistering or reloading", async () => {
const harness = createRecoveryHarness();
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(300);
expect(harness.update).toHaveBeenCalledTimes(1);
expect(harness.controller.postMessage).toHaveBeenCalledTimes(2);
harness.answerVersion();
await vi.advanceTimersByTimeAsync(10_000);
expect(harness.unregister).not.toHaveBeenCalled();
expect(harness.register).not.toHaveBeenCalled();
expect(harness.reload).not.toHaveBeenCalled();
expect(harness.storageValues.size).toBe(0);
});
it("nudges a waiting replacement after an update", async () => {
const harness = createRecoveryHarness({ waitingWorker: true });
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(300);
expect(harness.waitingWorker.postMessage).toHaveBeenCalledWith({ type: "HIVEGRID_SW_SKIP_WAITING" });
});
it("replaces a registration when a resolved update never changes controller", async () => {
const harness = createRecoveryHarness();
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(250 + 1_500 + 1_500);
expect(harness.update).toHaveBeenCalledTimes(1);
expect(harness.unregister).toHaveBeenCalledTimes(1);
expect(harness.register).toHaveBeenCalledWith(`/sw.js?v=${encodeURIComponent(SERVICE_WORKER_VERSION)}`, {
scope: "/",
updateViaCache: "none",
});
expect(harness.reload).toHaveBeenCalledTimes(1);
expect(harness.storageValues.size).toBe(0);
});
it("falls back immediately when the update is rejected", async () => {
const harness = createRecoveryHarness({ updateError: new Error("update failed") });
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(250 + 1_500);
expect(harness.update).toHaveBeenCalledTimes(1);
expect(harness.unregister).toHaveBeenCalledTimes(1);
expect(harness.register).toHaveBeenCalledTimes(1);
});
it("contains synchronous update errors and still reaches the bounded replacement", async () => {
const harness = createRecoveryHarness({ updateThrows: new Error("sync update failure") });
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(250 + 1_500);
expect(harness.update).toHaveBeenCalledTimes(1);
expect(harness.unregister).toHaveBeenCalledTimes(1);
expect(harness.register).toHaveBeenCalledTimes(1);
});
it("reloads through the network when re-registration fails after unregister", async () => {
const harness = createRecoveryHarness({
registerError: new Error("register failed"),
updateError: new Error("update failed"),
});
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(250 + 1_500);
expect(harness.unregister).toHaveBeenCalledTimes(1);
expect(harness.register).toHaveBeenCalledTimes(1);
expect(harness.reload).toHaveBeenCalledTimes(1);
expect(harness.storageValues.size).toBe(0);
});
it("bounds a replacement wait after unregister fails and clears the retry marker", async () => {
const harness = createRecoveryHarness({
unregisterError: new Error("unregister failed"),
updateError: new Error("update failed"),
});
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(250 + 1_500 + 1_500);
expect(harness.register).toHaveBeenCalledTimes(1);
expect(harness.reload).not.toHaveBeenCalled();
expect(harness.storageValues.size).toBe(0);
});
it("retries after an unexpired lock instead of treating it as permanent", async () => {
const harness = createRecoveryHarness({
existingMarker: JSON.stringify({ expiresAt: Date.now() + 1_000 }),
});
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(999);
expect(harness.update).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(20);
expect(harness.update).toHaveBeenCalledTimes(1);
});
it("re-registers when the legacy registration cannot be found", async () => {
const harness = createRecoveryHarness({ registrationAvailable: false });
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(300);
expect(harness.update).not.toHaveBeenCalled();
expect(harness.register).toHaveBeenCalledTimes(1);
});
it("does nothing without an active controller", async () => {
const harness = createRecoveryHarness({ controlled: false });
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(10_000);
expect(harness.getRegistration).not.toHaveBeenCalled();
expect(harness.storageValues.size).toBe(0);
});
it("still repairs a controlled page when session storage is unavailable", async () => {
const harness = createRecoveryHarness({ storageError: new Error("storage unavailable") });
await runBootstrap(harness);
await vi.advanceTimersByTimeAsync(300);
expect(harness.update).toHaveBeenCalledTimes(1);
});
it("contains no script-closing sequence", () => {
expect(SERVICE_WORKER_RECOVERY_BOOTSTRAP).not.toContain("</script>");
expect(SERVICE_WORKER_RECOVERY_BOOTSTRAP).not.toContain("${");
});
});
@@ -0,0 +1,221 @@
/**
* Version shared by the early recovery bootstrap and the regular client-side
* registration. Keep it in sync with `public/sw.js`; a regression test enforces
* that boundary.
*/
export const SERVICE_WORKER_VERSION = "v5-2026-07-15-web-push";
/**
* Runs before stylesheet discovery. A healthy worker answers one cheap version
* handshake and performs no update check. A legacy worker gets one update and,
* if it never takes control, one bounded unregister/register fallback.
*/
export const SERVICE_WORKER_RECOVERY_BOOTSTRAP = String.raw`
(function () {
var serviceWorker = navigator.serviceWorker;
var controller = serviceWorker && serviceWorker.controller;
if (!controller) return;
var expectedVersion = "${SERVICE_WORKER_VERSION}";
var expectedScriptPath = "/sw.js?v=" + encodeURIComponent(expectedVersion);
var markerKey = "service-worker-recovery:v4";
var legacyMarkerKey = "service-worker-csp-recovery:v3";
if (
typeof controller.scriptURL === "string" &&
controller.scriptURL === location.origin + expectedScriptPath
) {
try {
sessionStorage.removeItem(markerKey);
sessionStorage.removeItem(legacyMarkerKey);
} catch (error) {}
return;
}
var requestId = Date.now().toString(36) + ":" + Math.random().toString(36).slice(2);
var handshakeTimer;
var lockTimer;
var replacementTimer;
var recoveryStarted = false;
var replacementStarted = false;
var healthy = false;
var reloaded = false;
function clearTimer(timer) {
if (timer) clearTimeout(timer);
}
function removeHandshake() {
clearTimer(handshakeTimer);
try {
serviceWorker.removeEventListener("message", onMessage);
} catch (error) {}
}
function clearMarkers() {
try {
sessionStorage.removeItem(markerKey);
sessionStorage.removeItem(legacyMarkerKey);
} catch (error) {}
}
function cleanup() {
clearTimer(lockTimer);
clearTimer(replacementTimer);
removeHandshake();
try {
serviceWorker.removeEventListener("controllerchange", reloadOnce);
} catch (error) {}
clearMarkers();
}
function reloadOnce() {
if (reloaded || healthy) return;
reloaded = true;
cleanup();
location.reload();
}
function acquireLock() {
try {
var now = Date.now();
var rawMarker = sessionStorage.getItem(markerKey);
if (rawMarker) {
var marker = JSON.parse(rawMarker);
if (marker && typeof marker.expiresAt === "number" && marker.expiresAt > now) {
return marker.expiresAt - now;
}
}
sessionStorage.setItem(markerKey, JSON.stringify({ expiresAt: now + 3000 }));
} catch (error) {}
return 0;
}
function requestSkipWaiting(worker) {
if (!worker) return;
try {
worker.postMessage({ type: "HIVEGRID_SW_SKIP_WAITING" });
} catch (error) {}
}
function finishHealthy() {
if (healthy || reloaded) return;
healthy = true;
cleanup();
}
function probeBeforeReplacement(registration) {
if (healthy || reloaded) return;
clearTimer(handshakeTimer);
requestId = Date.now().toString(36) + ":" + Math.random().toString(36).slice(2);
try {
controller.postMessage({ type: "HIVEGRID_SW_VERSION_REQUEST", requestId: requestId });
handshakeTimer = setTimeout(function () {
replaceRegistration(registration);
}, 1500);
} catch (error) {
replaceRegistration(registration);
}
}
function replaceRegistration(registration) {
if (replacementStarted || reloaded || healthy) return;
replacementStarted = true;
var detached = false;
Promise.resolve()
.then(function () {
return registration ? registration.unregister() : true;
})
.then(
function (unregistered) {
detached = Boolean(unregistered);
},
function () {}
)
.then(function () {
return serviceWorker.register("/sw.js?v=" + encodeURIComponent(expectedVersion), {
scope: "/",
updateViaCache: "none"
});
})
.then(function (nextRegistration) {
if (healthy || reloaded) return;
requestSkipWaiting(nextRegistration.waiting);
replacementTimer = setTimeout(function () {
if (detached) reloadOnce();
else cleanup();
}, 1500);
})
.catch(function () {
if (detached) {
reloadOnce();
return;
}
cleanup();
});
}
function updateRegistration(registration) {
Promise.resolve()
.then(function () {
return registration.update();
})
.then(function () {
if (healthy || reloaded) return;
requestSkipWaiting(registration.waiting);
probeBeforeReplacement(registration);
})
.catch(function () {
probeBeforeReplacement(registration);
});
}
function startRecovery() {
if (recoveryStarted || reloaded || healthy) return;
clearTimer(handshakeTimer);
var lockDelay = acquireLock();
if (lockDelay > 0) {
lockTimer = setTimeout(startRecovery, lockDelay + 10);
return;
}
recoveryStarted = true;
try {
serviceWorker.addEventListener("controllerchange", reloadOnce);
serviceWorker
.getRegistration()
.then(function (registration) {
if (registration) updateRegistration(registration);
else replaceRegistration(null);
})
.catch(function () {
replaceRegistration(null);
});
} catch (error) {
cleanup();
}
}
function onMessage(event) {
var data = event && event.data;
if (!data || data.type !== "HIVEGRID_SW_VERSION_RESPONSE" || data.requestId !== requestId) return;
if (event.source && event.source !== controller) return;
if (data.version === expectedVersion) {
finishHealthy();
return;
}
startRecovery();
}
try {
serviceWorker.addEventListener("message", onMessage);
controller.postMessage({ type: "HIVEGRID_SW_VERSION_REQUEST", requestId: requestId });
handshakeTimer = setTimeout(startRecovery, 250);
} catch (error) {
startRecovery();
}
})();
`
.replace(/\s+/g, " ")
.trim();
@@ -0,0 +1,119 @@
import { describe, expect, it, vi } from "vitest";
import { SERVICE_WORKER_VERSION } from "./serviceWorkerRecoveryBootstrap";
import {
bootstrapTelephonyPush,
decodeVapidPublicKey,
registerTelephonyPushSubscription,
serializePushSubscription,
telephonyPushRegistrationPath,
} from "./telephonyPush";
const vapidPublicKey = Buffer.from(Uint8Array.from({ length: 65 }, (_, index) => (index === 0 ? 0x04 : index))).toString("base64url");
const p256dhKey = Buffer.from(Uint8Array.from({ length: 65 }, (_, index) => (index === 0 ? 0x04 : index + 1))).toString("base64url");
const authKey = Buffer.alloc(16, 7).toString("base64url");
function pushSubscription(endpoint = "https://push.example.test/subscriptions/device-1"): PushSubscription {
return {
endpoint,
toJSON: () => ({
endpoint,
expirationTime: null,
keys: { p256dh: p256dhKey, auth: authKey },
}),
} as PushSubscription;
}
function serviceWorkerRegistration(options: { existing?: PushSubscription | null; created?: PushSubscription } = {}) {
const subscribe = vi.fn().mockResolvedValue(options.created ?? pushSubscription());
const getSubscription = vi.fn().mockResolvedValue(options.existing ?? null);
return {
registration: { pushManager: { getSubscription, subscribe } } as unknown as ServiceWorkerRegistration,
getSubscription,
subscribe,
};
}
describe("telephony Web Push bootstrap", () => {
it("decodes the canonical uncompressed VAPID public key", () => {
const decoded = decodeVapidPublicKey(vapidPublicKey);
expect(decoded).toHaveLength(65);
expect(decoded[0]).toBe(0x04);
expect(() => decodeVapidPublicKey("invalid!" )).toThrow(/public key is invalid/i);
});
it("does not subscribe or register before the user has granted notification permission", async () => {
const registration = serviceWorkerRegistration();
const fetcher = vi.fn();
const navigatorRef = {
serviceWorker: { ready: Promise.resolve(registration.registration) },
} as unknown as Navigator;
await expect(
bootstrapTelephonyPush({
enabled: true,
tenantSlug: "hivegrid-demo",
vapidPublicKey,
csrfToken: "csrf-token",
notificationPermission: "default",
navigatorRef,
fetcher: fetcher as typeof fetch,
}),
).resolves.toBe("permission-not-granted");
expect(registration.getSubscription).not.toHaveBeenCalled();
expect(fetcher).not.toHaveBeenCalled();
});
it("creates a missing PushSubscription and registers the serialized token through the same-origin resource route", async () => {
const created = pushSubscription();
const registration = serviceWorkerRegistration({ created });
const fetcher = vi.fn().mockResolvedValue(Response.json({ ok: true }));
await registerTelephonyPushSubscription({
registration: registration.registration,
endpoint: "/hivegrid-demo/telephony/push-subscription",
vapidPublicKey,
csrfToken: "csrf-token",
fetcher: fetcher as typeof fetch,
});
expect(registration.subscribe).toHaveBeenCalledWith({
userVisibleOnly: true,
applicationServerKey: expect.any(Uint8Array),
});
expect(fetcher).toHaveBeenCalledTimes(1);
const [url, init] = fetcher.mock.calls[0] as [string, RequestInit];
expect(url).toBe("/hivegrid-demo/telephony/push-subscription");
expect(init).toMatchObject({
method: "POST",
credentials: "same-origin",
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token" },
});
const body = JSON.parse(String(init.body));
expect(body).toMatchObject({ platform: "web", pushProvider: "webpush", appVersion: SERVICE_WORKER_VERSION });
expect(JSON.parse(body.token)).toEqual(created.toJSON());
});
it("reuses an existing subscription on cold start and reports server rejection", async () => {
const existing = pushSubscription("https://push.example.test/subscriptions/existing");
const registration = serviceWorkerRegistration({ existing });
const fetcher = vi.fn().mockResolvedValue(new Response(null, { status: 503 }));
await expect(
registerTelephonyPushSubscription({
registration: registration.registration,
endpoint: "/hivegrid-demo/telephony/push-subscription",
vapidPublicKey,
csrfToken: "csrf-token",
fetcher: fetcher as typeof fetch,
}),
).rejects.toThrow("status 503");
expect(registration.subscribe).not.toHaveBeenCalled();
});
it("rejects unsafe tenant paths and incomplete browser subscription payloads", () => {
expect(telephonyPushRegistrationPath("hivegrid-demo")).toBe("/hivegrid-demo/telephony/push-subscription");
expect(() => telephonyPushRegistrationPath("//attacker.example")).toThrow(/tenant slug/i);
expect(() => serializePushSubscription(pushSubscription("http://push.example.test/device"))).toThrow(/incomplete/i);
});
});
@@ -0,0 +1,147 @@
import { SERVICE_WORKER_VERSION } from "./serviceWorkerRecoveryBootstrap";
const VAPID_PUBLIC_KEY_BYTES = 65;
const MAX_PUSH_SUBSCRIPTION_BYTES = 4_096;
export type TelephonyPushBootstrapResult =
| "disabled"
| "unsupported"
| "permission-not-granted"
| "registered";
export type TelephonyPushBootstrapOptions = {
enabled: boolean;
tenantSlug: string;
vapidPublicKey?: string;
csrfToken?: string;
isDev?: boolean;
navigatorRef?: Navigator;
notificationPermission?: NotificationPermission;
fetcher?: typeof fetch;
};
export type RegisterTelephonyPushSubscriptionOptions = {
registration: ServiceWorkerRegistration;
endpoint: string;
vapidPublicKey: string;
csrfToken: string;
fetcher?: typeof fetch;
};
/**
* Registers an already-authorized browser for Aircall ringing pushes.
* Permission prompting intentionally stays outside this silent bootstrap: the
* dedicated PWA pre-prompt owns that user gesture in VA-P27a.
*/
export async function bootstrapTelephonyPush(options: TelephonyPushBootstrapOptions): Promise<TelephonyPushBootstrapResult> {
if (!options.enabled || options.isDev || !options.vapidPublicKey || !options.csrfToken) {
return "disabled";
}
const navigatorRef = options.navigatorRef ?? (typeof navigator === "undefined" ? undefined : navigator);
if (!navigatorRef || !("serviceWorker" in navigatorRef)) {
return "unsupported";
}
const permission =
options.notificationPermission ?? (typeof Notification === "undefined" ? undefined : Notification.permission);
if (permission === undefined) {
return "unsupported";
}
if (permission !== "granted") {
return "permission-not-granted";
}
const registration = await navigatorRef.serviceWorker.ready;
await registerTelephonyPushSubscription({
registration,
endpoint: telephonyPushRegistrationPath(options.tenantSlug),
vapidPublicKey: options.vapidPublicKey,
csrfToken: options.csrfToken,
fetcher: options.fetcher,
});
return "registered";
}
export async function registerTelephonyPushSubscription(options: RegisterTelephonyPushSubscriptionOptions): Promise<void> {
if (!options.registration.pushManager) {
throw new Error("Web Push is unavailable in this service worker registration.");
}
const existingSubscription = await options.registration.pushManager.getSubscription();
const subscription =
existingSubscription ??
(await options.registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: decodeVapidPublicKey(options.vapidPublicKey),
}));
const token = serializePushSubscription(subscription);
const response = await (options.fetcher ?? fetch)(options.endpoint, {
method: "POST",
credentials: "same-origin",
headers: {
"content-type": "application/json",
"x-csrf-token": options.csrfToken,
},
body: JSON.stringify({
platform: "web",
pushProvider: "webpush",
appVersion: SERVICE_WORKER_VERSION,
token,
}),
});
if (!response.ok) {
throw new Error(`Web Push registration failed with status ${response.status}.`);
}
}
export function telephonyPushRegistrationPath(tenantSlug: string): string {
const normalized = tenantSlug.trim();
if (!normalized || normalized.length > 256 || /[\u0000-\u001F\u007F/\\]/.test(normalized)) {
throw new Error("Telephony Push registration requires a valid tenant slug.");
}
return `/${encodeURIComponent(normalized)}/telephony/push-subscription`;
}
export function serializePushSubscription(subscription: PushSubscription): string {
const value = subscription.toJSON();
if (
typeof value.endpoint !== "string" ||
!value.endpoint.startsWith("https://") ||
!value.keys ||
typeof value.keys.p256dh !== "string" ||
typeof value.keys.auth !== "string"
) {
throw new Error("The browser returned an incomplete Web Push subscription.");
}
const serialized = JSON.stringify(value);
if (new TextEncoder().encode(serialized).byteLength > MAX_PUSH_SUBSCRIPTION_BYTES) {
throw new Error("The browser Web Push subscription exceeds the registration limit.");
}
return serialized;
}
export function decodeVapidPublicKey(publicKey: string): Uint8Array<ArrayBuffer> {
const normalized = publicKey.trim();
if (!/^[A-Za-z0-9_-]+$/.test(normalized)) {
throw new Error("The Web Push public key is invalid.");
}
const padded = normalized.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(normalized.length / 4) * 4, "=");
let decoded: string;
try {
decoded = atob(padded);
} catch {
throw new Error("The Web Push public key is invalid.");
}
const bytes = new Uint8Array(new ArrayBuffer(decoded.length));
for (let index = 0; index < decoded.length; index += 1) {
bytes[index] = decoded.charCodeAt(index);
}
if (bytes.byteLength !== VAPID_PUBLIC_KEY_BYTES || bytes[0] !== 0x04) {
throw new Error("The Web Push public key is invalid.");
}
return bytes;
}