import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server"; import { Hono } from "hono"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { configureApiAppDependenciesForTests } from "../app-dependencies.js"; import type { ApiEnv } from "../api-types.js"; import { createApiSessionToken } from "../auth/session/session-token.js"; import { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "../config.js"; import { registerDevicesRoutes } from "./devices-routes.js"; const TEST_TOKEN = "test-service-token"; const TEST_USER_ID = "u-1"; type StoredDeviceToken = { id: string; userId: string; tenantId: string | null; platform: string; token: string; pushProvider: string; appVersion: string | null; createdAt: Date; lastSeenAt: Date; revokedAt: Date | null; }; let mockStore: Map; let resetApiAppDependencies: () => void; let findLegacyAuthUserById: ReturnType; let revalidateWorkspaceContext: ReturnType; let getActiveApiSession: ReturnType; vi.mock("@hivegrid/db/device-tokens.server", () => ({ parseDevicePlatform: (value: unknown) => (value === "web" ? value : null), parsePushProvider: (value: unknown) => (value === "webpush" ? value : null), async registerDeviceToken(input: { userId: string; tenantId: string | null; platform: "web"; token: string; pushProvider?: "webpush"; appVersion?: string | null; }) { const provider = input.pushProvider ?? "webpush"; const now = new Date(); const existing = mockStore.get(input.token); if (existing) { if (existing.userId !== input.userId) { throw new Error("token owner mismatch"); } existing.tenantId = input.tenantId; existing.platform = input.platform; existing.pushProvider = provider; existing.appVersion = input.appVersion ?? null; existing.lastSeenAt = now; existing.revokedAt = null; return existing; } const row = { id: `dt-${mockStore.size + 1}`, userId: input.userId, tenantId: input.tenantId, platform: input.platform, token: input.token, pushProvider: provider, appVersion: input.appVersion ?? null, createdAt: now, lastSeenAt: now, revokedAt: null, }; mockStore.set(input.token, row); return row; }, async revokeDeviceToken(input: { token: string; userId: string; tenantId: string | null }) { const row = mockStore.get(input.token); if (!row || row.userId !== input.userId || row.tenantId !== input.tenantId) { return null; } row.revokedAt = new Date(); return row; }, })); function buildApp() { const app = new Hono(); registerDevicesRoutes(app); return app; } beforeEach(() => { mockStore = new Map(); setApiRuntimeConfigForTests({ apiAccessToken: TEST_TOKEN, jwtSecret: "jwt", routing: { appBaseDomain: "example.com", webAppHost: "app.example.com", adminAppHost: "admin.example.com", apiHost: "api.example.com", portalAppHost: "portal.example.com", protocol: "https", }, apiKeys: { allowLegacyPlaintextFallback: false }, } as never); findLegacyAuthUserById = vi.fn(async (userId: string) => { expect(getRlsExecutionContext()).toMatchObject({ userId }); return { id: userId, email: `${userId}@example.test`, totpEnabledAt: null, pendingDeletion: false, pseudonymized: false, active: true, }; }); revalidateWorkspaceContext = vi.fn(async ({ tenantId, userId }: { tenantId?: string | null; userId?: string | null }) => { expect(getRlsExecutionContext()).toMatchObject({ tenantId, userId }); return { valid: true as const, tenantId: tenantId ?? "", userId: userId ?? "", membership: {} as never }; }); getActiveApiSession = vi.fn(async (sessionId: string) => { expect(getRlsExecutionContext()).toMatchObject({ userId: TEST_USER_ID }); return { sessionId, userId: TEST_USER_ID, createdAt: new Date() }; }); resetApiAppDependencies = configureApiAppDependenciesForTests({ findLegacyAuthUserById, revalidateWorkspaceContext, getActiveApiSession }); }); afterEach(() => { resetApiAppDependencies(); resetApiRuntimeConfigForTests(); }); function postRegister( app: ReturnType, body: unknown, options: { auth?: string | null; identityHeader?: string | null } = {}, ) { const auth = options.auth === undefined ? `Bearer ${createTestApiSessionToken()}` : options.auth; return app.request("/v1/devices/register", { method: "POST", headers: { "content-type": "application/json", ...(auth ? { authorization: auth } : {}), ...(options.identityHeader ? { "x-hivegrid-user-id": options.identityHeader } : {}), }, body: JSON.stringify(body), }); } function postRevoke( app: ReturnType, body: unknown, options: { auth?: string | null; identityHeader?: string | null } = {}, ) { const auth = options.auth === undefined ? `Bearer ${createTestApiSessionToken()}` : options.auth; return app.request("/v1/devices/revoke", { method: "POST", headers: { "content-type": "application/json", ...(auth ? { authorization: auth } : {}), ...(options.identityHeader ? { "x-hivegrid-user-id": options.identityHeader } : {}), }, body: JSON.stringify(body), }); } function createTestApiSessionToken(userId = TEST_USER_ID, sessionId = "session-1") { return createApiSessionToken({ userId, sessionId, secret: "jwt" }); } describe("POST /v1/devices/register", () => { it("rejects requests without an API session JWT", async () => { const response = await postRegister(buildApp(), {}, { auth: null }); expect(response.status).toBe(401); }); it("rejects a service token without a user-bearing API session", async () => { const response = await postRegister(buildApp(), { platform: "web", token: "tok-1" }, { auth: `Bearer ${TEST_TOKEN}` }); expect(response.status).toBe(401); await expect(response.json()).resolves.toMatchObject({ error: { code: "invalid_token" } }); }); it("rejects a signed JWT whose persistent session is inactive", async () => { getActiveApiSession.mockResolvedValueOnce(undefined); const response = await postRegister(buildApp(), { platform: "web", token: "tok-1" }); expect(response.status).toBe(401); }); it("rejects non-object bodies", async () => { const response = await buildApp().request("/v1/devices/register", { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${createTestApiSessionToken()}`, }, body: "not-json", }); expect(response.status).toBe(400); }); it("rejects body and header attempts to override the JWT owner", async () => { const bodyOverride = await postRegister(buildApp(), { userId: "u-2", platform: "web", token: "tok-1" }); expect(bodyOverride.status).toBe(400); await expect(bodyOverride.json()).resolves.toMatchObject({ error: { code: "device_identity_override_not_allowed" } }); const headerOverride = await postRegister( buildApp(), { platform: "web", token: "tok-1" }, { identityHeader: "u-2" }, ); expect(headerOverride.status).toBe(400); await expect(headerOverride.json()).resolves.toMatchObject({ error: { code: "device_identity_override_not_allowed" } }); expect(mockStore).toHaveLength(0); }); it("rejects unknown platforms and missing tokens", async () => { const app = buildApp(); expect((await postRegister(app, { platform: "wear", token: "t" })).status).toBe(400); const missingToken = await postRegister(app, { platform: "web" }); expect(missingToken.status).toBe(400); await expect(missingToken.json()).resolves.toMatchObject({ error: { params: { field: "token" } } }); }); it("validates the JWT owner and active session inside user RLS before registering", async () => { const response = await postRegister(buildApp(), { platform: "web", token: "tok-1", appVersion: "1.2.3" }); expect(response.status).toBe(200); expect(getActiveApiSession).toHaveBeenCalledWith("session-1"); expect(findLegacyAuthUserById).toHaveBeenCalledWith(TEST_USER_ID); expect(revalidateWorkspaceContext).not.toHaveBeenCalled(); await expect(response.json()).resolves.toMatchObject({ success: true, data: { userId: TEST_USER_ID, tenantId: null, platform: "web", pushProvider: "webpush", appVersion: "1.2.3" }, }); }); it("rejects a JWT owner whose account no longer exists", async () => { findLegacyAuthUserById.mockResolvedValueOnce(null); const response = await postRegister(buildApp(), { platform: "web", token: "tok-1" }); expect(response.status).toBe(401); expect(mockStore).toHaveLength(0); }); it("revalidates active membership inside tenant/user RLS before registering", async () => { const response = await postRegister(buildApp(), { tenantId: "tenant-1", platform: "web", token: "tok-1", }); expect(response.status).toBe(200); expect(revalidateWorkspaceContext).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: TEST_USER_ID }); expect(findLegacyAuthUserById).toHaveBeenCalledWith(TEST_USER_ID); }); it("keeps same-owner registration idempotent without duplicating rows", async () => { const app = buildApp(); await postRegister(app, { platform: "web", token: "tok-x" }); const second = await postRegister(app, { platform: "web", token: "tok-x" }); expect(second.status).toBe(200); expect(mockStore).toHaveLength(1); }); it("fails closed instead of reassigning a token owned by another user", async () => { mockStore.set("tok-x", { id: "dt-foreign", userId: "u-2", tenantId: null, platform: "web", token: "tok-x", pushProvider: "webpush", appVersion: null, createdAt: new Date(), lastSeenAt: new Date(), revokedAt: null, }); const response = await postRegister(buildApp(), { platform: "web", token: "tok-x" }); expect(response.status).toBe(500); expect(mockStore.get("tok-x")?.userId).toBe("u-2"); }); }); describe("POST /v1/devices/revoke", () => { it("rejects missing or service-token-only authentication", async () => { expect((await postRevoke(buildApp(), { token: "tok-a" }, { auth: null })).status).toBe(401); expect((await postRevoke(buildApp(), { token: "tok-a" }, { auth: `Bearer ${TEST_TOKEN}` })).status).toBe(401); }); it("rejects body and header attempts to override the JWT owner", async () => { expect((await postRevoke(buildApp(), { token: "tok-a", userId: "u-2" })).status).toBe(400); expect((await postRevoke(buildApp(), { token: "tok-a" }, { identityHeader: "u-2" })).status).toBe(400); }); it("revokes only the matching tenantless owner's token without echoing it", async () => { const app = buildApp(); await postRegister(app, { platform: "web", token: "tok-a" }); const response = await postRevoke(app, { token: "tok-a" }); expect(response.status).toBe(200); const responseText = await response.text(); expect(responseText).not.toContain("tok-a"); expect(JSON.parse(responseText)).toMatchObject({ success: true, data: { id: "dt-1", revokedAt: expect.any(String) } }); }); it("revalidates tenant membership before revoking a tenant token", async () => { const app = buildApp(); await postRegister(app, { tenantId: "tenant-1", platform: "web", token: "tok-a" }); revalidateWorkspaceContext.mockClear(); const response = await postRevoke(app, { token: "tok-a", tenantId: "tenant-1" }); expect(response.status).toBe(200); expect(revalidateWorkspaceContext).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: TEST_USER_ID }); }); it("hides tokens owned by another user or tenant", async () => { mockStore.set("tok-a", { id: "dt-foreign", userId: "u-2", tenantId: "tenant-1", platform: "web", token: "tok-a", pushProvider: "webpush", appVersion: null, createdAt: new Date(), lastSeenAt: new Date(), revokedAt: null, }); const wrongUser = await postRevoke(buildApp(), { token: "tok-a", tenantId: "tenant-1" }); expect(wrongUser.status).toBe(404); expect(mockStore.get("tok-a")?.revokedAt).toBeNull(); mockStore.get("tok-a")!.userId = TEST_USER_ID; const wrongTenant = await postRevoke(buildApp(), { token: "tok-a", tenantId: "tenant-2" }); expect(wrongTenant.status).toBe(404); expect(mockStore.get("tok-a")?.revokedAt).toBeNull(); }); it("returns 404 for unknown tokens", async () => { const response = await postRevoke(buildApp(), { token: "missing" }); expect(response.status).toBe(404); }); });