Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+238
-68
@@ -1,26 +1,52 @@
|
||||
import { describe, expect, it, beforeEach, afterEach, vi } from "vitest";
|
||||
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";
|
||||
import { setApiRuntimeConfigForTests, resetApiRuntimeConfigForTests } from "../config.js";
|
||||
|
||||
const TEST_TOKEN = "test-service-token";
|
||||
const TEST_USER_ID = "u-1";
|
||||
|
||||
let mockStore: Map<string, { id: string; userId: string; tenantId: string | null; platform: string; token: string; pushProvider: string; appVersion: string | null; createdAt: Date; lastSeenAt: Date; revokedAt: Date | null }>;
|
||||
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<string, StoredDeviceToken>;
|
||||
let resetApiAppDependencies: () => void;
|
||||
let findLegacyAuthUserById: ReturnType<typeof vi.fn>;
|
||||
let revalidateWorkspaceContext: ReturnType<typeof vi.fn>;
|
||||
let getActiveApiSession: ReturnType<typeof vi.fn>;
|
||||
|
||||
vi.mock("@hivegrid/db/device-tokens.server", () => ({
|
||||
parseDevicePlatform: (value: unknown) => {
|
||||
return value === "web" ? value : null;
|
||||
},
|
||||
parsePushProvider: (value: unknown) => {
|
||||
return value === "webpush" ? value : null;
|
||||
},
|
||||
async registerDeviceToken(input: { userId: string; tenantId: string | null; platform: "web"; token: string; pushProvider?: "webpush"; appVersion?: string | null }) {
|
||||
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) {
|
||||
existing.userId = input.userId;
|
||||
if (existing.userId !== input.userId) {
|
||||
throw new Error("token owner mismatch");
|
||||
}
|
||||
existing.tenantId = input.tenantId;
|
||||
existing.platform = input.platform;
|
||||
existing.pushProvider = provider;
|
||||
@@ -44,9 +70,11 @@ vi.mock("@hivegrid/db/device-tokens.server", () => ({
|
||||
mockStore.set(input.token, row);
|
||||
return row;
|
||||
},
|
||||
async revokeDeviceToken(token: string) {
|
||||
const row = mockStore.get(token);
|
||||
if (!row) return null;
|
||||
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;
|
||||
},
|
||||
@@ -63,113 +91,255 @@ beforeEach(() => {
|
||||
setApiRuntimeConfigForTests({
|
||||
apiAccessToken: TEST_TOKEN,
|
||||
jwtSecret: "jwt",
|
||||
routing: { appBaseDomain: "example.com", webAppHost: "app.example.com", adminAppHost: "admin.example.com", apiHost: "api.example.com", protocol: "https" },
|
||||
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<typeof buildApp>, body: unknown, auth: string | null = `Bearer ${TEST_TOKEN}`) {
|
||||
function postRegister(
|
||||
app: ReturnType<typeof buildApp>,
|
||||
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<typeof buildApp>,
|
||||
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 service credentials", async () => {
|
||||
const app = buildApp();
|
||||
const response = await postRegister(app, {}, null);
|
||||
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 app = buildApp();
|
||||
const response = await app.request("/v1/devices/register", {
|
||||
const response = await buildApp().request("/v1/devices/register", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", authorization: `Bearer ${TEST_TOKEN}` },
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
authorization: `Bearer ${createTestApiSessionToken()}`,
|
||||
},
|
||||
body: "not-json",
|
||||
});
|
||||
expect(response.status).toBe(400);
|
||||
});
|
||||
|
||||
it("rejects missing userId", async () => {
|
||||
const app = buildApp();
|
||||
const response = await postRegister(app, { platform: "web", token: "t" });
|
||||
expect(response.status).toBe(400);
|
||||
const json = (await response.json()) as { error: { params: { field: string } } };
|
||||
expect(json.error.params.field).toBe("userId");
|
||||
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 platform", async () => {
|
||||
it("rejects unknown platforms and missing tokens", async () => {
|
||||
const app = buildApp();
|
||||
const response = await postRegister(app, { userId: "u1", platform: "wear", token: "t" });
|
||||
expect(response.status).toBe(400);
|
||||
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("rejects missing token", async () => {
|
||||
const app = buildApp();
|
||||
const response = await postRegister(app, { userId: "u1", platform: "web" });
|
||||
expect(response.status).toBe(400);
|
||||
const json = (await response.json()) as { error: { params: { field: string } } };
|
||||
expect(json.error.params.field).toBe("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("upserts a valid registration and defaults the push provider", async () => {
|
||||
const app = buildApp();
|
||||
const response = await postRegister(app, {
|
||||
userId: "u-1",
|
||||
tenantId: "t-1",
|
||||
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",
|
||||
appVersion: "1.2.3",
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const json = (await response.json()) as { success: boolean; data: { pushProvider: string; platform: string; appVersion: string | null } };
|
||||
expect(json.success).toBe(true);
|
||||
expect(json.data.platform).toBe("web");
|
||||
expect(json.data.pushProvider).toBe("webpush");
|
||||
expect(json.data.appVersion).toBe("1.2.3");
|
||||
expect(mockStore.size).toBe(1);
|
||||
expect(revalidateWorkspaceContext).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: TEST_USER_ID });
|
||||
expect(findLegacyAuthUserById).toHaveBeenCalledWith(TEST_USER_ID);
|
||||
});
|
||||
|
||||
it("is idempotent: re-registering the same token bumps lastSeenAt without duplicating", async () => {
|
||||
it("keeps same-owner registration idempotent without duplicating rows", async () => {
|
||||
const app = buildApp();
|
||||
await postRegister(app, { userId: "u-1", tenantId: null, platform: "web", token: "tok-x" });
|
||||
const second = await postRegister(app, { userId: "u-1", tenantId: null, platform: "web", token: "tok-x" });
|
||||
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.size).toBe(1);
|
||||
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("revokes a known token", async () => {
|
||||
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, { userId: "u-1", platform: "web", token: "tok-a" });
|
||||
const response = await app.request("/v1/devices/revoke", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", authorization: `Bearer ${TEST_TOKEN}` },
|
||||
body: JSON.stringify({ token: "tok-a" }),
|
||||
});
|
||||
await postRegister(app, { platform: "web", token: "tok-a" });
|
||||
const response = await postRevoke(app, { token: "tok-a" });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const json = (await response.json()) as { data: { revokedAt: string | null } };
|
||||
expect(json.data.revokedAt).not.toBeNull();
|
||||
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 app = buildApp();
|
||||
const response = await app.request("/v1/devices/revoke", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", authorization: `Bearer ${TEST_TOKEN}` },
|
||||
body: JSON.stringify({ token: "missing" }),
|
||||
});
|
||||
const response = await postRevoke(buildApp(), { token: "missing" });
|
||||
expect(response.status).toBe(404);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user