Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@toolctrl/foundation",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./outbound-http": "./src/outbound-http.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "pnpm run typecheck",
|
||||
"test": "vitest run src",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@toolctrl/i18n": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.0.0",
|
||||
"typescript": "^5.3.2",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export type AdapterStatus = "not_configured" | "configured" | "healthy" | "degraded" | "unavailable";
|
||||
|
||||
export type AdapterDefinition<TAdapter = unknown> = {
|
||||
key: string;
|
||||
status: AdapterStatus;
|
||||
adapter?: TAdapter;
|
||||
};
|
||||
|
||||
const adapters = new Map<string, AdapterDefinition>();
|
||||
|
||||
export function defineAdapter<TAdapter>(definition: AdapterDefinition<TAdapter>): AdapterDefinition<TAdapter> {
|
||||
adapters.set(definition.key, definition as AdapterDefinition);
|
||||
return definition;
|
||||
}
|
||||
|
||||
export function getAdapter<TAdapter = unknown>(key: string): AdapterDefinition<TAdapter> {
|
||||
return (adapters.get(key) as AdapterDefinition<TAdapter> | undefined) ?? { key, status: "not_configured" };
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { auditEvent, withAuditMiddleware } from "./audit.js";
|
||||
|
||||
describe("foundation audit helpers", () => {
|
||||
it("normalizes empty optional fields and falls back to system actor type", async () => {
|
||||
const client = { auditEvent: { create: vi.fn(async (args) => args.data) } };
|
||||
|
||||
await auditEvent(
|
||||
{
|
||||
action: "resource.updated",
|
||||
tenantId: undefined,
|
||||
actorId: undefined,
|
||||
actorType: " ",
|
||||
targetType: undefined,
|
||||
targetId: undefined,
|
||||
requestId: undefined,
|
||||
metadata: undefined,
|
||||
},
|
||||
client,
|
||||
);
|
||||
|
||||
expect(client.auditEvent.create).toHaveBeenCalledWith({
|
||||
data: {
|
||||
tenantId: null,
|
||||
actorId: null,
|
||||
actorType: "system",
|
||||
action: "resource.updated",
|
||||
targetType: null,
|
||||
targetId: null,
|
||||
requestId: null,
|
||||
metadata: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves trimmed actor types and skips null middleware events", async () => {
|
||||
const client = { auditEvent: { create: vi.fn(async (args) => args.data) } };
|
||||
await auditEvent({ action: "resource.created", actorType: " user " }, client);
|
||||
|
||||
expect(client.auditEvent.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ action: "resource.created", actorType: "user" }),
|
||||
});
|
||||
|
||||
client.auditEvent.create.mockClear();
|
||||
const handler = withAuditMiddleware(async () => ({ id: "result_1" }), () => null, client);
|
||||
|
||||
await expect(handler()).resolves.toEqual({ id: "result_1" });
|
||||
expect(client.auditEvent.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { JsonValue } from "./errors.js";
|
||||
|
||||
export type AuditEventInput = {
|
||||
tenantId?: string | null;
|
||||
actorId?: string | null;
|
||||
actorType?: string | null;
|
||||
action: string;
|
||||
targetType?: string | null;
|
||||
targetId?: string | null;
|
||||
requestId?: string | null;
|
||||
metadata?: Record<string, JsonValue> | null;
|
||||
};
|
||||
|
||||
export type AuditEventClient = {
|
||||
auditEvent: {
|
||||
create(args: {
|
||||
data: Required<Pick<AuditEventInput, "actorType" | "action">> & Omit<AuditEventInput, "actorType" | "action">;
|
||||
}): Promise<unknown>;
|
||||
};
|
||||
};
|
||||
|
||||
export async function auditEvent(input: AuditEventInput, client: AuditEventClient): Promise<unknown> {
|
||||
return client.auditEvent.create({
|
||||
data: {
|
||||
tenantId: input.tenantId ?? null,
|
||||
actorId: input.actorId ?? null,
|
||||
actorType: input.actorType?.trim() || "system",
|
||||
action: input.action,
|
||||
targetType: input.targetType ?? null,
|
||||
targetId: input.targetId ?? null,
|
||||
requestId: input.requestId ?? null,
|
||||
metadata: input.metadata ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function withAuditMiddleware<TArgs extends readonly unknown[], TResult>(
|
||||
handler: (...args: TArgs) => Promise<TResult>,
|
||||
buildEvent: (result: TResult, args: TArgs) => AuditEventInput | null | undefined,
|
||||
client: AuditEventClient,
|
||||
): (...args: TArgs) => Promise<TResult> {
|
||||
return async (...args) => {
|
||||
const result = await handler(...args);
|
||||
const event = buildEvent(result, args);
|
||||
if (event) await auditEvent(event, client);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { mapWithConcurrency } from "./concurrency.js";
|
||||
|
||||
function deferred() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>((res) => {
|
||||
resolve = res;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
describe("mapWithConcurrency", () => {
|
||||
it("runs all items", async () => {
|
||||
const seen: number[] = [];
|
||||
await mapWithConcurrency([1, 2, 3], 2, async (item) => {
|
||||
seen.push(item);
|
||||
});
|
||||
expect(seen.sort((a, b) => a - b)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("caps active workers at the provided limit", async () => {
|
||||
let active = 0;
|
||||
let maxActive = 0;
|
||||
const releases = Array.from({ length: 5 }, () => deferred());
|
||||
const promise = mapWithConcurrency([1, 2, 3, 4, 5], 2, async (_item, index) => {
|
||||
active += 1;
|
||||
maxActive = Math.max(maxActive, active);
|
||||
await releases[index]!.promise;
|
||||
active -= 1;
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
releases[0]!.resolve();
|
||||
releases[1]!.resolve();
|
||||
await Promise.resolve();
|
||||
releases[2]!.resolve();
|
||||
releases[3]!.resolve();
|
||||
await Promise.resolve();
|
||||
releases[4]!.resolve();
|
||||
await promise;
|
||||
|
||||
expect(maxActive).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("clamps invalid concurrency to one worker", async () => {
|
||||
const order: number[] = [];
|
||||
await mapWithConcurrency([1, 2, 3], 0, async (item) => {
|
||||
order.push(item);
|
||||
});
|
||||
expect(order).toEqual([1, 2, 3]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
export async function mapWithConcurrency<T>(items: readonly T[], concurrency: number, worker: (item: T, index: number) => Promise<void>): Promise<void> {
|
||||
const limit = Math.max(1, Math.floor(concurrency));
|
||||
let nextIndex = 0;
|
||||
|
||||
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||
while (true) {
|
||||
const index = nextIndex;
|
||||
nextIndex += 1;
|
||||
if (index >= items.length) {
|
||||
return;
|
||||
}
|
||||
await worker(items[index] as T, index);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(runners);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
export type JsonPrimitive = string | number | boolean | null;
|
||||
export type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
export type CatalogErrorDefinition = {
|
||||
code: string;
|
||||
status: number;
|
||||
i18nKey: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
export const catalogRegistry = Object.freeze({}) satisfies Record<string, CatalogErrorDefinition>;
|
||||
|
||||
export class CatalogError extends Error {
|
||||
readonly code: string;
|
||||
readonly status: number;
|
||||
readonly i18nKey: string;
|
||||
readonly details?: Record<string, JsonValue>;
|
||||
|
||||
constructor(definition: CatalogErrorDefinition, details?: Record<string, JsonValue>) {
|
||||
super(definition.message ?? definition.code);
|
||||
this.name = "CatalogError";
|
||||
this.code = definition.code;
|
||||
this.status = definition.status;
|
||||
this.i18nKey = definition.i18nKey;
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
export const foundationErrors = {
|
||||
forbidden: { code: "foundation.forbidden", status: 403, i18nKey: "foundation.errors.forbidden" },
|
||||
notFound: { code: "foundation.not_found", status: 404, i18nKey: "foundation.errors.notFound" },
|
||||
idempotencyConflict: {
|
||||
code: "foundation.idempotency_conflict",
|
||||
status: 409,
|
||||
i18nKey: "foundation.errors.idempotencyConflict",
|
||||
},
|
||||
idempotencyInProgress: {
|
||||
code: "foundation.idempotency_in_progress",
|
||||
status: 409,
|
||||
i18nKey: "foundation.errors.idempotencyInProgress",
|
||||
},
|
||||
} as const satisfies Record<string, CatalogErrorDefinition>;
|
||||
|
||||
export function toPinoLogObject(error: unknown): Record<string, unknown> {
|
||||
if (error instanceof CatalogError) {
|
||||
return { error: { name: error.name, message: error.message, code: error.code, status: error.status, i18nKey: error.i18nKey, details: error.details } };
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return { error: { name: error.name, message: error.message, stack: error.stack } };
|
||||
}
|
||||
return { error };
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
export type FlagDefinition = {
|
||||
key: string;
|
||||
defaultEnabled?: boolean;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export type FlagRecord = {
|
||||
key?: string | null;
|
||||
name?: string | null;
|
||||
scope?: string | null;
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
export type FlagResolutionInput = {
|
||||
key: string;
|
||||
defaultEnabled?: boolean;
|
||||
override?: boolean | null;
|
||||
records?: readonly FlagRecord[];
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
};
|
||||
|
||||
export function defineFlag(definition: FlagDefinition): Required<Pick<FlagDefinition, "key" | "defaultEnabled">> & FlagDefinition {
|
||||
return { ...definition, defaultEnabled: definition.defaultEnabled ?? false };
|
||||
}
|
||||
|
||||
export function featureFlag(input: FlagResolutionInput): boolean {
|
||||
if (typeof input.override === "boolean") return input.override;
|
||||
const record = selectFlagRecord(input);
|
||||
return record?.enabled ?? input.defaultEnabled ?? false;
|
||||
}
|
||||
|
||||
export function selectFlagRecord<T extends FlagRecord>(input: Omit<FlagResolutionInput, "override" | "defaultEnabled" | "records"> & { records?: readonly T[] }): T | null {
|
||||
const records = (input.records ?? []).filter((record) => flagRecordKeyMatches(record, input.key));
|
||||
return (
|
||||
records.find((record) => flagRecordAppliesToUser(record, input)) ??
|
||||
records.find((record) => flagRecordAppliesToTenant(record, input)) ??
|
||||
records.find((record) => flagRecordAppliesGlobally(record)) ??
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
export type NormalizedFlagScope = "global" | "tenant" | "user";
|
||||
|
||||
export function normalizeFlagScope(record: FlagRecord): NormalizedFlagScope {
|
||||
if (record.scope === "user" || record.userId) return "user";
|
||||
if (record.scope === "tenant" || record.tenantId) return "tenant";
|
||||
return "global";
|
||||
}
|
||||
|
||||
function flagRecordKeyMatches(record: FlagRecord, key: string): boolean {
|
||||
const recordKey = record.key ?? record.name;
|
||||
return !recordKey || recordKey === key;
|
||||
}
|
||||
|
||||
function flagRecordAppliesToUser(record: FlagRecord, input: { tenantId?: string | null; userId?: string | null }): boolean {
|
||||
if (normalizeFlagScope(record) !== "user") return false;
|
||||
if (!input.userId || record.userId !== input.userId) return false;
|
||||
return !record.tenantId || record.tenantId === input.tenantId;
|
||||
}
|
||||
|
||||
function flagRecordAppliesToTenant(record: FlagRecord, input: { tenantId?: string | null }): boolean {
|
||||
return normalizeFlagScope(record) === "tenant" && Boolean(input.tenantId && record.tenantId === input.tenantId);
|
||||
}
|
||||
|
||||
function flagRecordAppliesGlobally(record: FlagRecord): boolean {
|
||||
return normalizeFlagScope(record) === "global" && !record.tenantId && !record.userId;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { CatalogError, foundationErrors, type JsonValue } from "./errors.js";
|
||||
|
||||
export type IdempotencyResponse = {
|
||||
status: number;
|
||||
body?: JsonValue;
|
||||
headers?: Record<string, string>;
|
||||
};
|
||||
|
||||
export type IdempotencyClient = {
|
||||
idempotencyKey: {
|
||||
findUnique(args: { where: { idempotency_key_scope_key: { scope: string; key: string } } }): Promise<{
|
||||
requestHash: string;
|
||||
responseStatus: number;
|
||||
responseBody: JsonValue | null;
|
||||
responseHeaders: Record<string, string> | null;
|
||||
expiresAt?: Date | null;
|
||||
} | null>;
|
||||
create(args: {
|
||||
data: {
|
||||
scope: string;
|
||||
key: string;
|
||||
requestHash: string;
|
||||
responseStatus: number;
|
||||
responseBody?: JsonValue | null;
|
||||
responseHeaders?: Record<string, string> | null;
|
||||
expiresAt?: Date | null;
|
||||
};
|
||||
}): Promise<unknown>;
|
||||
update(args: {
|
||||
where: { idempotency_key_scope_key: { scope: string; key: string } };
|
||||
data: {
|
||||
responseStatus: number;
|
||||
responseBody?: JsonValue | null;
|
||||
responseHeaders?: Record<string, string> | null;
|
||||
expiresAt?: Date | null;
|
||||
};
|
||||
}): Promise<unknown>;
|
||||
deleteMany?(args?: { where?: { scope?: string; key?: string; expiresAt?: { lte?: Date } } }): Promise<unknown>;
|
||||
};
|
||||
};
|
||||
|
||||
const idempotencyLockTails = new Map<string, Promise<void>>();
|
||||
|
||||
export async function withIdempotency(
|
||||
input: { scope?: string; key?: string | null; fingerprint: JsonValue; expiresAt?: Date | null },
|
||||
client: IdempotencyClient,
|
||||
operation: () => Promise<IdempotencyResponse>,
|
||||
): Promise<IdempotencyResponse & { replayed: boolean }> {
|
||||
const key = input.key?.trim();
|
||||
if (!key) return { ...(await operation()), replayed: false };
|
||||
|
||||
const scope = input.scope ?? "default";
|
||||
return runWithIdempotencyLock(`${scope}:${key}`, async () => runIdempotencyOperation({ ...input, scope, key }, client, operation));
|
||||
}
|
||||
|
||||
async function runIdempotencyOperation(
|
||||
input: { scope: string; key: string; fingerprint: JsonValue; expiresAt?: Date | null },
|
||||
client: IdempotencyClient,
|
||||
operation: () => Promise<IdempotencyResponse>,
|
||||
): Promise<IdempotencyResponse & { replayed: boolean }> {
|
||||
const { scope, key } = input;
|
||||
const requestHash = stableStringify(input.fingerprint);
|
||||
const existing = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope, key } } });
|
||||
|
||||
if (existing) {
|
||||
return replayExistingIdempotencyResponse(existing, requestHash);
|
||||
}
|
||||
|
||||
try {
|
||||
await client.idempotencyKey.create({
|
||||
data: {
|
||||
scope,
|
||||
key,
|
||||
requestHash,
|
||||
responseStatus: 0,
|
||||
responseBody: null,
|
||||
responseHeaders: null,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (!isUniqueConstraintError(error)) {
|
||||
throw error;
|
||||
}
|
||||
const reserved = await client.idempotencyKey.findUnique({ where: { idempotency_key_scope_key: { scope, key } } });
|
||||
if (reserved) {
|
||||
return replayExistingIdempotencyResponse(reserved, requestHash);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await operation();
|
||||
await client.idempotencyKey.update({
|
||||
where: { idempotency_key_scope_key: { scope, key } },
|
||||
data: {
|
||||
responseStatus: response.status,
|
||||
responseBody: response.body ?? null,
|
||||
responseHeaders: response.headers ?? null,
|
||||
expiresAt: input.expiresAt ?? null,
|
||||
},
|
||||
});
|
||||
return { ...response, replayed: false };
|
||||
} catch (error) {
|
||||
await client.idempotencyKey.deleteMany?.({ where: { scope, key } });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function replayExistingIdempotencyResponse(
|
||||
existing: {
|
||||
requestHash: string;
|
||||
responseStatus: number;
|
||||
responseBody: JsonValue | null;
|
||||
responseHeaders: Record<string, string> | null;
|
||||
},
|
||||
requestHash: string,
|
||||
): IdempotencyResponse & { replayed: true } {
|
||||
if (existing.requestHash !== requestHash) {
|
||||
throw new CatalogError(foundationErrors.idempotencyConflict);
|
||||
}
|
||||
if (existing.responseStatus <= 0) {
|
||||
throw new CatalogError(foundationErrors.idempotencyInProgress);
|
||||
}
|
||||
return {
|
||||
status: existing.responseStatus,
|
||||
body: existing.responseBody ?? undefined,
|
||||
headers: existing.responseHeaders ?? undefined,
|
||||
replayed: true,
|
||||
};
|
||||
}
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return Boolean(
|
||||
error &&
|
||||
typeof error === "object" &&
|
||||
("code" in error ? (error as { code?: unknown }).code === "P2002" : false),
|
||||
);
|
||||
}
|
||||
|
||||
async function runWithIdempotencyLock<T>(lockKey: string, task: () => Promise<T>): Promise<T> {
|
||||
const previousTail = idempotencyLockTails.get(lockKey) ?? Promise.resolve();
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const nextTail = previousTail.catch(() => undefined).then(() => gate);
|
||||
|
||||
idempotencyLockTails.set(lockKey, nextTail);
|
||||
await previousTail.catch(() => undefined);
|
||||
|
||||
try {
|
||||
return await task();
|
||||
} finally {
|
||||
release();
|
||||
if (idempotencyLockTails.get(lockKey) === nextTail) {
|
||||
idempotencyLockTails.delete(lockKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function stableStringify(value: JsonValue): string {
|
||||
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
|
||||
if (value && typeof value === "object") {
|
||||
return `{${Object.entries(value)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
CatalogError,
|
||||
auditEvent,
|
||||
defineAdapter,
|
||||
defineFlag,
|
||||
featureFlag,
|
||||
getAdapter,
|
||||
notify,
|
||||
bundleNotifications,
|
||||
isNotificationEnabled,
|
||||
notifyMany,
|
||||
requirePermission,
|
||||
withAuditMiddleware,
|
||||
withIdempotency,
|
||||
withOwnerCheck,
|
||||
withTenantScope,
|
||||
type NotificationInput,
|
||||
} from "./index.js";
|
||||
|
||||
describe("@toolctrl/foundation", () => {
|
||||
test("writes audit events through the provided DB boundary", async () => {
|
||||
const client = { auditEvent: { create: vi.fn(async (args) => args.data) } };
|
||||
await auditEvent({ action: "thing.changed", tenantId: "tenant_1" }, client);
|
||||
expect(client.auditEvent.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ action: "thing.changed", actorType: "system", tenantId: "tenant_1" }),
|
||||
});
|
||||
});
|
||||
|
||||
test("adds audit middleware after successful handler execution", async () => {
|
||||
const client = { auditEvent: { create: vi.fn(async (args) => args.data) } };
|
||||
const handler = withAuditMiddleware(async () => ({ id: "result_1" }), (result) => ({ action: "created", targetId: result.id }), client);
|
||||
await expect(handler()).resolves.toEqual({ id: "result_1" });
|
||||
expect(client.auditEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ action: "created", targetId: "result_1" }) });
|
||||
});
|
||||
|
||||
test("returns 404-style catalog errors for missing permissions and owner checks", () => {
|
||||
expect(() => requirePermission({ permissions: [] }, "resource.view")).toThrow(CatalogError);
|
||||
expect(() => withOwnerCheck({ userId: "user_1" }, { ownerId: "user_2" })).toThrow(/foundation.not_found/);
|
||||
});
|
||||
|
||||
test("applies tenant scopes without mutating the input", () => {
|
||||
const value = { id: "row_1" };
|
||||
expect(withTenantScope("tenant_1", value)).toEqual({ id: "row_1", tenantId: "tenant_1" });
|
||||
expect(value).toEqual({ id: "row_1" });
|
||||
});
|
||||
|
||||
test("resolves feature flags by override, user, tenant, global, and default precedence", () => {
|
||||
const flag = defineFlag({ key: "empty.flag", defaultEnabled: false });
|
||||
const records = [
|
||||
{ scope: "global", enabled: false },
|
||||
{ tenantId: "tenant_1", enabled: true },
|
||||
{ userId: "user_1", enabled: false, key: "empty.flag" },
|
||||
];
|
||||
expect(featureFlag({ ...flag, override: true, records, tenantId: "tenant_1", userId: "user_1" })).toBe(true);
|
||||
expect(featureFlag({ ...flag, records, tenantId: "tenant_1", userId: "user_1" })).toBe(false);
|
||||
expect(featureFlag({ ...flag, records, tenantId: "tenant_1" })).toBe(true);
|
||||
expect(featureFlag({ ...flag, records })).toBe(false);
|
||||
expect(featureFlag({ key: "new.flag", defaultEnabled: true })).toBe(true);
|
||||
});
|
||||
|
||||
test("does not apply tenant-scoped user flag overrides across tenants", () => {
|
||||
const flag = defineFlag({ key: "tenant.flag", defaultEnabled: false });
|
||||
const records = [
|
||||
{ tenantId: "tenant_1", userId: "user_1", enabled: false, key: "tenant.flag" },
|
||||
{ tenantId: "tenant_2", enabled: true, key: "tenant.flag" },
|
||||
];
|
||||
|
||||
expect(featureFlag({ ...flag, records, tenantId: "tenant_2", userId: "user_1" })).toBe(true);
|
||||
expect(featureFlag({ ...flag, records, tenantId: "tenant_1", userId: "user_1" })).toBe(false);
|
||||
});
|
||||
|
||||
test("does not treat scoped feature flag records as global fallbacks", () => {
|
||||
const flag = defineFlag({ key: "scoped.flag", defaultEnabled: false });
|
||||
const records = [
|
||||
{ scope: "tenant", tenantId: "tenant_1", enabled: true, key: "scoped.flag" },
|
||||
{ scope: "user", userId: "user_1", enabled: true, key: "scoped.flag" },
|
||||
];
|
||||
|
||||
expect(featureFlag({ ...flag, records, tenantId: "tenant_2", userId: "user_2" })).toBe(false);
|
||||
expect(featureFlag({ ...flag, records, tenantId: "tenant_1", userId: "user_2" })).toBe(true);
|
||||
expect(featureFlag({ ...flag, records, tenantId: "tenant_2", userId: "user_1" })).toBe(true);
|
||||
});
|
||||
|
||||
test("replays idempotent responses and rejects changed fingerprints", async () => {
|
||||
const rows = new Map<string, { requestHash: string; responseStatus: number; responseBody: { ok: boolean } | null; responseHeaders: null }>();
|
||||
const client = {
|
||||
idempotencyKey: {
|
||||
findUnique: vi.fn(async ({ where }) => rows.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`) ?? null),
|
||||
create: vi.fn(async ({ data }) => {
|
||||
const key = `${data.scope}:${data.key}`;
|
||||
if (rows.has(key)) throw Object.assign(new Error("unique"), { code: "P2002" });
|
||||
rows.set(key, {
|
||||
requestHash: data.requestHash,
|
||||
responseStatus: data.responseStatus,
|
||||
responseBody: data.responseBody as { ok: boolean },
|
||||
responseHeaders: null,
|
||||
});
|
||||
}),
|
||||
update: vi.fn(async ({ where, data }) => {
|
||||
const key = `${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`;
|
||||
const existing = rows.get(key);
|
||||
if (!existing) throw new Error("missing reservation");
|
||||
rows.set(key, {
|
||||
...existing,
|
||||
responseStatus: data.responseStatus,
|
||||
responseBody: data.responseBody as { ok: boolean },
|
||||
responseHeaders: null,
|
||||
});
|
||||
}),
|
||||
deleteMany: vi.fn(async ({ where }) => {
|
||||
rows.delete(`${where.scope}:${where.key}`);
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const first = await withIdempotency({ key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 201, body: { ok: true } }));
|
||||
const replay = await withIdempotency({ key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 500 }));
|
||||
expect(first.replayed).toBe(false);
|
||||
expect(replay).toMatchObject({ replayed: true, status: 201, body: { ok: true } });
|
||||
await expect(withIdempotency({ key: "key_1", fingerprint: { body: "b" } }, client, async () => ({ status: 200 }))).rejects.toThrow(CatalogError);
|
||||
});
|
||||
|
||||
test("serializes concurrent idempotent operations for the same scope and key", async () => {
|
||||
const rows = new Map<string, { requestHash: string; responseStatus: number; responseBody: { ok: boolean } | null; responseHeaders: null }>();
|
||||
let releaseOperation!: () => void;
|
||||
const operationGate = new Promise<void>((resolve) => {
|
||||
releaseOperation = resolve;
|
||||
});
|
||||
const operation = vi.fn(async () => {
|
||||
await operationGate;
|
||||
return { status: 201, body: { ok: true } };
|
||||
});
|
||||
const client = {
|
||||
idempotencyKey: {
|
||||
findUnique: vi.fn(async ({ where }) => rows.get(`${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`) ?? null),
|
||||
create: vi.fn(async ({ data }) => {
|
||||
const key = `${data.scope}:${data.key}`;
|
||||
if (rows.has(key)) throw Object.assign(new Error("unique"), { code: "P2002" });
|
||||
rows.set(key, {
|
||||
requestHash: data.requestHash,
|
||||
responseStatus: data.responseStatus,
|
||||
responseBody: data.responseBody as { ok: boolean },
|
||||
responseHeaders: null,
|
||||
});
|
||||
}),
|
||||
update: vi.fn(async ({ where, data }) => {
|
||||
const key = `${where.idempotency_key_scope_key.scope}:${where.idempotency_key_scope_key.key}`;
|
||||
const existing = rows.get(key);
|
||||
if (!existing) throw new Error("missing reservation");
|
||||
rows.set(key, {
|
||||
...existing,
|
||||
responseStatus: data.responseStatus,
|
||||
responseBody: data.responseBody as { ok: boolean },
|
||||
responseHeaders: null,
|
||||
});
|
||||
}),
|
||||
deleteMany: vi.fn(async ({ where }) => {
|
||||
rows.delete(`${where.scope}:${where.key}`);
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
const first = withIdempotency({ scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation);
|
||||
const second = withIdempotency({ scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation);
|
||||
releaseOperation();
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toEqual([
|
||||
{ status: 201, body: { ok: true }, replayed: false },
|
||||
{ status: 201, body: { ok: true }, replayed: true },
|
||||
]);
|
||||
expect(operation).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("tracks adapter five-state definitions and unknown adapters", () => {
|
||||
defineAdapter({ key: "empty.adapter", status: "healthy", adapter: { configured: true } });
|
||||
expect(getAdapter("empty.adapter").status).toBe("healthy");
|
||||
expect(getAdapter("missing.adapter").status).toBe("not_configured");
|
||||
});
|
||||
|
||||
test("creates generic notification delivery records", async () => {
|
||||
const client = {
|
||||
notificationDelivery: {
|
||||
create: vi.fn(async (args) => args.data),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
};
|
||||
await notify(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
category: " Ops ",
|
||||
messageKey: "foundation.notifications.empty",
|
||||
payloadMetadata: { requestId: "req_1", apiKey: "secret" },
|
||||
},
|
||||
client,
|
||||
);
|
||||
expect(client.notificationDelivery.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "ops",
|
||||
status: "SENT",
|
||||
attemptsMade: 1,
|
||||
sentAt: expect.any(Date),
|
||||
payloadMetadata: { requestId: "req_1", apiKey: "[redacted]" },
|
||||
}),
|
||||
});
|
||||
|
||||
await notify(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
category: "ops",
|
||||
messageKey: "foundation.notifications.disabled",
|
||||
},
|
||||
client,
|
||||
[{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", enabled: false }],
|
||||
);
|
||||
expect(client.notificationDelivery.create).toHaveBeenCalledTimes(2);
|
||||
expect(client.notificationDelivery.create).toHaveBeenLastCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "ops",
|
||||
status: "SKIPPED",
|
||||
lastError: "preference_disabled",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
test("upserts notification deliveries with source keys through the Foundation contract", async () => {
|
||||
const client = {
|
||||
notificationDelivery: {
|
||||
create: vi.fn(async (args) => args.data),
|
||||
upsert: vi.fn(async (args) => args.create),
|
||||
},
|
||||
};
|
||||
|
||||
await notify(
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "EMAIL",
|
||||
category: "billing",
|
||||
messageKey: "foundation.notifications.invoice",
|
||||
sourceKey: " invoice:invoice_1:user_1 ",
|
||||
},
|
||||
client,
|
||||
);
|
||||
|
||||
expect(client.notificationDelivery.upsert).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId_userId_channel_sourceKey: {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "EMAIL",
|
||||
sourceKey: "invoice:invoice_1:user_1",
|
||||
},
|
||||
},
|
||||
create: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "EMAIL",
|
||||
sourceKey: "invoice:invoice_1:user_1",
|
||||
status: "PENDING",
|
||||
attemptsMade: 0,
|
||||
}),
|
||||
update: expect.objectContaining({
|
||||
messageKey: "foundation.notifications.invoice",
|
||||
status: "PENDING",
|
||||
}),
|
||||
});
|
||||
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects notification delivery records without tenant scope", async () => {
|
||||
const client = {
|
||||
notificationDelivery: {
|
||||
create: vi.fn(async (args) => args.data),
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
notify(
|
||||
{
|
||||
tenantId: " ",
|
||||
userId: "user_1",
|
||||
messageKey: "foundation.notifications.empty",
|
||||
},
|
||||
client,
|
||||
),
|
||||
).rejects.toThrow("Notification delivery tenant scope is required.");
|
||||
expect(client.notificationDelivery.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("resolves notification preferences and records skipped batch diagnostics", async () => {
|
||||
const inputs: NotificationInput[] = [
|
||||
{ tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.one", payloadMetadata: { count: 1 } },
|
||||
{ tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.two", payloadMetadata: { source: "test", token: "secret-token" } },
|
||||
{ tenantId: "tenant_1", userId: "user_2", channel: "EMAIL" as const, category: "ops", messageKey: "foundation.notifications.three" },
|
||||
];
|
||||
const preferences = [{ tenantId: "tenant_1", userId: "user_2", channel: "EMAIL" as const, category: "ops", enabled: false }];
|
||||
const client = {
|
||||
notificationDelivery: {
|
||||
create: vi.fn(async (args) => args.data),
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
expect(isNotificationEnabled(inputs[2], preferences)).toBe(false);
|
||||
expect(bundleNotifications(inputs)).toEqual([
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "default",
|
||||
messageKeys: ["foundation.notifications.one", "foundation.notifications.two"],
|
||||
payloadMetadata: { count: 1, source: "test", token: "[redacted]" },
|
||||
},
|
||||
{
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_2",
|
||||
channel: "EMAIL",
|
||||
category: "ops",
|
||||
messageKeys: ["foundation.notifications.three"],
|
||||
payloadMetadata: {},
|
||||
},
|
||||
]);
|
||||
|
||||
await notifyMany(inputs, client, preferences);
|
||||
expect(client.notificationDelivery.create).toHaveBeenCalledTimes(3);
|
||||
expect(client.notificationDelivery.create).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_2",
|
||||
channel: "EMAIL",
|
||||
category: "ops",
|
||||
messageKey: "foundation.notifications.three",
|
||||
status: "SKIPPED",
|
||||
lastError: "preference_disabled",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("falls back to default notification preferences when category-specific preferences are absent", () => {
|
||||
const input: NotificationInput = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
channel: "IN_APP",
|
||||
category: "billing",
|
||||
messageKey: "foundation.notifications.billing",
|
||||
};
|
||||
|
||||
expect(
|
||||
isNotificationEnabled(input, [
|
||||
{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false },
|
||||
])
|
||||
).toBe(false);
|
||||
expect(
|
||||
isNotificationEnabled(input, [
|
||||
{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false },
|
||||
{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "billing", enabled: true },
|
||||
])
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
export * from "./errors.js";
|
||||
export * from "./audit.js";
|
||||
export * from "./permissions.js";
|
||||
export * from "./flags.js";
|
||||
export * from "./idempotency.js";
|
||||
export * from "./adapters.js";
|
||||
export * from "./notifications.js";
|
||||
export * from "./workflows.js";
|
||||
export * from "./concurrency.js";
|
||||
export * from "./mass-action.js";
|
||||
@@ -0,0 +1,89 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CatalogError } from "./errors.js";
|
||||
import { assertMassActionAllowed, evaluateMassAction, massActionErrors, previewMassAction } from "./mass-action.js";
|
||||
|
||||
const policy = { confirmThreshold: 50, hardLimit: 1000 };
|
||||
|
||||
describe("previewMassAction", () => {
|
||||
it("returns a bounded sample and the confirmation/limit flags", () => {
|
||||
const items = Array.from({ length: 20 }, (_, index) => index);
|
||||
const preview = previewMassAction({ affected: 1400, items, policy: { confirmThreshold: 50, hardLimit: 5000 } });
|
||||
expect(preview.affected).toBe(1400);
|
||||
expect(preview.sample).toEqual([0, 1, 2, 3, 4]);
|
||||
expect(preview.requiresConfirmation).toBe(true);
|
||||
expect(preview.exceedsHardLimit).toBe(false);
|
||||
});
|
||||
|
||||
it("honours a custom sample size and flags a hard-limit breach", () => {
|
||||
const preview = previewMassAction({ affected: 6000, items: [1, 2, 3], sampleSize: 2, policy: { confirmThreshold: 50, hardLimit: 5000 } });
|
||||
expect(preview.sample).toEqual([1, 2]);
|
||||
expect(preview.exceedsHardLimit).toBe(true);
|
||||
expect(preview.requiresConfirmation).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evaluateMassAction", () => {
|
||||
it("allows actions at or below the confirmation threshold", () => {
|
||||
expect(evaluateMassAction({ affected: 50, policy })).toEqual({ status: "allowed", affected: 50, confirmed: false });
|
||||
});
|
||||
|
||||
it("requires confirmation above the threshold", () => {
|
||||
expect(evaluateMassAction({ affected: 200, policy })).toEqual({ status: "requires_confirmation", affected: 200, confirmThreshold: 50 });
|
||||
});
|
||||
|
||||
it("allows once the user confirms the exact affected count", () => {
|
||||
expect(evaluateMassAction({ affected: 200, policy, confirmedAffected: 200 })).toEqual({ status: "allowed", affected: 200, confirmed: true });
|
||||
});
|
||||
|
||||
it("re-requires confirmation on scope drift (confirmed count differs)", () => {
|
||||
expect(evaluateMassAction({ affected: 250, policy, confirmedAffected: 200 })).toEqual({
|
||||
status: "requires_confirmation",
|
||||
affected: 250,
|
||||
confirmThreshold: 50,
|
||||
});
|
||||
});
|
||||
|
||||
it("blocks above the hard limit", () => {
|
||||
expect(evaluateMassAction({ affected: 1001, policy, confirmedAffected: 1001 })).toEqual({
|
||||
status: "blocked",
|
||||
reason: "exceeds_hard_limit",
|
||||
affected: 1001,
|
||||
hardLimit: 1000,
|
||||
});
|
||||
});
|
||||
|
||||
it("treats an absent hardLimit as no cap", () => {
|
||||
expect(evaluateMassAction({ affected: 1_000_000, policy: { confirmThreshold: 50 }, confirmedAffected: 1_000_000 })).toMatchObject({
|
||||
status: "allowed",
|
||||
confirmed: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertMassActionAllowed", () => {
|
||||
it("returns the decision when allowed", () => {
|
||||
expect(assertMassActionAllowed({ affected: 10, policy })).toMatchObject({ status: "allowed" });
|
||||
});
|
||||
|
||||
it("throws a 409 confirmation-required CatalogError above the threshold", () => {
|
||||
try {
|
||||
assertMassActionAllowed({ affected: 200, policy });
|
||||
throw new Error("expected throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CatalogError);
|
||||
expect((error as CatalogError).code).toBe(massActionErrors.confirmationRequired.code);
|
||||
expect((error as CatalogError).status).toBe(409);
|
||||
}
|
||||
});
|
||||
|
||||
it("throws a 422 exceeds-limit CatalogError above the hard limit", () => {
|
||||
try {
|
||||
assertMassActionAllowed({ affected: 5000, policy });
|
||||
throw new Error("expected throw");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(CatalogError);
|
||||
expect((error as CatalogError).code).toBe(massActionErrors.exceedsLimit.code);
|
||||
expect((error as CatalogError).status).toBe(422);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { CatalogError, type CatalogErrorDefinition, type JsonValue } from "./errors.js";
|
||||
|
||||
/**
|
||||
* Mass-action guard (M005 / Pflichtenheft A.10.1).
|
||||
*
|
||||
* A bulk action that touches many records is "never armed directly": the user
|
||||
* first sees a preview with the concrete impact ("würde 1.400 Personen betreffen,
|
||||
* hier die ersten 5: …") and must explicitly confirm. This module is the generic,
|
||||
* pure cross-cutting guard for that handshake; the caller computes the affected
|
||||
* count + sample (a query) and threads the decision into its action.
|
||||
*/
|
||||
|
||||
export type MassActionPolicy = {
|
||||
/** Above this affected count, explicit user confirmation is required (A.10.1). */
|
||||
confirmThreshold: number;
|
||||
/** Above this affected count the action is blocked entirely. Omit for no hard cap. */
|
||||
hardLimit?: number;
|
||||
};
|
||||
|
||||
export type MassActionPreview<T = unknown> = {
|
||||
readonly affected: number;
|
||||
readonly sample: readonly T[];
|
||||
readonly requiresConfirmation: boolean;
|
||||
readonly exceedsHardLimit: boolean;
|
||||
};
|
||||
|
||||
export type MassActionInput = {
|
||||
/** Number of records the action would affect right now. */
|
||||
affected: number;
|
||||
policy: MassActionPolicy;
|
||||
/**
|
||||
* The affected count the user saw and confirmed. Must equal the current
|
||||
* `affected` to proceed past the confirmation threshold — this rejects
|
||||
* scope-drift (confirming a small preview, then applying to a larger set).
|
||||
*/
|
||||
confirmedAffected?: number;
|
||||
};
|
||||
|
||||
export type MassActionDecision =
|
||||
| { readonly status: "allowed"; readonly affected: number; readonly confirmed: boolean }
|
||||
| { readonly status: "requires_confirmation"; readonly affected: number; readonly confirmThreshold: number }
|
||||
| { readonly status: "blocked"; readonly reason: "exceeds_hard_limit"; readonly affected: number; readonly hardLimit: number };
|
||||
|
||||
export const massActionErrors = {
|
||||
confirmationRequired: {
|
||||
code: "foundation.mass_action_confirmation_required",
|
||||
status: 409,
|
||||
i18nKey: "foundation.errors.massActionConfirmationRequired",
|
||||
},
|
||||
exceedsLimit: {
|
||||
code: "foundation.mass_action_exceeds_limit",
|
||||
status: 422,
|
||||
i18nKey: "foundation.errors.massActionExceedsLimit",
|
||||
},
|
||||
} satisfies Record<string, CatalogErrorDefinition>;
|
||||
|
||||
const DEFAULT_SAMPLE_SIZE = 5;
|
||||
|
||||
/**
|
||||
* Build the preview shown to the user before a mass action: the affected count,
|
||||
* a bounded sample of the affected items, and whether confirmation / a hard cap
|
||||
* applies. The caller supplies the already-fetched `items`.
|
||||
*/
|
||||
export function previewMassAction<T>(input: {
|
||||
affected: number;
|
||||
items?: readonly T[];
|
||||
sampleSize?: number;
|
||||
policy: MassActionPolicy;
|
||||
}): MassActionPreview<T> {
|
||||
const sampleSize = input.sampleSize ?? DEFAULT_SAMPLE_SIZE;
|
||||
const sample = (input.items ?? []).slice(0, Math.max(0, sampleSize));
|
||||
const exceedsHardLimit = typeof input.policy.hardLimit === "number" && input.affected > input.policy.hardLimit;
|
||||
const requiresConfirmation = !exceedsHardLimit && input.affected > input.policy.confirmThreshold;
|
||||
return { affected: input.affected, sample, requiresConfirmation, exceedsHardLimit };
|
||||
}
|
||||
|
||||
/** Pure policy decision for a mass action. */
|
||||
export function evaluateMassAction(input: MassActionInput): MassActionDecision {
|
||||
const { affected, policy, confirmedAffected } = input;
|
||||
if (typeof policy.hardLimit === "number" && affected > policy.hardLimit) {
|
||||
return { status: "blocked", reason: "exceeds_hard_limit", affected, hardLimit: policy.hardLimit };
|
||||
}
|
||||
if (affected <= policy.confirmThreshold) {
|
||||
return { status: "allowed", affected, confirmed: false };
|
||||
}
|
||||
if (confirmedAffected === affected) {
|
||||
return { status: "allowed", affected, confirmed: true };
|
||||
}
|
||||
return { status: "requires_confirmation", affected, confirmThreshold: policy.confirmThreshold };
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert a mass action may proceed, throwing a `CatalogError` otherwise:
|
||||
* `exceedsLimit` (422) when over the hard cap, `confirmationRequired` (409) when
|
||||
* the user has not confirmed the current affected count. Returns the decision on
|
||||
* success.
|
||||
*/
|
||||
export function assertMassActionAllowed(input: MassActionInput, details?: Record<string, JsonValue>): MassActionDecision {
|
||||
const decision = evaluateMassAction(input);
|
||||
if (decision.status === "blocked") {
|
||||
throw new CatalogError(massActionErrors.exceedsLimit, { affected: decision.affected, hardLimit: decision.hardLimit, ...details });
|
||||
}
|
||||
if (decision.status === "requires_confirmation") {
|
||||
throw new CatalogError(massActionErrors.confirmationRequired, {
|
||||
affected: decision.affected,
|
||||
confirmThreshold: decision.confirmThreshold,
|
||||
...details,
|
||||
});
|
||||
}
|
||||
return decision;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import type { JsonValue } from "./errors.js";
|
||||
|
||||
export type NotificationInput = {
|
||||
tenantId: string;
|
||||
userId?: string | null;
|
||||
channel?: NotificationPreferenceChannel;
|
||||
category?: string | null;
|
||||
messageKey: string;
|
||||
sourceKey?: string | null;
|
||||
payloadMetadata?: Record<string, JsonValue> | null;
|
||||
};
|
||||
|
||||
export type NotificationPreferenceChannel = "IN_APP" | "EMAIL";
|
||||
export type NotificationDeliveryStatus = "PENDING" | "SENT" | "FAILED" | "SKIPPED" | "READ";
|
||||
export type NotificationPayloadMetadata = Record<string, string | number | boolean | null>;
|
||||
|
||||
export type NotificationPreference = {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
channel: NotificationPreferenceChannel;
|
||||
category: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
export type NotificationBundle = {
|
||||
tenantId: string;
|
||||
userId: string | null;
|
||||
channel: NotificationPreferenceChannel;
|
||||
category: string;
|
||||
messageKeys: readonly string[];
|
||||
payloadMetadata: Record<string, JsonValue>;
|
||||
};
|
||||
|
||||
export type NotificationClient = {
|
||||
notificationDelivery: {
|
||||
create(args: {
|
||||
data: {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
channel: NotificationPreferenceChannel;
|
||||
category: string;
|
||||
messageKey: string;
|
||||
sourceKey: string | null;
|
||||
status: NotificationDeliveryStatus;
|
||||
attemptsMade: number;
|
||||
providerMessageId: string | null;
|
||||
lastError: string | null;
|
||||
payloadMetadata: NotificationPayloadMetadata | null;
|
||||
sentAt: Date | null;
|
||||
readAt: Date | null;
|
||||
};
|
||||
}): Promise<unknown>;
|
||||
upsert?(args: {
|
||||
where: {
|
||||
tenantId_userId_channel_sourceKey: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
channel: NotificationPreferenceChannel;
|
||||
sourceKey: string;
|
||||
};
|
||||
};
|
||||
create: {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
channel: NotificationPreferenceChannel;
|
||||
category: string;
|
||||
messageKey: string;
|
||||
sourceKey: string | null;
|
||||
status: NotificationDeliveryStatus;
|
||||
attemptsMade: number;
|
||||
providerMessageId: string | null;
|
||||
lastError: string | null;
|
||||
payloadMetadata: NotificationPayloadMetadata | null;
|
||||
sentAt: Date | null;
|
||||
readAt: Date | null;
|
||||
};
|
||||
update: {
|
||||
category: string;
|
||||
messageKey: string;
|
||||
status: NotificationDeliveryStatus;
|
||||
attemptsMade: number;
|
||||
providerMessageId: string | null;
|
||||
lastError: string | null;
|
||||
payloadMetadata: NotificationPayloadMetadata | null;
|
||||
sentAt: Date | null;
|
||||
readAt: Date | null;
|
||||
};
|
||||
}): Promise<unknown>;
|
||||
};
|
||||
};
|
||||
|
||||
export async function notify(input: NotificationInput, client: NotificationClient, preferences: readonly NotificationPreference[] = []): Promise<unknown> {
|
||||
const tenantId = requireNotificationTenantScope(input.tenantId);
|
||||
const enabled = isNotificationEnabled(input, preferences);
|
||||
const channel = input.channel ?? "IN_APP";
|
||||
const userId = input.userId ?? null;
|
||||
const sourceKey = normalizeNotificationSourceKey(input.sourceKey);
|
||||
const data = {
|
||||
tenantId,
|
||||
userId,
|
||||
channel,
|
||||
category: normalizeNotificationCategory(input.category),
|
||||
messageKey: input.messageKey,
|
||||
sourceKey,
|
||||
status: enabled ? channel === "IN_APP" ? "SENT" as const : "PENDING" as const : "SKIPPED" as const,
|
||||
attemptsMade: enabled && channel === "IN_APP" ? 1 : 0,
|
||||
providerMessageId: null,
|
||||
lastError: enabled ? null : "preference_disabled",
|
||||
payloadMetadata: sanitizeNotificationPayloadMetadata(input.payloadMetadata),
|
||||
sentAt: enabled && channel === "IN_APP" ? new Date() : null,
|
||||
readAt: null,
|
||||
};
|
||||
|
||||
if (sourceKey && userId && client.notificationDelivery.upsert) {
|
||||
return client.notificationDelivery.upsert({
|
||||
where: {
|
||||
tenantId_userId_channel_sourceKey: {
|
||||
tenantId,
|
||||
userId,
|
||||
channel,
|
||||
sourceKey,
|
||||
},
|
||||
},
|
||||
create: data,
|
||||
update: {
|
||||
category: data.category,
|
||||
messageKey: data.messageKey,
|
||||
status: data.status,
|
||||
attemptsMade: data.attemptsMade,
|
||||
providerMessageId: data.providerMessageId,
|
||||
lastError: data.lastError,
|
||||
payloadMetadata: data.payloadMetadata,
|
||||
sentAt: data.sentAt,
|
||||
readAt: data.readAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return client.notificationDelivery.create({ data });
|
||||
}
|
||||
|
||||
export function isNotificationEnabled(input: NotificationInput, preferences: readonly NotificationPreference[]): boolean {
|
||||
const tenantId = requireNotificationTenantScope(input.tenantId);
|
||||
const userId = input.userId ?? null;
|
||||
const channel = input.channel ?? "IN_APP";
|
||||
const category = normalizeNotificationCategory(input.category);
|
||||
|
||||
const scopedPreferences = preferences.filter(
|
||||
(candidate) =>
|
||||
candidate.tenantId === tenantId &&
|
||||
candidate.userId === userId &&
|
||||
candidate.channel === channel,
|
||||
);
|
||||
const preference = scopedPreferences.find((candidate) => candidate.category === category) ?? scopedPreferences.find((candidate) => candidate.category === "default");
|
||||
|
||||
return preference?.enabled ?? true;
|
||||
}
|
||||
|
||||
export function bundleNotifications(inputs: readonly NotificationInput[]): readonly NotificationBundle[] {
|
||||
const bundles = new Map<string, NotificationBundle & { messageKeys: string[]; payloadMetadata: Record<string, JsonValue> }>();
|
||||
|
||||
for (const input of inputs) {
|
||||
const tenantId = requireNotificationTenantScope(input.tenantId);
|
||||
const userId = input.userId ?? null;
|
||||
const channel = input.channel ?? "IN_APP";
|
||||
const category = normalizeNotificationCategory(input.category);
|
||||
const key = [tenantId ?? "", userId ?? "", channel, category].join(":");
|
||||
const existing =
|
||||
bundles.get(key) ??
|
||||
{
|
||||
tenantId,
|
||||
userId,
|
||||
channel,
|
||||
category,
|
||||
messageKeys: [],
|
||||
payloadMetadata: {},
|
||||
};
|
||||
|
||||
existing.messageKeys.push(input.messageKey);
|
||||
if (input.payloadMetadata) {
|
||||
Object.assign(existing.payloadMetadata, sanitizeNotificationPayloadMetadata(input.payloadMetadata) ?? {});
|
||||
}
|
||||
bundles.set(key, existing);
|
||||
}
|
||||
|
||||
return [...bundles.values()].map((bundle) => ({
|
||||
...bundle,
|
||||
messageKeys: [...new Set(bundle.messageKeys)],
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizeNotificationCategory(category: string | null | undefined) {
|
||||
return category?.trim().toLowerCase() || "default";
|
||||
}
|
||||
|
||||
function normalizeNotificationSourceKey(sourceKey: string | null | undefined): string | null {
|
||||
const normalized = sourceKey?.trim();
|
||||
return normalized ? normalized : null;
|
||||
}
|
||||
|
||||
function requireNotificationTenantScope(tenantId: string | null | undefined): string {
|
||||
const normalized = tenantId?.trim();
|
||||
|
||||
if (!normalized) {
|
||||
throw new Error("Notification delivery tenant scope is required.");
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
const SENSITIVE_NOTIFICATION_METADATA_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|body|header/i;
|
||||
const NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH = 500;
|
||||
|
||||
function sanitizeNotificationPayloadMetadata(payloadMetadata?: Record<string, JsonValue> | null): NotificationPayloadMetadata | null {
|
||||
if (!payloadMetadata) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sanitized: NotificationPayloadMetadata = {};
|
||||
for (const [rawKey, value] of Object.entries(payloadMetadata)) {
|
||||
const key = rawKey.trim();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (SENSITIVE_NOTIFICATION_METADATA_KEY_PATTERN.test(key)) {
|
||||
sanitized[key] = "[redacted]";
|
||||
} else if (typeof value === "string") {
|
||||
sanitized[key] = value.slice(0, NOTIFICATION_PAYLOAD_METADATA_STRING_MAX_LENGTH);
|
||||
} else if (typeof value === "number" && Number.isFinite(value)) {
|
||||
sanitized[key] = value;
|
||||
} else if (typeof value === "boolean" || value === null) {
|
||||
sanitized[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return Object.keys(sanitized).length > 0 ? sanitized : null;
|
||||
}
|
||||
|
||||
export async function notifyMany(
|
||||
inputs: readonly NotificationInput[],
|
||||
client: NotificationClient,
|
||||
preferences: readonly NotificationPreference[] = [],
|
||||
): Promise<unknown[]> {
|
||||
return Promise.all(inputs.map((input) => notify(input, client, preferences)));
|
||||
}
|
||||
|
||||
export function assertI18nKey(key: string): string {
|
||||
if (!/^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$/.test(key)) {
|
||||
throw new Error(`Invalid i18n key: ${key}`);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { fetchOutboundHttpWithRedirects, readLimitedResponseText, validateOutboundHttpUrl } from "./outbound-http.js";
|
||||
|
||||
describe("outbound HTTP guard", () => {
|
||||
const publicResolver = vi.fn(async () => ["93.184.216.34"]);
|
||||
|
||||
test("blocks private and internal targets", () => {
|
||||
expect(() => validateOutboundHttpUrl("http://127.0.0.1/metadata")).toThrow("Outbound HTTP endpoint host is not allowed.");
|
||||
expect(() => validateOutboundHttpUrl("https://service.internal/hook")).toThrow("Outbound HTTP endpoint host is not allowed.");
|
||||
expect(validateOutboundHttpUrl("https://hooks.example.com/workflow")).toBe("https://hooks.example.com/workflow");
|
||||
});
|
||||
|
||||
test("follows public redirects manually and rejects private redirect targets", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "https://hooks.example.com/ok" } }))
|
||||
.mockResolvedValueOnce(new Response("done", { status: 200 }));
|
||||
|
||||
await expect(fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "POST", body: "payload" }, { fetchImpl, addressResolver: publicResolver })).resolves.toMatchObject({ status: 200 });
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(1, "https://api.example.com/start", expect.objectContaining({ method: "POST", redirect: "manual", signal: expect.any(AbortSignal) }));
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(2, "https://hooks.example.com/ok", expect.objectContaining({ method: "GET", body: undefined, redirect: "manual", signal: expect.any(AbortSignal) }));
|
||||
|
||||
const privateRedirectFetch = vi.fn(async () => new Response(null, { status: 302, headers: { location: "http://10.0.0.1/metadata" } }));
|
||||
await expect(fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl: privateRedirectFetch, addressResolver: publicResolver })).rejects.toThrow(
|
||||
"Outbound HTTP endpoint host is not allowed."
|
||||
);
|
||||
expect(privateRedirectFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("rejects public hostnames that resolve to private addresses before fetch", async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response("should not happen", { status: 200 }));
|
||||
const addressResolver = vi.fn(async () => ["169.254.169.254"]);
|
||||
|
||||
await expect(fetchOutboundHttpWithRedirects("https://public.example.test/metadata", { method: "GET" }, { fetchImpl, addressResolver })).rejects.toThrow(
|
||||
"Outbound HTTP endpoint resolved to a blocked address."
|
||||
);
|
||||
|
||||
expect(addressResolver).toHaveBeenCalledWith("public.example.test");
|
||||
expect(fetchImpl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("rejects redirect hostnames that resolve to private addresses before following them", async () => {
|
||||
const fetchImpl = vi.fn(async () => new Response(null, { status: 302, headers: { location: "https://metadata.example.test/latest" } }));
|
||||
const addressResolver = vi.fn(async (hostname: string) => (hostname === "metadata.example.test" ? ["10.0.0.10"] : ["93.184.216.34"]));
|
||||
|
||||
await expect(fetchOutboundHttpWithRedirects("https://api.example.com/start", { method: "GET" }, { fetchImpl, addressResolver })).rejects.toThrow(
|
||||
"Outbound HTTP endpoint resolved to a blocked address."
|
||||
);
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
expect(addressResolver).toHaveBeenCalledWith("api.example.com");
|
||||
expect(addressResolver).toHaveBeenCalledWith("metadata.example.test");
|
||||
});
|
||||
|
||||
test("limits response body reads without buffering the full stream", async () => {
|
||||
const response = new Response("abcdef");
|
||||
await expect(readLimitedResponseText(response, 3)).resolves.toEqual({ body: "abc", truncated: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
const DEFAULT_OUTBOUND_HTTP_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_OUTBOUND_HTTP_REDIRECT_LIMIT = 5;
|
||||
const DEFAULT_OUTBOUND_HTTP_RESPONSE_LIMIT_BYTES = 16_384;
|
||||
const INTERNAL_OUTBOUND_HOST_SUFFIXES = [".localhost", ".local", ".internal", ".lan", ".home", ".corp", ".intranet", ".svc"] as const;
|
||||
|
||||
export class OutboundHttpUrlValidationError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "OutboundHttpUrlValidationError";
|
||||
}
|
||||
}
|
||||
|
||||
export type OutboundHttpFetchOptions = {
|
||||
fetchImpl?: typeof fetch;
|
||||
addressResolver?: OutboundHttpAddressResolver;
|
||||
timeoutMs?: number;
|
||||
redirectLimit?: number;
|
||||
};
|
||||
|
||||
export type LimitedResponseBody = {
|
||||
body: string;
|
||||
truncated: boolean;
|
||||
};
|
||||
|
||||
export type OutboundHttpAddressResolver = (hostname: string) => Promise<ReadonlyArray<string>>;
|
||||
|
||||
export async function fetchOutboundHttpWithRedirects(input: string, init: RequestInit, options: OutboundHttpFetchOptions = {}): Promise<Response> {
|
||||
const fetchImpl = options.fetchImpl ?? fetch;
|
||||
const addressResolver = options.addressResolver ?? resolveOutboundHttpAddresses;
|
||||
const redirectLimit = options.redirectLimit ?? DEFAULT_OUTBOUND_HTTP_REDIRECT_LIMIT;
|
||||
let currentUrl = validateOutboundHttpUrl(input);
|
||||
let currentInit = init;
|
||||
|
||||
for (let redirects = 0; redirects <= redirectLimit; redirects += 1) {
|
||||
await assertOutboundHttpResolvedAddresses(currentUrl, addressResolver);
|
||||
const response = await fetchOutboundHttpWithTimeout(fetchImpl, currentUrl, currentInit, options.timeoutMs ?? DEFAULT_OUTBOUND_HTTP_TIMEOUT_MS);
|
||||
if (!isRedirectResponse(response.status)) {
|
||||
return response;
|
||||
}
|
||||
|
||||
const location = response.headers.get("location");
|
||||
if (!location) {
|
||||
return response;
|
||||
}
|
||||
|
||||
if (redirects === redirectLimit) {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP redirect limit exceeded.");
|
||||
}
|
||||
|
||||
currentUrl = resolveOutboundHttpRedirect(currentUrl, location);
|
||||
currentInit = buildRedirectRequestInit(currentInit, response.status);
|
||||
}
|
||||
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP redirect limit exceeded.");
|
||||
}
|
||||
|
||||
export async function readLimitedResponseText(response: Response, limitBytes = DEFAULT_OUTBOUND_HTTP_RESPONSE_LIMIT_BYTES): Promise<LimitedResponseBody> {
|
||||
if (!response.body) {
|
||||
return { body: "", truncated: false };
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
const chunks: string[] = [];
|
||||
let bytes = 0;
|
||||
let truncated = false;
|
||||
|
||||
while (bytes < limitBytes) {
|
||||
const result = await reader.read();
|
||||
if (result.done) {
|
||||
chunks.push(decoder.decode());
|
||||
return { body: chunks.join(""), truncated };
|
||||
}
|
||||
|
||||
const chunk = result.value;
|
||||
const remaining = limitBytes - bytes;
|
||||
const slice = chunk.byteLength > remaining ? chunk.slice(0, remaining) : chunk;
|
||||
chunks.push(decoder.decode(slice, { stream: chunk.byteLength <= remaining }));
|
||||
bytes += slice.byteLength;
|
||||
|
||||
if (chunk.byteLength > remaining) {
|
||||
truncated = true;
|
||||
await reader.cancel();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
chunks.push(decoder.decode());
|
||||
return { body: chunks.join(""), truncated: truncated || bytes >= limitBytes };
|
||||
}
|
||||
|
||||
export function validateOutboundHttpUrl(endpoint: string): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(endpoint);
|
||||
} catch {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP endpoint must be an absolute URL.");
|
||||
}
|
||||
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP endpoint must use http or https.");
|
||||
}
|
||||
|
||||
if (isBlockedOutboundHostname(url.hostname)) {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP endpoint host is not allowed.");
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
async function assertOutboundHttpResolvedAddresses(endpoint: string, addressResolver: OutboundHttpAddressResolver): Promise<void> {
|
||||
const url = new URL(endpoint);
|
||||
const hostname = url.hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
||||
if (parseIpv4Address(hostname) || parseIpv6Address(hostname)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let addresses: ReadonlyArray<string>;
|
||||
try {
|
||||
addresses = await addressResolver(hostname);
|
||||
} catch {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP endpoint host could not be resolved.");
|
||||
}
|
||||
|
||||
if (addresses.length === 0) {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP endpoint host could not be resolved.");
|
||||
}
|
||||
|
||||
if (addresses.some((address) => isBlockedOutboundHostname(address))) {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP endpoint resolved to a blocked address.");
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveOutboundHttpAddresses(hostname: string): Promise<ReadonlyArray<string>> {
|
||||
const dns = await import("node:dns/promises");
|
||||
const addresses = await dns.lookup(hostname, { all: true, verbatim: false });
|
||||
return addresses.map((address) => address.address);
|
||||
}
|
||||
|
||||
async function fetchOutboundHttpWithTimeout(fetchImpl: typeof fetch, input: Parameters<typeof fetch>[0], init: RequestInit, timeoutMs: number): Promise<Response> {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
return await fetchImpl(input, { ...init, redirect: "manual", signal: controller.signal });
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveOutboundHttpRedirect(currentUrl: string, location: string): string {
|
||||
let redirectUrl: URL;
|
||||
try {
|
||||
redirectUrl = new URL(location, currentUrl);
|
||||
} catch {
|
||||
throw new OutboundHttpUrlValidationError("Outbound HTTP redirect location must be a valid URL.");
|
||||
}
|
||||
return validateOutboundHttpUrl(redirectUrl.toString());
|
||||
}
|
||||
|
||||
function isRedirectResponse(status: number): boolean {
|
||||
return status >= 300 && status < 400;
|
||||
}
|
||||
|
||||
function buildRedirectRequestInit(init: RequestInit, status: number): RequestInit {
|
||||
const method = typeof init.method === "string" ? init.method.toUpperCase() : undefined;
|
||||
if (status === 303 || ((status === 301 || status === 302) && method === "POST")) {
|
||||
const headers = new Headers(init.headers);
|
||||
headers.delete("content-type");
|
||||
headers.delete("content-length");
|
||||
return { ...init, method: "GET", body: undefined, headers };
|
||||
}
|
||||
return init;
|
||||
}
|
||||
|
||||
function isBlockedOutboundHostname(hostname: string): boolean {
|
||||
const normalizedHostname = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
||||
if (!normalizedHostname) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ipv4 = parseIpv4Address(normalizedHostname);
|
||||
if (ipv4) {
|
||||
return isBlockedIpv4Address(ipv4);
|
||||
}
|
||||
|
||||
const ipv6 = parseIpv6Address(normalizedHostname);
|
||||
if (ipv6) {
|
||||
return isBlockedIpv6Address(ipv6);
|
||||
}
|
||||
|
||||
return (
|
||||
normalizedHostname === "localhost" ||
|
||||
!normalizedHostname.includes(".") ||
|
||||
INTERNAL_OUTBOUND_HOST_SUFFIXES.some((suffix) => normalizedHostname.endsWith(suffix))
|
||||
);
|
||||
}
|
||||
|
||||
function parseIpv4Address(hostname: string): [number, number, number, number] | undefined {
|
||||
const parts = hostname.split(".");
|
||||
if (parts.length !== 4) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const octets = parts.map((part) => Number(part));
|
||||
if (octets.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return octets as [number, number, number, number];
|
||||
}
|
||||
|
||||
function isBlockedIpv4Address([first, second]: [number, number, number, number]): boolean {
|
||||
return (
|
||||
first === 0 ||
|
||||
first === 10 ||
|
||||
first === 127 ||
|
||||
first >= 224 ||
|
||||
(first === 100 && second >= 64 && second <= 127) ||
|
||||
(first === 169 && second === 254) ||
|
||||
(first === 172 && second >= 16 && second <= 31) ||
|
||||
(first === 192 && second === 168) ||
|
||||
(first === 198 && (second === 18 || second === 19))
|
||||
);
|
||||
}
|
||||
|
||||
function parseIpv6Address(hostname: string): number[] | undefined {
|
||||
if (!hostname.includes(":")) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const [head = "", tail = "", extra] = hostname.split("::");
|
||||
if (extra !== undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const headParts = head ? head.split(":") : [];
|
||||
const tailParts = tail ? tail.split(":") : [];
|
||||
const missingPartCount = 8 - headParts.length - tailParts.length;
|
||||
if (missingPartCount < 0 || (!hostname.includes("::") && missingPartCount !== 0)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const parts = [...headParts, ...Array(missingPartCount).fill("0"), ...tailParts];
|
||||
if (parts.length !== 8) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const hextets = parts.map((part) => Number.parseInt(part, 16));
|
||||
if (hextets.some((part) => !Number.isInteger(part) || part < 0 || part > 0xffff)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return hextets;
|
||||
}
|
||||
|
||||
function isBlockedIpv6Address(hextets: number[]): boolean {
|
||||
const first = hextets[0] ?? 0;
|
||||
const isUnspecified = hextets.every((part) => part === 0);
|
||||
const isLoopback = hextets.slice(0, 7).every((part) => part === 0) && hextets[7] === 1;
|
||||
const isUniqueLocal = (first & 0xfe00) === 0xfc00;
|
||||
const isLinkLocal = (first & 0xffc0) === 0xfe80;
|
||||
const isIpv4Mapped = hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 0xffff;
|
||||
const isIpv4Compatible = hextets.slice(0, 6).every((part) => part === 0);
|
||||
|
||||
if (isUnspecified || isLoopback || isUniqueLocal || isLinkLocal) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isIpv4Mapped || isIpv4Compatible) {
|
||||
const ipv4: [number, number, number, number] = [hextets[6] >> 8, hextets[6] & 0xff, hextets[7] >> 8, hextets[7] & 0xff];
|
||||
return isBlockedIpv4Address(ipv4);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { CatalogError, foundationErrors } from "./errors.js";
|
||||
|
||||
export type PermissionContext = {
|
||||
tenantId?: string | null;
|
||||
userId?: string | null;
|
||||
ownerId?: string | null;
|
||||
permissions?: readonly string[] | ReadonlySet<string>;
|
||||
};
|
||||
|
||||
function permissionSet(permissions?: PermissionContext["permissions"]): ReadonlySet<string> {
|
||||
return permissions instanceof Set ? permissions : new Set(permissions ?? []);
|
||||
}
|
||||
|
||||
export function requirePermission(context: PermissionContext, permission: string): PermissionContext {
|
||||
if (!permissionSet(context.permissions).has(permission)) {
|
||||
throw new CatalogError(foundationErrors.notFound, { permission });
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
export function withTenantScope<T extends object>(tenantId: string, value: T): T & { tenantId: string } {
|
||||
return { ...value, tenantId };
|
||||
}
|
||||
|
||||
export function withPermission<TArgs extends readonly unknown[], TResult>(
|
||||
permission: string,
|
||||
getContext: (...args: TArgs) => PermissionContext,
|
||||
handler: (...args: TArgs) => TResult,
|
||||
): (...args: TArgs) => TResult {
|
||||
return (...args) => {
|
||||
requirePermission(getContext(...args), permission);
|
||||
return handler(...args);
|
||||
};
|
||||
}
|
||||
|
||||
export function withOwnerCheck<T extends { ownerId?: string | null }>(context: PermissionContext, value: T | null | undefined): T {
|
||||
if (!value || !context.userId || value.ownerId !== context.userId) {
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
CORE_WORKFLOW_BLOCK_TYPES,
|
||||
PRO_WORKFLOW_BLOCK_TYPES,
|
||||
NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES,
|
||||
extractWorkflowReferences,
|
||||
getMissingWorkflowReferences,
|
||||
getNativeWorkflowTriggerCapabilityErrors,
|
||||
getWorkflowBlockContract,
|
||||
preflightWorkflow,
|
||||
validateWorkflowRequiredInputs,
|
||||
workflowBlockContracts,
|
||||
type WorkflowNativeCapabilityBlock,
|
||||
type WorkflowPreflightBlock,
|
||||
} from "./workflows.js";
|
||||
|
||||
function block(overrides: Partial<WorkflowPreflightBlock>): WorkflowPreflightBlock {
|
||||
return {
|
||||
id: "block_1",
|
||||
type: "manual",
|
||||
input: {},
|
||||
conditionGroups: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function nativeBlock(overrides: Partial<WorkflowNativeCapabilityBlock>): WorkflowNativeCapabilityBlock {
|
||||
return {
|
||||
id: "block_1",
|
||||
type: "manual",
|
||||
input: {},
|
||||
conditionGroups: [],
|
||||
toBlocks: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workflow block contracts", () => {
|
||||
test("keeps block values unique", () => {
|
||||
const values = workflowBlockContracts.map((contract) => contract.value);
|
||||
|
||||
expect(new Set(values).size).toBe(values.length);
|
||||
});
|
||||
|
||||
test("splits blocks into stable core and pro executor groups", () => {
|
||||
expect(CORE_WORKFLOW_BLOCK_TYPES).toEqual(["manual", "event", "if", "switch", "httpRequest", "log", "alertUser", "doNothing", "iterator", "variable"]);
|
||||
expect(PRO_WORKFLOW_BLOCK_TYPES).toEqual(["waitForInput", "rowGet", "rowCreate", "rowUpdate", "rowDelete", "email"]);
|
||||
});
|
||||
|
||||
test("captures required runtime inputs for worker-safe validation", () => {
|
||||
expect(getWorkflowBlockContract("event").requiredInputs).toEqual(["event"]);
|
||||
expect(getWorkflowBlockContract("httpRequest").requiredInputs).toEqual(["url", "method"]);
|
||||
expect(getWorkflowBlockContract("rowUpdate").requiredInputs).toEqual(["entity", "id", "data"]);
|
||||
expect(getWorkflowBlockContract("email").requiredInputs).toEqual(["provider", "to", "subject", "body"]);
|
||||
});
|
||||
|
||||
test("keeps native trigger support explicit in the shared contract", () => {
|
||||
const nativeSupported = workflowBlockContracts.filter((contract) => contract.nativeSupport === "supported").map((contract) => contract.value);
|
||||
|
||||
expect(nativeSupported).toEqual([...NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES]);
|
||||
expect(workflowBlockContracts.find((contract) => contract.value === "if")?.nativeSupport).toBe("supported");
|
||||
expect(workflowBlockContracts.find((contract) => contract.value === "rowGet")?.nativeSupport).toBe("supported");
|
||||
expect(workflowBlockContracts.find((contract) => contract.value === "email")?.nativeSupport).toBe("supported");
|
||||
expect(workflowBlockContracts.find((contract) => contract.value === "iterator")?.nativeSupport).toBe("supported");
|
||||
});
|
||||
|
||||
test("keeps high-risk worker-native gaps fail-loud until a native port exists", () => {
|
||||
expect(workflowBlockContracts.filter((contract) => contract.nativeSupport === "preflight-skip").map((contract) => contract.value)).toEqual([
|
||||
"waitForInput",
|
||||
"rowCreate",
|
||||
"rowUpdate",
|
||||
"rowDelete",
|
||||
]);
|
||||
});
|
||||
|
||||
test("documents requested boilerplate block families without phantom block ids", () => {
|
||||
const blockIds = new Set<string>(workflowBlockContracts.map((contract) => contract.value));
|
||||
const matrix = [
|
||||
{ family: "mail", status: "first-class", ids: ["email"] },
|
||||
{ family: "webhook", status: "alias", ids: ["httpRequest"] },
|
||||
{ family: "notification", status: "unsupported", ids: [] },
|
||||
{ family: "audit", status: "unsupported", ids: [] },
|
||||
{ family: "condition", status: "first-class", ids: ["if", "switch"] },
|
||||
{ family: "delay/schedule", status: "unsupported", ids: [] },
|
||||
] as const;
|
||||
|
||||
for (const item of matrix) {
|
||||
expect(
|
||||
item.ids.every((id) => blockIds.has(id)),
|
||||
`${item.family} block family points at a missing registry id`
|
||||
).toBe(true);
|
||||
}
|
||||
expect(matrix.filter((item) => item.status === "unsupported").map((item) => item.family)).toEqual(["notification", "audit", "delay/schedule"]);
|
||||
expect(blockIds.has("webhook")).toBe(false);
|
||||
expect(blockIds.has("mail")).toBe(false);
|
||||
expect(blockIds.has("delay")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("workflow preflight primitives", () => {
|
||||
test("extracts variable and credential references from nested block inputs", () => {
|
||||
const references = extractWorkflowReferences({
|
||||
blocks: [
|
||||
block({
|
||||
id: "http",
|
||||
input: {
|
||||
url: "{{$vars.apiBaseUrl}}/users",
|
||||
headers: [{ key: "Authorization", value: "Bearer {{ $credentials.apiToken }}" }],
|
||||
body: { tenant: "{{$vars.tenantId}}" },
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(references.variables).toEqual(["apiBaseUrl", "tenantId"]);
|
||||
expect(references.credentials).toEqual(["apiToken"]);
|
||||
expect(references.byBlock[0]).toMatchObject({
|
||||
blockId: "http",
|
||||
variables: ["apiBaseUrl", "tenantId"],
|
||||
credentials: ["apiToken"],
|
||||
});
|
||||
});
|
||||
|
||||
test("extracts references from condition variables and values", () => {
|
||||
const references = extractWorkflowReferences({
|
||||
blocks: [
|
||||
block({
|
||||
id: "condition",
|
||||
type: "if",
|
||||
conditionGroups: [
|
||||
{
|
||||
conditions: [{ variable: "{{$vars.plan}}", value: "{{$vars.expectedPlan}}" }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(references.variables).toEqual(["expectedPlan", "plan"]);
|
||||
});
|
||||
|
||||
test("deduplicates references and ignores params session and block outputs", () => {
|
||||
const references = extractWorkflowReferences({
|
||||
blocks: [
|
||||
block({
|
||||
id: "message",
|
||||
input: {
|
||||
message: "{{ $vars.subject }} {{$vars.subject}} {{$params.email}} {{$session.user.email}} {{httpRequest.body}}",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(references.variables).toEqual(["subject"]);
|
||||
expect(references.credentials).toEqual([]);
|
||||
});
|
||||
|
||||
test("extracts references from supported Handlebars lookup and with expressions", () => {
|
||||
const references = extractWorkflowReferences({
|
||||
blocks: [
|
||||
block({
|
||||
id: "message",
|
||||
input: {
|
||||
message: "Bearer {{lookup $credentials \"apiToken\"}} for {{lookup $vars 'planTier'}}",
|
||||
audit: "{{#with $credentials}}{{webhookSecret}}{{/with}} {{#with $vars}}{{region}}{{/with}}",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
expect(references.variables).toEqual(["planTier", "region"]);
|
||||
expect(references.credentials).toEqual(["apiToken", "webhookSecret"]);
|
||||
expect(references.byBlock[0]).toMatchObject({
|
||||
blockId: "message",
|
||||
variables: ["planTier", "region"],
|
||||
credentials: ["apiToken", "webhookSecret"],
|
||||
});
|
||||
});
|
||||
|
||||
test("treats variable blocks as local variable definitions", () => {
|
||||
const references = extractWorkflowReferences({
|
||||
blocks: [
|
||||
block({ id: "define", type: "variable", input: { variableName: "temporaryToken", value: "abc" } }),
|
||||
block({ id: "use", input: { value: "{{$vars.temporaryToken}} {{$credentials.mailer}}" } }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(references.variables).toEqual([]);
|
||||
expect(references.credentials).toEqual(["mailer"]);
|
||||
});
|
||||
|
||||
test("reports missing references against available names", () => {
|
||||
expect(
|
||||
getMissingWorkflowReferences({
|
||||
workflow: { blocks: [block({ input: { value: "{{$vars.present}} {{$vars.missing}} {{$credentials.missingToken}}" } })] },
|
||||
variables: ["present"],
|
||||
credentials: [],
|
||||
})
|
||||
).toEqual({
|
||||
missingVariables: ["missing"],
|
||||
missingCredentials: ["missingToken"],
|
||||
});
|
||||
});
|
||||
|
||||
test("validates required block inputs with the worker-safe contract", () => {
|
||||
expect(
|
||||
validateWorkflowRequiredInputs({
|
||||
blocks: [
|
||||
block({ id: "manual", type: "manual", input: {} }),
|
||||
block({ id: "http", type: "httpRequest", input: { method: "POST" } }),
|
||||
block({ id: "mail", type: "email", input: { provider: "mailer", to: "user@example.com", subject: "Hi" } }),
|
||||
],
|
||||
})
|
||||
).toEqual([
|
||||
{ blockId: "http", blockType: "httpRequest", missingInputs: ["url"] },
|
||||
{ blockId: "mail", blockType: "email", missingInputs: ["body"] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("treats blank required string inputs as missing", () => {
|
||||
expect(
|
||||
validateWorkflowRequiredInputs({
|
||||
blocks: [
|
||||
block({ id: "http", type: "httpRequest", input: { method: "POST", url: " " } }),
|
||||
block({ id: "mail", type: "email", input: { provider: "mailer", to: "user@example.com", subject: "Hi", body: "\n" } }),
|
||||
],
|
||||
})
|
||||
).toEqual([
|
||||
{ blockId: "http", blockType: "httpRequest", missingInputs: ["url"] },
|
||||
{ blockId: "mail", blockType: "email", missingInputs: ["body"] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("combines reference and required-input preflight checks", () => {
|
||||
expect(
|
||||
preflightWorkflow({
|
||||
workflow: {
|
||||
blocks: [
|
||||
block({
|
||||
id: "email",
|
||||
type: "email",
|
||||
input: { provider: "mailer", to: "{{$vars.recipient}}", subject: "Hi" },
|
||||
}),
|
||||
],
|
||||
},
|
||||
variables: [],
|
||||
credentials: [],
|
||||
})
|
||||
).toEqual({
|
||||
missingVariables: ["recipient"],
|
||||
missingCredentials: [],
|
||||
missingRequiredInputs: [{ blockId: "email", blockType: "email", missingInputs: ["body"] }],
|
||||
});
|
||||
});
|
||||
|
||||
test("reports worker-native capability gaps", () => {
|
||||
expect(
|
||||
getNativeWorkflowTriggerCapabilityErrors([
|
||||
nativeBlock({ id: "trigger", type: "event", isTrigger: true, input: { event: "row.updated" } }),
|
||||
nativeBlock({ id: "http", type: "httpRequest", input: { url: "{{$credentials.apiBase}}/users", method: "GET" } }),
|
||||
nativeBlock({
|
||||
id: "if_1",
|
||||
type: "if",
|
||||
conditionGroups: [],
|
||||
toBlocks: [{ id: "edge_true", condition: "true" }],
|
||||
}),
|
||||
nativeBlock({
|
||||
id: "iterator_1",
|
||||
type: "iterator",
|
||||
input: { variableName: "{{$params.items}}" },
|
||||
toBlocks: [
|
||||
{ id: "edge_next", condition: "loopNext" },
|
||||
{ id: "edge_end", condition: "loopEnd" },
|
||||
],
|
||||
}),
|
||||
])
|
||||
).toEqual([
|
||||
'unsupported credential reference "apiBase" on block http',
|
||||
"if block if_1 must have exactly one condition group",
|
||||
"if block if_1 is missing false edge",
|
||||
]);
|
||||
});
|
||||
|
||||
test("keeps every worker-native supported block credential-free", () => {
|
||||
const supportedBlocks = NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES.filter((type) => type !== "manual" && type !== "event").map((type) =>
|
||||
nativeBlock({
|
||||
id: type,
|
||||
type,
|
||||
input: { message: "{{$credentials.apiToken}}", value: "{{lookup $credentials 'lookupToken'}}", body: "{{#with $credentials}}{{bodyToken}}{{/with}}" },
|
||||
conditionGroups:
|
||||
type === "if" || type === "switch"
|
||||
? [
|
||||
{
|
||||
index: 0,
|
||||
conditions: [{ variable: "{{$credentials.conditionToken}}", value: "active" }],
|
||||
},
|
||||
]
|
||||
: [],
|
||||
toBlocks:
|
||||
type === "if"
|
||||
? [
|
||||
{ id: "edge_true", condition: "true" },
|
||||
{ id: "edge_false", condition: "false" },
|
||||
]
|
||||
: type === "switch"
|
||||
? [
|
||||
{ id: "edge_case", condition: "case1" },
|
||||
{ id: "edge_default", condition: "default" },
|
||||
]
|
||||
: type === "iterator"
|
||||
? [
|
||||
{ id: "edge_next", condition: "loopNext" },
|
||||
{ id: "edge_end", condition: "loopEnd" },
|
||||
]
|
||||
: [],
|
||||
})
|
||||
);
|
||||
|
||||
expect(getNativeWorkflowTriggerCapabilityErrors([nativeBlock({ id: "event", type: "event", isTrigger: true }), ...supportedBlocks])).toEqual([
|
||||
'unsupported credential reference "apiToken" on block if',
|
||||
'unsupported credential reference "bodyToken" on block if',
|
||||
'unsupported credential reference "conditionToken" on block if',
|
||||
'unsupported credential reference "lookupToken" on block if',
|
||||
'unsupported credential reference "apiToken" on block switch',
|
||||
'unsupported credential reference "bodyToken" on block switch',
|
||||
'unsupported credential reference "conditionToken" on block switch',
|
||||
'unsupported credential reference "lookupToken" on block switch',
|
||||
'unsupported credential reference "apiToken" on block httpRequest',
|
||||
'unsupported credential reference "bodyToken" on block httpRequest',
|
||||
'unsupported credential reference "lookupToken" on block httpRequest',
|
||||
'unsupported credential reference "apiToken" on block log',
|
||||
'unsupported credential reference "bodyToken" on block log',
|
||||
'unsupported credential reference "lookupToken" on block log',
|
||||
'unsupported credential reference "apiToken" on block alertUser',
|
||||
'unsupported credential reference "bodyToken" on block alertUser',
|
||||
'unsupported credential reference "lookupToken" on block alertUser',
|
||||
'unsupported credential reference "apiToken" on block doNothing',
|
||||
'unsupported credential reference "bodyToken" on block doNothing',
|
||||
'unsupported credential reference "lookupToken" on block doNothing',
|
||||
'unsupported credential reference "apiToken" on block rowGet',
|
||||
'unsupported credential reference "bodyToken" on block rowGet',
|
||||
'unsupported credential reference "lookupToken" on block rowGet',
|
||||
'unsupported credential reference "apiToken" on block iterator',
|
||||
'unsupported credential reference "bodyToken" on block iterator',
|
||||
'unsupported credential reference "lookupToken" on block iterator',
|
||||
'unsupported credential reference "apiToken" on block variable',
|
||||
'unsupported credential reference "bodyToken" on block variable',
|
||||
'unsupported credential reference "lookupToken" on block variable',
|
||||
'unsupported credential reference "apiToken" on block email',
|
||||
'unsupported credential reference "bodyToken" on block email',
|
||||
'unsupported credential reference "lookupToken" on block email',
|
||||
]);
|
||||
});
|
||||
|
||||
test("reports high-risk worker-native block families before worker execution", () => {
|
||||
expect(
|
||||
getNativeWorkflowTriggerCapabilityErrors([
|
||||
nativeBlock({ id: "trigger", type: "event", isTrigger: true, input: { event: "row.created" } }),
|
||||
nativeBlock({ id: "row_create", type: "rowCreate", input: { entity: "contact", row: { name: "Ada" } } }),
|
||||
nativeBlock({ id: "row_update", type: "rowUpdate", input: { entity: "contact", id: "row_1", data: { name: "Ada" } } }),
|
||||
nativeBlock({ id: "row_delete", type: "rowDelete", input: { entity: "contact", id: "row_1" } }),
|
||||
nativeBlock({ id: "wait", type: "waitForInput", input: {} }),
|
||||
])
|
||||
).toEqual([
|
||||
'unsupported block type "rowCreate" on block row_create',
|
||||
'unsupported block type "rowUpdate" on block row_update',
|
||||
'unsupported block type "rowDelete" on block row_delete',
|
||||
'unsupported block type "waitForInput" on block wait',
|
||||
]);
|
||||
});
|
||||
|
||||
test("reports missing trigger blocks for worker-native workflows", () => {
|
||||
expect(getNativeWorkflowTriggerCapabilityErrors([nativeBlock({ id: "log", type: "log", input: { message: "hello" } })])).toEqual(["missing trigger block"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,375 @@
|
||||
export type WorkflowBlockExecutor = "core" | "pro";
|
||||
export type WorkflowBlockNativeSupport = "supported" | "preflight-skip";
|
||||
|
||||
export type WorkflowBlockType =
|
||||
| "manual"
|
||||
| "event"
|
||||
| "if"
|
||||
| "switch"
|
||||
| "httpRequest"
|
||||
| "log"
|
||||
| "alertUser"
|
||||
| "doNothing"
|
||||
| "waitForInput"
|
||||
| "rowGet"
|
||||
| "rowCreate"
|
||||
| "rowUpdate"
|
||||
| "rowDelete"
|
||||
| "iterator"
|
||||
| "variable"
|
||||
| "email";
|
||||
|
||||
export type WorkflowBlockContract = {
|
||||
value: WorkflowBlockType;
|
||||
executor: WorkflowBlockExecutor;
|
||||
nativeSupport: WorkflowBlockNativeSupport;
|
||||
requiredInputs: readonly string[];
|
||||
};
|
||||
|
||||
type WorkflowReferenceKind = "variables" | "credentials";
|
||||
|
||||
type WorkflowReferenceMap = Record<WorkflowReferenceKind, Set<string>>;
|
||||
|
||||
export type WorkflowReferenceSummary = {
|
||||
variables: string[];
|
||||
credentials: string[];
|
||||
byBlock: {
|
||||
blockId: string;
|
||||
variables: string[];
|
||||
credentials: string[];
|
||||
}[];
|
||||
};
|
||||
|
||||
export type WorkflowPreflightBlock = {
|
||||
id: string;
|
||||
type?: string;
|
||||
input?: unknown;
|
||||
conditionGroups?: readonly {
|
||||
index?: number;
|
||||
conditions?: readonly {
|
||||
variable?: unknown;
|
||||
value?: unknown;
|
||||
}[];
|
||||
}[];
|
||||
};
|
||||
|
||||
export type WorkflowNativeCapabilityBlock = WorkflowPreflightBlock & {
|
||||
type: string;
|
||||
isTrigger?: boolean;
|
||||
conditionsGroups?: WorkflowPreflightBlock["conditionGroups"];
|
||||
toBlocks?: readonly {
|
||||
id: string;
|
||||
condition?: string | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type WorkflowPreflightWorkflow = {
|
||||
blocks: readonly WorkflowPreflightBlock[];
|
||||
};
|
||||
|
||||
export type WorkflowRequiredInputIssue = {
|
||||
blockId: string;
|
||||
blockType: WorkflowBlockType;
|
||||
missingInputs: string[];
|
||||
};
|
||||
|
||||
export type WorkflowPreflightInput = {
|
||||
workflow: WorkflowPreflightWorkflow;
|
||||
variables: readonly string[];
|
||||
credentials: readonly string[];
|
||||
};
|
||||
|
||||
export type WorkflowPreflightResult = {
|
||||
missingVariables: string[];
|
||||
missingCredentials: string[];
|
||||
missingRequiredInputs: WorkflowRequiredInputIssue[];
|
||||
};
|
||||
|
||||
export const NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES = [
|
||||
"manual",
|
||||
"event",
|
||||
"if",
|
||||
"switch",
|
||||
"httpRequest",
|
||||
"log",
|
||||
"alertUser",
|
||||
"doNothing",
|
||||
"rowGet",
|
||||
"iterator",
|
||||
"variable",
|
||||
"email",
|
||||
] as const satisfies readonly WorkflowBlockType[];
|
||||
|
||||
export const workflowBlockContracts = [
|
||||
{ value: "manual", executor: "core", nativeSupport: "supported", requiredInputs: [] },
|
||||
{ value: "event", executor: "core", nativeSupport: "supported", requiredInputs: ["event"] },
|
||||
{ value: "if", executor: "core", nativeSupport: "supported", requiredInputs: [] },
|
||||
{ value: "switch", executor: "core", nativeSupport: "supported", requiredInputs: [] },
|
||||
{ value: "httpRequest", executor: "core", nativeSupport: "supported", requiredInputs: ["url", "method"] },
|
||||
{ value: "log", executor: "core", nativeSupport: "supported", requiredInputs: ["message"] },
|
||||
{ value: "alertUser", executor: "core", nativeSupport: "supported", requiredInputs: ["message"] },
|
||||
{ value: "doNothing", executor: "core", nativeSupport: "supported", requiredInputs: [] },
|
||||
{ value: "waitForInput", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: [] },
|
||||
{ value: "rowGet", executor: "pro", nativeSupport: "supported", requiredInputs: ["entity", "id"] },
|
||||
{ value: "rowCreate", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: ["entity", "row"] },
|
||||
{ value: "rowUpdate", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: ["entity", "id", "data"] },
|
||||
{ value: "rowDelete", executor: "pro", nativeSupport: "preflight-skip", requiredInputs: ["entity", "id"] },
|
||||
{ value: "iterator", executor: "core", nativeSupport: "supported", requiredInputs: ["variableName"] },
|
||||
{ value: "variable", executor: "core", nativeSupport: "supported", requiredInputs: ["variableName", "value"] },
|
||||
{ value: "email", executor: "pro", nativeSupport: "supported", requiredInputs: ["provider", "to", "subject", "body"] },
|
||||
] as const satisfies readonly WorkflowBlockContract[];
|
||||
|
||||
export const CORE_WORKFLOW_BLOCK_TYPES = workflowBlockContracts.filter((contract) => contract.executor === "core").map((contract) => contract.value);
|
||||
export const PRO_WORKFLOW_BLOCK_TYPES = workflowBlockContracts.filter((contract) => contract.executor === "pro").map((contract) => contract.value);
|
||||
|
||||
export function getWorkflowBlockContract(value: WorkflowBlockType): WorkflowBlockContract {
|
||||
const contract = workflowBlockContracts.find((candidate) => candidate.value === value);
|
||||
if (!contract) {
|
||||
throw new Error(`Unknown workflow block contract: ${value}`);
|
||||
}
|
||||
return contract;
|
||||
}
|
||||
|
||||
const WORKFLOW_DIRECT_REFERENCE_REGEX = /{{{?\s*\$(vars|credentials)\.([a-zA-Z0-9_-]+)\s*}}}?/g;
|
||||
const WORKFLOW_LOOKUP_REFERENCE_REGEX = /{{{?\s*lookup\s+\$(vars|credentials)\s+["']([a-zA-Z0-9_-]+)["']\s*}}}?/g;
|
||||
const WORKFLOW_WITH_BLOCK_REGEX = /{{#with\s+\$(vars|credentials)\s*}}([\s\S]*?){{\/with}}/g;
|
||||
const WORKFLOW_WITH_REFERENCE_REGEX = /{{{?\s*([a-zA-Z0-9_-]+)\s*}}}?/g;
|
||||
|
||||
function createReferenceMap(): WorkflowReferenceMap {
|
||||
return {
|
||||
variables: new Set<string>(),
|
||||
credentials: new Set<string>(),
|
||||
};
|
||||
}
|
||||
|
||||
function addReference(target: WorkflowReferenceMap, type: string, name: string) {
|
||||
if (type === "vars") {
|
||||
target.variables.add(name);
|
||||
} else if (type === "credentials") {
|
||||
target.credentials.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
function scanString(target: WorkflowReferenceMap, value: string) {
|
||||
for (const match of value.matchAll(WORKFLOW_DIRECT_REFERENCE_REGEX)) {
|
||||
addReference(target, match[1], match[2]);
|
||||
}
|
||||
for (const match of value.matchAll(WORKFLOW_LOOKUP_REFERENCE_REGEX)) {
|
||||
addReference(target, match[1], match[2]);
|
||||
}
|
||||
for (const withMatch of value.matchAll(WORKFLOW_WITH_BLOCK_REGEX)) {
|
||||
const type = withMatch[1];
|
||||
const body = withMatch[2] ?? "";
|
||||
for (const referenceMatch of body.matchAll(WORKFLOW_WITH_REFERENCE_REGEX)) {
|
||||
addReference(target, type, referenceMatch[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function scanValue(target: WorkflowReferenceMap, value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
scanString(target, value);
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((item) => scanValue(target, item));
|
||||
return;
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
Object.values(value).forEach((item) => scanValue(target, item));
|
||||
}
|
||||
}
|
||||
|
||||
function toSortedArray(values: Set<string>) {
|
||||
return Array.from(values).sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
function getLocalVariableNames(blocks: readonly WorkflowPreflightBlock[]) {
|
||||
return new Set(
|
||||
blocks
|
||||
.filter((block) => block.type === "variable")
|
||||
.map((block) => (isRecord(block.input) ? block.input.variableName : undefined))
|
||||
.filter((value): value is string => typeof value === "string" && value.length > 0)
|
||||
);
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function extractBlockReferences(block: WorkflowPreflightBlock): WorkflowReferenceMap {
|
||||
const references = createReferenceMap();
|
||||
scanValue(references, block.input);
|
||||
block.conditionGroups?.forEach((group) => {
|
||||
group.conditions?.forEach((condition) => {
|
||||
scanValue(references, condition.variable);
|
||||
scanValue(references, condition.value);
|
||||
});
|
||||
});
|
||||
return references;
|
||||
}
|
||||
|
||||
function isWorkflowBlockType(value: string | undefined): value is WorkflowBlockType {
|
||||
return workflowBlockContracts.some((contract) => contract.value === value);
|
||||
}
|
||||
|
||||
function hasRequiredInputValue(value: unknown) {
|
||||
if (typeof value === "string") {
|
||||
return value.trim().length > 0;
|
||||
}
|
||||
return value !== undefined && value !== null;
|
||||
}
|
||||
|
||||
export function extractWorkflowReferences(workflow: WorkflowPreflightWorkflow): WorkflowReferenceSummary {
|
||||
const references = createReferenceMap();
|
||||
const localVariables = getLocalVariableNames(workflow.blocks);
|
||||
const byBlock = workflow.blocks.map((block) => {
|
||||
const blockReferences = extractBlockReferences(block);
|
||||
localVariables.forEach((name) => blockReferences.variables.delete(name));
|
||||
blockReferences.variables.forEach((name) => references.variables.add(name));
|
||||
blockReferences.credentials.forEach((name) => references.credentials.add(name));
|
||||
return {
|
||||
blockId: block.id,
|
||||
variables: toSortedArray(blockReferences.variables),
|
||||
credentials: toSortedArray(blockReferences.credentials),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
variables: toSortedArray(references.variables),
|
||||
credentials: toSortedArray(references.credentials),
|
||||
byBlock,
|
||||
};
|
||||
}
|
||||
|
||||
export function getMissingWorkflowReferences({
|
||||
workflow,
|
||||
variables,
|
||||
credentials,
|
||||
}: {
|
||||
workflow: WorkflowPreflightWorkflow;
|
||||
variables: readonly string[];
|
||||
credentials: readonly string[];
|
||||
}) {
|
||||
const references = extractWorkflowReferences(workflow);
|
||||
const availableVariables = new Set(variables);
|
||||
const availableCredentials = new Set(credentials);
|
||||
return {
|
||||
missingVariables: references.variables.filter((name) => !availableVariables.has(name)),
|
||||
missingCredentials: references.credentials.filter((name) => !availableCredentials.has(name)),
|
||||
};
|
||||
}
|
||||
|
||||
export function validateWorkflowRequiredInputs(workflow: WorkflowPreflightWorkflow): WorkflowRequiredInputIssue[] {
|
||||
return workflow.blocks.flatMap((block) => {
|
||||
if (!isWorkflowBlockType(block.type)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const input = isRecord(block.input) ? block.input : {};
|
||||
const missingInputs = getWorkflowBlockContract(block.type).requiredInputs.filter((name) => !hasRequiredInputValue(input[name]));
|
||||
|
||||
if (missingInputs.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [{ blockId: block.id, blockType: block.type, missingInputs }];
|
||||
});
|
||||
}
|
||||
|
||||
export function preflightWorkflow({ workflow, variables, credentials }: WorkflowPreflightInput): WorkflowPreflightResult {
|
||||
return {
|
||||
...getMissingWorkflowReferences({ workflow, variables, credentials }),
|
||||
missingRequiredInputs: validateWorkflowRequiredInputs(workflow),
|
||||
};
|
||||
}
|
||||
|
||||
function parseNativeCapabilityBlockInput(input: unknown): unknown {
|
||||
if (typeof input !== "string") {
|
||||
return input;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(input);
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
return parsed;
|
||||
}
|
||||
} catch {
|
||||
// Invalid persisted input is handled by block-specific validation.
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
function getNativeCapabilityConditionGroups(block: WorkflowNativeCapabilityBlock): WorkflowPreflightBlock["conditionGroups"] {
|
||||
return block.conditionGroups ?? block.conditionsGroups;
|
||||
}
|
||||
|
||||
export function getNativeWorkflowTriggerCapabilityErrors(blocks: ReadonlyArray<WorkflowNativeCapabilityBlock>): string[] {
|
||||
const errors: string[] = [];
|
||||
if (!blocks.some((block) => block.isTrigger === true)) {
|
||||
errors.push("missing trigger block");
|
||||
}
|
||||
for (const block of blocks) {
|
||||
if (!NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES.includes(block.type as (typeof NATIVE_WORKFLOW_TRIGGER_SUPPORTED_BLOCK_TYPES)[number])) {
|
||||
errors.push(`unsupported block type "${block.type}" on block ${block.id}`);
|
||||
}
|
||||
const credentialReferences = extractWorkflowReferences({
|
||||
blocks: [
|
||||
{
|
||||
id: block.id,
|
||||
type: block.type,
|
||||
input: parseNativeCapabilityBlockInput(block.input),
|
||||
conditionGroups: getNativeCapabilityConditionGroups(block),
|
||||
},
|
||||
],
|
||||
}).byBlock[0]?.credentials ?? [];
|
||||
for (const credentialName of credentialReferences) {
|
||||
errors.push(`unsupported credential reference "${credentialName}" on block ${block.id}`);
|
||||
}
|
||||
if (block.type === "if") {
|
||||
const conditionsGroups = getNativeCapabilityConditionGroups(block) ?? [];
|
||||
if (conditionsGroups.length !== 1) {
|
||||
errors.push(`if block ${block.id} must have exactly one condition group`);
|
||||
} else if ((conditionsGroups[0]?.conditions?.length ?? 0) === 0) {
|
||||
errors.push(`if block ${block.id} must have at least one condition`);
|
||||
}
|
||||
const edgeConditions = new Set((block.toBlocks ?? []).map((edge) => edge.condition));
|
||||
if (!edgeConditions.has("true")) {
|
||||
errors.push(`if block ${block.id} is missing true edge`);
|
||||
}
|
||||
if (!edgeConditions.has("false")) {
|
||||
errors.push(`if block ${block.id} is missing false edge`);
|
||||
}
|
||||
}
|
||||
if (block.type === "switch") {
|
||||
const conditionsGroups = getNativeCapabilityConditionGroups(block) ?? [];
|
||||
const edgeConditions = new Set((block.toBlocks ?? []).map((edge) => edge.condition));
|
||||
if (!edgeConditions.has("default")) {
|
||||
errors.push(`switch block ${block.id} is missing default edge`);
|
||||
}
|
||||
for (const conditionGroup of conditionsGroups) {
|
||||
if ((conditionGroup.conditions?.length ?? 0) === 0) {
|
||||
errors.push(`switch block ${block.id} condition group ${(conditionGroup.index ?? 0) + 1} must have at least one condition`);
|
||||
}
|
||||
const caseCondition = `case${(conditionGroup.index ?? 0) + 1}`;
|
||||
if (!edgeConditions.has(caseCondition)) {
|
||||
errors.push(`switch block ${block.id} is missing ${caseCondition} edge`);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const edge of block.toBlocks ?? []) {
|
||||
if (typeof edge.condition === "string" && edge.condition.trim().length > 0) {
|
||||
if (block.type === "if" && (edge.condition === "true" || edge.condition === "false")) {
|
||||
continue;
|
||||
}
|
||||
if (block.type === "switch" && (edge.condition === "default" || /^case\d+$/u.test(edge.condition))) {
|
||||
continue;
|
||||
}
|
||||
if (block.type === "iterator" && (edge.condition === "loopNext" || edge.condition === "loopEnd")) {
|
||||
continue;
|
||||
}
|
||||
errors.push(`unsupported conditional edge "${edge.id}" from block ${block.id}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": false,
|
||||
"allowImportingTsExtensions": false,
|
||||
"lib": ["ES2022"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"noEmit": true,
|
||||
"types": ["node", "vitest/globals"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user