Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -14,7 +14,7 @@
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@toolctrl/db": "workspace:*"
"@hivegrid/db": "workspace:*"
},
"devDependencies": {
"@types/node": "^25.0.0",
@@ -1,5 +1,5 @@
import { getDbClient } from "@toolctrl/db/client.server";
import type { Prisma } from "@toolctrl/db/prisma-browser";
import { getDbClient } from "@hivegrid/db/client.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import type { LogActivityInput } from "./types.js";
/**
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import type { Prisma } from "@toolctrl/db/prisma-browser";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { logActivity, type ActivityWriteClient } from "./logActivity.server.js";
import type { LogActivityInput } from "./types.js";
@@ -24,21 +24,40 @@ export type ActivityType =
| "assignee_changed"
| "deal_stage_changed"
| "project_stage_changed"
| "project_member_added"
| "project_appointment_created"
| "project_invoice_created"
| "project_invoice_status_changed"
| "project_checklist_created"
| "project_schedule_changed"
| "project_acceptance_submitted"
| "project_signature_changed"
| "file_uploaded"
| "form_submitted"
| "task_created"
| "task_completed"
| "appointment_scheduled"
| "appointment_held"
| "contact_created" // P6 CRM core (R-P6)
| "contact_updated" // P6 CRM core (R-P6)
| "contact_archived" // P6 CRM core (R-P6)
| "appointment_scheduled" // P16 Booking (AK-P16b)
| "appointment_held" // P16 Booking (AK-P16b)
| "appointment_cancelled" // P16 Booking (AK-P16b)
| "appointment_rescheduled" // P16 Booking (AK-P16b)
| "appointment_no_show" // P16 Booking (AK-P16b)
| "lead_created" // P7 Lead-Inbox (R-P7)
| "lead_updated" // P7 Lead-Inbox (R-P7)
| "lead_qualified" // P7 Lead-Inbox (R-P7)
| "status_changed" // P7 Lead-Inbox (R-P7)
| "lead_promoted"
| "deal_won"
| "deal_lost"
| "automation_triggered"
| "ki_action"
| "audit_event";
| "audit_event"
| "billing_state_changed";
/** Main object a stream hangs off (DoD #14: Kontakt/Firma/Lead/Verkaufsfall/Auftrag …). */
export type ActivitySubjectType = "contact" | "company" | "lead" | "deal" | "project" | "task";
export type ActivitySubjectType = "contact" | "company" | "lead" | "deal" | "project" | "task" | "tenant";
/** Additional entities referenced by an activity (denormalized for the timeline). */
export type ActivityRelatedRef = { type: ActivitySubjectType; id: string };
@@ -1,6 +1,6 @@
# @toolctrl/api-client-ts
# @hivegrid/api-client-ts
Official TypeScript SDK for the toolctrl boilerplate REST API.
Official TypeScript SDK for the HiveGrid REST API.
The SDK couples a `@hey-api/openapi-ts`-generated typed client with a hand-written
Higher-Level-Wrapper that adds:
@@ -14,12 +14,12 @@ Higher-Level-Wrapper that adds:
## Quickstart
```ts
import { createToolctrlClient } from "@toolctrl/api-client-ts";
import { createHiveGridClient } from "@hivegrid/api-client-ts";
const client = createToolctrlClient({
baseUrl: "https://api.toolctrl.de",
auth: { apiKey: process.env.TOOLCTRL_API_KEY! },
tenantId: process.env.TOOLCTRL_TENANT_ID,
const client = createHiveGridClient({
baseUrl: "https://api.hivegrid.de",
auth: { apiKey: process.env.HIVEGRID_API_KEY! },
tenantId: process.env.HIVEGRID_TENANT_ID,
});
const me = await client.request({ method: "GET", path: "/v1/me" });
@@ -35,7 +35,7 @@ The `src/generated/` directory is produced from the upstream OpenAPI document
checked into this package as `openapi.json`. Regenerate with:
```bash
pnpm --filter @toolctrl/api-client-ts generate:all
pnpm --filter @hivegrid/api-client-ts generate:all
```
The CI workflow `.github/workflows/sdk-codegen.yml` rejects PRs whose generated
@@ -6,10 +6,10 @@
* `src/generated/`.
*
* Run via:
* pnpm --filter @toolctrl/api-client-ts generate
* pnpm --filter @hivegrid/api-client-ts generate
*
* The full pipeline (capture spec → generate client) is:
* pnpm --filter @toolctrl/api-client-ts generate:all
* pnpm --filter @hivegrid/api-client-ts generate:all
*
* Refs: docs/improvement-plan/08-mobile-cli-storybook-sdk/ts-sdk.md
*/
@@ -21,7 +21,7 @@ import { defineConfig } from "@hey-api/openapi-ts";
*
* The `zod` plugin is intentionally omitted. The latest @hey-api/openapi-ts
* emits `z.iso.*`, `z.email()`, `z.int()`, and `z.url()` calls that require
* zod v4, while the wider toolctrl workspace is pinned to zod v3 via
* zod v4, while the wider hivegrid workspace is pinned to zod v3 via
* pnpm overrides. The generated TypeScript types and fetch SDK are
* sufficient for the Higher-Level-Wrapper in `src/client.ts`, which performs
* its own runtime validation policy (idempotency, retry) outside of zod.
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,8 @@
{
"name": "@toolctrl/api-client-ts",
"name": "@hivegrid/api-client-ts",
"version": "0.1.0",
"private": true,
"description": "Official TypeScript SDK for the toolctrl boilerplate REST API. Generated from the upstream OpenAPI spec with @hey-api/openapi-ts and wrapped with auth, retry, idempotency, pagination, and webhook-verify helpers.",
"description": "Official TypeScript SDK for the HiveGrid REST API. Generated from the upstream OpenAPI spec with @hey-api/openapi-ts and wrapped with auth, retry, idempotency, pagination, and webhook-verify helpers.",
"type": "module",
"sideEffects": false,
"exports": {
@@ -29,7 +29,7 @@
},
"devDependencies": {
"@hey-api/openapi-ts": "0.97.1",
"@toolctrl/api": "workspace:*",
"@hivegrid/api": "workspace:*",
"@types/node": "^25.0.0",
"tsup": "^8.5.1",
"tsx": "^4.6.2",
@@ -1,15 +1,15 @@
#!/usr/bin/env tsx
/**
* generate-spec — capture the boilerplate's OpenAPI document into a local file.
* generate-spec — capture the HiveGrid OpenAPI document into a local file.
*
* Invokes the headless `createOpenApiDocument` factory from `@toolctrl/api` and
* Invokes the headless `createOpenApiDocument` factory from `@hivegrid/api` and
* writes the result to `packages/api-client-ts/openapi.json`. This file feeds
* `@hey-api/openapi-ts` (see `openapi-ts.config.ts`) which then regenerates
* `src/generated/`.
*
* Usage:
* pnpm --filter @toolctrl/api-client-ts generate-spec
* pnpm --filter @toolctrl/api-client-ts generate-spec -- --check
* pnpm --filter @hivegrid/api-client-ts generate-spec
* pnpm --filter @hivegrid/api-client-ts generate-spec -- --check
*
* `--check` re-runs the generation and exits non-zero if the on-disk
* `openapi.json` would change — useful as a CI drift gate.
@@ -21,7 +21,7 @@ import { writeFileSync, readFileSync, existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { createOpenApiDocument } from "@toolctrl/api/openapi";
import { createOpenApiDocument } from "@hivegrid/api/openapi";
const here = dirname(fileURLToPath(import.meta.url));
const outputPath = resolve(here, "..", "openapi.json");
@@ -30,7 +30,7 @@ function buildSpec(): string {
const document = createOpenApiDocument({
routing: {
protocol: "https",
apiHost: "api.toolctrl.de",
apiHost: "api.hivegrid.de",
} as never,
});
return `${JSON.stringify(document, null, 2)}\n`;
@@ -42,14 +42,14 @@ function main(): void {
if (checkMode) {
if (!existsSync(outputPath)) {
process.stderr.write(`openapi.json missing at ${outputPath} — run \`pnpm --filter @toolctrl/api-client-ts generate-spec\`.\n`);
process.stderr.write(`openapi.json missing at ${outputPath} — run \`pnpm --filter @hivegrid/api-client-ts generate-spec\`.\n`);
process.exit(1);
}
const current = readFileSync(outputPath, "utf8");
if (current !== next) {
process.stderr.write(
`openapi.json is stale — the upstream OpenAPI document has changed.\n` +
`Run \`pnpm --filter @toolctrl/api-client-ts generate:all\` and commit the result.\n`,
`Run \`pnpm --filter @hivegrid/api-client-ts generate:all\` and commit the result.\n`,
);
process.exit(2);
}
@@ -0,0 +1,298 @@
import { describe, it, expect } from "vitest";
import { createHiveGridClient } from "./client.js";
// Local copies of the helpers used by client.test.ts — kept identical so the new
// suite stays independent of the existing test file (no shared-fixture edits).
function mockFetchSequence(responses: Array<Response | Error>): typeof fetch {
let index = 0;
return (async () => {
const next = responses[index++];
if (next === undefined) {
throw new Error("mock fetch exhausted");
}
if (next instanceof Error) throw next;
return next;
}) as unknown as typeof fetch;
}
function jsonResponse(status: number, body: unknown, headers: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json", ...headers },
});
}
function textResponse(status: number, body: string, headers: Record<string, string> = {}): Response {
return new Response(body, { status, headers });
}
describe("createHiveGridClient — request body parsing", () => {
it("returns parsed text when the response is not JSON", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: mockFetchSequence([textResponse(200, "plain-pong", { "content-type": "text/plain" })]),
});
const result = await client.request<string>({ method: "GET", path: "/v1/ping" });
expect(result).toBe("plain-pong");
});
it("returns null for an empty non-JSON body", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: mockFetchSequence([textResponse(200, "")]),
});
const result = await client.request({ method: "GET", path: "/v1/empty" });
expect(result).toBeNull();
});
it("returns null when a JSON content-type carries an unparseable body", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: mockFetchSequence([textResponse(200, "{not-valid-json", { "content-type": "application/json" })]),
});
const result = await client.request({ method: "GET", path: "/v1/broken" });
expect(result).toBeNull();
});
});
describe("createHiveGridClient — idempotency edge cases", () => {
it("forwards a caller idempotency key on a non-mutating method", async () => {
const captured: { headers: Headers | null } = { headers: null };
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
captured.headers = init.headers as Headers;
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
await client.request({ method: "GET", path: "/v1/items", idempotencyKey: "explicit-get-key" });
// GET never auto-generates, but an explicit key must still be honored.
expect(captured.headers!.get("idempotency-key")).toBe("explicit-get-key");
});
});
describe("createHiveGridClient — URL building", () => {
it("uses an absolute path verbatim instead of prefixing the base url", async () => {
const captured: { url: string | null } = { url: null };
const stub: typeof fetch = (async (url: string) => {
captured.url = url;
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
await client.request({ method: "GET", path: "https://other.example.test/v2/thing" });
expect(captured.url).toBe("https://other.example.test/v2/thing");
});
it("skips undefined query values while serializing the rest", async () => {
const captured: { url: string | null } = { url: null };
const stub: typeof fetch = (async (url: string) => {
captured.url = url;
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
await client.request({ method: "GET", path: "/v1/items", query: { a: 1, b: undefined, c: true } });
const parsed = new URL(captured.url!);
expect(parsed.searchParams.get("a")).toBe("1");
expect(parsed.searchParams.get("c")).toBe("true");
expect(parsed.searchParams.has("b")).toBe(false);
});
});
describe("createHiveGridClient — Retry-After handling", () => {
it("honors an HTTP-date Retry-After header, capped by maxDelayMs", async () => {
const future = new Date(Date.now() + 60_000).toUTCString();
const t0 = Date.now();
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 3, baseDelayMs: 1000, maxDelayMs: 5 },
fetch: mockFetchSequence([jsonResponse(429, { error: "rate" }, { "retry-after": future }), jsonResponse(200, { ok: true })]),
});
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
expect(result.ok).toBe(true);
// The 60s date must be clamped to the 5ms maxDelay, not waited out in full.
expect(Date.now() - t0).toBeLessThan(1000);
});
it("falls back to exponential backoff when Retry-After is unparseable", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
fetch: mockFetchSequence([jsonResponse(503, { error: "down" }, { "retry-after": "soon-ish" }), jsonResponse(200, { ok: true })]),
});
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
expect(result.ok).toBe(true);
});
it("treats a past HTTP-date Retry-After as a zero delay", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 2, baseDelayMs: 1000, maxDelayMs: 1000 },
fetch: mockFetchSequence([
jsonResponse(429, { error: "rate" }, { "retry-after": "Thu, 01 Jan 1970 00:00:00 GMT" }),
jsonResponse(200, { ok: true }),
]),
});
const t0 = Date.now();
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
expect(result.ok).toBe(true);
expect(Date.now() - t0).toBeLessThan(500);
});
});
describe("createHiveGridClient — network retry recovery", () => {
it("retries a transient network error and then succeeds", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
fetch: mockFetchSequence([new Error("ECONNRESET"), jsonResponse(200, { ok: true })]),
});
const result = await client.request<{ ok: boolean }>({ method: "GET", path: "/v1/ping" });
expect(result.ok).toBe(true);
});
});
describe("createHiveGridClient — error message extraction", () => {
it("falls back to `HTTP <status>` when the error body has no message", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 1 },
fetch: mockFetchSequence([jsonResponse(400, { error: {} })]),
});
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
name: "HiveGridApiError",
status: 400,
message: "HTTP 400",
});
});
it("falls back to `HTTP <status>` when `error` is not an object", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 1 },
fetch: mockFetchSequence([jsonResponse(422, { error: "validation failed" })]),
});
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
status: 422,
message: "HTTP 422",
});
});
it("uses `HTTP <status>` for a non-JSON error body and omits a missing requestId", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 1 },
fetch: mockFetchSequence([textResponse(500, "internal boom", { "content-type": "text/plain" })]),
});
await expect(client.request({ method: "GET", path: "/v1/x" })).rejects.toMatchObject({
status: 500,
message: "HTTP 500",
body: "internal boom",
requestId: undefined,
});
});
});
describe("createHiveGridClient — pagination edge cases", () => {
it("follows nextPageToken cursors", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: mockFetchSequence([
jsonResponse(200, { data: [{ id: "a" }], nextPageToken: "tok-2" }),
jsonResponse(200, { data: [{ id: "b" }], nextPageToken: null }),
]),
});
const ids: string[] = [];
for await (const item of client.paginate<{ id: string }>("/v1/items")) {
ids.push(item.id);
}
expect(ids).toEqual(["a", "b"]);
});
it("stops cleanly when a page returns a null body", async () => {
let calls = 0;
const stub: typeof fetch = (async () => {
calls += 1;
// JSON literal null → readBody returns null → request resolves null.
return textResponse(200, "null", { "content-type": "application/json" });
}) as unknown as typeof fetch;
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
const items: unknown[] = [];
for await (const item of client.paginate("/v1/items")) items.push(item);
expect(items).toEqual([]);
expect(calls).toBe(1);
});
it("yields nothing when `data` is not an array", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: mockFetchSequence([jsonResponse(200, { data: { not: "an-array" } })]),
});
const items: unknown[] = [];
for await (const item of client.paginate("/v1/items")) items.push(item);
expect(items).toEqual([]);
});
it("breaks on an empty page even when a next cursor is present (safety stop)", async () => {
let calls = 0;
const stub: typeof fetch = (async () => {
calls += 1;
// A server that keeps advertising a cursor but never returns rows must not loop forever.
return jsonResponse(200, { data: [], nextCursor: "always-more" });
}) as unknown as typeof fetch;
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
const items: unknown[] = [];
for await (const item of client.paginate("/v1/items")) items.push(item);
expect(items).toEqual([]);
expect(calls).toBe(1);
});
it("respects the maxPages safety cap", async () => {
let calls = 0;
const stub: typeof fetch = (async () => {
calls += 1;
return jsonResponse(200, { data: [{ id: calls }], nextCursor: `c-${calls}` });
}) as unknown as typeof fetch;
const client = createHiveGridClient({ baseUrl: "https://api.example.com", fetch: stub });
const items: Array<{ id: number }> = [];
for await (const item of client.paginate<{ id: number }>("/v1/items", { maxPages: 3 })) {
items.push(item);
}
expect(items).toHaveLength(3);
expect(calls).toBe(3);
});
});
describe("createHiveGridClient — refreshAuth", () => {
it("refreshes and caches the bearer token via the configured getter", async () => {
let issued = 0;
const captured: Array<string | null> = [];
const stub: typeof fetch = (async (_url: unknown, init: RequestInit) => {
captured.push((init.headers as Headers).get("authorization"));
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
auth: { getToken: async () => `jwt-${++issued}` },
fetch: stub,
});
await client.refreshAuth();
expect(issued).toBe(1);
// The getter is re-invoked per request, so the next call advances the counter.
await client.request({ method: "GET", path: "/v1/me" });
expect(captured).toEqual(["Bearer jwt-2"]);
});
it("is a no-op when no token getter is configured", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
auth: { apiKey: "ak_123" },
fetch: mockFetchSequence([]),
});
await expect(client.refreshAuth()).resolves.toBeUndefined();
});
});
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { createToolctrlClient, ToolctrlApiError, ToolctrlNetworkError } from "./client.js";
import { createHiveGridClient, HiveGridApiError, HiveGridNetworkError } from "./client.js";
function mockFetchSequence(responses: Array<Response | Error>): typeof fetch {
let index = 0;
@@ -20,13 +20,13 @@ function jsonResponse(status: number, body: unknown, headers: Record<string, str
});
}
describe("createToolctrlClient", () => {
describe("createHiveGridClient", () => {
it("rejects when baseUrl is missing", () => {
expect(() => createToolctrlClient({ baseUrl: "" } as never)).toThrow(/baseUrl/);
expect(() => createHiveGridClient({ baseUrl: "" } as never)).toThrow(/baseUrl/);
});
it("strips trailing slashes from the base url", () => {
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com///",
fetch: mockFetchSequence([jsonResponse(200, { ok: true })]),
});
@@ -40,7 +40,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(200, { hello: "world" });
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
auth: { bearerToken: "secret-token" },
fetch: stub,
@@ -57,7 +57,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
auth: { apiKey: "ak_test_123" },
fetch: stub,
@@ -73,7 +73,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(201, {});
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: stub,
});
@@ -88,7 +88,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: stub,
});
@@ -103,7 +103,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(201, {});
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
idempotency: { autoGenerate: false },
fetch: stub,
@@ -119,7 +119,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(201, {});
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: stub,
});
@@ -134,7 +134,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
tenantId: "ten_abc",
sentry: { trace: "abc-1", baggage: "k=v" },
@@ -147,7 +147,7 @@ describe("createToolctrlClient", () => {
});
it("retries on 5xx then succeeds", async () => {
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 3, baseDelayMs: 1, maxDelayMs: 5 },
fetch: mockFetchSequence([jsonResponse(503, { error: "down" }), jsonResponse(200, { ok: true })]),
@@ -157,7 +157,7 @@ describe("createToolctrlClient", () => {
});
it("retries on 429 honoring Retry-After", async () => {
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 3, baseDelayMs: 1000, maxDelayMs: 10_000 },
fetch: mockFetchSequence([
@@ -172,8 +172,8 @@ describe("createToolctrlClient", () => {
expect(Date.now() - t0).toBeLessThan(1000);
});
it("throws ToolctrlApiError on non-retryable 4xx", async () => {
const client = createToolctrlClient({
it("throws HiveGridApiError on non-retryable 4xx", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 3, baseDelayMs: 1 },
fetch: mockFetchSequence([
@@ -181,23 +181,23 @@ describe("createToolctrlClient", () => {
]),
});
await expect(client.request({ method: "GET", path: "/v1/missing" })).rejects.toMatchObject({
name: "ToolctrlApiError",
name: "HiveGridApiError",
status: 404,
requestId: "req_1",
});
});
it("throws ToolctrlNetworkError after exhausting retries", async () => {
const client = createToolctrlClient({
it("throws HiveGridNetworkError after exhausting retries", async () => {
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
retry: { maxAttempts: 2, baseDelayMs: 1, maxDelayMs: 5 },
fetch: mockFetchSequence([new Error("ECONNRESET"), new Error("ECONNRESET")]),
});
await expect(client.request({ method: "GET", path: "/v1/ping" })).rejects.toBeInstanceOf(ToolctrlNetworkError);
await expect(client.request({ method: "GET", path: "/v1/ping" })).rejects.toBeInstanceOf(HiveGridNetworkError);
});
it("paginate auto-follows nextCursor and stops on null", async () => {
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: mockFetchSequence([
jsonResponse(200, { data: [{ id: 1 }, { id: 2 }], nextCursor: "c1" }),
@@ -212,7 +212,7 @@ describe("createToolctrlClient", () => {
});
it("paginate handles nextPage offset pagination", async () => {
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
fetch: mockFetchSequence([
jsonResponse(200, { data: [{ id: "a" }], nextPage: 2 }),
@@ -234,7 +234,7 @@ describe("createToolctrlClient", () => {
return jsonResponse(200, {});
}) as unknown as typeof fetch;
const client = createToolctrlClient({
const client = createHiveGridClient({
baseUrl: "https://api.example.com",
auth: {
getToken: async () => `jwt-${++calls}`,
@@ -248,15 +248,15 @@ describe("createToolctrlClient", () => {
});
describe("error types", () => {
it("ToolctrlApiError carries status, body, and requestId", () => {
const err = new ToolctrlApiError(403, "Forbidden", { error: { code: "forbidden" } }, "req_x");
expect(err.name).toBe("ToolctrlApiError");
it("HiveGridApiError carries status, body, and requestId", () => {
const err = new HiveGridApiError(403, "Forbidden", { error: { code: "forbidden" } }, "req_x");
expect(err.name).toBe("HiveGridApiError");
expect(err.status).toBe(403);
expect(err.requestId).toBe("req_x");
});
it("ToolctrlNetworkError preserves cause", () => {
it("HiveGridNetworkError preserves cause", () => {
const cause = new Error("ECONNRESET");
const err = new ToolctrlNetworkError("net", cause);
const err = new HiveGridNetworkError("net", cause);
expect(err.cause).toBe(cause);
});
});
@@ -13,7 +13,7 @@
import { randomUUID } from "node:crypto";
export interface ToolctrlAuthConfig {
export interface HiveGridAuthConfig {
/** Bearer-token style — set as `Authorization: Bearer <key>`. */
bearerToken?: string;
/** API-key style — set as `X-API-Key: <key>`. */
@@ -22,7 +22,7 @@ export interface ToolctrlAuthConfig {
getToken?: () => Promise<string>;
}
export interface ToolctrlRetryConfig {
export interface HiveGridRetryConfig {
/** Maximum number of retry attempts (default 5). The initial request counts as 1. */
maxAttempts?: number;
/** Initial delay in ms before the first retry (default 1000). */
@@ -31,25 +31,25 @@ export interface ToolctrlRetryConfig {
maxDelayMs?: number;
}
export interface ToolctrlIdempotencyConfig {
export interface HiveGridIdempotencyConfig {
/** Auto-generate `Idempotency-Key` headers on POST/PUT/PATCH. Defaults to true. */
autoGenerate?: boolean;
}
export interface ToolctrlClientConfig {
/** Base URL of the toolctrl API, e.g. `https://api.toolctrl.de`. */
export interface HiveGridClientConfig {
/** Base URL of the hivegrid API, e.g. `https://api.hivegrid.de`. */
baseUrl: string;
/** Auth configuration. Exactly one of bearerToken / apiKey / getToken should be set. */
auth?: ToolctrlAuthConfig;
auth?: HiveGridAuthConfig;
/** Optional tenant scope; forwarded as `X-Tenant-ID` on every call. */
tenantId?: string;
/** User-Agent override. Defaults to `@toolctrl/api-client-ts/<version>`. */
/** User-Agent override. Defaults to `@hivegrid/api-client-ts/<version>`. */
userAgent?: string;
/** Retry policy for 429 + 5xx + network errors. */
retry?: ToolctrlRetryConfig;
retry?: HiveGridRetryConfig;
/** Idempotency-Key policy. */
idempotency?: ToolctrlIdempotencyConfig;
/** Optional fetch implementation (defaults to global fetch). Useful for Capacitor or test stubs. */
idempotency?: HiveGridIdempotencyConfig;
/** Optional fetch implementation (defaults to global fetch). Useful for custom runtimes or test stubs. */
fetch?: typeof fetch;
/** Sentry trace headers to forward (optional). */
sentry?: { trace?: string; baggage?: string };
@@ -72,29 +72,29 @@ export interface PaginateOptions {
query?: Record<string, string | number | undefined>;
}
export class ToolctrlApiError extends Error {
export class HiveGridApiError extends Error {
public readonly status: number;
public readonly body: unknown;
public readonly requestId?: string;
constructor(status: number, message: string, body: unknown, requestId?: string) {
super(message);
this.name = "ToolctrlApiError";
this.name = "HiveGridApiError";
this.status = status;
this.body = body;
this.requestId = requestId;
}
}
export class ToolctrlNetworkError extends Error {
export class HiveGridNetworkError extends Error {
public readonly cause: unknown;
constructor(message: string, cause: unknown) {
super(message);
this.name = "ToolctrlNetworkError";
this.name = "HiveGridNetworkError";
this.cause = cause;
}
}
export interface ToolctrlClient {
export interface HiveGridClient {
/** Issue a typed request against the API. */
request<T = unknown>(input: {
method: string;
@@ -158,16 +158,16 @@ async function readBody(response: Response): Promise<unknown> {
return text.length === 0 ? null : text;
}
export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClient {
export function createHiveGridClient(config: HiveGridClientConfig): HiveGridClient {
if (!config.baseUrl) {
throw new Error("createToolctrlClient: baseUrl is required");
throw new Error("createHiveGridClient: baseUrl is required");
}
const baseUrl = config.baseUrl.replace(/\/+$/, "");
const fetchImpl: typeof fetch =
config.fetch ?? (typeof fetch !== "undefined" ? fetch.bind(globalThis) : (undefined as unknown as typeof fetch));
if (!fetchImpl) {
throw new Error("createToolctrlClient: no fetch implementation available — pass `fetch` in the config");
throw new Error("createHiveGridClient: no fetch implementation available — pass `fetch` in the config");
}
const retryMaxAttempts = config.retry?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS;
const retryBaseMs = config.retry?.baseDelayMs ?? DEFAULT_RETRY_BASE_MS;
@@ -194,7 +194,7 @@ export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClie
const headers = new Headers();
headers.set("Accept", "application/json");
headers.set("Content-Type", "application/json");
headers.set("User-Agent", config.userAgent ?? `@toolctrl/api-client-ts/${PACKAGE_VERSION}`);
headers.set("User-Agent", config.userAgent ?? `@hivegrid/api-client-ts/${PACKAGE_VERSION}`);
if (config.tenantId) headers.set("X-Tenant-ID", config.tenantId);
if (config.sentry?.trace) headers.set("sentry-trace", config.sentry.trace);
if (config.sentry?.baggage) headers.set("baggage", config.sentry.baggage);
@@ -279,7 +279,7 @@ export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClie
errorBody && typeof errorBody === "object" && "error" in errorBody && errorBody.error && typeof errorBody.error === "object"
? String((errorBody.error as { message?: unknown }).message ?? `HTTP ${response.status}`)
: `HTTP ${response.status}`;
throw new ToolctrlApiError(response.status, message, errorBody, requestId);
throw new HiveGridApiError(response.status, message, errorBody, requestId);
}
// Network error path
@@ -292,7 +292,7 @@ export function createToolctrlClient(config: ToolctrlClientConfig): ToolctrlClie
break;
}
throw new ToolctrlNetworkError("Network request failed after retries", lastError);
throw new HiveGridNetworkError("Network request failed after retries", lastError);
}
async function* paginate<T = unknown>(path: string, options: PaginateOptions = {}): AsyncIterable<T> {
@@ -0,0 +1,158 @@
// @vitest-environment node
// Mirrors generated-client.test.ts: the generated fetch client runs server-side,
// so we pin the node environment to match the real runtime (Headers/Response
// semantics differ under jsdom).
import { describe, expect, it } from "vitest";
import { createClient } from "./generated/client/client.gen.js";
const encoder = new TextEncoder();
function eventStream(chunks: Array<string>): ReadableStream<Uint8Array> {
let index = 0;
return new ReadableStream<Uint8Array>({
pull(controller) {
if (index < chunks.length) {
controller.enqueue(encoder.encode(chunks[index]));
index += 1;
return;
}
controller.close();
},
});
}
describe("generated fetch client — response parsing matrix", () => {
it("parses a text/plain body via content-type auto-detection", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response("just text", { headers: { "Content-Type": "text/plain" } }),
responseStyle: "data",
});
await expect(client.get({ url: "/v1/text" })).resolves.toBe("just text");
});
it("parses a binary body as a Blob", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response(new Blob([new Uint8Array([1, 2, 3])]), { headers: { "Content-Type": "image/png" } }),
responseStyle: "data",
});
const blob = (await client.get({ url: "/v1/img" })) as unknown as Blob;
expect(blob).toBeInstanceOf(Blob);
expect(blob.size).toBe(3);
});
it("parses an explicit arrayBuffer response", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response(new Uint8Array([7, 8]).buffer, { headers: { "Content-Type": "application/octet-stream" } }),
responseStyle: "data",
});
const buf = (await client.get({ parseAs: "arrayBuffer", url: "/v1/bin" })) as unknown as ArrayBuffer;
expect(buf.byteLength).toBe(2);
});
it("returns the raw stream when parseAs is stream", async () => {
const body = eventStream(["chunk"]);
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response(body, { headers: { "Content-Type": "application/octet-stream" } }),
responseStyle: "data",
});
const result = await client.get({ parseAs: "stream", url: "/v1/stream" });
expect(result).toBeInstanceOf(ReadableStream);
});
it("returns an empty object for a 200 JSON response with an empty body", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response("", { headers: { "Content-Type": "application/json" } }),
responseStyle: "data",
});
await expect(client.get({ url: "/v1/empty-json" })).resolves.toEqual({});
});
it("returns empty text for a 204 with parseAs text", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response(null, { status: 204 }),
responseStyle: "data",
});
await expect(client.delete({ parseAs: "text", url: "/v1/gone" })).resolves.toBe("");
});
it("treats a Content-Length:0 response as an empty result", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response("", { headers: { "Content-Length": "0", "Content-Type": "application/json" } }),
responseStyle: "data",
});
await expect(client.get({ url: "/v1/no-content" })).resolves.toEqual({});
});
});
describe("generated fetch client — response style fields", () => {
it("wraps successful data with request and response when responseStyle is fields", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response('{"id":"x"}', { headers: { "Content-Type": "application/json" } }),
responseStyle: "fields",
});
const result = (await client.get({ url: "/v1/thing" })) as {
data: { id: string };
response: Response;
request: Request;
};
expect(result.data).toEqual({ id: "x" });
expect(result.response.status).toBe(200);
expect(result.request).toBeInstanceOf(Request);
});
});
describe("generated fetch client — error handling", () => {
it("throws the raw text error when the body is not JSON and throwOnError is set", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response("upstream exploded", { status: 502 }),
throwOnError: true,
});
await expect(client.get({ url: "/v1/boom" })).rejects.toBe("upstream exploded");
});
it("returns an error envelope for a non-JSON error when throwOnError is disabled", async () => {
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async () => new Response("nope", { status: 500 }),
throwOnError: false,
responseStyle: "fields",
});
const result = (await client.get({ url: "/v1/boom" })) as { error: unknown; response: Response };
expect(result.error).toBe("nope");
expect(result.response.status).toBe(500);
});
});
describe("generated fetch client — SSE method wiring", () => {
it("opens an SSE stream and runs request interceptors through onRequest", async () => {
let interceptorRan = false;
const client = createClient({
baseUrl: "https://api.example.test",
fetch: async (requestInfo) => {
const request = requestInfo as Request;
// The interceptor registered below must have stamped the header before fetch.
expect(request.headers.get("X-Sse-Interceptor")).toBe("ran");
return new Response(eventStream(['data: {"n":1}\n\n']), { headers: { "Content-Type": "text/event-stream" } });
},
});
client.interceptors.request.use((request) => {
interceptorRan = true;
request.headers.set("X-Sse-Interceptor", "ran");
return request;
});
const sse = await client.sse.get<{ n: number }>({ url: "/v1/stream" });
await expect(sse.stream.next()).resolves.toEqual({ done: false, value: { n: 1 } });
expect(interceptorRan).toBe(true);
});
});
@@ -1,3 +1,9 @@
// @vitest-environment node
// The generated SDK runs server-side (Node), where Headers.append("Cookie", ...)
// is RFC-6265-joined with "; ". The repo-root vitest config defaults to jsdom, whose
// Headers polyfill joins Cookie with ", " and breaks the auth-cookie assertion. Pin
// node here so the test matches the real runtime; keeps src/generated/ codegen-clean
// (no manual edit → no SDK-codegen-drift failure).
import { describe, expect, it } from "vitest";
import { getAuthToken } from "./generated/core/auth.gen.js";
import { createClient } from "./generated/client/client.gen.js";
@@ -0,0 +1,165 @@
import { describe, expect, it } from "vitest";
import {
separatorArrayExplode,
separatorArrayNoExplode,
separatorObjectExplode,
serializeArrayParam,
serializeObjectParam,
serializePrimitiveParam,
} from "./generated/core/pathSerializer.gen.js";
import { defaultPathSerializer, getUrl, getValidRequestBody } from "./generated/core/utils.gen.js";
import { queryKeyJsonReplacer, serializeQueryKeyValue } from "./generated/core/queryKeySerializer.gen.js";
import { buildClientParams } from "./generated/core/params.gen.js";
describe("pathSerializer separators (RFC6570 style table)", () => {
it("maps explode separators per style", () => {
expect(separatorArrayExplode("matrix")).toBe(";");
expect(separatorArrayExplode("simple")).toBe(",");
expect(separatorArrayExplode("form")).toBe("&");
});
it("maps no-explode separators per style", () => {
expect(separatorArrayNoExplode("form")).toBe(",");
expect(separatorArrayNoExplode("spaceDelimited")).toBe("%20");
// unknown styles fall back to a comma
expect(separatorArrayNoExplode("simple")).toBe(",");
});
it("maps object explode separators per style", () => {
expect(separatorObjectExplode("label")).toBe(".");
expect(separatorObjectExplode("simple")).toBe(",");
expect(separatorObjectExplode("form")).toBe("&");
});
});
describe("serializeArrayParam — non-explode styles", () => {
it("serializes label, matrix, and simple styles", () => {
expect(serializeArrayParam({ explode: false, name: "x", style: "label", value: ["a", "b"] })).toBe(".a,b");
expect(serializeArrayParam({ explode: false, name: "x", style: "matrix", value: ["a", "b"] })).toBe(";x=a,b");
expect(serializeArrayParam({ explode: false, name: "x", style: "simple", value: ["a", "b"] })).toBe("a,b");
});
it("keeps reserved characters when allowReserved is set", () => {
expect(serializeArrayParam({ allowReserved: true, explode: false, name: "x", style: "form", value: ["a/b", "c"] })).toBe("x=a/b,c");
});
});
describe("serializeArrayParam — explode styles", () => {
it("uses the style separator and encodes each member for label/simple", () => {
expect(serializeArrayParam({ explode: true, name: "x", style: "label", value: ["a/b", "c"] })).toBe(".a%2Fb.c");
expect(serializeArrayParam({ explode: true, name: "x", style: "simple", value: ["a/b", "c"] })).toBe("a%2Fb,c");
});
it("emits name=value pairs for matrix and form", () => {
expect(serializeArrayParam({ explode: true, name: "id", style: "matrix", value: ["a", "b"] })).toBe(";id=a;id=b");
expect(serializeArrayParam({ explode: true, name: "id", style: "form", value: ["a", "b"] })).toBe("id=a&id=b");
});
});
describe("serializePrimitiveParam — nullish guards", () => {
it("returns an empty string for null and undefined", () => {
expect(serializePrimitiveParam({ name: "x", value: undefined as never })).toBe("");
expect(serializePrimitiveParam({ name: "x", value: null as never })).toBe("");
});
});
describe("serializeObjectParam — non-explode styles", () => {
it("serializes matrix and the default (simple) styles", () => {
expect(serializeObjectParam({ explode: false, name: "f", style: "matrix", value: { status: "open", owner: "me" } })).toBe(
";f=status,open,owner,me"
);
expect(serializeObjectParam({ explode: false, name: "f", style: "simple" as never, value: { status: "open" } })).toBe("status,open");
});
it("keeps reserved characters in object values when allowReserved is set", () => {
expect(serializeObjectParam({ allowReserved: true, explode: false, name: "f", style: "form", value: { path: "a/b" } })).toBe(
"f=path,a/b"
);
});
});
describe("defaultPathSerializer — uncommon param shapes", () => {
it("leaves a placeholder untouched when the value is missing", () => {
expect(defaultPathSerializer({ path: {}, url: "/v1/{ghost}" })).toBe("/v1/{ghost}");
});
it("serializes a matrix-style primitive path parameter", () => {
expect(defaultPathSerializer({ path: { id: "5" }, url: "/v1/{;id}" })).toBe("/v1/;id=5");
});
});
describe("getUrl — without a base url", () => {
it("prefixes nothing when baseUrl is omitted", () => {
const url = getUrl({
path: { id: "a" },
query: { x: 1 },
querySerializer: (q) => `x=${(q as { x: number }).x}`,
url: "v1/{id}",
});
expect(url).toBe("/v1/a?x=1");
});
});
describe("getValidRequestBody — serializer without serializedBody property", () => {
it("returns the raw body when no serializedBody key is present", () => {
expect(getValidRequestBody({ body: { ok: true }, bodySerializer: JSON.stringify })).toEqual({ ok: true });
});
it("returns null for an empty body even without a serializedBody key", () => {
expect(getValidRequestBody({ body: "", bodySerializer: JSON.stringify })).toBeNull();
});
});
describe("queryKeyJsonReplacer", () => {
it("converts Date and bigint, and drops functions/undefined", () => {
expect(queryKeyJsonReplacer("k", new Date("2026-01-02T03:04:05.000Z"))).toBe("2026-01-02T03:04:05.000Z");
expect(queryKeyJsonReplacer("k", 7n)).toBe("7");
expect(queryKeyJsonReplacer("k", undefined)).toBeUndefined();
expect(queryKeyJsonReplacer("k", () => undefined)).toBeUndefined();
expect(queryKeyJsonReplacer("k", "kept")).toBe("kept");
});
});
describe("serializeQueryKeyValue — primitive and edge inputs", () => {
it("passes through null, numbers, and booleans", () => {
expect(serializeQueryKeyValue(null)).toBeNull();
expect(serializeQueryKeyValue(42)).toBe(42);
expect(serializeQueryKeyValue(true)).toBe(true);
});
it("normalizes bigint and Date scalars", () => {
expect(serializeQueryKeyValue(99n)).toBe("99");
expect(serializeQueryKeyValue(new Date("2026-01-02T00:00:00.000Z"))).toBe("2026-01-02T00:00:00.000Z");
});
it("serializes arrays via JSON round-trip", () => {
expect(serializeQueryKeyValue([1, "a", true])).toEqual([1, "a", true]);
});
it("collapses three repeated search-param keys into one array", () => {
const params = new URLSearchParams([
["a", "1"],
["a", "2"],
["a", "3"],
]);
expect(serializeQueryKeyValue(params)).toEqual({ a: ["1", "2", "3"] });
});
it("returns undefined for non-plain objects like Map", () => {
expect(serializeQueryKeyValue(new Map([["a", 1]]))).toBeUndefined();
});
});
describe("buildClientParams — sparse and aliasing configs", () => {
it("skips arguments that have no matching field config", () => {
expect(buildClientParams(["orphan"], [])).toEqual({});
});
it("tolerates an undefined object argument", () => {
expect(buildClientParams([undefined], [{ args: [{ in: "query", key: "q" }] }])).toEqual({});
});
it("falls back to the field key when no map override is given", () => {
expect(buildClientParams([{ q: "drill" }], [{ args: [{ in: "query", key: "q" }] }])).toEqual({ query: { q: "drill" } });
});
});
@@ -13,4 +13,4 @@ import type { ClientOptions as ClientOptions2 } from "./types.gen";
*/
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
export const client = createClient(createConfig<ClientOptions2>({ baseUrl: "https://api.toolctrl.de" }));
export const client = createClient(createConfig<ClientOptions2>({ baseUrl: "https://api.hivegrid.de" }));
@@ -4,12 +4,8 @@ export {
acceptWorkspaceInvite,
createAnalyticsEvent,
createAnalyticsPageView,
createLegacyEntityRow,
createLegacyRowRelationship,
createSupportTicketFromInboundEmail,
createWorkspaceInvite,
deleteLegacyEntityRow,
deleteLegacyRowRelationship,
enqueueExportArtifactRetention,
getAccount,
getAdminAnalyticsOverview,
@@ -19,9 +15,6 @@ export {
getExportDownloadUrl,
getExportJobProgress,
getHealthz,
getLegacyEntityByName,
getLegacyEntityRow,
getLegacyRowRelationship,
getMetrics,
getOpenApiDocument,
getPublicAnalyticsOverview,
@@ -29,7 +22,12 @@ export {
getStatus,
getV1Health,
listAccounts,
listLegacyEntityRows,
listPublicApiCompanies,
listPublicApiContacts,
listPublicApiDeals,
listPublicApiLeads,
listPublicApiProjects,
listPublicApiTasks,
listWorkspaceAuthProviders,
listWorkspaceInvites,
loginWithPassword,
@@ -38,13 +36,13 @@ export {
postDeviceRegister,
postDeviceRevoke,
receiveEmailSequenceMailjetWebhook,
receiveStripeBillingWebhook,
receiveMollieBillingWebhook,
receivePublicApiIncomingWebhook,
refreshJwtToken,
retryEventWebhookAttempt,
revalidateWorkspaceContext,
revokeWorkspaceInvite,
streamNotifications,
updateLegacyEntityRow,
uploadAiFile,
validateApiKey,
} from "./sdk.gen";
@@ -65,16 +63,6 @@ export type {
CreateAnalyticsPageViewErrors,
CreateAnalyticsPageViewResponse,
CreateAnalyticsPageViewResponses,
CreateLegacyEntityRowData,
CreateLegacyEntityRowError,
CreateLegacyEntityRowErrors,
CreateLegacyEntityRowResponse,
CreateLegacyEntityRowResponses,
CreateLegacyRowRelationshipData,
CreateLegacyRowRelationshipError,
CreateLegacyRowRelationshipErrors,
CreateLegacyRowRelationshipResponse,
CreateLegacyRowRelationshipResponses,
CreateSupportTicketFromInboundEmailData,
CreateSupportTicketFromInboundEmailError,
CreateSupportTicketFromInboundEmailErrors,
@@ -84,16 +72,6 @@ export type {
CreateWorkspaceInviteErrors,
CreateWorkspaceInviteResponse,
CreateWorkspaceInviteResponses,
DeleteLegacyEntityRowData,
DeleteLegacyEntityRowError,
DeleteLegacyEntityRowErrors,
DeleteLegacyEntityRowResponse,
DeleteLegacyEntityRowResponses,
DeleteLegacyRowRelationshipData,
DeleteLegacyRowRelationshipError,
DeleteLegacyRowRelationshipErrors,
DeleteLegacyRowRelationshipResponse,
DeleteLegacyRowRelationshipResponses,
EnqueueExportArtifactRetentionData,
EnqueueExportArtifactRetentionError,
EnqueueExportArtifactRetentionErrors,
@@ -134,20 +112,6 @@ export type {
GetHealthzData,
GetHealthzResponse,
GetHealthzResponses,
GetLegacyEntityByNameData,
GetLegacyEntityByNameError,
GetLegacyEntityByNameErrors,
GetLegacyEntityByNameResponses,
GetLegacyEntityRowData,
GetLegacyEntityRowError,
GetLegacyEntityRowErrors,
GetLegacyEntityRowResponse,
GetLegacyEntityRowResponses,
GetLegacyRowRelationshipData,
GetLegacyRowRelationshipError,
GetLegacyRowRelationshipErrors,
GetLegacyRowRelationshipResponse,
GetLegacyRowRelationshipResponses,
GetMetricsData,
GetMetricsError,
GetMetricsErrors,
@@ -178,11 +142,36 @@ export type {
ListAccountsErrors,
ListAccountsResponse,
ListAccountsResponses,
ListLegacyEntityRowsData,
ListLegacyEntityRowsError,
ListLegacyEntityRowsErrors,
ListLegacyEntityRowsResponse,
ListLegacyEntityRowsResponses,
ListPublicApiCompaniesData,
ListPublicApiCompaniesError,
ListPublicApiCompaniesErrors,
ListPublicApiCompaniesResponse,
ListPublicApiCompaniesResponses,
ListPublicApiContactsData,
ListPublicApiContactsError,
ListPublicApiContactsErrors,
ListPublicApiContactsResponse,
ListPublicApiContactsResponses,
ListPublicApiDealsData,
ListPublicApiDealsError,
ListPublicApiDealsErrors,
ListPublicApiDealsResponse,
ListPublicApiDealsResponses,
ListPublicApiLeadsData,
ListPublicApiLeadsError,
ListPublicApiLeadsErrors,
ListPublicApiLeadsResponse,
ListPublicApiLeadsResponses,
ListPublicApiProjectsData,
ListPublicApiProjectsError,
ListPublicApiProjectsErrors,
ListPublicApiProjectsResponse,
ListPublicApiProjectsResponses,
ListPublicApiTasksData,
ListPublicApiTasksError,
ListPublicApiTasksErrors,
ListPublicApiTasksResponse,
ListPublicApiTasksResponses,
ListWorkspaceAuthProvidersData,
ListWorkspaceAuthProvidersError,
ListWorkspaceAuthProvidersErrors,
@@ -215,10 +204,15 @@ export type {
ReceiveEmailSequenceMailjetWebhookError,
ReceiveEmailSequenceMailjetWebhookErrors,
ReceiveEmailSequenceMailjetWebhookResponses,
ReceiveStripeBillingWebhookData,
ReceiveStripeBillingWebhookError,
ReceiveStripeBillingWebhookErrors,
ReceiveStripeBillingWebhookResponses,
ReceiveMollieBillingWebhookData,
ReceiveMollieBillingWebhookError,
ReceiveMollieBillingWebhookErrors,
ReceiveMollieBillingWebhookResponses,
ReceivePublicApiIncomingWebhookData,
ReceivePublicApiIncomingWebhookError,
ReceivePublicApiIncomingWebhookErrors,
ReceivePublicApiIncomingWebhookResponse,
ReceivePublicApiIncomingWebhookResponses,
RefreshJwtTokenData,
RefreshJwtTokenError,
RefreshJwtTokenErrors,
@@ -242,11 +236,6 @@ export type {
StreamNotificationsErrors,
StreamNotificationsResponse,
StreamNotificationsResponses,
UpdateLegacyEntityRowData,
UpdateLegacyEntityRowError,
UpdateLegacyEntityRowErrors,
UpdateLegacyEntityRowResponse,
UpdateLegacyEntityRowResponses,
UploadAiFileData,
UploadAiFileError,
UploadAiFileErrors,
@@ -1,6 +1,6 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { Client, Options as Options2, TDataShape } from "./client";
import { type Client, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from "./client";
import { client } from "./client.gen";
import type {
AcceptWorkspaceInviteData,
@@ -12,24 +12,12 @@ import type {
CreateAnalyticsPageViewData,
CreateAnalyticsPageViewErrors,
CreateAnalyticsPageViewResponses,
CreateLegacyEntityRowData,
CreateLegacyEntityRowErrors,
CreateLegacyEntityRowResponses,
CreateLegacyRowRelationshipData,
CreateLegacyRowRelationshipErrors,
CreateLegacyRowRelationshipResponses,
CreateSupportTicketFromInboundEmailData,
CreateSupportTicketFromInboundEmailErrors,
CreateSupportTicketFromInboundEmailResponses,
CreateWorkspaceInviteData,
CreateWorkspaceInviteErrors,
CreateWorkspaceInviteResponses,
DeleteLegacyEntityRowData,
DeleteLegacyEntityRowErrors,
DeleteLegacyEntityRowResponses,
DeleteLegacyRowRelationshipData,
DeleteLegacyRowRelationshipErrors,
DeleteLegacyRowRelationshipResponses,
EnqueueExportArtifactRetentionData,
EnqueueExportArtifactRetentionErrors,
EnqueueExportArtifactRetentionResponses,
@@ -55,15 +43,6 @@ import type {
GetExportJobProgressResponses,
GetHealthzData,
GetHealthzResponses,
GetLegacyEntityByNameData,
GetLegacyEntityByNameErrors,
GetLegacyEntityByNameResponses,
GetLegacyEntityRowData,
GetLegacyEntityRowErrors,
GetLegacyEntityRowResponses,
GetLegacyRowRelationshipData,
GetLegacyRowRelationshipErrors,
GetLegacyRowRelationshipResponses,
GetMetricsData,
GetMetricsErrors,
GetMetricsResponses,
@@ -83,9 +62,24 @@ import type {
ListAccountsData,
ListAccountsErrors,
ListAccountsResponses,
ListLegacyEntityRowsData,
ListLegacyEntityRowsErrors,
ListLegacyEntityRowsResponses,
ListPublicApiCompaniesData,
ListPublicApiCompaniesErrors,
ListPublicApiCompaniesResponses,
ListPublicApiContactsData,
ListPublicApiContactsErrors,
ListPublicApiContactsResponses,
ListPublicApiDealsData,
ListPublicApiDealsErrors,
ListPublicApiDealsResponses,
ListPublicApiLeadsData,
ListPublicApiLeadsErrors,
ListPublicApiLeadsResponses,
ListPublicApiProjectsData,
ListPublicApiProjectsErrors,
ListPublicApiProjectsResponses,
ListPublicApiTasksData,
ListPublicApiTasksErrors,
ListPublicApiTasksResponses,
ListWorkspaceAuthProvidersData,
ListWorkspaceAuthProvidersErrors,
ListWorkspaceAuthProvidersResponses,
@@ -107,9 +101,12 @@ import type {
ReceiveEmailSequenceMailjetWebhookData,
ReceiveEmailSequenceMailjetWebhookErrors,
ReceiveEmailSequenceMailjetWebhookResponses,
ReceiveStripeBillingWebhookData,
ReceiveStripeBillingWebhookErrors,
ReceiveStripeBillingWebhookResponses,
ReceiveMollieBillingWebhookData,
ReceiveMollieBillingWebhookErrors,
ReceiveMollieBillingWebhookResponses,
ReceivePublicApiIncomingWebhookData,
ReceivePublicApiIncomingWebhookErrors,
ReceivePublicApiIncomingWebhookResponses,
RefreshJwtTokenData,
RefreshJwtTokenErrors,
RefreshJwtTokenResponses,
@@ -126,9 +123,6 @@ import type {
StreamNotificationsErrors,
StreamNotificationsResponse,
StreamNotificationsResponses,
UpdateLegacyEntityRowData,
UpdateLegacyEntityRowErrors,
UpdateLegacyEntityRowResponses,
UploadAiFileData,
UploadAiFileErrors,
UploadAiFileResponses,
@@ -403,12 +397,76 @@ export const getApiUsage = <ThrowOnError extends boolean = false>(options?: Opti
});
/**
* Canonical API-host entry point for Stripe billing lifecycle webhooks. The API runtime preserves the raw body and signature headers and applies subscription updates through API-owned billing services.
* Tenant-scoped private-person contacts from the CRM core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
*/
export const receiveStripeBillingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceiveStripeBillingWebhookData, ThrowOnError>) =>
(options.client ?? client).post<ReceiveStripeBillingWebhookResponses, ReceiveStripeBillingWebhookErrors, ThrowOnError>({
security: [{ name: "stripe-signature", type: "apiKey" }],
url: "/v1/billing/stripe/webhooks",
export const listPublicApiContacts = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiContactsData, ThrowOnError>) =>
(options.client ?? client).get<ListPublicApiContactsResponses, ListPublicApiContactsErrors, ThrowOnError>({
security: [{ name: "x-api-key", type: "apiKey" }],
url: "/v1/contacts",
...options,
});
/**
* Tenant-scoped organisation contacts from the CRM core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
*/
export const listPublicApiCompanies = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiCompaniesData, ThrowOnError>) =>
(options.client ?? client).get<ListPublicApiCompaniesResponses, ListPublicApiCompaniesErrors, ThrowOnError>({
security: [{ name: "x-api-key", type: "apiKey" }],
url: "/v1/companies",
...options,
});
/**
* Sales-pipeline project view. Deals and projects share the Projekt core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
*/
export const listPublicApiDeals = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiDealsData, ThrowOnError>) =>
(options.client ?? client).get<ListPublicApiDealsResponses, ListPublicApiDealsErrors, ThrowOnError>({
security: [{ name: "x-api-key", type: "apiKey" }],
url: "/v1/deals",
...options,
});
/**
* Tenant-scoped project records from the Projekt core. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
*/
export const listPublicApiProjects = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiProjectsData, ThrowOnError>) =>
(options.client ?? client).get<ListPublicApiProjectsResponses, ListPublicApiProjectsErrors, ThrowOnError>({
security: [{ name: "x-api-key", type: "apiKey" }],
url: "/v1/projects",
...options,
});
/**
* Tenant-scoped task records. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
*/
export const listPublicApiTasks = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiTasksData, ThrowOnError>) =>
(options.client ?? client).get<ListPublicApiTasksResponses, ListPublicApiTasksErrors, ThrowOnError>({
security: [{ name: "x-api-key", type: "apiKey" }],
url: "/v1/tasks",
...options,
});
/**
* Tenant-scoped lead-inbox records. Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.
*/
export const listPublicApiLeads = <ThrowOnError extends boolean = false>(options: Options<ListPublicApiLeadsData, ThrowOnError>) =>
(options.client ?? client).get<ListPublicApiLeadsResponses, ListPublicApiLeadsErrors, ThrowOnError>({
security: [{ name: "x-api-key", type: "apiKey" }],
url: "/v1/leads",
...options,
});
/**
* Tenant-scoped incoming lead webhook. The endpoint authenticates by the endpoint's configured mode: API key, HMAC token/signature, or URL/header token. Successful requests create an InboxLead and queue webhook.received automation executions.
*/
export const receivePublicApiIncomingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceivePublicApiIncomingWebhookData, ThrowOnError>) =>
(options.client ?? client).post<ReceivePublicApiIncomingWebhookResponses, ReceivePublicApiIncomingWebhookErrors, ThrowOnError>({
security: [
{ name: "x-api-key", type: "apiKey" },
{ name: "X-HiveGrid-Webhook-Token", type: "apiKey" },
{ name: "X-HiveGrid-Signature", type: "apiKey" },
],
url: "/v1/webhooks/incoming/{tenant}/{slug}",
...options,
headers: {
"Content-Type": "application/json",
@@ -416,6 +474,20 @@ export const receiveStripeBillingWebhook = <ThrowOnError extends boolean = false
},
});
/**
* Canonical API-host entry point for Mollie payment lifecycle webhooks. Mollie posts a payment id; the API refetches that payment from Mollie server-side before syncing tenant billing state.
*/
export const receiveMollieBillingWebhook = <ThrowOnError extends boolean = false>(options: Options<ReceiveMollieBillingWebhookData, ThrowOnError>) =>
(options.client ?? client).post<ReceiveMollieBillingWebhookResponses, ReceiveMollieBillingWebhookErrors, ThrowOnError>({
...urlSearchParamsBodySerializer,
url: "/v1/billing/mollie/webhooks",
...options,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
...options.headers,
},
});
/**
* Accepts Mailjet provider event webhooks for email sequences, authenticated with HTTP Basic Auth. Bounce, blocked, and spam events correlate by provider message id (Message_GUID), mark the sequence delivery bounced, and fail the in-flight run without echoing provider payloads.
*/
@@ -453,122 +525,6 @@ export const enqueueExportArtifactRetention = <ThrowOnError extends boolean = fa
},
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const listLegacyEntityRows = <ThrowOnError extends boolean = false>(options: Options<ListLegacyEntityRowsData, ThrowOnError>) =>
(options.client ?? client).get<ListLegacyEntityRowsResponses, ListLegacyEntityRowsErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/entities/{entity}/rows",
...options,
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const createLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<CreateLegacyEntityRowData, ThrowOnError>) =>
(options.client ?? client).post<CreateLegacyEntityRowResponses, CreateLegacyEntityRowErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/entities/{entity}/rows",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const deleteLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<DeleteLegacyEntityRowData, ThrowOnError>) =>
(options.client ?? client).delete<DeleteLegacyEntityRowResponses, DeleteLegacyEntityRowErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/entities/{entity}/rows/{rowId}",
...options,
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const getLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<GetLegacyEntityRowData, ThrowOnError>) =>
(options.client ?? client).get<GetLegacyEntityRowResponses, GetLegacyEntityRowErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/entities/{entity}/rows/{rowId}",
...options,
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const updateLegacyEntityRow = <ThrowOnError extends boolean = false>(options: Options<UpdateLegacyEntityRowData, ThrowOnError>) =>
(options.client ?? client).patch<UpdateLegacyEntityRowResponses, UpdateLegacyEntityRowErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/entities/{entity}/rows/{rowId}",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const createLegacyRowRelationship = <ThrowOnError extends boolean = false>(options: Options<CreateLegacyRowRelationshipData, ThrowOnError>) =>
(options.client ?? client).post<CreateLegacyRowRelationshipResponses, CreateLegacyRowRelationshipErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/relationships",
...options,
headers: {
"Content-Type": "application/json",
...options.headers,
},
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const deleteLegacyRowRelationship = <ThrowOnError extends boolean = false>(options: Options<DeleteLegacyRowRelationshipData, ThrowOnError>) =>
(options.client ?? client).delete<DeleteLegacyRowRelationshipResponses, DeleteLegacyRowRelationshipErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/relationships/{id}",
...options,
});
/**
* Authorize with either the configured service token bearer credential or a stored API key supplied in x-api-key. Stored API keys are tenant-bound and must include an entity permission for the resolved tenant/entity plus the documented CRUD operation.
*/
export const getLegacyRowRelationship = <ThrowOnError extends boolean = false>(options: Options<GetLegacyRowRelationshipData, ThrowOnError>) =>
(options.client ?? client).get<GetLegacyRowRelationshipResponses, GetLegacyRowRelationshipErrors, ThrowOnError>({
security: [
{ scheme: "bearer", type: "http" },
{ name: "x-api-key", type: "apiKey" },
],
url: "/v1/relationships/{id}",
...options,
});
/**
* Creates a short-lived signed GET URL for a completed, unexpired export job. Authorize with either the configured service token bearer credential or a tenant-bound stored API key supplied in x-api-key; stored API keys are scoped to their own tenant and this route does not publish CRUD entity-scope claims. Responses never include export artifact bucket/key values, storage credentials, signed URL internals beyond the URL envelope, payload filters, or object bodies.
*/
@@ -596,7 +552,7 @@ export const getExportJobProgress = <ThrowOnError extends boolean = false>(optio
});
/**
* Register or update a mobile push token (APNs / FCM / WebPush) for the authenticated principal. Requires a service-token bearer credential; the body's userId + tenantId are reconciled downstream against the authenticated principal. Tokens are upserted by their globally unique value so cold-start replays are idempotent.
* Register or update a Web Push token for the authenticated principal. Requires a service-token bearer credential; the body's userId + tenantId are reconciled downstream against the authenticated principal. Tokens are upserted by their globally unique value so cold-start replays are idempotent.
*/
export const postDeviceRegister = <ThrowOnError extends boolean = false>(options: Options<PostDeviceRegisterData, ThrowOnError>) =>
(options.client ?? client).post<PostDeviceRegisterResponses, PostDeviceRegisterErrors, ThrowOnError>({
@@ -610,7 +566,7 @@ export const postDeviceRegister = <ThrowOnError extends boolean = false>(options
});
/**
* Revoke a mobile push token. Requires a service-token bearer credential; the handler revokes by token hash and never echoes the raw token in the response.
* Revoke a Web Push token. Requires a service-token bearer credential; the handler revokes by token hash and never echoes the raw token in the response.
*/
export const postDeviceRevoke = <ThrowOnError extends boolean = false>(options: Options<PostDeviceRevokeData, ThrowOnError>) =>
(options.client ?? client).post<PostDeviceRevokeResponses, PostDeviceRevokeErrors, ThrowOnError>({
@@ -622,10 +578,3 @@ export const postDeviceRevoke = <ThrowOnError extends boolean = false>(options:
...options.headers,
},
});
export const getLegacyEntityByName = <ThrowOnError extends boolean = false>(options: Options<GetLegacyEntityByNameData, ThrowOnError>) =>
(options.client ?? client).get<GetLegacyEntityByNameResponses, GetLegacyEntityByNameErrors, ThrowOnError>({
security: [{ scheme: "bearer", type: "http" }],
url: "/v1/entities/{entity}",
...options,
});
@@ -1,7 +1,7 @@
/**
* @toolctrl/api-client-ts
* @hivegrid/api-client-ts
*
* Official TypeScript SDK for the toolctrl boilerplate REST API.
* Official TypeScript SDK for the HiveGrid REST API.
*
* The public surface is a thin Higher-Level-Wrapper around the @hey-api/openapi-ts
* generated client. The wrapper adds auth header injection, retry with exponential
@@ -12,14 +12,14 @@
*/
export {
createToolctrlClient,
ToolctrlApiError,
ToolctrlNetworkError,
type ToolctrlClient,
type ToolctrlClientConfig,
type ToolctrlAuthConfig,
type ToolctrlRetryConfig,
type ToolctrlIdempotencyConfig,
createHiveGridClient,
HiveGridApiError,
HiveGridNetworkError,
type HiveGridClient,
type HiveGridClientConfig,
type HiveGridAuthConfig,
type HiveGridRetryConfig,
type HiveGridIdempotencyConfig,
type PaginatedResponse,
type PaginateOptions,
} from "./client.js";
@@ -0,0 +1,47 @@
import { describe, it, expect } from "vitest";
import { verifyWebhookSignature, signWebhookPayload } from "./webhooks.js";
const SECRET = "whsec_test_super_secret";
const PAYLOAD = `{"event":"contact.created","data":{"id":"c_42"}}`;
const TIMESTAMP = 1_700_000_000;
describe("verifyWebhookSignature — defensive paths", () => {
it("returns false when the provided signature is same-length but not valid hex", () => {
// expectedHex is 64 hex chars; a 64-char all-`g` string passes the length
// gate but decodes to an empty buffer, so timingSafeEqual throws and is caught.
const provided = "g".repeat(64);
expect(
verifyWebhookSignature({
secret: SECRET,
payload: PAYLOAD,
signature: provided,
timestamp: TIMESTAMP,
now: () => TIMESTAMP * 1000,
})
).toBe(false);
});
it("defaults to Date.now() for the replay window when no clock override is given", () => {
const fresh = Math.floor(Date.now() / 1000);
const signature = signWebhookPayload({ secret: SECRET, payload: PAYLOAD, timestamp: fresh });
// No `now` passed → exercises the Date.now() default branch; a just-issued
// signature is inside the 5-minute window.
expect(verifyWebhookSignature({ secret: SECRET, payload: PAYLOAD, signature, timestamp: fresh })).toBe(true);
});
it("does not strip a late `=` (index >= 16) as an algorithm prefix", () => {
const signature = signWebhookPayload({ secret: SECRET, payload: PAYLOAD, timestamp: TIMESTAMP });
// Insert an `=` past position 16 — normalizeSignature must keep the value as-is,
// so the now-malformed/longer string fails verification rather than being trimmed.
const withLateEquals = `${signature.slice(0, 20)}=${signature.slice(20)}`;
expect(
verifyWebhookSignature({
secret: SECRET,
payload: PAYLOAD,
signature: withLateEquals,
timestamp: TIMESTAMP,
now: () => TIMESTAMP * 1000,
})
).toBe(false);
});
});
@@ -18,7 +18,7 @@ export interface VerifyWebhookOptions {
secret: string;
/** Raw request body, exactly as received (do not re-serialize). */
payload: string | Buffer;
/** Hex-encoded HMAC-SHA256 signature delivered via header (e.g. `X-Toolctrl-Signature`). */
/** Hex-encoded HMAC-SHA256 signature delivered via header (e.g. `X-HiveGrid-Signature`). */
signature: string;
/** Unix timestamp in seconds when the webhook was emitted. */
timestamp: number | string;
@@ -1,12 +1,12 @@
# @toolctrl/api-types
# @hivegrid/api-types
Types-only re-export of the toolctrl boilerplate REST API surface.
Types-only re-export of the HiveGrid REST API surface.
This package is dependency-free at runtime: it re-exports `type` declarations
from `@toolctrl/api-client-ts` plus the generated OpenAPI types. Use it in
from `@hivegrid/api-client-ts` plus the generated OpenAPI types. Use it in
consumers that only need compile-time types (e.g. shared interfaces in another
TypeScript service) without pulling in the SDK's fetch + crypto runtime.
```ts
import type { ToolctrlClientConfig, PaginatedResponse } from "@toolctrl/api-types";
import type { HiveGridClientConfig, PaginatedResponse } from "@hivegrid/api-types";
```
@@ -1,8 +1,8 @@
{
"name": "@toolctrl/api-types",
"name": "@hivegrid/api-types",
"version": "0.1.0",
"private": true,
"description": "Types-only re-export of the toolctrl boilerplate REST API surface. Zero runtime, zero dependencies — for consumers that need OpenAPI-derived TypeScript types without pulling in fetch / crypto code.",
"description": "Types-only re-export of the HiveGrid REST API surface. Zero runtime, zero dependencies — for consumers that need OpenAPI-derived TypeScript types without pulling in fetch / crypto code.",
"type": "module",
"sideEffects": false,
"exports": {
@@ -18,7 +18,7 @@
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@toolctrl/api-client-ts": "workspace:*"
"@hivegrid/api-client-ts": "workspace:*"
},
"devDependencies": {
"@types/node": "^25.0.0",
@@ -1,9 +1,9 @@
import { describe, it, expectTypeOf } from "vitest";
import type { ToolctrlClientConfig, PaginatedResponse, GetHealthzData, LoginWithPasswordData } from "./index.js";
import type { HiveGridClientConfig, PaginatedResponse, GetHealthzData, LoginWithPasswordData } from "./index.js";
describe("@toolctrl/api-types", () => {
it("re-exports the wrapper ToolctrlClientConfig", () => {
expectTypeOf<ToolctrlClientConfig>().toHaveProperty("baseUrl").toEqualTypeOf<string>();
describe("@hivegrid/api-types", () => {
it("re-exports the wrapper HiveGridClientConfig", () => {
expectTypeOf<HiveGridClientConfig>().toHaveProperty("baseUrl").toEqualTypeOf<string>();
});
it("re-exports PaginatedResponse<T>", () => {
expectTypeOf<PaginatedResponse<number>>().toHaveProperty("data").toEqualTypeOf<number[]>();
@@ -1,7 +1,7 @@
/**
* @toolctrl/api-types
* @hivegrid/api-types
*
* Types-only re-export of the toolctrl boilerplate REST API surface.
* Types-only re-export of the HiveGrid REST API surface.
* No runtime code, no dependencies that emit code at runtime.
*
* Consumers can import OpenAPI-derived TypeScript types without pulling in the
@@ -12,16 +12,16 @@
// Higher-level wrapper types (auth config, retry config, pagination, etc.).
export type {
ToolctrlClient,
ToolctrlClientConfig,
ToolctrlAuthConfig,
ToolctrlRetryConfig,
ToolctrlIdempotencyConfig,
HiveGridClient,
HiveGridClientConfig,
HiveGridAuthConfig,
HiveGridRetryConfig,
HiveGridIdempotencyConfig,
PaginatedResponse,
PaginateOptions,
} from "@toolctrl/api-client-ts";
} from "@hivegrid/api-client-ts";
// OpenAPI-derived request/response types for every operation.
// Re-exported as a `*` namespace to keep the surface area discoverable while
// preserving the original generated names (GetHealthzData, LoginWithPasswordData, …).
export type * from "@toolctrl/api-client-ts/types";
export type * from "@hivegrid/api-client-ts/types";
@@ -0,0 +1,28 @@
{
"name": "@hivegrid/billing",
"version": "0.0.0",
"private": true,
"type": "module",
"sideEffects": false,
"exports": {
".": "./src/index.ts",
"./lago": "./src/lago.ts",
"./mollie": "./src/mollie.ts",
"./sandbox-flow": "./src/sandbox-flow.ts",
"./sync-outbox": "./src/sync-outbox.ts"
},
"scripts": {
"build": "pnpm run typecheck",
"test": "vitest run src",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@hivegrid/db": "workspace:*",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/node": "^25.0.0",
"typescript": "^5.3.2",
"vitest": "^3.2.4"
}
}
@@ -0,0 +1,6 @@
export * from "./types.js";
export * from "./lago.js";
export * from "./mollie.js";
export * from "./sync-outbox.js";
export * from "./sandbox-flow.js";
export * from "./webhook.js";
@@ -0,0 +1,276 @@
import { describe, expect, it, vi } from "vitest";
import { createLagoBillingGateway, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js";
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: {
"content-type": "application/json",
},
});
}
describe("LagoBillingGateway", () => {
it("creates customers through the Lago API and maps the response", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
customer: {
lago_id: "lago_customer_1",
external_id: "tenant_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
created_at: "2026-07-04T00:00:00Z",
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test/",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(
gateway.createCustomer({
tenantId: "tenant_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
})
).resolves.toEqual({
provider: "lago",
externalId: "tenant_1",
providerCustomerId: "lago_customer_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
createdAt: "2026-07-04T00:00:00Z",
});
expect(fetchImpl).toHaveBeenCalledWith(
"https://lago.example.test/api/v1/customers",
expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
authorization: "Bearer secret_lago_key",
"content-type": "application/json",
}),
body: JSON.stringify({
customer: {
external_id: "tenant_1",
name: "ACME GmbH",
email: "billing@example.test",
currency: "EUR",
},
}),
})
);
});
it("creates plan subscriptions without storing seat count as unsupported Lago usage", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
subscription: {
lago_id: "lago_subscription_1",
external_id: "sub_tenant_1_business",
external_customer_id: "tenant_1",
plan_code: "business",
status: "active",
name: "business (5 seats)",
current_billing_period_started_at: "2026-07-01T00:00:00Z",
current_billing_period_ending_at: "2026-08-01T00:00:00Z",
created_at: "2026-07-04T00:00:00Z",
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
const subscription = await gateway.createSubscription({
tenantId: "tenant_1",
subscriptionExternalId: "sub_tenant_1_business",
planCode: "business",
seatQuantity: 5,
subscriptionAt: new Date("2026-07-04T00:00:00Z"),
});
expect(subscription).toMatchObject({
provider: "lago",
externalId: "sub_tenant_1_business",
providerSubscriptionId: "lago_subscription_1",
externalCustomerId: "tenant_1",
planCode: "business",
status: "active",
});
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request.subscription).toMatchObject({
external_customer_id: "tenant_1",
external_id: "sub_tenant_1_business",
plan_code: "business",
billing_time: "anniversary",
subscription_at: "2026-07-04T00:00:00.000Z",
});
expect(request.subscription).not.toHaveProperty("seatQuantity");
});
it("reads invoice status with optional tenant filter", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
invoices: [
{
lago_id: "invoice_1",
number: "LAG-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 4900,
issuing_date: "2026-07-04",
file_url: "https://files.example.test/invoice_1.pdf",
},
],
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.listInvoices({ tenantId: "tenant_1", page: 2, perPage: 10 })).resolves.toEqual([
{
provider: "lago",
providerInvoiceId: "invoice_1",
number: "LAG-001",
externalCustomerId: "tenant_1",
status: "finalized",
paymentStatus: "succeeded",
invoiceType: "subscription",
currency: "EUR",
totalAmountCents: 4900,
issuingDate: "2026-07-04",
fileUrl: "https://files.example.test/invoice_1.pdf",
},
]);
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices?external_customer_id=tenant_1&page=2&per_page=10");
});
it("downloads an invoice and maps the generated file url", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
invoice: {
lago_id: "invoice_1",
number: "LAG-001",
status: "finalized",
payment_status: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 4900,
issuing_date: "2026-07-04",
file_url: "https://files.example.test/invoice_1.pdf",
customer: {
external_id: "tenant_1",
},
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.downloadInvoice("invoice_1")).resolves.toMatchObject({
providerInvoiceId: "invoice_1",
externalCustomerId: "tenant_1",
fileUrl: "https://files.example.test/invoice_1.pdf",
});
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices/invoice_1/download");
expect(fetchImpl.mock.calls[0]?.[1]).toMatchObject({ method: "POST" });
});
it("updates an invoice payment status", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse({
invoice: {
lago_id: "invoice_1",
number: "LAG-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 99900,
issuing_date: "2026-07-06",
file_url: "https://files.example.test/invoice_1.pdf",
},
})
);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.updateInvoicePaymentStatus("invoice_1", "succeeded")).resolves.toMatchObject({
providerInvoiceId: "invoice_1",
paymentStatus: "succeeded",
});
expect(fetchImpl).toHaveBeenCalledWith(
"https://lago.example.test/api/v1/invoices/invoice_1",
expect.objectContaining({
method: "PUT",
body: JSON.stringify({
invoice: {
payment_status: "succeeded",
},
}),
})
);
});
it("returns null on 404 reads and throws clear errors for failed calls", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => new Response("{}", { status: 404 }));
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl,
});
await expect(gateway.getCustomer("tenant_missing")).resolves.toBeNull();
fetchImpl.mockResolvedValueOnce(new Response("{}", { status: 500 }));
await expect(gateway.listInvoices()).rejects.toMatchObject({
name: "LagoBillingGatewayError",
code: "REQUEST_FAILED",
status: 500,
message: "Lago request failed with status 500.",
});
});
it("rejects invalid configuration and invalid response shapes", async () => {
expect(() => normalizeLagoApiUrl("file:///tmp/lago")).toThrow(LagoBillingGatewayError);
expect(() => createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: " " })).toThrow(LagoBillingGatewayError);
const gateway = createLagoBillingGateway({
apiUrl: "https://lago.example.test",
apiKey: "secret_lago_key",
fetchImpl: vi.fn<typeof fetch>(async () => jsonResponse({ customer: { external_id: "tenant_1" } })),
});
await expect(gateway.createCustomer({ tenantId: "tenant_1", name: "Tenant" })).rejects.toMatchObject({
code: "RESPONSE_INVALID",
message: "Lago response shape is invalid.",
});
});
it("redacts Lago IDs and tokens for diagnostics", () => {
expect(redactLagoValue("secret_lago_key_123456")).toBe("secr…3456");
expect(redactLagoValue("short")).toBe("[redacted]");
expect(redactLagoValue(undefined)).toBeNull();
});
});
@@ -0,0 +1,319 @@
import { z } from "zod";
import type {
BillingGateway,
BillingGatewayCustomer,
BillingGatewayCustomerInput,
BillingGatewayInvoice,
BillingGatewayInvoiceListInput,
BillingGatewaySubscription,
BillingGatewaySubscriptionInput,
} from "./types.js";
const DEFAULT_LAGO_TIMEOUT_MS = 10_000;
const DEFAULT_LAGO_PER_PAGE = 20;
export type LagoBillingGatewayConfig = {
apiUrl: string;
apiKey: string;
timeoutMs?: number;
fetchImpl?: typeof fetch;
};
export class LagoBillingGatewayError extends Error {
readonly code: "CONFIG_INVALID" | "REQUEST_FAILED" | "RESPONSE_INVALID";
readonly status?: number;
constructor(message: string, code: LagoBillingGatewayError["code"], status?: number) {
super(message);
this.name = "LagoBillingGatewayError";
this.code = code;
this.status = status;
}
}
const nullableString = z.string().nullable().optional();
const lagoCustomerSchema = z.object({
lago_id: z.string(),
external_id: z.string(),
name: nullableString,
email: nullableString,
currency: nullableString,
created_at: nullableString,
});
const lagoSubscriptionSchema = z.object({
lago_id: z.string(),
external_id: z.string(),
external_customer_id: z.string(),
plan_code: z.string(),
status: z.string().nullable().optional(),
name: nullableString,
current_billing_period_started_at: nullableString,
current_billing_period_ending_at: nullableString,
created_at: nullableString,
});
const lagoInvoiceSchema = z.object({
lago_id: z.string(),
number: nullableString,
external_customer_id: nullableString,
customer: z
.object({
external_id: nullableString,
})
.nullable()
.optional(),
status: z.string().nullable().optional(),
payment_status: z.string().nullable().optional(),
invoice_type: nullableString,
currency: nullableString,
total_amount_cents: z.number().nullable().optional(),
issuing_date: nullableString,
file_url: nullableString,
});
const customerResponseSchema = z.object({ customer: lagoCustomerSchema });
const subscriptionResponseSchema = z.object({ subscription: lagoSubscriptionSchema });
const invoiceResponseSchema = z.object({ invoice: lagoInvoiceSchema });
const invoicesResponseSchema = z.object({ invoices: z.array(lagoInvoiceSchema) });
type LagoCustomer = z.infer<typeof lagoCustomerSchema>;
type LagoSubscription = z.infer<typeof lagoSubscriptionSchema>;
type LagoInvoice = z.infer<typeof lagoInvoiceSchema>;
export function createLagoBillingGateway(config: LagoBillingGatewayConfig): BillingGateway {
return new LagoBillingGateway(config);
}
export function normalizeLagoApiUrl(apiUrl: string): string {
let url: URL;
try {
url = new URL(apiUrl);
} catch {
throw new LagoBillingGatewayError("Lago API URL must be an absolute URL.", "CONFIG_INVALID");
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new LagoBillingGatewayError("Lago API URL must use http or https.", "CONFIG_INVALID");
}
url.pathname = url.pathname.replace(/\/+$/u, "");
return url.toString().replace(/\/$/u, "");
}
export function redactLagoValue(value: string | null | undefined): string | null {
if (!value) return null;
if (value.length <= 8) return "[redacted]";
return `${value.slice(0, 4)}…${value.slice(-4)}`;
}
class LagoBillingGateway implements BillingGateway {
private readonly apiUrl: string;
private readonly apiKey: string;
private readonly timeoutMs: number;
private readonly fetchImpl: typeof fetch;
constructor(config: LagoBillingGatewayConfig) {
this.apiUrl = normalizeLagoApiUrl(config.apiUrl);
this.apiKey = config.apiKey.trim();
if (!this.apiKey) {
throw new LagoBillingGatewayError("Lago API key is required.", "CONFIG_INVALID");
}
this.timeoutMs = normalizeTimeout(config.timeoutMs);
this.fetchImpl = config.fetchImpl ?? fetch;
}
async createCustomer(input: BillingGatewayCustomerInput): Promise<BillingGatewayCustomer> {
const response = await this.request("/customers", {
method: "POST",
body: {
customer: {
external_id: input.tenantId,
name: input.name,
...(input.email ? { email: input.email } : {}),
...(input.currency ? { currency: input.currency } : {}),
...(input.country ? { country: input.country } : {}),
...(input.timezone ? { timezone: input.timezone } : {}),
},
},
});
return toCustomer(parseLagoResponse(customerResponseSchema, response));
}
async getCustomer(tenantId: string): Promise<BillingGatewayCustomer | null> {
const response = await this.request(`/customers/${encodeURIComponent(tenantId)}`, { method: "GET", allowNotFound: true });
return response === null ? null : toCustomer(parseLagoResponse(customerResponseSchema, response));
}
async createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription> {
assertPositiveSeatQuantity(input.seatQuantity);
const response = await this.request("/subscriptions", {
method: "POST",
body: {
subscription: {
external_customer_id: input.tenantId,
external_id: input.subscriptionExternalId,
plan_code: input.planCode,
name: input.name ?? `${input.planCode} (${input.seatQuantity} seats)`,
billing_time: "anniversary",
...(input.subscriptionAt ? { subscription_at: toIsoString(input.subscriptionAt) } : {}),
...(input.endingAt ? { ending_at: toIsoString(input.endingAt) } : {}),
},
},
});
return toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
}
async getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null> {
const response = await this.request(`/subscriptions/${encodeURIComponent(subscriptionExternalId)}`, { method: "GET", allowNotFound: true });
return response === null ? null : toSubscription(parseLagoResponse(subscriptionResponseSchema, response));
}
async listInvoices(input: BillingGatewayInvoiceListInput = {}): Promise<BillingGatewayInvoice[]> {
const query = new URLSearchParams();
if (input.tenantId) query.set("external_customer_id", input.tenantId);
query.set("page", String(input.page ?? 1));
query.set("per_page", String(input.perPage ?? DEFAULT_LAGO_PER_PAGE));
const response = await this.request(`/invoices?${query.toString()}`, { method: "GET" });
return parseLagoResponse(invoicesResponseSchema, response).invoices.map(toInvoice);
}
async downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null> {
const id = providerInvoiceId.trim();
if (!id) {
throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID");
}
const response = await this.request(`/invoices/${encodeURIComponent(id)}/download`, { method: "POST", allowNotFound: true });
return response === null ? null : toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
}
async updateInvoicePaymentStatus(providerInvoiceId: string, paymentStatus: BillingGatewayInvoice["paymentStatus"]): Promise<BillingGatewayInvoice> {
const id = providerInvoiceId.trim();
if (!id) {
throw new LagoBillingGatewayError("Invoice id is required.", "CONFIG_INVALID");
}
if (paymentStatus !== "pending" && paymentStatus !== "succeeded" && paymentStatus !== "failed") {
throw new LagoBillingGatewayError("Invoice payment status is invalid.", "CONFIG_INVALID");
}
const response = await this.request(`/invoices/${encodeURIComponent(id)}`, {
method: "PUT",
body: {
invoice: {
payment_status: paymentStatus,
},
},
});
return toInvoice(parseLagoResponse(invoiceResponseSchema, response).invoice);
}
private async request(path: string, options: { method: "GET" | "POST" | "PUT"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const response = await this.fetchImpl(`${this.apiUrl}/api/v1${path}`, {
method: options.method,
headers: {
authorization: `Bearer ${this.apiKey}`,
accept: "application/json",
...(options.body ? { "content-type": "application/json" } : {}),
},
body: options.body ? JSON.stringify(options.body) : undefined,
signal: controller.signal,
});
if (response.status === 404 && options.allowNotFound) {
return null;
}
if (!response.ok) {
throw new LagoBillingGatewayError(`Lago request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
}
return await response.json();
} catch (error) {
if (error instanceof LagoBillingGatewayError) throw error;
throw new LagoBillingGatewayError("Lago request failed.", "REQUEST_FAILED");
} finally {
clearTimeout(timeout);
}
}
}
function parseLagoResponse<T>(schema: z.ZodType<T>, response: unknown): T {
const result = schema.safeParse(response);
if (!result.success) {
throw new LagoBillingGatewayError("Lago response shape is invalid.", "RESPONSE_INVALID");
}
return result.data;
}
function toCustomer(response: { customer: LagoCustomer }): BillingGatewayCustomer {
const customer = response.customer;
return {
provider: "lago",
externalId: customer.external_id,
providerCustomerId: customer.lago_id,
name: customer.name ?? null,
email: customer.email ?? null,
currency: customer.currency ?? null,
createdAt: customer.created_at ?? null,
};
}
function toSubscription(response: { subscription: LagoSubscription }): BillingGatewaySubscription {
const subscription = response.subscription;
return {
provider: "lago",
externalId: subscription.external_id,
providerSubscriptionId: subscription.lago_id,
externalCustomerId: subscription.external_customer_id,
planCode: subscription.plan_code,
status: normalizeSubscriptionStatus(subscription.status),
name: subscription.name ?? null,
currentBillingPeriodStartedAt: subscription.current_billing_period_started_at ?? null,
currentBillingPeriodEndingAt: subscription.current_billing_period_ending_at ?? null,
createdAt: subscription.created_at ?? null,
};
}
function toInvoice(invoice: LagoInvoice): BillingGatewayInvoice {
return {
provider: "lago",
providerInvoiceId: invoice.lago_id,
number: invoice.number ?? null,
externalCustomerId: invoice.external_customer_id ?? invoice.customer?.external_id ?? null,
status: normalizeInvoiceStatus(invoice.status),
paymentStatus: normalizePaymentStatus(invoice.payment_status),
invoiceType: invoice.invoice_type ?? null,
currency: invoice.currency ?? null,
totalAmountCents: invoice.total_amount_cents ?? null,
issuingDate: invoice.issuing_date ?? null,
fileUrl: invoice.file_url ?? null,
};
}
function normalizeTimeout(timeoutMs: number | undefined): number {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_LAGO_TIMEOUT_MS;
}
function assertPositiveSeatQuantity(seatQuantity: number): void {
if (!Number.isInteger(seatQuantity) || seatQuantity < 1) {
throw new LagoBillingGatewayError("Seat quantity must be a positive integer.", "CONFIG_INVALID");
}
}
function toIsoString(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
function normalizeSubscriptionStatus(value: string | null | undefined): BillingGatewaySubscription["status"] {
if (value === "pending" || value === "active" || value === "terminated" || value === "canceled" || value === "cancelled") return value;
return "unknown";
}
function normalizeInvoiceStatus(value: string | null | undefined): BillingGatewayInvoice["status"] {
if (value === "draft" || value === "finalized" || value === "voided" || value === "failed" || value === "pending") return value;
return "unknown";
}
function normalizePaymentStatus(value: string | null | undefined): BillingGatewayInvoice["paymentStatus"] {
if (value === "pending" || value === "succeeded" || value === "failed") return value;
return "unknown";
}
@@ -0,0 +1,202 @@
import { describe, expect, it, vi } from "vitest";
import {
createMolliePaymentGateway,
MolliePaymentGatewayError,
normalizeMollieApiUrl,
parseMollieWebhookEvent,
redactMollieValue,
resolveMollieWebhookPayment,
} from "./mollie.js";
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: {
"content-type": "application/json",
},
});
}
function molliePayment(overrides: Record<string, unknown> = {}) {
return {
id: "tr_123",
status: "open",
amount: { currency: "EUR", value: "49.00" },
amountRefunded: { currency: "EUR", value: "0.00" },
amountRemaining: { currency: "EUR", value: "49.00" },
paidAt: null,
expiresAt: "2026-07-05T00:00:00+00:00",
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
lagoCustomerId: null,
lagoSubscriptionId: null,
planCode: null,
seatQuantity: null,
},
_links: {
checkout: { href: "https://www.mollie.com/checkout/select-method/tr_123" },
},
...overrides,
};
}
describe("MolliePaymentGateway", () => {
it("creates checkout payments without HiveGrid domain data in the Mollie payload", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse(molliePayment()));
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
profileId: "pfl_123",
fetchImpl,
});
await expect(
gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
amountCents: 4900,
currency: "eur",
redirectUrl: "https://app.hivegrid.de/admin/billing/return?invoice=invoice_1",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
mollieCustomerId: "cst_123",
})
).resolves.toMatchObject({
provider: "mollie",
providerPaymentId: "tr_123",
externalId: "payment_1",
status: "open",
amountCents: 4900,
currency: "EUR",
checkoutUrl: "https://www.mollie.com/checkout/select-method/tr_123",
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
},
});
expect(fetchImpl).toHaveBeenCalledWith(
"https://api.mollie.com/v2/payments",
expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
authorization: "Bearer test_mollie_key",
"content-type": "application/json",
}),
})
);
const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body));
expect(request).toMatchObject({
amount: { currency: "EUR", value: "49.00" },
description: "Invoice invoice_1",
redirectUrl: "https://app.hivegrid.de/admin/billing/return?invoice=invoice_1",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
profileId: "pfl_123",
customerId: "cst_123",
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
},
});
expect(JSON.stringify(request)).not.toContain("business");
expect(JSON.stringify(request)).not.toContain("seat");
expect(JSON.stringify(request)).not.toContain("billing@example.test");
});
it("verifies classic Mollie webhooks by parsing the id and refetching payment status", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse(
molliePayment({
status: "paid",
paidAt: "2026-07-04T12:00:00+00:00",
})
)
);
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
const payment = await resolveMollieWebhookPayment(gateway, new URLSearchParams({ id: "tr_123" }));
expect(payment).toMatchObject({
providerPaymentId: "tr_123",
status: "paid",
paidAt: "2026-07-04T12:00:00+00:00",
});
expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://api.mollie.com/v2/payments/tr_123");
});
it("maps refunded amounts to refunded payment status", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () =>
jsonResponse(
molliePayment({
status: "paid",
amountRefunded: { currency: "EUR", value: "49.00" },
amountRemaining: { currency: "EUR", value: "0.00" },
})
)
);
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
await expect(gateway.getPayment("tr_123")).resolves.toMatchObject({
status: "refunded",
amountRefundedCents: 4900,
amountRemainingCents: 0,
});
});
it("returns null on 404 reads and throws clear errors for failed calls", async () => {
const fetchImpl = vi.fn<typeof fetch>(async () => new Response("{}", { status: 404 }));
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl,
});
await expect(gateway.getPayment("tr_missing")).resolves.toBeNull();
fetchImpl.mockResolvedValueOnce(new Response("{}", { status: 500 }));
await expect(
gateway.createPayment({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
amountCents: 4900,
currency: "EUR",
redirectUrl: "https://app.hivegrid.de/return",
webhookUrl: "https://api.hivegrid.de/v1/billing/mollie/webhooks",
})
).rejects.toMatchObject({
name: "MolliePaymentGatewayError",
code: "REQUEST_FAILED",
status: 500,
message: "Mollie request failed with status 500.",
});
});
it("rejects invalid config, invalid webhook payloads and invalid response shapes", async () => {
expect(() => normalizeMollieApiUrl("file:///tmp/mollie")).toThrow(MolliePaymentGatewayError);
expect(() => createMolliePaymentGateway({ apiKey: " " })).toThrow(MolliePaymentGatewayError);
expect(() => parseMollieWebhookEvent({})).toThrow(MolliePaymentGatewayError);
const gateway = createMolliePaymentGateway({
apiKey: "test_mollie_key",
fetchImpl: vi.fn<typeof fetch>(async () => jsonResponse({ status: "paid" })),
});
await expect(gateway.getPayment("tr_123")).rejects.toMatchObject({
code: "RESPONSE_INVALID",
message: "Mollie response shape is invalid.",
});
});
it("redacts Mollie IDs and tokens for diagnostics", () => {
expect(redactMollieValue("test_mollie_key_123456")).toBe("test…3456");
expect(redactMollieValue("short")).toBe("[redacted]");
expect(redactMollieValue(undefined)).toBeNull();
});
});
@@ -0,0 +1,312 @@
import { z } from "zod";
import type { PaymentGateway, PaymentGatewayCreatePaymentInput, PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
const DEFAULT_MOLLIE_API_URL = "https://api.mollie.com";
const DEFAULT_MOLLIE_TIMEOUT_MS = 10_000;
export type MolliePaymentGatewayConfig = {
apiKey: string;
apiUrl?: string;
profileId?: string | null;
timeoutMs?: number;
fetchImpl?: typeof fetch;
};
export type MollieWebhookEvent = {
providerPaymentId: string;
};
export class MolliePaymentGatewayError extends Error {
readonly code: "CONFIG_INVALID" | "REQUEST_FAILED" | "RESPONSE_INVALID" | "WEBHOOK_INVALID" | "WEBHOOK_PAYMENT_NOT_FOUND";
readonly status?: number;
constructor(message: string, code: MolliePaymentGatewayError["code"], status?: number) {
super(message);
this.name = "MolliePaymentGatewayError";
this.code = code;
this.status = status;
}
}
const amountSchema = z.object({
currency: z.string().nullable().optional(),
value: z.string().nullable().optional(),
});
const metadataSchema = z
.object({
tenantId: z.string().nullable().optional(),
invoiceExternalId: z.string().nullable().optional(),
paymentExternalId: z.string().nullable().optional(),
lagoCustomerId: z.string().nullable().optional(),
lagoSubscriptionId: z.string().nullable().optional(),
planCode: z.string().nullable().optional(),
seatQuantity: z.union([z.number(), z.string()]).nullable().optional(),
})
.nullable()
.optional();
const molliePaymentSchema = z.object({
id: z.string(),
status: z.string().nullable().optional(),
amount: amountSchema.nullable().optional(),
amountRefunded: amountSchema.nullable().optional(),
amountRemaining: amountSchema.nullable().optional(),
paidAt: z.string().nullable().optional(),
expiresAt: z.string().nullable().optional(),
metadata: metadataSchema,
_links: z
.object({
checkout: z
.object({
href: z.string().nullable().optional(),
})
.nullable()
.optional(),
})
.nullable()
.optional(),
});
type MolliePaymentResponse = z.infer<typeof molliePaymentSchema>;
export function createMolliePaymentGateway(config: MolliePaymentGatewayConfig): PaymentGateway {
return new MolliePaymentGateway(config);
}
export function normalizeMollieApiUrl(apiUrl: string | undefined): string {
const rawUrl = apiUrl?.trim() || DEFAULT_MOLLIE_API_URL;
let url: URL;
try {
url = new URL(rawUrl);
} catch {
throw new MolliePaymentGatewayError("Mollie API URL must be an absolute URL.", "CONFIG_INVALID");
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new MolliePaymentGatewayError("Mollie API URL must use http or https.", "CONFIG_INVALID");
}
url.pathname = url.pathname.replace(/\/+$/u, "");
return url.toString().replace(/\/$/u, "");
}
export function redactMollieValue(value: string | null | undefined): string | null {
if (!value) return null;
if (value.length <= 8) return "[redacted]";
return `${value.slice(0, 4)}…${value.slice(-4)}`;
}
export function parseMollieWebhookEvent(input: URLSearchParams | FormData | Record<string, unknown>): MollieWebhookEvent {
const id = getWebhookValue(input, "id")?.trim();
if (!id) {
throw new MolliePaymentGatewayError("Mollie webhook is missing payment id.", "WEBHOOK_INVALID");
}
return { providerPaymentId: id };
}
export async function resolveMollieWebhookPayment(gateway: PaymentGateway, input: URLSearchParams | FormData | Record<string, unknown>): Promise<PaymentGatewayPayment> {
const event = parseMollieWebhookEvent(input);
const payment = await gateway.getPayment(event.providerPaymentId);
if (!payment) {
throw new MolliePaymentGatewayError("Mollie webhook payment could not be verified.", "WEBHOOK_PAYMENT_NOT_FOUND", 404);
}
return payment;
}
class MolliePaymentGateway implements PaymentGateway {
private readonly apiUrl: string;
private readonly apiKey: string;
private readonly profileId: string | null;
private readonly timeoutMs: number;
private readonly fetchImpl: typeof fetch;
constructor(config: MolliePaymentGatewayConfig) {
this.apiUrl = normalizeMollieApiUrl(config.apiUrl);
this.apiKey = config.apiKey.trim();
if (!this.apiKey) {
throw new MolliePaymentGatewayError("Mollie API key is required.", "CONFIG_INVALID");
}
this.profileId = config.profileId?.trim() || null;
this.timeoutMs = normalizeTimeout(config.timeoutMs);
this.fetchImpl = config.fetchImpl ?? fetch;
}
async createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment> {
validateCreatePaymentInput(input);
const response = await this.request("/payments", {
method: "POST",
body: {
amount: {
currency: input.currency.toUpperCase(),
value: centsToMollieValue(input.amountCents),
},
description: input.description?.trim() || `Invoice ${input.invoiceExternalId}`,
redirectUrl: input.redirectUrl,
webhookUrl: input.webhookUrl,
...(this.profileId ? { profileId: this.profileId } : {}),
...(input.mollieCustomerId ? { customerId: input.mollieCustomerId } : {}),
metadata: {
tenantId: input.tenantId,
invoiceExternalId: input.invoiceExternalId,
...(input.paymentExternalId ? { paymentExternalId: input.paymentExternalId } : {}),
...(input.lagoCustomerId ? { lagoCustomerId: input.lagoCustomerId } : {}),
...(input.lagoSubscriptionId ? { lagoSubscriptionId: input.lagoSubscriptionId } : {}),
...(input.planCode ? { planCode: input.planCode } : {}),
...(input.seatQuantity ? { seatQuantity: input.seatQuantity } : {}),
},
},
});
return toPayment(parseMollieResponse(response));
}
async getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null> {
const id = providerPaymentId.trim();
if (!id) {
throw new MolliePaymentGatewayError("Mollie payment id is required.", "CONFIG_INVALID");
}
const response = await this.request(`/payments/${encodeURIComponent(id)}`, { method: "GET", allowNotFound: true });
return response === null ? null : toPayment(parseMollieResponse(response));
}
private async request(path: string, options: { method: "GET" | "POST"; body?: unknown; allowNotFound?: boolean }): Promise<unknown | null> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const response = await this.fetchImpl(`${this.apiUrl}/v2${path}`, {
method: options.method,
headers: {
authorization: `Bearer ${this.apiKey}`,
accept: "application/json",
...(options.body ? { "content-type": "application/json" } : {}),
},
body: options.body ? JSON.stringify(options.body) : undefined,
signal: controller.signal,
});
if (response.status === 404 && options.allowNotFound) {
return null;
}
if (!response.ok) {
throw new MolliePaymentGatewayError(`Mollie request failed with status ${response.status}.`, "REQUEST_FAILED", response.status);
}
return await response.json();
} catch (error) {
if (error instanceof MolliePaymentGatewayError) throw error;
throw new MolliePaymentGatewayError("Mollie request failed.", "REQUEST_FAILED");
} finally {
clearTimeout(timeout);
}
}
}
function parseMollieResponse(response: unknown): MolliePaymentResponse {
const result = molliePaymentSchema.safeParse(response);
if (!result.success) {
throw new MolliePaymentGatewayError("Mollie response shape is invalid.", "RESPONSE_INVALID");
}
return result.data;
}
function toPayment(payment: MolliePaymentResponse): PaymentGatewayPayment {
const metadata = payment.metadata ?? {};
return {
provider: "mollie",
providerPaymentId: payment.id,
externalId: metadata.paymentExternalId ?? null,
status: normalizePaymentStatus(payment.status, payment.amountRefunded?.value),
amountCents: mollieValueToCents(payment.amount?.value),
amountRefundedCents: mollieValueToCents(payment.amountRefunded?.value),
amountRemainingCents: mollieValueToCents(payment.amountRemaining?.value),
currency: payment.amount?.currency ?? null,
checkoutUrl: payment._links?.checkout?.href ?? null,
paidAt: payment.paidAt ?? null,
expiresAt: payment.expiresAt ?? null,
metadata: {
tenantId: metadata.tenantId ?? null,
invoiceExternalId: metadata.invoiceExternalId ?? null,
paymentExternalId: metadata.paymentExternalId ?? null,
lagoCustomerId: metadata.lagoCustomerId ?? null,
lagoSubscriptionId: metadata.lagoSubscriptionId ?? null,
planCode: metadata.planCode ?? null,
seatQuantity: normalizeMetadataSeatQuantity(metadata.seatQuantity),
},
};
}
function normalizeMetadataSeatQuantity(value: string | number | null | undefined): number | null {
if (typeof value === "number" && Number.isFinite(value)) {
const normalized = Math.trunc(value);
return normalized > 0 ? normalized : null;
}
if (typeof value === "string" && value.trim()) {
const normalized = Number.parseInt(value, 10);
return Number.isFinite(normalized) && normalized > 0 ? normalized : null;
}
return null;
}
function validateCreatePaymentInput(input: PaymentGatewayCreatePaymentInput): void {
if (!input.tenantId.trim()) throw new MolliePaymentGatewayError("Tenant id is required.", "CONFIG_INVALID");
if (!input.invoiceExternalId.trim()) throw new MolliePaymentGatewayError("Invoice reference is required.", "CONFIG_INVALID");
if (!Number.isInteger(input.amountCents) || input.amountCents < 1) {
throw new MolliePaymentGatewayError("Amount must be a positive cent integer.", "CONFIG_INVALID");
}
if (!/^[A-Za-z]{3}$/u.test(input.currency)) {
throw new MolliePaymentGatewayError("Currency must be a three-letter ISO code.", "CONFIG_INVALID");
}
assertHttpUrl(input.redirectUrl, "Redirect URL");
assertHttpUrl(input.webhookUrl, "Webhook URL");
}
function assertHttpUrl(value: string, label: string): void {
let url: URL;
try {
url = new URL(value);
} catch {
throw new MolliePaymentGatewayError(`${label} must be an absolute URL.`, "CONFIG_INVALID");
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new MolliePaymentGatewayError(`${label} must use http or https.`, "CONFIG_INVALID");
}
}
function normalizeTimeout(timeoutMs: number | undefined): number {
return typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.trunc(timeoutMs) : DEFAULT_MOLLIE_TIMEOUT_MS;
}
function centsToMollieValue(amountCents: number): string {
return (amountCents / 100).toFixed(2);
}
function mollieValueToCents(value: string | null | undefined): number | null {
if (!value) return null;
const normalized = value.trim();
if (!/^-?\d+(\.\d{1,2})?$/u.test(normalized)) return null;
return Math.round(Number(normalized) * 100);
}
function normalizePaymentStatus(status: string | null | undefined, refundedValue: string | null | undefined): PaymentGatewayPaymentStatus {
const refundedCents = mollieValueToCents(refundedValue);
if (typeof refundedCents === "number" && refundedCents > 0) return "refunded";
if (
status === "open" ||
status === "pending" ||
status === "authorized" ||
status === "paid" ||
status === "failed" ||
status === "expired" ||
status === "canceled"
) {
return status;
}
if (status === "charged_back") return "charged_back";
return "unknown";
}
function getWebhookValue(input: URLSearchParams | FormData | Record<string, unknown>, key: string): string | null {
if (input instanceof URLSearchParams || input instanceof FormData) {
const value = input.get(key);
return typeof value === "string" ? value : null;
}
const value = input[key];
return typeof value === "string" ? value : null;
}
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import { runBillingSandboxFlow } from "./sandbox-flow.js";
describe("runBillingSandboxFlow", () => {
it("proves the BILL-07 Lago/Mollie billing core with deterministic sandbox stubs", async () => {
const result = await runBillingSandboxFlow({
runId: "unit",
now: new Date("2026-07-04T10:00:00.000Z"),
moduleKey: "crm-basic",
seatQuantity: 5,
});
expect(result.ok).toBe(true);
expect(result.tenantId).toBe("hg-stg-bill-07-unit");
expect(result.customer.providerCustomerId).toBe("lago_customer_hg-stg-bill-07-unit");
expect(result.subscription.planCode).toBe("hg-stg-plan-bill-07-unit");
expect(result.invoice.providerInvoiceId).toBe("lago_invoice_subscription-unit");
expect(result.payment.status).toBe("paid");
expect(result.activeState).toMatchObject({
status: "active",
readOnly: false,
planCode: "hg-stg-plan-bill-07-unit",
seatQuantity: 5,
lastInvoiceExternalId: "lago_invoice_subscription-unit",
lastPaymentExternalId: "tr_payment-unit",
});
expect(result.gate).toMatchObject({
moduleKey: "crm-basic",
activeAllowed: true,
activeReadOnly: false,
failedReadOnly: true,
pastDueReadOnly: true,
frozenReadOnly: true,
});
expect(result.failedState.status).toBe("past_due");
expect(result.pastDueState.status).toBe("past_due");
expect(result.frozenState.status).toBe("frozen");
expect(result.referencesVisible).toBe(true);
expect(result.audit.auditEvents).toBeGreaterThanOrEqual(5);
expect(result.audit.activities).toBeGreaterThanOrEqual(5);
expect(result.steps.map((step) => [step.key, step.ok])).toEqual([
["lago.customer", true],
["lago.subscription", true],
["mollie.payment", true],
["local.sync", true],
["module.gate", true],
["references.audit", true],
["negative.failed-expired", true],
["negative.frozen", true],
]);
});
});
@@ -0,0 +1,595 @@
import {
applyLagoSubscriptionSync,
applyMolliePaymentSync,
type BillingSyncClient,
type BillingSyncResult,
} from "@hivegrid/db/billing-sync.server";
import {
resolveTenantBillingState,
type TenantBillingState,
type TenantBillingStateClient,
} from "@hivegrid/db/billing-domain.server";
import type {
BillingGateway,
BillingGatewayCustomer,
BillingGatewayInvoice,
BillingGatewaySubscription,
PaymentGateway,
PaymentGatewayCreatePaymentInput,
PaymentGatewayPayment,
PaymentGatewayPaymentStatus,
} from "./types.js";
export type BillingSandboxFlowInput = {
runId?: string;
tenantId?: string;
tenantName?: string;
planCode?: string;
seatQuantity?: number;
moduleKey?: string;
now?: Date;
};
export type BillingSandboxFlowStep = {
key: string;
ok: boolean;
detail: string;
};
export type BillingSandboxFlowResult = {
ok: boolean;
mode: "stub";
runId: string;
tenantId: string;
planCode: string;
seatQuantity: number;
customer: BillingGatewayCustomer;
subscription: BillingGatewaySubscription;
invoice: BillingGatewayInvoice;
payment: PaymentGatewayPayment;
activeState: TenantBillingState;
failedState: TenantBillingState;
pastDueState: TenantBillingState;
frozenState: TenantBillingState;
syncResults: {
lagoActive: BillingSyncResult;
molliePaid: BillingSyncResult;
mollieFailed: BillingSyncResult;
mollieExpired: BillingSyncResult;
lagoFrozen: BillingSyncResult;
};
gate: {
moduleKey: string;
activeAllowed: boolean;
activeReadOnly: boolean;
failedReadOnly: boolean;
pastDueReadOnly: boolean;
frozenReadOnly: boolean;
};
audit: {
auditEvents: number;
activities: number;
};
referencesVisible: boolean;
steps: BillingSandboxFlowStep[];
};
type SandboxProduct = {
id: string;
code: string;
lagoPlanCode: string;
title: string;
features: Array<{
code: string;
name: string;
order: number;
title: string;
type: number;
value: number;
quotaValue: unknown | null;
accumulate: boolean;
}>;
};
type SandboxState = {
idempotency: Map<string, { responseBody: unknown }>;
subscriptions: Map<string, Record<string, unknown> & { id: string; tenantId: string }>;
products: SandboxProduct[];
tenantProducts: Array<Record<string, unknown> & { id: string; tenantSubscriptionId: string }>;
auditEvents: unknown[];
activities: unknown[];
customers: Map<string, BillingGatewayCustomer>;
providerSubscriptions: Map<string, BillingGatewaySubscription>;
invoices: Map<string, BillingGatewayInvoice[]>;
payments: Map<string, PaymentGatewayPayment>;
};
const INCLUDED_LIMIT_TYPE = 1;
type IdempotencyFindUniqueArgs = Parameters<BillingSyncClient["idempotencyKey"]["findUnique"]>[0];
type IdempotencyCreateArgs = Parameters<BillingSyncClient["idempotencyKey"]["create"]>[0];
type AuditCreateArgs = Parameters<BillingSyncClient["auditEvent"]["create"]>[0];
type ActivityCreateArgs = Parameters<BillingSyncClient["activity"]["create"]>[0];
type TenantSubscriptionUpsertArgs = Parameters<BillingSyncClient["tenantSubscription"]["upsert"]>[0];
type TenantSubscriptionFindUniqueArgs = Parameters<TenantBillingStateClient["tenantSubscription"]["findUnique"]>[0];
type SubscriptionProductFindFirstArgs = Parameters<BillingSyncClient["subscriptionProduct"]["findFirst"]>[0];
type TenantSubscriptionProductFindFirstArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["findFirst"]>[0];
type TenantSubscriptionProductCreateArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["create"]>[0];
type TenantSubscriptionProductUpdateArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["update"]>[0];
type TenantSubscriptionProductUpdateManyArgs = Parameters<BillingSyncClient["tenantSubscriptionProduct"]["updateMany"]>[0];
function normalizeRunId(value: string | undefined): string {
const fallback = `bill-07-${Date.now().toString(36)}`;
return (value ?? fallback).trim().toLowerCase().replace(/[^a-z0-9-]+/gu, "-").replace(/^-+|-+$/gu, "") || fallback;
}
function positiveSeatQuantity(value: number | undefined): number {
return Number.isInteger(value) && value && value > 0 ? value : 3;
}
function createSandboxState(input: Required<Pick<BillingSandboxFlowInput, "planCode" | "moduleKey">>): SandboxState {
return {
idempotency: new Map(),
subscriptions: new Map(),
products: [
{
id: `product_${input.planCode}`,
code: input.planCode,
lagoPlanCode: input.planCode,
title: `Sandbox ${input.planCode}`,
features: [
{
code: input.moduleKey,
name: input.moduleKey,
order: 1,
title: "Sandbox module",
type: INCLUDED_LIMIT_TYPE,
value: 0,
quotaValue: null,
accumulate: false,
},
],
},
],
tenantProducts: [],
auditEvents: [],
activities: [],
customers: new Map(),
providerSubscriptions: new Map(),
invoices: new Map(),
payments: new Map(),
};
}
function createSandboxClient(state: SandboxState): BillingSyncClient & TenantBillingStateClient {
return {
idempotencyKey: {
async findUnique({ where }: IdempotencyFindUniqueArgs) {
const row = state.idempotency.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`);
return row
? ({
id: "idem_1",
createdAt: new Date("2026-07-04T00:00:00.000Z"),
updatedAt: new Date("2026-07-04T00:00:00.000Z"),
expiresAt: null,
scope: where.idempotency_key_scope_key.scope,
key: where.idempotency_key_scope_key.key,
requestHash: "sandbox",
responseStatus: 200,
responseBody: row.responseBody,
responseHeaders: null,
} as never)
: null;
},
async create({ data }: IdempotencyCreateArgs) {
state.idempotency.set(`${data.scope}:${data.key}`, { responseBody: data.responseBody });
return { id: `idem_${state.idempotency.size}`, createdAt: new Date(), updatedAt: new Date(), ...data } as never;
},
},
auditEvent: {
async findFirst() {
return null;
},
async create({ data }: AuditCreateArgs) {
state.auditEvents.push(data);
return { id: `audit_${state.auditEvents.length}`, createdAt: new Date(), ...data } as never;
},
},
activity: {
async create({ data }: ActivityCreateArgs) {
state.activities.push(data);
return { id: `activity_${state.activities.length}` };
},
},
tenantSubscription: {
async upsert({ where, create, update }: TenantSubscriptionUpsertArgs) {
const current = state.subscriptions.get(where.tenantId);
const next = {
...(current ?? { id: `tenant_subscription_${state.subscriptions.size + 1}` }),
...(current ? update : create),
tenantId: where.tenantId,
};
state.subscriptions.set(where.tenantId, next as Record<string, unknown> & { id: string; tenantId: string });
return next as never;
},
async findUnique({ where }: TenantSubscriptionFindUniqueArgs) {
const subscription = state.subscriptions.get(where.tenantId);
if (!subscription) return null;
const products = state.tenantProducts
.filter((tenantProduct) => tenantProduct.tenantSubscriptionId === subscription.id)
.map((tenantProduct) => {
const product = state.products.find((item) => item.id === tenantProduct.subscriptionProductId);
if (!product) return null;
return {
...tenantProduct,
createdAt: tenantProduct.createdAt instanceof Date ? tenantProduct.createdAt : new Date("2026-07-04T00:00:00.000Z"),
subscriptionProduct: product,
};
})
.filter((product): product is NonNullable<typeof product> => Boolean(product));
return { ...subscription, products } as never;
},
},
subscriptionProduct: {
async findFirst({ where }: SubscriptionProductFindFirstArgs) {
return (
state.products.find((product) =>
where.OR.some((condition) => condition.id === product.id || condition.code === product.code || condition.lagoPlanCode === product.lagoPlanCode)
) ?? null
);
},
},
tenantSubscriptionProduct: {
async findFirst({ where }: TenantSubscriptionProductFindFirstArgs) {
return (
state.tenantProducts.find(
(product) =>
product.tenantSubscriptionId === where.tenantSubscriptionId &&
where.OR.some(
(condition) =>
condition.lagoSubscriptionId === product.lagoSubscriptionId ||
condition.subscriptionProductId === product.subscriptionProductId ||
condition.planCode === product.planCode
)
) ?? null
);
},
async create({ data }: TenantSubscriptionProductCreateArgs) {
const row = { id: `tenant_product_${state.tenantProducts.length + 1}`, createdAt: new Date("2026-07-04T00:00:00.000Z"), ...data };
state.tenantProducts.push(row as unknown as Record<string, unknown> & { id: string; tenantSubscriptionId: string });
return row;
},
async update({ where, data }: TenantSubscriptionProductUpdateArgs) {
const index = state.tenantProducts.findIndex((row) => row.id === where.id);
state.tenantProducts[index] = { ...state.tenantProducts[index], ...data };
return state.tenantProducts[index];
},
async updateMany({ where, data }: TenantSubscriptionProductUpdateManyArgs) {
// Mirrors endOtherActivePlanProducts' where shape: scalar tenantSubscriptionId,
// id:{not}, cancelledAt:null and an OR over endsAt (null | { gt }).
const w = where as {
tenantSubscriptionId?: string;
id?: { not?: string };
cancelledAt?: unknown;
OR?: Array<{ endsAt?: unknown }>;
};
let count = 0;
state.tenantProducts = state.tenantProducts.map((row) => {
const current = row as Record<string, unknown>;
if (w.tenantSubscriptionId !== undefined && current.tenantSubscriptionId !== w.tenantSubscriptionId) return row;
if (w.id && "not" in w.id && current.id === w.id.not) return row;
if (w.cancelledAt === null && current.cancelledAt != null) return row;
if (Array.isArray(w.OR)) {
const endsAt = current.endsAt as Date | null | undefined;
const matchesOr = w.OR.some((condition) => {
const value = condition.endsAt as unknown;
if (value === null) return endsAt == null;
if (value && typeof value === "object" && "gt" in (value as Record<string, unknown>)) {
return endsAt != null && endsAt > (value as { gt: Date }).gt;
}
return false;
});
if (!matchesOr) return row;
}
count += 1;
return { ...current, ...(data as Record<string, unknown>) } as (typeof state.tenantProducts)[number];
});
return { count };
},
},
} as unknown as BillingSyncClient & TenantBillingStateClient;
}
function createSandboxBillingGateway(state: SandboxState, now: Date): BillingGateway {
return {
async createCustomer(input) {
const customer: BillingGatewayCustomer = {
provider: "lago",
externalId: input.tenantId,
providerCustomerId: `lago_customer_${input.tenantId}`,
name: input.name,
email: input.email ?? null,
currency: input.currency ?? "EUR",
createdAt: now.toISOString(),
};
state.customers.set(input.tenantId, customer);
return customer;
},
async getCustomer(tenantId) {
return state.customers.get(tenantId) ?? null;
},
async createSubscription(input) {
const subscription: BillingGatewaySubscription = {
provider: "lago",
externalId: input.subscriptionExternalId,
providerSubscriptionId: `lago_subscription_${input.subscriptionExternalId}`,
externalCustomerId: input.tenantId,
planCode: input.planCode,
status: "active",
name: input.name ?? `${input.planCode} (${input.seatQuantity} seats)`,
currentBillingPeriodStartedAt: now.toISOString(),
currentBillingPeriodEndingAt: new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString(),
createdAt: now.toISOString(),
};
const invoice: BillingGatewayInvoice = {
provider: "lago",
providerInvoiceId: `lago_invoice_${input.subscriptionExternalId}`,
number: `HG-${input.subscriptionExternalId}`,
externalCustomerId: input.tenantId,
status: "finalized",
paymentStatus: "pending",
invoiceType: "subscription",
currency: "EUR",
totalAmountCents: input.seatQuantity * 2_900,
issuingDate: now.toISOString(),
fileUrl: `https://lago.test/invoices/lago_invoice_${input.subscriptionExternalId}.pdf`,
};
state.providerSubscriptions.set(input.subscriptionExternalId, subscription);
state.invoices.set(input.tenantId, [invoice]);
return subscription;
},
async getSubscription(subscriptionExternalId) {
return state.providerSubscriptions.get(subscriptionExternalId) ?? null;
},
async listInvoices(input = {}) {
return input.tenantId ? state.invoices.get(input.tenantId) ?? [] : [...state.invoices.values()].flat();
},
async downloadInvoice(providerInvoiceId) {
return [...state.invoices.values()].flat().find((invoice) => invoice.providerInvoiceId === providerInvoiceId) ?? null;
},
async updateInvoicePaymentStatus(providerInvoiceId, paymentStatus) {
const invoice = [...state.invoices.values()].flat().find((item) => item.providerInvoiceId === providerInvoiceId);
if (!invoice) {
throw new Error(`Sandbox invoice ${providerInvoiceId} not found.`);
}
invoice.paymentStatus = paymentStatus;
return invoice;
},
};
}
function createSandboxPaymentGateway(state: SandboxState): PaymentGateway {
return {
async createPayment(input: PaymentGatewayCreatePaymentInput) {
const providerPaymentId = `tr_${input.paymentExternalId ?? input.invoiceExternalId}`;
const payment: PaymentGatewayPayment = {
provider: "mollie",
providerPaymentId,
externalId: input.paymentExternalId ?? null,
status: "open",
amountCents: input.amountCents,
amountRefundedCents: 0,
amountRemainingCents: input.amountCents,
currency: input.currency,
checkoutUrl: `https://mollie.test/checkout/${providerPaymentId}`,
paidAt: null,
expiresAt: null,
metadata: {
tenantId: input.tenantId,
invoiceExternalId: input.invoiceExternalId,
paymentExternalId: input.paymentExternalId ?? null,
lagoCustomerId: input.lagoCustomerId ?? null,
lagoSubscriptionId: input.lagoSubscriptionId ?? null,
planCode: input.planCode ?? null,
seatQuantity: input.seatQuantity ?? null,
},
};
state.payments.set(providerPaymentId, payment);
return payment;
},
async getPayment(providerPaymentId) {
return state.payments.get(providerPaymentId) ?? null;
},
};
}
function setSandboxPaymentStatus(state: SandboxState, providerPaymentId: string, status: PaymentGatewayPaymentStatus, at: Date): PaymentGatewayPayment {
const current = state.payments.get(providerPaymentId);
if (!current) throw new Error(`Sandbox payment ${providerPaymentId} not found.`);
const next: PaymentGatewayPayment = {
...current,
status,
paidAt: status === "paid" ? at.toISOString() : current.paidAt,
expiresAt: status === "expired" ? at.toISOString() : current.expiresAt,
amountRemainingCents: status === "paid" ? 0 : current.amountRemainingCents,
};
state.payments.set(providerPaymentId, next);
return next;
}
function moduleAllowed(state: TenantBillingState, moduleKey: string): boolean {
return !state.readOnly && state.entitlements.some((entitlement) => entitlement.featureKey === moduleKey && entitlement.enabled);
}
function buildStep(key: string, ok: boolean, detail: string): BillingSandboxFlowStep {
return { key, ok, detail };
}
export async function runBillingSandboxFlow(input: BillingSandboxFlowInput = {}): Promise<BillingSandboxFlowResult> {
const runId = normalizeRunId(input.runId);
const tenantId = input.tenantId ?? `hg-stg-bill-07-${runId}`;
const tenantName = input.tenantName ?? `BILL-07 Sandbox ${runId}`;
const planCode = input.planCode ?? `hg-stg-plan-bill-07-${runId}`;
const seatQuantity = positiveSeatQuantity(input.seatQuantity);
const moduleKey = input.moduleKey ?? "billing-sandbox";
const now = input.now ?? new Date();
const state = createSandboxState({ planCode, moduleKey });
const client = createSandboxClient(state);
const billingGateway = createSandboxBillingGateway(state, now);
const paymentGateway = createSandboxPaymentGateway(state);
const customer = await billingGateway.createCustomer({
tenantId,
name: tenantName,
email: `${runId}@sandbox.hivegrid.test`,
currency: "EUR",
country: "DE",
timezone: "Europe/Berlin",
});
const subscription = await billingGateway.createSubscription({
tenantId,
subscriptionExternalId: `subscription-${runId}`,
planCode,
seatQuantity,
subscriptionAt: now,
});
const [invoice] = await billingGateway.listInvoices({ tenantId, perPage: 1 });
if (!invoice) throw new Error("Sandbox Lago invoice was not created.");
const payment = await paymentGateway.createPayment({
tenantId,
invoiceExternalId: invoice.providerInvoiceId,
amountCents: invoice.totalAmountCents ?? 8_700,
currency: invoice.currency ?? "EUR",
redirectUrl: "https://app.hivegrid.test/billing/return",
webhookUrl: "https://api.hivegrid.test/v1/billing/mollie/webhooks",
paymentExternalId: `payment-${runId}`,
mollieCustomerId: `mollie_customer_${tenantId}`,
});
const paidPayment = setSandboxPaymentStatus(state, payment.providerPaymentId, "paid", now);
const lagoActive = await applyLagoSubscriptionSync(
{
tenantId,
eventKey: `sandbox:lago:active:${runId}`,
lagoCustomerId: customer.providerCustomerId,
lagoSubscriptionId: subscription.providerSubscriptionId,
status: "active",
planCode,
seatQuantity,
currentPeriodStart: new Date(subscription.currentBillingPeriodStartedAt ?? now),
currentPeriodEnd: new Date(subscription.currentBillingPeriodEndingAt ?? now),
invoiceExternalId: invoice.providerInvoiceId,
receivedAt: now,
},
client
);
const molliePaid = await applyMolliePaymentSync(
{
tenantId,
eventKey: `sandbox:mollie:paid:${runId}`,
mollieCustomerId: `mollie_customer_${tenantId}`,
paymentExternalId: paidPayment.providerPaymentId,
invoiceExternalId: invoice.providerInvoiceId,
status: paidPayment.status,
receivedAt: now,
},
client
);
const activeState = await resolveTenantBillingState(tenantId, { client, now });
const activeAllowed = moduleAllowed(activeState, moduleKey);
const failedPayment = setSandboxPaymentStatus(state, payment.providerPaymentId, "failed", new Date(now.getTime() + 30_000));
const mollieFailed = await applyMolliePaymentSync(
{
tenantId,
eventKey: `sandbox:mollie:failed:${runId}`,
mollieCustomerId: `mollie_customer_${tenantId}`,
paymentExternalId: failedPayment.providerPaymentId,
invoiceExternalId: invoice.providerInvoiceId,
status: failedPayment.status,
receivedAt: new Date(now.getTime() + 30_000),
},
client
);
const failedState = await resolveTenantBillingState(tenantId, { client, now: new Date(now.getTime() + 30_000) });
const expiredPayment = setSandboxPaymentStatus(state, payment.providerPaymentId, "expired", new Date(now.getTime() + 60_000));
const mollieExpired = await applyMolliePaymentSync(
{
tenantId,
eventKey: `sandbox:mollie:expired:${runId}`,
mollieCustomerId: `mollie_customer_${tenantId}`,
paymentExternalId: expiredPayment.providerPaymentId,
invoiceExternalId: invoice.providerInvoiceId,
status: expiredPayment.status,
receivedAt: new Date(now.getTime() + 60_000),
},
client
);
const pastDueState = await resolveTenantBillingState(tenantId, { client, now: new Date(now.getTime() + 60_000) });
const lagoFrozen = await applyLagoSubscriptionSync(
{
tenantId,
eventKey: `sandbox:lago:frozen:${runId}`,
lagoCustomerId: customer.providerCustomerId,
lagoSubscriptionId: subscription.providerSubscriptionId,
status: "paused",
planCode,
seatQuantity,
invoiceExternalId: invoice.providerInvoiceId,
receivedAt: new Date(now.getTime() + 120_000),
},
client
);
const frozenState = await resolveTenantBillingState(tenantId, { client, now: new Date(now.getTime() + 120_000) });
const referencesVisible = Boolean(activeState.lastInvoiceExternalId && activeState.lastPaymentExternalId);
const steps = [
buildStep("lago.customer", customer.externalId === tenantId, `Customer ${customer.providerCustomerId} created for ${tenantId}.`),
buildStep("lago.subscription", subscription.planCode === planCode && subscription.status === "active", `Subscription ${subscription.providerSubscriptionId} uses ${planCode}.`),
buildStep("mollie.payment", payment.status === "open" && paidPayment.status === "paid", `Payment ${payment.providerPaymentId} was created and simulated as paid.`),
buildStep("local.sync", activeState.status === "active" && activeState.lastInvoiceExternalId === invoice.providerInvoiceId, "Provider sync updated the local subscription."),
buildStep("module.gate", activeAllowed && !activeState.readOnly, `${moduleKey} is allowed while the subscription is active.`),
buildStep("references.audit", referencesVisible && state.auditEvents.length >= 2, "Invoice/payment references are visible and syncs are audited."),
buildStep(
"negative.failed-expired",
failedState.status === "past_due" && failedState.readOnly && pastDueState.status === "past_due" && pastDueState.readOnly,
"Failed and expired Mollie payments mark the subscription past_due/read-only."
),
buildStep("negative.frozen", frozenState.status === "frozen" && frozenState.readOnly, "Paused Lago subscription marks the tenant frozen/read-only."),
];
return {
ok: steps.every((step) => step.ok),
mode: "stub",
runId,
tenantId,
planCode,
seatQuantity,
customer,
subscription,
invoice,
payment: paidPayment,
activeState,
failedState,
pastDueState,
frozenState,
syncResults: { lagoActive, molliePaid, mollieFailed, mollieExpired, lagoFrozen },
gate: {
moduleKey,
activeAllowed,
activeReadOnly: activeState.readOnly,
failedReadOnly: failedState.readOnly,
pastDueReadOnly: pastDueState.readOnly,
frozenReadOnly: frozenState.readOnly,
},
audit: {
auditEvents: state.auditEvents.length,
activities: state.activities.length,
},
referencesVisible,
steps,
};
}
@@ -0,0 +1,201 @@
import { describe, expect, it } from "vitest";
import {
buildLagoBillingSyncDispatchKey,
buildLagoBillingSyncOutboxArgs,
buildMolliePaymentSyncDispatchKey,
buildMolliePaymentSyncOutboxArgs,
buildMolliePaymentSyncOutboxArgsFromPayment,
LAGO_BILLING_SYNC_EVENT_TYPE,
MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
} from "./sync-outbox.js";
import { buildLagoWebhookSyncOutboxArgs, parseLagoWebhookEvent } from "./webhook.js";
describe("Lago billing sync outbox", () => {
it("builds idempotent outbox args for Lago pull sync actions", () => {
const args = buildLagoBillingSyncOutboxArgs({
tenantId: "tenant_1",
action: "subscription.upsert",
externalId: "sub_1",
source: "pull",
receivedAt: new Date("2026-07-04T00:00:00Z"),
});
expect(args).toEqual({
tenantId: "tenant_1",
type: LAGO_BILLING_SYNC_EVENT_TYPE,
dispatchKey: "lago:subscription.upsert:tenant_1:sub_1",
payload: {
provider: "lago",
action: "subscription.upsert",
tenantId: "tenant_1",
externalId: "sub_1",
source: "pull",
receivedAt: "2026-07-04T00:00:00.000Z",
},
});
});
it("sanitizes dispatch keys to the outbox-safe character set", () => {
expect(
buildLagoBillingSyncDispatchKey({
tenantId: "tenant/with/slashes",
action: "invoice.refresh",
externalId: "invoice 123",
})
).toBe("lago:invoice.refresh:tenant_with_slashes:invoice_123");
});
it("maps Lago webhook events to idempotent sync events", () => {
const event = parseLagoWebhookEvent({
event_type: "invoice.finalized",
lago_id: "invoice_1",
external_customer_id: "tenant_1",
data: { status: "finalized" },
});
expect(
buildLagoWebhookSyncOutboxArgs({
tenantId: "tenant_1",
event,
receivedAt: new Date("2026-07-04T00:00:00Z"),
})
).toMatchObject({
tenantId: "tenant_1",
type: LAGO_BILLING_SYNC_EVENT_TYPE,
dispatchKey: "lago:invoice.refresh:tenant_1:invoice_1",
payload: {
action: "invoice.refresh",
externalId: "invoice_1",
source: "webhook",
},
});
});
});
describe("Mollie payment sync outbox", () => {
it("builds idempotent outbox args for paid payment events", () => {
const args = buildMolliePaymentSyncOutboxArgs({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
providerPaymentId: "tr_123",
paymentExternalId: "payment_1",
status: "paid",
amountCents: 4900,
amountRefundedCents: 0,
amountRemainingCents: 0,
source: "webhook",
receivedAt: new Date("2026-07-04T00:00:00Z"),
});
expect(args).toEqual({
tenantId: "tenant_1",
type: MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
dispatchKey: "mollie:payment.paid:tenant_1:tr_123:paid:0",
payload: {
provider: "mollie",
action: "payment.paid",
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
providerPaymentId: "tr_123",
paymentExternalId: "payment_1",
status: "paid",
amountCents: 4900,
amountRefundedCents: 0,
amountRemainingCents: 0,
source: "webhook",
receivedAt: "2026-07-04T00:00:00.000Z",
},
});
});
it("records failure, expired and refund statuses as distinct billing events", () => {
expect(
buildMolliePaymentSyncOutboxArgs({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
providerPaymentId: "tr_123",
paymentExternalId: null,
status: "failed",
amountCents: 4900,
amountRefundedCents: 0,
amountRemainingCents: 4900,
source: "webhook",
}).payload
).toMatchObject({ action: "payment.failed" });
expect(
buildMolliePaymentSyncOutboxArgs({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
providerPaymentId: "tr_123",
paymentExternalId: null,
status: "expired",
amountCents: 4900,
amountRefundedCents: 0,
amountRemainingCents: 4900,
source: "webhook",
}).payload
).toMatchObject({ action: "payment.expired" });
expect(
buildMolliePaymentSyncOutboxArgs({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
providerPaymentId: "tr_123",
paymentExternalId: null,
status: "refunded",
amountCents: 4900,
amountRefundedCents: 4900,
amountRemainingCents: 0,
source: "webhook",
}).payload
).toMatchObject({ action: "payment.refunded" });
});
it("sanitizes Mollie dispatch keys and can build them from verified payments", () => {
expect(
buildMolliePaymentSyncDispatchKey({
tenantId: "tenant/with/slashes",
providerPaymentId: "tr 123",
status: "refunded",
amountRefundedCents: 4900,
})
).toBe("mollie:payment.refunded:tenant_with_slashes:tr_123:refunded:4900");
expect(
buildMolliePaymentSyncOutboxArgsFromPayment(
{
provider: "mollie",
providerPaymentId: "tr_123",
externalId: "payment_1",
status: "refunded",
amountCents: 4900,
amountRefundedCents: 4900,
amountRemainingCents: 0,
currency: "EUR",
checkoutUrl: null,
paidAt: null,
expiresAt: null,
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_1",
lagoCustomerId: null,
lagoSubscriptionId: null,
planCode: null,
seatQuantity: null,
},
},
{ source: "webhook", receivedAt: new Date("2026-07-04T00:00:00Z") }
)
).toMatchObject({
tenantId: "tenant_1",
dispatchKey: "mollie:payment.refunded:tenant_1:tr_123:refunded:4900",
payload: {
action: "payment.refunded",
invoiceExternalId: "invoice_1",
},
});
});
});
@@ -0,0 +1,128 @@
import { publishOutboxEvent, type OutboxPublishArgs, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { PaymentGatewayPayment, PaymentGatewayPaymentStatus } from "./types.js";
export const LAGO_BILLING_SYNC_EVENT_TYPE = "billing.lago.sync";
export const MOLLIE_PAYMENT_SYNC_EVENT_TYPE = "billing.mollie.payment";
export type LagoBillingSyncAction = "customer.upsert" | "subscription.upsert" | "invoice.refresh" | "webhook.received";
export type MolliePaymentSyncAction = "payment.refresh" | "payment.paid" | "payment.failed" | "payment.expired" | "payment.refunded" | "payment.cancelled";
export type LagoBillingSyncPayload = {
provider: "lago";
action: LagoBillingSyncAction;
tenantId: string;
externalId: string;
receivedAt: string;
source: "api" | "webhook" | "pull";
};
export type LagoBillingSyncInput = Omit<LagoBillingSyncPayload, "provider" | "receivedAt"> & {
receivedAt?: Date;
};
export function buildLagoBillingSyncOutboxArgs(input: LagoBillingSyncInput): OutboxPublishArgs {
return {
tenantId: input.tenantId,
type: LAGO_BILLING_SYNC_EVENT_TYPE,
dispatchKey: buildLagoBillingSyncDispatchKey(input),
payload: {
provider: "lago",
action: input.action,
tenantId: input.tenantId,
externalId: input.externalId,
source: input.source,
receivedAt: (input.receivedAt ?? new Date()).toISOString(),
},
};
}
export async function publishLagoBillingSync(tx: OutboxPublisherTransaction, input: LagoBillingSyncInput) {
return await publishOutboxEvent(tx, buildLagoBillingSyncOutboxArgs(input));
}
export function buildLagoBillingSyncDispatchKey(input: Pick<LagoBillingSyncInput, "action" | "tenantId" | "externalId">): string {
return `lago:${input.action}:${input.tenantId}:${input.externalId}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256);
}
export type MolliePaymentSyncPayload = {
provider: "mollie";
action: MolliePaymentSyncAction;
tenantId: string;
invoiceExternalId: string;
providerPaymentId: string;
paymentExternalId: string | null;
status: PaymentGatewayPaymentStatus;
amountCents: number | null;
amountRefundedCents: number | null;
amountRemainingCents: number | null;
receivedAt: string;
source: "api" | "webhook" | "pull";
};
export type MolliePaymentSyncInput = Omit<MolliePaymentSyncPayload, "provider" | "receivedAt" | "action"> & {
action?: MolliePaymentSyncAction;
receivedAt?: Date;
};
export function buildMolliePaymentSyncOutboxArgs(input: MolliePaymentSyncInput): OutboxPublishArgs {
const action = input.action ?? actionForMolliePaymentStatus(input.status);
return {
tenantId: input.tenantId,
type: MOLLIE_PAYMENT_SYNC_EVENT_TYPE,
dispatchKey: buildMolliePaymentSyncDispatchKey({ ...input, action }),
payload: {
provider: "mollie",
action,
tenantId: input.tenantId,
invoiceExternalId: input.invoiceExternalId,
providerPaymentId: input.providerPaymentId,
paymentExternalId: input.paymentExternalId,
status: input.status,
amountCents: input.amountCents,
amountRefundedCents: input.amountRefundedCents,
amountRemainingCents: input.amountRemainingCents,
source: input.source,
receivedAt: (input.receivedAt ?? new Date()).toISOString(),
},
};
}
export function buildMolliePaymentSyncOutboxArgsFromPayment(payment: PaymentGatewayPayment, options: { source: "api" | "webhook" | "pull"; receivedAt?: Date }): OutboxPublishArgs {
const tenantId = payment.metadata.tenantId;
const invoiceExternalId = payment.metadata.invoiceExternalId;
if (!tenantId || !invoiceExternalId) {
throw new Error("Mollie payment metadata must include tenantId and invoiceExternalId.");
}
return buildMolliePaymentSyncOutboxArgs({
tenantId,
invoiceExternalId,
providerPaymentId: payment.providerPaymentId,
paymentExternalId: payment.externalId ?? payment.metadata.paymentExternalId,
status: payment.status,
amountCents: payment.amountCents,
amountRefundedCents: payment.amountRefundedCents,
amountRemainingCents: payment.amountRemainingCents,
source: options.source,
receivedAt: options.receivedAt,
});
}
export async function publishMolliePaymentSync(tx: OutboxPublisherTransaction, input: MolliePaymentSyncInput) {
return await publishOutboxEvent(tx, buildMolliePaymentSyncOutboxArgs(input));
}
export function actionForMolliePaymentStatus(status: PaymentGatewayPaymentStatus): MolliePaymentSyncAction {
if (status === "paid" || status === "authorized") return "payment.paid";
if (status === "failed" || status === "charged_back") return "payment.failed";
if (status === "expired") return "payment.expired";
if (status === "refunded") return "payment.refunded";
if (status === "canceled") return "payment.cancelled";
return "payment.refresh";
}
export function buildMolliePaymentSyncDispatchKey(input: Pick<MolliePaymentSyncInput, "tenantId" | "providerPaymentId" | "status" | "amountRefundedCents"> & { action?: MolliePaymentSyncAction }): string {
const refundPart = typeof input.amountRefundedCents === "number" ? input.amountRefundedCents : "none";
return `mollie:${input.action ?? actionForMolliePaymentStatus(input.status)}:${input.tenantId}:${input.providerPaymentId}:${input.status}:${refundPart}`
.replace(/[^A-Za-z0-9._:-]/gu, "_")
.slice(0, 256);
}
@@ -0,0 +1,129 @@
export type BillingGatewayCustomerInput = {
tenantId: string;
name: string;
email?: string | null;
currency?: string | null;
country?: string | null;
timezone?: string | null;
};
export type BillingGatewayCustomer = {
provider: "lago";
externalId: string;
providerCustomerId: string;
name: string | null;
email: string | null;
currency: string | null;
createdAt: string | null;
};
export type BillingGatewaySubscriptionInput = {
tenantId: string;
subscriptionExternalId: string;
planCode: string;
seatQuantity: number;
name?: string | null;
subscriptionAt?: Date | string | null;
endingAt?: Date | string | null;
};
export type BillingGatewaySubscription = {
provider: "lago";
externalId: string;
providerSubscriptionId: string;
externalCustomerId: string;
planCode: string;
status: "pending" | "active" | "terminated" | "canceled" | "cancelled" | "unknown";
name: string | null;
currentBillingPeriodStartedAt: string | null;
currentBillingPeriodEndingAt: string | null;
createdAt: string | null;
};
export type BillingGatewayInvoice = {
provider: "lago";
providerInvoiceId: string;
number: string | null;
externalCustomerId: string | null;
status: "draft" | "finalized" | "voided" | "failed" | "pending" | "unknown";
paymentStatus: "pending" | "succeeded" | "failed" | "unknown";
invoiceType: string | null;
currency: string | null;
totalAmountCents: number | null;
issuingDate: string | null;
fileUrl: string | null;
};
export type BillingGatewayInvoiceListInput = {
tenantId?: string;
page?: number;
perPage?: number;
};
export type BillingGateway = {
createCustomer(input: BillingGatewayCustomerInput): Promise<BillingGatewayCustomer>;
getCustomer(tenantId: string): Promise<BillingGatewayCustomer | null>;
createSubscription(input: BillingGatewaySubscriptionInput): Promise<BillingGatewaySubscription>;
getSubscription(subscriptionExternalId: string): Promise<BillingGatewaySubscription | null>;
listInvoices(input?: BillingGatewayInvoiceListInput): Promise<BillingGatewayInvoice[]>;
downloadInvoice(providerInvoiceId: string): Promise<BillingGatewayInvoice | null>;
updateInvoicePaymentStatus(providerInvoiceId: string, paymentStatus: BillingGatewayInvoice["paymentStatus"]): Promise<BillingGatewayInvoice>;
};
export type PaymentGatewayCreatePaymentInput = {
tenantId: string;
invoiceExternalId: string;
amountCents: number;
currency: string;
redirectUrl: string;
webhookUrl: string;
paymentExternalId?: string | null;
mollieCustomerId?: string | null;
lagoCustomerId?: string | null;
lagoSubscriptionId?: string | null;
planCode?: string | null;
seatQuantity?: number | null;
description?: string | null;
};
export type PaymentGatewayPaymentStatus =
| "open"
| "pending"
| "authorized"
| "paid"
| "failed"
| "expired"
| "canceled"
| "refunded"
| "charged_back"
| "unknown";
export type PaymentGatewayPaymentMetadata = {
tenantId: string | null;
invoiceExternalId: string | null;
paymentExternalId: string | null;
lagoCustomerId: string | null;
lagoSubscriptionId: string | null;
planCode: string | null;
seatQuantity: number | null;
};
export type PaymentGatewayPayment = {
provider: "mollie";
providerPaymentId: string;
externalId: string | null;
status: PaymentGatewayPaymentStatus;
amountCents: number | null;
amountRefundedCents: number | null;
amountRemainingCents: number | null;
currency: string | null;
checkoutUrl: string | null;
paidAt: string | null;
expiresAt: string | null;
metadata: PaymentGatewayPaymentMetadata;
};
export type PaymentGateway = {
createPayment(input: PaymentGatewayCreatePaymentInput): Promise<PaymentGatewayPayment>;
getPayment(providerPaymentId: string): Promise<PaymentGatewayPayment | null>;
};
@@ -0,0 +1,41 @@
import { z } from "zod";
import { buildLagoBillingSyncOutboxArgs, type LagoBillingSyncAction } from "./sync-outbox.js";
export const lagoWebhookEventSchema = z
.object({
event_type: z.string().optional(),
webhook_type: z.string().optional(),
object_type: z.string().optional(),
lago_id: z.string().optional(),
external_id: z.string().optional(),
external_customer_id: z.string().optional(),
data: z.unknown().optional(),
})
.passthrough();
export type LagoWebhookEvent = z.infer<typeof lagoWebhookEventSchema>;
export function parseLagoWebhookEvent(value: unknown): LagoWebhookEvent {
return lagoWebhookEventSchema.parse(value);
}
export function buildLagoWebhookSyncOutboxArgs(input: { tenantId: string; event: LagoWebhookEvent; receivedAt?: Date }) {
const action = resolveWebhookAction(input.event);
const externalId = input.event.external_id ?? input.event.lago_id ?? `${action}:${input.tenantId}`;
return buildLagoBillingSyncOutboxArgs({
tenantId: input.tenantId,
action,
externalId,
source: "webhook",
receivedAt: input.receivedAt,
});
}
function resolveWebhookAction(event: LagoWebhookEvent): LagoBillingSyncAction {
const type = [event.event_type, event.webhook_type, event.object_type].filter(Boolean).join(":").toLowerCase();
if (type.includes("invoice")) return "invoice.refresh";
if (type.includes("subscription")) return "subscription.upsert";
if (type.includes("customer")) return "customer.upsert";
return "webhook.received";
}
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"allowJs": false,
"allowImportingTsExtensions": false,
"lib": ["ES2022", "DOM"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noEmit": true,
"types": ["node", "vitest/globals"]
},
"include": ["src/**/*.ts"]
}
@@ -1,5 +1,5 @@
{
"name": "@toolctrl/brand",
"name": "@hivegrid/brand",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -11,16 +11,16 @@ import {
describe("brand token helpers", () => {
it("exposes stable default brand tokens", () => {
expect(defaultBrandTokens).toMatchObject({
productName: "ToolCTRL",
siteUrl: "https://tool-ctrl.de",
productName: "HiveGrid",
siteUrl: "https://hivegrid.de",
legal: {
imprintUrl: "https://tool-ctrl.de/impressum",
privacyUrl: "https://tool-ctrl.de/datenschutz",
termsUrl: "https://tool-ctrl.de/agb",
imprintUrl: "https://hivegrid.de/impressum",
privacyUrl: "https://hivegrid.de/datenschutz",
termsUrl: "https://hivegrid.de/agb",
},
support: {
email: "info@tool-ctrl.de",
fromName: "ToolCTRL Support",
email: "support@hivegrid.de",
fromName: "HiveGrid Support",
},
assets: {
logoUrl: "/android-chrome-512x512.png",
@@ -209,18 +209,18 @@ describe("brand token helpers", () => {
});
expect(brandCssVariables(tokens)).toEqual({
"--toolctrl-product-name": "Acme Ops",
"--toolctrl-site-url": defaultBrandLinks.siteUrl,
"--toolctrl-logo-url": "url(https://cdn.acme.test/logo.svg)",
"--toolctrl-favicon-url": `url(${defaultBrandTokens.assets.faviconUrl})`,
"--toolctrl-mail-background": defaultBrandTokens.mail.colors.background,
"--toolctrl-mail-surface": defaultBrandTokens.mail.colors.surface,
"--toolctrl-mail-primary": "#123456",
"--toolctrl-mail-primary-text": defaultBrandTokens.mail.colors.primaryText,
"--toolctrl-mail-text": defaultBrandTokens.mail.colors.text,
"--toolctrl-mail-muted-text": defaultBrandTokens.mail.colors.mutedText,
"--toolctrl-mail-border": defaultBrandTokens.mail.colors.border,
"--toolctrl-mail-link": defaultBrandTokens.mail.colors.link,
"--hivegrid-product-name": "Acme Ops",
"--hivegrid-site-url": defaultBrandLinks.siteUrl,
"--hivegrid-logo-url": "url(https://cdn.acme.test/logo.svg)",
"--hivegrid-favicon-url": `url(${defaultBrandTokens.assets.faviconUrl})`,
"--hivegrid-mail-background": defaultBrandTokens.mail.colors.background,
"--hivegrid-mail-surface": defaultBrandTokens.mail.colors.surface,
"--hivegrid-mail-primary": "#123456",
"--hivegrid-mail-primary-text": defaultBrandTokens.mail.colors.primaryText,
"--hivegrid-mail-text": defaultBrandTokens.mail.colors.text,
"--hivegrid-mail-muted-text": defaultBrandTokens.mail.colors.mutedText,
"--hivegrid-mail-border": defaultBrandTokens.mail.colors.border,
"--hivegrid-mail-link": defaultBrandTokens.mail.colors.link,
});
});
});
@@ -39,7 +39,7 @@ export type TransactionalMailColors = {
link: string;
};
export type ToolCTRLBrandTokens = {
export type BrandTokens = {
productName: string;
siteUrl: string;
legal: BrandLegalLinks;
@@ -51,8 +51,6 @@ export type ToolCTRLBrandTokens = {
};
};
export type BrandTokens = ToolCTRLBrandTokens;
export type BrandTokenOverrides = Partial<{
productName: string | null;
siteUrl: string | null;
@@ -85,15 +83,15 @@ export type AppConfigurationLike = Partial<{
}>;
export const defaultBrandLinks: BrandLinkConfiguration = {
siteUrl: "https://tool-ctrl.de",
siteUrl: "https://hivegrid.de",
legal: {
imprintUrl: "https://tool-ctrl.de/impressum",
privacyUrl: "https://tool-ctrl.de/datenschutz",
termsUrl: "https://tool-ctrl.de/agb",
imprintUrl: "https://hivegrid.de/impressum",
privacyUrl: "https://hivegrid.de/datenschutz",
termsUrl: "https://hivegrid.de/agb",
},
support: {
email: "info@tool-ctrl.de",
fromName: "ToolCTRL Support",
email: "support@hivegrid.de",
fromName: "HiveGrid Support",
},
assets: {
logoUrl: "/android-chrome-512x512.png",
@@ -103,7 +101,7 @@ export const defaultBrandLinks: BrandLinkConfiguration = {
};
export const defaultBrandTokens: BrandTokens = {
productName: "ToolCTRL",
productName: "HiveGrid",
siteUrl: defaultBrandLinks.siteUrl,
legal: defaultBrandLinks.legal,
support: defaultBrandLinks.support,
@@ -221,17 +219,17 @@ export { loadBrandFromEnv, type BrandEnvSource } from "./env.js";
export function brandCssVariables(tokens: BrandTokens): Record<string, string> {
return {
"--toolctrl-product-name": tokens.productName,
"--toolctrl-site-url": tokens.siteUrl,
"--toolctrl-logo-url": `url(${tokens.assets.logoUrl})`,
"--toolctrl-favicon-url": `url(${tokens.assets.faviconUrl})`,
"--toolctrl-mail-background": tokens.mail.colors.background,
"--toolctrl-mail-surface": tokens.mail.colors.surface,
"--toolctrl-mail-primary": tokens.mail.colors.primary,
"--toolctrl-mail-primary-text": tokens.mail.colors.primaryText,
"--toolctrl-mail-text": tokens.mail.colors.text,
"--toolctrl-mail-muted-text": tokens.mail.colors.mutedText,
"--toolctrl-mail-border": tokens.mail.colors.border,
"--toolctrl-mail-link": tokens.mail.colors.link,
"--hivegrid-product-name": tokens.productName,
"--hivegrid-site-url": tokens.siteUrl,
"--hivegrid-logo-url": `url(${tokens.assets.logoUrl})`,
"--hivegrid-favicon-url": `url(${tokens.assets.faviconUrl})`,
"--hivegrid-mail-background": tokens.mail.colors.background,
"--hivegrid-mail-surface": tokens.mail.colors.surface,
"--hivegrid-mail-primary": tokens.mail.colors.primary,
"--hivegrid-mail-primary-text": tokens.mail.colors.primaryText,
"--hivegrid-mail-text": tokens.mail.colors.text,
"--hivegrid-mail-muted-text": tokens.mail.colors.mutedText,
"--hivegrid-mail-border": tokens.mail.colors.border,
"--hivegrid-mail-link": tokens.mail.colors.link,
};
}
@@ -0,0 +1,105 @@
import { describe, expect, it } from "vitest";
import { defaultBrandTokens, resolveTransactionalBrandTokens } from "./index.js";
describe("resolveTransactionalBrandTokens null-safety", () => {
it("returns default tokens when given null", () => {
expect(resolveTransactionalBrandTokens(null)).toEqual(defaultBrandTokens);
});
it("returns default tokens when given undefined", () => {
expect(resolveTransactionalBrandTokens(undefined)).toEqual(defaultBrandTokens);
});
it("returns default tokens for an empty configuration object", () => {
expect(resolveTransactionalBrandTokens({})).toEqual(defaultBrandTokens);
});
});
describe("resolveTransactionalBrandTokens nested brand precedence", () => {
it("prefers brand.legal over flat legal URLs", () => {
const tokens = resolveTransactionalBrandTokens({
imprintUrl: "https://flat.test/imprint",
privacyUrl: "https://flat.test/privacy",
termsUrl: "https://flat.test/terms",
brand: {
legal: {
imprintUrl: "https://brand.test/imprint",
privacyUrl: "https://brand.test/privacy",
termsUrl: "https://brand.test/terms",
},
},
});
expect(tokens.legal).toEqual({
imprintUrl: "https://brand.test/imprint",
privacyUrl: "https://brand.test/privacy",
termsUrl: "https://brand.test/terms",
});
});
it("falls back to flat legal URLs when brand.legal entries are blank", () => {
const tokens = resolveTransactionalBrandTokens({
imprintUrl: "https://flat.test/imprint",
termsUrl: "https://flat.test/terms",
brand: {
legal: {
imprintUrl: " ",
privacyUrl: "https://brand.test/privacy",
termsUrl: null,
},
},
});
// Blank brand value -> flat fallback; non-blank brand value wins; missing flat -> default.
expect(tokens.legal.imprintUrl).toBe("https://flat.test/imprint");
expect(tokens.legal.privacyUrl).toBe("https://brand.test/privacy");
expect(tokens.legal.termsUrl).toBe("https://flat.test/terms");
});
it("prefers brand.assets over flat asset URLs", () => {
const tokens = resolveTransactionalBrandTokens({
logoUrl: "https://flat.test/logo.png",
faviconUrl: "https://flat.test/favicon.ico",
brand: {
assets: {
logoUrl: "https://brand.test/logo.svg",
faviconUrl: "https://brand.test/favicon.png",
},
},
});
expect(tokens.assets).toEqual({
logoUrl: "https://brand.test/logo.svg",
faviconUrl: "https://brand.test/favicon.png",
});
});
it("falls back to flat asset URLs when brand.assets entries are blank", () => {
const tokens = resolveTransactionalBrandTokens({
logoUrl: "https://flat.test/logo.png",
faviconUrl: "https://flat.test/favicon.ico",
brand: {
assets: {
logoUrl: "",
faviconUrl: "https://brand.test/favicon.png",
},
},
});
expect(tokens.assets.logoUrl).toBe("https://flat.test/logo.png");
expect(tokens.assets.faviconUrl).toBe("https://brand.test/favicon.png");
});
it("ignores a null brand container and uses flat values", () => {
const tokens = resolveTransactionalBrandTokens({
logoUrl: "https://flat.test/logo.png",
imprintUrl: "https://flat.test/imprint",
brand: null,
});
expect(tokens.assets.logoUrl).toBe("https://flat.test/logo.png");
expect(tokens.legal.imprintUrl).toBe("https://flat.test/imprint");
expect(tokens.assets.faviconUrl).toBe(defaultBrandTokens.assets.faviconUrl);
});
});
@@ -1,5 +1,5 @@
{
"name": "@toolctrl/captcha",
"name": "@hivegrid/captcha",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { resolveCaptchaConfig, getSitekey, isCaptchaConfigured } from "./config.js";
import { resolveCaptchaConfig, getSecret, getSitekey, isCaptchaConfigured } from "./config.js";
describe("resolveCaptchaConfig", () => {
it("maps env vars to config", () => {
@@ -14,6 +14,25 @@ describe("resolveCaptchaConfig", () => {
expect(cfg.instanceUrl).toBe("https://captcha.tool-ctrl.de");
expect(getSitekey(cfg, "login")).toBe("login-key");
expect(getSitekey(cfg, "booking")).toBe("booking-key");
expect(getSecret(cfg, "forms")).toBe("secret");
expect(isCaptchaConfigured(cfg)).toBe(true);
});
it("maps Cap env vars to config", () => {
const cfg = resolveCaptchaConfig({
CAPTCHA_PROVIDER: "cap",
CAP_INSTANCE_URL: "https://captcha.hivegrid.de",
CAP_SITE_SECRET: "shared-secret",
CAP_SITE_SECRET_LOGIN: "login-secret",
CAP_SITEKEY_LOGIN: "login-key",
CAP_SITEKEY_FORMS: "forms-key",
CAP_SITEKEY_BOOKING: "booking-key",
});
expect(cfg.provider).toBe("cap");
expect(cfg.instanceUrl).toBe("https://captcha.hivegrid.de");
expect(getSitekey(cfg, "login")).toBe("login-key");
expect(getSecret(cfg, "login")).toBe("login-secret");
expect(getSecret(cfg, "forms")).toBe("shared-secret");
expect(isCaptchaConfigured(cfg)).toBe(true);
});
@@ -1,4 +1,4 @@
import type { CaptchaConfig, CaptchaSurface } from "./types.js";
import type { CaptchaConfig, CaptchaProvider, CaptchaSurface } from "./types.js";
type EnvLike = Record<string, string | undefined>;
@@ -8,28 +8,68 @@ function present(value: string | undefined): string | undefined {
}
/**
* Resolves the captcha config from env. mCaptcha is the only provider
* (see HiveGrid docs/ARCHITECTURE-DECISIONS.md AD-7).
* Resolves the captcha config from env. mCaptcha remains the default provider
* for compatibility; set CAPTCHA_PROVIDER=cap to use Cap.
*
* CAPTCHA_PROVIDER=mcaptcha|cap
* MCAPTCHA_INSTANCE_URL=https://captcha.tool-ctrl.de
* MCAPTCHA_ACCOUNT_SECRET=<dashboard account secret>
* MCAPTCHA_SITEKEY_LOGIN / _FORMS / _BOOKING=<public sitekeys>
*
* CAP_INSTANCE_URL=https://captcha.hivegrid.de
* CAP_SITE_SECRET=<fallback site secret>
* CAP_SITE_SECRET_LOGIN / _FORMS / _BOOKING=<per-surface site secrets>
* CAP_SITEKEY_LOGIN / _FORMS / _BOOKING=<public sitekeys>
*
* CAPTCHA_FAIL_OPEN=true|false (default true)
*/
export function resolveCaptchaConfig(env: EnvLike): CaptchaConfig {
const provider = resolveProvider(env);
if (provider === "cap") {
const sharedSecret = present(env.CAP_SITE_SECRET);
return {
provider,
instanceUrl: present(env.CAP_INSTANCE_URL),
accountSecret: sharedSecret,
sitekeys: {
login: present(env.CAP_SITEKEY_LOGIN),
forms: present(env.CAP_SITEKEY_FORMS),
booking: present(env.CAP_SITEKEY_BOOKING),
},
secrets: {
login: present(env.CAP_SITE_SECRET_LOGIN) ?? sharedSecret,
forms: present(env.CAP_SITE_SECRET_FORMS) ?? sharedSecret,
booking: present(env.CAP_SITE_SECRET_BOOKING) ?? sharedSecret,
},
failOpen: present(env.CAPTCHA_FAIL_OPEN) !== "false",
};
}
const accountSecret = present(env.MCAPTCHA_ACCOUNT_SECRET);
return {
provider: "mcaptcha",
provider,
instanceUrl: present(env.MCAPTCHA_INSTANCE_URL),
accountSecret: present(env.MCAPTCHA_ACCOUNT_SECRET),
accountSecret,
sitekeys: {
login: present(env.MCAPTCHA_SITEKEY_LOGIN),
forms: present(env.MCAPTCHA_SITEKEY_FORMS),
booking: present(env.MCAPTCHA_SITEKEY_BOOKING),
},
secrets: {
login: accountSecret,
forms: accountSecret,
booking: accountSecret,
},
failOpen: present(env.CAPTCHA_FAIL_OPEN) !== "false",
};
}
function resolveProvider(env: EnvLike): CaptchaProvider {
const explicit = present(env.CAPTCHA_PROVIDER)?.toLowerCase();
if (explicit === "cap") return "cap";
return "mcaptcha";
}
export function getSitekey(
config: CaptchaConfig,
surface: CaptchaSurface,
@@ -37,7 +77,14 @@ export function getSitekey(
return config.sitekeys[surface];
}
/** True when the instance + account secret are present (sitekeys checked per-surface). */
export function getSecret(
config: CaptchaConfig,
surface: CaptchaSurface,
): string | undefined {
return config.secrets[surface] ?? config.accountSecret;
}
/** True when the instance + at least one secret are present (sitekeys checked per-surface). */
export function isCaptchaConfigured(config: CaptchaConfig): boolean {
return Boolean(config.instanceUrl && config.accountSecret);
return Boolean(config.instanceUrl && (config.accountSecret || Object.values(config.secrets).some(Boolean)));
}
@@ -2,4 +2,4 @@ export type { CaptchaSurface, CaptchaLogger, CaptchaConfig } from "./types.js";
export { CAPTCHA_SURFACES } from "./types.js";
export { verifyCaptchaToken } from "./verify.js";
export type { VerifyCaptchaArgs } from "./verify.js";
export { resolveCaptchaConfig, getSitekey, isCaptchaConfigured } from "./config.js";
export { resolveCaptchaConfig, getSecret, getSitekey, isCaptchaConfigured } from "./config.js";
@@ -1,21 +1,25 @@
// Captcha surfaces — one mCaptcha sitekey per surface so difficulty/rate-limit
// can be tuned independently (see infra/mcaptcha/README.md).
// Captcha surfaces — one sitekey per surface so difficulty/rate-limit can be
// tuned independently (see infra/mcaptcha/README.md and infra/cap/README.md).
export type CaptchaSurface = "login" | "forms" | "booking";
export const CAPTCHA_SURFACES: readonly CaptchaSurface[] = ["login", "forms", "booking"];
export type CaptchaProvider = "mcaptcha" | "cap";
export type CaptchaLogger = {
warn: (metadata: Record<string, unknown>, message: string) => void;
};
export type CaptchaConfig = {
provider: "mcaptcha";
/** Public base URL of the self-hosted mCaptcha instance, e.g. https://captcha.tool-ctrl.de */
provider: CaptchaProvider;
/** Public base URL of the self-hosted captcha instance, e.g. https://captcha.hivegrid.de */
instanceUrl: string | undefined;
/** mCaptcha dashboard account secret used for server-side siteverify. */
/** Legacy/shared secret used for server-side siteverify. Prefer `secrets` for new Cap keys. */
accountSecret: string | undefined;
/** Public sitekey per surface (created in the mCaptcha dashboard). */
sitekeys: Record<CaptchaSurface, string | undefined>;
/** Server-side secret per surface. mCaptcha uses the same account secret for every surface. */
secrets: Record<CaptchaSurface, string | undefined>;
/**
* When the instance is unreachable/misconfigured: true = let the request
* through (fail-open, default), false = block it (fail-closed). A missing
@@ -32,6 +32,26 @@ describe("verifyCaptchaToken", () => {
expect(calledBody).toEqual({ token: "pow-token", key: "site-key", secret: "account-secret" });
});
it("returns true when Cap reports success", async () => {
let calledUrl = "";
let calledBody: unknown = null;
const fetchImpl = (async (url: string, init?: RequestInit) => {
calledUrl = url;
calledBody = JSON.parse(String(init?.body));
return jsonResponse({ success: true });
}) as unknown as typeof fetch;
const ok = await verifyCaptchaToken({ ...base, provider: "cap", fetchImpl });
expect(ok).toBe(true);
expect(calledUrl).toBe("https://captcha.example.test/site-key/siteverify");
expect(calledBody).toEqual({ response: "pow-token", secret: "account-secret" });
});
it("returns false when Cap reports failure", async () => {
const fetchImpl = (async () => jsonResponse({ success: false })) as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, provider: "cap", fetchImpl })).toBe(false);
});
it("returns false when mCaptcha reports invalid", async () => {
const fetchImpl = (async () => jsonResponse({ valid: false })) as unknown as typeof fetch;
expect(await verifyCaptchaToken({ ...base, fetchImpl })).toBe(false);
@@ -1,17 +1,18 @@
import type { CaptchaLogger } from "./types.js";
import type { CaptchaLogger, CaptchaProvider } from "./types.js";
const DEFAULT_TIMEOUT_MS = 3_000;
const SITEVERIFY_PATH = "/api/v1/pow/siteverify";
const MCAPTCHA_SITEVERIFY_PATH = "/api/v1/pow/siteverify";
export type VerifyCaptchaArgs = {
/** PoW solution token produced by the mCaptcha widget. */
/** Challenge token produced by the captcha widget. */
token: string | null | undefined;
/** Public sitekey for the surface being protected. */
sitekey: string | undefined;
/** mCaptcha account secret (server-side only). */
/** Server-side site/account secret. */
secret: string | undefined;
/** Base URL of the mCaptcha instance. */
/** Base URL of the captcha instance. */
instanceUrl: string | undefined;
provider?: CaptchaProvider;
/** Outage/misconfig policy: true (default) lets the request through. */
failOpen?: boolean;
logger?: CaptchaLogger;
@@ -20,10 +21,15 @@ export type VerifyCaptchaArgs = {
};
/**
* Verifies an mCaptcha proof-of-work token against a self-hosted instance.
* Verifies a captcha token against a self-hosted provider.
*
* POST {instanceUrl}/api/v1/pow/siteverify body: { token, key, secret }
* response: { valid: boolean }
* mCaptcha:
* POST {instanceUrl}/api/v1/pow/siteverify body: { token, key, secret }
* response: { valid: boolean }
*
* Cap:
* POST {instanceUrl}/{sitekey}/siteverify body: { response, secret }
* response: { success: boolean }
*
* Semantics:
* - missing token -> false (real client failure, never fail-open)
@@ -35,6 +41,7 @@ export async function verifyCaptchaToken({
sitekey,
secret,
instanceUrl,
provider = "mcaptcha",
failOpen = true,
logger,
fetchImpl = fetch,
@@ -49,43 +56,73 @@ export async function verifyCaptchaToken({
hasSitekey: Boolean(sitekey),
failOpen,
},
"mCaptcha not configured — applying fail policy",
"captcha not configured — applying fail policy",
);
return failOpen;
}
if (!token) return false;
const url = instanceUrl.replace(/\/+$/, "") + SITEVERIFY_PATH;
const url = buildSiteverifyUrl({ provider, instanceUrl, sitekey });
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetchImpl(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ token, key: sitekey, secret }),
body: JSON.stringify(buildSiteverifyBody({ provider, token, sitekey, secret })),
signal: controller.signal,
});
if (!res.ok) {
logger?.warn(
{ op: "captcha.http_error", status: res.status, failOpen },
"mCaptcha siteverify returned non-OK — applying fail policy",
{ op: "captcha.http_error", provider, status: res.status, failOpen },
"captcha siteverify returned non-OK — applying fail policy",
);
return failOpen;
}
const data = (await res.json()) as { valid?: boolean };
return data.valid === true;
const data = (await res.json()) as { valid?: boolean; success?: boolean };
return provider === "cap" ? data.success === true : data.valid === true;
} catch (err) {
logger?.warn(
{
op: "captcha.error",
provider,
err: err instanceof Error ? err.message : String(err),
failOpen,
},
"mCaptcha verification failed — applying fail policy",
"captcha verification failed — applying fail policy",
);
return failOpen;
} finally {
clearTimeout(timeout);
}
}
function buildSiteverifyUrl({
provider,
instanceUrl,
sitekey,
}: {
provider: CaptchaProvider;
instanceUrl: string;
sitekey: string;
}): string {
const base = instanceUrl.replace(/\/+$/, "");
if (provider === "cap") return `${base}/${encodeURIComponent(sitekey)}/siteverify`;
return base + MCAPTCHA_SITEVERIFY_PATH;
}
function buildSiteverifyBody({
provider,
token,
sitekey,
secret,
}: {
provider: CaptchaProvider;
token: string;
sitekey: string;
secret: string;
}): Record<string, string> {
if (provider === "cap") return { response: token, secret };
return { token, key: sitekey, secret };
}
@@ -1,7 +1,7 @@
# @toolctrl/cli
# @hivegrid/cli
Operator CLI for the ToolCTRL boilerplate. Currently ships the `backup` family
of subcommands. The entrypoint is `bin/toolctrl-cli.mjs`, wired up via
Operator CLI for HiveGrid. Currently ships the `backup` family
of subcommands. The entrypoint is `bin/hivegrid-cli.mjs`, wired up via
[citty](https://github.com/unjs/citty) for consistent subcommand handling.
## Subcommands
@@ -36,6 +36,6 @@ isolated from the application bucket:
## Development
```sh
pnpm --filter @toolctrl/cli test
pnpm --filter @toolctrl/cli typecheck
pnpm --filter @hivegrid/cli test
pnpm --filter @hivegrid/cli typecheck
```
@@ -1,5 +1,5 @@
#!/usr/bin/env node
// Thin shim so the CLI is callable as `toolctrl-cli`.
// Thin shim so the CLI is callable as `hivegrid-cli`.
// The actual command tree lives in ../src/index.ts and is loaded via tsx in dev,
// or via the compiled output once the build pipeline produces dist/index.js.
import { fileURLToPath, pathToFileURL } from "node:url";
@@ -1,5 +1,5 @@
{
"name": "@toolctrl/cli",
"name": "@hivegrid/cli",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -9,7 +9,7 @@
"./backup": "./src/commands/backup/index.ts"
},
"bin": {
"toolctrl-cli": "./bin/toolctrl-cli.mjs"
"hivegrid-cli": "./bin/hivegrid-cli.mjs"
},
"scripts": {
"build": "pnpm run typecheck",
@@ -19,13 +19,13 @@
"dependencies": {
"@aws-sdk/client-s3": "^3.1048.0",
"@aws-sdk/lib-storage": "^3.1048.0",
"@toolctrl/db": "workspace:*",
"@toolctrl/entitlements": "workspace:*",
"@toolctrl/exports": "workspace:*",
"@toolctrl/feature-flags": "workspace:*",
"@toolctrl/form-widget": "workspace:*",
"@toolctrl/plugin-runtime": "workspace:*",
"@toolctrl/search": "workspace:*",
"@hivegrid/db": "workspace:*",
"@hivegrid/entitlements": "workspace:*",
"@hivegrid/exports": "workspace:*",
"@hivegrid/feature-flags": "workspace:*",
"@hivegrid/form-widget": "workspace:*",
"@hivegrid/plugin-runtime": "workspace:*",
"@hivegrid/search": "workspace:*",
"citty": "^0.1.6",
"consola": "^3.4.0",
"tar": "^7.4.3",
@@ -55,7 +55,7 @@ describe("scaffold helpers / writeScaffoldFile", () => {
let tempRoot: string;
beforeEach(async () => {
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-scaffold-"));
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-scaffold-"));
});
afterEach(async () => {
@@ -1,5 +1,5 @@
/**
* Shared helpers for the `toolctrl create …` / `toolctrl add …` scaffolding
* Shared helpers for the `hivegrid create …` / `hivegrid add …` scaffolding
* generators (Phase 08 / task #60).
*
* Design goals:
@@ -8,7 +8,7 @@ describe("add event-type generator", () => {
let tempRoot: string;
beforeEach(async () => {
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-event-type-"));
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-event-type-"));
});
afterEach(async () => {
@@ -1,5 +1,5 @@
/**
* `toolctrl add event-type <name>` — scaffold a new EntityWebhook
* `hivegrid add event-type <name>` — scaffold a new EntityWebhook
* event-type definition (zod schema + example payload + handler stub).
*
* The workflow engine does not yet expose a single canonical event-type
@@ -70,7 +70,7 @@ export async function generateEventType(options: GenerateEventTypeOptions): Prom
function renderEventTypeFile({ eventName, typeName }: { eventName: string; typeName: string }): string {
return `/**
* EntityWebhook event-type: ${eventName}
* Generated by toolctrl-cli.
* Generated by hivegrid-cli.
*/
import { z } from "zod";
@@ -8,7 +8,7 @@ describe("add hook generator", () => {
let tempRoot: string;
beforeEach(async () => {
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-hook-"));
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-hook-"));
});
afterEach(async () => {
@@ -31,7 +31,7 @@ describe("add hook generator", () => {
it("notes mention the plugin SDK migration path", async () => {
const result = await generateHook({ name: "on-foo", repoRoot: tempRoot, dryRun: true });
expect(result.notes.join("\n")).toMatch(/@toolctrl\/plugin-sdk/);
expect(result.notes.join("\n")).toMatch(/@hivegrid\/plugin-sdk/);
});
it("refuses to overwrite an existing hook", async () => {
@@ -1,11 +1,11 @@
/**
* `toolctrl add hook <name>` — scaffold a plugin-hook registration file.
* `hivegrid add hook <name>` — scaffold a plugin-hook registration file.
*
* NOTE: the plugin-system itself (Phase 06) is not yet built. This
* generator therefore produces a *stub* with a clear "scaffolding for
* future plugin system" header so downstream readers know the API
* surface is provisional. Once Phase 06 lands the template will be
* upgraded to import the real `@toolctrl/plugin-sdk`.
* upgraded to import the real `@hivegrid/plugin-sdk`.
*
* Refs: docs/improvement-plan/08-mobile-cli-storybook-sdk/cli-scaffolding.md
* Refs: docs/improvement-plan/06-plugin-system/audit-docs.md
@@ -48,7 +48,7 @@ export async function generateHook(options: GenerateHookOptions): Promise<Scaffo
result.notes.push(
"Phase 06 plugin system is not implemented yet — this hook is a forward-compatible stub.",
"Update the import path to @toolctrl/plugin-sdk once Phase 06 ships.",
"Update the import path to @hivegrid/plugin-sdk once Phase 06 ships.",
);
return result;
@@ -8,7 +8,7 @@ describe("add permission generator", () => {
let tempRoot: string;
beforeEach(async () => {
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-permission-"));
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-permission-"));
});
afterEach(async () => {
@@ -1,5 +1,5 @@
/**
* `toolctrl add permission <name>` — scaffold a new permission key plus
* `hivegrid add permission <name>` — scaffold a new permission key plus
* a frontend-mapper stub.
*
* The canonical permission list lives in
@@ -87,7 +87,7 @@ function renderSeedFragment({
}): string {
return `/**
* Permission seed fragment for "${permission}".
* Generated by toolctrl-cli.
* Generated by hivegrid-cli.
*
* Paste the constant into the \`defaultPermissionSeeds\` array in
* \`packages/db/src/permissions-seed.server.ts\` and add a matching
@@ -106,7 +106,7 @@ ${isAdmin ? ' "SuperAdmin",' : ' "SuperUser",\n "Admin",'}
function renderMapperFragment({ permission, constName }: { permission: string; constName: string }): string {
return `/**
* Frontend permission-mapper stub for "${permission}".
* Generated by toolctrl-cli.
* Generated by hivegrid-cli.
*
* Wire this into your route loaders via the project's permission
* helper (typically apps/web/app/utils/helpers/PermissionsHelper).
@@ -0,0 +1,265 @@
// @vitest-environment node
//
// Pin to the node environment. When the coverage gate runs this suite from the
// repo root, the root vitest.config.ts (environment: "jsdom") is loaded instead
// of packages/cli/vitest.config.ts (environment: "node"). Under jsdom, vitest's
// module interop for the mocked `node:fs/promises` builtin demands a `default`
// export the mock does not provide, so the whole suite fails to load. These are
// node CLI commands, so this pragma keeps the environment identical regardless
// of the working directory the runner is invoked from.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AuditPdfEvent } from "@hivegrid/exports/audit-pdf";
/**
* Exercises the citty `run` wrappers of the audit commands — the inline
* Prisma wiring (where-building, cursor pagination, chain-event mapping)
* that the pure-function tests in verify-chain.test.ts / export-pdf.test.ts
* deliberately bypass via injected dependencies.
*/
const findMany = vi.fn<() => Promise<unknown[]>>();
const verifyAuditChain = vi.fn();
const serializeAuditEventsToPdf = vi.fn<() => Promise<Uint8Array>>();
const writeFile = vi.fn<() => Promise<void>>();
vi.mock("@hivegrid/db/client.server", () => ({
getReadDbClient: () => ({ auditEvent: { findMany } }),
}));
vi.mock("@hivegrid/db/audit-hash", () => ({
verifyAuditChain: (...args: unknown[]) => verifyAuditChain(...(args as [])),
}));
vi.mock("@hivegrid/exports/audit-pdf", () => ({
serializeAuditEventsToPdf: (...args: unknown[]) => serializeAuditEventsToPdf(...(args as [])),
}));
vi.mock("node:fs/promises", () => ({
writeFile: (...args: unknown[]) => writeFile(...(args as [])),
}));
vi.mock("consola", () => ({
default: {
log: vi.fn(),
success: vi.fn(),
error: vi.fn(),
},
}));
import consola from "consola";
import { auditExportPdfCommand } from "./export-pdf.js";
import { auditVerifyChainCommand } from "./verify-chain.js";
const consoleMock = vi.mocked(consola);
function makeEvent(over: Partial<AuditPdfEvent> = {}): AuditPdfEvent {
return {
id: "audit_1",
createdAt: new Date("2026-05-17T00:00:00.000Z"),
tenantId: "tenant_1",
actorType: "user",
actorId: "user_1",
actorEmail: null,
actorIp: null,
actorUserAgent: null,
action: "widget.created",
targetType: "widget",
targetId: "widget_1",
requestId: null,
sourceModule: "crm",
outcome: "success",
dataSensitivity: "internal",
regulatoryScope: ["soc2"],
metadata: null,
previousHash: null,
eventHash: "h1",
...over,
};
}
describe("audit verify-chain command wrapper", () => {
beforeEach(() => {
vi.clearAllMocks();
process.exitCode = undefined;
findMany.mockResolvedValue([]);
verifyAuditChain.mockReturnValue({ ok: true, inspected: 0, firstBreak: undefined });
});
afterEach(() => {
process.exitCode = undefined;
});
it("maps a concrete tenant + date range into the Prisma where clause", async () => {
findMany.mockResolvedValueOnce([makeEvent()]);
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
await auditVerifyChainCommand.run?.({
args: { tenant: "tenant_1", from: "2026-05-01T00:00:00Z", to: "2026-06-01T00:00:00Z" },
} as never);
expect(findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
tenantId: "tenant_1",
createdAt: { gte: new Date("2026-05-01T00:00:00Z"), lt: new Date("2026-06-01T00:00:00Z") },
},
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
take: 5_000,
}),
);
expect(consoleMock.success).toHaveBeenCalledWith("audit-chain OK — tenant=tenant_1 inspected=1");
expect(process.exitCode).toBe(0);
});
it("translates --tenant=__platform__ into a null tenant filter", async () => {
await auditVerifyChainCommand.run?.({ args: { tenant: "__platform__" } } as never);
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: null } }));
});
it("follows the cursor across pages until a short final page", async () => {
const fullPage = Array.from({ length: 5_000 }, (_v, i) => makeEvent({ id: `evt_${i}` }));
findMany.mockResolvedValueOnce(fullPage).mockResolvedValueOnce([makeEvent({ id: "evt_last" })]);
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 5_001, firstBreak: undefined });
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
expect(findMany).toHaveBeenCalledTimes(2);
// Second page is requested with a skip+cursor anchored on the last id of page one.
expect(findMany).toHaveBeenLastCalledWith(
expect.objectContaining({ skip: 1, cursor: { id: "evt_4999" } }),
);
expect(verifyAuditChain).toHaveBeenCalledWith(
expect.arrayContaining([expect.objectContaining({ id: "evt_last" })]),
{},
);
});
it("reports a broken chain on stderr with a non-zero exit code", async () => {
findMany.mockResolvedValueOnce([makeEvent()]);
verifyAuditChain.mockReturnValueOnce({
ok: false,
inspected: 1,
firstBreak: { eventId: "audit_1", reason: "hash-mismatch" },
});
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
expect(consoleMock.error).toHaveBeenCalledWith(
"audit-chain BROKEN — tenant=tenant_1 inspected=1 firstBreakId=audit_1 reason=hash-mismatch",
);
expect(process.exitCode).toBe(1);
});
it("emits a single JSON object in --json mode", async () => {
findMany.mockResolvedValueOnce([makeEvent()]);
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1", json: true } } as never);
const printed = JSON.parse(String(consoleMock.log.mock.calls[0]?.[0]));
expect(printed).toMatchObject({ tenantId: "tenant_1", from: null, to: null, inspected: 1, ok: true });
// An intact chain has no firstBreak, so JSON.stringify drops the key entirely.
expect(printed).not.toHaveProperty("firstBreak");
});
it("catches an invalid --from value and exits non-zero", async () => {
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1", from: "not-a-date" } } as never);
expect(consoleMock.error).toHaveBeenCalledWith(
expect.stringContaining('Invalid --from value "not-a-date"'),
);
expect(process.exitCode).toBe(1);
expect(findMany).not.toHaveBeenCalled();
});
it("catches a database failure and exits non-zero", async () => {
findMany.mockRejectedValueOnce(new Error("connection reset"));
await auditVerifyChainCommand.run?.({ args: { tenant: "tenant_1" } } as never);
expect(consoleMock.error).toHaveBeenCalledWith("connection reset");
expect(process.exitCode).toBe(1);
});
});
describe("audit export-pdf command wrapper", () => {
beforeEach(() => {
vi.clearAllMocks();
process.exitCode = undefined;
findMany.mockResolvedValue([]);
verifyAuditChain.mockReturnValue({ ok: true, inspected: 0, firstBreak: undefined });
serializeAuditEventsToPdf.mockResolvedValue(new Uint8Array([1, 2, 3, 4]));
writeFile.mockResolvedValue(undefined);
});
afterEach(() => {
process.exitCode = undefined;
});
it("builds the where filter, renders, and writes the PDF on an intact chain", async () => {
findMany.mockResolvedValueOnce([makeEvent()]);
verifyAuditChain.mockReturnValueOnce({ ok: true, inspected: 1, firstBreak: undefined });
await auditExportPdfCommand.run?.({
args: {
tenant: "tenant_1",
from: "2026-05-01T00:00:00Z",
to: "2026-06-01T00:00:00Z",
"regulatory-scope": "gdpr",
out: "/tmp/audit.pdf",
"generated-by": "Ops",
},
} as never);
expect(findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
tenantId: "tenant_1",
createdAt: { gte: new Date("2026-05-01T00:00:00Z"), lt: new Date("2026-06-01T00:00:00Z") },
regulatoryScope: { hasSome: ["gdpr"] },
},
orderBy: { createdAt: "asc" },
take: 5_000,
}),
);
expect(serializeAuditEventsToPdf).toHaveBeenCalledTimes(1);
expect(writeFile).toHaveBeenCalledWith("/tmp/audit.pdf", new Uint8Array([1, 2, 3, 4]));
expect(consoleMock.success).toHaveBeenCalledWith(
"audit-pdf written — out=/tmp/audit.pdf rows=1 bytes=4 integrity=ok",
);
expect(process.exitCode).toBe(0);
});
it("maps __platform__ to a null tenant and omits the date range when unset", async () => {
await auditExportPdfCommand.run?.({
args: { tenant: "__platform__", out: "/tmp/p.pdf" },
} as never);
expect(findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: null } }));
});
it("flags a broken chain in the log line and exits non-zero", async () => {
findMany.mockResolvedValueOnce([makeEvent()]);
verifyAuditChain.mockReturnValueOnce({
ok: false,
inspected: 1,
firstBreak: { eventId: "audit_1", reason: "hash-mismatch" },
});
await auditExportPdfCommand.run?.({
args: { tenant: "tenant_1", out: "/tmp/audit.pdf" },
} as never);
expect(writeFile).toHaveBeenCalledTimes(1);
expect(consoleMock.error).toHaveBeenCalledWith(
expect.stringContaining("audit-pdf written WITH BROKEN CHAIN"),
);
expect(process.exitCode).toBe(1);
});
it("rejects an empty --out before touching the database", async () => {
await auditExportPdfCommand.run?.({ args: { tenant: "tenant_1", out: " " } } as never);
expect(consoleMock.error).toHaveBeenCalledWith("Missing --out.");
expect(findMany).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
});
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@hivegrid/exports/audit-pdf";
import { runAuditExportPdf, type AuditExportPdfDependencies } from "./export-pdf.js";
function makeEvent(over: Partial<AuditPdfEvent> = {}): AuditPdfEvent {
@@ -50,7 +50,7 @@ function makeDeps(opts: {
render: async (input) => {
state.renderInput = input;
// Fake PDF bytes — the renderer is unit-tested separately in
// @toolctrl/exports.
// @hivegrid/exports.
return new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x37]); // "%PDF-1.7"
},
writeOutput: async (path, bytes) => {
@@ -1,5 +1,5 @@
/**
* `toolctrl audit export-pdf --tenant <id> [--from] [--to] [--regulatory-scope]
* `hivegrid audit export-pdf --tenant <id> [--from] [--to] [--regulatory-scope]
* --out <path>`
*
* Renders a tamper-evident PDF compliance report from AuditEvent rows for
@@ -7,7 +7,7 @@
* `verifyAuditChain` integrity check; the body lists each event in
* chronological order with hash + actor + outcome + scope.
*
* Renders via @react-pdf/renderer through `@toolctrl/exports/audit-pdf`.
* Renders via @react-pdf/renderer through `@hivegrid/exports/audit-pdf`.
*
* See docs/improvement-plan/10-compliance-polish/compliance-audit-export.md.
*/
@@ -15,7 +15,7 @@ import { writeFile } from "node:fs/promises";
import { defineCommand } from "citty";
import consola from "consola";
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@toolctrl/exports/audit-pdf";
import type { AuditPdfEvent, AuditPdfIntegrity, AuditPdfReportInput } from "@hivegrid/exports/audit-pdf";
const AUDIT_PDF_QUERY_LIMIT = 5_000;
@@ -138,9 +138,9 @@ export const auditExportPdfCommand = defineCommand({
},
async run({ args }) {
const [{ getReadDbClient }, { verifyAuditChain }, { serializeAuditEventsToPdf }] = await Promise.all([
import("@toolctrl/db/client.server"),
import("@toolctrl/db/audit-hash"),
import("@toolctrl/exports/audit-pdf"),
import("@hivegrid/db/client.server"),
import("@hivegrid/db/audit-hash"),
import("@hivegrid/exports/audit-pdf"),
]);
const db = getReadDbClient();
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { computeAuditHash, verifyAuditChain } from "@toolctrl/db/audit-hash";
import { computeAuditHash, verifyAuditChain } from "@hivegrid/db/audit-hash";
import {
runAuditVerifyChain,
type AuditVerifyChainDependencies,
@@ -1,7 +1,7 @@
/**
* `toolctrl audit verify-chain --tenant <id> [--from <iso8601>] [--to <iso8601>] [--json]`
* `hivegrid audit verify-chain --tenant <id> [--from <iso8601>] [--to <iso8601>] [--json]`
*
* Thin CLI wrapper around `verifyAuditChain` from @toolctrl/db/audit-hash.
* Thin CLI wrapper around `verifyAuditChain` from @hivegrid/db/audit-hash.
* Loads the per-tenant AuditEvent chain in chronological order, recomputes
* each event's eventHash and compares it against the stored value. Exits
* 0 on intact chain, non-zero with first-break diagnostics otherwise.
@@ -21,7 +21,7 @@
import { defineCommand } from "citty";
import consola from "consola";
import type { AuditChainEvent, VerifyAuditChainResult } from "@toolctrl/db/audit-hash";
import type { AuditChainEvent, VerifyAuditChainResult } from "@hivegrid/db/audit-hash";
const AUDIT_VERIFY_BATCH_SIZE = 5_000;
@@ -37,7 +37,7 @@ export type AuditVerifyChainRow = AuditChainEvent;
export type AuditVerifyChainDependencies = {
/** Cursor-iterable read of events ordered by createdAt ascending. */
readRows: (args: { tenantId: string; from: Date | null; to: Date | null; batchSize: number }) => AsyncIterable<AuditVerifyChainRow>;
/** Chain verifier — usually `verifyAuditChain` from @toolctrl/db/audit-hash. */
/** Chain verifier — usually `verifyAuditChain` from @hivegrid/db/audit-hash. */
verify: (events: ReadonlyArray<AuditVerifyChainRow>, options?: { secret?: string | null }) => VerifyAuditChainResult;
/** Output sink. Tests pass an array collector; production wires consola. */
output: { info: (msg: string) => void; json: (obj: unknown) => void; error: (msg: string) => void };
@@ -111,8 +111,8 @@ export const auditVerifyChainCommand = defineCommand({
json: { type: "boolean", required: false, default: false, description: "Emit a single JSON object instead of human-readable text." },
},
async run({ args }) {
const { verifyAuditChain } = await import("@toolctrl/db/audit-hash");
const { getReadDbClient } = await import("@toolctrl/db/client.server");
const { verifyAuditChain } = await import("@hivegrid/db/audit-hash");
const { getReadDbClient } = await import("@hivegrid/db/client.server");
const db = getReadDbClient();
const tenantId = String(args.tenant);
@@ -9,7 +9,7 @@ describe("create entity generator", () => {
const fakeTimestamp = "20260101000000";
beforeEach(async () => {
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-entity-"));
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-entity-"));
});
afterEach(async () => {
@@ -1,5 +1,5 @@
/**
* `toolctrl create entity <name>` — emit a Prisma model snippet plus a
* `hivegrid create entity <name>` — emit a Prisma model snippet plus a
* timestamped migration directory.
*
* The generator does NOT modify `prisma/schema.prisma` automatically —
@@ -92,7 +92,7 @@ function defaultTimestamp(): string {
}
function renderPrismaModel({ pascal, snake }: { pascal: string; snake: string }): string {
return `// Generated by toolctrl-cli — paste this block into prisma/schema.prisma.
return `// Generated by hivegrid-cli — paste this block into prisma/schema.prisma.
model ${pascal} {
id String @id @default(cuid())
tenantId String
@@ -107,7 +107,7 @@ model ${pascal} {
}
function renderMigrationSql({ pascal, snake }: { pascal: string; snake: string }): string {
return `-- Generated by toolctrl-cli for entity ${pascal}.
return `-- Generated by hivegrid-cli for entity ${pascal}.
-- Replace columns with actual schema before running \`prisma migrate dev\`.
CREATE TABLE "${snake}" (
"id" TEXT NOT NULL,
@@ -133,7 +133,7 @@ function renderMigrationReadme({
}): string {
return `# Migration: create entity ${pascal}
Generated by \`toolctrl create entity ${kebab}\`.
Generated by \`hivegrid create entity ${kebab}\`.
## How to apply
@@ -8,7 +8,7 @@ describe("create module generator", () => {
let tempRoot: string;
beforeEach(async () => {
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-module-"));
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-module-"));
});
afterEach(async () => {
@@ -1,5 +1,5 @@
/**
* `toolctrl create module <name>` — generate a new feature-module skeleton
* `hivegrid create module <name>` — generate a new feature-module skeleton
* under `apps/web/app/modules/<name>/`.
*
* The generator emits the minimum set of files needed for a tenant-scoped
@@ -107,7 +107,7 @@ export async function generateModule(options: GenerateModuleOptions): Promise<Sc
function renderDbFile({ camel, pascal }: { camel: string; pascal: string }): string {
return `/**
* Tenant-scoped CRUD helpers for the ${pascal} module.
* Generated by toolctrl-cli — fill in the model field references after
* Generated by hivegrid-cli — fill in the model field references after
* adding the Prisma model and running \`prisma migrate dev\`.
*/
import { db } from "~/utils/db.server";
@@ -134,7 +134,7 @@ function renderServiceFile({ camel, pascal }: { camel: string; pascal: string })
return `/**
* Service-layer for the ${pascal} module — wraps the db helpers with
* tenant-access guards so route handlers don't have to repeat the
* permission boilerplate.
* permission scaffold.
*/
import { list${pascal}, get${pascal}ById } from "../db/${camel}.db.server";
@@ -193,7 +193,7 @@ import { ${pascal}List } from "~/modules/${camel}/components/${pascal}List";
/**
* Tenant route for the ${pascal} module.
* Generated by toolctrl-cli. Wire in \`requireAuth\` and the
* Generated by hivegrid-cli. Wire in \`requireAuth\` and the
* "${permissionPrefix}.view" permission guard once you connect the module
* to your auth helpers.
*/
@@ -241,7 +241,7 @@ function renderReadme({
}): string {
return `# ${pascal} module
Generated by \`toolctrl create module ${kebab}\`.
Generated by \`hivegrid create module ${kebab}\`.
## Layout
@@ -8,7 +8,7 @@ describe("create route generator", () => {
let tempRoot: string;
beforeEach(async () => {
tempRoot = await mkdtemp(path.join(tmpdir(), "toolctrl-cli-route-"));
tempRoot = await mkdtemp(path.join(tmpdir(), "hivegrid-cli-route-"));
});
afterEach(async () => {
@@ -1,5 +1,5 @@
/**
* `toolctrl create route <path>` — generate a single React-Router-v7
* `hivegrid create route <path>` — generate a single React-Router-v7
* route file with a sensible auth/CSRF default plus a co-located
* vitest stub.
*
@@ -97,7 +97,7 @@ function renderRoute({
import { isRouteErrorResponse } from "react-router";
/**
* Generated by \`toolctrl create route ${filename}\`.
* Generated by \`hivegrid create route ${filename}\`.
* TODO: wire \`requireAuth(request)\` and \`validateCSRFToken(request)\`
* from your project's auth utility module.
*/
@@ -24,10 +24,10 @@ function getDsgvoCliMocks(): DsgvoCliMocks {
return global.__dsgvoCliMocks__;
}
vi.mock("@toolctrl/db/client.server", () => ({
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => getDsgvoCliMocks().db,
}));
vi.mock("@toolctrl/db/audit-events.server", () => ({
vi.mock("@hivegrid/db/audit-events.server", () => ({
createAuditEvent: getDsgvoCliMocks().createAuditEvent,
}));
vi.mock("consola", () => ({
@@ -47,8 +47,8 @@ export const dsgvoDeleteCommand = defineCommand({
const requestId = randomUUID();
const [{ getDbClient }, { createAuditEvent }] = await Promise.all([
import("@toolctrl/db/client.server"),
import("@toolctrl/db/audit-events.server"),
import("@hivegrid/db/client.server"),
import("@hivegrid/db/audit-events.server"),
]);
const prisma = getDbClient();
await prisma.user.update({
@@ -0,0 +1,107 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
type AuditEventInput = {
tenantId: string | null;
actorId: string;
actorType: string;
action: string;
targetType: string;
targetId: string;
regulatoryScope: string[];
dataSensitivity: string;
outcome: string;
metadata: { requestId: string; intent: string; source: string };
};
const createAuditEvent = vi.fn<(input: AuditEventInput) => Promise<{ id: string }>>();
vi.mock("@hivegrid/db/audit-events.server", () => ({
createAuditEvent: (...args: unknown[]) => createAuditEvent(...(args as [AuditEventInput])),
}));
vi.mock("consola", () => ({
default: {
success: vi.fn(),
},
}));
import consola from "consola";
import { dsgvoExportCommand } from "./export.js";
import { dsgvoVerifyCommand } from "./verify.js";
const consoleMock = vi.mocked(consola);
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u;
describe("dsgvo export command", () => {
beforeEach(() => {
vi.clearAllMocks();
createAuditEvent.mockResolvedValue({ id: "audit_1" });
});
it("writes a REQUEST_PERSONAL_DATA_EXPORT audit row with explicit tenant and actor", async () => {
await dsgvoExportCommand.run?.({
args: { user: "user_1", tenant: "tenant_1", actor: "admin_1" },
} as never);
expect(createAuditEvent).toHaveBeenCalledTimes(1);
const payload = createAuditEvent.mock.calls[0]![0];
expect(payload).toMatchObject({
tenantId: "tenant_1",
actorId: "admin_1",
action: "REQUEST_PERSONAL_DATA_EXPORT",
targetType: "User",
targetId: "user_1",
regulatoryScope: ["gdpr"],
dataSensitivity: "pii",
outcome: "success",
});
expect(payload.metadata.intent).toBe("export");
expect(payload.metadata.source).toBe("cli");
expect(payload.metadata.requestId).toMatch(UUID_RE);
expect(consoleMock.success).toHaveBeenCalledWith(
`Personal-data export queued for user=user_1 requestId=${payload.metadata.requestId}`,
);
});
it("defaults the actor to cli-operator and tenant to null when omitted", async () => {
await dsgvoExportCommand.run?.({ args: { user: "user_2" } } as never);
expect(createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: null, actorId: "cli-operator" }),
);
});
});
describe("dsgvo verify command", () => {
beforeEach(() => {
vi.clearAllMocks();
createAuditEvent.mockResolvedValue({ id: "audit_1" });
});
it("writes a VERIFY_USER_DELETION audit row with verify intent", async () => {
await dsgvoVerifyCommand.run?.({
args: { user: "user_1", tenant: "tenant_1", actor: "admin_1" },
} as never);
const payload = createAuditEvent.mock.calls[0]![0];
expect(payload).toMatchObject({
tenantId: "tenant_1",
actorId: "admin_1",
action: "VERIFY_USER_DELETION",
targetType: "User",
targetId: "user_1",
});
expect(payload.metadata.intent).toBe("verify");
expect(payload.metadata.requestId).toMatch(UUID_RE);
expect(consoleMock.success).toHaveBeenCalledWith(
`Verifier-pass queued for user=user_1 requestId=${payload.metadata.requestId}`,
);
});
it("defaults the actor and tenant when only the user id is given", async () => {
await dsgvoVerifyCommand.run?.({ args: { user: "user_9" } } as never);
expect(createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: null, actorId: "cli-operator" }),
);
});
});
@@ -23,7 +23,7 @@ export const dsgvoExportCommand = defineCommand({
const actorId = args.actor ? String(args.actor) : "cli-operator";
const requestId = randomUUID();
const { createAuditEvent } = await import("@toolctrl/db/audit-events.server");
const { createAuditEvent } = await import("@hivegrid/db/audit-events.server");
await createAuditEvent({
tenantId,
actorId,
@@ -23,8 +23,8 @@ export const dsgvoReactivateCommand = defineCommand({
const requestId = randomUUID();
const [{ getDbClient }, { createAuditEvent }] = await Promise.all([
import("@toolctrl/db/client.server"),
import("@toolctrl/db/audit-events.server"),
import("@hivegrid/db/client.server"),
import("@hivegrid/db/audit-events.server"),
]);
const prisma = getDbClient();
const existing = await prisma.user.findUnique({
@@ -25,7 +25,7 @@ export const dsgvoVerifyCommand = defineCommand({
const tenantId = args.tenant ? String(args.tenant) : null;
const actorId = args.actor ? String(args.actor) : "cli-operator";
const requestId = randomUUID();
const { createAuditEvent } = await import("@toolctrl/db/audit-events.server");
const { createAuditEvent } = await import("@hivegrid/db/audit-events.server");
await createAuditEvent({
tenantId,
actorId,
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const publishMock = vi.fn();
vi.mock("@toolctrl/feature-flags", () => ({
vi.mock("@hivegrid/feature-flags", () => ({
publishFeatureFlagInvalidationOnce: (...args: unknown[]) => publishMock(...args),
}));
@@ -10,7 +10,7 @@
* web side (60s default) is the safety net.
*/
import consola from "consola";
import { publishFeatureFlagInvalidationOnce } from "@toolctrl/feature-flags";
import { publishFeatureFlagInvalidationOnce } from "@hivegrid/feature-flags";
const DEFAULT_PUBLISH_NAMESPACE = "web";
@@ -17,7 +17,7 @@ const dbMock = {
},
};
vi.mock("@toolctrl/db/client.server", () => ({
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => dbMock,
}));
vi.mock("consola", () => ({
@@ -18,7 +18,7 @@ export const featureFlagsListCommand = defineCommand({
},
async run({ args }) {
const filter = args.enabled === undefined ? undefined : String(args.enabled) === "true";
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const where = filter === undefined ? {} : { enabled: filter };
const flags = await prisma.featureFlag.findMany({
@@ -22,10 +22,10 @@ const dbMock = {
const broadcastFlagInvalidationMock = vi.fn();
const evaluateRuleMock = vi.fn();
vi.mock("@toolctrl/db/client.server", () => ({
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => dbMock,
}));
vi.mock("@toolctrl/feature-flags", () => ({
vi.mock("@hivegrid/feature-flags", () => ({
evaluateRule: (...args: unknown[]) => evaluateRuleMock(...args),
}));
vi.mock("consola", () => ({
@@ -52,7 +52,7 @@ function writeRulesFile(contents: string): string {
describe("feature flag set-rules command", () => {
beforeEach(() => {
tempDir = mkdtempSync(join(tmpdir(), "toolctrl-cli-flags-"));
tempDir = mkdtempSync(join(tmpdir(), "hivegrid-cli-flags-"));
vi.clearAllMocks();
process.exitCode = undefined;
dbMock.$transaction.mockResolvedValue([]);
@@ -7,7 +7,7 @@
import { defineCommand } from "citty";
import consola from "consola";
import { readFileSync } from "node:fs";
import { evaluateRule, type TargetingRule } from "@toolctrl/feature-flags";
import { evaluateRule, type TargetingRule } from "@hivegrid/feature-flags";
import { broadcastFlagInvalidation } from "./invalidate.js";
async function applyRules(name: string, rulesJson: string): Promise<void> {
@@ -29,7 +29,7 @@ async function applyRules(name: string, rulesJson: string): Promise<void> {
return;
}
}
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const existing = await prisma.featureFlag.findFirst({ where: { name } });
if (!existing) {
@@ -18,7 +18,7 @@ const dbMock = {
};
const broadcastFlagInvalidationMock = vi.fn();
vi.mock("@toolctrl/db/client.server", () => ({
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => dbMock,
}));
vi.mock("consola", () => ({
@@ -11,7 +11,7 @@ import consola from "consola";
import { broadcastFlagInvalidation } from "./invalidate.js";
async function toggleFlag(name: string, target: boolean): Promise<void> {
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const existing = await prisma.featureFlag.findFirst({ where: { name } });
if (!existing) {
@@ -0,0 +1,144 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
type FormRow = {
id: string;
key: string;
name: string;
isEnabled: boolean;
_count: { submissions: number };
};
type FormCreateArgs = {
data: {
tenantId: string;
name: string;
definition: { fields: Array<{ key: string; type: string }> };
allowedOrigins: string[];
config: { honeypotEnabled: boolean };
};
};
const dbMock = {
form: {
create: vi.fn<(args: FormCreateArgs) => Promise<{ id: string; key: string }>>(),
findMany: vi.fn<() => Promise<FormRow[]>>(),
findUnique: vi.fn<() => Promise<{ id: string; name: string } | null>>(),
delete: vi.fn<() => Promise<{ id: string }>>(),
},
};
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => dbMock,
}));
vi.mock("consola", () => ({
default: {
info: vi.fn(),
log: vi.fn(),
error: vi.fn(),
success: vi.fn(),
},
}));
import consola from "consola";
import { formsCreateCommand } from "./create.js";
import { formsDeleteCommand } from "./delete.js";
import { formsListCommand } from "./list.js";
const consoleMock = vi.mocked(consola);
describe("forms create command", () => {
beforeEach(() => {
vi.clearAllMocks();
process.exitCode = undefined;
dbMock.form.create.mockResolvedValue({ id: "form_1", key: "pub_key_1" });
});
it("seeds the default text/email/textarea/honeypot definition with no origins", async () => {
await formsCreateCommand.run?.({ args: { tenant: "tenant_1", name: "Contact" } } as never);
expect(dbMock.form.create).toHaveBeenCalledTimes(1);
const payload = dbMock.form.create.mock.calls[0]![0];
expect(payload.data.tenantId).toBe("tenant_1");
expect(payload.data.name).toBe("Contact");
expect(payload.data.allowedOrigins).toEqual([]);
expect(payload.data.config).toEqual({ honeypotEnabled: true });
const fieldTypes = payload.data.definition.fields.map((f) => f.type);
expect(fieldTypes).toEqual(["text", "email", "textarea", "honeypot"]);
expect(consoleMock.success).toHaveBeenCalledWith("Form created: id=form_1 key=pub_key_1");
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining('data-form-key="pub_key_1"'));
});
it("records the allowed embedding origin when --origin is supplied", async () => {
await formsCreateCommand.run?.({
args: { tenant: "tenant_1", name: "Newsletter", origin: "https://acme.example" },
} as never);
const payload = dbMock.form.create.mock.calls[0]![0];
expect(payload.data.allowedOrigins).toEqual(["https://acme.example"]);
});
});
describe("forms list command", () => {
beforeEach(() => {
vi.clearAllMocks();
dbMock.form.findMany.mockResolvedValue([]);
});
it("prints ON/OFF state, submission counts, and a closing summary", async () => {
dbMock.form.findMany.mockResolvedValueOnce([
{ id: "form_1", key: "pub_a", name: "Contact", isEnabled: true, _count: { submissions: 12 } },
{ id: "form_2", key: "pub_b", name: "Survey", isEnabled: false, _count: { submissions: 0 } },
]);
await formsListCommand.run?.({ args: { tenant: "tenant_1" } } as never);
expect(dbMock.form.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
orderBy: { createdAt: "desc" },
select: {
id: true,
key: true,
name: true,
isEnabled: true,
_count: { select: { submissions: true } },
},
});
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/^ON .*form_1.*subs=12 Contact/u));
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/^OFF.*form_2.*subs=0 Survey/u));
expect(consoleMock.success).toHaveBeenCalledWith("2 forms listed.");
});
it("reports an empty tenant without a summary line", async () => {
await formsListCommand.run?.({ args: { tenant: "tenant_empty" } } as never);
expect(consoleMock.info).toHaveBeenCalledWith("No forms for tenant tenant_empty.");
expect(consoleMock.success).not.toHaveBeenCalled();
});
});
describe("forms delete command", () => {
beforeEach(() => {
vi.clearAllMocks();
process.exitCode = undefined;
dbMock.form.findUnique.mockResolvedValue(null);
dbMock.form.delete.mockResolvedValue({ id: "form_1" });
});
it("hard-deletes an existing form and confirms with its name", async () => {
dbMock.form.findUnique.mockResolvedValueOnce({ id: "form_1", name: "Contact" });
await formsDeleteCommand.run?.({ args: { id: "form_1" } } as never);
expect(dbMock.form.delete).toHaveBeenCalledWith({ where: { id: "form_1" } });
expect(consoleMock.success).toHaveBeenCalledWith("Form deleted: form_1 (Contact).");
expect(process.exitCode).toBeUndefined();
});
it("sets a non-zero exit code and skips the delete when the form is missing", async () => {
await formsDeleteCommand.run?.({ args: { id: "ghost" } } as never);
expect(consoleMock.error).toHaveBeenCalledWith("Form ghost not found.");
expect(process.exitCode).toBe(1);
expect(dbMock.form.delete).not.toHaveBeenCalled();
});
});
@@ -5,7 +5,7 @@
*/
import { defineCommand } from "citty";
import consola from "consola";
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@toolctrl/form-widget";
import { FormDefinitionSchema, HONEYPOT_FIELD_KEY } from "@hivegrid/form-widget";
export const formsCreateCommand = defineCommand({
meta: { name: "create", description: "Seed a minimal form for a tenant." },
@@ -29,7 +29,7 @@ export const formsCreateCommand = defineCommand({
{ key: HONEYPOT_FIELD_KEY, type: "honeypot", label: "Leave empty" },
],
});
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const created = await prisma.form.create({
data: {
@@ -11,7 +11,7 @@ export const formsDeleteCommand = defineCommand({
id: { type: "string", required: true, description: "Form ID." },
},
async run({ args }) {
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const id = String(args.id);
const existing = await prisma.form.findUnique({ where: { id }, select: { id: true, name: true } });
@@ -10,7 +10,7 @@ export const formsListCommand = defineCommand({
tenant: { type: "string", required: true, description: "Tenant ID." },
},
async run({ args }) {
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const tenantId = String(args.tenant);
const forms = await prisma.form.findMany({
@@ -19,7 +19,7 @@ const dbMock = {
};
const writeFileMock = vi.fn();
vi.mock("@toolctrl/db/client.server", () => ({
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => dbMock,
}));
vi.mock("node:fs/promises", () => ({
@@ -0,0 +1,52 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const dbMock = {
lead: {
findUnique: vi.fn<() => Promise<{ email: string } | null>>(),
delete: vi.fn<() => Promise<{ id: string }>>(),
},
};
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => dbMock,
}));
vi.mock("consola", () => ({
default: {
warn: vi.fn(),
success: vi.fn(),
},
}));
import consola from "consola";
import { leadsDeleteCommand } from "./delete.js";
const consoleMock = vi.mocked(consola);
describe("leads delete command", () => {
beforeEach(() => {
vi.clearAllMocks();
dbMock.lead.findUnique.mockResolvedValue(null);
dbMock.lead.delete.mockResolvedValue({ id: "lead_1" });
});
it("hard-deletes an existing lead and echoes its email for the audit trail", async () => {
dbMock.lead.findUnique.mockResolvedValueOnce({ email: "ada@example.com" });
await leadsDeleteCommand.run?.({ args: { id: "lead_1" } } as never);
expect(dbMock.lead.findUnique).toHaveBeenCalledWith({
where: { id: "lead_1" },
select: { email: true },
});
expect(dbMock.lead.delete).toHaveBeenCalledWith({ where: { id: "lead_1" } });
expect(consoleMock.success).toHaveBeenCalledWith("Deleted lead lead_1 (ada@example.com).");
});
it("warns and skips the delete when the lead does not exist", async () => {
await leadsDeleteCommand.run?.({ args: { id: "ghost" } } as never);
expect(consoleMock.warn).toHaveBeenCalledWith("Lead ghost not found.");
expect(dbMock.lead.delete).not.toHaveBeenCalled();
expect(consoleMock.success).not.toHaveBeenCalled();
});
});
@@ -11,7 +11,7 @@ export const leadsDeleteCommand = defineCommand({
id: { type: "string", required: true, description: "Lead id." },
},
async run({ args }) {
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const id = String(args.id);
const existing = await prisma.lead.findUnique({ where: { id }, select: { email: true } });
@@ -44,7 +44,7 @@ export const leadsExportCommand = defineCommand({
status: { type: "string", required: false, description: "Filter by status." },
},
async run({ args }) {
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const where = args.status ? { status: String(args.status) as never } : {};
const leads = await prisma.lead.findMany({ where, orderBy: { createdAt: "desc" } });
@@ -11,7 +11,7 @@ export const leadsListCommand = defineCommand({
limit: { type: "string", required: false, description: "Max rows (default 50)." },
},
async run({ args }) {
const { getDbClient } = await import("@toolctrl/db/client.server");
const { getDbClient } = await import("@hivegrid/db/client.server");
const prisma = getDbClient();
const limit = Math.min(500, Math.max(1, Number(args.limit ?? "50")));
const where = args.status ? { status: String(args.status) as never } : {};
@@ -15,7 +15,7 @@ export const marketingAttributionCommand = defineCommand({
limit: { type: "string", required: false, description: "Top N rows (default 25)." },
},
async run({ args }) {
const { getReadDbClient } = await import("@toolctrl/db/client.server");
const { getReadDbClient } = await import("@hivegrid/db/client.server");
const prisma = getReadDbClient();
const days = Math.min(365, Math.max(1, Number(args.days ?? "30")));
const dim = (DIMENSIONS as readonly string[]).includes(String(args.dimension ?? ""))
@@ -0,0 +1,178 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
type GroupByRow = {
_count: { _all: number };
utmCampaign?: string | null;
utmSource?: string | null;
source?: string | null;
conversionPath?: string | null;
};
const dbMock = {
tenantAcquisition: {
groupBy: vi.fn<() => Promise<GroupByRow[]>>(),
count: vi.fn<() => Promise<number>>(),
},
lead: {
count: vi.fn<() => Promise<number>>(),
groupBy: vi.fn<() => Promise<Array<{ status: string; _count: { _all: number } }>>>(),
},
};
vi.mock("@hivegrid/db/client.server", () => ({
getReadDbClient: () => dbMock,
}));
vi.mock("consola", () => ({
default: {
info: vi.fn(),
log: vi.fn(),
},
}));
import consola from "consola";
import { marketingAttributionCommand } from "./attribution.js";
import { marketingFunnelCommand } from "./funnel.js";
const consoleMock = vi.mocked(consola);
const now = new Date("2026-06-25T00:00:00.000Z");
describe("marketing attribution command", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(now);
vi.clearAllMocks();
dbMock.tenantAcquisition.groupBy.mockResolvedValue([]);
});
afterEach(() => {
vi.useRealTimers();
});
it("defaults to the campaign dimension, 30 days, and limit 25", async () => {
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([
{ utmCampaign: "spring", _count: { _all: 7 } },
{ utmCampaign: null, _count: { _all: 3 } },
]);
await marketingAttributionCommand.run?.({ args: {} } as never);
const since = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith({
by: ["utmCampaign"],
_count: { _all: true },
where: { convertedAt: { gte: since } },
orderBy: { _count: { tenantId: "desc" } },
take: 25,
});
expect(consoleMock.log).toHaveBeenCalledWith(
expect.stringContaining(`Attribution by campaign — last 30 days (since ${since.toISOString().slice(0, 10)})`),
);
// Null keys fall back to "(none)" and counts are padded.
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("spring"));
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("(none)"));
});
it("groups by utmSource when that dimension is requested", async () => {
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([{ utmSource: "newsletter", _count: { _all: 2 } }]);
await marketingAttributionCommand.run?.({ args: { dimension: "utmSource" } } as never);
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
expect.objectContaining({ by: ["utmSource"] }),
);
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("Attribution by utmSource"));
});
it("groups by source when that dimension is requested", async () => {
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([{ source: "organic", _count: { _all: 9 } }]);
await marketingAttributionCommand.run?.({ args: { dimension: "source" } } as never);
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
expect.objectContaining({ by: ["source"] }),
);
});
it("groups by conversionPath for the path dimension", async () => {
dbMock.tenantAcquisition.groupBy.mockResolvedValueOnce([{ conversionPath: "/pricing", _count: { _all: 4 } }]);
await marketingAttributionCommand.run?.({ args: { dimension: "path" } } as never);
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
expect.objectContaining({ by: ["conversionPath"] }),
);
});
it("falls back to campaign for an unknown dimension value", async () => {
await marketingAttributionCommand.run?.({ args: { dimension: "garbage" } } as never);
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
expect.objectContaining({ by: ["utmCampaign"] }),
);
});
it("clamps days to the [1, 365] window and limit to [1, 200]", async () => {
await marketingAttributionCommand.run?.({ args: { days: "9999", limit: "5000" } } as never);
const since365 = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
expect.objectContaining({ where: { convertedAt: { gte: since365 } }, take: 200 }),
);
vi.clearAllMocks();
dbMock.tenantAcquisition.groupBy.mockResolvedValue([]);
await marketingAttributionCommand.run?.({ args: { days: "0", limit: "0" } } as never);
const since1 = new Date(now.getTime() - 1 * 24 * 60 * 60 * 1000);
expect(dbMock.tenantAcquisition.groupBy).toHaveBeenCalledWith(
expect.objectContaining({ where: { convertedAt: { gte: since1 } }, take: 1 }),
);
});
it("reports an empty period via consola.info without a table", async () => {
await marketingAttributionCommand.run?.({ args: { days: "14" } } as never);
expect(consoleMock.info).toHaveBeenCalledWith("No conversions in last 14 days.");
expect(consoleMock.log).not.toHaveBeenCalled();
});
});
describe("marketing funnel command", () => {
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(now);
vi.clearAllMocks();
dbMock.lead.count.mockResolvedValue(0);
dbMock.tenantAcquisition.count.mockResolvedValue(0);
dbMock.lead.groupBy.mockResolvedValue([]);
});
afterEach(() => {
vi.useRealTimers();
});
it("computes the conversion rate and renders the full stage ladder", async () => {
dbMock.lead.count.mockResolvedValueOnce(200);
dbMock.tenantAcquisition.count.mockResolvedValueOnce(50);
dbMock.lead.groupBy.mockResolvedValueOnce([
{ status: "new", _count: { _all: 120 } },
{ status: "customer", _count: { _all: 50 } },
]);
await marketingFunnelCommand.run?.({ args: {} } as never);
expect(consoleMock.log).toHaveBeenCalledWith("Leads captured: 200");
expect(consoleMock.log).toHaveBeenCalledWith("Conversions: 50");
expect(consoleMock.log).toHaveBeenCalledWith("Conversion rate: 25.00%");
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("new"));
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringContaining("120"));
// Stages without data render a zero count rather than being skipped.
expect(consoleMock.log).toHaveBeenCalledWith(expect.stringMatching(/churned\s+0/u));
});
it("guards division by zero when no leads were captured", async () => {
await marketingFunnelCommand.run?.({ args: { days: "7" } } as never);
const since = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
expect(dbMock.lead.count).toHaveBeenCalledWith({ where: { createdAt: { gte: since } } });
expect(consoleMock.log).toHaveBeenCalledWith("Conversion rate: 0.00%");
});
});
@@ -12,7 +12,7 @@ export const marketingFunnelCommand = defineCommand({
days: { type: "string", required: false, description: "Period in days (default 30)." },
},
async run({ args }) {
const { getReadDbClient } = await import("@toolctrl/db/client.server");
const { getReadDbClient } = await import("@hivegrid/db/client.server");
const prisma = getReadDbClient();
const days = Math.min(365, Math.max(1, Number(args.days ?? "30")));
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
@@ -8,7 +8,7 @@ describe("ops env resolver", () => {
let home: string;
beforeEach(() => {
home = mkdtempSync(path.join(tmpdir(), "toolctrl-cli-ops-env-"));
home = mkdtempSync(path.join(tmpdir(), "hivegrid-cli-ops-env-"));
});
afterEach(() => {
@@ -23,8 +23,8 @@ describe("ops env resolver", () => {
expect(resolved.warnings).toEqual([]);
});
it("reads ~/.toolctrl/envs/<name>.env when --env is supplied", () => {
const envDir = path.join(home, ".toolctrl", "envs");
it("reads ~/.hivegrid/envs/<name>.env when --env is supplied", () => {
const envDir = path.join(home, ".hivegrid", "envs");
mkdirSync(envDir, { recursive: true });
const file = path.join(envDir, "staging.env");
writeFileSync(file, "# header\nDATABASE_URL=postgres://u:p@host:5432/db\nREDIS_URL=\"redis://r\"\n");
@@ -38,7 +38,7 @@ describe("ops env resolver", () => {
});
it("warns when the env-file is world-readable", () => {
const envDir = path.join(home, ".toolctrl", "envs");
const envDir = path.join(home, ".hivegrid", "envs");
mkdirSync(envDir, { recursive: true });
const file = path.join(envDir, "loose.env");
writeFileSync(file, "FOO=bar\n");
@@ -1,11 +1,11 @@
/**
* `toolctrl ops` env resolver.
* `hivegrid ops` env resolver.
*
* Two layers:
* - **local (default):** the operator's working-dir `.env` (already loaded
* by the runtime via dotenv or shell-export). We just read from
* `process.env`.
* - **named (`--env=<name>`):** parsed from `~/.toolctrl/envs/<name>.env`.
* - **named (`--env=<name>`):** parsed from `~/.hivegrid/envs/<name>.env`.
* File format is a simple `KEY=VALUE` `.env` syntax — no shell
* interpolation. Lines starting with `#` and blank lines are skipped.
*
@@ -63,7 +63,7 @@ export function resolveOpsEnv(options: ResolveEnvOptions = {}): ResolvedOpsEnv {
}
validateEnvName(options.name);
const home = options.homeDirOverride ?? homedir();
const filePath = path.join(home, ".toolctrl", "envs", `${options.name}.env`);
const filePath = path.join(home, ".hivegrid", "envs", `${options.name}.env`);
if (!existsSync(filePath)) {
throw new OpsEnvError(
`Env file not found: ${filePath}. Create it (chmod 600) before invoking --env=${options.name}.`,
Loaded 100 of 3781 files, more files were not shown because too many files have changed in this diff. Show more