138 lines
5.4 KiB
TypeScript
138 lines
5.4 KiB
TypeScript
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const mocks = vi.hoisted(() => ({
|
|
loadTelephonyContext: vi.fn(),
|
|
requireTelephonyPermission: vi.fn(),
|
|
validateCSRFToken: vi.fn(),
|
|
withTenantRLS: vi.fn(),
|
|
registerDeviceToken: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/modules/telephony/routes/telephonyAccess.server", () => ({
|
|
TELEPHONY_PERMISSIONS: { readOwn: "telephony.read_own" },
|
|
loadTelephonyContext: mocks.loadTelephonyContext,
|
|
requireTelephonyPermission: mocks.requireTelephonyPermission,
|
|
}));
|
|
|
|
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
|
|
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
|
|
vi.mock("@hivegrid/db/device-tokens.server", () => ({ registerDeviceToken: mocks.registerDeviceToken }));
|
|
|
|
import { action, isValidSerializedPushSubscription, loader } from "./telephony.push-subscription";
|
|
|
|
const context = {
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
tenantUserId: "tenant_user_1",
|
|
permissions: ["telephony.read_own"],
|
|
hasModule: true,
|
|
};
|
|
const p256dhKey = Buffer.from(Uint8Array.from({ length: 65 }, (_, index) => (index === 0 ? 0x04 : index + 1))).toString("base64url");
|
|
const authKey = Buffer.alloc(16, 7).toString("base64url");
|
|
const subscription = JSON.stringify({
|
|
endpoint: "https://push.example.test/subscriptions/device-1",
|
|
expirationTime: null,
|
|
keys: { p256dh: p256dhKey, auth: authKey },
|
|
});
|
|
|
|
function request(body: Record<string, unknown>, headers: Record<string, string> = {}) {
|
|
return new Request("https://app.example.test/hivegrid-demo/telephony/push-subscription", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token", ...headers },
|
|
body: JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.loadTelephonyContext.mockResolvedValue(context);
|
|
mocks.requireTelephonyPermission.mockImplementation((value) => value);
|
|
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
|
mocks.withTenantRLS.mockImplementation(async (_tenantId, callback) => callback({ deviceToken: {} }));
|
|
mocks.registerDeviceToken.mockResolvedValue({ id: "device_1", lastSeenAt: new Date("2026-07-15T12:00:00.000Z") });
|
|
});
|
|
|
|
describe("tenant Telephony Push registration resource", () => {
|
|
it("keeps GET undiscoverable", () => {
|
|
expect(loader()).toMatchObject({ status: 404 });
|
|
});
|
|
|
|
it("requires the active Telephony module, read permission, and header-only session CSRF before storing under tenant RLS", async () => {
|
|
const incoming = request({
|
|
platform: "web",
|
|
pushProvider: "webpush",
|
|
appVersion: "sw-v5",
|
|
token: subscription,
|
|
});
|
|
const response = await action({ request: incoming, params: { tenant: "hivegrid-demo" }, context: {} } as never);
|
|
|
|
expect(response.status).toBe(200);
|
|
expect(mocks.loadTelephonyContext).toHaveBeenCalledWith({
|
|
request: incoming,
|
|
params: { tenant: "hivegrid-demo" },
|
|
requireModule: true,
|
|
});
|
|
expect(mocks.requireTelephonyPermission).toHaveBeenCalledWith(context, "telephony.read_own");
|
|
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(incoming, { headerOnly: true });
|
|
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
|
|
expect(mocks.registerDeviceToken).toHaveBeenCalledWith(
|
|
{
|
|
userId: "user_1",
|
|
tenantId: "tenant_1",
|
|
platform: "web",
|
|
pushProvider: "webpush",
|
|
token: subscription,
|
|
appVersion: "sw-v5",
|
|
},
|
|
expect.any(Object),
|
|
);
|
|
await expect(response.json()).resolves.toEqual({
|
|
ok: true,
|
|
data: { id: "device_1", registeredAt: "2026-07-15T12:00:00.000Z" },
|
|
});
|
|
});
|
|
|
|
it("returns 404 and never reaches CSRF or persistence when module/permission access is denied", async () => {
|
|
mocks.requireTelephonyPermission.mockImplementationOnce(() => {
|
|
throw new CatalogError(foundationErrors.notFound);
|
|
});
|
|
const response = await action({
|
|
request: request({ platform: "web", pushProvider: "webpush", token: subscription }),
|
|
params: { tenant: "hivegrid-demo" },
|
|
context: {},
|
|
} as never);
|
|
|
|
expect(response.status).toBe(404);
|
|
expect(mocks.validateCSRFToken).not.toHaveBeenCalled();
|
|
expect(mocks.registerDeviceToken).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects identity overrides and malformed subscriptions without writing", async () => {
|
|
const identityOverride = await action({
|
|
request: request({ platform: "web", pushProvider: "webpush", token: subscription, userId: "attacker" }),
|
|
params: { tenant: "hivegrid-demo" },
|
|
context: {},
|
|
} as never);
|
|
const malformed = await action({
|
|
request: request({ platform: "web", pushProvider: "webpush", token: "not-json" }),
|
|
params: { tenant: "hivegrid-demo" },
|
|
context: {},
|
|
} as never);
|
|
|
|
expect(identityOverride.status).toBe(400);
|
|
expect(malformed.status).toBe(400);
|
|
expect(mocks.registerDeviceToken).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("validates only bounded HTTPS PushSubscription JSON", () => {
|
|
expect(isValidSerializedPushSubscription(subscription)).toBe(true);
|
|
expect(
|
|
isValidSerializedPushSubscription(
|
|
JSON.stringify({ endpoint: "http://push.example.test/device", keys: { p256dh: "key", auth: "auth" } }),
|
|
),
|
|
).toBe(false);
|
|
expect(isValidSerializedPushSubscription("x".repeat(4_097))).toBe(false);
|
|
});
|
|
});
|