@valiron/sdk 0.12.0 → 1.0.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.
package/README.md CHANGED
@@ -28,15 +28,28 @@ if (gate.allow) { /* serve the request */ }
28
28
  // One-line Express middleware — blocks untrusted agents automatically
29
29
  app.use("/api/paid", createValironGate({ sdk: valiron }));
30
30
 
31
- // Payment channels (Solana) — trust-adaptive USDC credit lines
32
- const preflight = await valiron.channelPreflight("1226", "So1anaWa11et...");
33
- const channel = await valiron.channelOpen("1226", "So1anaWa11et...", "depositTxSig");
34
- const usage = await valiron.channelConsume(channel.sessionId, 0.50, "API call");
35
- const settlement = await valiron.channelSettle(channel.sessionId);
31
+ // Fastify, Next.js, and generic middleware also available
32
+ // See SDK Reference for valironFastifyPlugin, createValironNextMiddleware, valironGateCheck
36
33
  ```
37
34
 
38
35
  No API key required for read operations.
39
36
 
37
+ ### Additional Features
38
+
39
+ - **Auto-Sandbox** — Middleware automatically evaluates new agents (on-chain and key-based) on their first gated request
40
+ - **Proxy Gateway** (Pro) — Forward requests through Valiron's edge proxy with SSRF protection
41
+ - **Key-Based Agents** — Support Web2 agents via EIP-191 challenge-response (auto-detected, auto-sandboxed)
42
+ - **World ID** — Verify agent-human linkage via Worldcoin proof-of-personhood
43
+ - **Telemetry** — Optional anonymous usage metrics (disable with `telemetry: { enabled: false }`)
44
+
45
+ ### Cleanup
46
+
47
+ Call `dispose()` when shutting down long-running servers:
48
+
49
+ ```typescript
50
+ await valiron.dispose();
51
+ ```
52
+
40
53
  ## Documentation
41
54
 
42
55
  Full SDK reference, API docs, trust model, and integration guides:
package/dist/clients.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, ChannelPreflightResponse, ChannelOpenResponse, ChannelConsumeResponse, ChannelStatusResponse, ChannelSettlementResponse, ChannelHealthResponse } from "./types";
1
+ import { ValironConfig, AgentProfile, AgentSnapshotSummary, WalletProfile, WalletResolution, SandboxResult, KeyAgentSandboxResult, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
2
2
  /**
3
3
  * HTTP client for the Valiron Operator API.
4
4
  *
@@ -63,6 +63,17 @@ export declare class ValironClient {
63
63
  * `POST /operator/trigger-sandbox/:agentId`
64
64
  */
65
65
  triggerSandboxTest(agentId: string, options?: CallOptions): Promise<SandboxResult>;
66
+ /**
67
+ * Trigger sandbox testing for a key-based (web2) agent.
68
+ *
69
+ * Key agents have no on-chain endpoints, so this uses sandbox_relay mode:
70
+ * the agent interacts with the sandbox-api mock server, and its behavior
71
+ * is observed and scored. The result is written to Redis so subsequent
72
+ * `getKeyAgentProfile()` calls return a real score.
73
+ *
74
+ * `POST /operator/trigger-sandbox-key/:agentAddress`
75
+ */
76
+ triggerKeyAgentSandbox(agentAddress: string): Promise<KeyAgentSandboxResult>;
66
77
  /**
67
78
  * Trust gate — single call combining on-chain reputation + sandbox tests.
68
79
  *
@@ -73,12 +84,23 @@ export declare class ValironClient {
73
84
  * `POST /operator/gate/:agentId`
74
85
  */
75
86
  gate(agentId: string, options?: GateOptions): Promise<GateResult>;
87
+ /**
88
+ * Proxy an API call through Valiron's trust gateway.
89
+ *
90
+ * Linear flow: Agent → Valiron → API Seller
91
+ *
92
+ * Valiron evaluates the agent's trust score and either forwards the
93
+ * request to the real API or blocks it with a 403.
94
+ *
95
+ * `POST /proxy/:agentId`
96
+ */
97
+ proxy<T = unknown>(agentId: string, request: ProxyRequest, options?: CallOptions): Promise<ProxyResponse<T>>;
76
98
  /**
77
99
  * Get a challenge nonce for key-based identity verification.
78
100
  *
79
- * `POST /operator/key/:agentKeyHash/challenge`
101
+ * `POST /operator/key/:agentAddress/challenge`
80
102
  */
81
- getKeyAgentChallenge(agentKeyHash: string): Promise<KeyAgentChallenge>;
103
+ getKeyAgentChallenge(agentAddress: string): Promise<KeyAgentChallenge>;
82
104
  /**
83
105
  * Verify a key-based agent via challenge-response signature.
84
106
  *
@@ -87,16 +109,14 @@ export declare class ValironClient {
87
109
  verifyKeyAgent(params: {
88
110
  challenge: string;
89
111
  signature: string;
90
- publicKey: string;
91
- agentKeyHash: string;
92
- ethereumAddress?: string;
112
+ agentAddress: string;
93
113
  }): Promise<KeyAgentProfile>;
94
114
  /**
95
115
  * Get trust profile for a verified key-based agent.
96
116
  *
97
- * `GET /operator/key/:agentKeyHash`
117
+ * `GET /operator/key/:agentAddress`
98
118
  */
99
- getKeyAgentProfile(agentKeyHash: string): Promise<KeyAgentProfile>;
119
+ getKeyAgentProfile(agentAddress: string): Promise<KeyAgentProfile>;
100
120
  /**
101
121
  * Verify a World ID proof linking a human to an agent.
102
122
  *
@@ -129,66 +149,10 @@ export declare class ValironClient {
129
149
  * `GET /operator/world-id/profile/:agentId`
130
150
  */
131
151
  getWorldIdProfile(agentId: string, options?: CallOptions): Promise<WorldIdAgentProfile>;
132
- /**
133
- * Preflight gate check for a payment channel.
134
- *
135
- * Checks agent trust score, returns escrow address and credit line
136
- * policy for the agent's tier. Call this before opening a channel.
137
- *
138
- * `POST /channel/preflight/:agentId`
139
- */
140
- channelPreflight(agentId: string, walletAddress: string): Promise<ChannelPreflightResponse>;
141
- /**
142
- * Open a payment channel with a deposit transaction.
143
- *
144
- * The agent must have already deposited USDC to the escrow address
145
- * returned by `channelPreflight()`. Pass the deposit TX signature
146
- * to verify on-chain and open the credit line.
147
- *
148
- * `POST /channel/open/:agentId`
149
- */
150
- channelOpen(agentId: string, walletAddress: string, depositSignature: string): Promise<ChannelOpenResponse>;
151
- /**
152
- * Consume credit from an open payment channel.
153
- *
154
- * Records a usage charge against the channel's credit line.
155
- * Requires the session ID as a Bearer token in the Authorization header.
156
- *
157
- * `POST /channel/consume/:sessionId`
158
- */
159
- channelConsume(sessionId: string, cost: number, description?: string): Promise<ChannelConsumeResponse>;
160
- /**
161
- * Get the current status of a payment channel.
162
- *
163
- * Returns credit usage, remaining balance, request count, and expiry.
164
- *
165
- * `GET /channel/status/:sessionId`
166
- */
167
- channelStatus(sessionId: string): Promise<ChannelStatusResponse>;
168
- /**
169
- * Settle and close a payment channel.
170
- *
171
- * Closes the channel, calculates unused credit, and initiates
172
- * a USDC refund to the agent's wallet for any unspent balance.
173
- *
174
- * `POST /channel/settle/:sessionId`
175
- */
176
- channelSettle(sessionId: string): Promise<ChannelSettlementResponse>;
177
- /**
178
- * Check payment channel service health.
179
- *
180
- * `GET /channel/health`
181
- */
182
- channelHealth(): Promise<ChannelHealthResponse>;
183
152
  /** Flush any pending telemetry events and clean up resources. */
184
153
  dispose(): Promise<void>;
185
154
  private buildHeaders;
186
155
  private get;
187
156
  private post;
188
- /**
189
- * POST with a custom Bearer token (used by channel consume where
190
- * the session ID is the auth token, not the operator API key).
191
- */
192
- private postWithAuth;
193
157
  private extractMethodName;
194
158
  }
package/dist/clients.js CHANGED
@@ -112,6 +112,24 @@ class ValironClient {
112
112
  delete result.mode;
113
113
  return result;
114
114
  }
115
+ /**
116
+ * Trigger sandbox testing for a key-based (web2) agent.
117
+ *
118
+ * Key agents have no on-chain endpoints, so this uses sandbox_relay mode:
119
+ * the agent interacts with the sandbox-api mock server, and its behavior
120
+ * is observed and scored. The result is written to Redis so subsequent
121
+ * `getKeyAgentProfile()` calls return a real score.
122
+ *
123
+ * `POST /operator/trigger-sandbox-key/:agentAddress`
124
+ */
125
+ async triggerKeyAgentSandbox(agentAddress) {
126
+ const result = await this.post(`/operator/trigger-sandbox-key/${agentAddress}`);
127
+ // Strip internal behavioral metrics and execution details
128
+ delete result.metrics;
129
+ delete result.testSummary;
130
+ delete result.mode;
131
+ return result;
132
+ }
115
133
  /**
116
134
  * Trust gate — single call combining on-chain reputation + sandbox tests.
117
135
  *
@@ -128,14 +146,29 @@ class ValironClient {
128
146
  delete result.reasons;
129
147
  return result;
130
148
  }
149
+ // ─── Proxy Gateway ──────────────────────────────────────────────────────
150
+ /**
151
+ * Proxy an API call through Valiron's trust gateway.
152
+ *
153
+ * Linear flow: Agent → Valiron → API Seller
154
+ *
155
+ * Valiron evaluates the agent's trust score and either forwards the
156
+ * request to the real API or blocks it with a 403.
157
+ *
158
+ * `POST /proxy/:agentId`
159
+ */
160
+ async proxy(agentId, request, options) {
161
+ const chain = this.resolveChain(options);
162
+ return this.post(`/proxy/${agentId}`, request, chain);
163
+ }
131
164
  // ─── Key-Based Agent Identity (Web2 Agents) ─────────────────────────────
132
165
  /**
133
166
  * Get a challenge nonce for key-based identity verification.
134
167
  *
135
- * `POST /operator/key/:agentKeyHash/challenge`
168
+ * `POST /operator/key/:agentAddress/challenge`
136
169
  */
137
- async getKeyAgentChallenge(agentKeyHash) {
138
- return this.post(`/operator/key/${agentKeyHash}/challenge`);
170
+ async getKeyAgentChallenge(agentAddress) {
171
+ return this.post(`/operator/key/${agentAddress}/challenge`);
139
172
  }
140
173
  /**
141
174
  * Verify a key-based agent via challenge-response signature.
@@ -148,10 +181,10 @@ class ValironClient {
148
181
  /**
149
182
  * Get trust profile for a verified key-based agent.
150
183
  *
151
- * `GET /operator/key/:agentKeyHash`
184
+ * `GET /operator/key/:agentAddress`
152
185
  */
153
- async getKeyAgentProfile(agentKeyHash) {
154
- return this.get(`/operator/key/${agentKeyHash}`);
186
+ async getKeyAgentProfile(agentAddress) {
187
+ return this.get(`/operator/key/${agentAddress}`);
155
188
  }
156
189
  // ─── World ID (Proof-of-Personhood) ───────────────────────────────────
157
190
  /**
@@ -178,70 +211,6 @@ class ValironClient {
178
211
  async getWorldIdProfile(agentId, options) {
179
212
  return this.get(`/operator/world-id/profile/${agentId}`, this.resolveChain(options));
180
213
  }
181
- // ─── Payment Channels (Solana) ──────────────────────────────────────────
182
- /**
183
- * Preflight gate check for a payment channel.
184
- *
185
- * Checks agent trust score, returns escrow address and credit line
186
- * policy for the agent's tier. Call this before opening a channel.
187
- *
188
- * `POST /channel/preflight/:agentId`
189
- */
190
- async channelPreflight(agentId, walletAddress) {
191
- return this.post(`/channel/preflight/${agentId}`, { walletAddress });
192
- }
193
- /**
194
- * Open a payment channel with a deposit transaction.
195
- *
196
- * The agent must have already deposited USDC to the escrow address
197
- * returned by `channelPreflight()`. Pass the deposit TX signature
198
- * to verify on-chain and open the credit line.
199
- *
200
- * `POST /channel/open/:agentId`
201
- */
202
- async channelOpen(agentId, walletAddress, depositSignature) {
203
- return this.post(`/channel/open/${agentId}`, { walletAddress, depositSignature });
204
- }
205
- /**
206
- * Consume credit from an open payment channel.
207
- *
208
- * Records a usage charge against the channel's credit line.
209
- * Requires the session ID as a Bearer token in the Authorization header.
210
- *
211
- * `POST /channel/consume/:sessionId`
212
- */
213
- async channelConsume(sessionId, cost, description) {
214
- return this.postWithAuth(`/channel/consume/${sessionId}`, { cost, ...(description ? { description } : {}) }, sessionId);
215
- }
216
- /**
217
- * Get the current status of a payment channel.
218
- *
219
- * Returns credit usage, remaining balance, request count, and expiry.
220
- *
221
- * `GET /channel/status/:sessionId`
222
- */
223
- async channelStatus(sessionId) {
224
- return this.get(`/channel/status/${sessionId}`);
225
- }
226
- /**
227
- * Settle and close a payment channel.
228
- *
229
- * Closes the channel, calculates unused credit, and initiates
230
- * a USDC refund to the agent's wallet for any unspent balance.
231
- *
232
- * `POST /channel/settle/:sessionId`
233
- */
234
- async channelSettle(sessionId) {
235
- return this.post(`/channel/settle/${sessionId}`, {});
236
- }
237
- /**
238
- * Check payment channel service health.
239
- *
240
- * `GET /channel/health`
241
- */
242
- async channelHealth() {
243
- return this.get(`/channel/health`);
244
- }
245
214
  /** Flush any pending telemetry events and clean up resources. */
246
215
  async dispose() {
247
216
  await this.telemetry.dispose();
@@ -435,100 +404,6 @@ class ValironClient {
435
404
  throw new types_1.ValironError(error.message || "Network error", "NETWORK_ERROR");
436
405
  }
437
406
  }
438
- /**
439
- * POST with a custom Bearer token (used by channel consume where
440
- * the session ID is the auth token, not the operator API key).
441
- */
442
- async postWithAuth(path, body, bearerToken) {
443
- const url = new URL(path, this.endpoint);
444
- if (this.debug) {
445
- console.log(`[Valiron SDK] POST (auth) ${url.toString()}`, body);
446
- }
447
- const controller = new AbortController();
448
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
449
- const start = Date.now();
450
- try {
451
- const headers = {
452
- "Content-Type": "application/json",
453
- "Authorization": `Bearer ${bearerToken}`,
454
- };
455
- const response = await fetch(url.toString(), {
456
- method: "POST",
457
- headers,
458
- body: JSON.stringify(body),
459
- signal: controller.signal,
460
- });
461
- clearTimeout(timeoutId);
462
- const durationMs = Date.now() - start;
463
- const methodName = this.extractMethodName(path);
464
- if (!response.ok) {
465
- const respBody = await response
466
- .json()
467
- .catch(() => ({ message: response.statusText }));
468
- this.telemetry.emit("sdk_call", {
469
- method: methodName,
470
- chain: "solana",
471
- duration_ms: durationMs,
472
- success: false,
473
- http_status: response.status,
474
- error_code: "API_ERROR",
475
- retries: 0,
476
- timeout_count: 0,
477
- abort_count: 0,
478
- });
479
- this.telemetry.recordLatency(methodName, "solana", durationMs);
480
- throw new types_1.ValironError(respBody.error || respBody.message || `Request failed: ${response.statusText}`, "API_ERROR", response.status);
481
- }
482
- const data = await response.json();
483
- this.telemetry.emit("sdk_call", {
484
- method: methodName,
485
- chain: "solana",
486
- duration_ms: durationMs,
487
- success: true,
488
- http_status: response.status,
489
- retries: 0,
490
- timeout_count: 0,
491
- abort_count: 0,
492
- });
493
- this.telemetry.recordLatency(methodName, "solana", durationMs);
494
- if (this.debug)
495
- console.log(`[Valiron SDK] Response:`, data);
496
- return data;
497
- }
498
- catch (error) {
499
- clearTimeout(timeoutId);
500
- const durationMs = Date.now() - start;
501
- const methodName = this.extractMethodName(path);
502
- if (error.name === "AbortError") {
503
- this.telemetry.emit("sdk_call", {
504
- method: methodName,
505
- chain: "solana",
506
- duration_ms: durationMs,
507
- success: false,
508
- error_code: "TIMEOUT_ERROR",
509
- retries: 0,
510
- timeout_count: 1,
511
- abort_count: 1,
512
- });
513
- this.telemetry.recordLatency(methodName, "solana", durationMs);
514
- throw new types_1.ValironError(`Request timeout after ${this.timeout}ms`, "TIMEOUT_ERROR");
515
- }
516
- if (error instanceof types_1.ValironError)
517
- throw error;
518
- this.telemetry.emit("sdk_call", {
519
- method: methodName,
520
- chain: "solana",
521
- duration_ms: durationMs,
522
- success: false,
523
- error_code: "NETWORK_ERROR",
524
- retries: 0,
525
- timeout_count: 0,
526
- abort_count: 0,
527
- });
528
- this.telemetry.recordLatency(methodName, "solana", durationMs);
529
- throw new types_1.ValironError(error.message || "Network error", "NETWORK_ERROR");
530
- }
531
- }
532
407
  extractMethodName(path) {
533
408
  if (path.startsWith("/operator/agent/"))
534
409
  return "getAgentProfile";
@@ -548,18 +423,6 @@ class ValironClient {
548
423
  return "getWorldIdProfile";
549
424
  if (path.startsWith("/operator/key/"))
550
425
  return "keyAgent";
551
- if (path.startsWith("/channel/preflight/"))
552
- return "channelPreflight";
553
- if (path.startsWith("/channel/open/"))
554
- return "channelOpen";
555
- if (path.startsWith("/channel/consume/"))
556
- return "channelConsume";
557
- if (path.startsWith("/channel/status/"))
558
- return "channelStatus";
559
- if (path.startsWith("/channel/settle/"))
560
- return "channelSettle";
561
- if (path === "/channel/health")
562
- return "channelHealth";
563
426
  return "unknown";
564
427
  }
565
428
  }
@@ -1,80 +1,16 @@
1
- export interface AgentKeypair {
2
- /** Raw Ed25519 private key (base64-encoded) */
3
- privateKey: string;
4
- /** Raw Ed25519 public key (base64-encoded) */
5
- publicKey: string;
6
- /** SHA-256 hash of the public key — the agent's portable identifier */
7
- agentKeyHash: string;
8
- }
9
1
  export interface ChallengeResponse {
10
2
  /** The challenge nonce that was signed */
11
3
  challenge: string;
12
- /** Base64-encoded signature of the challenge */
4
+ /** EIP-191 signature (0x-prefixed hex) */
13
5
  signature: string;
14
- /** The agent's public key (base64-encoded) — needed for first-contact verification */
15
- publicKey: string;
16
- /** The agent's key hash (SHA-256 of public key) */
17
- agentKeyHash: string;
6
+ /** The agent's Ethereum address */
7
+ agentAddress: string;
18
8
  }
19
- /**
20
- * Generate an Ed25519 keypair for an agent.
21
- *
22
- * The SHA-256 hash of the public key becomes the agent's
23
- * stable, portable identifier — no registration needed.
24
- *
25
- * @returns The keypair and derived agent key hash
26
- *
27
- * @example
28
- * ```typescript
29
- * import { generateAgentKeypair } from '@valiron/sdk';
30
- *
31
- * const keypair = generateAgentKeypair();
32
- * console.log(keypair.agentKeyHash); // "a3f8c1d2e5..."
33
- *
34
- * // Store privateKey securely (env var, file, KMS)
35
- * // Use agentKeyHash as the agent's identity
36
- * ```
37
- */
38
- export declare function generateAgentKeypair(): AgentKeypair;
39
- /**
40
- * Derive the agent key hash from a base64-encoded public key.
41
- *
42
- * @param publicKeyB64 - Base64-encoded Ed25519 public key (SPKI DER format)
43
- * @returns SHA-256 hex hash of the public key
44
- */
45
- export declare function deriveKeyHash(publicKeyB64: string): string;
9
+ /** Validate that a string looks like an Ethereum address (0x + 40 hex chars). */
10
+ export declare function isValidAddress(address: string): boolean;
46
11
  /**
47
12
  * Generate a random challenge nonce for identity verification.
48
13
  *
49
14
  * @returns A 32-byte hex-encoded nonce
50
15
  */
51
16
  export declare function generateChallenge(): string;
52
- /**
53
- * Sign a challenge with the agent's private key.
54
- * Used to prove the agent controls the keypair.
55
- *
56
- * @param challenge - The challenge nonce to sign
57
- * @param privateKeyB64 - Base64-encoded Ed25519 private key (PKCS8 DER format)
58
- * @param publicKeyB64 - Base64-encoded Ed25519 public key (SPKI DER format)
59
- * @returns The challenge response containing signature + identity info
60
- *
61
- * @example
62
- * ```typescript
63
- * import { signChallenge } from '@valiron/sdk';
64
- *
65
- * // Agent receives a challenge from Valiron middleware
66
- * const response = signChallenge(challenge, keypair.privateKey, keypair.publicKey);
67
- * // Send response back to prove identity
68
- * ```
69
- */
70
- export declare function signChallenge(challenge: string, privateKeyB64: string, publicKeyB64: string): ChallengeResponse;
71
- /**
72
- * Verify a challenge-response signature.
73
- * Confirms the agent controls the private key corresponding to the public key.
74
- *
75
- * @param challenge - The original challenge nonce
76
- * @param signatureB64 - Base64-encoded signature
77
- * @param publicKeyB64 - Base64-encoded Ed25519 public key
78
- * @returns true if the signature is valid
79
- */
80
- export declare function verifyChallenge(challenge: string, signatureB64: string, publicKeyB64: string): boolean;
package/dist/identity.js CHANGED
@@ -1,58 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateAgentKeypair = generateAgentKeypair;
4
- exports.deriveKeyHash = deriveKeyHash;
3
+ exports.isValidAddress = isValidAddress;
5
4
  exports.generateChallenge = generateChallenge;
6
- exports.signChallenge = signChallenge;
7
- exports.verifyChallenge = verifyChallenge;
8
5
  const crypto_1 = require("crypto");
9
- // ─── Keypair Generation ─────────────────────────────────────────────────────
10
- /**
11
- * Generate an Ed25519 keypair for an agent.
12
- *
13
- * The SHA-256 hash of the public key becomes the agent's
14
- * stable, portable identifier — no registration needed.
15
- *
16
- * @returns The keypair and derived agent key hash
17
- *
18
- * @example
19
- * ```typescript
20
- * import { generateAgentKeypair } from '@valiron/sdk';
21
- *
22
- * const keypair = generateAgentKeypair();
23
- * console.log(keypair.agentKeyHash); // "a3f8c1d2e5..."
24
- *
25
- * // Store privateKey securely (env var, file, KMS)
26
- * // Use agentKeyHash as the agent's identity
27
- * ```
28
- */
29
- function generateAgentKeypair() {
30
- const { publicKey, privateKey } = (0, crypto_1.generateKeyPairSync)("ed25519", {
31
- publicKeyEncoding: { type: "spki", format: "der" },
32
- privateKeyEncoding: { type: "pkcs8", format: "der" },
33
- });
34
- const publicKeyB64 = Buffer.from(publicKey).toString("base64");
35
- const privateKeyB64 = Buffer.from(privateKey).toString("base64");
36
- const agentKeyHash = deriveKeyHash(publicKeyB64);
37
- return {
38
- privateKey: privateKeyB64,
39
- publicKey: publicKeyB64,
40
- agentKeyHash,
41
- };
42
- }
43
- // ─── Key Hash Derivation ────────────────────────────────────────────────────
44
- /**
45
- * Derive the agent key hash from a base64-encoded public key.
46
- *
47
- * @param publicKeyB64 - Base64-encoded Ed25519 public key (SPKI DER format)
48
- * @returns SHA-256 hex hash of the public key
49
- */
50
- function deriveKeyHash(publicKeyB64) {
51
- return (0, crypto_1.createHash)("sha256")
52
- .update(Buffer.from(publicKeyB64, "base64"))
53
- .digest("hex");
6
+ // ─── Validation Helpers ─────────────────────────────────────────────────────
7
+ /** Validate that a string looks like an Ethereum address (0x + 40 hex chars). */
8
+ function isValidAddress(address) {
9
+ return /^0x[a-fA-F0-9]{40}$/.test(address);
54
10
  }
55
- // ─── Challenge-Response ─────────────────────────────────────────────────────
11
+ // ─── Challenge Generation ───────────────────────────────────────────────────
56
12
  /**
57
13
  * Generate a random challenge nonce for identity verification.
58
14
  *
@@ -61,61 +17,3 @@ function deriveKeyHash(publicKeyB64) {
61
17
  function generateChallenge() {
62
18
  return (0, crypto_1.randomBytes)(32).toString("hex");
63
19
  }
64
- /**
65
- * Sign a challenge with the agent's private key.
66
- * Used to prove the agent controls the keypair.
67
- *
68
- * @param challenge - The challenge nonce to sign
69
- * @param privateKeyB64 - Base64-encoded Ed25519 private key (PKCS8 DER format)
70
- * @param publicKeyB64 - Base64-encoded Ed25519 public key (SPKI DER format)
71
- * @returns The challenge response containing signature + identity info
72
- *
73
- * @example
74
- * ```typescript
75
- * import { signChallenge } from '@valiron/sdk';
76
- *
77
- * // Agent receives a challenge from Valiron middleware
78
- * const response = signChallenge(challenge, keypair.privateKey, keypair.publicKey);
79
- * // Send response back to prove identity
80
- * ```
81
- */
82
- function signChallenge(challenge, privateKeyB64, publicKeyB64) {
83
- const privateKeyObj = createPrivateKeyFromB64(privateKeyB64);
84
- const signature = (0, crypto_1.sign)(null, Buffer.from(challenge), privateKeyObj);
85
- return {
86
- challenge,
87
- signature: signature.toString("base64"),
88
- publicKey: publicKeyB64,
89
- agentKeyHash: deriveKeyHash(publicKeyB64),
90
- };
91
- }
92
- /**
93
- * Verify a challenge-response signature.
94
- * Confirms the agent controls the private key corresponding to the public key.
95
- *
96
- * @param challenge - The original challenge nonce
97
- * @param signatureB64 - Base64-encoded signature
98
- * @param publicKeyB64 - Base64-encoded Ed25519 public key
99
- * @returns true if the signature is valid
100
- */
101
- function verifyChallenge(challenge, signatureB64, publicKeyB64) {
102
- try {
103
- const publicKeyObj = (0, crypto_1.createPublicKey)({
104
- key: Buffer.from(publicKeyB64, "base64"),
105
- format: "der",
106
- type: "spki",
107
- });
108
- return (0, crypto_1.verify)(null, Buffer.from(challenge), publicKeyObj, Buffer.from(signatureB64, "base64"));
109
- }
110
- catch {
111
- return false;
112
- }
113
- }
114
- // ─── Helpers ────────────────────────────────────────────────────────────────
115
- function createPrivateKeyFromB64(privateKeyB64) {
116
- return {
117
- key: Buffer.from(privateKeyB64, "base64"),
118
- format: "der",
119
- type: "pkcs8",
120
- };
121
- }