@valiron/sdk 1.4.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +11 -148
  2. package/bin/valiron-card.mjs +211 -0
  3. package/dist/card.d.ts +565 -0
  4. package/dist/card.js +722 -0
  5. package/dist/clients.d.ts +6 -6
  6. package/dist/clients.js +33 -26
  7. package/dist/edge.d.ts +87 -0
  8. package/dist/edge.js +164 -0
  9. package/dist/edgeGate.d.ts +146 -0
  10. package/dist/edgeGate.js +230 -0
  11. package/dist/edgeGateVerify.d.ts +146 -0
  12. package/dist/edgeGateVerify.js +243 -0
  13. package/dist/identity.d.ts +6 -0
  14. package/dist/identity.js +6 -1
  15. package/dist/identityMiddleware.d.ts +8 -0
  16. package/dist/identityMiddleware.js +12 -4
  17. package/dist/index.d.ts +5 -10
  18. package/dist/index.js +4 -10
  19. package/dist/middleware.d.ts +20 -9
  20. package/dist/middleware.js +47 -19
  21. package/dist/operatorSdk.d.ts +11 -2
  22. package/dist/operatorSdk.js +13 -7
  23. package/dist/types.d.ts +14 -4
  24. package/docs/AGENT-READY-APIS.md +3 -181
  25. package/docs/API-REFERENCE.md +94 -546
  26. package/docs/CHAINS.md +3 -3
  27. package/docs/CLOUDFLARE-GATE-MIDDLEWARE.md +196 -0
  28. package/docs/CRAWLER-PROTECTION.md +545 -0
  29. package/docs/DASHBOARD.md +55 -23
  30. package/docs/E2E-MIDDLEWARE-INTEGRATION.md +19 -13
  31. package/docs/ERRORS.md +29 -19
  32. package/docs/IDENTITY.md +16 -14
  33. package/docs/PROVIDER-IDENTITY.md +15 -5
  34. package/docs/QUICKSTART.md +40 -24
  35. package/docs/README.md +21 -4
  36. package/docs/SANDBOX.md +7 -1
  37. package/docs/SDK-REFERENCE.md +115 -52
  38. package/docs/SECURITY-UPGRADE-2026-10-31.md +98 -0
  39. package/docs/TRUST-MODEL.md +14 -11
  40. package/docs/llms.txt +70 -302
  41. package/examples/cloudflare-gate-worker/README.md +198 -0
  42. package/examples/cloudflare-gate-worker/package.json +20 -0
  43. package/examples/cloudflare-gate-worker/worker.ts +309 -0
  44. package/examples/cloudflare-gate-worker/wrangler.toml +46 -0
  45. package/examples/cloudflare-worker/package.json +8 -0
  46. package/examples/cloudflare-worker/worker.ts +495 -0
  47. package/examples/cloudflare-worker/wrangler.toml +57 -0
  48. package/package.json +35 -5
  49. package/docs/MCP.md +0 -50
package/README.md CHANGED
@@ -1,157 +1,20 @@
1
1
  # @valiron/sdk
2
2
 
3
- Official TypeScript SDK for **Valiron** — Trust & Reputation Middleware for API Protection
3
+ Valiron verifies AI agent identity and enforces access policies at your API.
4
4
 
5
- Protect your API endpoints from bad or malicious AI agents. Valiron evaluates incoming agents using on-chain identity (ERC-8004/Solana), key-based identity for local/Web2 agents, behavioral sandbox testing, optional wallet-history intelligence, predictive risk forecasts, and Moody's-style credit ratings — so you can allow trusted agents and block risky ones automatically.
5
+ - [Documentation](https://www.valiron.co/docs)
6
+ - [Agent docs](https://www.valiron.co/llms-full.txt)
7
+ - [Website](https://www.valiron.co)
8
+ - [founders@valiron.co](mailto:founders@valiron.co)
6
9
 
7
- ## Installation
10
+ ## Hosted request billing
8
11
 
9
- ```bash
10
- npm install @valiron/sdk
11
- ```
12
+ Free includes 10,000 metered middleware requests per UTC month; Pro includes 100,000. Active paid Pro customers can separately opt in to additional middleware calls at 0.001 each in their subscription currency. Crawler Protection has its own allowance and opt-in. This counts hosted admission calls, not every local SDK method. View current counts and request-overage estimates in [Dashboard → Usage](https://www.valiron.co/dashboard/usage). See the [metered routes and billing contract](https://www.valiron.co/docs/agents/API-REFERENCE.md#monthly-request-allowance).
12
13
 
13
- ## Quick Start
14
+ ## Website crawler protection
14
15
 
15
- ```typescript
16
- import { ValironSDK, createValironGate } from "@valiron/sdk";
16
+ Website crawler verification and rendering/database admission use the separate `@valiron/crawler-protection` package, not this agent middleware SDK. Install `npm install @valiron/crawler-protection@^0.6.0` for the current AI provider checks and explicit allow/block defaults. Sign up for a server-side operator key and follow the [Crawler Protection quickstart](https://www.valiron.co/docs/crawler-protection/quickstart) and [selected AI service policy](https://www.valiron.co/docs/crawler-protection/policies#allow-selected-ai-services). Their allowances and optional overage consent are independent.
17
17
 
18
- const valiron = new ValironSDK({
19
- chain: "ethereum",
20
- apiKey: process.env.VALIRON_API_KEY, // required for Pro signals
21
- });
18
+ ## Cloudflare Workers gate
22
19
 
23
- // Check if an on-chain agent is trusted
24
- const route = await valiron.checkAgent("AGENT_ID");
25
- // Returns: "prod" | "prod_throttled" | "sandbox" | "sandbox_only"
26
-
27
- // Check a local/Web2/non-ERC-8004 agent by persistent key address
28
- const keyProfile = await valiron.getKeyAgentProfile("0xAgentAddress");
29
- console.log(keyProfile.route);
30
-
31
- // Gate an agent — allow/deny decision
32
- const gate = await valiron.gate("AGENT_ID");
33
- if (gate.allow) { /* serve the request */ }
34
-
35
- // One-line Express middleware — blocks untrusted agents automatically
36
- app.use("/api/paid", createValironGate({ sdk: valiron }));
37
-
38
- // Optional: choose endpoint-specific trust signals
39
- app.use("/api/paid", createValironGate({
40
- sdk: valiron,
41
- trustSignals: ["8004", "sandbox"], // Pro can add "world", "self", "icebreaker", and "wallet"
42
- }));
43
-
44
- // Fastify, Next.js, and generic middleware also available
45
- // See SDK Reference for valironFastifyPlugin, createValironNextMiddleware, valironGateCheck
46
- ```
47
-
48
- No API key is required for basic read operations. Sandbox runs require an operator API key. Pro trust signals, enriched profiles, proxy calls, webhooks, and `getWalletRisk()` require a Pro operator key.
49
-
50
- Use `x-agent-id` for ERC-8004/Solana agents. Use `x-agent-address` plus Valiron challenge-response for local, Web2, or non-ERC-8004 agents. Agents can follow the hosted identity skill at https://www.valiron.co/auth.md.
51
-
52
- For a verified key-based agent, a Pro operator can read private Icebreaker
53
- human-owner context with `getKeyAgentIcebreaker()`:
54
-
55
- ```typescript
56
- const { icebreaker } = await valiron.getKeyAgentIcebreaker("0xAgentAddress");
57
- if (icebreaker.attested) {
58
- console.log(icebreaker.owner, icebreaker.verifiedHandles);
59
- }
60
- ```
61
-
62
- The public key-agent profile redacts this context. The API seller decides
63
- whether to require the attestation for an action; it does not automatically
64
- change the Web2 behavioral score or provide social connections or mutuals.
65
-
66
- Provider-backed identities such as ANS use signed `x-valiron-identity-*`
67
- headers. SDK 1.3 provides `createAgentIdentityProof()` for agents,
68
- `verifyAgentIdentity()` for low-level verification, and dedicated Express,
69
- Fastify, Next.js, and generic identity gates. Valiron hosts the ANS credentials
70
- and trusted CA bundle; SDK users do not configure them. See the
71
- [provider-backed identity guide](https://valiron.co/docs/agents/PROVIDER-IDENTITY.md)
72
- for the signing and middleware quickstart.
73
-
74
- ```typescript
75
- import {
76
- agentIdentityProofHeaders,
77
- createAgentIdentityProof,
78
- createValironIdentityGate,
79
- } from "@valiron/sdk";
80
-
81
- // Agent: sign the exact bytes it will send.
82
- const body = JSON.stringify({ operation: "quote" });
83
- const proof = await createAgentIdentityProof({
84
- provider: "ans",
85
- agentId: "ans://v1.0.0.sales-agent.acme.com",
86
- body,
87
- sign: (payload) => agentKey.sign(payload),
88
- });
89
- await fetch(apiUrl, { method: "POST", body, headers: agentIdentityProofHeaders(proof) });
90
-
91
- // API owner: capture raw bytes, then enforce the returned identity policy.
92
- app.use(express.json({ verify: (req: any, _res, bytes) => { req.rawBody = Buffer.from(bytes); } }));
93
- app.post("/quote", createValironIdentityGate({
94
- sdk: valiron,
95
- policy: { anonymous: "challenge", claimed: "block", verified: "allow" },
96
- }), handler);
97
- ```
98
-
99
- ## Error diagnostics
100
-
101
- SDK failures are `ValironError` instances. Handle the stable `code` programmatically and log `details.action`, `details.requestId`, `details.docsUrl`, and `details.retryAfterMs` to make recovery explicit.
102
-
103
- ```typescript
104
- import { ValironError } from "@valiron/sdk";
105
-
106
- try {
107
- await valiron.getAgentProfile("AGENT_ID");
108
- } catch (error) {
109
- if (error instanceof ValironError) {
110
- console.error(error.code, error.message, error.details?.action);
111
- }
112
- }
113
- ```
114
-
115
- Trust middleware returns the same fields in JSON responses. Its primary codes are `MISSING_AGENT_IDENTITY`, `TRUST_GATE_DENIED`, `AGENT_EVALUATION_PENDING`, and `TRUST_GATE_UNAVAILABLE`. See the [error guide](https://valiron.co/docs#error-handling) for retry rules and hosted-wrapper diagnostics.
116
-
117
- ### Additional Features
118
-
119
- - **Auto-Sandbox** — Middleware automatically evaluates new agents (on-chain and key-based) on their first gated request
120
- - **Predictive Risk** — Dashboard/API forecasts whether an observed agent is improving, stable, or becoming riskier before the next action
121
- - **Proxy Gateway** (Pro) — Forward requests through Valiron's edge proxy with SSRF protection
122
- - **Key-Based Agents** — Support Web2 agents via EIP-191 challenge-response (auto-detected, auto-sandboxed)
123
- - **World ID** — Verify agent-human linkage via Worldcoin proof-of-personhood
124
- - **Self** — Create Self Enterprise sessions and store signed eligible-human webhook results
125
- - **Wallet Intelligence** (Pro) — Score bounded Alchemy/Helius wallet history with confidence and explainable reasons
126
- - **Telemetry** — Optional anonymous usage metrics (disable with `telemetry: { enabled: false }`)
127
-
128
- ### Cleanup
129
-
130
- Call `dispose()` when shutting down long-running servers:
131
-
132
- ```typescript
133
- await valiron.dispose();
134
- ```
135
-
136
- ## Documentation
137
-
138
- Full SDK reference, API docs, trust model, and integration guides:
139
-
140
- - **[valiron.co/docs](https://valiron.co/docs)** — interactive documentation
141
- - **[SDK Reference](https://valiron.co/docs/agents/SDK-REFERENCE.md)** — all methods, options, and response types
142
- - **[API Reference](https://valiron.co/docs/agents/API-REFERENCE.md)** — HTTP endpoints
143
- - **[Quickstart](https://valiron.co/docs/agents/QUICKSTART.md)** — get started in 2 minutes
144
- - **[End-to-End Middleware Integration](https://valiron.co/docs/agents/E2E-MIDDLEWARE-INTEGRATION.md)** — identity, trust signals, downstream policy, and testing
145
- - **[Provider-Backed Identity](https://valiron.co/docs/agents/PROVIDER-IDENTITY.md)** — resolver foundation, proof format, replay handling, policy actions, and ANS adapter status
146
- - **[Error Guide](https://valiron.co/docs#error-handling)** — codes, recovery actions, retries, and wrapper diagnostics
147
- - **[llms.txt](https://valiron.co/llms.txt)** — compact reference for LLM/agent integration
148
- - **Install agent skill**: `npx @valiron/skill`
149
-
150
- ## Support
151
-
152
- - **Email**: founders@valiron.co
153
- - **Telegram**: https://t.me/valirongrade
154
-
155
- ## License
156
-
157
- MIT © Valiron
20
+ Import `ValironClient`, `runValironEdgeGate`, `stripEdgeGateHeaders`, and `createEdgeIdentityVerifier` from `@valiron/sdk/edge-gate`. This node-free entry point runs the same general trust-gate contract (fresh request-bound proof checked before every decision including profile-cache hits, a 30-second per-isolate profile cache, and fail-closed 503s) in Cloudflare Workers and other fetch-based edge runtimes. A deployable template lives in `examples/cloudflare-gate-worker`; setup and end-to-end verification are in the [Cloudflare gate middleware guide](https://www.valiron.co/docs/agents/CLOUDFLARE-GATE-MIDDLEWARE.md).
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env node
2
+ import { readFile, open, unlink } from "node:fs/promises";
3
+ import {
4
+ CardClient,
5
+ CardSellerClient,
6
+ CardAPIError,
7
+ createCardKey,
8
+ } from "../dist/card.js";
9
+
10
+ const [role, action, ...args] = process.argv.slice(2);
11
+ const option = (name) => {
12
+ const i = args.indexOf(`--${name}`);
13
+ if (i < 0 || !args[i + 1] || args[i + 1].startsWith("--"))
14
+ throw new Error(`--${name} is required`);
15
+ return args[i + 1];
16
+ };
17
+ const env = (name) => {
18
+ if (!process.env[name]) throw new Error(`${name} is required`);
19
+ return process.env[name];
20
+ };
21
+ const jsonInput = async () =>
22
+ JSON.parse(await readFile(option("input"), "utf8"));
23
+ // Exclusive creation prevents replacing another agent's keys or following a symlink.
24
+ async function saveSecret(path, produce) {
25
+ const file = await open(path, "wx", 0o600);
26
+ try {
27
+ const result = await produce();
28
+ await file.writeFile(JSON.stringify(result, null, 2));
29
+ return result;
30
+ } catch (error) {
31
+ await file.close();
32
+ await unlink(path);
33
+ throw error;
34
+ } finally {
35
+ await file.close();
36
+ }
37
+ }
38
+ async function main() {
39
+ if (!role || role === "--help")
40
+ return {
41
+ commands: [
42
+ "agent apply --name NAME --key-file NEW_FILE",
43
+ "agent link --code CODE --name NAME --key-file NEW_FILE",
44
+ "agent poll --key-file FILE",
45
+ "seller status",
46
+ "seller register --input FILE",
47
+ "seller key --input FILE --output NEW_SECRET_FILE",
48
+ "seller offers",
49
+ "seller offer-create --input FILE",
50
+ "seller test-enable --id ID",
51
+ "seller publish --id ID",
52
+ "seller disable --id ID",
53
+ "seller revoke --id ID",
54
+ ],
55
+ authentication: {
56
+ baseUrl:
57
+ "VALIRON_PASS_API_URL; set VALIRON_PASS_TRANSPORT=website for the Valiron website, otherwise use the explicitly enabled local Pass service API",
58
+ bootstrap: "VALIRON_OPERATOR_TOKEN (authorized seller session)",
59
+ operations: "VALIRON_PASS_MERCHANT_KEY (scoped Test or Live key)",
60
+ },
61
+ workspace: "https://www.valiron.co/pass",
62
+ };
63
+ const baseUrl = process.env.VALIRON_PASS_API_URL ?? env("VALIRON_CARD_API_URL");
64
+ const transport =
65
+ (process.env.VALIRON_PASS_TRANSPORT ?? process.env.VALIRON_CARD_TRANSPORT) === "website" ? "website" : "service";
66
+ if (role === "agent") {
67
+ const client = new CardClient({ baseUrl, transport });
68
+ if (action === "apply") {
69
+ const name = option("name");
70
+ const stored = await saveSecret(option("key-file"), async () => {
71
+ const keys = createCardKey();
72
+ const application = await client.startApplication({
73
+ name,
74
+ privateKey: keys.privateKey,
75
+ });
76
+ return { ...keys, application };
77
+ });
78
+ const { approvalUrl, comparisonCode, expiresAt, pollIntervalSeconds } =
79
+ stored.application;
80
+ return {
81
+ status: "owner_approval_required",
82
+ approvalUrl,
83
+ comparisonCode,
84
+ expiresAt,
85
+ pollIntervalSeconds,
86
+ nextAction:
87
+ "Ask the owner to open the URL, sign in or apply with an invite, compare the code, and approve. Then poll with the same key file. Never approve on their behalf.",
88
+ };
89
+ }
90
+ if (action === "link") {
91
+ const code = option("code");
92
+ const name = option("name");
93
+ const stored = await saveSecret(option("key-file"), async () => {
94
+ const keys = createCardKey();
95
+ const application = await client.linkWithInvite({
96
+ code, name, privateKey: keys.privateKey,
97
+ });
98
+ return { ...keys, application };
99
+ });
100
+ return {
101
+ status: "owner_approval_required",
102
+ approvalUrl: stored.application.approvalUrl,
103
+ comparisonCode: stored.application.comparisonCode,
104
+ expiresAt: stored.application.expiresAt,
105
+ pollIntervalSeconds: stored.application.pollIntervalSeconds,
106
+ nextAction: "Show the owner the approval URL and comparison code, wait for their explicit approval, then poll with the same private key file.",
107
+ };
108
+ }
109
+ if (action === "poll") {
110
+ const stored = JSON.parse(await readFile(option("key-file"), "utf8"));
111
+ return client.pollApplication({
112
+ id: stored.application.id,
113
+ pollSecret: stored.application.pollSecret,
114
+ privateKey: stored.privateKey,
115
+ });
116
+ }
117
+ }
118
+ if (role === "seller") {
119
+ if (["status", "register", "key", "revoke"].includes(action)) {
120
+ if (!process.env.VALIRON_OPERATOR_TOKEN) {
121
+ process.exitCode = 2;
122
+ return {
123
+ status: "authorization_required",
124
+ code: "operator_access_required",
125
+ signInUrl:
126
+ transport === "website"
127
+ ? new URL("/dashboard/login?next=%2Fdashboard%2Fpass", baseUrl)
128
+ .href
129
+ : null,
130
+ nextAction:
131
+ "Ask the business operator to sign in and authorize bootstrap through the runtime secret store. Never request their password or an administrator key.",
132
+ };
133
+ }
134
+ const seller = new CardSellerClient({
135
+ baseUrl,
136
+ transport,
137
+ operatorToken: env("VALIRON_OPERATOR_TOKEN"),
138
+ });
139
+ if (action === "status") {
140
+ const setup = await seller.getSetup();
141
+ return {
142
+ ...setup,
143
+ nextAction: !setup.merchant
144
+ ? "register_business"
145
+ : setup.merchant.status === "pending"
146
+ ? "wait_for_pilot_approval"
147
+ : setup.merchant.status !== "active"
148
+ ? "contact_support"
149
+ : !setup.credentials.some(
150
+ (k) =>
151
+ !k.revoked_at && Date.parse(k.expires_at) > Date.now(),
152
+ )
153
+ ? "create_scoped_test_credentials"
154
+ : "configure_offer_and_test_real_enforcement",
155
+ };
156
+ }
157
+ if (action === "register")
158
+ return seller.registerBusiness(await jsonInput());
159
+ if (action === "revoke") return seller.revokeCredential(option("id"));
160
+ if (action === "key") {
161
+ const input = await jsonInput();
162
+ const path = option("output");
163
+ const result = await saveSecret(path, () =>
164
+ seller.createCredential(input),
165
+ );
166
+ return {
167
+ id: result.id,
168
+ expiresAt: result.expires_at,
169
+ credentialFile: path,
170
+ status: "created",
171
+ nextAction:
172
+ "Load the key from this private file into the authorized service secret store. It is not printed.",
173
+ };
174
+ }
175
+ }
176
+ const client = new CardClient({
177
+ baseUrl,
178
+ transport,
179
+ merchantKey: process.env.VALIRON_PASS_MERCHANT_KEY ?? env("VALIRON_CARD_MERCHANT_KEY"),
180
+ });
181
+ if (action === "offers") return client.listOffers();
182
+ if (action === "offer-create") return client.createOffer(await jsonInput());
183
+ if (action === "test-enable") return client.enableTestOffer(option("id"));
184
+ if (action === "publish") return client.publishOffer(option("id"));
185
+ if (action === "disable") return client.disableOffer(option("id"));
186
+ }
187
+ throw new Error("Unknown command. Run valiron-pass --help.");
188
+ }
189
+ try {
190
+ console.log(JSON.stringify(await main(), null, 2));
191
+ } catch (error) {
192
+ // Never echo transport errors, response bodies, input, or credentials.
193
+ console.error(
194
+ JSON.stringify(
195
+ error instanceof CardAPIError
196
+ ? {
197
+ status: "error",
198
+ httpStatus: error.status,
199
+ code: error.code,
200
+ retryable: error.status === 429 || error.status >= 500,
201
+ }
202
+ : {
203
+ status: "error",
204
+ code: "command_failed",
205
+ nextAction:
206
+ "Check command syntax, required environment, private file paths, and network access. Run valiron-pass --help.",
207
+ },
208
+ ),
209
+ );
210
+ process.exitCode = 1;
211
+ }