@valiron/sdk 1.4.0 → 2.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.
- package/README.md +11 -148
- package/bin/valiron-card.mjs +211 -0
- package/dist/card.d.ts +565 -0
- package/dist/card.js +722 -0
- package/dist/clients.d.ts +6 -6
- package/dist/clients.js +33 -26
- package/dist/edge.d.ts +87 -0
- package/dist/edge.js +164 -0
- package/dist/edgeGate.d.ts +146 -0
- package/dist/edgeGate.js +230 -0
- package/dist/edgeGateVerify.d.ts +146 -0
- package/dist/edgeGateVerify.js +243 -0
- package/dist/identity.d.ts +6 -0
- package/dist/identity.js +6 -1
- package/dist/identityMiddleware.d.ts +8 -0
- package/dist/identityMiddleware.js +12 -4
- package/dist/index.d.ts +5 -10
- package/dist/index.js +4 -10
- package/dist/middleware.d.ts +20 -9
- package/dist/middleware.js +47 -19
- package/dist/operatorSdk.d.ts +11 -2
- package/dist/operatorSdk.js +13 -7
- package/dist/types.d.ts +14 -4
- package/docs/AGENT-READY-APIS.md +3 -181
- package/docs/API-REFERENCE.md +94 -546
- package/docs/CHAINS.md +3 -3
- package/docs/CLOUDFLARE-GATE-MIDDLEWARE.md +196 -0
- package/docs/CRAWLER-PROTECTION.md +545 -0
- package/docs/DASHBOARD.md +55 -23
- package/docs/E2E-MIDDLEWARE-INTEGRATION.md +19 -13
- package/docs/ERRORS.md +29 -19
- package/docs/IDENTITY.md +16 -14
- package/docs/PROVIDER-IDENTITY.md +15 -5
- package/docs/QUICKSTART.md +40 -24
- package/docs/README.md +21 -4
- package/docs/SANDBOX.md +7 -1
- package/docs/SDK-REFERENCE.md +115 -52
- package/docs/SECURITY-UPGRADE-2026-10-31.md +98 -0
- package/docs/TRUST-MODEL.md +14 -11
- package/docs/llms.txt +70 -302
- package/examples/cloudflare-gate-worker/README.md +198 -0
- package/examples/cloudflare-gate-worker/package.json +20 -0
- package/examples/cloudflare-gate-worker/worker.ts +309 -0
- package/examples/cloudflare-gate-worker/wrangler.toml +46 -0
- package/examples/cloudflare-worker/package.json +8 -0
- package/examples/cloudflare-worker/worker.ts +495 -0
- package/examples/cloudflare-worker/wrangler.toml +57 -0
- package/package.json +35 -5
- package/docs/MCP.md +0 -50
package/dist/card.js
ADDED
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CardMcpClient = exports.CardAgent = exports.CardClient = exports.CardSellerClient = exports.cardNonce = exports.CardAPIError = void 0;
|
|
4
|
+
exports.createCardKey = createCardKey;
|
|
5
|
+
exports.createPassRequestProof = createPassRequestProof;
|
|
6
|
+
exports.createValironPassMiddleware = createValironPassMiddleware;
|
|
7
|
+
exports.createCardRequestProof = createCardRequestProof;
|
|
8
|
+
exports.cardPresentationHeaders = cardPresentationHeaders;
|
|
9
|
+
exports.createWbaKeyPair = createWbaKeyPair;
|
|
10
|
+
exports.createDirectorySelfSignature = createDirectorySelfSignature;
|
|
11
|
+
exports.signWbaRequest = signWbaRequest;
|
|
12
|
+
exports.accountSnapshotUsable = accountSnapshotUsable;
|
|
13
|
+
exports.createCardQuotaAdapter = createCardQuotaAdapter;
|
|
14
|
+
exports.createValironCardGate = createValironCardGate;
|
|
15
|
+
exports.canonicalCardJson = canonicalCardJson;
|
|
16
|
+
exports.buildAgentLinkPayload = buildAgentLinkPayload;
|
|
17
|
+
exports.signAgentLinkPayload = signAgentLinkPayload;
|
|
18
|
+
/** Independent Node entry point. Imports no wallet, chain, legacy identity, or telemetry modules. */
|
|
19
|
+
const node_crypto_1 = require("node:crypto");
|
|
20
|
+
class CardAPIError extends Error {
|
|
21
|
+
constructor(status, code,
|
|
22
|
+
/** Non-secret extra fields the API returned with the error. */
|
|
23
|
+
details) {
|
|
24
|
+
super(code.replace(/_/g, " "));
|
|
25
|
+
this.status = status;
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.details = details;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.CardAPIError = CardAPIError;
|
|
31
|
+
const cardNonce = () => (0, node_crypto_1.randomBytes)(24).toString("base64url");
|
|
32
|
+
exports.cardNonce = cardNonce;
|
|
33
|
+
const digest = (v) => (0, node_crypto_1.createHash)("sha256").update(v).digest("hex");
|
|
34
|
+
const timestamp = () => Math.floor(Date.now() / 1000);
|
|
35
|
+
const signature = (key, payload) => (0, node_crypto_1.sign)(null, Buffer.from(payload), key).toString("base64url");
|
|
36
|
+
function createCardKey() {
|
|
37
|
+
const pair = (0, node_crypto_1.generateKeyPairSync)("ed25519");
|
|
38
|
+
return {
|
|
39
|
+
privateKey: pair.privateKey
|
|
40
|
+
.export({ type: "pkcs8", format: "pem" })
|
|
41
|
+
.toString(),
|
|
42
|
+
publicKey: pair.publicKey
|
|
43
|
+
.export({ type: "spki", format: "pem" })
|
|
44
|
+
.toString(),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/** Bootstrap with the seller's existing authorized operator session. Never use an admin key or share a browser password. */
|
|
48
|
+
class CardSellerClient {
|
|
49
|
+
constructor(options) {
|
|
50
|
+
if (!options.operatorToken)
|
|
51
|
+
throw new Error("An authorized seller operator token is required");
|
|
52
|
+
this.client = new CardClient({
|
|
53
|
+
...options,
|
|
54
|
+
merchantKey: options.operatorToken,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
getSetup() {
|
|
58
|
+
return this.client.request("/operator/card/v1/setup", undefined, "GET");
|
|
59
|
+
}
|
|
60
|
+
registerBusiness(input) {
|
|
61
|
+
return this.client.request("/operator/card/v1/merchants", input);
|
|
62
|
+
}
|
|
63
|
+
createCredential(input) {
|
|
64
|
+
return this.client.request("/operator/card/v1/credentials", input);
|
|
65
|
+
}
|
|
66
|
+
revokeCredential(id) {
|
|
67
|
+
return this.client.request(`/operator/card/v1/credentials/${encodeURIComponent(id)}/revoke`, {});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
exports.CardSellerClient = CardSellerClient;
|
|
71
|
+
class CardClient {
|
|
72
|
+
constructor(options) {
|
|
73
|
+
this.options = options;
|
|
74
|
+
/** delegationId -> delegation expiry (epoch s), learned from the pairing poll
|
|
75
|
+
* or from the server's own expiry-only rejection. In-memory only. */
|
|
76
|
+
this.delegationExpiry = new Map();
|
|
77
|
+
}
|
|
78
|
+
async request(path, body, method = "POST", extraHeaders = {}) {
|
|
79
|
+
const base = new URL(this.options.baseUrl);
|
|
80
|
+
if (base.protocol !== "https:" &&
|
|
81
|
+
!(base.protocol === "http:" &&
|
|
82
|
+
["localhost", "127.0.0.1"].includes(base.hostname)))
|
|
83
|
+
throw new Error("Card API requires HTTPS");
|
|
84
|
+
let requestPath = path;
|
|
85
|
+
if (this.options.transport === "website") {
|
|
86
|
+
if (path.startsWith("/operator/card/v1/"))
|
|
87
|
+
requestPath = path.replace("/operator/card/v1/", "/api/pass/_operator/");
|
|
88
|
+
else if (path.startsWith("/card/v1/"))
|
|
89
|
+
requestPath = path.replace("/card/v1/", "/api/pass/");
|
|
90
|
+
else
|
|
91
|
+
throw new Error("Unsupported Card website route");
|
|
92
|
+
}
|
|
93
|
+
const target = new URL(requestPath, base);
|
|
94
|
+
if (target.origin !== base.origin || base.username || base.password)
|
|
95
|
+
throw new Error("Card requests must stay on the configured API origin");
|
|
96
|
+
const evaluationRequest = path.endsWith("/sandbox-evaluation") || (path.endsWith("/mcp") && body?.params?.name === "valiron_pass_run_sandbox");
|
|
97
|
+
const response = await (this.options.fetch ?? fetch)(target, {
|
|
98
|
+
method,
|
|
99
|
+
redirect: "error",
|
|
100
|
+
signal: AbortSignal.timeout(this.options.timeoutMs ?? (evaluationRequest ? 130000 : 10000)),
|
|
101
|
+
headers: {
|
|
102
|
+
...(this.options.transport === "website" &&
|
|
103
|
+
!["GET", "HEAD"].includes(method)
|
|
104
|
+
? { Origin: base.origin }
|
|
105
|
+
: {}),
|
|
106
|
+
...(body === undefined ? {} : { "Content-Type": "application/json" }),
|
|
107
|
+
...(this.options.merchantKey
|
|
108
|
+
? { Authorization: `Bearer ${this.options.merchantKey}` }
|
|
109
|
+
: {}),
|
|
110
|
+
...extraHeaders,
|
|
111
|
+
},
|
|
112
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
113
|
+
});
|
|
114
|
+
const value = (await response.json());
|
|
115
|
+
if (!response.ok)
|
|
116
|
+
throw new CardAPIError(response.status, value.code ?? "card_request_failed", Number.isInteger(value.delegationExpiresAt) ? { delegationExpiresAt: value.delegationExpiresAt } : undefined);
|
|
117
|
+
return value;
|
|
118
|
+
}
|
|
119
|
+
/** Requires a scoped offers:write key; response is restricted to that merchant and environment. */
|
|
120
|
+
listOffers() {
|
|
121
|
+
return this.request("/operator/card/v1/offers", undefined, "GET");
|
|
122
|
+
}
|
|
123
|
+
createOffer(input) {
|
|
124
|
+
return this.request("/operator/card/v1/offers", input);
|
|
125
|
+
}
|
|
126
|
+
enableTestOffer(id) {
|
|
127
|
+
return this.request(`/operator/card/v1/offers/${encodeURIComponent(id)}/test-enable`, {});
|
|
128
|
+
}
|
|
129
|
+
publishOffer(id) {
|
|
130
|
+
return this.request(`/operator/card/v1/offers/${encodeURIComponent(id)}/publish`, {});
|
|
131
|
+
}
|
|
132
|
+
disableOffer(id) {
|
|
133
|
+
return this.request(`/operator/card/v1/offers/${encodeURIComponent(id)}/disable`, {});
|
|
134
|
+
}
|
|
135
|
+
async createConnect(input) {
|
|
136
|
+
const verifier = (0, exports.cardNonce)() + (0, exports.cardNonce)();
|
|
137
|
+
const state = (0, exports.cardNonce)();
|
|
138
|
+
const result = await this.request("/operator/card/v1/connect-sessions", {
|
|
139
|
+
...input,
|
|
140
|
+
idempotencyKey: input.idempotencyKey ?? (0, exports.cardNonce)(),
|
|
141
|
+
state,
|
|
142
|
+
codeChallenge: (0, node_crypto_1.createHash)("sha256").update(verifier).digest("base64url"),
|
|
143
|
+
});
|
|
144
|
+
return { ...result, state, verifier }; // Persist these only in the merchant's authenticated server session.
|
|
145
|
+
}
|
|
146
|
+
async exchangeConnect(input) {
|
|
147
|
+
if (input.state !== input.expectedState || !input.expectedState)
|
|
148
|
+
throw new Error("Card return state does not match the current customer session");
|
|
149
|
+
return this.request(`/operator/card/v1/connect-sessions/${encodeURIComponent(input.id)}/exchange`, { code: input.code, codeVerifier: input.verifier });
|
|
150
|
+
}
|
|
151
|
+
resolveAccount(input) {
|
|
152
|
+
return this.request("/operator/card/v1/account-benefits/resolve", input);
|
|
153
|
+
}
|
|
154
|
+
reportEnforcement(input) {
|
|
155
|
+
return this.request("/operator/card/v1/enforcement-events", input);
|
|
156
|
+
}
|
|
157
|
+
async startApplication(input) {
|
|
158
|
+
const key = (0, node_crypto_1.createPublicKey)(input.privateKey);
|
|
159
|
+
const publicKey = key.export({ format: "pem", type: "spki" }).toString();
|
|
160
|
+
const thumbprint = digest(key.export({ format: "der", type: "spki" }));
|
|
161
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
162
|
+
return this.request("/card/v1/pairings", {
|
|
163
|
+
publicKey,
|
|
164
|
+
name: input.name,
|
|
165
|
+
merchantId: input.merchantId,
|
|
166
|
+
...(input.scopes ? { scopes: input.scopes } : {}),
|
|
167
|
+
nonce,
|
|
168
|
+
timestamp: at,
|
|
169
|
+
signature: signature(input.privateKey, [
|
|
170
|
+
"valiron-card-pair-v1",
|
|
171
|
+
thumbprint,
|
|
172
|
+
input.name,
|
|
173
|
+
input.merchantId ?? "*",
|
|
174
|
+
nonce,
|
|
175
|
+
at,
|
|
176
|
+
...(input.scopes ? [input.scopes.join(",")] : []),
|
|
177
|
+
].join("\n")),
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
/** Redeem a human-created one-use code with a fresh agent key. Human approval is still required. */
|
|
181
|
+
async linkWithInvite(input) {
|
|
182
|
+
if (!/^\d{12}$/.test(input.code))
|
|
183
|
+
throw new Error("Invalid agent invite code");
|
|
184
|
+
const key = (0, node_crypto_1.createPublicKey)(input.privateKey);
|
|
185
|
+
const publicKey = key.export({ format: "pem", type: "spki" }).toString();
|
|
186
|
+
const thumbprint = digest(key.export({ format: "der", type: "spki" }));
|
|
187
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
188
|
+
return this.request("/card/v1/agent-invites/redeem", {
|
|
189
|
+
code: input.code, name: input.name, publicKey, nonce, timestamp: at,
|
|
190
|
+
...(input.scopes ? { scopes: input.scopes } : {}),
|
|
191
|
+
signature: signature(input.privateKey, [
|
|
192
|
+
"valiron-card-agent-invite-v1", digest(input.code), thumbprint,
|
|
193
|
+
input.name, nonce, at,
|
|
194
|
+
...(input.scopes ? [input.scopes.join(",")] : []),
|
|
195
|
+
].join("\n")),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
pollApplication(input) {
|
|
199
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
200
|
+
/** `delegationExpiresAt` is epoch seconds; pass it to registerWbaKey. */
|
|
201
|
+
const result = this.request("/card/v1/pairings/poll", {
|
|
202
|
+
id: input.id,
|
|
203
|
+
pollSecret: input.pollSecret,
|
|
204
|
+
nonce,
|
|
205
|
+
timestamp: at,
|
|
206
|
+
signature: signature(input.privateKey, ["valiron-card-poll-v1", input.id, nonce, at].join("\n")),
|
|
207
|
+
});
|
|
208
|
+
return result.then((polled) => {
|
|
209
|
+
// Remember the delegation's own expiry so a later registerWbaKey on this
|
|
210
|
+
// client bounds its signature without the caller threading it through.
|
|
211
|
+
if (polled.delegationId && Number.isInteger(polled.delegationExpiresAt))
|
|
212
|
+
this.delegationExpiry.set(polled.delegationId, polled.delegationExpiresAt);
|
|
213
|
+
return polled;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
mintToken(input) {
|
|
217
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
218
|
+
return this.request("/card/v1/tokens", {
|
|
219
|
+
delegationId: input.delegationId,
|
|
220
|
+
customerBindingId: input.customerBindingId,
|
|
221
|
+
offerId: input.offerId,
|
|
222
|
+
nonce,
|
|
223
|
+
timestamp: at,
|
|
224
|
+
signature: signature(input.privateKey, [
|
|
225
|
+
"valiron-card-mint-v1",
|
|
226
|
+
input.delegationId,
|
|
227
|
+
input.customerBindingId,
|
|
228
|
+
input.offerId,
|
|
229
|
+
nonce,
|
|
230
|
+
at,
|
|
231
|
+
].join("\n")),
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
verifyPresentation(input) {
|
|
235
|
+
return this.request("/operator/card/v1/decisions", input);
|
|
236
|
+
}
|
|
237
|
+
getMerchantIdentity(merchantId) {
|
|
238
|
+
return this.request(`/card/v1/merchants/${encodeURIComponent(merchantId)}/identity`, undefined, "GET");
|
|
239
|
+
}
|
|
240
|
+
mintIdentityToken(input) {
|
|
241
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
242
|
+
const audienceOrigin = new URL(input.audienceOrigin).origin;
|
|
243
|
+
return this.request("/card/v1/identity-tokens", {
|
|
244
|
+
delegationId: input.delegationId, merchantId: input.merchantId, environment: input.environment,
|
|
245
|
+
audienceOrigin, nonce, timestamp: at, ...(input.format ? { format: input.format } : {}),
|
|
246
|
+
signature: signature(input.privateKey, ["valiron-pass-mint-v1", input.delegationId,
|
|
247
|
+
input.merchantId, input.environment, audienceOrigin, nonce, at].join("\n")),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/** Registers a Web Bot Auth signing key into Valiron's public key directory
|
|
251
|
+
* (/.well-known/http-message-signatures-directory). While the delegation is
|
|
252
|
+
* active, Valiron vouches for the key: requests signed with it verify as
|
|
253
|
+
* coming from a current Valiron Pass holder. Keys expire with the delegation
|
|
254
|
+
* or after 30 days, whichever comes first; re-register to rotate.
|
|
255
|
+
*
|
|
256
|
+
* Registration includes a directory self-signature made with the NEW WBA key
|
|
257
|
+
* (draft-meunier-http-message-signatures-directory-03 section 5.2: each key
|
|
258
|
+
* in a directory provides one signature over "@authority";req, proving the
|
|
259
|
+
* registrant holds the private key). `privateKey` is the DELEGATION key used
|
|
260
|
+
* only to authenticate the registration; `wbaPrivateKey` is the new key. */
|
|
261
|
+
async registerWbaKey(input) {
|
|
262
|
+
const explicit = input.delegationExpiresAt;
|
|
263
|
+
if (explicit !== undefined)
|
|
264
|
+
return this.registerWbaKeyOnce(input, explicit);
|
|
265
|
+
const known = this.delegationExpiry.get(input.delegationId);
|
|
266
|
+
if (known !== undefined)
|
|
267
|
+
return this.registerWbaKeyOnce(input, known);
|
|
268
|
+
try {
|
|
269
|
+
return await this.registerWbaKeyOnce(input, undefined);
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
const learned = error instanceof CardAPIError && error.status === 400 && error.code === "invalid_directory_signature"
|
|
273
|
+
? error.details?.delegationExpiresAt : undefined;
|
|
274
|
+
if (learned === undefined || !Number.isInteger(learned))
|
|
275
|
+
throw error;
|
|
276
|
+
// The server only returns this after the delegation-signed request and the
|
|
277
|
+
// self-signature verified; retry exactly once, bounded by that expiry.
|
|
278
|
+
this.delegationExpiry.set(input.delegationId, learned);
|
|
279
|
+
return this.registerWbaKeyOnce(input, learned);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
registerWbaKeyOnce(input, delegationExpiresAt) {
|
|
283
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
284
|
+
const authority = new URL(this.options.baseUrl).host;
|
|
285
|
+
const jwk = (0, node_crypto_1.createPublicKey)(input.publicKey).export({ format: "jwk" });
|
|
286
|
+
const kid = (0, node_crypto_1.createHash)("sha256")
|
|
287
|
+
.update(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x }))
|
|
288
|
+
.digest("base64url");
|
|
289
|
+
const created = timestamp();
|
|
290
|
+
let expires;
|
|
291
|
+
if (delegationExpiresAt !== undefined) {
|
|
292
|
+
if (!Number.isInteger(delegationExpiresAt))
|
|
293
|
+
throw new CardAPIError(400, "invalid_delegation_expiry");
|
|
294
|
+
// Never sign a lifetime past the delegation, and never one that is about to lapse.
|
|
295
|
+
if (delegationExpiresAt - created < 60)
|
|
296
|
+
throw new CardAPIError(400, "delegation_expiring");
|
|
297
|
+
expires = Math.min(created + 30 * 24 * 3600, delegationExpiresAt);
|
|
298
|
+
}
|
|
299
|
+
const self = createDirectorySelfSignature({ privateKey: input.wbaPrivateKey, keyid: kid }, authority, { created, ...(expires === undefined ? {} : { expires }) });
|
|
300
|
+
return this.request("/card/v1/agent/wba-keys", {
|
|
301
|
+
delegationId: input.delegationId, publicKey: input.publicKey, nonce, timestamp: at,
|
|
302
|
+
directorySignatureParams: self.params, directorySignature: self.signature,
|
|
303
|
+
signature: signature(input.privateKey, ["valiron-pass-wba-v1", input.delegationId,
|
|
304
|
+
input.publicKey, nonce, at].join("\n")),
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
revokeWbaKey(input) {
|
|
308
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
309
|
+
return this.request(`/card/v1/agent/wba-keys/${encodeURIComponent(input.kid)}`, {
|
|
310
|
+
delegationId: input.delegationId, publicKey: input.publicKey, nonce, timestamp: at,
|
|
311
|
+
signature: signature(input.privateKey, ["valiron-pass-wba-revoke-v1", input.delegationId,
|
|
312
|
+
input.publicKey, nonce, at].join("\n")),
|
|
313
|
+
}, "DELETE");
|
|
314
|
+
}
|
|
315
|
+
recognizeAgent(input) {
|
|
316
|
+
return this.request("/operator/card/v1/agents/recognize", input);
|
|
317
|
+
}
|
|
318
|
+
reportAgentEnforcement(input) {
|
|
319
|
+
return this.request(`/operator/card/v1/agent-visits/${encodeURIComponent(input.visitId)}/enforcement`, {
|
|
320
|
+
offerId: input.offerId, allowed: input.allowed,
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
exports.CardClient = CardClient;
|
|
325
|
+
function createPassRequestProof(input) {
|
|
326
|
+
const at = timestamp();
|
|
327
|
+
const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ: "valiron-pass-proof+jwt" })).toString("base64url");
|
|
328
|
+
const payload = Buffer.from(JSON.stringify({ v: 1, aud: input.merchantId, environment: input.environment,
|
|
329
|
+
delegation_id: input.delegationId, token_hash: `sha256:${digest(input.token)}`,
|
|
330
|
+
method: input.method.toUpperCase(), url: input.url, body_digest: `sha256:${digest(input.body ?? "")}`,
|
|
331
|
+
iat: at, exp: at + 60, jti: (0, exports.cardNonce)() })).toString("base64url");
|
|
332
|
+
return `${header}.${payload}.${signature(input.privateKey, `${header}.${payload}`)}`;
|
|
333
|
+
}
|
|
334
|
+
/** Recognizes an explicitly presented Pass. Anonymous requests keep the merchant's normal path.
|
|
335
|
+
* Install before JSON parsing, or supply rawBody containing the exact bytes received.
|
|
336
|
+
* Set requirePass for protected endpoints. A verified human-agent link is identity context,
|
|
337
|
+
* never a replacement for the merchant's account authorization.
|
|
338
|
+
*/
|
|
339
|
+
function createValironPassMiddleware(options) {
|
|
340
|
+
const origin = new URL(options.publicOrigin).origin;
|
|
341
|
+
return async (req, res, next) => {
|
|
342
|
+
const token = req.headers["x-valiron-card-token"], proof = req.headers["x-valiron-card-proof"];
|
|
343
|
+
if (!token && !proof && !options.requirePass)
|
|
344
|
+
return next();
|
|
345
|
+
if (typeof token !== "string" || typeof proof !== "string")
|
|
346
|
+
return res.status(401).json({ code: "pass_proof_required" });
|
|
347
|
+
const method = String(req.method).toUpperCase();
|
|
348
|
+
if (req.rawBody === undefined && !["GET", "HEAD"].includes(method))
|
|
349
|
+
return res.status(400).json({ code: "pass_raw_body_required" });
|
|
350
|
+
const path = String(req.originalUrl ?? req.url);
|
|
351
|
+
if (!path.startsWith("/") || path.startsWith("//") || path.includes("#"))
|
|
352
|
+
return res.status(400).json({ code: "invalid_request_target" });
|
|
353
|
+
try {
|
|
354
|
+
const identity = await options.client.recognizeAgent({ presentationToken: token, proof,
|
|
355
|
+
request: { method, publicUrl: `${origin}${path}`, bodyDigest: `sha256:${digest(req.rawBody ?? "")}`,
|
|
356
|
+
requestId: (0, exports.cardNonce)() } });
|
|
357
|
+
req.valironPass = identity;
|
|
358
|
+
if (options.applyPerk) {
|
|
359
|
+
const outcome = await options.applyPerk(identity);
|
|
360
|
+
if (outcome.offerId && !identity.offers.some((offer) => offer.id === outcome.offerId))
|
|
361
|
+
throw new Error("Unverified perk");
|
|
362
|
+
await options.client.reportAgentEnforcement({ visitId: identity.visitId, ...outcome });
|
|
363
|
+
if (!outcome.allowed) {
|
|
364
|
+
if (outcome.retryAfter)
|
|
365
|
+
res.setHeader("Retry-After", String(outcome.retryAfter));
|
|
366
|
+
return res.status(429).json({ code: "quota_exceeded" });
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
next();
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
const status = error instanceof CardAPIError && [400, 401, 403, 409, 429].includes(error.status) ? error.status : 503;
|
|
373
|
+
return res.status(status).json({ code: status === 503 ? "pass_verification_unavailable" : "pass_verification_failed" });
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
function createCardRequestProof(input) {
|
|
378
|
+
const at = timestamp();
|
|
379
|
+
const header = Buffer.from(JSON.stringify({ alg: "EdDSA", typ: "valiron-card-proof+jwt" })).toString("base64url");
|
|
380
|
+
const payload = Buffer.from(JSON.stringify({
|
|
381
|
+
v: 1,
|
|
382
|
+
aud: input.merchantId,
|
|
383
|
+
delegation_id: input.delegationId,
|
|
384
|
+
customer_binding_id: input.customerBindingId,
|
|
385
|
+
token_hash: `sha256:${digest(input.token)}`,
|
|
386
|
+
method: input.method.toUpperCase(),
|
|
387
|
+
url: input.url,
|
|
388
|
+
body_digest: `sha256:${digest(input.body ?? "")}`,
|
|
389
|
+
iat: at,
|
|
390
|
+
exp: at + 60,
|
|
391
|
+
jti: (0, exports.cardNonce)(),
|
|
392
|
+
})).toString("base64url");
|
|
393
|
+
return `${header}.${payload}.${signature(input.privateKey, `${header}.${payload}`)}`;
|
|
394
|
+
}
|
|
395
|
+
function cardPresentationHeaders(token, proof) {
|
|
396
|
+
return { "X-Valiron-Card-Token": token, "X-Valiron-Card-Proof": proof };
|
|
397
|
+
}
|
|
398
|
+
function createWbaKeyPair() {
|
|
399
|
+
return createCardKey();
|
|
400
|
+
}
|
|
401
|
+
/** The signature every directory key provides over the directory's own
|
|
402
|
+
* authority ("@authority";req with tag http-message-signatures-directory),
|
|
403
|
+
* proving the key's holder controls it. Made once at registration and served
|
|
404
|
+
* verbatim; re-register to rotate. */
|
|
405
|
+
function createDirectorySelfSignature(identity, authority, options) {
|
|
406
|
+
const created = options?.created ?? timestamp();
|
|
407
|
+
const expires = options?.expires ?? created + 30 * 24 * 3600;
|
|
408
|
+
const params = `("@authority";req);alg="ed25519";keyid="${identity.keyid}";nonce="${(0, exports.cardNonce)()}";tag="http-message-signatures-directory";created=${created};expires=${expires}`;
|
|
409
|
+
const base = `"@authority";req: ${authority}\n"@signature-params": ${params}`;
|
|
410
|
+
return { params, signature: (0, node_crypto_1.sign)(null, Buffer.from(base), identity.privateKey).toString("base64") };
|
|
411
|
+
}
|
|
412
|
+
/** Signs one outbound request per draft-ietf-webbotauth-httpsig-protocol-01
|
|
413
|
+
* section 5.2: covers @method (lowercase, RFC 9421 2.2.1), @path, @authority
|
|
414
|
+
* and the Signature-Agent member keyed to the signature label, with
|
|
415
|
+
* tag="web-bot-auth" and a base64url JWK-thumbprint keyid; Signature-Agent is
|
|
416
|
+
* sent in the required Dictionary form. The Pass presentation headers
|
|
417
|
+
* (X-Valiron-Card-Token / X-Valiron-Card-Proof) are covered when present - so
|
|
418
|
+
* a merchant never sees a Pass proof without the WBA signature that binds it
|
|
419
|
+
* (5.2.4 additional headers). Conforms to Valiron's published verifier
|
|
420
|
+
* limits (no @query / @target-uri, ASCII-only covered values). */
|
|
421
|
+
function signWbaRequest(identity, request) {
|
|
422
|
+
const label = "sig1";
|
|
423
|
+
const url = new URL(request.url);
|
|
424
|
+
// Verifiers compare against the normalized absolute-URI form (URL.href).
|
|
425
|
+
const agentUrl = new URL(identity.signatureAgent).href;
|
|
426
|
+
const headers = {};
|
|
427
|
+
for (const [name, value] of Object.entries(request.headers))
|
|
428
|
+
headers[name.toLowerCase()] = value;
|
|
429
|
+
const signatureAgentValue = `${label}="${agentUrl}"`;
|
|
430
|
+
headers["signature-agent"] = signatureAgentValue;
|
|
431
|
+
const covered = ["@method", "@path", "@authority", "signature-agent"];
|
|
432
|
+
for (const name of ["x-valiron-card-token", "x-valiron-card-proof"])
|
|
433
|
+
if (headers[name])
|
|
434
|
+
covered.push(name);
|
|
435
|
+
const lines = [];
|
|
436
|
+
for (const component of covered) {
|
|
437
|
+
let value;
|
|
438
|
+
let identifier = `"${component}"`;
|
|
439
|
+
if (component === "@method")
|
|
440
|
+
value = request.method.toLowerCase();
|
|
441
|
+
else if (component === "@path")
|
|
442
|
+
value = url.pathname || "/";
|
|
443
|
+
else if (component === "@authority")
|
|
444
|
+
value = url.host.toLowerCase();
|
|
445
|
+
else if (component === "signature-agent") {
|
|
446
|
+
identifier = `"signature-agent";key="${label}"`;
|
|
447
|
+
value = `"${agentUrl}"`;
|
|
448
|
+
}
|
|
449
|
+
else
|
|
450
|
+
value = headers[component];
|
|
451
|
+
if (/[^\x20-\x7e]/.test(value))
|
|
452
|
+
throw new Error("Web Bot Auth covered values must be printable ASCII");
|
|
453
|
+
lines.push(`${identifier}: ${value}`);
|
|
454
|
+
}
|
|
455
|
+
const created = timestamp(), expires = created + 60;
|
|
456
|
+
const params = `(${covered.map((c) => c === "signature-agent" ? `"signature-agent";key="${label}"` : `"${c}"`).join(" ")});created=${created};expires=${expires};keyid="${identity.keyid}";alg="ed25519";nonce="${(0, exports.cardNonce)()}";tag="web-bot-auth"`;
|
|
457
|
+
lines.push(`"@signature-params": ${params}`);
|
|
458
|
+
const signatureValue = (0, node_crypto_1.sign)(null, Buffer.from(lines.join("\n")), identity.privateKey).toString("base64");
|
|
459
|
+
return {
|
|
460
|
+
...request.headers,
|
|
461
|
+
"Signature-Agent": signatureAgentValue,
|
|
462
|
+
"Signature-Input": `${label}=${params}`,
|
|
463
|
+
Signature: `${label}=:${signatureValue}:`,
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
function accountSnapshotUsable(value, expected, now = Date.now()) {
|
|
467
|
+
return (value.eligible &&
|
|
468
|
+
value.verificationMode === "owner_account" &&
|
|
469
|
+
value.customerBindingId === expected.bindingId &&
|
|
470
|
+
value.versions.offer === expected.offerVersion &&
|
|
471
|
+
Date.parse(value.expiresAt) > now &&
|
|
472
|
+
Date.parse(value.expiresAt) <= now + 60000);
|
|
473
|
+
}
|
|
474
|
+
/** Atomic fixed windows use Redis time and one owner bucket, shared by account and agent modes. */
|
|
475
|
+
const quotaScript = `
|
|
476
|
+
local t=redis.call('TIME')
|
|
477
|
+
local window=math.floor(tonumber(t[1])/60)
|
|
478
|
+
local owner=KEYS[1]..':'..window
|
|
479
|
+
local global=KEYS[2]..':'..window
|
|
480
|
+
local used=tonumber(redis.call('GET',owner) or '0')
|
|
481
|
+
local total=tonumber(redis.call('GET',global) or '0')
|
|
482
|
+
local retry=60-(tonumber(t[1])%60)
|
|
483
|
+
if used>=tonumber(ARGV[1]) or total>=tonumber(ARGV[2]) then return {0,retry,0} end
|
|
484
|
+
redis.call('INCR',owner);redis.call('EXPIRE',owner,120)
|
|
485
|
+
redis.call('INCR',global);redis.call('EXPIRE',global,120)
|
|
486
|
+
return {1,retry,tonumber(ARGV[1])-used-1}
|
|
487
|
+
`;
|
|
488
|
+
function createCardQuotaAdapter(options) {
|
|
489
|
+
if (!Number.isSafeInteger(options.globalLimit) ||
|
|
490
|
+
options.globalLimit < 1 ||
|
|
491
|
+
!Number.isSafeInteger(options.hardOwnerLimit) ||
|
|
492
|
+
options.hardOwnerLimit < 1)
|
|
493
|
+
throw new Error("Explicit quota caps required");
|
|
494
|
+
const tag = digest(`${options.merchantId}:${options.environment}:${options.endpoint}`).slice(0, 24);
|
|
495
|
+
return {
|
|
496
|
+
async consume(input) {
|
|
497
|
+
if (!input.subject ||
|
|
498
|
+
!Number.isSafeInteger(input.limit) ||
|
|
499
|
+
input.limit < 1)
|
|
500
|
+
throw new Error("Trusted subject and limit required");
|
|
501
|
+
const keys = [
|
|
502
|
+
`card-quota:{${tag}}:owner:${digest(input.subject)}`,
|
|
503
|
+
`card-quota:{${tag}}:global`,
|
|
504
|
+
];
|
|
505
|
+
const result = (await options.redis.eval(quotaScript, 2, ...keys, Math.min(input.limit, options.hardOwnerLimit), options.globalLimit));
|
|
506
|
+
return {
|
|
507
|
+
allowed: result[0] === 1,
|
|
508
|
+
retryAfter: result[1],
|
|
509
|
+
remaining: result[2],
|
|
510
|
+
};
|
|
511
|
+
},
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
function createValironCardGate(options) {
|
|
515
|
+
return async (req, res, next) => {
|
|
516
|
+
try {
|
|
517
|
+
const token = req.headers["x-valiron-card-token"], proof = req.headers["x-valiron-card-proof"];
|
|
518
|
+
if (typeof token !== "string" || typeof proof !== "string")
|
|
519
|
+
return res.status(401).json({ code: "card_proof_required" });
|
|
520
|
+
const method = String(req.method).toUpperCase();
|
|
521
|
+
if (req.rawBody === undefined && !["GET", "HEAD"].includes(method))
|
|
522
|
+
return res.status(400).json({ code: "card_raw_body_required" });
|
|
523
|
+
const result = await options.client.verifyPresentation({
|
|
524
|
+
presentationToken: token,
|
|
525
|
+
proof,
|
|
526
|
+
request: {
|
|
527
|
+
method,
|
|
528
|
+
publicUrl: `${new URL(options.publicOrigin).origin}${req.originalUrl ?? req.url}`,
|
|
529
|
+
bodyDigest: `sha256:${digest(req.rawBody ?? "")}`,
|
|
530
|
+
customerBindingId: options.customerBinding(req),
|
|
531
|
+
requestId: String(req.id ?? (0, exports.cardNonce)()),
|
|
532
|
+
},
|
|
533
|
+
});
|
|
534
|
+
if (!result.eligible || result.verificationMode !== "delegated_agent")
|
|
535
|
+
return res.status(403).json({ code: "card_mode_mismatch" });
|
|
536
|
+
const quota = await options.consumeQuota(result);
|
|
537
|
+
await options.client.reportEnforcement({
|
|
538
|
+
decisionId: result.decisionId,
|
|
539
|
+
requestId: String(req.id ?? result.decisionId),
|
|
540
|
+
allowed: quota.allowed,
|
|
541
|
+
});
|
|
542
|
+
if (!quota.allowed) {
|
|
543
|
+
res.setHeader("Retry-After", String(quota.retryAfter));
|
|
544
|
+
return res.status(429).json({ code: "quota_exceeded" });
|
|
545
|
+
}
|
|
546
|
+
options.onVerified?.(req, result);
|
|
547
|
+
next();
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return res.status(503).json({ code: "card_verification_unavailable" });
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
/** Automatically renews short-lived credentials without extending owner consent or delegation. */
|
|
555
|
+
class CardAgent {
|
|
556
|
+
constructor(options) {
|
|
557
|
+
this.options = options;
|
|
558
|
+
this.tokens = new Map();
|
|
559
|
+
this.pending = new Map();
|
|
560
|
+
}
|
|
561
|
+
/** Carries the approved human identity to an integrated business without an offer or account binding. */
|
|
562
|
+
async identityFor(input) {
|
|
563
|
+
const environment = input.environment ?? "live", audienceOrigin = new URL(input.url).origin;
|
|
564
|
+
const cacheKey = `identity:${input.merchantId}:${environment}:${audienceOrigin}`;
|
|
565
|
+
const cached = this.tokens.get(cacheKey);
|
|
566
|
+
let token = cached && cached.expiresAt > Date.now() + 30000 ? cached.token : undefined;
|
|
567
|
+
if (!token) {
|
|
568
|
+
let mint = this.pending.get(cacheKey);
|
|
569
|
+
if (!mint) {
|
|
570
|
+
mint = this.options.client.mintIdentityToken({ delegationId: this.options.delegationId,
|
|
571
|
+
privateKey: this.options.privateKey, merchantId: input.merchantId, environment, audienceOrigin })
|
|
572
|
+
.then((result) => {
|
|
573
|
+
this.tokens.set(cacheKey, { token: result.token, expiresAt: Date.now() + result.expiresIn * 1000 });
|
|
574
|
+
return result.token;
|
|
575
|
+
}).finally(() => { this.pending.delete(cacheKey); });
|
|
576
|
+
this.pending.set(cacheKey, mint);
|
|
577
|
+
}
|
|
578
|
+
token = await mint;
|
|
579
|
+
}
|
|
580
|
+
const presentation = cardPresentationHeaders(token, createPassRequestProof({ ...input, environment, token,
|
|
581
|
+
delegationId: this.options.delegationId, privateKey: this.options.privateKey }));
|
|
582
|
+
if (this.options.webBotAuth)
|
|
583
|
+
return signWbaRequest(this.options.webBotAuth, { method: input.method, url: input.url, headers: presentation });
|
|
584
|
+
return presentation;
|
|
585
|
+
}
|
|
586
|
+
async presentationFor(input) {
|
|
587
|
+
const cacheKey = `${input.merchantId}:${input.customerBindingId}:${input.offerId}`;
|
|
588
|
+
const cached = this.tokens.get(cacheKey);
|
|
589
|
+
let token = cached && cached.expiresAt > Date.now() + 30000
|
|
590
|
+
? cached.token
|
|
591
|
+
: undefined;
|
|
592
|
+
if (!token) {
|
|
593
|
+
let mint = this.pending.get(cacheKey);
|
|
594
|
+
if (!mint) {
|
|
595
|
+
mint = this.options.client
|
|
596
|
+
.mintToken({
|
|
597
|
+
delegationId: this.options.delegationId,
|
|
598
|
+
privateKey: this.options.privateKey,
|
|
599
|
+
customerBindingId: input.customerBindingId,
|
|
600
|
+
offerId: input.offerId,
|
|
601
|
+
})
|
|
602
|
+
.then((result) => {
|
|
603
|
+
this.tokens.set(cacheKey, {
|
|
604
|
+
token: result.token,
|
|
605
|
+
expiresAt: Date.now() + result.expiresIn * 1000,
|
|
606
|
+
});
|
|
607
|
+
return result.token;
|
|
608
|
+
})
|
|
609
|
+
.finally(() => {
|
|
610
|
+
this.pending.delete(cacheKey);
|
|
611
|
+
});
|
|
612
|
+
this.pending.set(cacheKey, mint);
|
|
613
|
+
}
|
|
614
|
+
token = await mint;
|
|
615
|
+
}
|
|
616
|
+
const proof = createCardRequestProof({
|
|
617
|
+
...input,
|
|
618
|
+
privateKey: this.options.privateKey,
|
|
619
|
+
delegationId: this.options.delegationId,
|
|
620
|
+
token,
|
|
621
|
+
});
|
|
622
|
+
const presentation = cardPresentationHeaders(token, proof);
|
|
623
|
+
if (this.options.webBotAuth)
|
|
624
|
+
return signWbaRequest(this.options.webBotAuth, { method: input.method, url: input.url, headers: presentation });
|
|
625
|
+
return presentation;
|
|
626
|
+
}
|
|
627
|
+
clearCredentials() {
|
|
628
|
+
this.tokens.clear();
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
exports.CardAgent = CardAgent;
|
|
632
|
+
/** Deterministic JSON matching the Card backend so signatures cover identical bytes. */
|
|
633
|
+
function canonicalCardJson(value) {
|
|
634
|
+
if (Array.isArray(value))
|
|
635
|
+
return `[${value.map(canonicalCardJson).join(",")}]`;
|
|
636
|
+
if (value && typeof value === "object")
|
|
637
|
+
return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalCardJson(value[k])}`).join(",")}}`;
|
|
638
|
+
return JSON.stringify(value);
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* Speaks MCP (JSON-RPC over POST) to the Valiron Pass MCP endpoint. Following
|
|
642
|
+
* the MCP authorization spec, the endpoint is an OAuth-style resource server:
|
|
643
|
+
* this client mints a short-lived scoped bearer token by signing a token grant
|
|
644
|
+
* with the owner-approved agent key, then sends it as Authorization: Bearer.
|
|
645
|
+
* The server enforces the scopes the owner granted at approval and records the
|
|
646
|
+
* action history.
|
|
647
|
+
*/
|
|
648
|
+
class CardMcpClient {
|
|
649
|
+
constructor(options) {
|
|
650
|
+
this.options = options;
|
|
651
|
+
}
|
|
652
|
+
async accessToken() {
|
|
653
|
+
if (this.token && this.token.expiresAt > Date.now() + 30000)
|
|
654
|
+
return this.token.value;
|
|
655
|
+
if (!this.pending) {
|
|
656
|
+
const scopes = this.options.scopes ?? ["offers:read"];
|
|
657
|
+
const nonce = (0, exports.cardNonce)(), at = timestamp();
|
|
658
|
+
this.pending = this.options.client.request("/card/v1/mcp/tokens", {
|
|
659
|
+
delegationId: this.options.delegationId, scopes, nonce, timestamp: at,
|
|
660
|
+
signature: signature(this.options.privateKey, [
|
|
661
|
+
"valiron-pass-mcp-token-v1", this.options.delegationId, scopes.join(","), nonce, at,
|
|
662
|
+
].join("\n")),
|
|
663
|
+
}).then((result) => {
|
|
664
|
+
this.token = { value: result.access_token, expiresAt: Date.now() + result.expires_in * 1000 };
|
|
665
|
+
return result.access_token;
|
|
666
|
+
}).finally(() => { this.pending = undefined; });
|
|
667
|
+
}
|
|
668
|
+
return this.pending;
|
|
669
|
+
}
|
|
670
|
+
async rpc(method, params, authenticate) {
|
|
671
|
+
const value = await this.options.client.request("/card/v1/mcp", { jsonrpc: "2.0", id: (0, exports.cardNonce)(), method, params: params ?? {} }, "POST", authenticate ? { Authorization: `Bearer ${await this.accessToken()}` } : {});
|
|
672
|
+
if (value?.error)
|
|
673
|
+
throw new Error(`MCP ${method} failed: ${value.error.code} ${value.error.message}`);
|
|
674
|
+
return value?.result;
|
|
675
|
+
}
|
|
676
|
+
initialize() {
|
|
677
|
+
return this.rpc("initialize", {
|
|
678
|
+
protocolVersion: "2025-06-18",
|
|
679
|
+
capabilities: {},
|
|
680
|
+
clientInfo: { name: "valiron-sdk", version: "1.6.0" },
|
|
681
|
+
}, false);
|
|
682
|
+
}
|
|
683
|
+
listTools() {
|
|
684
|
+
return this.rpc("tools/list", {}, true);
|
|
685
|
+
}
|
|
686
|
+
callTool(name, args = {}) {
|
|
687
|
+
return this.rpc("tools/call", { name, arguments: args }, true);
|
|
688
|
+
}
|
|
689
|
+
listOffers() { return this.callTool("valiron_pass_list_offers"); }
|
|
690
|
+
getOffer(offerId) { return this.callTool("valiron_pass_get_offer", { offerId }); }
|
|
691
|
+
/** Claiming shares what a manual owner claim shares today (email + Card profile, future updates included) - the owner approved this when linking the agent. */
|
|
692
|
+
claimOffer(offerId) { return this.callTool("valiron_pass_claim_offer", { offerId }); }
|
|
693
|
+
clearCredentials() { this.token = undefined; }
|
|
694
|
+
}
|
|
695
|
+
exports.CardMcpClient = CardMcpClient;
|
|
696
|
+
/**
|
|
697
|
+
* Canonical payload the Card backend asks the agent to sign when the owner
|
|
698
|
+
* links their delegation to an operator agent identity (wallet, optionally an
|
|
699
|
+
* ERC-8004 agent id). Mirrors linkPayload in the edge card agentLinks module;
|
|
700
|
+
* the challenge endpoint also returns the exact string to sign, so prefer
|
|
701
|
+
* signing that value and use this only to cross-check it.
|
|
702
|
+
*/
|
|
703
|
+
function buildAgentLinkPayload(input) {
|
|
704
|
+
return [
|
|
705
|
+
"valiron-pass-agent-link-v1",
|
|
706
|
+
`delegation:${input.delegationId}`,
|
|
707
|
+
`agent:${input.agentAddress.toLowerCase()}`,
|
|
708
|
+
`network:${input.network}`,
|
|
709
|
+
`agent-id:${input.agentId ?? ""}`,
|
|
710
|
+
`nonce:${input.nonce}`,
|
|
711
|
+
`expires:${input.expiresAt}`,
|
|
712
|
+
].join("\n");
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Signs an agent-link payload with the owner-approved delegation key
|
|
716
|
+
* (Ed25519, base64url). The operator agent wallet signs the same payload with
|
|
717
|
+
* any EIP-191 signer (for example viem's signMessage); the backend verifies
|
|
718
|
+
* both proofs and, for an on-chain agent id, the registry ownerOf match.
|
|
719
|
+
*/
|
|
720
|
+
function signAgentLinkPayload(privateKey, payload) {
|
|
721
|
+
return signature(privateKey, payload);
|
|
722
|
+
}
|