134 lines
4.7 KiB
TypeScript
134 lines
4.7 KiB
TypeScript
import { CatalogError } from "@hivegrid/foundation";
|
|
import { registerDeviceToken, type DeviceTokenClient } from "@hivegrid/db/device-tokens.server";
|
|
import type { ActionFunctionArgs } from "react-router";
|
|
|
|
import {
|
|
TELEPHONY_PERMISSIONS,
|
|
loadTelephonyContext,
|
|
requireTelephonyPermission,
|
|
} from "~/modules/telephony/routes/telephonyAccess.server";
|
|
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
|
import { readLimitedRequestBytes } from "~/utils/http/readLimitedRequestBody.server";
|
|
import { validateCSRFToken } from "~/utils/session.server";
|
|
|
|
const MAX_REQUEST_BYTES = 8_192;
|
|
const MAX_SUBSCRIPTION_BYTES = 4_096;
|
|
const MAX_APP_VERSION_LENGTH = 128;
|
|
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
|
|
type RegistrationBody = {
|
|
platform?: unknown;
|
|
pushProvider?: unknown;
|
|
token?: unknown;
|
|
appVersion?: unknown;
|
|
userId?: unknown;
|
|
tenantId?: unknown;
|
|
};
|
|
|
|
export const loader = () => new Response(null, { status: 404 });
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
let ctx;
|
|
try {
|
|
ctx = requireTelephonyPermission(
|
|
await loadTelephonyContext({ request, params, requireModule: true }),
|
|
TELEPHONY_PERMISSIONS.readOwn,
|
|
);
|
|
} catch (error) {
|
|
if (error instanceof CatalogError) return new Response(null, { status: error.status });
|
|
throw error;
|
|
}
|
|
|
|
await validateCSRFToken(request, { headerOnly: true });
|
|
if (!request.headers.get("content-type")?.toLowerCase().includes("application/json")) {
|
|
return Response.json({ ok: false, error: "unsupported_media_type" }, { status: 415 });
|
|
}
|
|
|
|
const body = await readRegistrationBody(request);
|
|
if (!body || body.userId !== undefined || body.tenantId !== undefined) {
|
|
return Response.json({ ok: false, error: "invalid_request" }, { status: 400 });
|
|
}
|
|
|
|
const token = typeof body.token === "string" ? body.token.trim() : "";
|
|
const appVersion = typeof body.appVersion === "string" ? body.appVersion.trim() : "";
|
|
if (
|
|
body.platform !== "web" ||
|
|
body.pushProvider !== "webpush" ||
|
|
!isValidSerializedPushSubscription(token) ||
|
|
appVersion.length > MAX_APP_VERSION_LENGTH
|
|
) {
|
|
return Response.json({ ok: false, error: "invalid_request" }, { status: 400 });
|
|
}
|
|
|
|
try {
|
|
const record = await withTenantRLS(ctx.tenantId, (tx) =>
|
|
registerDeviceToken(
|
|
{
|
|
userId: ctx.userId,
|
|
tenantId: ctx.tenantId,
|
|
platform: "web",
|
|
pushProvider: "webpush",
|
|
token,
|
|
appVersion: appVersion || null,
|
|
},
|
|
tx as unknown as DeviceTokenClient,
|
|
),
|
|
);
|
|
return Response.json({ ok: true, data: { id: record.id, registeredAt: record.lastSeenAt.toISOString() } });
|
|
} catch {
|
|
return Response.json({ ok: false, error: "registration_failed" }, { status: 503 });
|
|
}
|
|
};
|
|
|
|
async function readRegistrationBody(request: Request): Promise<RegistrationBody | null> {
|
|
try {
|
|
const bytes = await readLimitedRequestBytes(request, MAX_REQUEST_BYTES);
|
|
const parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)) as unknown;
|
|
return isPlainRecord(parsed) ? parsed : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function isValidSerializedPushSubscription(token: string): boolean {
|
|
if (!token || new TextEncoder().encode(token).byteLength > MAX_SUBSCRIPTION_BYTES) return false;
|
|
|
|
try {
|
|
const value = JSON.parse(token) as unknown;
|
|
if (!isPlainRecord(value) || !isPlainRecord(value.keys)) return false;
|
|
const endpoint = typeof value.endpoint === "string" ? value.endpoint : "";
|
|
const p256dh = typeof value.keys.p256dh === "string" ? value.keys.p256dh : "";
|
|
const auth = typeof value.keys.auth === "string" ? value.keys.auth : "";
|
|
const endpointUrl = new URL(endpoint);
|
|
return (
|
|
endpointUrl.protocol === "https:" &&
|
|
!endpointUrl.username &&
|
|
!endpointUrl.password &&
|
|
!endpointUrl.hash &&
|
|
isCanonicalBase64Url(p256dh, 65, 0x04) &&
|
|
isCanonicalBase64Url(auth, 16)
|
|
);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isCanonicalBase64Url(value: string, expectedBytes: number, firstByte?: number): boolean {
|
|
if (!BASE64URL_PATTERN.test(value)) return false;
|
|
try {
|
|
const padded = value.replace(/-/gu, "+").replace(/_/gu, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
const decoded = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
|
|
const canonical = btoa(String.fromCharCode(...decoded))
|
|
.replace(/\+/gu, "-")
|
|
.replace(/\//gu, "_")
|
|
.replace(/=+$/gu, "");
|
|
return decoded.byteLength === expectedBytes && canonical === value && (firstByte === undefined || decoded[0] === firstByte);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|