Files

148 lines
4.9 KiB
TypeScript

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;
}