@valiron/sdk 0.12.0 → 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.
package/README.md CHANGED
@@ -28,15 +28,27 @@ 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
+ - **Proxy Gateway** (Pro) — Forward requests through Valiron's edge proxy with SSRF protection
40
+ - **Key-Based Agents** — Support Web2 agents via EIP-191 challenge-response (auto-detected)
41
+ - **World ID** — Verify agent-human linkage via Worldcoin proof-of-personhood
42
+ - **Telemetry** — Optional anonymous usage metrics (disable with `telemetry: { enabled: false }`)
43
+
44
+ ### Cleanup
45
+
46
+ Call `dispose()` when shutting down long-running servers:
47
+
48
+ ```typescript
49
+ await valiron.dispose();
50
+ ```
51
+
40
52
  ## Documentation
41
53
 
42
54
  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, GateResult, GateOptions, CallOptions, KeyAgentChallenge, KeyAgentProfile, WorldIdStatus, WorldIdAgentProfile, ProxyRequest, ProxyResponse } from "./types";
2
2
  /**
3
3
  * HTTP client for the Valiron Operator API.
4
4
  *
@@ -73,12 +73,23 @@ export declare class ValironClient {
73
73
  * `POST /operator/gate/:agentId`
74
74
  */
75
75
  gate(agentId: string, options?: GateOptions): Promise<GateResult>;
76
+ /**
77
+ * Proxy an API call through Valiron's trust gateway.
78
+ *
79
+ * Linear flow: Agent → Valiron → API Seller
80
+ *
81
+ * Valiron evaluates the agent's trust score and either forwards the
82
+ * request to the real API or blocks it with a 403.
83
+ *
84
+ * `POST /proxy/:agentId`
85
+ */
86
+ proxy<T = unknown>(agentId: string, request: ProxyRequest, options?: CallOptions): Promise<ProxyResponse<T>>;
76
87
  /**
77
88
  * Get a challenge nonce for key-based identity verification.
78
89
  *
79
- * `POST /operator/key/:agentKeyHash/challenge`
90
+ * `POST /operator/key/:agentAddress/challenge`
80
91
  */
81
- getKeyAgentChallenge(agentKeyHash: string): Promise<KeyAgentChallenge>;
92
+ getKeyAgentChallenge(agentAddress: string): Promise<KeyAgentChallenge>;
82
93
  /**
83
94
  * Verify a key-based agent via challenge-response signature.
84
95
  *
@@ -87,16 +98,14 @@ export declare class ValironClient {
87
98
  verifyKeyAgent(params: {
88
99
  challenge: string;
89
100
  signature: string;
90
- publicKey: string;
91
- agentKeyHash: string;
92
- ethereumAddress?: string;
101
+ agentAddress: string;
93
102
  }): Promise<KeyAgentProfile>;
94
103
  /**
95
104
  * Get trust profile for a verified key-based agent.
96
105
  *
97
- * `GET /operator/key/:agentKeyHash`
106
+ * `GET /operator/key/:agentAddress`
98
107
  */
99
- getKeyAgentProfile(agentKeyHash: string): Promise<KeyAgentProfile>;
108
+ getKeyAgentProfile(agentAddress: string): Promise<KeyAgentProfile>;
100
109
  /**
101
110
  * Verify a World ID proof linking a human to an agent.
102
111
  *
@@ -129,66 +138,10 @@ export declare class ValironClient {
129
138
  * `GET /operator/world-id/profile/:agentId`
130
139
  */
131
140
  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
141
  /** Flush any pending telemetry events and clean up resources. */
184
142
  dispose(): Promise<void>;
185
143
  private buildHeaders;
186
144
  private get;
187
145
  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
146
  private extractMethodName;
194
147
  }
package/dist/clients.js CHANGED
@@ -128,14 +128,29 @@ class ValironClient {
128
128
  delete result.reasons;
129
129
  return result;
130
130
  }
131
+ // ─── Proxy Gateway ──────────────────────────────────────────────────────
132
+ /**
133
+ * Proxy an API call through Valiron's trust gateway.
134
+ *
135
+ * Linear flow: Agent → Valiron → API Seller
136
+ *
137
+ * Valiron evaluates the agent's trust score and either forwards the
138
+ * request to the real API or blocks it with a 403.
139
+ *
140
+ * `POST /proxy/:agentId`
141
+ */
142
+ async proxy(agentId, request, options) {
143
+ const chain = this.resolveChain(options);
144
+ return this.post(`/proxy/${agentId}`, request, chain);
145
+ }
131
146
  // ─── Key-Based Agent Identity (Web2 Agents) ─────────────────────────────
132
147
  /**
133
148
  * Get a challenge nonce for key-based identity verification.
134
149
  *
135
- * `POST /operator/key/:agentKeyHash/challenge`
150
+ * `POST /operator/key/:agentAddress/challenge`
136
151
  */
137
- async getKeyAgentChallenge(agentKeyHash) {
138
- return this.post(`/operator/key/${agentKeyHash}/challenge`);
152
+ async getKeyAgentChallenge(agentAddress) {
153
+ return this.post(`/operator/key/${agentAddress}/challenge`);
139
154
  }
140
155
  /**
141
156
  * Verify a key-based agent via challenge-response signature.
@@ -148,10 +163,10 @@ class ValironClient {
148
163
  /**
149
164
  * Get trust profile for a verified key-based agent.
150
165
  *
151
- * `GET /operator/key/:agentKeyHash`
166
+ * `GET /operator/key/:agentAddress`
152
167
  */
153
- async getKeyAgentProfile(agentKeyHash) {
154
- return this.get(`/operator/key/${agentKeyHash}`);
168
+ async getKeyAgentProfile(agentAddress) {
169
+ return this.get(`/operator/key/${agentAddress}`);
155
170
  }
156
171
  // ─── World ID (Proof-of-Personhood) ───────────────────────────────────
157
172
  /**
@@ -178,70 +193,6 @@ class ValironClient {
178
193
  async getWorldIdProfile(agentId, options) {
179
194
  return this.get(`/operator/world-id/profile/${agentId}`, this.resolveChain(options));
180
195
  }
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
196
  /** Flush any pending telemetry events and clean up resources. */
246
197
  async dispose() {
247
198
  await this.telemetry.dispose();
@@ -435,100 +386,6 @@ class ValironClient {
435
386
  throw new types_1.ValironError(error.message || "Network error", "NETWORK_ERROR");
436
387
  }
437
388
  }
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
389
  extractMethodName(path) {
533
390
  if (path.startsWith("/operator/agent/"))
534
391
  return "getAgentProfile";
@@ -548,18 +405,6 @@ class ValironClient {
548
405
  return "getWorldIdProfile";
549
406
  if (path.startsWith("/operator/key/"))
550
407
  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
408
  return "unknown";
564
409
  }
565
410
  }
@@ -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
- }