@certkor/certone 0.0.0-stage → 0.1.1

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.
Files changed (103) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +140 -2
  3. package/dist/cjs/binary.d.ts +8 -0
  4. package/dist/cjs/binary.d.ts.map +1 -0
  5. package/dist/cjs/binary.js +39 -0
  6. package/dist/cjs/binary.js.map +1 -0
  7. package/dist/cjs/client.d.ts +66 -0
  8. package/dist/cjs/client.d.ts.map +1 -0
  9. package/dist/cjs/client.js +401 -0
  10. package/dist/cjs/client.js.map +1 -0
  11. package/dist/cjs/common.d.ts +7 -0
  12. package/dist/cjs/common.d.ts.map +1 -0
  13. package/dist/cjs/common.js +22 -0
  14. package/dist/cjs/common.js.map +1 -0
  15. package/dist/cjs/errors.d.ts +53 -0
  16. package/dist/cjs/errors.d.ts.map +1 -0
  17. package/dist/cjs/errors.js +74 -0
  18. package/dist/cjs/errors.js.map +1 -0
  19. package/dist/cjs/index.d.ts +8 -0
  20. package/dist/cjs/index.d.ts.map +1 -0
  21. package/dist/cjs/index.js +27 -0
  22. package/dist/cjs/index.js.map +1 -0
  23. package/dist/cjs/index.node.d.ts +7 -0
  24. package/dist/cjs/index.node.d.ts.map +1 -0
  25. package/dist/cjs/index.node.js +26 -0
  26. package/dist/cjs/index.node.js.map +1 -0
  27. package/dist/cjs/package.json +1 -0
  28. package/dist/cjs/sha256.d.ts +13 -0
  29. package/dist/cjs/sha256.d.ts.map +1 -0
  30. package/dist/cjs/sha256.js +25 -0
  31. package/dist/cjs/sha256.js.map +1 -0
  32. package/dist/cjs/sha256.node.d.ts +13 -0
  33. package/dist/cjs/sha256.node.d.ts.map +1 -0
  34. package/dist/cjs/sha256.node.js +40 -0
  35. package/dist/cjs/sha256.node.js.map +1 -0
  36. package/dist/cjs/types.d.ts +234 -0
  37. package/dist/cjs/types.d.ts.map +1 -0
  38. package/dist/cjs/types.js +12 -0
  39. package/dist/cjs/types.js.map +1 -0
  40. package/dist/cjs/validate.d.ts +24 -0
  41. package/dist/cjs/validate.d.ts.map +1 -0
  42. package/dist/cjs/validate.js +202 -0
  43. package/dist/cjs/validate.js.map +1 -0
  44. package/dist/cjs/version.d.ts +3 -0
  45. package/dist/cjs/version.d.ts.map +1 -0
  46. package/dist/cjs/version.js +6 -0
  47. package/dist/cjs/version.js.map +1 -0
  48. package/dist/esm/binary.d.ts +8 -0
  49. package/dist/esm/binary.d.ts.map +1 -0
  50. package/dist/esm/binary.js +34 -0
  51. package/dist/esm/binary.js.map +1 -0
  52. package/dist/esm/client.d.ts +66 -0
  53. package/dist/esm/client.d.ts.map +1 -0
  54. package/dist/esm/client.js +397 -0
  55. package/dist/esm/client.js.map +1 -0
  56. package/dist/esm/common.d.ts +7 -0
  57. package/dist/esm/common.d.ts.map +1 -0
  58. package/dist/esm/common.js +6 -0
  59. package/dist/esm/common.js.map +1 -0
  60. package/dist/esm/errors.d.ts +53 -0
  61. package/dist/esm/errors.d.ts.map +1 -0
  62. package/dist/esm/errors.js +69 -0
  63. package/dist/esm/errors.js.map +1 -0
  64. package/dist/esm/index.d.ts +8 -0
  65. package/dist/esm/index.d.ts.map +1 -0
  66. package/dist/esm/index.js +8 -0
  67. package/dist/esm/index.js.map +1 -0
  68. package/dist/esm/index.node.d.ts +7 -0
  69. package/dist/esm/index.node.d.ts.map +1 -0
  70. package/dist/esm/index.node.js +7 -0
  71. package/dist/esm/index.node.js.map +1 -0
  72. package/dist/esm/sha256.d.ts +13 -0
  73. package/dist/esm/sha256.d.ts.map +1 -0
  74. package/dist/esm/sha256.js +21 -0
  75. package/dist/esm/sha256.js.map +1 -0
  76. package/dist/esm/sha256.node.d.ts +13 -0
  77. package/dist/esm/sha256.node.d.ts.map +1 -0
  78. package/dist/esm/sha256.node.js +36 -0
  79. package/dist/esm/sha256.node.js.map +1 -0
  80. package/dist/esm/types.d.ts +234 -0
  81. package/dist/esm/types.d.ts.map +1 -0
  82. package/dist/esm/types.js +11 -0
  83. package/dist/esm/types.js.map +1 -0
  84. package/dist/esm/validate.d.ts +24 -0
  85. package/dist/esm/validate.d.ts.map +1 -0
  86. package/dist/esm/validate.js +193 -0
  87. package/dist/esm/validate.js.map +1 -0
  88. package/dist/esm/version.d.ts +3 -0
  89. package/dist/esm/version.d.ts.map +1 -0
  90. package/dist/esm/version.js +3 -0
  91. package/dist/esm/version.js.map +1 -0
  92. package/package.json +83 -4
  93. package/src/binary.ts +35 -0
  94. package/src/client.ts +480 -0
  95. package/src/common.ts +48 -0
  96. package/src/errors.ts +105 -0
  97. package/src/index.node.ts +6 -0
  98. package/src/index.ts +7 -0
  99. package/src/sha256.node.ts +36 -0
  100. package/src/sha256.ts +26 -0
  101. package/src/types.ts +260 -0
  102. package/src/validate.ts +214 -0
  103. package/src/version.ts +2 -0
package/src/errors.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The single error type every CertOne SDK operation rejects with.
3
+ *
4
+ * `kind` tells the failure modes apart without string matching:
5
+ *
6
+ * - `http` the API answered with a status >= 400 (`status` and `detail` are set);
7
+ * - `network` the request never got a response (DNS, TLS, connection reset, CORS, ...);
8
+ * - `timeout` the per-request timeout or the `waitForReport` deadline elapsed;
9
+ * - `aborted` the caller's `AbortSignal` fired;
10
+ * - `scan_failed` `waitForReport` saw the scan end in `failed` (`detail` is the scan's error);
11
+ * - `invalid_response` a 2xx response whose body is not the documented JSON shape.
12
+ */
13
+ export type CertOneErrorKind =
14
+ | "http"
15
+ | "network"
16
+ | "timeout"
17
+ | "aborted"
18
+ | "scan_failed"
19
+ | "invalid_response";
20
+
21
+ export interface CertOneErrorInit {
22
+ kind: CertOneErrorKind;
23
+ status?: number | null;
24
+ detail?: string;
25
+ method?: string;
26
+ url?: string;
27
+ scanId?: string;
28
+ responseBody?: unknown;
29
+ cause?: unknown;
30
+ }
31
+
32
+ const BRAND = Symbol.for("@certkor/certone.CertOneError");
33
+
34
+ export class CertOneError extends Error {
35
+ override readonly name = "CertOneError";
36
+ readonly kind: CertOneErrorKind;
37
+ /** HTTP status code for `kind === "http"` (and `invalid_response`); otherwise `null`. */
38
+ readonly status: number | null;
39
+ /** The API's `detail` message (or the scan's `error` for `scan_failed`). */
40
+ readonly detail: string;
41
+ /** HTTP method of the failed request, when the failure is tied to one request. */
42
+ readonly method: string | undefined;
43
+ /** Absolute URL of the failed request (never contains credentials). */
44
+ readonly url: string | undefined;
45
+ /** The scan the failure concerns (`scan_failed`, and `waitForReport` timeouts). */
46
+ readonly scanId: string | undefined;
47
+ /** The parsed (or raw text) error body returned by the API, when there was one. */
48
+ readonly responseBody: unknown;
49
+
50
+ constructor(message: string, init: CertOneErrorInit) {
51
+ super(message, init.cause === undefined ? undefined : { cause: init.cause });
52
+ this.kind = init.kind;
53
+ this.status = init.status ?? null;
54
+ this.detail = init.detail ?? "";
55
+ this.method = init.method;
56
+ this.url = init.url;
57
+ this.scanId = init.scanId;
58
+ this.responseBody = init.responseBody;
59
+ Object.defineProperty(this, BRAND, { value: true });
60
+ }
61
+
62
+ /**
63
+ * `true` for any CertOneError, including one thrown by another copy of this package (for
64
+ * example the CommonJS build loaded next to the ESM build), where `instanceof` would fail.
65
+ */
66
+ static is(value: unknown): value is CertOneError {
67
+ return (
68
+ value instanceof CertOneError ||
69
+ (typeof value === "object" && value !== null && (value as Record<symbol, unknown>)[BRAND] === true)
70
+ );
71
+ }
72
+ }
73
+
74
+ const MAX_DETAIL_CHARS = 2000;
75
+
76
+ /**
77
+ * Extract a human-readable message from an API error body.
78
+ *
79
+ * FastAPI sends `{"detail": "..."}` for application errors and `{"detail": [{loc, msg}, ...]}`
80
+ * for request validation errors (422); proxies and load balancers may send HTML or plain text.
81
+ */
82
+ export function extractDetail(body: unknown, rawText: string): string {
83
+ if (typeof body === "object" && body !== null && "detail" in body) {
84
+ const detail = (body as { detail: unknown }).detail;
85
+ if (typeof detail === "string") return detail;
86
+ if (Array.isArray(detail)) {
87
+ const parts = detail.map((entry: unknown) => {
88
+ if (typeof entry === "object" && entry !== null) {
89
+ const { loc, msg } = entry as { loc?: unknown; msg?: unknown };
90
+ const where = Array.isArray(loc) ? loc.map(String).join(".") : "";
91
+ const text = typeof msg === "string" ? msg : JSON.stringify(entry);
92
+ return where ? `${where}: ${text}` : text;
93
+ }
94
+ return String(entry);
95
+ });
96
+ return truncate(parts.join("; "));
97
+ }
98
+ if (detail !== null && detail !== undefined) return truncate(JSON.stringify(detail));
99
+ }
100
+ return truncate(rawText.trim());
101
+ }
102
+
103
+ function truncate(text: string): string {
104
+ return text.length > MAX_DETAIL_CHARS ? `${text.slice(0, MAX_DETAIL_CHARS)}…` : text;
105
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@certkor/certone` for Node.js (selected by the `node` export condition). Identical API to the
3
+ * browser entry; SHA-256 uses `node:crypto` so it works on Node 18 and streams large Blobs.
4
+ */
5
+ export * from "./common.js";
6
+ export { inputDigest, sha256Hex } from "./sha256.node.js";
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `@certkor/certone`: the CertOne control-plane client for browsers and other Web-platform
3
+ * runtimes (Deno, Bun, edge workers). SHA-256 uses Web Crypto. Node.js resolves `index.node`
4
+ * through the package `exports` map instead.
5
+ */
6
+ export * from "./common.js";
7
+ export { inputDigest, sha256Hex } from "./sha256.js";
@@ -0,0 +1,36 @@
1
+ /**
2
+ * SHA-256 via `node:crypto`: works on every supported Node.js release (Node 18 has no global
3
+ * `crypto`) and hashes Blobs as a stream, so large snapshots are not buffered twice.
4
+ */
5
+
6
+ import { createHash } from "node:crypto";
7
+
8
+ import type { BinaryInput } from "./types.js";
9
+
10
+ /** Hex-encoded SHA-256 of the input bytes. */
11
+ export async function sha256Hex(data: BinaryInput): Promise<string> {
12
+ const hash = createHash("sha256");
13
+ if (data instanceof Blob) {
14
+ const reader = data.stream().getReader();
15
+ for (;;) {
16
+ const { done, value } = await reader.read();
17
+ if (done) break;
18
+ hash.update(value);
19
+ }
20
+ } else if (data instanceof ArrayBuffer) {
21
+ hash.update(new Uint8Array(data));
22
+ } else if (ArrayBuffer.isView(data)) {
23
+ hash.update(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
24
+ } else {
25
+ throw new TypeError("expected a Blob, ArrayBuffer or ArrayBufferView (Uint8Array, Buffer, ...)");
26
+ }
27
+ return hash.digest("hex");
28
+ }
29
+
30
+ /**
31
+ * The `input_digest` for `ingestReport`: `sha256:<hex>` over the exact snapshot bytes, which binds
32
+ * the attestation to that input.
33
+ */
34
+ export async function inputDigest(data: BinaryInput): Promise<string> {
35
+ return `sha256:${await sha256Hex(data)}`;
36
+ }
package/src/sha256.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * SHA-256 via the Web Crypto API (browsers, Deno, Bun, Node.js >= 19 global `crypto`).
3
+ * The Node.js entry point replaces this with `node:crypto`, which also streams Blobs.
4
+ */
5
+
6
+ import { toBytes, toHex } from "./binary.js";
7
+ import type { BinaryInput } from "./types.js";
8
+
9
+ /** Hex-encoded SHA-256 of the input bytes. */
10
+ export async function sha256Hex(data: BinaryInput): Promise<string> {
11
+ const subtle = globalThis.crypto?.subtle;
12
+ if (subtle === undefined) {
13
+ throw new TypeError(
14
+ "Web Crypto (crypto.subtle) is unavailable: use a secure context (https) or the Node.js build",
15
+ );
16
+ }
17
+ return toHex(await subtle.digest("SHA-256", await toBytes(data)));
18
+ }
19
+
20
+ /**
21
+ * The `input_digest` for `ingestReport`: `sha256:<hex>` over the exact snapshot bytes, which binds
22
+ * the attestation to that input.
23
+ */
24
+ export async function inputDigest(data: BinaryInput): Promise<string> {
25
+ return `sha256:${await sha256Hex(data)}`;
26
+ }
package/src/types.ts ADDED
@@ -0,0 +1,260 @@
1
+ /**
2
+ * Wire types for the CertOne control-plane API.
3
+ *
4
+ * Response objects keep the API's snake_case field names, exactly as documented in
5
+ * `SPEC.md` and the conformance fixtures, so they can be logged, stored and compared with the
6
+ * REST payloads one-to-one. Timestamps are ISO-8601 strings as sent by the API. Unions that the
7
+ * server may extend (for example scan statuses) accept any string while still offering the known
8
+ * values to editors.
9
+ */
10
+
11
+ /** A string union that still accepts values a newer control plane may introduce. */
12
+ export type OpenUnion<T extends string> = T | (string & Record<never, never>);
13
+
14
+ /** Lifecycle of a scan run. `succeeded` and `failed` are terminal. */
15
+ export type ScanStatus = OpenUnion<"queued" | "running" | "succeeded" | "failed">;
16
+
17
+ export type ScanKind = OpenUnion<"check" | "process" | "correct">;
18
+
19
+ /** Engine verdict for a report. */
20
+ export type VerdictStatus = OpenUnion<"pass" | "fail">;
21
+
22
+ export type Severity = OpenUnion<"low" | "medium" | "high">;
23
+
24
+ /** Lowest severity that makes the verdict fail; `none` never fails. */
25
+ export type FailOn = "low" | "medium" | "high" | "none";
26
+
27
+ /** The surface a submission came from (the server maps unknown values to `api`). */
28
+ export type Environment = "ci" | "jupyter" | "vscode" | "edge" | "api" | "cloud" | "cli";
29
+
30
+ /** `GET /v1/scans/{id}` (fixture `scan.json`). */
31
+ export interface ScanRun {
32
+ readonly id: string;
33
+ readonly kind: ScanKind;
34
+ readonly status: ScanStatus;
35
+ readonly snapshot_ref: string | null;
36
+ readonly created_by: string | null;
37
+ readonly created_at: string;
38
+ readonly finished_at: string | null;
39
+ /** Why the scan failed, when `status === "failed"`. */
40
+ readonly error: string | null;
41
+ }
42
+
43
+ /**
44
+ * A report record (fixture `report.json`). `id` is the record id used by `getReportDocument` and
45
+ * `getAttestation`; `report_id` is the engine's own report identifier.
46
+ */
47
+ export interface Report {
48
+ readonly id: string;
49
+ readonly scan_run_id: string;
50
+ readonly report_id: string;
51
+ readonly verdict_status: VerdictStatus;
52
+ readonly fail_on: FailOn;
53
+ readonly total_issues: number;
54
+ readonly by_severity: Readonly<Record<string, number>>;
55
+ readonly country_code: string | null;
56
+ readonly created_at: string;
57
+ }
58
+
59
+ /** `POST /v1/checks` and `POST /v1/checks/report` (fixtures `check_result.json`, `ingest_result.json`). */
60
+ export interface CheckResult {
61
+ readonly scan_run: ScanRun;
62
+ /** `null` when the submission was queued for the worker pool: use `waitForReport(scan_run.id)`. */
63
+ readonly report: Report | null;
64
+ readonly queued: boolean;
65
+ }
66
+
67
+ /** `POST /v1/process`: a `CheckResult` plus the processing unit's job telemetry when it ran inline. */
68
+ export interface ProcessResult extends CheckResult {
69
+ readonly jobs?: Readonly<Record<string, number>>;
70
+ readonly health?: Readonly<Record<string, unknown>>;
71
+ readonly energy?: Readonly<Record<string, number>>;
72
+ }
73
+
74
+ /** One regulatory citation attached to an issue. */
75
+ export interface RegulatoryReference {
76
+ readonly framework: string;
77
+ readonly article?: string;
78
+ readonly [key: string]: unknown;
79
+ }
80
+
81
+ /** One finding in the engine report document (`compliance-issue.schema.json`). */
82
+ export interface ReportIssue {
83
+ readonly issue_id: string;
84
+ readonly description: string;
85
+ readonly severity: Severity;
86
+ readonly detected_by: string;
87
+ readonly compliance_topic?: string;
88
+ /** The AI-system component the issue concerns (input | model | output | pipeline | config). */
89
+ readonly component?: string;
90
+ readonly regulatory_references: readonly RegulatoryReference[];
91
+ readonly location: Readonly<Record<string, unknown>>;
92
+ readonly suggested_fix?: string;
93
+ readonly rule_path?: string;
94
+ readonly [key: string]: unknown;
95
+ }
96
+
97
+ export interface ReportVerdict {
98
+ readonly status: VerdictStatus;
99
+ readonly fail_on: FailOn;
100
+ readonly reason?: string;
101
+ readonly [key: string]: unknown;
102
+ }
103
+
104
+ export interface ReportSummary {
105
+ readonly total_issues: number;
106
+ readonly by_severity: Readonly<Record<string, number>>;
107
+ readonly by_topic?: Readonly<Record<string, number>>;
108
+ readonly by_component?: Readonly<Record<string, number>>;
109
+ readonly rules_evaluated?: number;
110
+ readonly rules_triggered?: number;
111
+ readonly [key: string]: unknown;
112
+ }
113
+
114
+ /**
115
+ * The full engine report (`GET /v1/reports/{id}/document`, fixture `report_document_excerpt.json`).
116
+ * Only the stable core is typed; every other section is available as `unknown`.
117
+ */
118
+ export interface ReportDocument {
119
+ readonly report_id: string;
120
+ readonly verdict: ReportVerdict;
121
+ readonly summary: ReportSummary;
122
+ readonly issues: readonly ReportIssue[];
123
+ readonly [key: string]: unknown;
124
+ }
125
+
126
+ /**
127
+ * The conditional compliance attestation for a passing report
128
+ * (`GET /v1/reports/{id}/attestation`, fixture `attestation.json`).
129
+ */
130
+ export interface Attestation {
131
+ readonly attestation_id: string;
132
+ readonly input_version: string;
133
+ readonly issued_at: string;
134
+ readonly signature: string;
135
+ readonly signature_algorithm: string;
136
+ readonly test_status?: Readonly<Record<string, unknown>>;
137
+ readonly issuance?: Readonly<Record<string, unknown>>;
138
+ readonly conditional_validity?: {
139
+ readonly valid: boolean;
140
+ readonly covers?: readonly string[];
141
+ readonly [key: string]: unknown;
142
+ };
143
+ readonly fingerprint?: {
144
+ readonly algorithm: string;
145
+ readonly value: string;
146
+ readonly [key: string]: unknown;
147
+ };
148
+ readonly log?: readonly unknown[];
149
+ readonly [key: string]: unknown;
150
+ }
151
+
152
+ /** An AI system and its rolled-up posture (`GET /v1/systems`, fixture `systems.json`). */
153
+ export interface AISystem {
154
+ readonly id: string;
155
+ readonly slug: string;
156
+ readonly name: string;
157
+ readonly lifecycle: string;
158
+ readonly owner_team_id: string | null;
159
+ readonly description: string | null;
160
+ readonly created_at: string;
161
+ readonly regions: readonly string[];
162
+ readonly environments: readonly string[];
163
+ readonly standards: readonly string[];
164
+ readonly scans: number;
165
+ readonly open_issues: number;
166
+ readonly last_verdict: VerdictStatus | null;
167
+ readonly attested: boolean;
168
+ readonly attestation_status: OpenUnion<"valid" | "revoked" | "none">;
169
+ readonly risk: OpenUnion<"low" | "medium" | "high" | "unknown">;
170
+ readonly last_evaluated: string | null;
171
+ }
172
+
173
+ /**
174
+ * A snapshot or any other binary input: a `Blob` (or `File`), an `ArrayBuffer`, or a typed-array
175
+ * view such as `Uint8Array` (a Node.js `Buffer` is one).
176
+ */
177
+ export type BinaryInput = Blob | ArrayBuffer | ArrayBufferView;
178
+
179
+ /** Per-call transport options accepted by every operation. */
180
+ export interface RequestOptions {
181
+ /** Cancels the call; the promise rejects with a `CertOneError` of kind `aborted`. */
182
+ readonly signal?: AbortSignal | undefined;
183
+ /** Overrides the client's per-request timeout (milliseconds) for this call. */
184
+ readonly timeoutMs?: number | undefined;
185
+ }
186
+
187
+ /** Multipart form fields for `submitCheck` (all optional; the server applies the defaults shown). */
188
+ export interface ScanOptions extends RequestOptions {
189
+ /** AI system name (auto-registered on first scan). Default: derived by the server. */
190
+ readonly asset?: string | undefined;
191
+ /** Default `api`. */
192
+ readonly environment?: Environment | undefined;
193
+ /** Origin region, for example `EU` or `US`. Default `ZZ`. */
194
+ readonly countryCode?: string | undefined;
195
+ /** Default `high`. */
196
+ readonly failOn?: FailOn | undefined;
197
+ /** Policy packs (array or comma-separated). Default: auto-matched from the AI BOM. */
198
+ readonly packs?: string | readonly string[] | undefined;
199
+ /** Stable source reference, for example `git:org/repo@sha`. */
200
+ readonly snapshotRef?: string | undefined;
201
+ /** Commit the scan is about. */
202
+ readonly commitHash?: string | undefined;
203
+ /** File name sent for the `snapshot` part. Default `snapshot.tar.gz`. */
204
+ readonly filename?: string | undefined;
205
+ }
206
+
207
+ /** `submitProcess` options: the scan options plus the confidential-compute backend. */
208
+ export interface ProcessOptions extends ScanOptions {
209
+ /** Confidential-compute backend id (`GET /v1/capabilities/tee`). Default `amd_sev_snp`. */
210
+ readonly tee?: OpenUnion<"amd_sev_snp" | "intel_tdx"> | undefined;
211
+ }
212
+
213
+ /** Fields sent with a run-at-source report (`POST /v1/checks/report`). */
214
+ export interface IngestOptions extends RequestOptions {
215
+ readonly asset?: string | undefined;
216
+ /** Default `api`. */
217
+ readonly environment?: Environment | undefined;
218
+ /** Default `ZZ`. */
219
+ readonly countryCode?: string | undefined;
220
+ readonly snapshotRef?: string | undefined;
221
+ /**
222
+ * `sha256:<hex>` of the exact artifact the report covers; binds the attestation to that input.
223
+ * Compute it with `inputDigest(snapshotBytes)`.
224
+ */
225
+ readonly inputDigest?: string | undefined;
226
+ /** Repository full name (`owner/name`) the report is about. */
227
+ readonly repo?: string | undefined;
228
+ readonly commitHash?: string | undefined;
229
+ }
230
+
231
+ /** `waitForReport` options. */
232
+ export interface WaitOptions {
233
+ /** Overall deadline in milliseconds. Default 900 000 (15 min). */
234
+ readonly timeoutMs?: number | undefined;
235
+ /** Delay between polls in milliseconds. Default 2 000. */
236
+ readonly intervalMs?: number | undefined;
237
+ /** Cancels the wait; rejects with a `CertOneError` of kind `aborted`. */
238
+ readonly signal?: AbortSignal | undefined;
239
+ /** Per-poll request timeout; defaults to the client's request timeout. */
240
+ readonly requestTimeoutMs?: number | undefined;
241
+ }
242
+
243
+ /** A `fetch`-compatible function (inject one for tests, proxies, retries or custom TLS agents). */
244
+ export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
245
+
246
+ /** Supplies the bearer token per request, so short-lived OIDC tokens can be refreshed. */
247
+ export type TokenProvider = () => string | Promise<string>;
248
+
249
+ export interface CertOneClientOptions {
250
+ /** Control-plane base URL, for example `https://api.yourco.com`. */
251
+ readonly baseUrl: string;
252
+ /** Tenant API key (`ck_...`) or OIDC ID token, or a function returning one. Never logged. */
253
+ readonly token?: string | TokenProvider | undefined;
254
+ /** Per-request timeout in milliseconds. Default 30 000. */
255
+ readonly timeoutMs?: number | undefined;
256
+ /** `fetch` implementation. Default: the global `fetch` (Node >= 18, browsers). */
257
+ readonly fetch?: FetchLike | undefined;
258
+ /** Extra headers sent with every request (for example tracing or proxy headers). */
259
+ readonly headers?: Readonly<Record<string, string>> | undefined;
260
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Runtime checks for API responses.
3
+ *
4
+ * A 2xx body that does not have the documented shape (a misrouted proxy, an incompatible control
5
+ * plane version) is rejected with `CertOneError(kind: "invalid_response")` at the SDK boundary
6
+ * instead of surfacing later as an `undefined` deep inside the caller's code. Only the documented,
7
+ * stable fields are checked; additional fields are kept as-is so newer servers stay compatible.
8
+ */
9
+
10
+ import { CertOneError } from "./errors.js";
11
+ import type {
12
+ AISystem,
13
+ Attestation,
14
+ CheckResult,
15
+ ProcessResult,
16
+ Report,
17
+ ReportDocument,
18
+ ScanRun,
19
+ } from "./types.js";
20
+
21
+ type Json = Record<string, unknown>;
22
+
23
+ class Checker {
24
+ constructor(private readonly what: string) {}
25
+
26
+ fail(path: string, expected: string, value: unknown): never {
27
+ const got = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
28
+ throw new CertOneError(
29
+ `invalid ${this.what} from the CertOne API: ${path} must be ${expected} (got ${got})`,
30
+ { kind: "invalid_response", detail: `${path} must be ${expected}` },
31
+ );
32
+ }
33
+
34
+ object(value: unknown, path: string): Json {
35
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
36
+ this.fail(path, "an object", value);
37
+ }
38
+ return value as Json;
39
+ }
40
+
41
+ array(value: unknown, path: string): unknown[] {
42
+ if (!Array.isArray(value)) this.fail(path, "an array", value);
43
+ return value;
44
+ }
45
+
46
+ string(o: Json, key: string, path: string): void {
47
+ if (typeof o[key] !== "string") this.fail(`${path}.${key}`, "a string", o[key]);
48
+ }
49
+
50
+ nullableString(o: Json, key: string, path: string): void {
51
+ const v = o[key];
52
+ if (v !== null && typeof v !== "string") this.fail(`${path}.${key}`, "a string or null", v);
53
+ }
54
+
55
+ optionalString(o: Json, key: string, path: string): void {
56
+ const v = o[key];
57
+ if (v !== undefined && typeof v !== "string") this.fail(`${path}.${key}`, "a string", v);
58
+ }
59
+
60
+ number(o: Json, key: string, path: string): void {
61
+ const v = o[key];
62
+ if (typeof v !== "number" || !Number.isFinite(v)) this.fail(`${path}.${key}`, "a number", v);
63
+ }
64
+
65
+ boolean(o: Json, key: string, path: string): void {
66
+ if (typeof o[key] !== "boolean") this.fail(`${path}.${key}`, "a boolean", o[key]);
67
+ }
68
+
69
+ counts(o: Json, key: string, path: string): void {
70
+ const counts = this.object(o[key], `${path}.${key}`);
71
+ for (const [k, v] of Object.entries(counts)) {
72
+ if (typeof v !== "number") this.fail(`${path}.${key}.${k}`, "a number", v);
73
+ }
74
+ }
75
+
76
+ stringArray(o: Json, key: string, path: string): void {
77
+ this.array(o[key], `${path}.${key}`).forEach((v, i) => {
78
+ if (typeof v !== "string") this.fail(`${path}.${key}[${i}]`, "a string", v);
79
+ });
80
+ }
81
+ }
82
+
83
+ function checkScanRun(c: Checker, value: unknown, path: string): ScanRun {
84
+ const o = c.object(value, path);
85
+ c.string(o, "id", path);
86
+ c.string(o, "kind", path);
87
+ c.string(o, "status", path);
88
+ c.nullableString(o, "snapshot_ref", path);
89
+ c.nullableString(o, "created_by", path);
90
+ c.string(o, "created_at", path);
91
+ c.nullableString(o, "finished_at", path);
92
+ c.nullableString(o, "error", path);
93
+ return o as unknown as ScanRun;
94
+ }
95
+
96
+ function checkReport(c: Checker, value: unknown, path: string): Report {
97
+ const o = c.object(value, path);
98
+ c.string(o, "id", path);
99
+ c.string(o, "scan_run_id", path);
100
+ c.string(o, "report_id", path);
101
+ c.string(o, "verdict_status", path);
102
+ c.string(o, "fail_on", path);
103
+ c.number(o, "total_issues", path);
104
+ c.counts(o, "by_severity", path);
105
+ if (o["country_code"] !== undefined) c.nullableString(o, "country_code", path);
106
+ c.string(o, "created_at", path);
107
+ return o as unknown as Report;
108
+ }
109
+
110
+ function checkCheckResult(c: Checker, value: unknown): Json {
111
+ const o = c.object(value, "body");
112
+ checkScanRun(c, o["scan_run"], "body.scan_run");
113
+ if (o["report"] !== null && o["report"] !== undefined) checkReport(c, o["report"], "body.report");
114
+ if (o["queued"] !== undefined) c.boolean(o, "queued", "body");
115
+ // Normalise the two fields a pydantic default may omit, without dropping anything else.
116
+ return { ...o, report: o["report"] ?? null, queued: o["queued"] ?? false };
117
+ }
118
+
119
+ /** Validate a `GET /v1/scans/{id}` body. */
120
+ export function parseScanRun(value: unknown): ScanRun {
121
+ return checkScanRun(new Checker("ScanRun"), value, "body");
122
+ }
123
+
124
+ /** Validate a report record (`GET /v1/scans/{id}/report`, `GET /v1/reports/{id}`). */
125
+ export function parseReport(value: unknown): Report {
126
+ return checkReport(new Checker("Report"), value, "body");
127
+ }
128
+
129
+ /** Validate a `POST /v1/checks` or `POST /v1/checks/report` body. */
130
+ export function parseCheckResult(value: unknown): CheckResult {
131
+ return checkCheckResult(new Checker("CheckResult"), value) as unknown as CheckResult;
132
+ }
133
+
134
+ /** Validate a `POST /v1/process` body. */
135
+ export function parseProcessResult(value: unknown): ProcessResult {
136
+ return checkCheckResult(new Checker("ProcessResult"), value) as unknown as ProcessResult;
137
+ }
138
+
139
+ /** Validate the core of a full engine report document (`GET /v1/reports/{id}/document`). */
140
+ export function parseReportDocument(value: unknown): ReportDocument {
141
+ const c = new Checker("ReportDocument");
142
+ const o = c.object(value, "body");
143
+ c.string(o, "report_id", "body");
144
+ const verdict = c.object(o["verdict"], "body.verdict");
145
+ c.string(verdict, "status", "body.verdict");
146
+ c.string(verdict, "fail_on", "body.verdict");
147
+ c.optionalString(verdict, "reason", "body.verdict");
148
+ const summary = c.object(o["summary"], "body.summary");
149
+ c.number(summary, "total_issues", "body.summary");
150
+ c.counts(summary, "by_severity", "body.summary");
151
+ c.array(o["issues"], "body.issues").forEach((item, i) => {
152
+ const path = `body.issues[${i}]`;
153
+ const issue = c.object(item, path);
154
+ c.string(issue, "issue_id", path);
155
+ c.string(issue, "description", path);
156
+ c.string(issue, "severity", path);
157
+ c.string(issue, "detected_by", path);
158
+ c.optionalString(issue, "compliance_topic", path);
159
+ c.optionalString(issue, "component", path);
160
+ c.optionalString(issue, "suggested_fix", path);
161
+ c.optionalString(issue, "rule_path", path);
162
+ c.array(issue["regulatory_references"], `${path}.regulatory_references`);
163
+ c.object(issue["location"], `${path}.location`);
164
+ });
165
+ return o as unknown as ReportDocument;
166
+ }
167
+
168
+ /** Validate a `GET /v1/reports/{id}/attestation` body. */
169
+ export function parseAttestation(value: unknown): Attestation {
170
+ const c = new Checker("Attestation");
171
+ const o = c.object(value, "body");
172
+ c.string(o, "attestation_id", "body");
173
+ c.string(o, "input_version", "body");
174
+ c.string(o, "issued_at", "body");
175
+ c.string(o, "signature", "body");
176
+ c.string(o, "signature_algorithm", "body");
177
+ if (o["conditional_validity"] !== undefined) {
178
+ const cv = c.object(o["conditional_validity"], "body.conditional_validity");
179
+ c.boolean(cv, "valid", "body.conditional_validity");
180
+ }
181
+ if (o["fingerprint"] !== undefined) {
182
+ const fp = c.object(o["fingerprint"], "body.fingerprint");
183
+ c.string(fp, "algorithm", "body.fingerprint");
184
+ c.string(fp, "value", "body.fingerprint");
185
+ }
186
+ return o as unknown as Attestation;
187
+ }
188
+
189
+ /** Validate a `GET /v1/systems` body. */
190
+ export function parseSystems(value: unknown): AISystem[] {
191
+ const c = new Checker("AISystem list");
192
+ return c.array(value, "body").map((item, i) => {
193
+ const path = `body[${i}]`;
194
+ const o = c.object(item, path);
195
+ c.string(o, "id", path);
196
+ c.string(o, "slug", path);
197
+ c.string(o, "name", path);
198
+ c.string(o, "lifecycle", path);
199
+ c.nullableString(o, "owner_team_id", path);
200
+ c.nullableString(o, "description", path);
201
+ c.string(o, "created_at", path);
202
+ c.stringArray(o, "regions", path);
203
+ c.stringArray(o, "environments", path);
204
+ c.stringArray(o, "standards", path);
205
+ c.number(o, "scans", path);
206
+ c.number(o, "open_issues", path);
207
+ c.nullableString(o, "last_verdict", path);
208
+ c.boolean(o, "attested", path);
209
+ c.string(o, "attestation_status", path);
210
+ c.string(o, "risk", path);
211
+ c.nullableString(o, "last_evaluated", path);
212
+ return o as unknown as AISystem;
213
+ });
214
+ }
package/src/version.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** The SDK version (kept in step with `package.json`). */
2
+ export const VERSION = "0.1.1";