@comms-id/sanctions 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ // Runtime template: copied into every generated client package as src/runtime/errors.ts.
2
+ // It has no imports, so the copy is identical to this file.
3
+ /**
4
+ * Every failure of a call. The service sends `code`, `message`, `retryable` and `requestId`.
5
+ * The client adds the codes INVALID_REQUEST (refused before any request), NETWORK, TIMEOUT,
6
+ * ABORTED and INVALID_RESPONSE.
7
+ */
8
+ export class CommsIdError extends Error {
9
+ code;
10
+ status;
11
+ retryable;
12
+ requestId;
13
+ /** The structured reply of a status such as 503 whose body is an outcome, not an error body (code HTTP_<status>). */
14
+ body;
15
+ constructor(init) {
16
+ super(init.message);
17
+ this.name = "CommsIdError";
18
+ this.code = init.code;
19
+ this.status = init.status;
20
+ this.retryable = init.retryable;
21
+ this.requestId = init.requestId;
22
+ this.body = init.body;
23
+ }
24
+ }
25
+ export const isCommsIdError = (value) => value instanceof CommsIdError;
26
+ /** HTTP statuses that say the source or the path to it is down: 502, 503 and 504. The client's own failures have status 0. */
27
+ const GATEWAY_STATUSES = new Set([502, 503, 504]);
28
+ /** Maps an error to the outcome that the reply convention names. A match never reaches this. */
29
+ export const outcomeOf = (error) => {
30
+ if (!isCommsIdError(error)) {
31
+ return "failed";
32
+ }
33
+ if (error.code === "NOT_FOUND") {
34
+ return "no-match";
35
+ }
36
+ if (error.code === "UNAVAILABLE" || GATEWAY_STATUSES.has(error.status)) {
37
+ return "source-unavailable";
38
+ }
39
+ return "failed";
40
+ };
@@ -0,0 +1,7 @@
1
+ import type { TransportConfig } from "./http.js";
2
+ /** Every fixture reply carries this header, and every fixture client exposes it. */
3
+ export declare const FIXTURE_HEADER = "x-comms-id-fixture";
4
+ export declare const FIXTURE_NOTICE = "LOCAL FIXTURE: fake data, no network call was made.";
5
+ /** A fetch that answers each operation path with its canned reply. */
6
+ export declare const createFixtureFetch: (replies: Readonly<Record<string, unknown>>) => typeof fetch;
7
+ export declare const createFixtureTransport: (replies: Readonly<Record<string, unknown>>) => TransportConfig;
@@ -0,0 +1,26 @@
1
+ // Runtime template: copied into every generated client package as src/runtime/fixture-core.ts.
2
+ // LOCAL FIXTURES: no network. The client runs the same request and reply checks as a real call.
3
+ /** Every fixture reply carries this header, and every fixture client exposes it. */
4
+ export const FIXTURE_HEADER = "x-comms-id-fixture";
5
+ export const FIXTURE_NOTICE = "LOCAL FIXTURE: fake data, no network call was made.";
6
+ /** A fetch that answers each operation path with its canned reply. */
7
+ export const createFixtureFetch = (replies) => (input) => {
8
+ const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url, "http://fixture.invalid");
9
+ const reply = replies[url.pathname];
10
+ if (reply === undefined) {
11
+ return Promise.resolve(new Response(JSON.stringify({ code: "NOT_FOUND", message: "No fixture for this operation.", retryable: false }), {
12
+ status: 404,
13
+ headers: { "content-type": "application/json", [FIXTURE_HEADER]: FIXTURE_NOTICE },
14
+ }));
15
+ }
16
+ return Promise.resolve(new Response(JSON.stringify(reply), {
17
+ status: 200,
18
+ headers: { "content-type": "application/json", [FIXTURE_HEADER]: FIXTURE_NOTICE },
19
+ }));
20
+ };
21
+ export const createFixtureTransport = (replies) => ({
22
+ urlFor: (operation) => operation.path,
23
+ headers: () => Promise.resolve({}),
24
+ fetch: createFixtureFetch(replies),
25
+ maxRetries: 0,
26
+ });
@@ -0,0 +1,34 @@
1
+ import { type Schema } from "./validate.js";
2
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
3
+ /** A hand-written check that a schema cannot state. It returns the reason to refuse, or undefined. */
4
+ export type Guard = (input: unknown) => string | undefined;
5
+ /** One hosted operation, as the generator writes it from the OpenAPI document. */
6
+ export interface Operation {
7
+ /** Run after the schema check and before any request (for example an ABN check digit). */
8
+ readonly guard?: Guard | undefined;
9
+ readonly method: HttpMethod;
10
+ readonly name: string;
11
+ readonly path: string;
12
+ readonly request: Schema | undefined;
13
+ readonly response: Schema;
14
+ /** From x-comms-id-safe-to-retry: only such an operation is ever sent twice. */
15
+ readonly safeToRetry: boolean;
16
+ }
17
+ export interface CallOptions {
18
+ /** Overrides the deadline for this call, in milliseconds. */
19
+ readonly deadlineMs?: number;
20
+ /** Cancels the call. The error code is ABORTED. */
21
+ readonly signal?: AbortSignal;
22
+ }
23
+ export interface TransportConfig {
24
+ /** The deadline for the whole call, retries included. 10 seconds by default. */
25
+ readonly deadlineMs?: number;
26
+ readonly fetch?: typeof fetch;
27
+ readonly headers: () => Promise<Readonly<Record<string, string>>>;
28
+ /** Extra tries of a safe operation after a retryable failure. 2 by default. */
29
+ readonly maxRetries?: number;
30
+ readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
31
+ readonly urlFor: (operation: Operation) => string;
32
+ }
33
+ /** Sends one operation and returns its decoded reply, or throws a CommsIdError. */
34
+ export declare const call: <Reply>(transport: TransportConfig, operation: Operation, input: unknown, options?: CallOptions) => Promise<Reply>;
@@ -0,0 +1,165 @@
1
+ // Runtime template: copied into every generated client package as src/runtime/http.ts.
2
+ // One call: validate the request, send it with a deadline and a cancel signal, retry only an
3
+ // operation that is safe to repeat, validate the reply. No dependencies, no Comms.ID logic
4
+ // beyond the reply convention.
5
+ import { CommsIdError } from "./errors.js";
6
+ import { validate } from "./validate.js";
7
+ const DEFAULT_DEADLINE_MS = 10_000;
8
+ const DEFAULT_MAX_RETRIES = 2;
9
+ const BASE_DELAY_MS = 200;
10
+ const MAX_DELAY_MS = 2000;
11
+ const fail = (code, message, status, retryable, requestId, body) => new CommsIdError({ code, message, status, retryable, requestId, body });
12
+ const summarize = (issues) => issues
13
+ .slice(0, 3)
14
+ .map((issue) => `${issue.path} ${issue.message}`)
15
+ .join("; ");
16
+ const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
17
+ const timer = setTimeout(resolve, ms);
18
+ signal.addEventListener("abort", () => {
19
+ clearTimeout(timer);
20
+ reject(signal.reason);
21
+ }, { once: true });
22
+ });
23
+ const abortError = (user) => user?.aborted === true
24
+ ? fail("ABORTED", "The call was cancelled.", 0, false)
25
+ : fail("TIMEOUT", "The call passed its deadline.", 0, true);
26
+ const retryAfterMs = (response) => {
27
+ const header = response.headers.get("retry-after");
28
+ const seconds = header === null ? Number.NaN : Number(header);
29
+ return Number.isInteger(seconds) && seconds >= 0 ? seconds * 1000 : undefined;
30
+ };
31
+ const readFailure = async (response) => {
32
+ const headerId = response.headers.get("x-request-id") ?? undefined;
33
+ let body;
34
+ try {
35
+ body = await response.json();
36
+ }
37
+ catch {
38
+ body = undefined;
39
+ }
40
+ const record = typeof body === "object" && body !== null ? body : {};
41
+ if (typeof record.code === "string" && typeof record.message === "string" && typeof record.retryable === "boolean") {
42
+ const requestId = typeof record.requestId === "string" ? record.requestId : headerId;
43
+ return fail(record.code, record.message, response.status, record.retryable, requestId);
44
+ }
45
+ const gateway = response.status >= 502 && response.status <= 504;
46
+ return fail(`HTTP_${response.status}`, `The service answered ${response.status}.`, response.status, gateway, headerId,
47
+ // A structured reply with an error status (an unavailable or partial outcome) keeps its body.
48
+ Object.keys(record).length > 0 ? record : undefined);
49
+ };
50
+ const readSuccess = async (operation, response) => {
51
+ const requestId = response.headers.get("x-request-id") ?? undefined;
52
+ let value;
53
+ try {
54
+ value = await response.json();
55
+ }
56
+ catch {
57
+ return {
58
+ ok: false,
59
+ error: fail("INVALID_RESPONSE", "The reply is not JSON.", response.status, false, requestId),
60
+ retryAfterMs: undefined,
61
+ };
62
+ }
63
+ const issues = validate(operation.response, value, "response");
64
+ if (issues.length > 0) {
65
+ return {
66
+ ok: false,
67
+ error: fail("INVALID_RESPONSE", `The reply does not match the contract: ${summarize(issues)}`, response.status, false, requestId),
68
+ retryAfterMs: undefined,
69
+ };
70
+ }
71
+ return { ok: true, value };
72
+ };
73
+ /**
74
+ * Builds the credential headers. A failure here is not a network failure: a CommsIdError (for
75
+ * example a refused public key) is passed on as it is, and anything else is a configuration
76
+ * error. Neither is sent anywhere.
77
+ */
78
+ const credentialHeaders = async (transport) => {
79
+ try {
80
+ return { ok: true, headers: await transport.headers() };
81
+ }
82
+ catch (cause) {
83
+ if (cause instanceof CommsIdError) {
84
+ return { ok: false, error: cause };
85
+ }
86
+ const reason = cause instanceof Error ? cause.message : "unknown error";
87
+ return { ok: false, error: fail("NOT_CONFIGURED", `Could not prepare the credentials: ${reason}`, 0, false) };
88
+ }
89
+ };
90
+ const attemptOnce = async (transport, operation, body, signal, user) => {
91
+ if (signal.aborted) {
92
+ throw abortError(user);
93
+ }
94
+ const credentials = await credentialHeaders(transport);
95
+ // A cancel that arrives while the credentials are built must not reach fetch.
96
+ if (signal.aborted) {
97
+ throw abortError(user);
98
+ }
99
+ if (!credentials.ok) {
100
+ return { ok: false, error: credentials.error, retryAfterMs: undefined };
101
+ }
102
+ const headers = {
103
+ accept: "application/json",
104
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
105
+ ...credentials.headers,
106
+ };
107
+ let response;
108
+ try {
109
+ response = await (transport.fetch ?? fetch)(transport.urlFor(operation), {
110
+ method: operation.method,
111
+ headers,
112
+ body,
113
+ signal,
114
+ });
115
+ }
116
+ catch (cause) {
117
+ if (signal.aborted) {
118
+ throw abortError(user);
119
+ }
120
+ const reason = cause instanceof Error ? cause.message : "The request failed.";
121
+ return { ok: false, error: fail("NETWORK", reason, 0, true), retryAfterMs: undefined };
122
+ }
123
+ if (response.ok) {
124
+ return await readSuccess(operation, response);
125
+ }
126
+ return { ok: false, error: await readFailure(response), retryAfterMs: retryAfterMs(response) };
127
+ };
128
+ const prepare = (operation, input) => {
129
+ if (operation.request === undefined) {
130
+ return undefined;
131
+ }
132
+ const issues = validate(operation.request, input, "request");
133
+ if (issues.length > 0) {
134
+ throw fail("INVALID_REQUEST", `The request is not valid: ${summarize(issues)}`, 0, false);
135
+ }
136
+ const refusal = operation.guard?.(input);
137
+ if (refusal !== undefined) {
138
+ throw fail("INVALID_REQUEST", `The request is not valid: ${refusal}`, 0, false);
139
+ }
140
+ return JSON.stringify(input);
141
+ };
142
+ /** Sends one operation and returns its decoded reply, or throws a CommsIdError. */
143
+ export const call = async (transport, operation, input, options = {}) => {
144
+ const body = prepare(operation, input);
145
+ const deadline = AbortSignal.timeout(options.deadlineMs ?? transport.deadlineMs ?? DEFAULT_DEADLINE_MS);
146
+ const signal = options.signal === undefined ? deadline : AbortSignal.any([options.signal, deadline]);
147
+ const maxRetries = operation.safeToRetry ? (transport.maxRetries ?? DEFAULT_MAX_RETRIES) : 0;
148
+ const sleep = transport.sleep ?? defaultSleep;
149
+ for (let attempt = 0;; attempt += 1) {
150
+ const result = await attemptOnce(transport, operation, body, signal, options.signal);
151
+ if (result.ok) {
152
+ return result.value;
153
+ }
154
+ if (attempt >= maxRetries || !result.error.retryable) {
155
+ throw result.error;
156
+ }
157
+ const delay = result.retryAfterMs ?? Math.min(BASE_DELAY_MS * 2 ** attempt, MAX_DELAY_MS);
158
+ try {
159
+ await sleep(delay, signal);
160
+ }
161
+ catch {
162
+ throw abortError(options.signal);
163
+ }
164
+ }
165
+ };
@@ -0,0 +1,26 @@
1
+ import { type Environment } from "./environment.js";
2
+ import type { TransportConfig } from "./http.js";
3
+ import { type PrivateJwk } from "./sign.js";
4
+ export declare const DEFAULT_BASE_URL: string;
5
+ export interface ServerOptions {
6
+ /** Another host. It wins over `environment`. */
7
+ readonly baseUrl?: string;
8
+ /** The registered app id (COMMS_ID_CLIENT_ID). */
9
+ readonly clientId: string;
10
+ readonly deadlineMs?: number;
11
+ /** "live" (the default) or "test": synthetic replies for apps registered in the development directory. */
12
+ readonly environment?: Environment;
13
+ readonly fetch?: typeof fetch;
14
+ readonly maxRetries?: number;
15
+ readonly now?: () => number;
16
+ /** The app's private Ed25519 key (COMMS_ID_PRIVATE_JWK). */
17
+ readonly privateJwk: PrivateJwk;
18
+ /** Seconds each signed token stays valid: 120 by default, 600 at most. */
19
+ readonly tokenLifetimeSeconds?: number;
20
+ }
21
+ /** What the service verifies: its audience and scope, written into the generated client. */
22
+ export interface ServerTarget {
23
+ readonly audience: string;
24
+ readonly scope: string;
25
+ }
26
+ export declare const createServerTransport: (options: ServerOptions, target: ServerTarget) => TransportConfig;
@@ -0,0 +1,39 @@
1
+ // Runtime template: copied into every generated client package as src/runtime/server-core.ts.
2
+ // Server entry only. The private key never leaves the consumer's server.
3
+ import { BASE_URLS, resolveBaseUrl } from "./environment.js";
4
+ import { CommsIdError } from "./errors.js";
5
+ import { createTokenSigner } from "./sign.js";
6
+ export const DEFAULT_BASE_URL = BASE_URLS.live;
7
+ const TRAILING_SLASHES = /\/+$/;
8
+ /** A transport that signs a fresh short-lived token for every call. */
9
+ const notConfigured = (message) => new CommsIdError({ code: "NOT_CONFIGURED", message, status: 0, retryable: false });
10
+ /** A client with no identified caller is a configuration error: it never sends an unsigned request. */
11
+ const requireCaller = (options) => {
12
+ if (typeof options.clientId !== "string" || options.clientId.trim() === "") {
13
+ throw notConfigured("clientId is empty: set COMMS_ID_CLIENT_ID to your registered app id.");
14
+ }
15
+ const key = options.privateJwk;
16
+ if (key?.kty !== "OKP" || key.crv !== "Ed25519" || typeof key.x !== "string" || typeof key.d !== "string") {
17
+ throw notConfigured("privateJwk is missing or not an Ed25519 private key: set COMMS_ID_PRIVATE_JWK.");
18
+ }
19
+ };
20
+ export const createServerTransport = (options, target) => {
21
+ requireCaller(options);
22
+ const sign = createTokenSigner(options.privateJwk);
23
+ const base = resolveBaseUrl(options.environment, options.baseUrl).replace(TRAILING_SLASHES, "");
24
+ return {
25
+ urlFor: (operation) => `${base}${operation.path}`,
26
+ headers: async () => ({
27
+ authorization: `Bearer ${await sign({
28
+ clientId: options.clientId,
29
+ audience: target.audience,
30
+ scope: target.scope,
31
+ ...(options.tokenLifetimeSeconds === undefined ? {} : { lifetimeSeconds: options.tokenLifetimeSeconds }),
32
+ ...(options.now === undefined ? {} : { now: options.now }),
33
+ })}`,
34
+ }),
35
+ ...(options.fetch === undefined ? {} : { fetch: options.fetch }),
36
+ ...(options.deadlineMs === undefined ? {} : { deadlineMs: options.deadlineMs }),
37
+ ...(options.maxRetries === undefined ? {} : { maxRetries: options.maxRetries }),
38
+ };
39
+ };
@@ -0,0 +1,22 @@
1
+ /** An Ed25519 private key as a JWK: the key pair's private half stays on the consumer's server. */
2
+ export interface PrivateJwk {
3
+ readonly crv: "Ed25519";
4
+ readonly d: string;
5
+ readonly kty: "OKP";
6
+ readonly x: string;
7
+ }
8
+ export interface TokenInput {
9
+ /** The service the token is for. */
10
+ readonly audience: string;
11
+ /** The registered app id, sent as the token issuer. */
12
+ readonly clientId: string;
13
+ /** Seconds the token stays valid: 120 by default, 600 at most. */
14
+ readonly lifetimeSeconds?: number;
15
+ readonly now?: () => number;
16
+ readonly scope: string;
17
+ }
18
+ /**
19
+ * Returns a function that signs one short-lived token for each call. The key is imported once.
20
+ * The token is a JWT with alg EdDSA and the claims iss, aud, sub, jti, iat, exp and scope.
21
+ */
22
+ export declare const createTokenSigner: (privateJwk: PrivateJwk) => ((input: TokenInput) => Promise<string>);
@@ -0,0 +1,41 @@
1
+ // Runtime template: copied into every generated client package as src/runtime/sign.ts.
2
+ // Server entry only: the browser entry never imports this file. Web Crypto, no dependencies.
3
+ const DEFAULT_LIFETIME_SECONDS = 120;
4
+ const MAX_LIFETIME_SECONDS = 600;
5
+ const encoder = new TextEncoder();
6
+ const base64url = (bytes) => {
7
+ let binary = "";
8
+ for (const byte of bytes) {
9
+ binary += String.fromCharCode(byte);
10
+ }
11
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
12
+ };
13
+ const encodeJson = (value) => base64url(encoder.encode(JSON.stringify(value)));
14
+ /**
15
+ * Returns a function that signs one short-lived token for each call. The key is imported once.
16
+ * The token is a JWT with alg EdDSA and the claims iss, aud, sub, jti, iat, exp and scope.
17
+ */
18
+ export const createTokenSigner = (privateJwk) => {
19
+ let key;
20
+ const importKey = () => {
21
+ key ??= crypto.subtle.importKey("jwk", privateJwk, { name: "Ed25519" }, false, ["sign"]);
22
+ return key;
23
+ };
24
+ return async (input) => {
25
+ const lifetime = Math.min(Math.max(input.lifetimeSeconds ?? DEFAULT_LIFETIME_SECONDS, 1), MAX_LIFETIME_SECONDS);
26
+ const issuedAt = Math.floor((input.now?.() ?? Date.now()) / 1000);
27
+ const header = encodeJson({ alg: "EdDSA" });
28
+ const payload = encodeJson({
29
+ scope: input.scope,
30
+ iss: input.clientId,
31
+ aud: input.audience,
32
+ sub: crypto.randomUUID(),
33
+ jti: crypto.randomUUID(),
34
+ iat: issuedAt,
35
+ exp: issuedAt + lifetime,
36
+ });
37
+ const signingInput = `${header}.${payload}`;
38
+ const signature = await crypto.subtle.sign({ name: "Ed25519" }, await importKey(), encoder.encode(signingInput));
39
+ return `${signingInput}.${base64url(new Uint8Array(signature))}`;
40
+ };
41
+ };
@@ -0,0 +1,57 @@
1
+ /** The JSON Schema subset that generated clients check, in a compact form the generator writes. */
2
+ export type Schema = {
3
+ readonly t: "str";
4
+ readonly min?: number;
5
+ readonly max?: number;
6
+ readonly values?: readonly string[];
7
+ /** A JSON Schema pattern: checked in a request only. */
8
+ readonly pattern?: string;
9
+ } | {
10
+ readonly t: "int" | "num";
11
+ readonly min?: number;
12
+ readonly max?: number;
13
+ /** exclusiveMinimum and exclusiveMaximum, checked in a request only. */
14
+ readonly exMin?: number;
15
+ readonly exMax?: number;
16
+ readonly values?: readonly number[];
17
+ } | {
18
+ readonly t: "bool";
19
+ } | {
20
+ readonly t: "null";
21
+ } | {
22
+ readonly t: "any";
23
+ } | {
24
+ readonly t: "const";
25
+ readonly value: string | number | boolean | null;
26
+ } | {
27
+ readonly t: "arr";
28
+ readonly of: Schema;
29
+ readonly min?: number;
30
+ readonly max?: number;
31
+ } | {
32
+ readonly t: "tup";
33
+ readonly of: readonly Schema[];
34
+ } | {
35
+ readonly t: "map";
36
+ readonly of: Schema;
37
+ } | {
38
+ readonly t: "obj";
39
+ readonly props: Readonly<Record<string, Schema>>;
40
+ readonly req: readonly string[];
41
+ readonly extra: boolean;
42
+ } | {
43
+ readonly t: "any_of";
44
+ readonly of: readonly Schema[];
45
+ };
46
+ /**
47
+ * A request is checked against every constraint before it leaves the client. A response is
48
+ * checked for shape only: unknown properties, new enum values and size limits are accepted, so
49
+ * a service can add to a reply in a minor version without breaking an installed client.
50
+ */
51
+ export type Mode = "request" | "response";
52
+ export interface Issue {
53
+ readonly message: string;
54
+ readonly path: string;
55
+ }
56
+ /** Returns the problems found, at most eight, or an empty array when the value is acceptable. */
57
+ export declare const validate: (schema: Schema, value: unknown, mode: Mode) => readonly Issue[];
@@ -0,0 +1,175 @@
1
+ // Runtime template: copied into every generated client package as src/runtime/validate.ts.
2
+ // It has no imports, so the copy is identical to this file.
3
+ const MAX_ISSUES = 8;
4
+ const describe = (value) => {
5
+ if (value === null) {
6
+ return "null";
7
+ }
8
+ return Array.isArray(value) ? "array" : typeof value;
9
+ };
10
+ const add = (issues, path, message) => {
11
+ if (issues.length < MAX_ISSUES) {
12
+ issues.push({ path, message });
13
+ }
14
+ };
15
+ const strictSize = (mode, size, min, max) => {
16
+ if (mode !== "request") {
17
+ return undefined;
18
+ }
19
+ if (min !== undefined && size < min) {
20
+ return `must be at least ${min}`;
21
+ }
22
+ if (max !== undefined && size > max) {
23
+ return `must be at most ${max}`;
24
+ }
25
+ return undefined;
26
+ };
27
+ /** A pattern the runtime cannot compile is not checked here: the service checks it. */
28
+ const matches = (pattern, value) => {
29
+ try {
30
+ return new RegExp(pattern).test(value);
31
+ }
32
+ catch {
33
+ return true;
34
+ }
35
+ };
36
+ const checkString = (schema, value, path, mode, issues) => {
37
+ if (typeof value !== "string") {
38
+ add(issues, path, `expected a string, got ${describe(value)}`);
39
+ return;
40
+ }
41
+ const size = strictSize(mode, value.length, schema.min, schema.max);
42
+ if (size !== undefined) {
43
+ add(issues, path, `length ${size}`);
44
+ }
45
+ if (mode === "request" && schema.values !== undefined && !schema.values.includes(value)) {
46
+ add(issues, path, `must be one of ${schema.values.join(", ")}`);
47
+ }
48
+ if (mode === "request" && schema.pattern !== undefined && !matches(schema.pattern, value)) {
49
+ add(issues, path, `must match the pattern ${schema.pattern}`);
50
+ }
51
+ };
52
+ const checkNumber = (schema, value, path, mode, issues) => {
53
+ const ok = typeof value === "number" && Number.isFinite(value) && (schema.t === "num" || Number.isInteger(value));
54
+ if (!ok) {
55
+ add(issues, path, `expected ${schema.t === "int" ? "an integer" : "a number"}, got ${describe(value)}`);
56
+ return;
57
+ }
58
+ const size = strictSize(mode, value, schema.min, schema.max);
59
+ if (size !== undefined) {
60
+ add(issues, path, `value ${size}`);
61
+ }
62
+ if (mode === "request" && schema.exMin !== undefined && value <= schema.exMin) {
63
+ add(issues, path, `value must be greater than ${schema.exMin}`);
64
+ }
65
+ if (mode === "request" && schema.exMax !== undefined && value >= schema.exMax) {
66
+ add(issues, path, `value must be less than ${schema.exMax}`);
67
+ }
68
+ if (mode === "request" && schema.values !== undefined && !schema.values.includes(value)) {
69
+ add(issues, path, `must be one of ${schema.values.join(", ")}`);
70
+ }
71
+ };
72
+ const checkArray = (schema, value, path, mode, issues) => {
73
+ if (!Array.isArray(value)) {
74
+ add(issues, path, `expected an array, got ${describe(value)}`);
75
+ return;
76
+ }
77
+ const size = strictSize(mode, value.length, schema.min, schema.max);
78
+ if (size !== undefined) {
79
+ add(issues, path, `item count ${size}`);
80
+ }
81
+ value.forEach((item, index) => {
82
+ check(schema.of, item, `${path}[${index}]`, mode, issues);
83
+ });
84
+ };
85
+ const checkTuple = (schema, value, path, mode, issues) => {
86
+ if (!Array.isArray(value) || value.length !== schema.of.length) {
87
+ add(issues, path, `expected an array of ${schema.of.length} items`);
88
+ return;
89
+ }
90
+ schema.of.forEach((member, index) => {
91
+ check(member, value[index], `${path}[${index}]`, mode, issues);
92
+ });
93
+ };
94
+ const checkObject = (schema, value, path, mode, issues) => {
95
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
96
+ add(issues, path, `expected an object, got ${describe(value)}`);
97
+ return;
98
+ }
99
+ const record = value;
100
+ for (const key of schema.req) {
101
+ if (!(key in record) || record[key] === undefined) {
102
+ add(issues, `${path}.${key}`, "is required");
103
+ }
104
+ }
105
+ for (const [key, member] of Object.entries(record)) {
106
+ const known = schema.props[key];
107
+ if (known !== undefined) {
108
+ if (member !== undefined) {
109
+ check(known, member, `${path}.${key}`, mode, issues);
110
+ }
111
+ }
112
+ else if (mode === "request" && !schema.extra) {
113
+ add(issues, `${path}.${key}`, "is not a known property");
114
+ }
115
+ }
116
+ };
117
+ const checkMap = (schema, value, path, mode, issues) => {
118
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
119
+ add(issues, path, `expected an object, got ${describe(value)}`);
120
+ return;
121
+ }
122
+ for (const [key, member] of Object.entries(value)) {
123
+ if (member !== undefined) {
124
+ check(schema.of, member, `${path}.${key}`, mode, issues);
125
+ }
126
+ }
127
+ };
128
+ const checkUnion = (schema, value, path, mode, issues) => {
129
+ const matches = schema.of.some((member) => {
130
+ const nested = [];
131
+ check(member, value, path, mode, nested);
132
+ return nested.length === 0;
133
+ });
134
+ if (!matches) {
135
+ add(issues, path, "does not match any allowed shape");
136
+ }
137
+ };
138
+ const checkers = {
139
+ str: checkString,
140
+ int: checkNumber,
141
+ num: checkNumber,
142
+ arr: checkArray,
143
+ tup: checkTuple,
144
+ map: checkMap,
145
+ obj: checkObject,
146
+ any_of: checkUnion,
147
+ };
148
+ const checkSimple = (schema, value, path, issues) => {
149
+ if (schema.t === "bool" && typeof value !== "boolean") {
150
+ add(issues, path, `expected a boolean, got ${describe(value)}`);
151
+ }
152
+ else if (schema.t === "null" && value !== null) {
153
+ add(issues, path, `expected null, got ${describe(value)}`);
154
+ }
155
+ else if (schema.t === "const" && value !== schema.value) {
156
+ add(issues, path, `must be ${JSON.stringify(schema.value)}`);
157
+ }
158
+ };
159
+ const check = (schema, value, path, mode, issues) => {
160
+ if (issues.length >= MAX_ISSUES || schema.t === "any") {
161
+ return;
162
+ }
163
+ const checker = checkers[schema.t];
164
+ if (checker === undefined) {
165
+ checkSimple(schema, value, path, issues);
166
+ return;
167
+ }
168
+ checker(schema, value, path, mode, issues);
169
+ };
170
+ /** Returns the problems found, at most eight, or an empty array when the value is acceptable. */
171
+ export const validate = (schema, value, mode) => {
172
+ const issues = [];
173
+ check(schema, value, "$", mode, issues);
174
+ return issues;
175
+ };
@@ -0,0 +1,9 @@
1
+ import { type SanctionsClient } from "./generated/client.js";
2
+ import { type ServerOptions } from "./runtime/server-core.js";
3
+ export type { Environment } from "./runtime/environment.js";
4
+ export type { PrivateJwk } from "./runtime/sign.js";
5
+ export type { ServerOptions } from "./runtime/server-core.js";
6
+ /** What the service verifies in the token. */
7
+ export declare const AUDIENCE = "dfat-consolidated-list";
8
+ export declare const SCOPE = "dfat-consolidated-list:read";
9
+ export declare const createSanctionsClient: (options: ServerOptions) => SanctionsClient;
package/dist/server.js ADDED
@@ -0,0 +1,8 @@
1
+ // Generated by @comms-id/forge-transformers from the service's OpenAPI contract. Do not edit: change the contract and regenerate.
2
+ // Server entry: signs a short-lived token for each call with the app's private key.
3
+ import { buildClient } from "./generated/client.js";
4
+ import { createServerTransport } from "./runtime/server-core.js";
5
+ /** What the service verifies in the token. */
6
+ export const AUDIENCE = "dfat-consolidated-list";
7
+ export const SCOPE = "dfat-consolidated-list:read";
8
+ export const createSanctionsClient = (options) => buildClient(createServerTransport(options, { audience: AUDIENCE, scope: SCOPE }));