@belticlabs/agent-risk-sdk 0.6.0 → 0.8.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.
@@ -1,144 +0,0 @@
1
- import {
2
- summaryOf
3
- } from "./chunk-M4I3FGZG.js";
4
- import {
5
- toJsonObject
6
- } from "./chunk-FQDHFTVR.js";
7
- import {
8
- payloadDigest
9
- } from "./chunk-77D74TWX.js";
10
-
11
- // src/x402/binding.ts
12
- var SESSION_EXTENSION = "beltic.sessionId";
13
- var SESSION_HEADER = "Beltic-Session-Id";
14
- function sessionIdOf(extensions) {
15
- const v = extensions?.[SESSION_EXTENSION];
16
- return typeof v === "string" && v.length > 0 ? v : null;
17
- }
18
-
19
- // src/x402/moments.ts
20
- function x402Currency(network, asset) {
21
- return `${network}/${asset}`;
22
- }
23
- function x402Summary(accepts, opts = {}) {
24
- const payer = opts.payer?.toLowerCase();
25
- return {
26
- protocol: "x402",
27
- payee: accepts?.payTo ?? "unknown",
28
- amount: {
29
- value: accepts?.amount ?? "0",
30
- currency: accepts ? x402Currency(accepts.network ?? "unknown", accepts.asset ?? "unknown") : "unknown"
31
- },
32
- ...payer ? { payer } : {}
33
- };
34
- }
35
- function fromAccepts(a, artifact, raw, payer) {
36
- return { ...x402Summary(a, { payer }), artifact, raw };
37
- }
38
- function payerOf(payload) {
39
- const p = payload.payload ?? {};
40
- const auth = p.authorization;
41
- const candidates = [
42
- auth?.from,
43
- p.from,
44
- p.payer,
45
- p.signer,
46
- p.permit?.owner
47
- ];
48
- const hit = candidates.find((c) => typeof c === "string" && c.length > 0);
49
- return typeof hit === "string" ? hit.toLowerCase() : void 0;
50
- }
51
- var x402Moments = {
52
- /** The 402 challenge as the buyer saw it, from the `PAYMENT-REQUIRED` header. */
53
- required(required) {
54
- return fromAccepts(required.accepts?.[0], "http-402", toJsonObject(required));
55
- },
56
- /** The requirements the seller's resource server resolved for a request. */
57
- requirements(req) {
58
- return fromAccepts(req, "http-402", toJsonObject(req));
59
- },
60
- /** A route's static `accepts` config, before any payment header exists. */
61
- route(route, raw) {
62
- const accepts = route ?? {};
63
- const extra = accepts.extra;
64
- return fromAccepts(
65
- {
66
- payTo: typeof accepts.payTo === "string" ? accepts.payTo : "dynamic",
67
- amount: priceValue(accepts.price),
68
- network: accepts.network,
69
- asset: extra?.asset ?? "route"
70
- },
71
- "http-402",
72
- raw
73
- );
74
- },
75
- /** The signed payment the buyer presented, with the requirement it accepted. */
76
- payload(payload) {
77
- return fromAccepts(
78
- payload.accepted,
79
- "payment-signature",
80
- toJsonObject(payload),
81
- payerOf(payload)
82
- );
83
- }
84
- };
85
- function priceValue(price) {
86
- if (typeof price === "string") return price.replace(/[^0-9.]/g, "") || "0";
87
- if (typeof price === "number") return String(price);
88
- if (price && typeof price === "object" && typeof price.amount === "string")
89
- return price.amount;
90
- return "0";
91
- }
92
-
93
- // src/x402/adapter.ts
94
- function attachX402(beltic, server, http) {
95
- const inFlight = /* @__PURE__ */ new Map();
96
- http?.onProtectedRequest(async (ctx, route) => {
97
- if (ctx.paymentHeader) return;
98
- const bound = ctx.adapter.getHeader(SESSION_HEADER) ?? ctx.adapter.getHeader(SESSION_HEADER.toLowerCase());
99
- if (!bound) return;
100
- const stream = await beltic.streams.ensure(bound);
101
- const accepts = Array.isArray(route.accepts) ? route.accepts[0] : route.accepts;
102
- await stream.emit(
103
- "payment.requested",
104
- x402Moments.route(accepts, {
105
- path: ctx.path,
106
- method: ctx.method,
107
- route: JSON.parse(JSON.stringify(route))
108
- })
109
- );
110
- });
111
- server.onBeforeVerify(async (ctx) => {
112
- const payload = ctx.paymentPayload;
113
- const requirements = ctx.requirements;
114
- const stream = await beltic.streams.ensure(sessionIdOf(payload.extensions));
115
- if (stream.born === "seller")
116
- await stream.emit("payment.requested", x402Moments.requirements(requirements));
117
- const presented = x402Moments.payload(payload);
118
- await stream.emit("payment.presented", presented);
119
- inFlight.set(payloadDigest(payload), stream);
120
- const decision = await beltic.evaluate(stream.id, summaryOf(presented));
121
- if (decision.absent || decision.allowed) return;
122
- return {
123
- abort: true,
124
- reason: `BELTIC_${decision.value}`,
125
- message: decision.reasonCodes.join(",")
126
- };
127
- });
128
- server.onAfterSettle(async (ctx) => {
129
- const key = payloadDigest(ctx.paymentPayload);
130
- const stream = inFlight.get(key);
131
- if (!stream) return;
132
- inFlight.delete(key);
133
- if (ctx.result.success) await stream.close("settled", { transaction: ctx.result.transaction });
134
- });
135
- }
136
-
137
- export {
138
- SESSION_EXTENSION,
139
- SESSION_HEADER,
140
- x402Currency,
141
- x402Summary,
142
- x402Moments,
143
- attachX402
144
- };
@@ -1,13 +0,0 @@
1
- // src/core/payment-moment.ts
2
- function summaryOf(m) {
3
- return {
4
- protocol: m.protocol,
5
- payee: m.payee,
6
- amount: { value: m.amount.value, currency: m.amount.currency },
7
- ...m.payer ? { payer: m.payer } : {}
8
- };
9
- }
10
-
11
- export {
12
- summaryOf
13
- };
@@ -1,65 +0,0 @@
1
- import { a7 as PaymentSummary } from './index-IfY4XCvJ.js';
2
- import { b as SessionOptions, S as Session, a as Decision } from './session-Dcof4UIn.js';
3
-
4
- /**
5
- * One SDK, two halves (Fraud SDK RFC › Summary). `Beltic` is the single
6
- * client: `session` for the buyer half, `evaluate` for whichever half is
7
- * about to let a payment through. Protocol integrations are plain
8
- * functions behind subpath exports, each pulling exactly one optional peer:
9
- *
10
- * @belticlabs/agent-risk-sdk/ai → middleware(session), wrapTools(session, …)
11
- * @belticlabs/agent-risk-sdk/x402 → belticFetch(session), x402Summary(…), attachX402(beltic, …)
12
- * @belticlabs/agent-risk-sdk/hono → belticPaymentMiddleware(beltic, …)
13
- *
14
- * Neither half decides risk locally: verdicts are platform-side.
15
- *
16
- * A client is configured or it is not constructed — `Beltic.fromEnv()`
17
- * reads `BELTIC_*`, and there is no disabled client (GAP-78). Evidence is
18
- * a side channel of the work it observes, so a platform outage never
19
- * throws into that work (GAP-70): the transport waits it out, `session`
20
- * runs without a stream, `evaluate` answers `Decision.absent()` — never an
21
- * invented verdict. What the platform *rejects* (a 4xx, a forked chain)
22
- * is the client's fault and throws.
23
- */
24
-
25
- declare const SDK_VERSION = "0.6.0";
26
- interface BelticOptions {
27
- apiKey: string;
28
- baseUrl: string;
29
- /** The agent's 32-byte Ed25519 seed as 64 hex — the buyer half. Without it, `session` is unavailable; the seller half works. */
30
- agentSeed?: string | undefined;
31
- }
32
- declare class Beltic {
33
- private readonly api;
34
- private readonly transport;
35
- private readonly sessions;
36
- /**
37
- * The client the environment describes: `BELTIC_API_KEY` and
38
- * `BELTIC_BASE_URL`, both required, and `BELTIC_AGENT_SEED` (64 hex) for
39
- * the buyer half. A missing required variable is a configuration error,
40
- * thrown (GAP-78).
41
- */
42
- static fromEnv(env?: Record<string, string | undefined>): Beltic;
43
- constructor(opts: BelticOptions);
44
- /**
45
- * The session for a key of the host's own (its session, run or
46
- * conversation id) — one object per key until it closes; the options
47
- * count on the first call only. See `Session`.
48
- */
49
- session(key: string, opts?: SessionOptions): Session;
50
- /**
51
- * The platform's verdict on a payment — the seller's before it verifies,
52
- * the buyer's before it presents (Fraud SDK RFC › Evaluation Client).
53
- * Read-your-writes: the buffered evidence is flushed first so the
54
- * platform judges what the caller already saw (GAP-16). Absent when the
55
- * platform could not be reached (GAP-70).
56
- */
57
- evaluate(sessionId: string, payment: PaymentSummary): Promise<Decision>;
58
- /** Send everything buffered now and wait for that attempt. */
59
- flush(): Promise<void>;
60
- shutdown(): Promise<void>;
61
- /** `process.env` where there is a `process` (Node); `{}` on workerd, where the shell passes its `env`. */
62
- private static processEnv;
63
- }
64
-
65
- export { Beltic as B, SDK_VERSION as S, type BelticOptions as a };