Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+71
@@ -0,0 +1,71 @@
|
||||
import type { Extension, onAuthenticatePayload } from "@hocuspocus/server";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createAuthExtension } from "./auth.js";
|
||||
|
||||
const SECRET = "extension-secret-please-rotate-in-prod-min-32-bytes";
|
||||
const DOC = "tenant_x:kb-article:art_9";
|
||||
|
||||
function payload(token: string, documentName = DOC): onAuthenticatePayload {
|
||||
// The hook only reads `token` + `documentName`; the rest of the Hocuspocus
|
||||
// payload is irrelevant to the auth decision, so a minimal cast is honest here.
|
||||
return { token, documentName } as unknown as onAuthenticatePayload;
|
||||
}
|
||||
|
||||
function sign(claims: Record<string, unknown>, secret = SECRET): string {
|
||||
return jwt.sign(claims, secret, { algorithm: "HS256", expiresIn: 60 });
|
||||
}
|
||||
|
||||
function authenticate(ext: Extension, p: onAuthenticatePayload): Promise<unknown> {
|
||||
const fn = ext.onAuthenticate;
|
||||
if (!fn) throw new Error("auth extension is missing onAuthenticate hook");
|
||||
return fn(p);
|
||||
}
|
||||
|
||||
const matchingClaims = {
|
||||
userId: "user_1",
|
||||
tenantId: "tenant_x",
|
||||
resourceType: "kb-article",
|
||||
resourceId: "art_9",
|
||||
};
|
||||
|
||||
describe("createAuthExtension onAuthenticate", () => {
|
||||
it("resolves the connection context for a token whose claims match the document name", async () => {
|
||||
const ext = createAuthExtension({ secret: SECRET });
|
||||
await expect(authenticate(ext, payload(sign(matchingClaims)))).resolves.toEqual({
|
||||
userId: "user_1",
|
||||
tenantId: "tenant_x",
|
||||
resourceType: "kb-article",
|
||||
resourceId: "art_9",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects the connection when token claims point at a different tenant", async () => {
|
||||
const ext = createAuthExtension({ secret: SECRET });
|
||||
const token = sign({ ...matchingClaims, tenantId: "tenant_other" });
|
||||
await expect(authenticate(ext, payload(token))).rejects.toThrow("hocuspocus: authentication refused");
|
||||
});
|
||||
|
||||
it("rejects the connection when the token is signed with the wrong secret", async () => {
|
||||
const ext = createAuthExtension({ secret: SECRET });
|
||||
const token = sign(matchingClaims, "a-different-server-secret");
|
||||
await expect(authenticate(ext, payload(token))).rejects.toThrow("hocuspocus: authentication refused");
|
||||
});
|
||||
|
||||
it("refuses every connection when the server secret is empty (mis-configured deploy)", async () => {
|
||||
const ext = createAuthExtension({ secret: "" });
|
||||
// Even a token signed with the real secret must be refused — an empty
|
||||
// server secret must never silently fall through to anonymous collaboration.
|
||||
await expect(authenticate(ext, payload(sign(matchingClaims)))).rejects.toThrow(
|
||||
"hocuspocus: authentication refused",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects the connection for a malformed document name", async () => {
|
||||
const ext = createAuthExtension({ secret: SECRET });
|
||||
await expect(authenticate(ext, payload(sign(matchingClaims), "not-a-valid-doc-name"))).rejects.toThrow(
|
||||
"hocuspocus: authentication refused",
|
||||
);
|
||||
});
|
||||
});
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
import type { Extension } from "@hocuspocus/server";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createDatabaseExtension, type DatabaseExtensionDeps } from "./database.js";
|
||||
|
||||
type CollabRow = {
|
||||
tenantId: string;
|
||||
resourceType: string;
|
||||
resourceId: string;
|
||||
ydocState: Buffer;
|
||||
version: number;
|
||||
lastUpdatedAt: Date;
|
||||
};
|
||||
|
||||
type CompositeKey = { tenantId_resourceType_resourceId: { tenantId: string; resourceType: string; resourceId: string } };
|
||||
|
||||
function createStubDb() {
|
||||
const rows = new Map<string, CollabRow>();
|
||||
const keyOf = (k: CompositeKey["tenantId_resourceType_resourceId"]): string =>
|
||||
`${k.tenantId}:${k.resourceType}:${k.resourceId}`;
|
||||
|
||||
const findUnique = vi.fn(async ({ where }: { where: CompositeKey; select?: unknown }) => {
|
||||
const row = rows.get(keyOf(where.tenantId_resourceType_resourceId));
|
||||
return row ? { ydocState: row.ydocState } : null;
|
||||
});
|
||||
|
||||
const upsert = vi.fn(
|
||||
async ({
|
||||
where,
|
||||
create,
|
||||
update,
|
||||
}: {
|
||||
where: CompositeKey;
|
||||
create: CollabRow;
|
||||
update: { ydocState: Buffer; version: { increment: number }; lastUpdatedAt: Date };
|
||||
}) => {
|
||||
const key = keyOf(where.tenantId_resourceType_resourceId);
|
||||
const existing = rows.get(key);
|
||||
if (existing) {
|
||||
existing.ydocState = update.ydocState;
|
||||
existing.version += update.version.increment;
|
||||
existing.lastUpdatedAt = update.lastUpdatedAt;
|
||||
return existing;
|
||||
}
|
||||
rows.set(key, { ...create });
|
||||
return create;
|
||||
},
|
||||
);
|
||||
|
||||
return { rows, findUnique, upsert, db: { collabDoc: { findUnique, upsert } } };
|
||||
}
|
||||
|
||||
function buildDeps(maxPayloadBytes = 1024) {
|
||||
const stub = createStubDb();
|
||||
const deps: DatabaseExtensionDeps = {
|
||||
db: stub.db as unknown as DatabaseExtensionDeps["db"],
|
||||
maxPayloadBytes,
|
||||
clock: () => new Date("2026-06-01T00:00:00Z"),
|
||||
};
|
||||
return { deps, ...stub };
|
||||
}
|
||||
|
||||
// The wired `fetch`/`store` callbacks the factory hands to the Hocuspocus
|
||||
// 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>;
|
||||
};
|
||||
|
||||
function configOf(ext: Extension): WiredConfig {
|
||||
return (ext as unknown as { configuration: WiredConfig }).configuration;
|
||||
}
|
||||
|
||||
describe("createDatabaseExtension", () => {
|
||||
it("returns a Hocuspocus database extension exposing the document lifecycle hooks", () => {
|
||||
const { deps } = buildDeps();
|
||||
const ext = createDatabaseExtension(deps) as unknown as {
|
||||
onLoadDocument: unknown;
|
||||
onStoreDocument: unknown;
|
||||
};
|
||||
expect(typeof ext.onLoadDocument).toBe("function");
|
||||
expect(typeof ext.onStoreDocument).toBe("function");
|
||||
});
|
||||
|
||||
it("wires fetch to load persisted Y.js state by document name", async () => {
|
||||
const { deps, rows, findUnique } = buildDeps();
|
||||
rows.set("tenant_x:kb-article:art_9", {
|
||||
tenantId: "tenant_x",
|
||||
resourceType: "kb-article",
|
||||
resourceId: "art_9",
|
||||
ydocState: Buffer.from([5, 6, 7]),
|
||||
version: 3,
|
||||
lastUpdatedAt: new Date(),
|
||||
});
|
||||
|
||||
const ext = createDatabaseExtension(deps);
|
||||
const result = await configOf(ext).fetch({ documentName: "tenant_x:kb-article:art_9" });
|
||||
|
||||
expect(result).toBeInstanceOf(Uint8Array);
|
||||
expect(Array.from(result ?? [])).toEqual([5, 6, 7]);
|
||||
expect(findUnique).toHaveBeenCalledWith({
|
||||
where: { tenantId_resourceType_resourceId: { tenantId: "tenant_x", resourceType: "kb-article", resourceId: "art_9" } },
|
||||
select: { ydocState: true },
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
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]) });
|
||||
|
||||
expect(upsert).toHaveBeenCalledTimes(1);
|
||||
const stored = rows.get("tenant_x:kb-article:art_9");
|
||||
expect(stored?.version).toBe(1);
|
||||
expect(Array.from(stored?.ydocState ?? new Uint8Array())).toEqual([8, 8]);
|
||||
});
|
||||
|
||||
it("propagates the max-payload guard from the wired store callback", async () => {
|
||||
const { deps, upsert } = buildDeps(4);
|
||||
const ext = createDatabaseExtension(deps);
|
||||
|
||||
await expect(
|
||||
configOf(ext).store({ documentName: "tenant_x:kb-article:art_9", state: new Uint8Array(16) }),
|
||||
).rejects.toThrow(/exceeds HOCUSPOCUS_MAX_PAYLOAD_BYTES/);
|
||||
expect(upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back to a real-time clock for lastUpdatedAt when no clock hook is injected", async () => {
|
||||
// Omit the `clock` dep so the default `() => new Date()` branch runs and
|
||||
// stamps lastUpdatedAt with the actual current time.
|
||||
const stub = createStubDb();
|
||||
const deps: DatabaseExtensionDeps = {
|
||||
db: stub.db as unknown as DatabaseExtensionDeps["db"],
|
||||
maxPayloadBytes: 1024,
|
||||
};
|
||||
const ext = createDatabaseExtension(deps);
|
||||
|
||||
const before = Date.now();
|
||||
await configOf(ext).store({ documentName: "tenant_x:kb-article:art_9", state: new Uint8Array([1]) });
|
||||
const after = Date.now();
|
||||
|
||||
const stamped = stub.rows.get("tenant_x:kb-article:art_9")?.lastUpdatedAt;
|
||||
expect(stamped).toBeInstanceOf(Date);
|
||||
expect(stamped?.getTime()).toBeGreaterThanOrEqual(before);
|
||||
expect(stamped?.getTime()).toBeLessThanOrEqual(after);
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,7 @@
|
||||
*/
|
||||
import { Database } from "@hocuspocus/extension-database";
|
||||
import type { Extension } from "@hocuspocus/server";
|
||||
import type { DbClient } from "@toolctrl/db/client.server";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
import { parseDocumentName } from "./auth.js";
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ const mocks = vi.hoisted(() => {
|
||||
|
||||
vi.mock("@hocuspocus/server", () => ({ Server: mocks.MockServer }));
|
||||
vi.mock("@hocuspocus/extension-logger", () => ({ Logger: mocks.MockLogger }));
|
||||
vi.mock("@toolctrl/db/client.server", () => ({ getWriteDbClient: mocks.getWriteDbClient }));
|
||||
vi.mock("@hivegrid/db/client.server", () => ({ getWriteDbClient: mocks.getWriteDbClient }));
|
||||
vi.mock("./config.js", () => ({ getHocuspocusRuntimeConfig: mocks.getHocuspocusRuntimeConfig }));
|
||||
vi.mock("./extensions/auth.js", () => ({ createAuthExtension: mocks.createAuthExtension }));
|
||||
vi.mock("./extensions/database.js", () => ({ createDatabaseExtension: mocks.createDatabaseExtension }));
|
||||
@@ -100,7 +100,7 @@ describe("hocuspocus entrypoint", () => {
|
||||
address: "127.0.0.1",
|
||||
debounce: 2000,
|
||||
maxDebounce: 10000,
|
||||
name: "toolctrl-hocuspocus",
|
||||
name: "hivegrid-hocuspocus",
|
||||
port: 4321,
|
||||
quiet: true,
|
||||
timeout: 30000,
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
*/
|
||||
import { Server } from "@hocuspocus/server";
|
||||
import { Logger } from "@hocuspocus/extension-logger";
|
||||
import { getWriteDbClient } from "@toolctrl/db/client.server";
|
||||
import { getWriteDbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
import { getHocuspocusRuntimeConfig } from "./config.js";
|
||||
import { createAuthExtension } from "./extensions/auth.js";
|
||||
@@ -27,7 +27,7 @@ async function main(): Promise<void> {
|
||||
}
|
||||
|
||||
const server = new Server({
|
||||
name: "toolctrl-hocuspocus",
|
||||
name: "hivegrid-hocuspocus",
|
||||
port: config.port,
|
||||
address: config.host,
|
||||
timeout: 30_000,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Mock the shared logger package so we can assert how logger.ts wires the
|
||||
// child logger without depending on pino's stdout transport.
|
||||
const mocks = vi.hoisted(() => {
|
||||
const childLogger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), child: vi.fn() };
|
||||
return {
|
||||
childLogger,
|
||||
defaultLogger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), child: vi.fn() },
|
||||
createChildLogger: vi.fn(() => childLogger),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@hivegrid/logger", () => ({
|
||||
defaultLogger: mocks.defaultLogger,
|
||||
createChildLogger: mocks.createChildLogger,
|
||||
}));
|
||||
|
||||
describe("hocuspocusLogger", () => {
|
||||
it("derives from the default logger and binds the hocuspocus component label", async () => {
|
||||
const { hocuspocusLogger } = await import("./logger.js");
|
||||
|
||||
// The binding must carry the `component` label so Loki/Grafana can filter
|
||||
// this service's lines out of the shared estate stream.
|
||||
expect(mocks.createChildLogger).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.createChildLogger).toHaveBeenCalledWith(mocks.defaultLogger, { component: "hocuspocus" });
|
||||
expect(hocuspocusLogger).toBe(mocks.childLogger);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,3 @@
|
||||
import { createChildLogger, defaultLogger } from "@toolctrl/logger";
|
||||
import { createChildLogger, defaultLogger } from "@hivegrid/logger";
|
||||
|
||||
export const hocuspocusLogger = createChildLogger(defaultLogger, { component: "hocuspocus" });
|
||||
Reference in new issue
Block a user