@proof-layer/sdk 1.0.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,112 @@
1
+ type Verdict = "EXECUTE" | "SHADOW" | "REVIEW" | "BLOCK";
2
+ type ActionType = "READ_RESOURCE" | "DELETE_RESOURCE" | "TRANSACT_PAYMENT" | "EXPORT_DATA" | "MODIFY_ACCESS" | "WRITE_RESOURCE";
3
+ interface EvaluateOptions {
4
+ actionType: ActionType;
5
+ resourceId: string;
6
+ agentId: string;
7
+ parameters?: Record<string, unknown>;
8
+ idempotencyKey?: string;
9
+ requestedAt?: string;
10
+ timeoutPolicy?: "fail_closed" | "fail_open";
11
+ }
12
+ interface EvaluateResult {
13
+ verdict: Verdict;
14
+ reason: string;
15
+ receiptId: string;
16
+ receipt: Receipt;
17
+ governance_mode?: string;
18
+ }
19
+ interface Receipt {
20
+ receiptId: string;
21
+ tenantId: string;
22
+ eventType: string;
23
+ agentId: string;
24
+ verdict: string;
25
+ policyPackHash: string;
26
+ payloadHash: string;
27
+ signature?: {
28
+ algorithm: string;
29
+ keyId: string;
30
+ value: string;
31
+ };
32
+ seq: number;
33
+ canonicalPayload?: Record<string, unknown>;
34
+ createdAt: string;
35
+ }
36
+ interface ListReceiptsOptions {
37
+ limit?: number;
38
+ offset?: number;
39
+ }
40
+ interface VerifyChainResult {
41
+ valid: boolean;
42
+ receiptCount: number;
43
+ merkleRoot: string;
44
+ receipts: {
45
+ receiptId: string;
46
+ payloadHash: string;
47
+ signatureValid: boolean;
48
+ }[];
49
+ }
50
+ interface ProofLayerClientOptions {
51
+ /** Your Proof Layer API key (vdk_...) */
52
+ apiKey: string;
53
+ /** Override the base URL — useful for self-hosted deployments. Defaults to https://prooflayer.world999labs.com */
54
+ baseUrl?: string;
55
+ /** Maximum number of retry attempts on transient errors (5xx, network). Default: 3 */
56
+ maxRetries?: number;
57
+ /** Tenant ID — required for multi-tenant operations, optional for single-tenant. */
58
+ tenantId?: string;
59
+ }
60
+
61
+ declare class ProofLayerClient {
62
+ private readonly apiKey;
63
+ private readonly baseUrl;
64
+ private readonly maxRetries;
65
+ private readonly tenantId;
66
+ constructor(options: ProofLayerClientOptions);
67
+ private authHeaders;
68
+ /**
69
+ * Internal fetch wrapper with exponential-backoff retry on transient errors.
70
+ */
71
+ private fetchWithRetry;
72
+ private request;
73
+ /**
74
+ * Submit an action proposal for governance evaluation.
75
+ * The Guardian returns a verdict (EXECUTE | SHADOW | REVIEW | BLOCK).
76
+ */
77
+ evaluate(options: EvaluateOptions): Promise<EvaluateResult>;
78
+ /**
79
+ * Retrieve a single receipt by ID.
80
+ */
81
+ getReceipt(receiptId: string): Promise<Receipt>;
82
+ /**
83
+ * List receipts for the authenticated tenant.
84
+ */
85
+ listReceipts(options?: ListReceiptsOptions): Promise<{
86
+ receipts: Receipt[];
87
+ count: number;
88
+ }>;
89
+ /**
90
+ * Verify the cryptographic integrity of a receipt.
91
+ */
92
+ verifyReceipt(receiptId: string): Promise<{
93
+ valid: boolean;
94
+ receipt: Receipt;
95
+ }>;
96
+ /**
97
+ * Verify the full audit chain (Merkle root integrity) for the tenant.
98
+ */
99
+ verifyChain(): Promise<VerifyChainResult>;
100
+ /**
101
+ * Retrieve usage statistics for the current billing period.
102
+ */
103
+ getUsage(): Promise<{
104
+ tenant_id: string;
105
+ tier: string;
106
+ receipts_this_month: number;
107
+ receipts_included: number;
108
+ percent_used: number;
109
+ }>;
110
+ }
111
+
112
+ export { type ActionType, type EvaluateOptions, type EvaluateResult, type ListReceiptsOptions, ProofLayerClient, type ProofLayerClientOptions, type Receipt, type Verdict, type VerifyChainResult };
@@ -0,0 +1,112 @@
1
+ type Verdict = "EXECUTE" | "SHADOW" | "REVIEW" | "BLOCK";
2
+ type ActionType = "READ_RESOURCE" | "DELETE_RESOURCE" | "TRANSACT_PAYMENT" | "EXPORT_DATA" | "MODIFY_ACCESS" | "WRITE_RESOURCE";
3
+ interface EvaluateOptions {
4
+ actionType: ActionType;
5
+ resourceId: string;
6
+ agentId: string;
7
+ parameters?: Record<string, unknown>;
8
+ idempotencyKey?: string;
9
+ requestedAt?: string;
10
+ timeoutPolicy?: "fail_closed" | "fail_open";
11
+ }
12
+ interface EvaluateResult {
13
+ verdict: Verdict;
14
+ reason: string;
15
+ receiptId: string;
16
+ receipt: Receipt;
17
+ governance_mode?: string;
18
+ }
19
+ interface Receipt {
20
+ receiptId: string;
21
+ tenantId: string;
22
+ eventType: string;
23
+ agentId: string;
24
+ verdict: string;
25
+ policyPackHash: string;
26
+ payloadHash: string;
27
+ signature?: {
28
+ algorithm: string;
29
+ keyId: string;
30
+ value: string;
31
+ };
32
+ seq: number;
33
+ canonicalPayload?: Record<string, unknown>;
34
+ createdAt: string;
35
+ }
36
+ interface ListReceiptsOptions {
37
+ limit?: number;
38
+ offset?: number;
39
+ }
40
+ interface VerifyChainResult {
41
+ valid: boolean;
42
+ receiptCount: number;
43
+ merkleRoot: string;
44
+ receipts: {
45
+ receiptId: string;
46
+ payloadHash: string;
47
+ signatureValid: boolean;
48
+ }[];
49
+ }
50
+ interface ProofLayerClientOptions {
51
+ /** Your Proof Layer API key (vdk_...) */
52
+ apiKey: string;
53
+ /** Override the base URL — useful for self-hosted deployments. Defaults to https://prooflayer.world999labs.com */
54
+ baseUrl?: string;
55
+ /** Maximum number of retry attempts on transient errors (5xx, network). Default: 3 */
56
+ maxRetries?: number;
57
+ /** Tenant ID — required for multi-tenant operations, optional for single-tenant. */
58
+ tenantId?: string;
59
+ }
60
+
61
+ declare class ProofLayerClient {
62
+ private readonly apiKey;
63
+ private readonly baseUrl;
64
+ private readonly maxRetries;
65
+ private readonly tenantId;
66
+ constructor(options: ProofLayerClientOptions);
67
+ private authHeaders;
68
+ /**
69
+ * Internal fetch wrapper with exponential-backoff retry on transient errors.
70
+ */
71
+ private fetchWithRetry;
72
+ private request;
73
+ /**
74
+ * Submit an action proposal for governance evaluation.
75
+ * The Guardian returns a verdict (EXECUTE | SHADOW | REVIEW | BLOCK).
76
+ */
77
+ evaluate(options: EvaluateOptions): Promise<EvaluateResult>;
78
+ /**
79
+ * Retrieve a single receipt by ID.
80
+ */
81
+ getReceipt(receiptId: string): Promise<Receipt>;
82
+ /**
83
+ * List receipts for the authenticated tenant.
84
+ */
85
+ listReceipts(options?: ListReceiptsOptions): Promise<{
86
+ receipts: Receipt[];
87
+ count: number;
88
+ }>;
89
+ /**
90
+ * Verify the cryptographic integrity of a receipt.
91
+ */
92
+ verifyReceipt(receiptId: string): Promise<{
93
+ valid: boolean;
94
+ receipt: Receipt;
95
+ }>;
96
+ /**
97
+ * Verify the full audit chain (Merkle root integrity) for the tenant.
98
+ */
99
+ verifyChain(): Promise<VerifyChainResult>;
100
+ /**
101
+ * Retrieve usage statistics for the current billing period.
102
+ */
103
+ getUsage(): Promise<{
104
+ tenant_id: string;
105
+ tier: string;
106
+ receipts_this_month: number;
107
+ receipts_included: number;
108
+ percent_used: number;
109
+ }>;
110
+ }
111
+
112
+ export { type ActionType, type EvaluateOptions, type EvaluateResult, type ListReceiptsOptions, ProofLayerClient, type ProofLayerClientOptions, type Receipt, type Verdict, type VerifyChainResult };
package/dist/index.js ADDED
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ProofLayerClient: () => ProofLayerClient
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/client.ts
28
+ var import_crypto = require("crypto");
29
+ var DEFAULT_BASE_URL = "https://prooflayer.world999labs.com";
30
+ var MAX_BACKOFF_MS = 4e3;
31
+ function backoffMs(attempt) {
32
+ return Math.min(250 * Math.pow(2, attempt), MAX_BACKOFF_MS);
33
+ }
34
+ function sleep(ms) {
35
+ return new Promise((resolve) => setTimeout(resolve, ms));
36
+ }
37
+ var ProofLayerClient = class {
38
+ apiKey;
39
+ baseUrl;
40
+ maxRetries;
41
+ tenantId;
42
+ constructor(options) {
43
+ if (!options.apiKey) throw new Error("ProofLayerClient: apiKey is required");
44
+ this.apiKey = options.apiKey;
45
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
46
+ this.maxRetries = options.maxRetries ?? 3;
47
+ this.tenantId = options.tenantId;
48
+ }
49
+ authHeaders() {
50
+ return {
51
+ "Content-Type": "application/json",
52
+ "X-Api-Key": this.apiKey
53
+ };
54
+ }
55
+ /**
56
+ * Internal fetch wrapper with exponential-backoff retry on transient errors.
57
+ */
58
+ async fetchWithRetry(path, init, attempt = 0) {
59
+ const url = `${this.baseUrl}${path}`;
60
+ let lastErr;
61
+ for (let i = 0; i <= this.maxRetries; i++) {
62
+ if (i > 0) await sleep(backoffMs(i - 1));
63
+ try {
64
+ const resp = await fetch(url, init);
65
+ if (resp.status >= 500 && i < this.maxRetries) {
66
+ lastErr = new Error(`HTTP ${resp.status}`);
67
+ continue;
68
+ }
69
+ return resp;
70
+ } catch (err) {
71
+ lastErr = err;
72
+ if (i >= this.maxRetries) break;
73
+ }
74
+ }
75
+ throw lastErr ?? new Error("Request failed after retries");
76
+ }
77
+ async request(path, init) {
78
+ const resp = await this.fetchWithRetry(path, {
79
+ ...init,
80
+ headers: { ...this.authHeaders(), ...init.headers ?? {} }
81
+ });
82
+ if (!resp.ok) {
83
+ const body = await resp.json().catch(() => ({}));
84
+ const msg = body?.message ?? body?.error ?? `HTTP ${resp.status}`;
85
+ throw Object.assign(new Error(`Proof Layer API error: ${msg}`), {
86
+ status: resp.status,
87
+ body
88
+ });
89
+ }
90
+ return resp.json();
91
+ }
92
+ /**
93
+ * Submit an action proposal for governance evaluation.
94
+ * The Guardian returns a verdict (EXECUTE | SHADOW | REVIEW | BLOCK).
95
+ */
96
+ async evaluate(options) {
97
+ const tenantId = this.tenantId;
98
+ const payload = {
99
+ schema_version: "1.0",
100
+ action_type: options.actionType,
101
+ resource_id: options.resourceId,
102
+ agent_id: options.agentId,
103
+ parameters: options.parameters ?? {},
104
+ idempotency_key: options.idempotencyKey ?? (0, import_crypto.randomUUID)(),
105
+ requested_at: options.requestedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
106
+ guardian_timeout_policy: options.timeoutPolicy ?? "fail_closed"
107
+ };
108
+ if (tenantId) payload.tenant_id = tenantId;
109
+ return this.request("/v1/evaluate", {
110
+ method: "POST",
111
+ body: JSON.stringify(payload)
112
+ });
113
+ }
114
+ /**
115
+ * Retrieve a single receipt by ID.
116
+ */
117
+ async getReceipt(receiptId) {
118
+ return this.request(`/v1/receipts/${encodeURIComponent(receiptId)}`, {
119
+ method: "GET"
120
+ });
121
+ }
122
+ /**
123
+ * List receipts for the authenticated tenant.
124
+ */
125
+ async listReceipts(options = {}) {
126
+ const params = new URLSearchParams();
127
+ if (options.limit) params.set("limit", String(options.limit));
128
+ if (options.offset) params.set("offset", String(options.offset));
129
+ const qs = params.toString() ? `?${params}` : "";
130
+ return this.request(`/v1/receipts${qs}`, {
131
+ method: "GET"
132
+ });
133
+ }
134
+ /**
135
+ * Verify the cryptographic integrity of a receipt.
136
+ */
137
+ async verifyReceipt(receiptId) {
138
+ return this.request("/v1/receipts/verify", {
139
+ method: "POST",
140
+ body: JSON.stringify({ receipt_id: receiptId })
141
+ });
142
+ }
143
+ /**
144
+ * Verify the full audit chain (Merkle root integrity) for the tenant.
145
+ */
146
+ async verifyChain() {
147
+ return this.request("/v1/receipts/verify-chain", {
148
+ method: "POST",
149
+ body: JSON.stringify({})
150
+ });
151
+ }
152
+ /**
153
+ * Retrieve usage statistics for the current billing period.
154
+ */
155
+ async getUsage() {
156
+ return this.request("/v1/usage", { method: "GET" });
157
+ }
158
+ };
159
+ // Annotate the CommonJS export names for ESM import in node:
160
+ 0 && (module.exports = {
161
+ ProofLayerClient
162
+ });
163
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts"],"sourcesContent":["export { ProofLayerClient } from \"./client\";\nexport type {\n ProofLayerClientOptions,\n EvaluateOptions,\n EvaluateResult,\n Receipt,\n ListReceiptsOptions,\n VerifyChainResult,\n Verdict,\n ActionType,\n} from \"./types\";\n","import { randomUUID } from \"crypto\";\nimport type {\n EvaluateOptions,\n EvaluateResult,\n Receipt,\n ListReceiptsOptions,\n VerifyChainResult,\n ProofLayerClientOptions,\n} from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://prooflayer.world999labs.com\";\nconst MAX_BACKOFF_MS = 4_000;\n\n/**\n * Exponential backoff delay, doubling per attempt, capped at MAX_BACKOFF_MS.\n * attempt 0 → 250ms, 1 → 500ms, 2 → 1000ms, 3 → 2000ms, 4+ → 4000ms.\n */\nfunction backoffMs(attempt: number): number {\n return Math.min(250 * Math.pow(2, attempt), MAX_BACKOFF_MS);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class ProofLayerClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly maxRetries: number;\n private readonly tenantId: string | undefined;\n\n constructor(options: ProofLayerClientOptions) {\n if (!options.apiKey) throw new Error(\"ProofLayerClient: apiKey is required\");\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n this.maxRetries = options.maxRetries ?? 3;\n this.tenantId = options.tenantId;\n }\n\n private authHeaders(): Record<string, string> {\n return {\n \"Content-Type\": \"application/json\",\n \"X-Api-Key\": this.apiKey,\n };\n }\n\n /**\n * Internal fetch wrapper with exponential-backoff retry on transient errors.\n */\n private async fetchWithRetry(\n path: string,\n init: RequestInit,\n attempt = 0,\n ): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n let lastErr: unknown;\n for (let i = 0; i <= this.maxRetries; i++) {\n if (i > 0) await sleep(backoffMs(i - 1));\n try {\n const resp = await fetch(url, init);\n // Retry on 5xx server errors only\n if (resp.status >= 500 && i < this.maxRetries) {\n lastErr = new Error(`HTTP ${resp.status}`);\n continue;\n }\n return resp;\n } catch (err) {\n lastErr = err;\n if (i >= this.maxRetries) break;\n }\n }\n throw lastErr ?? new Error(\"Request failed after retries\");\n }\n\n private async request<T>(path: string, init: RequestInit): Promise<T> {\n const resp = await this.fetchWithRetry(path, {\n ...init,\n headers: { ...this.authHeaders(), ...(init.headers as Record<string, string> ?? {}) },\n });\n if (!resp.ok) {\n const body = await resp.json().catch(() => ({}));\n const msg = (body as any)?.message ?? (body as any)?.error ?? `HTTP ${resp.status}`;\n throw Object.assign(new Error(`Proof Layer API error: ${msg}`), {\n status: resp.status,\n body,\n });\n }\n return resp.json() as Promise<T>;\n }\n\n /**\n * Submit an action proposal for governance evaluation.\n * The Guardian returns a verdict (EXECUTE | SHADOW | REVIEW | BLOCK).\n */\n async evaluate(options: EvaluateOptions): Promise<EvaluateResult> {\n const tenantId = this.tenantId;\n const payload: Record<string, unknown> = {\n schema_version: \"1.0\",\n action_type: options.actionType,\n resource_id: options.resourceId,\n agent_id: options.agentId,\n parameters: options.parameters ?? {},\n idempotency_key: options.idempotencyKey ?? randomUUID(),\n requested_at: options.requestedAt ?? new Date().toISOString(),\n guardian_timeout_policy: options.timeoutPolicy ?? \"fail_closed\",\n };\n if (tenantId) payload.tenant_id = tenantId;\n return this.request<EvaluateResult>(\"/v1/evaluate\", {\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n }\n\n /**\n * Retrieve a single receipt by ID.\n */\n async getReceipt(receiptId: string): Promise<Receipt> {\n return this.request<Receipt>(`/v1/receipts/${encodeURIComponent(receiptId)}`, {\n method: \"GET\",\n });\n }\n\n /**\n * List receipts for the authenticated tenant.\n */\n async listReceipts(options: ListReceiptsOptions = {}): Promise<{ receipts: Receipt[]; count: number }> {\n const params = new URLSearchParams();\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.offset) params.set(\"offset\", String(options.offset));\n const qs = params.toString() ? `?${params}` : \"\";\n return this.request<{ receipts: Receipt[]; count: number }>(`/v1/receipts${qs}`, {\n method: \"GET\",\n });\n }\n\n /**\n * Verify the cryptographic integrity of a receipt.\n */\n async verifyReceipt(receiptId: string): Promise<{ valid: boolean; receipt: Receipt }> {\n return this.request<{ valid: boolean; receipt: Receipt }>(\"/v1/receipts/verify\", {\n method: \"POST\",\n body: JSON.stringify({ receipt_id: receiptId }),\n });\n }\n\n /**\n * Verify the full audit chain (Merkle root integrity) for the tenant.\n */\n async verifyChain(): Promise<VerifyChainResult> {\n return this.request<VerifyChainResult>(\"/v1/receipts/verify-chain\", {\n method: \"POST\",\n body: JSON.stringify({}),\n });\n }\n\n /**\n * Retrieve usage statistics for the current billing period.\n */\n async getUsage(): Promise<{\n tenant_id: string;\n tier: string;\n receipts_this_month: number;\n receipts_included: number;\n percent_used: number;\n }> {\n return this.request(\"/v1/usage\", { method: \"GET\" });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA2B;AAU3B,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AAMvB,SAAS,UAAU,SAAyB;AAC1C,SAAO,KAAK,IAAI,MAAM,KAAK,IAAI,GAAG,OAAO,GAAG,cAAc;AAC5D;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IA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M,KAAK,OAAO,SAAS,IAAI,IAAI,MAAM,KAAK;AAC9C,WAAO,KAAK,QAAgD,eAAe,EAAE,IAAI;AAAA,MAC/E,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAAc,WAAkE;AACpF,WAAO,KAAK,QAA8C,uBAAuB;AAAA,MAC/E,QAAQ;AAAA,MACR,MAAM,KAAK,UAAU,EAAE,YAAY,UAAU,CAAC;AAAA,IAChD,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAA0C;AAC9C,WAAO,KAAK,QAA2B,6BAA6B;AAAA,MAClE,QAAQ;AAAA,MACR,MAAM,KAAK,UAAU,CAAC,CAAC;AAAA,IACzB,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAMH;AACD,WAAO,KAAK,QAAQ,aAAa,EAAE,QAAQ,MAAM,CAAC;AAAA,EACpD;AACF;","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,136 @@
1
+ // src/client.ts
2
+ import { randomUUID } from "crypto";
3
+ var DEFAULT_BASE_URL = "https://prooflayer.world999labs.com";
4
+ var MAX_BACKOFF_MS = 4e3;
5
+ function backoffMs(attempt) {
6
+ return Math.min(250 * Math.pow(2, attempt), MAX_BACKOFF_MS);
7
+ }
8
+ function sleep(ms) {
9
+ return new Promise((resolve) => setTimeout(resolve, ms));
10
+ }
11
+ var ProofLayerClient = class {
12
+ apiKey;
13
+ baseUrl;
14
+ maxRetries;
15
+ tenantId;
16
+ constructor(options) {
17
+ if (!options.apiKey) throw new Error("ProofLayerClient: apiKey is required");
18
+ this.apiKey = options.apiKey;
19
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
20
+ this.maxRetries = options.maxRetries ?? 3;
21
+ this.tenantId = options.tenantId;
22
+ }
23
+ authHeaders() {
24
+ return {
25
+ "Content-Type": "application/json",
26
+ "X-Api-Key": this.apiKey
27
+ };
28
+ }
29
+ /**
30
+ * Internal fetch wrapper with exponential-backoff retry on transient errors.
31
+ */
32
+ async fetchWithRetry(path, init, attempt = 0) {
33
+ const url = `${this.baseUrl}${path}`;
34
+ let lastErr;
35
+ for (let i = 0; i <= this.maxRetries; i++) {
36
+ if (i > 0) await sleep(backoffMs(i - 1));
37
+ try {
38
+ const resp = await fetch(url, init);
39
+ if (resp.status >= 500 && i < this.maxRetries) {
40
+ lastErr = new Error(`HTTP ${resp.status}`);
41
+ continue;
42
+ }
43
+ return resp;
44
+ } catch (err) {
45
+ lastErr = err;
46
+ if (i >= this.maxRetries) break;
47
+ }
48
+ }
49
+ throw lastErr ?? new Error("Request failed after retries");
50
+ }
51
+ async request(path, init) {
52
+ const resp = await this.fetchWithRetry(path, {
53
+ ...init,
54
+ headers: { ...this.authHeaders(), ...init.headers ?? {} }
55
+ });
56
+ if (!resp.ok) {
57
+ const body = await resp.json().catch(() => ({}));
58
+ const msg = body?.message ?? body?.error ?? `HTTP ${resp.status}`;
59
+ throw Object.assign(new Error(`Proof Layer API error: ${msg}`), {
60
+ status: resp.status,
61
+ body
62
+ });
63
+ }
64
+ return resp.json();
65
+ }
66
+ /**
67
+ * Submit an action proposal for governance evaluation.
68
+ * The Guardian returns a verdict (EXECUTE | SHADOW | REVIEW | BLOCK).
69
+ */
70
+ async evaluate(options) {
71
+ const tenantId = this.tenantId;
72
+ const payload = {
73
+ schema_version: "1.0",
74
+ action_type: options.actionType,
75
+ resource_id: options.resourceId,
76
+ agent_id: options.agentId,
77
+ parameters: options.parameters ?? {},
78
+ idempotency_key: options.idempotencyKey ?? randomUUID(),
79
+ requested_at: options.requestedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
80
+ guardian_timeout_policy: options.timeoutPolicy ?? "fail_closed"
81
+ };
82
+ if (tenantId) payload.tenant_id = tenantId;
83
+ return this.request("/v1/evaluate", {
84
+ method: "POST",
85
+ body: JSON.stringify(payload)
86
+ });
87
+ }
88
+ /**
89
+ * Retrieve a single receipt by ID.
90
+ */
91
+ async getReceipt(receiptId) {
92
+ return this.request(`/v1/receipts/${encodeURIComponent(receiptId)}`, {
93
+ method: "GET"
94
+ });
95
+ }
96
+ /**
97
+ * List receipts for the authenticated tenant.
98
+ */
99
+ async listReceipts(options = {}) {
100
+ const params = new URLSearchParams();
101
+ if (options.limit) params.set("limit", String(options.limit));
102
+ if (options.offset) params.set("offset", String(options.offset));
103
+ const qs = params.toString() ? `?${params}` : "";
104
+ return this.request(`/v1/receipts${qs}`, {
105
+ method: "GET"
106
+ });
107
+ }
108
+ /**
109
+ * Verify the cryptographic integrity of a receipt.
110
+ */
111
+ async verifyReceipt(receiptId) {
112
+ return this.request("/v1/receipts/verify", {
113
+ method: "POST",
114
+ body: JSON.stringify({ receipt_id: receiptId })
115
+ });
116
+ }
117
+ /**
118
+ * Verify the full audit chain (Merkle root integrity) for the tenant.
119
+ */
120
+ async verifyChain() {
121
+ return this.request("/v1/receipts/verify-chain", {
122
+ method: "POST",
123
+ body: JSON.stringify({})
124
+ });
125
+ }
126
+ /**
127
+ * Retrieve usage statistics for the current billing period.
128
+ */
129
+ async getUsage() {
130
+ return this.request("/v1/usage", { method: "GET" });
131
+ }
132
+ };
133
+ export {
134
+ ProofLayerClient
135
+ };
136
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import { randomUUID } from \"crypto\";\nimport type {\n EvaluateOptions,\n EvaluateResult,\n Receipt,\n ListReceiptsOptions,\n VerifyChainResult,\n ProofLayerClientOptions,\n} from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://prooflayer.world999labs.com\";\nconst MAX_BACKOFF_MS = 4_000;\n\n/**\n * Exponential backoff delay, doubling per attempt, capped at MAX_BACKOFF_MS.\n * attempt 0 → 250ms, 1 → 500ms, 2 → 1000ms, 3 → 2000ms, 4+ → 4000ms.\n */\nfunction backoffMs(attempt: number): number {\n return Math.min(250 * Math.pow(2, attempt), MAX_BACKOFF_MS);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport class ProofLayerClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly maxRetries: number;\n private readonly tenantId: string | undefined;\n\n constructor(options: ProofLayerClientOptions) {\n if (!options.apiKey) throw new Error(\"ProofLayerClient: apiKey is required\");\n this.apiKey = options.apiKey;\n this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n this.maxRetries = options.maxRetries ?? 3;\n this.tenantId = options.tenantId;\n }\n\n private authHeaders(): Record<string, string> {\n return {\n \"Content-Type\": \"application/json\",\n \"X-Api-Key\": this.apiKey,\n };\n }\n\n /**\n * Internal fetch wrapper with exponential-backoff retry on transient errors.\n */\n private async fetchWithRetry(\n path: string,\n init: RequestInit,\n attempt = 0,\n ): Promise<Response> {\n const url = `${this.baseUrl}${path}`;\n let lastErr: unknown;\n for (let i = 0; i <= this.maxRetries; i++) {\n if (i > 0) await sleep(backoffMs(i - 1));\n try {\n const resp = await fetch(url, init);\n // Retry on 5xx server errors only\n if (resp.status >= 500 && i < this.maxRetries) {\n lastErr = new Error(`HTTP ${resp.status}`);\n continue;\n }\n return resp;\n } catch (err) {\n lastErr = err;\n if (i >= this.maxRetries) break;\n }\n }\n throw lastErr ?? new Error(\"Request failed after retries\");\n }\n\n private async request<T>(path: string, init: RequestInit): Promise<T> {\n const resp = await this.fetchWithRetry(path, {\n ...init,\n headers: { ...this.authHeaders(), ...(init.headers as Record<string, string> ?? {}) },\n });\n if (!resp.ok) {\n const body = await resp.json().catch(() => ({}));\n const msg = (body as any)?.message ?? (body as any)?.error ?? `HTTP ${resp.status}`;\n throw Object.assign(new Error(`Proof Layer API error: ${msg}`), {\n status: resp.status,\n body,\n });\n }\n return resp.json() as Promise<T>;\n }\n\n /**\n * Submit an action proposal for governance evaluation.\n * The Guardian returns a verdict (EXECUTE | SHADOW | REVIEW | BLOCK).\n */\n async evaluate(options: EvaluateOptions): Promise<EvaluateResult> {\n const tenantId = this.tenantId;\n const payload: Record<string, unknown> = {\n schema_version: \"1.0\",\n action_type: options.actionType,\n resource_id: options.resourceId,\n agent_id: options.agentId,\n parameters: options.parameters ?? {},\n idempotency_key: options.idempotencyKey ?? randomUUID(),\n requested_at: options.requestedAt ?? new Date().toISOString(),\n guardian_timeout_policy: options.timeoutPolicy ?? \"fail_closed\",\n };\n if (tenantId) payload.tenant_id = tenantId;\n return this.request<EvaluateResult>(\"/v1/evaluate\", {\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n }\n\n /**\n * Retrieve a single receipt by ID.\n */\n async getReceipt(receiptId: string): Promise<Receipt> {\n return this.request<Receipt>(`/v1/receipts/${encodeURIComponent(receiptId)}`, {\n method: \"GET\",\n });\n }\n\n /**\n * List receipts for the authenticated tenant.\n */\n async listReceipts(options: ListReceiptsOptions = {}): Promise<{ receipts: Receipt[]; count: number }> {\n const params = new URLSearchParams();\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.offset) params.set(\"offset\", String(options.offset));\n const qs = params.toString() ? `?${params}` : \"\";\n return this.request<{ receipts: Receipt[]; count: number }>(`/v1/receipts${qs}`, {\n method: \"GET\",\n });\n }\n\n /**\n * Verify the cryptographic integrity of a receipt.\n */\n async verifyReceipt(receiptId: string): Promise<{ valid: boolean; receipt: Receipt }> {\n return this.request<{ valid: boolean; receipt: Receipt }>(\"/v1/receipts/verify\", {\n method: \"POST\",\n body: JSON.stringify({ receipt_id: receiptId }),\n });\n }\n\n /**\n * Verify the full audit chain (Merkle root integrity) for the tenant.\n */\n async verifyChain(): Promise<VerifyChainResult> {\n return this.request<VerifyChainResult>(\"/v1/receipts/verify-chain\", {\n method: \"POST\",\n body: JSON.stringify({}),\n });\n }\n\n /**\n * Retrieve usage statistics for the current billing period.\n */\n async getUsage(): Promise<{\n tenant_id: string;\n tier: string;\n receipts_this_month: number;\n receipts_included: number;\n percent_used: number;\n }>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AAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAAa,UAA+B,CAAC,GAAoD;AACrG,UAAM,SAAS,IAAI,gBAAgB;AACnC,QAAI,QAAQ,MAAO,QAAO,IAAI,SAAS,OAAO,QAAQ,KAAK,CAAC;AAC5D,QAAI,QAAQ,OAAQ,QAAO,IAAI,UAAU,OAAO,QAAQ,MAAM,CAAC;AAC/D,UAAM,KAAK,OAAO,SAAS,IAAI,IAAI,MAAM,KAAK;AAC9C,WAAO,KAAK,QAAgD,eAAe,EAAE,IAAI;AAAA,MAC/E,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAAc,WAAkE;AACpF,WAAO,KAAK,QAA8C,uBAAuB;AAAA,MAC/E,QAAQ;AAAA,MACR,MAAM,KAAK,UAAU,EAAE,YAAY,UAAU,CAAC;AAAA,IAChD,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,cAA0C;AAC9C,WAAO,KAAK,QAA2B,6BAA6B;AAAA,MAClE,QAAQ;AAAA,MACR,MAAM,KAAK,UAAU,CAAC,CAAC;AAAA,IACzB,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,WAMH;AACD,WAAO,KAAK,QAAQ,aAAa,EAAE,QAAQ,MAAM,CAAC;AAAA,EACpD;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@proof-layer/sdk",
3
+ "version": "1.0.0",
4
+ "description": "Official Proof Layer Node.js SDK — submit AI agent action proposals for governance, retrieve Ed25519-signed receipts, and verify hash-chained audit trails. Drop-in for any Node service that needs cryptographic proof of agent decisions.",
5
+ "keywords": [
6
+ "proof-layer",
7
+ "prooflayer",
8
+ "world999labs",
9
+ "ai-governance",
10
+ "ai-safety",
11
+ "agent-governance",
12
+ "audit",
13
+ "receipts",
14
+ "ed25519",
15
+ "hash-chain",
16
+ "merkle"
17
+ ],
18
+ "license": "MIT",
19
+ "homepage": "https://prooflayer.world999labs.com",
20
+ "bugs": { "url": "https://github.com/World-999-Labs/proof-layer/issues" },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/World-999-Labs/proof-layer.git",
24
+ "directory": "packages/sdk"
25
+ },
26
+ "main": "./dist/index.js",
27
+ "module": "./dist/index.mjs",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.mjs",
33
+ "require": "./dist/index.js"
34
+ }
35
+ },
36
+ "files": ["dist", "README.md", "LICENSE"],
37
+ "scripts": {
38
+ "build": "tsup",
39
+ "dev": "tsup --watch",
40
+ "prepublishOnly": "npm run build"
41
+ },
42
+ "engines": { "node": ">=18" },
43
+ "devDependencies": {
44
+ "tsup": "^8.0.0",
45
+ "typescript": "^5.0.0"
46
+ }
47
+ }