@vorim/sdk 3.11.0 → 3.12.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/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/integrations/cloudflare.cjs +134 -0
- package/dist/integrations/cloudflare.cjs.map +1 -0
- package/dist/integrations/cloudflare.d.cts +93 -0
- package/dist/integrations/cloudflare.d.ts +93 -0
- package/dist/integrations/cloudflare.js +108 -0
- package/dist/integrations/cloudflare.js.map +1 -0
- package/dist/integrations/shopify.cjs +203 -0
- package/dist/integrations/shopify.cjs.map +1 -0
- package/dist/integrations/shopify.d.cts +175 -0
- package/dist/integrations/shopify.d.ts +175 -0
- package/dist/integrations/shopify.js +177 -0
- package/dist/integrations/shopify.js.map +1 -0
- package/dist/integrations/web-bot-auth.cjs +143 -0
- package/dist/integrations/web-bot-auth.cjs.map +1 -0
- package/dist/integrations/web-bot-auth.d.cts +51 -0
- package/dist/integrations/web-bot-auth.d.ts +51 -0
- package/dist/integrations/web-bot-auth.js +108 -0
- package/dist/integrations/web-bot-auth.js.map +1 -0
- package/package.json +31 -1
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// src/integrations/shopify.ts
|
|
2
|
+
var OPERATION_SCOPE = {
|
|
3
|
+
read: "agent:read",
|
|
4
|
+
orderCreate: "agent:write",
|
|
5
|
+
inventoryAdjustQuantities: "agent:write",
|
|
6
|
+
fulfillmentCreate: "agent:write",
|
|
7
|
+
returnProcess: "agent:write",
|
|
8
|
+
productCreate: "agent:write",
|
|
9
|
+
productUpdate: "agent:write",
|
|
10
|
+
refundCreate: "agent:transact"
|
|
11
|
+
};
|
|
12
|
+
var VorimShopify = class {
|
|
13
|
+
sdk;
|
|
14
|
+
agentId;
|
|
15
|
+
shopDomain;
|
|
16
|
+
humanId;
|
|
17
|
+
minTrustScore;
|
|
18
|
+
maxRefundAmount;
|
|
19
|
+
onError;
|
|
20
|
+
constructor(sdk, config) {
|
|
21
|
+
if (!config?.agentId) throw new Error("[vorim] Shopify integration requires an agentId.");
|
|
22
|
+
if (!config?.shopDomain) throw new Error("[vorim] Shopify integration requires a shopDomain.");
|
|
23
|
+
this.sdk = sdk;
|
|
24
|
+
this.agentId = config.agentId;
|
|
25
|
+
this.shopDomain = config.shopDomain;
|
|
26
|
+
this.humanId = config.humanId;
|
|
27
|
+
this.minTrustScore = config.minTrustScore ?? 0;
|
|
28
|
+
this.maxRefundAmount = config.maxRefundAmount;
|
|
29
|
+
this.onError = config.onError ?? "closed";
|
|
30
|
+
}
|
|
31
|
+
/** The Vorim scope a given operation requires. Unknown mutations fall back to
|
|
32
|
+
* agent:write (a mutation is at least a write). */
|
|
33
|
+
scopeFor(operation) {
|
|
34
|
+
return OPERATION_SCOPE[operation] ?? "agent:write";
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Check whether the acting agent may run this store operation, before it
|
|
38
|
+
* runs. Enforces (in order): trust floor, refund ceiling, permission scope.
|
|
39
|
+
* Returns { authorized, reason }.
|
|
40
|
+
*/
|
|
41
|
+
async authorize(action) {
|
|
42
|
+
const scope = this.scopeFor(action.operation);
|
|
43
|
+
if (action.operation === "refundCreate" && this.maxRefundAmount != null && typeof action.amount === "number" && action.amount > this.maxRefundAmount) {
|
|
44
|
+
return {
|
|
45
|
+
authorized: false,
|
|
46
|
+
reason: `refund ${action.amount} exceeds this agent's ceiling of ${this.maxRefundAmount}`
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
if (this.minTrustScore > 0) {
|
|
51
|
+
const trust = await this.sdk.verify(this.agentId);
|
|
52
|
+
if ((trust?.trust_score ?? 0) < this.minTrustScore) {
|
|
53
|
+
return { authorized: false, reason: `trust score below ${this.minTrustScore}` };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const perm = await this.sdk.check(this.agentId, scope);
|
|
57
|
+
return perm.allowed ? { authorized: true } : { authorized: false, reason: perm.reason ?? `missing scope ${scope}` };
|
|
58
|
+
} catch (e) {
|
|
59
|
+
return this.onError === "open" ? { authorized: true, reason: "vorim unreachable, failed open" } : { authorized: false, reason: `vorim unreachable: ${e?.message ?? "error"}` };
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Emit a source-signed audit event for a store operation and return whether
|
|
64
|
+
* it was recorded. Called after the mutation runs (or after a denial). The
|
|
65
|
+
* event names the agent, the shop, and the human the agent acts for, so the
|
|
66
|
+
* record is attributable and independently verifiable offline.
|
|
67
|
+
*/
|
|
68
|
+
async record(action, result, reason) {
|
|
69
|
+
const scope = this.scopeFor(action.operation);
|
|
70
|
+
try {
|
|
71
|
+
await this.sdk.emit({
|
|
72
|
+
agent_id: this.agentId,
|
|
73
|
+
event_type: "api_request",
|
|
74
|
+
action: `shopify:${action.operation}${action.resourceId ? " " + action.resourceId : ""}`,
|
|
75
|
+
resource: action.resourceId || this.shopDomain,
|
|
76
|
+
permission: scope,
|
|
77
|
+
result,
|
|
78
|
+
input_hash: action.inputHash,
|
|
79
|
+
metadata: {
|
|
80
|
+
integration: "shopify-admin",
|
|
81
|
+
shop_domain: this.shopDomain,
|
|
82
|
+
acts_for_human: this.humanId,
|
|
83
|
+
operation: action.operation,
|
|
84
|
+
...action.amount != null ? { amount: action.amount } : {},
|
|
85
|
+
...action.currency ? { currency: action.currency } : {},
|
|
86
|
+
...reason ? { reason } : {}
|
|
87
|
+
}
|
|
88
|
+
}, { sign: true });
|
|
89
|
+
return true;
|
|
90
|
+
} catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The full flow for one store operation: authorize, run the Admin GraphQL
|
|
96
|
+
* mutation if allowed, sign a receipt either way. If not authorized, `run` is
|
|
97
|
+
* never called (the mutation does not happen). Rethrows an error from `run`
|
|
98
|
+
* after recording it, with the receipt attached as `vorimReceipt`, so your
|
|
99
|
+
* handler still sees Shopify failures.
|
|
100
|
+
*/
|
|
101
|
+
async guard(action, run) {
|
|
102
|
+
const auth = await this.authorize(action);
|
|
103
|
+
if (!auth.authorized) {
|
|
104
|
+
const recorded = await this.record(action, "denied", auth.reason);
|
|
105
|
+
return { receipt: this.receipt(action, false, "denied", auth.reason, recorded) };
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
const value = await run();
|
|
109
|
+
const recorded = await this.record(action, "success");
|
|
110
|
+
return { receipt: this.receipt(action, true, "success", void 0, recorded), value };
|
|
111
|
+
} catch (e) {
|
|
112
|
+
const recorded = await this.record(action, "error", e?.message);
|
|
113
|
+
throw Object.assign(e ?? new Error("shopify operation failed"), {
|
|
114
|
+
vorimReceipt: this.receipt(action, true, "error", e?.message, recorded)
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// --- Named helpers for the high-risk Admin mutations -----------------------
|
|
119
|
+
// Each wraps guard() with the right operation label so the scope and receipt
|
|
120
|
+
// are correct without the caller having to remember the mapping. You pass the
|
|
121
|
+
// GraphQL call as `run`; this layer never talks to Shopify itself.
|
|
122
|
+
/** Guard an `orderCreate`. Requires agent:write. */
|
|
123
|
+
orderCreate(meta, run) {
|
|
124
|
+
return this.guard({ operation: "orderCreate", resourceId: meta.orderId, inputHash: meta.inputHash }, run);
|
|
125
|
+
}
|
|
126
|
+
/** Guard a `refundCreate`. Requires agent:transact AND stays within
|
|
127
|
+
* `maxRefundAmount` if one was configured. `amount` is in minor units. */
|
|
128
|
+
refundCreate(meta, run) {
|
|
129
|
+
return this.guard(
|
|
130
|
+
{ operation: "refundCreate", resourceId: meta.orderId, amount: meta.amount, currency: meta.currency, inputHash: meta.inputHash },
|
|
131
|
+
run
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
/** Guard an `inventoryAdjustQuantities`. Requires agent:write. */
|
|
135
|
+
inventoryAdjustQuantities(meta, run) {
|
|
136
|
+
return this.guard({ operation: "inventoryAdjustQuantities", resourceId: meta.resourceId, inputHash: meta.inputHash }, run);
|
|
137
|
+
}
|
|
138
|
+
/** Guard a `fulfillmentCreate`. Requires agent:write. */
|
|
139
|
+
fulfillmentCreate(meta, run) {
|
|
140
|
+
return this.guard({ operation: "fulfillmentCreate", resourceId: meta.orderId, inputHash: meta.inputHash }, run);
|
|
141
|
+
}
|
|
142
|
+
/** Guard a `returnProcess`. Requires agent:write. */
|
|
143
|
+
returnProcess(meta, run) {
|
|
144
|
+
return this.guard({ operation: "returnProcess", resourceId: meta.resourceId, inputHash: meta.inputHash }, run);
|
|
145
|
+
}
|
|
146
|
+
/** Guard a `productCreate` or `productUpdate`. Requires agent:write. */
|
|
147
|
+
productWrite(meta, run) {
|
|
148
|
+
return this.guard(
|
|
149
|
+
{ operation: meta.operation ?? "productUpdate", resourceId: meta.productId, inputHash: meta.inputHash },
|
|
150
|
+
run
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
receipt(action, authorized, result, reason, recorded) {
|
|
154
|
+
return {
|
|
155
|
+
authorized,
|
|
156
|
+
agentId: this.agentId,
|
|
157
|
+
humanId: this.humanId,
|
|
158
|
+
shopDomain: this.shopDomain,
|
|
159
|
+
operation: action.operation,
|
|
160
|
+
resourceId: action.resourceId,
|
|
161
|
+
amount: action.amount,
|
|
162
|
+
currency: action.currency,
|
|
163
|
+
result,
|
|
164
|
+
scope: this.scopeFor(action.operation),
|
|
165
|
+
reason,
|
|
166
|
+
recorded
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
function createVorimShopify(sdk, config) {
|
|
171
|
+
return new VorimShopify(sdk, config);
|
|
172
|
+
}
|
|
173
|
+
export {
|
|
174
|
+
VorimShopify,
|
|
175
|
+
createVorimShopify
|
|
176
|
+
};
|
|
177
|
+
//# sourceMappingURL=shopify.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/shopify.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Shopify (merchant-side store operations) Integration\n//\n// This guards an AI agent that MANAGES a Shopify store through the Admin\n// GraphQL API — creating orders, issuing refunds, adjusting inventory,\n// fulfilling, processing returns, editing products. Before each mutation runs\n// it checks the acting agent holds the right permission (and, for refunds, that\n// the amount is within a delegated ceiling), then signs a tamper-evident audit\n// record of what the agent did.\n//\n// WHY MERCHANT-SIDE, NOT CHECKOUT\n// The buyer-side purchase moment is already covered by signed rails: ACP's\n// delegated payment token + allowance, Visa's Trusted Agent Protocol and Web\n// Bot Auth (per-agent Ed25519 identity over the HTTP request — Vorim already\n// integrates Web Bot Auth), and AP2's signed mandates. Those prove identity and\n// payment authorization AT THE MOMENT OF PURCHASE and then stop at the\n// transaction boundary. None of them produce a signed, attenuated record of an\n// agent's operations ON THE STORE. On the Admin API an agent authenticates with\n// a single OAuth token and coarse write_* scopes: every agent on that token\n// looks identical, there is no way to cap a sub-agent below write_orders, and\n// nothing proves agent X (not agent Y) issued a given refundCreate. That is the\n// gap this fills. It COMPOSES WITH Web Bot Auth / TAP on the buyer side rather\n// than competing with the payment rails.\n//\n// SCOPE MAPPING (uses Vorim's three real scopes)\n// read Admin data -> agent:read\n// mutate the store -> agent:write (orders, inventory, fulfil,\n// returns, products)\n// move money back to a buyer -> agent:transact (refundCreate) + amount cap\n//\n// This layer never holds a Shopify token and never calls Shopify itself. You\n// pass it the mutation to run; it authorizes, runs it, and signs the receipt.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimShopify } from '@vorim/sdk/integrations/shopify';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const shop = createVorimShopify(vorim, {\n// agentId: 'agid_abc123',\n// shopDomain: 'acme.myshopify.com',\n// humanId: 'user_42', // the person the agent acts for\n// maxRefundAmount: 20000, // cap this agent's refunds at $200.00 (cents)\n// });\n//\n// // Wrap the Admin GraphQL call you were going to make anyway:\n// const { receipt, value } = await shop.refundCreate(\n// { orderId: 'gid://shopify/Order/123', amount: 4999, currency: 'USD' },\n// () => adminClient.request(REFUND_CREATE_MUTATION, { input }),\n// );\n// if (!receipt.authorized) console.warn(receipt.reason);\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\nimport type { PermissionScope } from '../types.js';\n\n/** The Admin GraphQL mutations this guard knows how to classify. Any other\n * label is accepted too; it just defaults to the 'write' risk tier. */\nexport type ShopifyOperation =\n | 'orderCreate'\n | 'refundCreate'\n | 'inventoryAdjustQuantities'\n | 'fulfillmentCreate'\n | 'returnProcess'\n | 'productCreate'\n | 'productUpdate'\n | 'read';\n\n/** Map each Admin mutation to the least Vorim scope that should be required to\n * run it. Reads need read; store mutations need write; moving money back to a\n * customer (refundCreate) needs transact, the same scope Vorim requires for\n * any value-moving action. */\nconst OPERATION_SCOPE: Record<string, PermissionScope> = {\n read: 'agent:read',\n orderCreate: 'agent:write',\n inventoryAdjustQuantities: 'agent:write',\n fulfillmentCreate: 'agent:write',\n returnProcess: 'agent:write',\n productCreate: 'agent:write',\n productUpdate: 'agent:write',\n refundCreate: 'agent:transact',\n};\n\nexport interface ShopifyGuardConfig {\n /** The acting agent's Vorim id (agid_...). */\n agentId: string;\n /** The store this agent operates on, e.g. 'acme.myshopify.com'. Recorded in\n * every receipt so an action is attributable to a specific shop. */\n shopDomain: string;\n /** The human/principal the agent acts for. Recorded in every receipt so a\n * store action is attributable to a person, not just a machine. */\n humanId?: string;\n /** Minimum trust score the acting agent must hold before any mutation runs.\n * Default 0 (off). */\n minTrustScore?: number;\n /** Attenuation: cap the total this agent may refund in a single refundCreate,\n * in the currency's minor unit (e.g. cents). Shopify's coarse write_orders\n * scope cannot express this; Vorim can. Omit for no ceiling. */\n maxRefundAmount?: number;\n /** Fail closed (deny on any Vorim error) or fail open. Default 'closed'. */\n onError?: 'closed' | 'open';\n}\n\nexport interface ShopifyAction {\n /** The Admin GraphQL mutation being run, e.g. 'refundCreate'. Drives the\n * scope requirement. Unknown labels default to the 'write' tier. */\n operation: ShopifyOperation | string;\n /** The Shopify resource the action targets, e.g. an order or product GID. */\n resourceId?: string;\n /** For refundCreate: the amount moving back to the customer, in the minor\n * unit (cents). Checked against maxRefundAmount. */\n amount?: number;\n /** Currency code for `amount`, e.g. 'USD'. Informational. */\n currency?: string;\n /** Optional hash of the mutation variables so the receipt covers the exact\n * input without the guard storing it. */\n inputHash?: string;\n}\n\n/** An offline-verifiable receipt for one Shopify store operation. */\nexport interface ShopifyReceipt {\n authorized: boolean;\n agentId: string;\n humanId?: string;\n shopDomain: string;\n operation: string;\n resourceId?: string;\n amount?: number;\n currency?: string;\n result: 'success' | 'denied' | 'error';\n scope: PermissionScope;\n /** Reason a check failed, when authorized is false. */\n reason?: string;\n /** True once the audit event was signed and ingested. */\n recorded: boolean;\n}\n\nexport class VorimShopify {\n private sdk: VorimSDK;\n private agentId: string;\n private shopDomain: string;\n private humanId?: string;\n private minTrustScore: number;\n private maxRefundAmount?: number;\n private onError: 'closed' | 'open';\n\n constructor(sdk: VorimSDK, config: ShopifyGuardConfig) {\n if (!config?.agentId) throw new Error('[vorim] Shopify integration requires an agentId.');\n if (!config?.shopDomain) throw new Error('[vorim] Shopify integration requires a shopDomain.');\n this.sdk = sdk;\n this.agentId = config.agentId;\n this.shopDomain = config.shopDomain;\n this.humanId = config.humanId;\n this.minTrustScore = config.minTrustScore ?? 0;\n this.maxRefundAmount = config.maxRefundAmount;\n this.onError = config.onError ?? 'closed';\n }\n\n /** The Vorim scope a given operation requires. Unknown mutations fall back to\n * agent:write (a mutation is at least a write). */\n private scopeFor(operation: string): PermissionScope {\n return OPERATION_SCOPE[operation] ?? 'agent:write';\n }\n\n /**\n * Check whether the acting agent may run this store operation, before it\n * runs. Enforces (in order): trust floor, refund ceiling, permission scope.\n * Returns { authorized, reason }.\n */\n async authorize(action: ShopifyAction): Promise<{ authorized: boolean; reason?: string }> {\n const scope = this.scopeFor(action.operation);\n\n // Attenuation: a refund above this agent's delegated ceiling is denied\n // before any Vorim round-trip. This is the differentiator over Shopify's\n // coarse write_orders scope, which cannot bound a refund amount.\n if (\n action.operation === 'refundCreate' &&\n this.maxRefundAmount != null &&\n typeof action.amount === 'number' &&\n action.amount > this.maxRefundAmount\n ) {\n return {\n authorized: false,\n reason: `refund ${action.amount} exceeds this agent's ceiling of ${this.maxRefundAmount}`,\n };\n }\n\n try {\n // Trust floor (optional): refuse low-trust agents up front.\n if (this.minTrustScore > 0) {\n const trust = await this.sdk.verify(this.agentId);\n if ((trust?.trust_score ?? 0) < this.minTrustScore) {\n return { authorized: false, reason: `trust score below ${this.minTrustScore}` };\n }\n }\n const perm = await this.sdk.check(this.agentId, scope);\n return perm.allowed\n ? { authorized: true }\n : { authorized: false, reason: perm.reason ?? `missing scope ${scope}` };\n } catch (e: any) {\n // Fail closed by default: a check we could not complete is a deny.\n return this.onError === 'open'\n ? { authorized: true, reason: 'vorim unreachable, failed open' }\n : { authorized: false, reason: `vorim unreachable: ${e?.message ?? 'error'}` };\n }\n }\n\n /**\n * Emit a source-signed audit event for a store operation and return whether\n * it was recorded. Called after the mutation runs (or after a denial). The\n * event names the agent, the shop, and the human the agent acts for, so the\n * record is attributable and independently verifiable offline.\n */\n async record(action: ShopifyAction, result: 'success' | 'denied' | 'error', reason?: string): Promise<boolean> {\n const scope = this.scopeFor(action.operation);\n try {\n await this.sdk.emit({\n agent_id: this.agentId,\n event_type: 'api_request',\n action: `shopify:${action.operation}${action.resourceId ? ' ' + action.resourceId : ''}`,\n resource: action.resourceId || this.shopDomain,\n permission: scope,\n result,\n input_hash: action.inputHash,\n metadata: {\n integration: 'shopify-admin',\n shop_domain: this.shopDomain,\n acts_for_human: this.humanId,\n operation: action.operation,\n ...(action.amount != null ? { amount: action.amount } : {}),\n ...(action.currency ? { currency: action.currency } : {}),\n ...(reason ? { reason } : {}),\n },\n }, { sign: true }); // source-signed: the agent's key signs the record\n return true;\n } catch {\n return false;\n }\n }\n\n /**\n * The full flow for one store operation: authorize, run the Admin GraphQL\n * mutation if allowed, sign a receipt either way. If not authorized, `run` is\n * never called (the mutation does not happen). Rethrows an error from `run`\n * after recording it, with the receipt attached as `vorimReceipt`, so your\n * handler still sees Shopify failures.\n */\n async guard<T>(action: ShopifyAction, run: () => Promise<T>): Promise<{ receipt: ShopifyReceipt; value?: T }> {\n const auth = await this.authorize(action);\n if (!auth.authorized) {\n const recorded = await this.record(action, 'denied', auth.reason);\n return { receipt: this.receipt(action, false, 'denied', auth.reason, recorded) };\n }\n try {\n const value = await run();\n const recorded = await this.record(action, 'success');\n return { receipt: this.receipt(action, true, 'success', undefined, recorded), value };\n } catch (e: any) {\n const recorded = await this.record(action, 'error', e?.message);\n throw Object.assign(e ?? new Error('shopify operation failed'), {\n vorimReceipt: this.receipt(action, true, 'error', e?.message, recorded),\n });\n }\n }\n\n // --- Named helpers for the high-risk Admin mutations -----------------------\n // Each wraps guard() with the right operation label so the scope and receipt\n // are correct without the caller having to remember the mapping. You pass the\n // GraphQL call as `run`; this layer never talks to Shopify itself.\n\n /** Guard an `orderCreate`. Requires agent:write. */\n orderCreate<T>(meta: { orderId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'orderCreate', resourceId: meta.orderId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a `refundCreate`. Requires agent:transact AND stays within\n * `maxRefundAmount` if one was configured. `amount` is in minor units. */\n refundCreate<T>(meta: { orderId?: string; amount?: number; currency?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard(\n { operation: 'refundCreate', resourceId: meta.orderId, amount: meta.amount, currency: meta.currency, inputHash: meta.inputHash },\n run,\n );\n }\n\n /** Guard an `inventoryAdjustQuantities`. Requires agent:write. */\n inventoryAdjustQuantities<T>(meta: { resourceId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'inventoryAdjustQuantities', resourceId: meta.resourceId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a `fulfillmentCreate`. Requires agent:write. */\n fulfillmentCreate<T>(meta: { orderId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'fulfillmentCreate', resourceId: meta.orderId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a `returnProcess`. Requires agent:write. */\n returnProcess<T>(meta: { resourceId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard({ operation: 'returnProcess', resourceId: meta.resourceId, inputHash: meta.inputHash }, run);\n }\n\n /** Guard a `productCreate` or `productUpdate`. Requires agent:write. */\n productWrite<T>(meta: { operation?: 'productCreate' | 'productUpdate'; productId?: string; inputHash?: string }, run: () => Promise<T>) {\n return this.guard(\n { operation: meta.operation ?? 'productUpdate', resourceId: meta.productId, inputHash: meta.inputHash },\n run,\n );\n }\n\n private receipt(\n action: ShopifyAction,\n authorized: boolean,\n result: 'success' | 'denied' | 'error',\n reason: string | undefined,\n recorded: boolean,\n ): ShopifyReceipt {\n return {\n authorized,\n agentId: this.agentId,\n humanId: this.humanId,\n shopDomain: this.shopDomain,\n operation: action.operation,\n resourceId: action.resourceId,\n amount: action.amount,\n currency: action.currency,\n result,\n scope: this.scopeFor(action.operation),\n reason,\n recorded,\n };\n }\n}\n\n/**\n * Create a VorimShopify guard around a Vorim SDK instance.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimShopify } from '@vorim/sdk/integrations/shopify';\n *\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const shop = createVorimShopify(vorim, {\n * agentId: 'agid_abc123',\n * shopDomain: 'acme.myshopify.com',\n * humanId: 'user_42',\n * maxRefundAmount: 20000, // this agent can refund up to $200.00\n * });\n *\n * const { receipt, value } = await shop.refundCreate(\n * { orderId: 'gid://shopify/Order/123', amount: 4999, currency: 'USD' },\n * () => adminClient.request(REFUND_CREATE, { input }),\n * );\n * ```\n */\nexport function createVorimShopify(sdk: VorimSDK, config: ShopifyGuardConfig): VorimShopify {\n return new VorimShopify(sdk, config);\n}\n"],"mappings":";AAwEA,IAAM,kBAAmD;AAAA,EACvD,MAAM;AAAA,EACN,aAAa;AAAA,EACb,2BAA2B;AAAA,EAC3B,mBAAmB;AAA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AiB,MAAmD,KAAuB;AACzF,WAAO,KAAK,MAAM,EAAE,WAAW,iBAAiB,YAAY,KAAK,YAAY,WAAW,KAAK,UAAU,GAAG,GAAG;AAAA,EAC/G;AAAA;AAAA,EAGA,aAAgB,MAAiG,KAAuB;AACtI,WAAO,KAAK;AAAA,MACV,EAAE,WAAW,KAAK,aAAa,iBAAiB,YAAY,KAAK,WAAW,WAAW,KAAK,UAAU;AAAA,MACtG;AAAA,IACF;AAAA,EACF;AAAA,EAEQ,QACN,QACA,YACA,QACA,QACA,UACgB;AAChB,WAAO;AAAA,MACL;AAAA,MACA,SAAS,KAAK;AAAA,MACd,SAAS,KAAK;AAAA,MACd,YAAY,KAAK;AAAA,MACjB,WAAW,OAAO;AAAA,MAClB,YAAY,OAAO;AAAA,MACnB,QAAQ,OAAO;AAAA,MACf,UAAU,OAAO;AAAA,MACjB;AAAA,MACA,OAAO,KAAK,SAAS,OAAO,SAAS;AAAA,MACrC;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAwBO,SAAS,mBAAmB,KAAe,QAA0C;AAC1F,SAAO,IAAI,aAAa,KAAK,MAAM;AACrC;","names":[]}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/integrations/web-bot-auth.ts
|
|
31
|
+
var web_bot_auth_exports = {};
|
|
32
|
+
__export(web_bot_auth_exports, {
|
|
33
|
+
signRequestForBot: () => signRequestForBot
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(web_bot_auth_exports);
|
|
36
|
+
var bytesToBinary = (bytes) => {
|
|
37
|
+
let s = "";
|
|
38
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
39
|
+
return s;
|
|
40
|
+
};
|
|
41
|
+
var b64 = (buf) => {
|
|
42
|
+
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
|
43
|
+
const s = bytesToBinary(bytes);
|
|
44
|
+
return typeof btoa !== "undefined" ? btoa(s) : Buffer.from(bytes).toString("base64");
|
|
45
|
+
};
|
|
46
|
+
var b64url = (buf) => b64(buf).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
47
|
+
function b64AnyToBytes(s) {
|
|
48
|
+
const norm = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
49
|
+
const padded = norm + "=".repeat((4 - norm.length % 4) % 4);
|
|
50
|
+
const raw = typeof atob !== "undefined" ? atob(padded) : Buffer.from(padded, "base64").toString("binary");
|
|
51
|
+
const out = new Uint8Array(raw.length);
|
|
52
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
function pemBodyToBytes(pem) {
|
|
56
|
+
const body = pem.replace(/-----BEGIN [^-]+-----/, "").replace(/-----END [^-]+-----/, "").replace(/\s+/g, "");
|
|
57
|
+
return b64AnyToBytes(body);
|
|
58
|
+
}
|
|
59
|
+
function pemToPkcs8(pem) {
|
|
60
|
+
const bytes = pemBodyToBytes(pem);
|
|
61
|
+
const out = new ArrayBuffer(bytes.length);
|
|
62
|
+
new Uint8Array(out).set(bytes);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
async function sha256(bytes) {
|
|
66
|
+
if (typeof globalThis.crypto?.subtle !== "undefined") {
|
|
67
|
+
return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
|
|
68
|
+
}
|
|
69
|
+
const nodeCrypto = await import("crypto");
|
|
70
|
+
return new Uint8Array(nodeCrypto.createHash("sha256").update(bytes).digest());
|
|
71
|
+
}
|
|
72
|
+
async function rawEd25519PublicKey(req) {
|
|
73
|
+
const pk = req.publicKey;
|
|
74
|
+
if (pk instanceof Uint8Array) return last32(pk);
|
|
75
|
+
if (typeof pk === "string") {
|
|
76
|
+
if (pk.includes("-----BEGIN")) return spkiToRawEd25519(pemBodyToBytes(pk));
|
|
77
|
+
return last32(b64AnyToBytes(pk));
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const nodeCrypto = await import("crypto");
|
|
81
|
+
const keyObj = nodeCrypto.createPublicKey(nodeCrypto.createPrivateKey(req.privateKey));
|
|
82
|
+
const spki = keyObj.export({ format: "der", type: "spki" });
|
|
83
|
+
return spkiToRawEd25519(new Uint8Array(spki));
|
|
84
|
+
} catch {
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
var spkiToRawEd25519 = (spki) => last32(spki);
|
|
89
|
+
var last32 = (b) => b.length <= 32 ? b : b.slice(b.length - 32);
|
|
90
|
+
async function ed25519JwkThumbprint(rawPublicKey) {
|
|
91
|
+
const x = b64url(rawPublicKey);
|
|
92
|
+
const json = `{"crv":"Ed25519","kty":"OKP","x":"${x}"}`;
|
|
93
|
+
return b64url(await sha256(new TextEncoder().encode(json)));
|
|
94
|
+
}
|
|
95
|
+
async function ed25519Sign(payload, privateKeyPem) {
|
|
96
|
+
if (typeof globalThis.crypto?.subtle !== "undefined") {
|
|
97
|
+
const key = await globalThis.crypto.subtle.importKey("pkcs8", pemToPkcs8(privateKeyPem), { name: "Ed25519" }, false, ["sign"]);
|
|
98
|
+
return globalThis.crypto.subtle.sign("Ed25519", key, new TextEncoder().encode(payload));
|
|
99
|
+
}
|
|
100
|
+
const nodeCrypto = await import("crypto");
|
|
101
|
+
const sig = nodeCrypto.sign(null, Buffer.from(payload), privateKeyPem);
|
|
102
|
+
return sig.buffer.slice(sig.byteOffset, sig.byteOffset + sig.byteLength);
|
|
103
|
+
}
|
|
104
|
+
async function signRequestForBot(req) {
|
|
105
|
+
if (!req?.privateKey) throw new Error("[vorim] Web Bot Auth requires the agent privateKey (Ed25519 PKCS#8 PEM).");
|
|
106
|
+
if (!req?.signatureAgent) throw new Error("[vorim] Web Bot Auth requires a signatureAgent directory URL.");
|
|
107
|
+
const u = new URL(req.url);
|
|
108
|
+
const method = req.method.toUpperCase();
|
|
109
|
+
const created = req.createdAt ?? Math.floor(nowSeconds());
|
|
110
|
+
const expires = created + (req.expiresInSeconds ?? 300);
|
|
111
|
+
const label = req.label ?? "sig1";
|
|
112
|
+
const sigAgentValue = `"${req.signatureAgent}"`;
|
|
113
|
+
const rawPub = await rawEd25519PublicKey(req);
|
|
114
|
+
if (!rawPub) {
|
|
115
|
+
throw new Error("[vorim] Web Bot Auth could not derive the public key in this runtime. Pass `publicKey` (SPKI PEM or raw 32-byte base64) so keyid can be the JWK thumbprint the spec requires.");
|
|
116
|
+
}
|
|
117
|
+
const keyid = await ed25519JwkThumbprint(rawPub);
|
|
118
|
+
const covered = ["@authority", "@method", "@path", "signature-agent"];
|
|
119
|
+
const nonceParam = req.nonce ? `;nonce="${req.nonce}"` : "";
|
|
120
|
+
const paramsInner = `(${covered.map((c) => `"${c}"`).join(" ")});created=${created};expires=${expires};keyid="${keyid}";alg="ed25519";tag="web-bot-auth"${nonceParam}`;
|
|
121
|
+
const baseLines = [
|
|
122
|
+
`"@authority": ${u.host}`,
|
|
123
|
+
`"@method": ${method}`,
|
|
124
|
+
`"@path": ${u.pathname}`,
|
|
125
|
+
`"signature-agent": ${sigAgentValue}`,
|
|
126
|
+
`"@signature-params": ${paramsInner}`
|
|
127
|
+
];
|
|
128
|
+
const signatureBase = baseLines.join("\n");
|
|
129
|
+
const signature = await ed25519Sign(signatureBase, req.privateKey);
|
|
130
|
+
return {
|
|
131
|
+
"Signature-Input": `${label}=${paramsInner}`,
|
|
132
|
+
"Signature": `${label}=:${b64(signature)}:`,
|
|
133
|
+
"Signature-Agent": sigAgentValue
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function nowSeconds() {
|
|
137
|
+
return Date.now() / 1e3;
|
|
138
|
+
}
|
|
139
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
140
|
+
0 && (module.exports = {
|
|
141
|
+
signRequestForBot
|
|
142
|
+
});
|
|
143
|
+
//# sourceMappingURL=web-bot-auth.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/web-bot-auth.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — Web Bot Auth (RFC 9421 HTTP Message Signatures)\n//\n// The agentic web needs agents to prove who they are to publishers, instead of\n// hiding behind a spoofable User-Agent. Web Bot Auth does this with RFC 9421\n// HTTP Message Signatures: the agent signs a few request components with its\n// Ed25519 key, and the publisher verifies the signature against the agent's\n// published key directory. Cloudflare, and a growing set of sites, check for it.\n//\n// Vorim already gives every agent an Ed25519 identity, a live trust score, and a\n// signed audit trail. This turns that same identity into Web-Bot-Auth headers,\n// so a Vorim agent is a first-class, verifiable citizen of the agentic web: the\n// publisher can confirm which agent is knocking, and the same identity carries a\n// trust score and a signed record of what it did next.\n//\n// This is a standalone signer (no API call, no Node): it uses Web Crypto Ed25519,\n// so it runs in a Cloudflare Worker, the browser, Deno, Bun, or Node 20+. Keep\n// the agent private key in a secret; it never leaves the process.\n//\n// Usage:\n// import { signRequestForBot } from '@vorim/sdk/integrations/web-bot-auth';\n//\n// const headers = await signRequestForBot({\n// method: 'GET',\n// url: 'https://publisher.example/article',\n// privateKey: env.AGENT_PRIVATE_KEY, // Ed25519 PKCS#8 PEM\n// signatureAgent: 'https://vorim.ai/agents/agid_abc123', // your key directory\n// });\n// // -> { 'Signature-Input': '...', 'Signature': '...', 'Signature-Agent': '...' }\n//\n// const res = await fetch('https://publisher.example/article', { headers });\n// ============================================================================\n\nexport interface WebBotAuthRequest {\n /** HTTP method, e.g. 'GET'. */\n method: string;\n /** Absolute request URL. Its authority and path are covered by the signature. */\n url: string;\n /** The agent's Ed25519 private key, PKCS#8 PEM. Never leaves the process. */\n privateKey: string;\n /**\n * The URL where the agent's public key(s) are published (its directory). Sent\n * as the Signature-Agent header and covered by the signature, so a publisher\n * knows where to fetch the key to verify. With Vorim, this is typically your\n * agent's public verification URL.\n */\n signatureAgent: string;\n /**\n * The agent's Ed25519 PUBLIC key, needed to compute the `keyid` (the JWK\n * thumbprint the Web Bot Auth spec requires). Accepts a SPKI PEM, or the raw\n * 32-byte key as a base64/base64url string or Uint8Array. Optional: if omitted\n * it is derived from `privateKey` in runtimes that can (Node / workerd with\n * nodejs_compat). In a pure-Web-Crypto runtime that cannot derive it, pass it.\n */\n publicKey?: string | Uint8Array;\n /** Signature validity window in seconds. Default 300 (5 minutes). */\n expiresInSeconds?: number;\n /** Unix seconds the signature was created. Default: now (pass in for tests). */\n createdAt?: number;\n /**\n * Optional random nonce, base64url. The spec lets clients include one to make a\n * signed request single-use. Omitted by default (the spec marks it optional).\n */\n nonce?: string;\n /** RFC 9421 signature label. Default 'sig1'. */\n label?: string;\n}\n\nexport interface WebBotAuthHeaders {\n 'Signature-Input': string;\n 'Signature': string;\n 'Signature-Agent': string;\n}\n\nconst bytesToBinary = (bytes: Uint8Array): string => {\n let s = '';\n for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);\n return s;\n};\n\nconst b64 = (buf: ArrayBuffer | Uint8Array): string => {\n const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);\n const s = bytesToBinary(bytes);\n // Prefer btoa where available (browser / Workers); fall back to Buffer (Node).\n return typeof btoa !== 'undefined' ? btoa(s) : Buffer.from(bytes).toString('base64');\n};\n\n// base64url, unpadded — the encoding both keyid (JWK thumbprint) and JWK `x`\n// require.\nconst b64url = (buf: ArrayBuffer | Uint8Array): string =>\n b64(buf).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n\nfunction b64AnyToBytes(s: string): Uint8Array {\n const norm = s.replace(/-/g, '+').replace(/_/g, '/');\n const padded = norm + '='.repeat((4 - (norm.length % 4)) % 4);\n const raw = typeof atob !== 'undefined' ? atob(padded) : Buffer.from(padded, 'base64').toString('binary');\n const out = new Uint8Array(raw.length);\n for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);\n return out;\n}\n\nfunction pemBodyToBytes(pem: string): Uint8Array {\n const body = pem.replace(/-----BEGIN [^-]+-----/, '').replace(/-----END [^-]+-----/, '').replace(/\\s+/g, '');\n return b64AnyToBytes(body);\n}\n\nfunction pemToPkcs8(pem: string): ArrayBuffer {\n const bytes = pemBodyToBytes(pem);\n const out = new ArrayBuffer(bytes.length);\n new Uint8Array(out).set(bytes);\n return out;\n}\n\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n if (typeof globalThis.crypto?.subtle !== 'undefined') {\n return new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes));\n }\n const nodeCrypto = await import('node:crypto');\n return new Uint8Array(nodeCrypto.createHash('sha256').update(bytes).digest());\n}\n\n// Pull the raw 32-byte Ed25519 public key out of whatever the caller gave us,\n// or derive it from the private key where the runtime can (Node / nodejs_compat).\n// Returns null only when no public key is available and it cannot be derived —\n// the caller then throws a clear error rather than emitting a wrong keyid.\nasync function rawEd25519PublicKey(req: WebBotAuthRequest): Promise<Uint8Array | null> {\n const pk = req.publicKey;\n if (pk instanceof Uint8Array) return last32(pk);\n if (typeof pk === 'string') {\n if (pk.includes('-----BEGIN')) return spkiToRawEd25519(pemBodyToBytes(pk));\n return last32(b64AnyToBytes(pk)); // raw 32-byte key, base64 or base64url\n }\n // Derive from the private key. Web Crypto cannot export a public key from a\n // private-only import, so this path needs node:crypto (present in Node and in\n // workerd with nodejs_compat). In a pure-Web-Crypto runtime, pass publicKey.\n try {\n const nodeCrypto = await import('node:crypto');\n const keyObj = nodeCrypto.createPublicKey(nodeCrypto.createPrivateKey(req.privateKey));\n const spki = keyObj.export({ format: 'der', type: 'spki' }) as Uint8Array;\n return spkiToRawEd25519(new Uint8Array(spki));\n } catch {\n return null;\n }\n}\n\n// Ed25519 SPKI is a fixed 44-byte structure ending in the 32-byte key.\nconst spkiToRawEd25519 = (spki: Uint8Array): Uint8Array => last32(spki);\nconst last32 = (b: Uint8Array): Uint8Array => (b.length <= 32 ? b : b.slice(b.length - 32));\n\n/**\n * The Web Bot Auth keyid: base64url SHA-256 JWK thumbprint of the Ed25519 key,\n * per RFC 7638 with the RFC 8037 OKP members in lexical order (crv, kty, x).\n * This is the value a compliant verifier (Cloudflare and others) matches against\n * the key it fetched from the Signature-Agent directory.\n */\nasync function ed25519JwkThumbprint(rawPublicKey: Uint8Array): Promise<string> {\n const x = b64url(rawPublicKey);\n const json = `{\"crv\":\"Ed25519\",\"kty\":\"OKP\",\"x\":\"${x}\"}`;\n return b64url(await sha256(new TextEncoder().encode(json)));\n}\n\nasync function ed25519Sign(payload: string, privateKeyPem: string): Promise<ArrayBuffer> {\n if (typeof globalThis.crypto?.subtle !== 'undefined') {\n const key = await globalThis.crypto.subtle.importKey('pkcs8', pemToPkcs8(privateKeyPem), { name: 'Ed25519' }, false, ['sign']);\n return globalThis.crypto.subtle.sign('Ed25519', key, new TextEncoder().encode(payload));\n }\n const nodeCrypto = await import('node:crypto');\n const sig = nodeCrypto.sign(null, Buffer.from(payload), privateKeyPem);\n return sig.buffer.slice(sig.byteOffset, sig.byteOffset + sig.byteLength);\n}\n\n/**\n * Produce RFC 9421 Web Bot Auth headers for an outbound agent request.\n *\n * The signature covers @authority, @method, @path, and signature-agent, plus the\n * signature params (created, expires, keyid, alg=ed25519, tag=\"web-bot-auth\",\n * and nonce when supplied), per the Web Bot Auth profile. `keyid` is the base64url\n * SHA-256 JWK thumbprint of the Ed25519 key, as the spec requires. Returns the\n * three headers to attach to fetch().\n */\nexport async function signRequestForBot(req: WebBotAuthRequest): Promise<WebBotAuthHeaders> {\n if (!req?.privateKey) throw new Error('[vorim] Web Bot Auth requires the agent privateKey (Ed25519 PKCS#8 PEM).');\n if (!req?.signatureAgent) throw new Error('[vorim] Web Bot Auth requires a signatureAgent directory URL.');\n\n const u = new URL(req.url);\n const method = req.method.toUpperCase();\n const created = req.createdAt ?? Math.floor(nowSeconds());\n const expires = created + (req.expiresInSeconds ?? 300);\n const label = req.label ?? 'sig1';\n const sigAgentValue = `\"${req.signatureAgent}\"`;\n\n // keyid MUST be the base64url SHA-256 JWK thumbprint of the signing key\n // (RFC 7638 + RFC 8037 A.3), not the directory URL — that is what a compliant\n // verifier matches against the key it fetched from Signature-Agent.\n const rawPub = await rawEd25519PublicKey(req);\n if (!rawPub) {\n throw new Error('[vorim] Web Bot Auth could not derive the public key in this runtime. Pass `publicKey` (SPKI PEM or raw 32-byte base64) so keyid can be the JWK thumbprint the spec requires.');\n }\n const keyid = await ed25519JwkThumbprint(rawPub);\n\n // Covered components, in the order they appear in the signature base.\n const covered = ['@authority', '@method', '@path', 'signature-agent'];\n const nonceParam = req.nonce ? `;nonce=\"${req.nonce}\"` : '';\n const paramsInner = `(${covered.map((c) => `\"${c}\"`).join(' ')});created=${created};expires=${expires};keyid=\"${keyid}\";alg=\"ed25519\";tag=\"web-bot-auth\"${nonceParam}`;\n\n // RFC 9421 signature base: one line per covered component, then the\n // @signature-params line whose value is the inner params string above.\n const baseLines: string[] = [\n `\"@authority\": ${u.host}`,\n `\"@method\": ${method}`,\n `\"@path\": ${u.pathname}`,\n `\"signature-agent\": ${sigAgentValue}`,\n `\"@signature-params\": ${paramsInner}`,\n ];\n const signatureBase = baseLines.join('\\n');\n\n const signature = await ed25519Sign(signatureBase, req.privateKey);\n\n return {\n 'Signature-Input': `${label}=${paramsInner}`,\n 'Signature': `${label}=:${b64(signature)}:`,\n 'Signature-Agent': sigAgentValue,\n };\n}\n\n// nowSeconds is isolated so callers/tests can reason about time; production uses\n// Date.now(). (The SDK targets runtimes where Date is available.)\nfunction nowSeconds(): number {\n return Date.now() / 1000;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA0EA,IAAM,gBAAgB,CAAC,UAA8B;AACnD,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,IAAK,MAAK,OAAO,aAAa,MAAM,CAAC,CAAC;AACxE,SAAO;AACT;AAEA,IAAM,MAAM,CAAC,QAA0C;AACrD,QAAM,QAAQ,eAAe,aAAa,MAAM,IAAI,WAAW,GAAG;AAClE,QAAM,IAAI,cAAc,KAAK;AAE7B,SAAO,OAAO,SAAS,cAAc,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,EAAE,SAAS,QAAQ;AACrF;AAIA,IAAM,SAAS,CAAC,QACd,IAAI,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAA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Its authority and path are covered by the signature. */
|
|
5
|
+
url: string;
|
|
6
|
+
/** The agent's Ed25519 private key, PKCS#8 PEM. Never leaves the process. */
|
|
7
|
+
privateKey: string;
|
|
8
|
+
/**
|
|
9
|
+
* The URL where the agent's public key(s) are published (its directory). Sent
|
|
10
|
+
* as the Signature-Agent header and covered by the signature, so a publisher
|
|
11
|
+
* knows where to fetch the key to verify. With Vorim, this is typically your
|
|
12
|
+
* agent's public verification URL.
|
|
13
|
+
*/
|
|
14
|
+
signatureAgent: string;
|
|
15
|
+
/**
|
|
16
|
+
* The agent's Ed25519 PUBLIC key, needed to compute the `keyid` (the JWK
|
|
17
|
+
* thumbprint the Web Bot Auth spec requires). Accepts a SPKI PEM, or the raw
|
|
18
|
+
* 32-byte key as a base64/base64url string or Uint8Array. Optional: if omitted
|
|
19
|
+
* it is derived from `privateKey` in runtimes that can (Node / workerd with
|
|
20
|
+
* nodejs_compat). In a pure-Web-Crypto runtime that cannot derive it, pass it.
|
|
21
|
+
*/
|
|
22
|
+
publicKey?: string | Uint8Array;
|
|
23
|
+
/** Signature validity window in seconds. Default 300 (5 minutes). */
|
|
24
|
+
expiresInSeconds?: number;
|
|
25
|
+
/** Unix seconds the signature was created. Default: now (pass in for tests). */
|
|
26
|
+
createdAt?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Optional random nonce, base64url. The spec lets clients include one to make a
|
|
29
|
+
* signed request single-use. Omitted by default (the spec marks it optional).
|
|
30
|
+
*/
|
|
31
|
+
nonce?: string;
|
|
32
|
+
/** RFC 9421 signature label. Default 'sig1'. */
|
|
33
|
+
label?: string;
|
|
34
|
+
}
|
|
35
|
+
interface WebBotAuthHeaders {
|
|
36
|
+
'Signature-Input': string;
|
|
37
|
+
'Signature': string;
|
|
38
|
+
'Signature-Agent': string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Produce RFC 9421 Web Bot Auth headers for an outbound agent request.
|
|
42
|
+
*
|
|
43
|
+
* The signature covers @authority, @method, @path, and signature-agent, plus the
|
|
44
|
+
* signature params (created, expires, keyid, alg=ed25519, tag="web-bot-auth",
|
|
45
|
+
* and nonce when supplied), per the Web Bot Auth profile. `keyid` is the base64url
|
|
46
|
+
* SHA-256 JWK thumbprint of the Ed25519 key, as the spec requires. Returns the
|
|
47
|
+
* three headers to attach to fetch().
|
|
48
|
+
*/
|
|
49
|
+
declare function signRequestForBot(req: WebBotAuthRequest): Promise<WebBotAuthHeaders>;
|
|
50
|
+
|
|
51
|
+
export { type WebBotAuthHeaders, type WebBotAuthRequest, signRequestForBot };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
interface WebBotAuthRequest {
|
|
2
|
+
/** HTTP method, e.g. 'GET'. */
|
|
3
|
+
method: string;
|
|
4
|
+
/** Absolute request URL. Its authority and path are covered by the signature. */
|
|
5
|
+
url: string;
|
|
6
|
+
/** The agent's Ed25519 private key, PKCS#8 PEM. Never leaves the process. */
|
|
7
|
+
privateKey: string;
|
|
8
|
+
/**
|
|
9
|
+
* The URL where the agent's public key(s) are published (its directory). Sent
|
|
10
|
+
* as the Signature-Agent header and covered by the signature, so a publisher
|
|
11
|
+
* knows where to fetch the key to verify. With Vorim, this is typically your
|
|
12
|
+
* agent's public verification URL.
|
|
13
|
+
*/
|
|
14
|
+
signatureAgent: string;
|
|
15
|
+
/**
|
|
16
|
+
* The agent's Ed25519 PUBLIC key, needed to compute the `keyid` (the JWK
|
|
17
|
+
* thumbprint the Web Bot Auth spec requires). Accepts a SPKI PEM, or the raw
|
|
18
|
+
* 32-byte key as a base64/base64url string or Uint8Array. Optional: if omitted
|
|
19
|
+
* it is derived from `privateKey` in runtimes that can (Node / workerd with
|
|
20
|
+
* nodejs_compat). In a pure-Web-Crypto runtime that cannot derive it, pass it.
|
|
21
|
+
*/
|
|
22
|
+
publicKey?: string | Uint8Array;
|
|
23
|
+
/** Signature validity window in seconds. Default 300 (5 minutes). */
|
|
24
|
+
expiresInSeconds?: number;
|
|
25
|
+
/** Unix seconds the signature was created. Default: now (pass in for tests). */
|
|
26
|
+
createdAt?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Optional random nonce, base64url. The spec lets clients include one to make a
|
|
29
|
+
* signed request single-use. Omitted by default (the spec marks it optional).
|
|
30
|
+
*/
|
|
31
|
+
nonce?: string;
|
|
32
|
+
/** RFC 9421 signature label. Default 'sig1'. */
|
|
33
|
+
label?: string;
|
|
34
|
+
}
|
|
35
|
+
interface WebBotAuthHeaders {
|
|
36
|
+
'Signature-Input': string;
|
|
37
|
+
'Signature': string;
|
|
38
|
+
'Signature-Agent': string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Produce RFC 9421 Web Bot Auth headers for an outbound agent request.
|
|
42
|
+
*
|
|
43
|
+
* The signature covers @authority, @method, @path, and signature-agent, plus the
|
|
44
|
+
* signature params (created, expires, keyid, alg=ed25519, tag="web-bot-auth",
|
|
45
|
+
* and nonce when supplied), per the Web Bot Auth profile. `keyid` is the base64url
|
|
46
|
+
* SHA-256 JWK thumbprint of the Ed25519 key, as the spec requires. Returns the
|
|
47
|
+
* three headers to attach to fetch().
|
|
48
|
+
*/
|
|
49
|
+
declare function signRequestForBot(req: WebBotAuthRequest): Promise<WebBotAuthHeaders>;
|
|
50
|
+
|
|
51
|
+
export { type WebBotAuthHeaders, type WebBotAuthRequest, signRequestForBot };
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// src/integrations/web-bot-auth.ts
|
|
2
|
+
var bytesToBinary = (bytes) => {
|
|
3
|
+
let s = "";
|
|
4
|
+
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
|
|
5
|
+
return s;
|
|
6
|
+
};
|
|
7
|
+
var b64 = (buf) => {
|
|
8
|
+
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
|
9
|
+
const s = bytesToBinary(bytes);
|
|
10
|
+
return typeof btoa !== "undefined" ? btoa(s) : Buffer.from(bytes).toString("base64");
|
|
11
|
+
};
|
|
12
|
+
var b64url = (buf) => b64(buf).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
13
|
+
function b64AnyToBytes(s) {
|
|
14
|
+
const norm = s.replace(/-/g, "+").replace(/_/g, "/");
|
|
15
|
+
const padded = norm + "=".repeat((4 - norm.length % 4) % 4);
|
|
16
|
+
const raw = typeof atob !== "undefined" ? atob(padded) : Buffer.from(padded, "base64").toString("binary");
|
|
17
|
+
const out = new Uint8Array(raw.length);
|
|
18
|
+
for (let i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
function pemBodyToBytes(pem) {
|
|
22
|
+
const body = pem.replace(/-----BEGIN [^-]+-----/, "").replace(/-----END [^-]+-----/, "").replace(/\s+/g, "");
|
|
23
|
+
return b64AnyToBytes(body);
|
|
24
|
+
}
|
|
25
|
+
function pemToPkcs8(pem) {
|
|
26
|
+
const bytes = pemBodyToBytes(pem);
|
|
27
|
+
const out = new ArrayBuffer(bytes.length);
|
|
28
|
+
new Uint8Array(out).set(bytes);
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
async function sha256(bytes) {
|
|
32
|
+
if (typeof globalThis.crypto?.subtle !== "undefined") {
|
|
33
|
+
return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes));
|
|
34
|
+
}
|
|
35
|
+
const nodeCrypto = await import("crypto");
|
|
36
|
+
return new Uint8Array(nodeCrypto.createHash("sha256").update(bytes).digest());
|
|
37
|
+
}
|
|
38
|
+
async function rawEd25519PublicKey(req) {
|
|
39
|
+
const pk = req.publicKey;
|
|
40
|
+
if (pk instanceof Uint8Array) return last32(pk);
|
|
41
|
+
if (typeof pk === "string") {
|
|
42
|
+
if (pk.includes("-----BEGIN")) return spkiToRawEd25519(pemBodyToBytes(pk));
|
|
43
|
+
return last32(b64AnyToBytes(pk));
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
const nodeCrypto = await import("crypto");
|
|
47
|
+
const keyObj = nodeCrypto.createPublicKey(nodeCrypto.createPrivateKey(req.privateKey));
|
|
48
|
+
const spki = keyObj.export({ format: "der", type: "spki" });
|
|
49
|
+
return spkiToRawEd25519(new Uint8Array(spki));
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
var spkiToRawEd25519 = (spki) => last32(spki);
|
|
55
|
+
var last32 = (b) => b.length <= 32 ? b : b.slice(b.length - 32);
|
|
56
|
+
async function ed25519JwkThumbprint(rawPublicKey) {
|
|
57
|
+
const x = b64url(rawPublicKey);
|
|
58
|
+
const json = `{"crv":"Ed25519","kty":"OKP","x":"${x}"}`;
|
|
59
|
+
return b64url(await sha256(new TextEncoder().encode(json)));
|
|
60
|
+
}
|
|
61
|
+
async function ed25519Sign(payload, privateKeyPem) {
|
|
62
|
+
if (typeof globalThis.crypto?.subtle !== "undefined") {
|
|
63
|
+
const key = await globalThis.crypto.subtle.importKey("pkcs8", pemToPkcs8(privateKeyPem), { name: "Ed25519" }, false, ["sign"]);
|
|
64
|
+
return globalThis.crypto.subtle.sign("Ed25519", key, new TextEncoder().encode(payload));
|
|
65
|
+
}
|
|
66
|
+
const nodeCrypto = await import("crypto");
|
|
67
|
+
const sig = nodeCrypto.sign(null, Buffer.from(payload), privateKeyPem);
|
|
68
|
+
return sig.buffer.slice(sig.byteOffset, sig.byteOffset + sig.byteLength);
|
|
69
|
+
}
|
|
70
|
+
async function signRequestForBot(req) {
|
|
71
|
+
if (!req?.privateKey) throw new Error("[vorim] Web Bot Auth requires the agent privateKey (Ed25519 PKCS#8 PEM).");
|
|
72
|
+
if (!req?.signatureAgent) throw new Error("[vorim] Web Bot Auth requires a signatureAgent directory URL.");
|
|
73
|
+
const u = new URL(req.url);
|
|
74
|
+
const method = req.method.toUpperCase();
|
|
75
|
+
const created = req.createdAt ?? Math.floor(nowSeconds());
|
|
76
|
+
const expires = created + (req.expiresInSeconds ?? 300);
|
|
77
|
+
const label = req.label ?? "sig1";
|
|
78
|
+
const sigAgentValue = `"${req.signatureAgent}"`;
|
|
79
|
+
const rawPub = await rawEd25519PublicKey(req);
|
|
80
|
+
if (!rawPub) {
|
|
81
|
+
throw new Error("[vorim] Web Bot Auth could not derive the public key in this runtime. Pass `publicKey` (SPKI PEM or raw 32-byte base64) so keyid can be the JWK thumbprint the spec requires.");
|
|
82
|
+
}
|
|
83
|
+
const keyid = await ed25519JwkThumbprint(rawPub);
|
|
84
|
+
const covered = ["@authority", "@method", "@path", "signature-agent"];
|
|
85
|
+
const nonceParam = req.nonce ? `;nonce="${req.nonce}"` : "";
|
|
86
|
+
const paramsInner = `(${covered.map((c) => `"${c}"`).join(" ")});created=${created};expires=${expires};keyid="${keyid}";alg="ed25519";tag="web-bot-auth"${nonceParam}`;
|
|
87
|
+
const baseLines = [
|
|
88
|
+
`"@authority": ${u.host}`,
|
|
89
|
+
`"@method": ${method}`,
|
|
90
|
+
`"@path": ${u.pathname}`,
|
|
91
|
+
`"signature-agent": ${sigAgentValue}`,
|
|
92
|
+
`"@signature-params": ${paramsInner}`
|
|
93
|
+
];
|
|
94
|
+
const signatureBase = baseLines.join("\n");
|
|
95
|
+
const signature = await ed25519Sign(signatureBase, req.privateKey);
|
|
96
|
+
return {
|
|
97
|
+
"Signature-Input": `${label}=${paramsInner}`,
|
|
98
|
+
"Signature": `${label}=:${b64(signature)}:`,
|
|
99
|
+
"Signature-Agent": sigAgentValue
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function nowSeconds() {
|
|
103
|
+
return Date.now() / 1e3;
|
|
104
|
+
}
|
|
105
|
+
export {
|
|
106
|
+
signRequestForBot
|
|
107
|
+
};
|
|
108
|
+
//# sourceMappingURL=web-bot-auth.js.map
|