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
@@ -3,6 +3,8 @@ import { describe, expect, it } from "vitest";
|
||||
import { getHocuspocusRuntimeConfig } from "./config.js";
|
||||
|
||||
describe("getHocuspocusRuntimeConfig", () => {
|
||||
const primarySecret = "hocuspocus-secret-at-least-32-bytes-long";
|
||||
const legacySecret = "legacy-hocuspocus-secret-at-least-32-bytes";
|
||||
it("uses production-safe defaults when optional env is absent", () => {
|
||||
expect(getHocuspocusRuntimeConfig({})).toEqual({
|
||||
port: 1234,
|
||||
@@ -17,15 +19,15 @@ describe("getHocuspocusRuntimeConfig", () => {
|
||||
getHocuspocusRuntimeConfig({
|
||||
HOCUSPOCUS_PORT: "4321",
|
||||
HOCUSPOCUS_HOST: " 127.0.0.1 ",
|
||||
HOCUSPOCUS_AUTH_SECRET: " hocuspocus-secret ",
|
||||
HOCUSPOCUS_SECRET: "legacy-secret",
|
||||
HOCUSPOCUS_AUTH_SECRET: ` ${primarySecret} `,
|
||||
HOCUSPOCUS_SECRET: legacySecret,
|
||||
HOCUSPOCUS_MAX_PAYLOAD_BYTES: "2048",
|
||||
PORT: "9999",
|
||||
})
|
||||
).toEqual({
|
||||
port: 4321,
|
||||
host: "127.0.0.1",
|
||||
authSecret: "hocuspocus-secret",
|
||||
authSecret: primarySecret,
|
||||
maxPayloadBytes: 2048,
|
||||
});
|
||||
});
|
||||
@@ -34,16 +36,31 @@ describe("getHocuspocusRuntimeConfig", () => {
|
||||
expect(
|
||||
getHocuspocusRuntimeConfig({
|
||||
PORT: "2345",
|
||||
HOCUSPOCUS_SECRET: " legacy-secret ",
|
||||
HOCUSPOCUS_SECRET: ` ${legacySecret} `,
|
||||
})
|
||||
).toEqual({
|
||||
port: 2345,
|
||||
host: "0.0.0.0",
|
||||
authSecret: "legacy-secret",
|
||||
authSecret: legacySecret,
|
||||
maxPayloadBytes: 10 * 1024 * 1024,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects short secrets and invalid numeric bounds", () => {
|
||||
expect(
|
||||
getHocuspocusRuntimeConfig({
|
||||
HOCUSPOCUS_AUTH_SECRET: "too-short",
|
||||
HOCUSPOCUS_MAX_PAYLOAD_BYTES: "-1",
|
||||
HOCUSPOCUS_PORT: "70000",
|
||||
}),
|
||||
).toEqual({
|
||||
authSecret: null,
|
||||
host: "0.0.0.0",
|
||||
maxPayloadBytes: 10 * 1024 * 1024,
|
||||
port: 1234,
|
||||
});
|
||||
});
|
||||
|
||||
it("treats blank host and blank secrets as absent", () => {
|
||||
expect(
|
||||
getHocuspocusRuntimeConfig({
|
||||
|
||||
@@ -11,10 +11,29 @@ export type HocuspocusRuntimeConfig = {
|
||||
readonly maxPayloadBytes: number;
|
||||
};
|
||||
|
||||
export const HOCUSPOCUS_MIN_AUTH_SECRET_BYTES = 32;
|
||||
const DEFAULT_MAX_PAYLOAD_BYTES = 10 * 1024 * 1024;
|
||||
const MAX_MAX_PAYLOAD_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
function parsePort(raw: string | undefined): number {
|
||||
const value = Number(raw ?? 1234);
|
||||
return Number.isInteger(value) && value >= 1 && value <= 65_535 ? value : 1234;
|
||||
}
|
||||
|
||||
function parseMaxPayloadBytes(raw: string | undefined): number {
|
||||
const value = Number(raw ?? DEFAULT_MAX_PAYLOAD_BYTES);
|
||||
return Number.isInteger(value) && value >= 1024 && value <= MAX_MAX_PAYLOAD_BYTES ? value : DEFAULT_MAX_PAYLOAD_BYTES;
|
||||
}
|
||||
|
||||
function parseAuthSecret(env: NodeJS.ProcessEnv): string | null {
|
||||
const secret = env.HOCUSPOCUS_AUTH_SECRET?.trim() || env.HOCUSPOCUS_SECRET?.trim() || "";
|
||||
return Buffer.byteLength(secret, "utf8") >= HOCUSPOCUS_MIN_AUTH_SECRET_BYTES ? secret : null;
|
||||
}
|
||||
|
||||
export function getHocuspocusRuntimeConfig(env: NodeJS.ProcessEnv = process.env): HocuspocusRuntimeConfig {
|
||||
const port = Number(env.HOCUSPOCUS_PORT ?? env.PORT ?? 1234);
|
||||
const port = parsePort(env.HOCUSPOCUS_PORT ?? env.PORT);
|
||||
const host = env.HOCUSPOCUS_HOST?.trim() || "0.0.0.0";
|
||||
const authSecret = env.HOCUSPOCUS_AUTH_SECRET?.trim() || env.HOCUSPOCUS_SECRET?.trim() || null;
|
||||
const maxPayloadBytes = Number(env.HOCUSPOCUS_MAX_PAYLOAD_BYTES ?? 10 * 1024 * 1024);
|
||||
const authSecret = parseAuthSecret(env);
|
||||
const maxPayloadBytes = parseMaxPayloadBytes(env.HOCUSPOCUS_MAX_PAYLOAD_BYTES);
|
||||
return Object.freeze({ port, host, authSecret, maxPayloadBytes });
|
||||
}
|
||||
+7
-2
@@ -2,7 +2,7 @@ import type { Extension, onAuthenticatePayload } from "@hocuspocus/server";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createAuthExtension } from "./auth.js";
|
||||
import { COLLAB_TOKEN_AUDIENCE, COLLAB_TOKEN_ISSUER, createAuthExtension } from "./auth.js";
|
||||
|
||||
const SECRET = "extension-secret-please-rotate-in-prod-min-32-bytes";
|
||||
const DOC = "tenant_x:kb-article:art_9";
|
||||
@@ -14,7 +14,12 @@ function payload(token: string, documentName = DOC): onAuthenticatePayload {
|
||||
}
|
||||
|
||||
function sign(claims: Record<string, unknown>, secret = SECRET): string {
|
||||
return jwt.sign(claims, secret, { algorithm: "HS256", expiresIn: 60 });
|
||||
return jwt.sign(claims, secret, {
|
||||
algorithm: "HS256",
|
||||
audience: COLLAB_TOKEN_AUDIENCE,
|
||||
expiresIn: 60,
|
||||
issuer: COLLAB_TOKEN_ISSUER,
|
||||
});
|
||||
}
|
||||
|
||||
function authenticate(ext: Extension, p: onAuthenticatePayload): Promise<unknown> {
|
||||
|
||||
+47
-3
@@ -1,12 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
import { parseDocumentName, verifyCollabToken } from "./auth.js";
|
||||
import { COLLAB_TOKEN_AUDIENCE, COLLAB_TOKEN_ISSUER, parseDocumentName, verifyCollabToken } from "./auth.js";
|
||||
|
||||
const SECRET = "test-secret-please-rotate-in-prod-min-32-bytes";
|
||||
|
||||
function signToken(claims: Record<string, unknown>, expiresInSeconds = 60): string {
|
||||
return jwt.sign(claims, SECRET, { algorithm: "HS256", expiresIn: expiresInSeconds });
|
||||
return jwt.sign(claims, SECRET, {
|
||||
algorithm: "HS256",
|
||||
audience: COLLAB_TOKEN_AUDIENCE,
|
||||
expiresIn: expiresInSeconds,
|
||||
issuer: COLLAB_TOKEN_ISSUER,
|
||||
});
|
||||
}
|
||||
|
||||
describe("parseDocumentName", () => {
|
||||
@@ -31,6 +36,8 @@ describe("parseDocumentName", () => {
|
||||
expect(parseDocumentName("tenant_only")).toBeNull();
|
||||
expect(parseDocumentName("tenant:type")).toBeNull();
|
||||
expect(parseDocumentName(":kb:art")).toBeNull();
|
||||
expect(parseDocumentName("tenant name:kb:art")).toBeNull();
|
||||
expect(parseDocumentName(`tenant:kb:${"x".repeat(257)}`)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,7 +56,12 @@ describe("verifyCollabToken", () => {
|
||||
});
|
||||
|
||||
it("refuses tokens signed with a different secret", () => {
|
||||
const token = jwt.sign({ userId: "u", tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_123" }, "other-secret", { algorithm: "HS256" });
|
||||
const token = jwt.sign({ userId: "u", tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_123" }, "other-secret", {
|
||||
algorithm: "HS256",
|
||||
audience: COLLAB_TOKEN_AUDIENCE,
|
||||
expiresIn: 60,
|
||||
issuer: COLLAB_TOKEN_ISSUER,
|
||||
});
|
||||
expect(verifyCollabToken(token, docName, { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -78,6 +90,38 @@ describe("verifyCollabToken", () => {
|
||||
expect(verifyCollabToken(token, docName, { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses otherwise valid tokens without an expiry", () => {
|
||||
const token = jwt.sign(
|
||||
{ userId: "u", tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_123" },
|
||||
SECRET,
|
||||
{ algorithm: "HS256", audience: COLLAB_TOKEN_AUDIENCE, issuer: COLLAB_TOKEN_ISSUER },
|
||||
);
|
||||
expect(verifyCollabToken(token, docName, { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses tokens for another issuer or audience", () => {
|
||||
const claims = { userId: "u", tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_123" };
|
||||
const wrongIssuer = jwt.sign(claims, SECRET, {
|
||||
algorithm: "HS256",
|
||||
audience: COLLAB_TOKEN_AUDIENCE,
|
||||
expiresIn: 60,
|
||||
issuer: "other-service",
|
||||
});
|
||||
const wrongAudience = jwt.sign(claims, SECRET, {
|
||||
algorithm: "HS256",
|
||||
audience: "other-service",
|
||||
expiresIn: 60,
|
||||
issuer: COLLAB_TOKEN_ISSUER,
|
||||
});
|
||||
expect(verifyCollabToken(wrongIssuer, docName, { secret: SECRET })).toBeNull();
|
||||
expect(verifyCollabToken(wrongAudience, docName, { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses tokens whose declared lifetime exceeds the issuer contract", () => {
|
||||
const token = signToken({ userId: "u", tenantId: "tenant_abc", resourceType: "kb-article", resourceId: "art_123" }, 3600);
|
||||
expect(verifyCollabToken(token, docName, { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses missing or empty token", () => {
|
||||
expect(verifyCollabToken("", docName, { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -34,6 +34,13 @@ export type AuthExtensionOptions = {
|
||||
readonly clockTolerance?: number;
|
||||
};
|
||||
|
||||
export const COLLAB_TOKEN_ISSUER = "hivegrid-web";
|
||||
export const COLLAB_TOKEN_AUDIENCE = "hivegrid-hocuspocus";
|
||||
export const COLLAB_TOKEN_MAX_TTL_SECONDS = 15 * 60;
|
||||
const DOCUMENT_NAME_MAX_LENGTH = 3 * 256 + 2;
|
||||
const DOCUMENT_NAME_PART_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/u;
|
||||
const RESOURCE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/u;
|
||||
|
||||
/**
|
||||
* Parse `tenantId:resourceType:resourceId` document-name into its parts.
|
||||
* Returns `null` for malformed names — caller refuses the connection.
|
||||
@@ -43,13 +50,16 @@ export function parseDocumentName(documentName: string): {
|
||||
resourceType: string;
|
||||
resourceId: string;
|
||||
} | null {
|
||||
if (typeof documentName !== "string" || documentName.length === 0) return null;
|
||||
if (typeof documentName !== "string" || documentName.length === 0 || documentName.length > DOCUMENT_NAME_MAX_LENGTH) return null;
|
||||
// resourceId may itself contain `:` (e.g. namespaced slugs); split into 3 parts only.
|
||||
const parts = documentName.split(":");
|
||||
if (parts.length < 3) return null;
|
||||
const [tenantId, resourceType, ...rest] = parts;
|
||||
const resourceId = rest.join(":");
|
||||
if (!tenantId || !resourceType || !resourceId) return null;
|
||||
if (!DOCUMENT_NAME_PART_PATTERN.test(tenantId) || !DOCUMENT_NAME_PART_PATTERN.test(resourceType) || !RESOURCE_ID_PATTERN.test(resourceId)) {
|
||||
return null;
|
||||
}
|
||||
return { tenantId, resourceType, resourceId };
|
||||
}
|
||||
|
||||
@@ -59,6 +69,8 @@ type TokenClaims = {
|
||||
tenantId?: string;
|
||||
resourceType?: string;
|
||||
resourceId?: string;
|
||||
exp?: number;
|
||||
iat?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -78,7 +90,10 @@ export function verifyCollabToken(
|
||||
try {
|
||||
claims = jwt.verify(token, options.secret, {
|
||||
algorithms: ["HS256"],
|
||||
audience: COLLAB_TOKEN_AUDIENCE,
|
||||
clockTolerance: options.clockTolerance ?? 30,
|
||||
issuer: COLLAB_TOKEN_ISSUER,
|
||||
maxAge: `${COLLAB_TOKEN_MAX_TTL_SECONDS}s`,
|
||||
}) as TokenClaims;
|
||||
} catch {
|
||||
return null;
|
||||
@@ -86,6 +101,8 @@ export function verifyCollabToken(
|
||||
|
||||
const userId = claims.userId ?? claims.sub;
|
||||
if (!userId || typeof userId !== "string") return null;
|
||||
if (!Number.isInteger(claims.iat) || !Number.isInteger(claims.exp)) return null;
|
||||
if ((claims.exp as number) <= (claims.iat as number) || (claims.exp as number) - (claims.iat as number) > COLLAB_TOKEN_MAX_TTL_SECONDS) return null;
|
||||
if (claims.tenantId !== parsed.tenantId) return null;
|
||||
if (claims.resourceType !== parsed.resourceType) return null;
|
||||
if (claims.resourceId !== parsed.resourceId) return null;
|
||||
|
||||
+62
-7
@@ -2,6 +2,7 @@ import type { Extension } from "@hocuspocus/server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createDatabaseExtension, type DatabaseExtensionDeps } from "./database.js";
|
||||
import type { HocuspocusConnectionContext } from "./auth.js";
|
||||
|
||||
type CollabRow = {
|
||||
tenantId: string;
|
||||
@@ -64,8 +65,15 @@ function buildDeps(maxPayloadBytes = 1024) {
|
||||
// Database extension are stored on its `configuration`. Reaching in lets us
|
||||
// prove the factory delegates to fetchCollabDoc / storeCollabDoc.
|
||||
type WiredConfig = {
|
||||
fetch: (data: { documentName: string }) => Promise<Uint8Array | null>;
|
||||
store: (data: { documentName: string; state: Uint8Array }) => Promise<void>;
|
||||
fetch: (data: { context: HocuspocusConnectionContext; documentName: string }) => Promise<Uint8Array | null>;
|
||||
store: (data: { documentName: string; lastContext: HocuspocusConnectionContext; state: Uint8Array }) => Promise<void>;
|
||||
};
|
||||
|
||||
const authenticatedContext: HocuspocusConnectionContext = {
|
||||
userId: "user_1",
|
||||
tenantId: "tenant_x",
|
||||
resourceType: "kb-article",
|
||||
resourceId: "art_9",
|
||||
};
|
||||
|
||||
function configOf(ext: Extension): WiredConfig {
|
||||
@@ -95,7 +103,10 @@ describe("createDatabaseExtension", () => {
|
||||
});
|
||||
|
||||
const ext = createDatabaseExtension(deps);
|
||||
const result = await configOf(ext).fetch({ documentName: "tenant_x:kb-article:art_9" });
|
||||
const result = await configOf(ext).fetch({
|
||||
context: authenticatedContext,
|
||||
documentName: "tenant_x:kb-article:art_9",
|
||||
});
|
||||
|
||||
expect(result).toBeInstanceOf(Uint8Array);
|
||||
expect(Array.from(result ?? [])).toEqual([5, 6, 7]);
|
||||
@@ -108,14 +119,23 @@ describe("createDatabaseExtension", () => {
|
||||
it("wires fetch to return null when the document has no row yet", async () => {
|
||||
const { deps } = buildDeps();
|
||||
const ext = createDatabaseExtension(deps);
|
||||
expect(await configOf(ext).fetch({ documentName: "tenant_x:kb-article:missing" })).toBeNull();
|
||||
expect(
|
||||
await configOf(ext).fetch({
|
||||
context: { ...authenticatedContext, resourceId: "missing" },
|
||||
documentName: "tenant_x:kb-article:missing",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("wires store to upsert the Y.js state under the parsed composite key", async () => {
|
||||
const { deps, rows, upsert } = buildDeps();
|
||||
const ext = createDatabaseExtension(deps);
|
||||
|
||||
await configOf(ext).store({ documentName: "tenant_x:kb-article:art_9", state: new Uint8Array([8, 8]) });
|
||||
await configOf(ext).store({
|
||||
documentName: "tenant_x:kb-article:art_9",
|
||||
lastContext: authenticatedContext,
|
||||
state: new Uint8Array([8, 8]),
|
||||
});
|
||||
|
||||
expect(upsert).toHaveBeenCalledTimes(1);
|
||||
const stored = rows.get("tenant_x:kb-article:art_9");
|
||||
@@ -128,7 +148,11 @@ describe("createDatabaseExtension", () => {
|
||||
const ext = createDatabaseExtension(deps);
|
||||
|
||||
await expect(
|
||||
configOf(ext).store({ documentName: "tenant_x:kb-article:art_9", state: new Uint8Array(16) }),
|
||||
configOf(ext).store({
|
||||
documentName: "tenant_x:kb-article:art_9",
|
||||
lastContext: authenticatedContext,
|
||||
state: new Uint8Array(16),
|
||||
}),
|
||||
).rejects.toThrow(/exceeds HOCUSPOCUS_MAX_PAYLOAD_BYTES/);
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -144,7 +168,11 @@ describe("createDatabaseExtension", () => {
|
||||
const ext = createDatabaseExtension(deps);
|
||||
|
||||
const before = Date.now();
|
||||
await configOf(ext).store({ documentName: "tenant_x:kb-article:art_9", state: new Uint8Array([1]) });
|
||||
await configOf(ext).store({
|
||||
documentName: "tenant_x:kb-article:art_9",
|
||||
lastContext: authenticatedContext,
|
||||
state: new Uint8Array([1]),
|
||||
});
|
||||
const after = Date.now();
|
||||
|
||||
const stamped = stub.rows.get("tenant_x:kb-article:art_9")?.lastUpdatedAt;
|
||||
@@ -152,4 +180,31 @@ describe("createDatabaseExtension", () => {
|
||||
expect(stamped?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
expect(stamped?.getTime()).toBeLessThanOrEqual(after);
|
||||
});
|
||||
|
||||
it("does not let the document name substitute for an authenticated fetch context", async () => {
|
||||
const { deps, findUnique } = buildDeps();
|
||||
const ext = createDatabaseExtension(deps);
|
||||
|
||||
await expect(
|
||||
configOf(ext).fetch({
|
||||
context: { ...authenticatedContext, tenantId: "tenant_other" },
|
||||
documentName: "tenant_x:kb-article:art_9",
|
||||
}),
|
||||
).rejects.toThrow("hocuspocus: authenticated document context required");
|
||||
expect(findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not persist a debounced update without the last authenticated connection context", async () => {
|
||||
const { deps, upsert } = buildDeps();
|
||||
const ext = createDatabaseExtension(deps);
|
||||
|
||||
await expect(
|
||||
configOf(ext).store({
|
||||
documentName: "tenant_x:kb-article:art_9",
|
||||
lastContext: undefined as unknown as HocuspocusConnectionContext,
|
||||
state: new Uint8Array([1]),
|
||||
}),
|
||||
).rejects.toThrow("hocuspocus: authenticated document context required");
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+50
-13
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { fetchCollabDoc, storeCollabDoc, type DatabaseExtensionDeps } from "./database.js";
|
||||
import type { HocuspocusConnectionContext } from "./auth.js";
|
||||
|
||||
type StubCollabRow = {
|
||||
tenantId: string;
|
||||
@@ -55,16 +57,26 @@ function buildDeps(): { deps: DatabaseExtensionDeps; rows: Map<string, StubColla
|
||||
};
|
||||
}
|
||||
|
||||
function context(
|
||||
tenantId = "t",
|
||||
resourceType = "kb-article",
|
||||
resourceId = "art_1",
|
||||
): HocuspocusConnectionContext {
|
||||
return { userId: "user_1", tenantId, resourceType, resourceId };
|
||||
}
|
||||
|
||||
describe("fetchCollabDoc", () => {
|
||||
it("returns null when no row exists for the document", async () => {
|
||||
const { deps } = buildDeps();
|
||||
const result = await fetchCollabDoc("t:kb-article:art_1", deps);
|
||||
const result = await fetchCollabDoc("t:kb-article:art_1", context(), deps);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for malformed document names", async () => {
|
||||
it("refuses malformed document names instead of treating the name as authority", async () => {
|
||||
const { deps } = buildDeps();
|
||||
expect(await fetchCollabDoc("malformed", deps)).toBeNull();
|
||||
await expect(fetchCollabDoc("malformed", context(), deps)).rejects.toThrow(
|
||||
"hocuspocus: authenticated document context required",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns a Uint8Array when the row exists", async () => {
|
||||
@@ -77,16 +89,24 @@ describe("fetchCollabDoc", () => {
|
||||
version: 7,
|
||||
lastUpdatedAt: new Date(),
|
||||
});
|
||||
const result = await fetchCollabDoc("t:kb-article:art_1", deps);
|
||||
const result = await fetchCollabDoc("t:kb-article:art_1", context(), deps);
|
||||
expect(result).toBeInstanceOf(Uint8Array);
|
||||
expect(Array.from(result ?? [])).toEqual([1, 2, 3, 4]);
|
||||
});
|
||||
|
||||
it("refuses a document name that does not match the authenticated connection context", async () => {
|
||||
const { deps } = buildDeps();
|
||||
|
||||
await expect(
|
||||
fetchCollabDoc("tenant_b:kb-article:art_1", context("tenant_a"), deps),
|
||||
).rejects.toThrow("hocuspocus: authenticated document context required");
|
||||
});
|
||||
});
|
||||
|
||||
describe("storeCollabDoc", () => {
|
||||
it("inserts a new row on first store", async () => {
|
||||
const { deps, rows } = buildDeps();
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([9, 9, 9]), deps);
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([9, 9, 9]), context(), deps);
|
||||
const row = rows.get("t:kb-article:art_1");
|
||||
expect(row).toBeDefined();
|
||||
expect(row?.version).toBe(1);
|
||||
@@ -95,9 +115,9 @@ describe("storeCollabDoc", () => {
|
||||
|
||||
it("increments version on subsequent stores", async () => {
|
||||
const { deps, rows } = buildDeps();
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([1]), deps);
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([2]), deps);
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([3]), deps);
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([1]), context(), deps);
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([2]), context(), deps);
|
||||
await storeCollabDoc("t:kb-article:art_1", new Uint8Array([3]), context(), deps);
|
||||
expect(rows.get("t:kb-article:art_1")?.version).toBe(3);
|
||||
expect(Array.from(rows.get("t:kb-article:art_1")?.ydocState ?? new Uint8Array())).toEqual([3]);
|
||||
});
|
||||
@@ -105,21 +125,38 @@ describe("storeCollabDoc", () => {
|
||||
it("refuses payloads exceeding maxPayloadBytes", async () => {
|
||||
const { deps } = buildDeps();
|
||||
const large = new Uint8Array(2048);
|
||||
await expect(storeCollabDoc("t:kb:art_1", large, deps)).rejects.toThrow(/exceeds HOCUSPOCUS_MAX_PAYLOAD_BYTES/);
|
||||
await expect(storeCollabDoc("t:kb:art_1", large, context("t", "kb"), deps)).rejects.toThrow(
|
||||
/exceeds HOCUSPOCUS_MAX_PAYLOAD_BYTES/,
|
||||
);
|
||||
});
|
||||
|
||||
it("is a no-op for malformed document names", async () => {
|
||||
it("refuses a store without authenticated document context", async () => {
|
||||
const { deps, rows } = buildDeps();
|
||||
await storeCollabDoc("malformed", new Uint8Array([1]), deps);
|
||||
await expect(
|
||||
storeCollabDoc("t:kb-article:art_1", new Uint8Array([1]), undefined, deps),
|
||||
).rejects.toThrow("hocuspocus: authenticated document context required");
|
||||
expect(rows.size).toBe(0);
|
||||
});
|
||||
|
||||
it("isolates tenants — same resourceType/Id under different tenant gets its own row", async () => {
|
||||
const { deps, rows } = buildDeps();
|
||||
await storeCollabDoc("tenant_a:kb:art_1", new Uint8Array([1]), deps);
|
||||
await storeCollabDoc("tenant_b:kb:art_1", new Uint8Array([2]), deps);
|
||||
await storeCollabDoc("tenant_a:kb:art_1", new Uint8Array([1]), context("tenant_a", "kb"), deps);
|
||||
await storeCollabDoc("tenant_b:kb:art_1", new Uint8Array([2]), context("tenant_b", "kb"), deps);
|
||||
expect(rows.size).toBe(2);
|
||||
expect(Array.from(rows.get("tenant_a:kb:art_1")?.ydocState ?? new Uint8Array())).toEqual([1]);
|
||||
expect(Array.from(rows.get("tenant_b:kb:art_1")?.ydocState ?? new Uint8Array())).toEqual([2]);
|
||||
});
|
||||
|
||||
it("binds the authenticated user and tenant while the persistence query runs", async () => {
|
||||
const { deps } = buildDeps();
|
||||
const upsert = deps.db.collabDoc.upsert as unknown as ReturnType<typeof vi.fn>;
|
||||
upsert.mockImplementationOnce(async () => {
|
||||
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_a", userId: "user_1" });
|
||||
return {};
|
||||
});
|
||||
|
||||
await storeCollabDoc("tenant_a:kb:art_1", new Uint8Array([1]), context("tenant_a", "kb"), deps);
|
||||
|
||||
expect(getRlsExecutionContext()).toBeNull();
|
||||
});
|
||||
});
|
||||
+84
-43
@@ -10,18 +10,18 @@
|
||||
* Hocuspocus per the server-level
|
||||
* `debounce` / `maxDebounce` settings.
|
||||
*
|
||||
* The DocumentName is parsed via `parseDocumentName()` (see auth.ts) and is
|
||||
* authoritative for the `(tenantId, resourceType, resourceId)` triple. Auth
|
||||
* has already verified that the connection has access to this triple; here
|
||||
* we just persist the bytes.
|
||||
* The authenticated connection context is authoritative for the
|
||||
* `(tenantId, resourceType, resourceId)` triple. The document name is checked
|
||||
* against that context but is never trusted as an authorization source.
|
||||
*
|
||||
* Refs: docs/improvement-plan/05-business-features/realtime-collab.md
|
||||
*/
|
||||
import { Database } from "@hocuspocus/extension-database";
|
||||
import type { Extension } from "@hocuspocus/server";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { parseDocumentName } from "./auth.js";
|
||||
import { parseDocumentName, type HocuspocusConnectionContext } from "./auth.js";
|
||||
|
||||
export type DatabaseExtensionDeps = {
|
||||
/** Prisma client (write-able). */
|
||||
@@ -34,22 +34,57 @@ export type DatabaseExtensionDeps = {
|
||||
readonly clock?: () => Date;
|
||||
};
|
||||
|
||||
function requireAuthenticatedDocumentContext(
|
||||
documentName: string,
|
||||
context: unknown,
|
||||
): HocuspocusConnectionContext {
|
||||
const parsed = parseDocumentName(documentName);
|
||||
if (
|
||||
!parsed ||
|
||||
typeof context !== "object" ||
|
||||
context === null ||
|
||||
!("userId" in context) ||
|
||||
typeof context.userId !== "string" ||
|
||||
context.userId.length === 0 ||
|
||||
!("tenantId" in context) ||
|
||||
context.tenantId !== parsed.tenantId ||
|
||||
!("resourceType" in context) ||
|
||||
context.resourceType !== parsed.resourceType ||
|
||||
!("resourceId" in context) ||
|
||||
context.resourceId !== parsed.resourceId
|
||||
) {
|
||||
throw new Error("hocuspocus: authenticated document context required");
|
||||
}
|
||||
|
||||
return {
|
||||
userId: context.userId,
|
||||
tenantId: parsed.tenantId,
|
||||
resourceType: parsed.resourceType,
|
||||
resourceId: parsed.resourceId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal `fetch` implementation — exported for unit-testing.
|
||||
*/
|
||||
export async function fetchCollabDoc(documentName: string, deps: DatabaseExtensionDeps): Promise<Uint8Array | null> {
|
||||
const parsed = parseDocumentName(documentName);
|
||||
if (!parsed) return null;
|
||||
const row = await deps.db.collabDoc.findUnique({
|
||||
where: {
|
||||
tenantId_resourceType_resourceId: {
|
||||
tenantId: parsed.tenantId,
|
||||
resourceType: parsed.resourceType,
|
||||
resourceId: parsed.resourceId,
|
||||
export async function fetchCollabDoc(
|
||||
documentName: string,
|
||||
context: unknown,
|
||||
deps: DatabaseExtensionDeps,
|
||||
): Promise<Uint8Array | null> {
|
||||
const identity = requireAuthenticatedDocumentContext(documentName, context);
|
||||
const row = await runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, () =>
|
||||
deps.db.collabDoc.findUnique({
|
||||
where: {
|
||||
tenantId_resourceType_resourceId: {
|
||||
tenantId: identity.tenantId,
|
||||
resourceType: identity.resourceType,
|
||||
resourceId: identity.resourceId,
|
||||
},
|
||||
},
|
||||
},
|
||||
select: { ydocState: true },
|
||||
});
|
||||
select: { ydocState: true },
|
||||
}),
|
||||
);
|
||||
if (!row) return null;
|
||||
// Prisma returns `Buffer` for Bytes columns — wrap to Uint8Array for Y.js.
|
||||
return new Uint8Array(row.ydocState);
|
||||
@@ -58,9 +93,13 @@ export async function fetchCollabDoc(documentName: string, deps: DatabaseExtensi
|
||||
/**
|
||||
* Internal `store` implementation — exported for unit-testing.
|
||||
*/
|
||||
export async function storeCollabDoc(documentName: string, state: Uint8Array, deps: DatabaseExtensionDeps): Promise<void> {
|
||||
const parsed = parseDocumentName(documentName);
|
||||
if (!parsed) return;
|
||||
export async function storeCollabDoc(
|
||||
documentName: string,
|
||||
state: Uint8Array,
|
||||
context: unknown,
|
||||
deps: DatabaseExtensionDeps,
|
||||
): Promise<void> {
|
||||
const identity = requireAuthenticatedDocumentContext(documentName, context);
|
||||
if (state.byteLength > deps.maxPayloadBytes) {
|
||||
throw new Error(
|
||||
`hocuspocus: refusing to persist Y.js state of ${state.byteLength} bytes — exceeds HOCUSPOCUS_MAX_PAYLOAD_BYTES=${deps.maxPayloadBytes}`,
|
||||
@@ -68,28 +107,30 @@ export async function storeCollabDoc(documentName: string, state: Uint8Array, de
|
||||
}
|
||||
const now = (deps.clock ?? (() => new Date()))();
|
||||
const buffer = Buffer.from(state);
|
||||
await deps.db.collabDoc.upsert({
|
||||
where: {
|
||||
tenantId_resourceType_resourceId: {
|
||||
tenantId: parsed.tenantId,
|
||||
resourceType: parsed.resourceType,
|
||||
resourceId: parsed.resourceId,
|
||||
await runWithRlsContext({ tenantId: identity.tenantId, userId: identity.userId }, () =>
|
||||
deps.db.collabDoc.upsert({
|
||||
where: {
|
||||
tenantId_resourceType_resourceId: {
|
||||
tenantId: identity.tenantId,
|
||||
resourceType: identity.resourceType,
|
||||
resourceId: identity.resourceId,
|
||||
},
|
||||
},
|
||||
},
|
||||
create: {
|
||||
tenantId: parsed.tenantId,
|
||||
resourceType: parsed.resourceType,
|
||||
resourceId: parsed.resourceId,
|
||||
ydocState: buffer,
|
||||
version: 1,
|
||||
lastUpdatedAt: now,
|
||||
},
|
||||
update: {
|
||||
ydocState: buffer,
|
||||
version: { increment: 1 },
|
||||
lastUpdatedAt: now,
|
||||
},
|
||||
});
|
||||
create: {
|
||||
tenantId: identity.tenantId,
|
||||
resourceType: identity.resourceType,
|
||||
resourceId: identity.resourceId,
|
||||
ydocState: buffer,
|
||||
version: 1,
|
||||
lastUpdatedAt: now,
|
||||
},
|
||||
update: {
|
||||
ydocState: buffer,
|
||||
version: { increment: 1 },
|
||||
lastUpdatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,7 +138,7 @@ export async function storeCollabDoc(documentName: string, state: Uint8Array, de
|
||||
*/
|
||||
export function createDatabaseExtension(deps: DatabaseExtensionDeps): Extension {
|
||||
return new Database({
|
||||
fetch: async ({ documentName }) => fetchCollabDoc(documentName, deps),
|
||||
store: async ({ documentName, state }) => storeCollabDoc(documentName, state, deps),
|
||||
fetch: async ({ context, documentName }) => fetchCollabDoc(documentName, context, deps),
|
||||
store: async ({ documentName, lastContext, state }) => storeCollabDoc(documentName, state, lastContext, deps),
|
||||
}) as unknown as Extension;
|
||||
}
|
||||
@@ -30,6 +30,7 @@ const mocks = vi.hoisted(() => {
|
||||
MockLogger,
|
||||
MockServer,
|
||||
authExtension: { name: "auth-extension" },
|
||||
assertRlsRuntimeReady: vi.fn(async () => undefined),
|
||||
createAuthExtension: vi.fn(),
|
||||
createDatabaseExtension: vi.fn(),
|
||||
databaseExtension: { name: "database-extension" },
|
||||
@@ -47,6 +48,7 @@ const mocks = vi.hoisted(() => {
|
||||
vi.mock("@hocuspocus/server", () => ({ Server: mocks.MockServer }));
|
||||
vi.mock("@hocuspocus/extension-logger", () => ({ Logger: mocks.MockLogger }));
|
||||
vi.mock("@hivegrid/db/client.server", () => ({ getWriteDbClient: mocks.getWriteDbClient }));
|
||||
vi.mock("@hivegrid/db/rls-runtime-readiness.server", () => ({ assertRlsRuntimeReady: mocks.assertRlsRuntimeReady }));
|
||||
vi.mock("./config.js", () => ({ getHocuspocusRuntimeConfig: mocks.getHocuspocusRuntimeConfig }));
|
||||
vi.mock("./extensions/auth.js", () => ({ createAuthExtension: mocks.createAuthExtension }));
|
||||
vi.mock("./extensions/database.js", () => ({ createDatabaseExtension: mocks.createDatabaseExtension }));
|
||||
@@ -67,6 +69,7 @@ describe("hocuspocus entrypoint", () => {
|
||||
mocks.listen.mockResolvedValue(undefined);
|
||||
mocks.createAuthExtension.mockReturnValue(mocks.authExtension);
|
||||
mocks.createDatabaseExtension.mockReturnValue(mocks.databaseExtension);
|
||||
mocks.assertRlsRuntimeReady.mockResolvedValue(undefined);
|
||||
mocks.getWriteDbClient.mockReturnValue(mocks.dbClient);
|
||||
mocks.getHocuspocusRuntimeConfig.mockReturnValue({
|
||||
authSecret: "collab-secret",
|
||||
@@ -89,7 +92,13 @@ describe("hocuspocus entrypoint", () => {
|
||||
|
||||
it("boots a standalone Hocuspocus server with auth and database extensions", async () => {
|
||||
await import("./index.js");
|
||||
await vi.waitFor(() => expect(mocks.listen).toHaveBeenCalledTimes(1));
|
||||
|
||||
expect(mocks.assertRlsRuntimeReady).toHaveBeenCalledWith(
|
||||
[mocks.dbClient],
|
||||
expect.objectContaining({ DATABASE_RUNTIME_ROLE: "hivegrid_app" }),
|
||||
);
|
||||
expect(mocks.assertRlsRuntimeReady.mock.invocationCallOrder[0]).toBeLessThan(mocks.listen.mock.invocationCallOrder[0] as number);
|
||||
expect(mocks.createAuthExtension).toHaveBeenCalledWith({ secret: "collab-secret" });
|
||||
expect(mocks.createDatabaseExtension).toHaveBeenCalledWith({
|
||||
db: mocks.dbClient,
|
||||
@@ -100,10 +109,14 @@ describe("hocuspocus entrypoint", () => {
|
||||
address: "127.0.0.1",
|
||||
debounce: 2000,
|
||||
maxDebounce: 10000,
|
||||
maxPendingDocuments: 2,
|
||||
maxUnauthenticatedQueueMessages: 8,
|
||||
maxUnauthenticatedQueueSize: 4096,
|
||||
name: "hivegrid-hocuspocus",
|
||||
port: 4321,
|
||||
quiet: true,
|
||||
timeout: 30000,
|
||||
websocketOptions: { maxPayload: 4096 },
|
||||
});
|
||||
expect(mocks.MockServer.instances[0]?.listen).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.hocuspocusLogger.info).toHaveBeenCalledWith({ port: 4321, host: "127.0.0.1" }, "hocuspocus listening");
|
||||
@@ -111,6 +124,7 @@ describe("hocuspocus entrypoint", () => {
|
||||
|
||||
it("wires Hocuspocus extension logs into the app logger", async () => {
|
||||
await import("./index.js");
|
||||
await vi.waitFor(() => expect(mocks.listen).toHaveBeenCalledTimes(1));
|
||||
|
||||
const options = mocks.MockServer.instances[0]?.options as { extensions: Array<{ options?: { log?: (message: string) => void } }> };
|
||||
const loggerExtension = options.extensions[0];
|
||||
@@ -131,6 +145,20 @@ describe("hocuspocus entrypoint", () => {
|
||||
|
||||
expect(mocks.hocuspocusLogger.error).toHaveBeenCalledWith("HOCUSPOCUS_AUTH_SECRET is not set — refusing to boot");
|
||||
expect(processExit).toHaveBeenCalledWith(1);
|
||||
expect(mocks.assertRlsRuntimeReady).not.toHaveBeenCalled();
|
||||
expect(mocks.listen).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses to create or listen on the server when app-role RLS readiness fails", async () => {
|
||||
const error = new Error("RLS runtime readiness failed");
|
||||
mocks.assertRlsRuntimeReady.mockRejectedValueOnce(error);
|
||||
|
||||
await import("./index.js");
|
||||
await vi.waitFor(() => expect(mocks.hocuspocusLogger.error).toHaveBeenCalledWith({ err: error }, "hocuspocus failed to start"));
|
||||
|
||||
expect(mocks.MockServer.instances).toHaveLength(0);
|
||||
expect(mocks.listen).not.toHaveBeenCalled();
|
||||
expect(processExit).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it("logs startup failures and exits non-zero", async () => {
|
||||
@@ -138,6 +166,7 @@ describe("hocuspocus entrypoint", () => {
|
||||
mocks.listen.mockRejectedValueOnce(error);
|
||||
|
||||
await import("./index.js");
|
||||
await vi.waitFor(() => expect(mocks.hocuspocusLogger.error).toHaveBeenCalledWith({ err: error }, "hocuspocus failed to start"));
|
||||
|
||||
expect(mocks.hocuspocusLogger.error).toHaveBeenCalledWith({ err: error }, "hocuspocus failed to start");
|
||||
expect(processExit).toHaveBeenCalledWith(1);
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
import { Server } from "@hocuspocus/server";
|
||||
import { Logger } from "@hocuspocus/extension-logger";
|
||||
import { getWriteDbClient } from "@hivegrid/db/client.server";
|
||||
import { assertRlsRuntimeReady } from "@hivegrid/db/rls-runtime-readiness.server";
|
||||
|
||||
import { getHocuspocusRuntimeConfig } from "./config.js";
|
||||
import { createAuthExtension } from "./extensions/auth.js";
|
||||
@@ -24,8 +25,15 @@ async function main(): Promise<void> {
|
||||
if (!config.authSecret) {
|
||||
hocuspocusLogger.error("HOCUSPOCUS_AUTH_SECRET is not set — refusing to boot");
|
||||
process.exit(1);
|
||||
return;
|
||||
}
|
||||
|
||||
const db = getWriteDbClient();
|
||||
await assertRlsRuntimeReady([db], {
|
||||
...process.env,
|
||||
DATABASE_RUNTIME_ROLE: "hivegrid_app",
|
||||
});
|
||||
|
||||
const server = new Server({
|
||||
name: "hivegrid-hocuspocus",
|
||||
port: config.port,
|
||||
@@ -33,7 +41,11 @@ async function main(): Promise<void> {
|
||||
timeout: 30_000,
|
||||
debounce: 2_000,
|
||||
maxDebounce: 10_000,
|
||||
maxPendingDocuments: 2,
|
||||
maxUnauthenticatedQueueMessages: 8,
|
||||
maxUnauthenticatedQueueSize: Math.min(config.maxPayloadBytes, 64 * 1024),
|
||||
quiet: true,
|
||||
websocketOptions: { maxPayload: config.maxPayloadBytes },
|
||||
extensions: [
|
||||
new Logger({
|
||||
log: (message) => {
|
||||
@@ -42,7 +54,7 @@ async function main(): Promise<void> {
|
||||
}),
|
||||
createAuthExtension({ secret: config.authSecret }),
|
||||
createDatabaseExtension({
|
||||
db: getWriteDbClient(),
|
||||
db,
|
||||
maxPayloadBytes: config.maxPayloadBytes,
|
||||
}),
|
||||
],
|
||||
|
||||
Reference in new issue
Block a user