Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
+188
@@ -0,0 +1,188 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
parseAnalyticsEventPayload,
|
||||
parseAnalyticsPageViewPayload,
|
||||
parseApiKeyValidationPayload,
|
||||
parseEntityRowObjectBody,
|
||||
parseLoginCredentialsPayload,
|
||||
parseRelationshipCreatePayload,
|
||||
parseWorkspaceContextRevalidationPayload,
|
||||
parseWorkspaceInviteAcceptPayload,
|
||||
parseWorkspaceInviteCreatePayload,
|
||||
parseWorkspaceInviteRevokePayload,
|
||||
} from "./request-schemas.js";
|
||||
|
||||
const secretValue = "sk_live_secret_api_key_should_not_leak_value";
|
||||
|
||||
function expectValidationError(result: { ok: boolean; error?: { message: string; params: Record<string, unknown> } }, params: Record<string, unknown>) {
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.error).toMatchObject({
|
||||
message: expect.any(String),
|
||||
params,
|
||||
});
|
||||
expect(JSON.stringify(result.error)).not.toContain(secretValue);
|
||||
}
|
||||
|
||||
function expectErrorWithoutSecret(result: { ok: boolean; error?: { message: string; params: Record<string, unknown> } }) {
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.error?.message).toBeTypeOf("string");
|
||||
expect(JSON.stringify(result.error)).not.toContain(secretValue);
|
||||
}
|
||||
|
||||
describe("request schema validators", () => {
|
||||
test("accepts valid login credentials", () => {
|
||||
expect(parseLoginCredentialsPayload({ email: "user@example.com", password: "correct horse" })).toEqual({
|
||||
ok: true,
|
||||
value: { email: "user@example.com", password: "correct horse" },
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects malformed login credentials with field-level redacted messages", () => {
|
||||
expectValidationError(parseLoginCredentialsPayload(null), { reason: "body_invalid", bodyType: "login_credentials" });
|
||||
expectValidationError(parseLoginCredentialsPayload([]), { reason: "body_invalid", bodyType: "login_credentials" });
|
||||
expectValidationError(parseLoginCredentialsPayload({ password: "present" }), { reason: "field_required", field: "email" });
|
||||
expectValidationError(parseLoginCredentialsPayload({ email: 123, password: secretValue }), { reason: "field_type_invalid", field: "email", expected: "string" });
|
||||
});
|
||||
|
||||
test("accepts API-key validation bodies without leaking invalid secret-like values", () => {
|
||||
expect(parseApiKeyValidationPayload({ apiKey: "valid-key" })).toEqual({ ok: true, value: { apiKey: "valid-key" } });
|
||||
expect(parseApiKeyValidationPayload({})).toEqual({ ok: true, value: {} });
|
||||
|
||||
expectErrorWithoutSecret(parseApiKeyValidationPayload({ apiKey: { plaintext: secretValue } }));
|
||||
expectValidationError(parseApiKeyValidationPayload(null), { reason: "body_invalid", bodyType: "api_key_validation" });
|
||||
});
|
||||
|
||||
test("accepts valid analytics events with optional string fields", () => {
|
||||
expect(
|
||||
parseAnalyticsEventPayload({
|
||||
action: "clicked",
|
||||
category: "featureFlag",
|
||||
label: "cta",
|
||||
value: "1",
|
||||
url: "https://example.test/page",
|
||||
route: "/page",
|
||||
analytics: {
|
||||
userAnalyticsId: "visitor-1",
|
||||
portalId: "portal-1",
|
||||
portalUserId: "portal-user-1",
|
||||
referrer: "https://referrer.test",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
action: "clicked",
|
||||
category: "featureFlag",
|
||||
label: "cta",
|
||||
value: "1",
|
||||
url: "https://example.test/page",
|
||||
route: "/page",
|
||||
analytics: {
|
||||
userAnalyticsId: "visitor-1",
|
||||
portalId: "portal-1",
|
||||
portalUserId: "portal-user-1",
|
||||
referrer: "https://referrer.test",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects malformed analytics event bodies and analytics fields without echoing values", () => {
|
||||
expectValidationError(parseAnalyticsEventPayload([]), { reason: "body_invalid", bodyType: "analytics_event" });
|
||||
expectValidationError(parseAnalyticsEventPayload({ category: "featureFlag", analytics: { userAnalyticsId: "visitor-1" } }), { reason: "field_required", field: "action" });
|
||||
expectValidationError(parseAnalyticsEventPayload({ action: "clicked", category: 42, analytics: { userAnalyticsId: "visitor-1" } }), { reason: "field_type_invalid", field: "category", expected: "string" });
|
||||
expectValidationError(parseAnalyticsEventPayload({ action: "clicked", category: "featureFlag", analytics: null }), { reason: "field_type_invalid", field: "analytics", expected: "object" });
|
||||
expectErrorWithoutSecret(parseAnalyticsEventPayload({ action: "clicked", category: "featureFlag", analytics: { userAnalyticsId: { token: secretValue } } }));
|
||||
});
|
||||
|
||||
test("accepts and rejects analytics page-view payloads", () => {
|
||||
expect(parseAnalyticsPageViewPayload({ url: "https://example.test", analytics: { userAnalyticsId: "visitor-1" } })).toEqual({
|
||||
ok: true,
|
||||
value: { url: "https://example.test", analytics: { userAnalyticsId: "visitor-1" } },
|
||||
});
|
||||
expect(parseAnalyticsPageViewPayload({ url: "https://example.test", route: "/home", analytics: { userAnalyticsId: "visitor-1", portalId: null } })).toEqual({
|
||||
ok: true,
|
||||
value: { url: "https://example.test", route: "/home", analytics: { userAnalyticsId: "visitor-1", portalId: null } },
|
||||
});
|
||||
expectValidationError(parseAnalyticsPageViewPayload(null), { reason: "body_invalid", bodyType: "analytics_page_view" });
|
||||
expectValidationError(parseAnalyticsPageViewPayload({ url: 123, analytics: { userAnalyticsId: "visitor-1" } }), { reason: "field_type_invalid", field: "url", expected: "string" });
|
||||
expectErrorWithoutSecret(parseAnalyticsPageViewPayload({ url: "https://example.test", analytics: { userAnalyticsId: secretValue, portalId: 123 } }));
|
||||
});
|
||||
|
||||
test("accepts relationship create payloads and rejects missing or non-string row ids", () => {
|
||||
expect(parseRelationshipCreatePayload({ parent: "row-parent", child: "row-child" })).toEqual({
|
||||
ok: true,
|
||||
value: { parent: "row-parent", child: "row-child" },
|
||||
});
|
||||
expectValidationError(parseRelationshipCreatePayload(null), { reason: "body_invalid", bodyType: "relationship" });
|
||||
expectValidationError(parseRelationshipCreatePayload({ child: "row-child" }), { reason: "field_required", field: "parent" });
|
||||
expectValidationError(parseRelationshipCreatePayload({ parent: secretValue, child: 7 }), { reason: "field_type_invalid", field: "child", expected: "string" });
|
||||
});
|
||||
|
||||
test("entity row bodies only require non-array JSON objects and preserve arbitrary data", () => {
|
||||
const row = { name: "Widget", count: 3, nested: { enabled: true }, tags: ["a", "b"], secret: secretValue };
|
||||
|
||||
expect(parseEntityRowObjectBody(row)).toEqual({ ok: true, value: row });
|
||||
expectValidationError(parseEntityRowObjectBody(null), { reason: "body_invalid", bodyType: "entity_row" });
|
||||
expectValidationError(parseEntityRowObjectBody([]), { reason: "body_invalid", bodyType: "entity_row" });
|
||||
expectValidationError(parseEntityRowObjectBody("not object"), { reason: "body_invalid", bodyType: "entity_row" });
|
||||
});
|
||||
|
||||
test("accepts valid workspace invite create payloads", () => {
|
||||
expect(
|
||||
parseWorkspaceInviteCreatePayload({
|
||||
email: "MEMBER@example.com",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
type: 2,
|
||||
expiresAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
email: "MEMBER@example.com",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
type: 2,
|
||||
expiresAt: "2026-06-01T12:00:00.000Z",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("rejects malformed workspace invite create payloads without echoing values", () => {
|
||||
expectValidationError(parseWorkspaceInviteCreatePayload(null), { reason: "body_invalid", bodyType: "workspace_invite_create" });
|
||||
expectValidationError(parseWorkspaceInviteCreatePayload({ firstName: "Ada", lastName: "Lovelace", type: 2 }), { reason: "field_required", field: "email" });
|
||||
expectValidationError(parseWorkspaceInviteCreatePayload({ email: 7, firstName: "Ada", lastName: "Lovelace", type: 2 }), { reason: "field_type_invalid", field: "email", expected: "string" });
|
||||
expectValidationError(parseWorkspaceInviteCreatePayload({ email: "member@example.com", firstName: secretValue, lastName: "Lovelace", type: "2" }), { reason: "field_type_invalid", field: "type", expected: "number" });
|
||||
expectValidationError(parseWorkspaceInviteCreatePayload({ email: "member@example.com", firstName: "Ada", lastName: "Lovelace", type: 2, expiresAt: "tomorrow" }), { reason: "field_value_invalid", field: "expiresAt", expected: "datetime" });
|
||||
expectErrorWithoutSecret(parseWorkspaceInviteCreatePayload({ email: "member@example.com", firstName: secretValue, lastName: 99, type: 2 }));
|
||||
});
|
||||
|
||||
test("accepts and rejects workspace invite accept payloads with redacted token errors", () => {
|
||||
expect(parseWorkspaceInviteAcceptPayload({ token: secretValue, userId: "user_1" })).toEqual({ ok: true, value: { token: secretValue, userId: "user_1" } });
|
||||
expectValidationError(parseWorkspaceInviteAcceptPayload(null), { reason: "body_invalid", bodyType: "workspace_invite_accept" });
|
||||
expectValidationError(parseWorkspaceInviteAcceptPayload({ userId: "user_1" }), { reason: "field_required", field: "token" });
|
||||
expectValidationError(parseWorkspaceInviteAcceptPayload({ token: { plaintext: secretValue }, userId: "user_1" }), { reason: "field_type_invalid", field: "token", expected: "string" });
|
||||
expectErrorWithoutSecret(parseWorkspaceInviteAcceptPayload({ token: secretValue, userId: 123 }));
|
||||
});
|
||||
|
||||
test("accepts and rejects workspace invite revoke payloads", () => {
|
||||
expect(parseWorkspaceInviteRevokePayload({ reason: "duplicate", revokedByUserId: "admin_1" })).toEqual({
|
||||
ok: true,
|
||||
value: { reason: "duplicate", revokedByUserId: "admin_1" },
|
||||
});
|
||||
expect(parseWorkspaceInviteRevokePayload({})).toEqual({ ok: true, value: {} });
|
||||
expectValidationError(parseWorkspaceInviteRevokePayload([]), { reason: "body_invalid", bodyType: "workspace_invite_revoke" });
|
||||
expectValidationError(parseWorkspaceInviteRevokePayload({ reason: 404, revokedByUserId: secretValue }), { reason: "field_type_invalid", field: "reason", expected: "string" });
|
||||
expectErrorWithoutSecret(parseWorkspaceInviteRevokePayload({ reason: "duplicate", revokedByUserId: { token: secretValue } }));
|
||||
});
|
||||
|
||||
test("accepts and rejects workspace context revalidation payloads without echoing secret-like values", () => {
|
||||
expect(parseWorkspaceContextRevalidationPayload({ userId: "user_1" })).toEqual({ ok: true, value: { userId: "user_1" } });
|
||||
expect(parseWorkspaceContextRevalidationPayload({ userId: "user_1", providerSlug: "okta" })).toEqual({ ok: true, value: { userId: "user_1", providerSlug: "okta" } });
|
||||
expectValidationError(parseWorkspaceContextRevalidationPayload(null), { reason: "body_invalid", bodyType: "workspace_context_revalidation" });
|
||||
expectValidationError(parseWorkspaceContextRevalidationPayload({ providerSlug: "okta" }), { reason: "field_required", field: "userId" });
|
||||
expectValidationError(parseWorkspaceContextRevalidationPayload({ userId: 123, providerSlug: secretValue }), { reason: "field_type_invalid", field: "userId", expected: "string" });
|
||||
expectErrorWithoutSecret(parseWorkspaceContextRevalidationPayload({ userId: "user_1", providerSlug: { secret: secretValue } }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,265 @@
|
||||
import { z } from "zod";
|
||||
import type { ApiErrorParams } from "../middleware/error-envelope.js";
|
||||
|
||||
export type ValidationErrorReason = "body_invalid" | "field_required" | "field_type_invalid" | "field_value_invalid";
|
||||
|
||||
export type RequestValidationError = {
|
||||
message: string;
|
||||
params: ApiErrorParams;
|
||||
};
|
||||
|
||||
export type ParseResult<T> = { ok: true; value: T } | { ok: false; error: RequestValidationError };
|
||||
|
||||
export type LoginCredentialsPayload = {
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type ApiKeyValidationPayload = {
|
||||
apiKey?: string;
|
||||
};
|
||||
|
||||
export type AnalyticsInfoPayload = {
|
||||
userAnalyticsId: string;
|
||||
portalId?: string | null;
|
||||
portalUserId?: string | null;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
export type AnalyticsEventPayload = {
|
||||
action: string;
|
||||
category: string;
|
||||
label?: string;
|
||||
value?: string;
|
||||
url?: string;
|
||||
route?: string;
|
||||
analytics: AnalyticsInfoPayload;
|
||||
};
|
||||
|
||||
export type AnalyticsPageViewPayload = {
|
||||
url: string;
|
||||
route?: string;
|
||||
analytics: AnalyticsInfoPayload;
|
||||
};
|
||||
|
||||
export type RelationshipCreatePayload = {
|
||||
parent: string;
|
||||
child: string;
|
||||
};
|
||||
|
||||
export type WorkspaceInviteCreatePayload = {
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
type: number;
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
export type WorkspaceInviteAcceptPayload = {
|
||||
token: string;
|
||||
userId?: string;
|
||||
};
|
||||
|
||||
export type WorkspaceInviteRevokePayload = {
|
||||
reason?: string;
|
||||
revokedByUserId?: string;
|
||||
};
|
||||
|
||||
export type WorkspaceContextRevalidationPayload = {
|
||||
userId: string;
|
||||
providerSlug?: string;
|
||||
};
|
||||
|
||||
const jsonObjectSchema = z.object({}).passthrough();
|
||||
const requiredString = z.string().min(1);
|
||||
const optionalString = z.string().optional();
|
||||
const optionalNullableString = z.string().nullable().optional();
|
||||
const optionalDateTimeString = z.string().datetime().optional();
|
||||
|
||||
const analyticsInfoSchema = z
|
||||
.object({
|
||||
userAnalyticsId: requiredString,
|
||||
portalId: optionalNullableString,
|
||||
portalUserId: optionalNullableString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const loginCredentialsSchema = z
|
||||
.object({
|
||||
email: requiredString,
|
||||
password: requiredString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const apiKeyValidationSchema = z
|
||||
.object({
|
||||
apiKey: optionalString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const analyticsEventSchema = z
|
||||
.object({
|
||||
action: requiredString,
|
||||
category: requiredString,
|
||||
label: optionalString,
|
||||
value: optionalString,
|
||||
url: optionalString,
|
||||
route: optionalString,
|
||||
analytics: analyticsInfoSchema,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const analyticsPageViewSchema = z
|
||||
.object({
|
||||
url: requiredString,
|
||||
route: optionalString,
|
||||
analytics: analyticsInfoSchema,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const relationshipCreateSchema = z
|
||||
.object({
|
||||
parent: requiredString,
|
||||
child: requiredString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const workspaceInviteCreateSchema = z
|
||||
.object({
|
||||
email: requiredString,
|
||||
firstName: requiredString,
|
||||
lastName: requiredString,
|
||||
type: z.number().int(),
|
||||
expiresAt: optionalDateTimeString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const workspaceInviteAcceptSchema = z
|
||||
.object({
|
||||
token: requiredString,
|
||||
userId: optionalString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const workspaceInviteRevokeSchema = z
|
||||
.object({
|
||||
reason: optionalString,
|
||||
revokedByUserId: optionalString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
const workspaceContextRevalidationSchema = z
|
||||
.object({
|
||||
userId: requiredString,
|
||||
providerSlug: optionalString,
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export function parseLoginCredentialsPayload(body: unknown): ParseResult<LoginCredentialsPayload> {
|
||||
return parseSchema(body, loginCredentialsSchema, "login_credentials");
|
||||
}
|
||||
|
||||
export function parseApiKeyValidationPayload(body: unknown): ParseResult<ApiKeyValidationPayload> {
|
||||
return parseSchema(body, apiKeyValidationSchema, "api_key_validation");
|
||||
}
|
||||
|
||||
export function parseAnalyticsEventPayload(body: unknown): ParseResult<AnalyticsEventPayload> {
|
||||
return parseSchema(body, analyticsEventSchema, "analytics_event");
|
||||
}
|
||||
|
||||
export function parseAnalyticsPageViewPayload(body: unknown): ParseResult<AnalyticsPageViewPayload> {
|
||||
return parseSchema(body, analyticsPageViewSchema, "analytics_page_view");
|
||||
}
|
||||
|
||||
export function parseRelationshipCreatePayload(body: unknown): ParseResult<RelationshipCreatePayload> {
|
||||
return parseSchema(body, relationshipCreateSchema, "relationship");
|
||||
}
|
||||
|
||||
export function parseWorkspaceInviteCreatePayload(body: unknown): ParseResult<WorkspaceInviteCreatePayload> {
|
||||
return parseSchema(body, workspaceInviteCreateSchema, "workspace_invite_create");
|
||||
}
|
||||
|
||||
export function parseWorkspaceInviteAcceptPayload(body: unknown): ParseResult<WorkspaceInviteAcceptPayload> {
|
||||
return parseSchema(body, workspaceInviteAcceptSchema, "workspace_invite_accept");
|
||||
}
|
||||
|
||||
export function parseWorkspaceInviteRevokePayload(body: unknown): ParseResult<WorkspaceInviteRevokePayload> {
|
||||
return parseSchema(body, workspaceInviteRevokeSchema, "workspace_invite_revoke");
|
||||
}
|
||||
|
||||
export function parseWorkspaceContextRevalidationPayload(body: unknown): ParseResult<WorkspaceContextRevalidationPayload> {
|
||||
return parseSchema(body, workspaceContextRevalidationSchema, "workspace_context_revalidation");
|
||||
}
|
||||
|
||||
export function parseEntityRowObjectBody(body: unknown): ParseResult<Record<string, unknown>> {
|
||||
return parseSchema(body, jsonObjectSchema, "entity_row");
|
||||
}
|
||||
|
||||
function parseSchema<T>(body: unknown, schema: z.ZodType<T>, bodyType: string): ParseResult<T> {
|
||||
if (!isJsonObject(body)) {
|
||||
return { ok: false, error: createValidationError("body_invalid", { bodyType }) };
|
||||
}
|
||||
|
||||
const result = schema.safeParse(body);
|
||||
if (!result.success) {
|
||||
return { ok: false, error: formatValidationError(result.error) };
|
||||
}
|
||||
|
||||
return { ok: true, value: result.data };
|
||||
}
|
||||
|
||||
function isJsonObject(body: unknown): body is Record<string, unknown> {
|
||||
return Boolean(body && typeof body === "object" && !Array.isArray(body));
|
||||
}
|
||||
|
||||
function formatValidationError(error: z.ZodError): RequestValidationError {
|
||||
const issue = error.issues[0];
|
||||
const field = issue?.path.length ? issue.path.join(".") : "body";
|
||||
return createValidationError(reasonForIssue(issue), {
|
||||
field,
|
||||
...paramsForIssue(issue),
|
||||
});
|
||||
}
|
||||
|
||||
function reasonForIssue(issue: z.ZodIssue | undefined): ValidationErrorReason {
|
||||
if (!issue) {
|
||||
return "field_value_invalid";
|
||||
}
|
||||
|
||||
if (issue.code === z.ZodIssueCode.invalid_type) {
|
||||
return issue.received === "undefined" ? "field_required" : "field_type_invalid";
|
||||
}
|
||||
|
||||
if (issue.code === z.ZodIssueCode.too_small && issue.type === "string") {
|
||||
return "field_required";
|
||||
}
|
||||
|
||||
return "field_value_invalid";
|
||||
}
|
||||
|
||||
function paramsForIssue(issue: z.ZodIssue | undefined): ApiErrorParams {
|
||||
if (!issue) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (issue.code === z.ZodIssueCode.invalid_type && issue.received !== "undefined") {
|
||||
return { expected: issue.expected };
|
||||
}
|
||||
|
||||
if (issue.code === z.ZodIssueCode.too_small && issue.type === "string") {
|
||||
return { min: Number(issue.minimum) };
|
||||
}
|
||||
|
||||
if (issue.code === z.ZodIssueCode.invalid_string) {
|
||||
return { expected: String(issue.validation) };
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
function createValidationError(reason: ValidationErrorReason, params: ApiErrorParams = {}): RequestValidationError {
|
||||
return {
|
||||
message: reason === "body_invalid" ? "Request body must be a JSON object." : "Request validation failed.",
|
||||
params: { reason, ...params },
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user