@vorim/sdk 3.10.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/CHANGELOG.md +13 -0
- 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/truanon.cjs +188 -0
- package/dist/integrations/truanon.cjs.map +1 -0
- package/dist/integrations/truanon.d.cts +115 -0
- package/dist/integrations/truanon.d.ts +115 -0
- package/dist/integrations/truanon.js +161 -0
- package/dist/integrations/truanon.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 +41 -1
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { VorimSDK } from '../index.js';
|
|
2
|
+
import '../types-zzK9YOoa.js';
|
|
3
|
+
|
|
4
|
+
/** TruAnon rank tiers, weakest to strongest. `Unknown` never meets a minimum. */
|
|
5
|
+
type TruAnonRank = 'Unknown' | 'Dangerous' | 'Cautioned' | 'Credible' | 'Reliable' | 'Genuine';
|
|
6
|
+
/** Does `userRank` meet or exceed `minimumRank`? Unknown always fails. */
|
|
7
|
+
declare function meetsMinimumRank(userRank: string, minimumRank: TruAnonRank): boolean;
|
|
8
|
+
interface TruAnonAnchor {
|
|
9
|
+
name: string;
|
|
10
|
+
display: string;
|
|
11
|
+
icon: string;
|
|
12
|
+
type: string;
|
|
13
|
+
kind: string;
|
|
14
|
+
}
|
|
15
|
+
/** The get_profile response shape (the fields TruAnon returns for a human). */
|
|
16
|
+
interface TruAnonProfile {
|
|
17
|
+
rank: string;
|
|
18
|
+
score: string;
|
|
19
|
+
name?: string;
|
|
20
|
+
title?: string;
|
|
21
|
+
photo?: string;
|
|
22
|
+
ageBadge?: string;
|
|
23
|
+
anchors?: TruAnonAnchor[];
|
|
24
|
+
isAnchored: boolean;
|
|
25
|
+
}
|
|
26
|
+
interface TruAnonConfig {
|
|
27
|
+
/** Vorim API key (already on the sdk instance; not used directly here). */
|
|
28
|
+
apiKey?: string;
|
|
29
|
+
baseUrl?: string;
|
|
30
|
+
/** TruAnon private API key — SERVER-SIDE ONLY. */
|
|
31
|
+
privateKey: string;
|
|
32
|
+
/** Your registered TruAnon service name. */
|
|
33
|
+
service: string;
|
|
34
|
+
/** Minimum human rank required to authorize an agent. Default 'Credible'. */
|
|
35
|
+
minRank?: TruAnonRank;
|
|
36
|
+
/** Minimum agent trust score. Default 50. */
|
|
37
|
+
minTrustScore?: number;
|
|
38
|
+
/** Required agent scope. Default 'agent:transact'. */
|
|
39
|
+
requiredScope?: string;
|
|
40
|
+
/** TruAnon API base. Default 'https://truanon.com/api/v2'. */
|
|
41
|
+
truanonBaseUrl?: string;
|
|
42
|
+
/** Per-request timeout in ms. Default 30000 (TruAnon's guidance). */
|
|
43
|
+
timeoutMs?: number;
|
|
44
|
+
/** Injectable fetch (for testing). Defaults to global fetch. */
|
|
45
|
+
fetchImpl?: typeof fetch;
|
|
46
|
+
}
|
|
47
|
+
interface HumanBindingAuthorization {
|
|
48
|
+
authorized: boolean;
|
|
49
|
+
agentId: string;
|
|
50
|
+
humanUsername: string;
|
|
51
|
+
/** The human's TruAnon rank + whether it met the minimum. */
|
|
52
|
+
humanRank: string;
|
|
53
|
+
humanScore: string;
|
|
54
|
+
humanAnchored: boolean;
|
|
55
|
+
humanRankMet: boolean;
|
|
56
|
+
/** The agent's Vorim standing. */
|
|
57
|
+
trustScore: number;
|
|
58
|
+
status: string;
|
|
59
|
+
scopeVerified: boolean;
|
|
60
|
+
reason?: string;
|
|
61
|
+
}
|
|
62
|
+
declare class VorimTruAnon {
|
|
63
|
+
private sdk;
|
|
64
|
+
private privateKey;
|
|
65
|
+
private service;
|
|
66
|
+
private minRank;
|
|
67
|
+
private minTrustScore;
|
|
68
|
+
private requiredScope;
|
|
69
|
+
private truanonBaseUrl;
|
|
70
|
+
private timeoutMs;
|
|
71
|
+
private doFetch;
|
|
72
|
+
constructor(sdk: VorimSDK, config: TruAnonConfig);
|
|
73
|
+
/**
|
|
74
|
+
* Fetch a human's TruAnon profile (the anchor). Server-side call with your
|
|
75
|
+
* private key. Returns the rank/score/anchors; `isAnchored` is false if the
|
|
76
|
+
* lookup fails or the human has no anchor.
|
|
77
|
+
*/
|
|
78
|
+
verifyHuman(username: string): Promise<TruAnonProfile>;
|
|
79
|
+
/**
|
|
80
|
+
* The binding gate: authorize an agent to act on a human's behalf only if
|
|
81
|
+
* BOTH sides check out — the human is anchored at/above minRank (TruAnon) AND
|
|
82
|
+
* the agent holds the scope, is active, and clears trust (Vorim). Signs an
|
|
83
|
+
* audit event capturing both identities regardless of outcome.
|
|
84
|
+
*/
|
|
85
|
+
authorizeAgentForHuman(input: {
|
|
86
|
+
agentId: string;
|
|
87
|
+
humanUsername: string;
|
|
88
|
+
minRank?: TruAnonRank;
|
|
89
|
+
minTrustScore?: number;
|
|
90
|
+
}): Promise<HumanBindingAuthorization>;
|
|
91
|
+
/** Log that an anchored-human + agent action completed (the end-to-end record). */
|
|
92
|
+
logBoundAction(agentId: string, humanUsername: string, action: string, metadata?: Record<string, any>): Promise<void>;
|
|
93
|
+
private emptyProfile;
|
|
94
|
+
private logEvent;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Create a VorimTruAnon instance. Bind a TruAnon-anchored human to a
|
|
98
|
+
* Vorim-identified agent, with a signed record of both.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```typescript
|
|
102
|
+
* import createVorim from '@vorim/sdk';
|
|
103
|
+
* import { createVorimTruAnon } from '@vorim/sdk/integrations/truanon';
|
|
104
|
+
* const vorim = createVorim({ apiKey: 'agid_sk_...' });
|
|
105
|
+
* const truanon = createVorimTruAnon(vorim, {
|
|
106
|
+
* privateKey: process.env.VORIM_TRUANON_KEY!,
|
|
107
|
+
* service: process.env.VORIM_TRUANON_SERVICE!,
|
|
108
|
+
* minRank: 'Credible',
|
|
109
|
+
* });
|
|
110
|
+
* const auth = await truanon.authorizeAgentForHuman({ agentId: 'agid_abc', humanUsername: 'jtayler' });
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
declare function createVorimTruAnon(sdk: VorimSDK, config: TruAnonConfig): VorimTruAnon;
|
|
114
|
+
|
|
115
|
+
export { type HumanBindingAuthorization, type TruAnonAnchor, type TruAnonConfig, type TruAnonProfile, type TruAnonRank, VorimTruAnon, createVorimTruAnon, meetsMinimumRank };
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// src/integrations/truanon.ts
|
|
2
|
+
var RANK_ORDER = ["Dangerous", "Cautioned", "Credible", "Reliable", "Genuine"];
|
|
3
|
+
function meetsMinimumRank(userRank, minimumRank) {
|
|
4
|
+
if (userRank === "Unknown") return false;
|
|
5
|
+
const u = RANK_ORDER.indexOf(userRank);
|
|
6
|
+
const m = RANK_ORDER.indexOf(minimumRank);
|
|
7
|
+
return u >= 0 && m >= 0 && u >= m;
|
|
8
|
+
}
|
|
9
|
+
var VorimTruAnon = class {
|
|
10
|
+
sdk;
|
|
11
|
+
privateKey;
|
|
12
|
+
service;
|
|
13
|
+
minRank;
|
|
14
|
+
minTrustScore;
|
|
15
|
+
requiredScope;
|
|
16
|
+
truanonBaseUrl;
|
|
17
|
+
timeoutMs;
|
|
18
|
+
doFetch;
|
|
19
|
+
constructor(sdk, config) {
|
|
20
|
+
if (!config?.privateKey) throw new Error("[vorim] TruAnon integration requires a privateKey (server-side only).");
|
|
21
|
+
if (!config?.service) throw new Error("[vorim] TruAnon integration requires a service name.");
|
|
22
|
+
this.sdk = sdk;
|
|
23
|
+
this.privateKey = config.privateKey;
|
|
24
|
+
this.service = config.service;
|
|
25
|
+
this.minRank = config.minRank ?? "Credible";
|
|
26
|
+
this.minTrustScore = config.minTrustScore ?? 50;
|
|
27
|
+
this.requiredScope = config.requiredScope ?? "agent:transact";
|
|
28
|
+
this.truanonBaseUrl = (config.truanonBaseUrl ?? "https://truanon.com/api/v2").replace(/\/$/, "");
|
|
29
|
+
this.timeoutMs = config.timeoutMs ?? 3e4;
|
|
30
|
+
this.doFetch = config.fetchImpl ?? fetch;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Fetch a human's TruAnon profile (the anchor). Server-side call with your
|
|
34
|
+
* private key. Returns the rank/score/anchors; `isAnchored` is false if the
|
|
35
|
+
* lookup fails or the human has no anchor.
|
|
36
|
+
*/
|
|
37
|
+
async verifyHuman(username) {
|
|
38
|
+
const url = `${this.truanonBaseUrl}/get_profile?id=${encodeURIComponent(username)}&service=${encodeURIComponent(this.service)}`;
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
41
|
+
try {
|
|
42
|
+
const res = await this.doFetch(url, {
|
|
43
|
+
method: "GET",
|
|
44
|
+
headers: { Authorization: this.privateKey, Accept: "application/json" },
|
|
45
|
+
redirect: "error",
|
|
46
|
+
signal: controller.signal
|
|
47
|
+
});
|
|
48
|
+
if (!res.ok) return this.emptyProfile();
|
|
49
|
+
const data = await res.json();
|
|
50
|
+
const rank = typeof data?.rank === "string" ? data.rank : "Unknown";
|
|
51
|
+
return {
|
|
52
|
+
rank,
|
|
53
|
+
score: typeof data?.score === "string" ? data.score : String(data?.score ?? "0"),
|
|
54
|
+
name: data?.name,
|
|
55
|
+
title: data?.title,
|
|
56
|
+
photo: data?.photo,
|
|
57
|
+
ageBadge: data?.ageBadge,
|
|
58
|
+
anchors: Array.isArray(data?.anchors) ? data.anchors : [],
|
|
59
|
+
isAnchored: rank !== "Unknown" && !!rank
|
|
60
|
+
};
|
|
61
|
+
} catch {
|
|
62
|
+
return this.emptyProfile();
|
|
63
|
+
} finally {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The binding gate: authorize an agent to act on a human's behalf only if
|
|
69
|
+
* BOTH sides check out — the human is anchored at/above minRank (TruAnon) AND
|
|
70
|
+
* the agent holds the scope, is active, and clears trust (Vorim). Signs an
|
|
71
|
+
* audit event capturing both identities regardless of outcome.
|
|
72
|
+
*/
|
|
73
|
+
async authorizeAgentForHuman(input) {
|
|
74
|
+
const minRank = input.minRank ?? this.minRank;
|
|
75
|
+
const threshold = input.minTrustScore ?? this.minTrustScore;
|
|
76
|
+
const profile = await this.verifyHuman(input.humanUsername);
|
|
77
|
+
const rankMet = meetsMinimumRank(profile.rank, minRank);
|
|
78
|
+
const base = {
|
|
79
|
+
agentId: input.agentId,
|
|
80
|
+
humanUsername: input.humanUsername,
|
|
81
|
+
humanRank: profile.rank,
|
|
82
|
+
humanScore: profile.score,
|
|
83
|
+
humanAnchored: profile.isAnchored,
|
|
84
|
+
humanRankMet: rankMet
|
|
85
|
+
};
|
|
86
|
+
if (!profile.isAnchored) {
|
|
87
|
+
await this.logEvent(input.agentId, "truanon.bind.authorize", "denied", base, { reason: "Human is not anchored" });
|
|
88
|
+
return { ...base, authorized: false, trustScore: 0, status: "unknown", scopeVerified: false, reason: `Human ${input.humanUsername} is not anchored on TruAnon` };
|
|
89
|
+
}
|
|
90
|
+
if (!rankMet) {
|
|
91
|
+
await this.logEvent(input.agentId, "truanon.bind.authorize", "denied", base, { reason: `Rank ${profile.rank} < ${minRank}` });
|
|
92
|
+
return { ...base, authorized: false, trustScore: 0, status: "unknown", scopeVerified: false, reason: `Human rank ${profile.rank} is below the required ${minRank}` };
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
const perm = await this.sdk.check(input.agentId, this.requiredScope);
|
|
96
|
+
if (!perm.allowed) {
|
|
97
|
+
await this.logEvent(input.agentId, "truanon.bind.authorize", "denied", base, { reason: `Missing ${this.requiredScope}` });
|
|
98
|
+
return { ...base, authorized: false, trustScore: 0, status: "unknown", scopeVerified: false, reason: `Agent does not have ${this.requiredScope} permission` };
|
|
99
|
+
}
|
|
100
|
+
} catch (e) {
|
|
101
|
+
await this.logEvent(input.agentId, "truanon.bind.authorize", "denied", base, { reason: `Permission check failed: ${e.message}` });
|
|
102
|
+
return { ...base, authorized: false, trustScore: 0, status: "unknown", scopeVerified: false, reason: `Permission check failed: ${e.message}` };
|
|
103
|
+
}
|
|
104
|
+
let score = 0;
|
|
105
|
+
let status = "unknown";
|
|
106
|
+
try {
|
|
107
|
+
const trust = await this.sdk.verify(input.agentId);
|
|
108
|
+
score = trust.trust_score ?? 0;
|
|
109
|
+
status = trust.status ?? "unknown";
|
|
110
|
+
} catch {
|
|
111
|
+
}
|
|
112
|
+
if (status !== "active") {
|
|
113
|
+
await this.logEvent(input.agentId, "truanon.bind.authorize", "denied", base, { reason: `Agent status: ${status}` });
|
|
114
|
+
return { ...base, authorized: false, trustScore: score, status, scopeVerified: true, reason: `Agent is ${status}, not active` };
|
|
115
|
+
}
|
|
116
|
+
if (score < threshold) {
|
|
117
|
+
await this.logEvent(input.agentId, "truanon.bind.authorize", "denied", base, { reason: `Score ${score} < ${threshold}` });
|
|
118
|
+
return { ...base, authorized: false, trustScore: score, status, scopeVerified: true, reason: `Agent trust score ${score} is below minimum ${threshold}` };
|
|
119
|
+
}
|
|
120
|
+
await this.logEvent(input.agentId, "truanon.bind.authorize", "success", base, { trust_score: score });
|
|
121
|
+
return { ...base, authorized: true, trustScore: score, status, scopeVerified: true };
|
|
122
|
+
}
|
|
123
|
+
/** Log that an anchored-human + agent action completed (the end-to-end record). */
|
|
124
|
+
async logBoundAction(agentId, humanUsername, action, metadata) {
|
|
125
|
+
await this.logEvent(agentId, "truanon.bound_action", "success", { agentId, humanUsername }, { bound_action: action, ...metadata });
|
|
126
|
+
}
|
|
127
|
+
emptyProfile() {
|
|
128
|
+
return { rank: "Unknown", score: "0", anchors: [], isAnchored: false };
|
|
129
|
+
}
|
|
130
|
+
async logEvent(agentId, action, result, base, metadata) {
|
|
131
|
+
try {
|
|
132
|
+
await this.sdk.emit({
|
|
133
|
+
agent_id: agentId,
|
|
134
|
+
event_type: "api_request",
|
|
135
|
+
action,
|
|
136
|
+
result,
|
|
137
|
+
resource: base?.humanUsername ?? "",
|
|
138
|
+
metadata: {
|
|
139
|
+
provider: "truanon",
|
|
140
|
+
service: this.service,
|
|
141
|
+
human_username: base?.humanUsername ?? "",
|
|
142
|
+
human_rank: base?.humanRank ?? "",
|
|
143
|
+
human_score: base?.humanScore ?? "",
|
|
144
|
+
human_anchored: base?.humanAnchored ?? false,
|
|
145
|
+
human_rank_met: base?.humanRankMet ?? false,
|
|
146
|
+
...metadata
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
} catch {
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
function createVorimTruAnon(sdk, config) {
|
|
154
|
+
return new VorimTruAnon(sdk, config);
|
|
155
|
+
}
|
|
156
|
+
export {
|
|
157
|
+
VorimTruAnon,
|
|
158
|
+
createVorimTruAnon,
|
|
159
|
+
meetsMinimumRank
|
|
160
|
+
};
|
|
161
|
+
//# sourceMappingURL=truanon.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/integrations/truanon.ts"],"sourcesContent":["// ============================================================================\n// Vorim AI — TruAnon Integration\n//\n// TruAnon (truanon.com) anchors a real HUMAN to an account: a member binds their\n// profile to connections other people already know them by, without the platform\n// storing any identity documents. TruAnon returns a rank (Genuine, Reliable,\n// Credible, Cautioned, Dangerous, Unknown) and a 0-5 score for the human.\n//\n// Vorim anchors the AI AGENT: cryptographic identity, scoped permissions, and a\n// signed audit trail of what the agent did. This integration BINDS the two: it\n// verifies a human is anchored (via TruAnon) AND the acting agent is authorized\n// (via Vorim), then signs an audit event capturing BOTH identities — so you can\n// prove one accountable line from a verified human, through the platform, to the\n// specific agent and action. Protection end to end.\n//\n// It calls TruAnon's public API server-side with your private key, and Vorim's\n// verify/emit. Keep the TruAnon private key on the server — never in the browser.\n//\n// Usage:\n// import createVorim from '@vorim/sdk';\n// import { createVorimTruAnon } from '@vorim/sdk/integrations/truanon';\n//\n// const vorim = createVorim({ apiKey: 'agid_sk_...' });\n// const truanon = createVorimTruAnon(vorim, {\n// privateKey: process.env.VORIM_TRUANON_KEY!, // server-side only\n// service: process.env.VORIM_TRUANON_SERVICE!, // your TruAnon service name\n// minRank: 'Credible', // ID-verification-equivalent\n// });\n//\n// // Before an agent acts on a human's behalf, bind + authorize:\n// const auth = await truanon.authorizeAgentForHuman({\n// agentId: 'agid_abc123',\n// humanUsername: 'jtayler',\n// });\n// if (auth.authorized) { /* proceed; the binding is signed to the audit trail */ }\n// ============================================================================\n\nimport type { VorimSDK } from '../index.js';\n\n/** TruAnon rank tiers, weakest to strongest. `Unknown` never meets a minimum. */\nexport type TruAnonRank = 'Unknown' | 'Dangerous' | 'Cautioned' | 'Credible' | 'Reliable' | 'Genuine';\n\n// Verbatim from the TruAnon API: index-based ordering, Unknown is off-axis.\nconst RANK_ORDER: TruAnonRank[] = ['Dangerous', 'Cautioned', 'Credible', 'Reliable', 'Genuine'];\n\n/** Does `userRank` meet or exceed `minimumRank`? Unknown always fails. */\nexport function meetsMinimumRank(userRank: string, minimumRank: TruAnonRank): boolean {\n if (userRank === 'Unknown') return false;\n const u = RANK_ORDER.indexOf(userRank as TruAnonRank);\n const m = RANK_ORDER.indexOf(minimumRank);\n return u >= 0 && m >= 0 && u >= m;\n}\n\nexport interface TruAnonAnchor {\n name: string;\n display: string;\n icon: string;\n type: string;\n kind: string;\n}\n\n/** The get_profile response shape (the fields TruAnon returns for a human). */\nexport interface TruAnonProfile {\n rank: string;\n score: string; // \"0\" .. \"5.0\"\n name?: string;\n title?: string;\n photo?: string;\n ageBadge?: string;\n anchors?: TruAnonAnchor[];\n isAnchored: boolean; // derived: true when TruAnon returned a real rank\n}\n\nexport interface TruAnonConfig {\n /** Vorim API key (already on the sdk instance; not used directly here). */\n apiKey?: string;\n baseUrl?: string;\n /** TruAnon private API key — SERVER-SIDE ONLY. */\n privateKey: string;\n /** Your registered TruAnon service name. */\n service: string;\n /** Minimum human rank required to authorize an agent. Default 'Credible'. */\n minRank?: TruAnonRank;\n /** Minimum agent trust score. Default 50. */\n minTrustScore?: number;\n /** Required agent scope. Default 'agent:transact'. */\n requiredScope?: string;\n /** TruAnon API base. Default 'https://truanon.com/api/v2'. */\n truanonBaseUrl?: string;\n /** Per-request timeout in ms. Default 30000 (TruAnon's guidance). */\n timeoutMs?: number;\n /** Injectable fetch (for testing). Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n}\n\nexport interface HumanBindingAuthorization {\n authorized: boolean;\n agentId: string;\n humanUsername: string;\n /** The human's TruAnon rank + whether it met the minimum. */\n humanRank: string;\n humanScore: string;\n humanAnchored: boolean;\n humanRankMet: boolean;\n /** The agent's Vorim standing. */\n trustScore: number;\n status: string;\n scopeVerified: boolean;\n reason?: string;\n}\n\nexport class VorimTruAnon {\n private sdk: VorimSDK;\n private privateKey: string;\n private service: string;\n private minRank: TruAnonRank;\n private minTrustScore: number;\n private requiredScope: string;\n private truanonBaseUrl: string;\n private timeoutMs: number;\n private doFetch: typeof fetch;\n\n constructor(sdk: VorimSDK, config: TruAnonConfig) {\n if (!config?.privateKey) throw new Error('[vorim] TruAnon integration requires a privateKey (server-side only).');\n if (!config?.service) throw new Error('[vorim] TruAnon integration requires a service name.');\n this.sdk = sdk;\n this.privateKey = config.privateKey;\n this.service = config.service;\n this.minRank = config.minRank ?? 'Credible';\n this.minTrustScore = config.minTrustScore ?? 50;\n this.requiredScope = config.requiredScope ?? 'agent:transact';\n this.truanonBaseUrl = (config.truanonBaseUrl ?? 'https://truanon.com/api/v2').replace(/\\/$/, '');\n this.timeoutMs = config.timeoutMs ?? 30_000;\n this.doFetch = config.fetchImpl ?? fetch;\n }\n\n /**\n * Fetch a human's TruAnon profile (the anchor). Server-side call with your\n * private key. Returns the rank/score/anchors; `isAnchored` is false if the\n * lookup fails or the human has no anchor.\n */\n async verifyHuman(username: string): Promise<TruAnonProfile> {\n const url = `${this.truanonBaseUrl}/get_profile?id=${encodeURIComponent(username)}&service=${encodeURIComponent(this.service)}`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n // redirect: 'error' — never replay the Authorization header to a 3xx target.\n const res = await this.doFetch(url, {\n method: 'GET',\n headers: { Authorization: this.privateKey, Accept: 'application/json' },\n redirect: 'error',\n signal: controller.signal,\n });\n if (!res.ok) return this.emptyProfile();\n const data: any = await res.json();\n const rank = typeof data?.rank === 'string' ? data.rank : 'Unknown';\n return {\n rank,\n score: typeof data?.score === 'string' ? data.score : String(data?.score ?? '0'),\n name: data?.name,\n title: data?.title,\n photo: data?.photo,\n ageBadge: data?.ageBadge,\n anchors: Array.isArray(data?.anchors) ? data.anchors : [],\n isAnchored: rank !== 'Unknown' && !!rank,\n };\n } catch {\n return this.emptyProfile();\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * The binding gate: authorize an agent to act on a human's behalf only if\n * BOTH sides check out — the human is anchored at/above minRank (TruAnon) AND\n * the agent holds the scope, is active, and clears trust (Vorim). Signs an\n * audit event capturing both identities regardless of outcome.\n */\n async authorizeAgentForHuman(input: {\n agentId: string;\n humanUsername: string;\n minRank?: TruAnonRank;\n minTrustScore?: number;\n }): Promise<HumanBindingAuthorization> {\n const minRank = input.minRank ?? this.minRank;\n const threshold = input.minTrustScore ?? this.minTrustScore;\n\n // 1. The human side — TruAnon anchor.\n const profile = await this.verifyHuman(input.humanUsername);\n const rankMet = meetsMinimumRank(profile.rank, minRank);\n\n const base = {\n agentId: input.agentId,\n humanUsername: input.humanUsername,\n humanRank: profile.rank,\n humanScore: profile.score,\n humanAnchored: profile.isAnchored,\n humanRankMet: rankMet,\n };\n\n if (!profile.isAnchored) {\n await this.logEvent(input.agentId, 'truanon.bind.authorize', 'denied', base, { reason: 'Human is not anchored' });\n return { ...base, authorized: false, trustScore: 0, status: 'unknown', scopeVerified: false, reason: `Human ${input.humanUsername} is not anchored on TruAnon` };\n }\n if (!rankMet) {\n await this.logEvent(input.agentId, 'truanon.bind.authorize', 'denied', base, { reason: `Rank ${profile.rank} < ${minRank}` });\n return { ...base, authorized: false, trustScore: 0, status: 'unknown', scopeVerified: false, reason: `Human rank ${profile.rank} is below the required ${minRank}` };\n }\n\n // 2. The agent side — Vorim scope + status + trust.\n try {\n const perm = await this.sdk.check(input.agentId, this.requiredScope as any);\n if (!(perm as any).allowed) {\n await this.logEvent(input.agentId, 'truanon.bind.authorize', 'denied', base, { reason: `Missing ${this.requiredScope}` });\n return { ...base, authorized: false, trustScore: 0, status: 'unknown', scopeVerified: false, reason: `Agent does not have ${this.requiredScope} permission` };\n }\n } catch (e: any) {\n await this.logEvent(input.agentId, 'truanon.bind.authorize', 'denied', base, { reason: `Permission check failed: ${e.message}` });\n return { ...base, authorized: false, trustScore: 0, status: 'unknown', scopeVerified: false, reason: `Permission check failed: ${e.message}` };\n }\n\n let score = 0;\n let status = 'unknown';\n try {\n const trust = await this.sdk.verify(input.agentId);\n score = (trust as any).trust_score ?? 0;\n status = (trust as any).status ?? 'unknown';\n } catch { /* treated as not-active below */ }\n\n if (status !== 'active') {\n await this.logEvent(input.agentId, 'truanon.bind.authorize', 'denied', base, { reason: `Agent status: ${status}` });\n return { ...base, authorized: false, trustScore: score, status, scopeVerified: true, reason: `Agent is ${status}, not active` };\n }\n if (score < threshold) {\n await this.logEvent(input.agentId, 'truanon.bind.authorize', 'denied', base, { reason: `Score ${score} < ${threshold}` });\n return { ...base, authorized: false, trustScore: score, status, scopeVerified: true, reason: `Agent trust score ${score} is below minimum ${threshold}` };\n }\n\n // Both sides pass — sign the binding.\n await this.logEvent(input.agentId, 'truanon.bind.authorize', 'success', base, { trust_score: score });\n return { ...base, authorized: true, trustScore: score, status, scopeVerified: true };\n }\n\n /** Log that an anchored-human + agent action completed (the end-to-end record). */\n async logBoundAction(agentId: string, humanUsername: string, action: string, metadata?: Record<string, any>): Promise<void> {\n await this.logEvent(agentId, 'truanon.bound_action', 'success', { agentId, humanUsername }, { bound_action: action, ...metadata });\n }\n\n private emptyProfile(): TruAnonProfile {\n return { rank: 'Unknown', score: '0', anchors: [], isAnchored: false };\n }\n\n private async logEvent(\n agentId: string,\n action: string,\n result: 'success' | 'denied' | 'error',\n base?: Partial<HumanBindingAuthorization> & { agentId?: string; humanUsername?: string },\n metadata?: Record<string, any>,\n ): Promise<void> {\n try {\n await this.sdk.emit({\n agent_id: agentId,\n event_type: 'api_request',\n action,\n result,\n resource: base?.humanUsername ?? '',\n metadata: {\n provider: 'truanon',\n service: this.service,\n human_username: base?.humanUsername ?? '',\n human_rank: base?.humanRank ?? '',\n human_score: base?.humanScore ?? '',\n human_anchored: base?.humanAnchored ?? false,\n human_rank_met: base?.humanRankMet ?? false,\n ...metadata,\n },\n });\n } catch { /* never block the flow on an audit hiccup */ }\n }\n}\n\n/**\n * Create a VorimTruAnon instance. Bind a TruAnon-anchored human to a\n * Vorim-identified agent, with a signed record of both.\n *\n * @example\n * ```typescript\n * import createVorim from '@vorim/sdk';\n * import { createVorimTruAnon } from '@vorim/sdk/integrations/truanon';\n * const vorim = createVorim({ apiKey: 'agid_sk_...' });\n * const truanon = createVorimTruAnon(vorim, {\n * privateKey: process.env.VORIM_TRUANON_KEY!,\n * service: process.env.VORIM_TRUANON_SERVICE!,\n * minRank: 'Credible',\n * });\n * const auth = await truanon.authorizeAgentForHuman({ agentId: 'agid_abc', humanUsername: 'jtayler' });\n * ```\n */\nexport function createVorimTruAnon(sdk: VorimSDK, config: TruAnonConfig): VorimTruAnon {\n return new VorimTruAnon(sdk, config);\n}\n"],"mappings":";AA2CA,IAAM,aAA4B,CAAC,aAAa,aAAa,YAAY,YAAY,SAAS;AAGvF,SAAS,iBAAiB,UAAkB,aAAmC;AACpF,MAAI,aAAa,UAAW,QAAO;AACnC,QAAM,IAAI,WAAW,QAAQ,QAAuB;AACpD,QAAM,IAAI,WAAW,QAAQ,WAAW;AACxC,SAAO,KAAK,KAAK,KAAK,KAAK,KAAK;AAClC;AA4DO,IAAM,eAAN,MAAmB;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,KAAe,QAAuB;AAChD,QAAI,CAAC,QAAQ,WAAY,OAAM,IAAI,MAAM,uEAAuE;AAChH,QAAI,CAAC,QAAQ,QAAS,OAAM,IAAI,MAAM,sDAAsD;AAC5F,SAAK,MAAM;AACX,SAAK,aAAa,OAAO;AACzB,SAAK,UAAU,OAAO;AACtB,SAAK,UAAU,OAAO,WAAW;AACjC,SAAK,gBAAgB,OAAO,iBAAiB;AAC7C,SAAK,gBAAgB,OAAO,iBAAiB;AAC7C,SAAK,kBAAkB,OAAO,kBAAkB,8BAA8B,QAAQ,OAAO,EAAE;AAC/F,SAAK,YAAY,OAAO,aAAa;AACrC,SAAK,UAAU,OAAO,aAAa;AAAA,EACrC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,YAAY,UAA2C;AAC3D,UAAM,MAAM,GAAG,KAAK,cAAc,mBAAmB,mBAAmB,QAAQ,CAAC,YAAY,mBAAmB,KAAK,OAAO,CAAC;AAC7H,UAAM,aAAa,IAAI,gBAAgB;AACvC,UAAM,QAAQ,WAAW,MAAM,WAAW,MAAM,GAAG,KAAK,SAAS;AACjE,QA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MAAM,cAAc;AAAA,UACjC,gBAAgB,MAAM,iBAAiB;AAAA,UACvC,gBAAgB,MAAM,gBAAgB;AAAA,UACtC,GAAG;AAAA,QACL;AAAA,MACF,CAAC;AAAA,IACH,QAAQ;AAAA,IAAgD;AAAA,EAC1D;AACF;AAmBO,SAAS,mBAAmB,KAAe,QAAqC;AACrF,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,OAAO,EAAE;AAEpE,SAAS,cAAc,GAAuB;AAC5C,QAAM,OAAO,EAAE,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG;AACnD,QAAM,SAAS,OAAO,IAAI,QAAQ,IAAK,KAAK,SAAS,KAAM,CAAC;AAC5D,QAAM,MAAM,OAAO,SAAS,cAAc,KAAK,MAAM,IAAI,OAAO,KAAK,QAAQ,QAAQ,EAAE,SAAS,QAAQ;AACxG,QAAM,MAAM,IAAI,WAAW,IAAI,MAAM;AACrC,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,IAAK,KAAI,CAAC,IAAI,IAAI,WAAW,CAAC;AAC9D,SAAO;AACT;AAEA,SAAS,eAAe,KAAyB;AAC/C,QA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Q,WAAW,IAAI,KAAK,MAAM;AACzD,QAAM,cAAc,IAAI,QAAQ,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG,EAAE,KAAK,GAAG,CAAC,aAAa,OAAO,YAAY,OAAO,WAAW,KAAK,qCAAqC,UAAU;AAIpK,QAAM,YAAsB;AAAA,IAC1B,iBAAiB,EAAE,IAAI;AAAA,IACvB,cAAc,MAAM;AAAA,IACpB,YAAY,EAAE,QAAQ;AAAA,IACtB,sBAAsB,aAAa;AAAA,IACnC,wBAAwB,WAAW;AAAA,EACrC;AACA,QAAM,gBAAgB,UAAU,KAAK,IAAI;AAEzC,QAAM,YAAY,MAAM,YAAY,eAAe,IAAI,UAAU;AAEjE,SAAO;AAAA,IACL,mBAAmB,GAAG,KAAK,IAAI,WAAW;AAAA,IAC1C,aAAa,GAAG,KAAK,KAAK,IAAI,SAAS,CAAC;AAAA,IACxC,mBAAmB;AAAA,EACrB;AACF;AAIA,SAAS,aAAqB;AAC5B,SAAO,KAAK,IAAI,IAAI;AACtB;","names":[]}
|
|
@@ -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,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 };
|