@certkor/certone 0.0.0-stage → 0.1.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.
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/package.json CHANGED
@@ -1,6 +1,85 @@
1
1
  {
2
2
  "name": "@certkor/certone",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Typed JavaScript/TypeScript client for the CertOne control-plane API (Node.js and browsers, zero runtime dependencies).",
5
+ "license": "Apache-2.0",
6
+ "author": "Certkor AI",
7
+ "homepage": "https://certkor.ai",
8
+ "keywords": [
9
+ "certone",
10
+ "certkor",
11
+ "ai-compliance",
12
+ "ai-governance",
13
+ "attestation",
14
+ "sdk"
15
+ ],
16
+ "type": "module",
17
+ "sideEffects": false,
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "main": "./dist/cjs/index.node.js",
22
+ "module": "./dist/esm/index.js",
23
+ "types": "./dist/cjs/index.node.d.ts",
24
+ "browser": {
25
+ "./dist/cjs/index.node.js": "./dist/cjs/index.js",
26
+ "./dist/esm/index.node.js": "./dist/esm/index.js"
27
+ },
28
+ "exports": {
29
+ ".": {
30
+ "node": {
31
+ "import": {
32
+ "types": "./dist/esm/index.node.d.ts",
33
+ "default": "./dist/esm/index.node.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/cjs/index.node.d.ts",
37
+ "default": "./dist/cjs/index.node.js"
38
+ }
39
+ },
40
+ "import": {
41
+ "types": "./dist/esm/index.d.ts",
42
+ "default": "./dist/esm/index.js"
43
+ },
44
+ "require": {
45
+ "types": "./dist/cjs/index.d.ts",
46
+ "default": "./dist/cjs/index.js"
47
+ }
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ "files": [
52
+ "dist",
53
+ "src",
54
+ "README.md",
55
+ "LICENSE"
56
+ ],
57
+ "scripts": {
58
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
59
+ "build": "npm run clean && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && node -e \"require('node:fs').writeFileSync('dist/cjs/package.json', JSON.stringify({type:'commonjs'}))\"",
60
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.browser.json",
61
+ "typecheck:examples": "tsc -p examples/tsconfig.json",
62
+ "test": "vitest run",
63
+ "check": "npm run typecheck && npm run build && npm run typecheck:examples && npm test && npm run lint:package",
64
+ "prepack": "npm run build",
65
+ "lint:package": "attw --pack ."
66
+ },
67
+ "devDependencies": {
68
+ "@arethetypeswrong/cli": "0.18.5",
69
+ "@types/node": "20.19.43",
70
+ "typescript": "5.9.3",
71
+ "vitest": "3.2.7"
72
+ },
73
+ "repository": {
74
+ "type": "git",
75
+ "url": "git+https://github.com/certkorai/certone-sdks.git",
76
+ "directory": "js"
77
+ },
78
+ "bugs": {
79
+ "url": "https://github.com/certkorai/certone-sdks/issues"
80
+ },
81
+ "publishConfig": {
82
+ "access": "public",
83
+ "provenance": true
84
+ }
85
+ }
package/src/binary.ts ADDED
@@ -0,0 +1,35 @@
1
+ import type { BinaryInput } from "./types.js";
2
+
3
+ function isBlob(value: unknown): value is Blob {
4
+ return typeof Blob !== "undefined" && value instanceof Blob;
5
+ }
6
+
7
+ /** A view over the input's bytes backed by a plain `ArrayBuffer` (copies only shared memory). */
8
+ function bytesView(input: ArrayBuffer | ArrayBufferView): Uint8Array<ArrayBuffer> {
9
+ if (input instanceof ArrayBuffer) return new Uint8Array(input);
10
+ if (ArrayBuffer.isView(input)) {
11
+ const view = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
12
+ return input.buffer instanceof ArrayBuffer ? (view as Uint8Array<ArrayBuffer>) : view.slice();
13
+ }
14
+ throw new TypeError("expected a Blob, ArrayBuffer or ArrayBufferView (Uint8Array, Buffer, ...)");
15
+ }
16
+
17
+ /** Wrap any supported binary input as a `Blob` for a multipart upload (no copy for Blobs). */
18
+ export function toBlob(input: BinaryInput, type = "application/gzip"): Blob {
19
+ if (isBlob(input)) return input;
20
+ return new Blob([bytesView(input)], { type });
21
+ }
22
+
23
+ /** The input's bytes, reading a `Blob` fully into memory. */
24
+ export async function toBytes(input: BinaryInput): Promise<Uint8Array<ArrayBuffer>> {
25
+ if (isBlob(input)) return new Uint8Array(await input.arrayBuffer());
26
+ return bytesView(input);
27
+ }
28
+
29
+ /** Lower-case hex encoding. */
30
+ export function toHex(bytes: ArrayBuffer | Uint8Array): string {
31
+ const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
32
+ let out = "";
33
+ for (const byte of view) out += byte.toString(16).padStart(2, "0");
34
+ return out;
35
+ }
package/src/client.ts ADDED
@@ -0,0 +1,480 @@
1
+ import { toBlob } from "./binary.js";
2
+ import { CertOneError, extractDetail } from "./errors.js";
3
+ import type {
4
+ AISystem,
5
+ Attestation,
6
+ BinaryInput,
7
+ CertOneClientOptions,
8
+ CheckResult,
9
+ FetchLike,
10
+ IngestOptions,
11
+ ProcessOptions,
12
+ ProcessResult,
13
+ Report,
14
+ ReportDocument,
15
+ RequestOptions,
16
+ ScanOptions,
17
+ ScanRun,
18
+ TokenProvider,
19
+ WaitOptions,
20
+ } from "./types.js";
21
+ import {
22
+ parseAttestation,
23
+ parseCheckResult,
24
+ parseProcessResult,
25
+ parseReport,
26
+ parseReportDocument,
27
+ parseScanRun,
28
+ parseSystems,
29
+ } from "./validate.js";
30
+
31
+ /** Default per-request timeout (SPEC: 30 s). */
32
+ export const DEFAULT_TIMEOUT_MS = 30_000;
33
+ /** Default `waitForReport` deadline (SPEC: 900 s). */
34
+ export const DEFAULT_WAIT_TIMEOUT_MS = 900_000;
35
+ /** Default `waitForReport` poll interval (SPEC: 2 s). */
36
+ export const DEFAULT_POLL_INTERVAL_MS = 2_000;
37
+
38
+ // setTimeout stores delays as a signed 32-bit integer; longer delays fire immediately.
39
+ const MAX_TIMER_MS = 2_147_483_647;
40
+
41
+ interface Call {
42
+ readonly method: "GET" | "POST";
43
+ readonly path: string;
44
+ readonly json?: unknown;
45
+ readonly form?: FormData;
46
+ readonly signal?: AbortSignal | undefined;
47
+ readonly timeoutMs?: number | undefined;
48
+ }
49
+
50
+ interface RawResponse {
51
+ readonly status: number;
52
+ readonly value: unknown;
53
+ readonly method: string;
54
+ readonly url: string;
55
+ }
56
+
57
+ /**
58
+ * Client for the CertOne control-plane REST API (`SPEC.md`).
59
+ *
60
+ * ```ts
61
+ * const certone = new CertOneClient({ baseUrl: "https://api.yourco.com", token: process.env.CERTONE_API_KEY });
62
+ * const { scan_run, report } = await certone.submitCheck(snapshotBytes, { asset: "Fraud Scorer" });
63
+ * ```
64
+ *
65
+ * Every method rejects with {@link CertOneError} on HTTP errors (status >= 400), network
66
+ * failures, timeouts, aborts and malformed responses. The token is held in a private field and is
67
+ * never included in errors, logs or `JSON.stringify(client)`.
68
+ */
69
+ export class CertOneClient {
70
+ /** Normalised base URL (no trailing slash). */
71
+ readonly baseUrl: string;
72
+ /** Per-request timeout in milliseconds. */
73
+ readonly timeoutMs: number;
74
+
75
+ readonly #token: string | TokenProvider | undefined;
76
+ readonly #fetch: FetchLike;
77
+ readonly #headers: Readonly<Record<string, string>>;
78
+
79
+ constructor(options: CertOneClientOptions) {
80
+ if (typeof options !== "object" || options === null || typeof options.baseUrl !== "string") {
81
+ throw new TypeError("CertOneClient: options.baseUrl is required");
82
+ }
83
+ this.baseUrl = normaliseBaseUrl(options.baseUrl);
84
+ this.timeoutMs = positiveMs(options.timeoutMs, "timeoutMs", DEFAULT_TIMEOUT_MS);
85
+
86
+ const token = options.token;
87
+ if (token !== undefined && typeof token !== "string" && typeof token !== "function") {
88
+ throw new TypeError("CertOneClient: token must be a string or a function returning one");
89
+ }
90
+ if (token === "") throw new TypeError("CertOneClient: token must not be empty");
91
+ if (typeof token === "string") checkTokenChars(token);
92
+ this.#token = token;
93
+
94
+ if (options.fetch !== undefined && typeof options.fetch !== "function") {
95
+ throw new TypeError("CertOneClient: fetch must be a function");
96
+ }
97
+ // Resolve the global lazily (and call it unbound-safe) so polyfills installed later still apply.
98
+ this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
99
+
100
+ const headers: Record<string, string> = {};
101
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
102
+ const key = name.toLowerCase();
103
+ if (key === "authorization") {
104
+ throw new TypeError("CertOneClient: pass credentials with options.token, not options.headers");
105
+ }
106
+ const text = String(value);
107
+ if (/[\r\n\0]/.test(text)) {
108
+ throw new TypeError(`CertOneClient: header ${JSON.stringify(name)} contains a line break or NUL`);
109
+ }
110
+ headers[key] = text;
111
+ }
112
+ this.#headers = Object.freeze(headers);
113
+ }
114
+
115
+ /** `POST /v1/checks`: static compliance check of a project snapshot (`.tar.gz`). */
116
+ async submitCheck(snapshot: BinaryInput, options: ScanOptions = {}): Promise<CheckResult> {
117
+ const form = scanForm(snapshot, options);
118
+ return this.#call(
119
+ { method: "POST", path: "/v1/checks", form, signal: options.signal, timeoutMs: options.timeoutMs },
120
+ parseCheckResult,
121
+ );
122
+ }
123
+
124
+ /**
125
+ * `POST /v1/process`: full processing (static + dynamic) on the confidential worker pool. On the
126
+ * asynchronous pool the result has `queued: true` and `report: null`; use {@link waitForReport}.
127
+ */
128
+ async submitProcess(snapshot: BinaryInput, options: ProcessOptions = {}): Promise<ProcessResult> {
129
+ const form = scanForm(snapshot, options);
130
+ if (options.tee !== undefined) form.append("tee", options.tee);
131
+ return this.#call(
132
+ { method: "POST", path: "/v1/process", form, signal: options.signal, timeoutMs: options.timeoutMs },
133
+ parseProcessResult,
134
+ );
135
+ }
136
+
137
+ /** `GET /v1/scans/{id}`. */
138
+ async getScan(scanId: string, options: RequestOptions = {}): Promise<ScanRun> {
139
+ return this.#call(
140
+ { method: "GET", path: `/v1/scans/${pathId(scanId, "scanId")}`, ...options },
141
+ parseScanRun,
142
+ );
143
+ }
144
+
145
+ /**
146
+ * Polls `GET /v1/scans/{id}` until the scan is `succeeded` or `failed`, then returns its report
147
+ * (`GET /v1/scans/{id}/report`). A `failed` scan rejects with kind `scan_failed` carrying the
148
+ * scan's `error`; exceeding `timeoutMs` rejects with kind `timeout`.
149
+ */
150
+ async waitForReport(scanId: string, options: WaitOptions = {}): Promise<Report> {
151
+ const id = pathId(scanId, "scanId");
152
+ const timeoutMs = positiveMs(options.timeoutMs, "timeoutMs", DEFAULT_WAIT_TIMEOUT_MS);
153
+ const intervalMs = nonNegativeMs(options.intervalMs, "intervalMs", DEFAULT_POLL_INTERVAL_MS);
154
+ const requestTimeoutMs = positiveMs(options.requestTimeoutMs, "requestTimeoutMs", this.timeoutMs);
155
+ const { signal } = options;
156
+ const deadline = Date.now() + timeoutMs;
157
+ // Each request is bounded by the overall deadline as well as its own timeout.
158
+ const budget = (): number => Math.max(1, Math.min(requestTimeoutMs, deadline - Date.now()));
159
+
160
+ for (;;) {
161
+ const scan = await this.getScan(scanId, { signal, timeoutMs: budget() });
162
+ if (scan.status === "failed") {
163
+ const detail = scan.error ?? "the scan failed without an error message";
164
+ throw new CertOneError(`scan ${scanId} failed: ${detail}`, { kind: "scan_failed", detail, scanId });
165
+ }
166
+ if (scan.status === "succeeded") {
167
+ return this.#call(
168
+ { method: "GET", path: `/v1/scans/${id}/report`, signal, timeoutMs: budget() },
169
+ parseReport,
170
+ );
171
+ }
172
+ const remaining = deadline - Date.now();
173
+ if (remaining <= 0) {
174
+ throw new CertOneError(
175
+ `scan ${scanId} did not finish within ${timeoutMs} ms (last status: ${scan.status})`,
176
+ { kind: "timeout", detail: `last status: ${scan.status}`, scanId },
177
+ );
178
+ }
179
+ await sleep(Math.min(intervalMs, remaining), signal);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * `GET /v1/reports/{id}/document`: the full engine report (`verdict`, `summary`, `issues`).
185
+ * `reportId` is the report record's `id` (for example `report.id`), not the engine `report_id`.
186
+ */
187
+ async getReportDocument(reportId: string, options: RequestOptions = {}): Promise<ReportDocument> {
188
+ return this.#call(
189
+ { method: "GET", path: `/v1/reports/${pathId(reportId, "reportId")}/document`, ...options },
190
+ parseReportDocument,
191
+ );
192
+ }
193
+
194
+ /**
195
+ * `GET /v1/reports/{id}/attestation`: the conditional compliance attestation. Rejects with an
196
+ * `http` error of status 404 when the verdict did not pass (no attestation was issued).
197
+ */
198
+ async getAttestation(reportId: string, options: RequestOptions = {}): Promise<Attestation> {
199
+ return this.#call(
200
+ { method: "GET", path: `/v1/reports/${pathId(reportId, "reportId")}/attestation`, ...options },
201
+ parseAttestation,
202
+ );
203
+ }
204
+
205
+ /**
206
+ * `POST /v1/checks/report`: submit an engine report computed where the model lives
207
+ * (run-at-source). The model and code never leave the caller's environment; pass
208
+ * `inputDigest: await inputDigest(snapshotBytes)` to bind the attestation to the exact input.
209
+ */
210
+ async ingestReport(report: Readonly<Record<string, unknown>>, options: IngestOptions = {}): Promise<CheckResult> {
211
+ if (typeof report !== "object" || report === null || Array.isArray(report)) {
212
+ throw new TypeError("ingestReport: report must be a JSON object (an engine report)");
213
+ }
214
+ const body = {
215
+ report,
216
+ asset: options.asset,
217
+ environment: options.environment,
218
+ country_code: options.countryCode,
219
+ snapshot_ref: options.snapshotRef,
220
+ input_digest: options.inputDigest,
221
+ repo: options.repo,
222
+ commit_hash: options.commitHash,
223
+ };
224
+ return this.#call(
225
+ {
226
+ method: "POST",
227
+ path: "/v1/checks/report",
228
+ json: body,
229
+ signal: options.signal,
230
+ timeoutMs: options.timeoutMs,
231
+ },
232
+ parseCheckResult,
233
+ );
234
+ }
235
+
236
+ /** `GET /v1/systems`: the tenant's AI-system inventory with each system's posture. */
237
+ async listSystems(options: RequestOptions = {}): Promise<AISystem[]> {
238
+ return this.#call({ method: "GET", path: "/v1/systems", ...options }, parseSystems);
239
+ }
240
+
241
+ /** Never expose the token through `JSON.stringify(client)`. */
242
+ toJSON(): { baseUrl: string; timeoutMs: number } {
243
+ return { baseUrl: this.baseUrl, timeoutMs: this.timeoutMs };
244
+ }
245
+
246
+ async #call<T>(call: Call, parse: (value: unknown) => T): Promise<T> {
247
+ const raw = await this.#send(call);
248
+ try {
249
+ return parse(raw.value);
250
+ } catch (err) {
251
+ if (CertOneError.is(err) && err.kind === "invalid_response") {
252
+ throw new CertOneError(err.message, {
253
+ kind: "invalid_response",
254
+ status: raw.status,
255
+ detail: err.detail,
256
+ method: raw.method,
257
+ url: raw.url,
258
+ responseBody: raw.value,
259
+ });
260
+ }
261
+ throw err;
262
+ }
263
+ }
264
+
265
+ async #send(call: Call): Promise<RawResponse> {
266
+ const { method } = call;
267
+ const url = `${this.baseUrl}${call.path}`;
268
+ const timeoutMs = positiveMs(call.timeoutMs, "timeoutMs", this.timeoutMs);
269
+ const external = call.signal;
270
+ if (external?.aborted) throw abortedError(external, method, url);
271
+
272
+ const headers: Record<string, string> = { ...this.#headers, accept: "application/json" };
273
+ const token = await this.#resolveToken();
274
+ if (token) headers["authorization"] = `Bearer ${token}`;
275
+ let body: BodyInit | null = null;
276
+ if (call.json !== undefined) {
277
+ headers["content-type"] = "application/json";
278
+ body = JSON.stringify(call.json);
279
+ } else if (call.form !== undefined) {
280
+ body = call.form; // fetch sets the multipart content-type with its boundary
281
+ }
282
+
283
+ const controller = new AbortController();
284
+ let timedOut = false;
285
+ const timer = setTimeout(() => {
286
+ timedOut = true;
287
+ controller.abort();
288
+ }, Math.min(timeoutMs, MAX_TIMER_MS));
289
+ const onAbort = (): void => controller.abort();
290
+ external?.addEventListener("abort", onAbort, { once: true });
291
+
292
+ let status: number;
293
+ let text: string;
294
+ try {
295
+ const response = await this.#fetch(url, { method, headers, body, signal: controller.signal });
296
+ status = response.status;
297
+ // Reading the body stays under the same timeout: a stalled body must not hang the caller.
298
+ text = await response.text();
299
+ } catch (err) {
300
+ if (timedOut) {
301
+ throw new CertOneError(`${method} ${url} timed out after ${timeoutMs} ms`, {
302
+ kind: "timeout",
303
+ method,
304
+ url,
305
+ cause: err,
306
+ });
307
+ }
308
+ if (external?.aborted) throw abortedError(external, method, url);
309
+ if (CertOneError.is(err)) throw err;
310
+ throw new CertOneError(`${method} ${url} failed: ${describe(err)}`, {
311
+ kind: "network",
312
+ method,
313
+ url,
314
+ cause: err,
315
+ });
316
+ } finally {
317
+ clearTimeout(timer);
318
+ external?.removeEventListener("abort", onAbort);
319
+ }
320
+
321
+ const parsed = parseJson(text);
322
+ if (status >= 400) {
323
+ const detail = extractDetail(parsed.ok ? parsed.value : undefined, text);
324
+ throw new CertOneError(detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`, {
325
+ kind: "http",
326
+ status,
327
+ detail,
328
+ method,
329
+ url,
330
+ responseBody: parsed.ok ? parsed.value : text,
331
+ });
332
+ }
333
+ if (status < 200 || status >= 300 || !parsed.ok) {
334
+ const why = parsed.ok ? "unexpected status" : "the response body is not JSON";
335
+ throw new CertOneError(`HTTP ${status} from ${method} ${url}: ${why}`, {
336
+ kind: "invalid_response",
337
+ status,
338
+ detail: why,
339
+ method,
340
+ url,
341
+ responseBody: text,
342
+ });
343
+ }
344
+ return { status, value: parsed.value, method, url };
345
+ }
346
+
347
+ async #resolveToken(): Promise<string | undefined> {
348
+ const token = this.#token;
349
+ if (typeof token !== "function") return token;
350
+ const value = await token();
351
+ if (typeof value !== "string" || value === "") {
352
+ throw new TypeError("CertOneClient: the token provider must return a non-empty string");
353
+ }
354
+ checkTokenChars(value);
355
+ return value;
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Bearer tokens (API keys, JWTs) are visible ASCII. Reject anything else up front: a stray CR/LF
361
+ * or space (typically from a CRLF env file) would otherwise make `fetch` throw an "invalid header
362
+ * value" error whose message embeds the token. The token itself is never echoed.
363
+ */
364
+ function checkTokenChars(token: string): void {
365
+ if (!/^[\x21-\x7e]+$/.test(token)) {
366
+ throw new TypeError(
367
+ "CertOneClient: the token contains whitespace or non-printable characters " +
368
+ "(check for a trailing newline or carriage return)",
369
+ );
370
+ }
371
+ }
372
+
373
+ function scanForm(snapshot: BinaryInput, options: ScanOptions): FormData {
374
+ const form = new FormData();
375
+ form.append("snapshot", toBlob(snapshot), options.filename ?? "snapshot.tar.gz");
376
+ const packs = typeof options.packs === "string" ? options.packs : options.packs?.join(",");
377
+ const fields: ReadonlyArray<readonly [string, string | undefined]> = [
378
+ ["asset", options.asset],
379
+ ["environment", options.environment],
380
+ ["country_code", options.countryCode],
381
+ ["fail_on", options.failOn],
382
+ ["packs", packs],
383
+ ["snapshot_ref", options.snapshotRef],
384
+ ["commit_hash", options.commitHash],
385
+ ];
386
+ for (const [name, value] of fields) {
387
+ if (value !== undefined) form.append(name, value);
388
+ }
389
+ return form;
390
+ }
391
+
392
+ function normaliseBaseUrl(raw: string): string {
393
+ let url: URL;
394
+ try {
395
+ url = new URL(raw);
396
+ } catch {
397
+ throw new TypeError(`CertOneClient: baseUrl is not a valid URL: ${JSON.stringify(raw)}`);
398
+ }
399
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
400
+ throw new TypeError("CertOneClient: baseUrl must be an http(s) URL");
401
+ }
402
+ if (url.username || url.password) {
403
+ throw new TypeError("CertOneClient: baseUrl must not embed credentials; use options.token");
404
+ }
405
+ if (url.search || url.hash) {
406
+ throw new TypeError("CertOneClient: baseUrl must not have a query string or fragment");
407
+ }
408
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
409
+ }
410
+
411
+ function pathId(value: string, name: string): string {
412
+ if (typeof value !== "string" || value.trim() === "") {
413
+ throw new TypeError(`${name} must be a non-empty string`);
414
+ }
415
+ return encodeURIComponent(value);
416
+ }
417
+
418
+ function positiveMs(value: number | undefined, name: string, fallback: number): number {
419
+ if (value === undefined) return fallback;
420
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
421
+ throw new RangeError(`${name} must be a positive number of milliseconds`);
422
+ }
423
+ return value;
424
+ }
425
+
426
+ function nonNegativeMs(value: number | undefined, name: string, fallback: number): number {
427
+ if (value === undefined) return fallback;
428
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
429
+ throw new RangeError(`${name} must be a non-negative number of milliseconds`);
430
+ }
431
+ return value;
432
+ }
433
+
434
+ function parseJson(text: string): { ok: true; value: unknown } | { ok: false } {
435
+ if (text.trim() === "") return { ok: false };
436
+ try {
437
+ return { ok: true, value: JSON.parse(text) as unknown };
438
+ } catch {
439
+ return { ok: false };
440
+ }
441
+ }
442
+
443
+ function abortedError(signal: AbortSignal, method?: string, url?: string): CertOneError {
444
+ const message = method && url ? `${method} ${url} was aborted by the caller` : "Aborted by the caller";
445
+ return new CertOneError(message, {
446
+ kind: "aborted",
447
+ ...(method === undefined ? {} : { method }),
448
+ ...(url === undefined ? {} : { url }),
449
+ cause: signal.reason,
450
+ });
451
+ }
452
+
453
+ /** A short reason for a network failure (undici nests the system error in `cause`). */
454
+ function describe(err: unknown): string {
455
+ if (!(err instanceof Error)) return String(err);
456
+ const cause = err.cause;
457
+ if (cause instanceof Error) {
458
+ const code = (cause as { code?: unknown }).code;
459
+ return `${err.message} (${typeof code === "string" ? `${code}: ` : ""}${cause.message})`;
460
+ }
461
+ return err.message;
462
+ }
463
+
464
+ function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
465
+ return new Promise((resolve, reject) => {
466
+ if (signal?.aborted) {
467
+ reject(abortedError(signal));
468
+ return;
469
+ }
470
+ const onAbort = (): void => {
471
+ clearTimeout(timer);
472
+ reject(abortedError(signal as AbortSignal));
473
+ };
474
+ const timer = setTimeout(() => {
475
+ signal?.removeEventListener("abort", onAbort);
476
+ resolve();
477
+ }, Math.min(ms, MAX_TIMER_MS));
478
+ signal?.addEventListener("abort", onAbort, { once: true });
479
+ });
480
+ }
package/src/common.ts ADDED
@@ -0,0 +1,48 @@
1
+ // Everything both entry points share; they differ only in the SHA-256 implementation.
2
+ export {
3
+ CertOneClient,
4
+ DEFAULT_POLL_INTERVAL_MS,
5
+ DEFAULT_TIMEOUT_MS,
6
+ DEFAULT_WAIT_TIMEOUT_MS,
7
+ } from "./client.js";
8
+ export { CertOneError } from "./errors.js";
9
+ export type { CertOneErrorInit, CertOneErrorKind } from "./errors.js";
10
+ export type {
11
+ AISystem,
12
+ Attestation,
13
+ BinaryInput,
14
+ CertOneClientOptions,
15
+ CheckResult,
16
+ Environment,
17
+ FailOn,
18
+ FetchLike,
19
+ IngestOptions,
20
+ OpenUnion,
21
+ ProcessOptions,
22
+ ProcessResult,
23
+ RegulatoryReference,
24
+ Report,
25
+ ReportDocument,
26
+ ReportIssue,
27
+ ReportSummary,
28
+ ReportVerdict,
29
+ RequestOptions,
30
+ ScanKind,
31
+ ScanOptions,
32
+ ScanRun,
33
+ ScanStatus,
34
+ Severity,
35
+ TokenProvider,
36
+ VerdictStatus,
37
+ WaitOptions,
38
+ } from "./types.js";
39
+ export {
40
+ parseAttestation,
41
+ parseCheckResult,
42
+ parseProcessResult,
43
+ parseReport,
44
+ parseReportDocument,
45
+ parseScanRun,
46
+ parseSystems,
47
+ } from "./validate.js";
48
+ export { VERSION } from "./version.js";