@vinaystwt/xmpp-policy-engine 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/config/src/index.d.ts +49 -0
- package/dist/config/src/index.js +117 -0
- package/dist/contract-runtime/src/index.d.ts +44 -0
- package/dist/contract-runtime/src/index.js +364 -0
- package/dist/logger/src/index.d.ts +2 -0
- package/dist/logger/src/index.js +18 -0
- package/dist/policy-engine/src/index.d.ts +8 -0
- package/dist/policy-engine/src/index.js +90 -0
- package/dist/policy-engine/src/index.test.d.ts +1 -0
- package/dist/policy-engine/src/index.test.js +21 -0
- package/dist/types/src/index.d.ts +343 -0
- package/dist/types/src/index.js +1 -0
- package/package.json +50 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 xMPP contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export declare const config: {
|
|
2
|
+
readonly nodeEnv: string;
|
|
3
|
+
readonly network: string;
|
|
4
|
+
readonly paymentExecutionMode: "mock" | "testnet";
|
|
5
|
+
readonly rpcUrl: string;
|
|
6
|
+
readonly networkPassphrase: string;
|
|
7
|
+
readonly gatewayPort: number;
|
|
8
|
+
readonly dashboardPort: number;
|
|
9
|
+
readonly dashboardGatewayUrl: string | undefined;
|
|
10
|
+
readonly dailyBudgetUsd: number;
|
|
11
|
+
readonly facilitatorUrl: string;
|
|
12
|
+
readonly wallet: {
|
|
13
|
+
readonly agentSecretKey: string | undefined;
|
|
14
|
+
readonly smartAccountContractId: string | undefined;
|
|
15
|
+
readonly smartAccountWasmHash: string;
|
|
16
|
+
readonly webauthnVerifierAddress: string;
|
|
17
|
+
readonly ed25519VerifierAddress: string;
|
|
18
|
+
readonly spendingLimitPolicyAddress: string;
|
|
19
|
+
readonly thresholdPolicyAddress: string;
|
|
20
|
+
};
|
|
21
|
+
readonly x402: {
|
|
22
|
+
readonly facilitatorUrl: string;
|
|
23
|
+
readonly facilitatorApiKey: string | undefined;
|
|
24
|
+
readonly maxTransactionFeeStroops: number;
|
|
25
|
+
readonly facilitatorPrivateKey: string | undefined;
|
|
26
|
+
readonly recipientAddress: string | undefined;
|
|
27
|
+
};
|
|
28
|
+
readonly mpp: {
|
|
29
|
+
readonly secretKey: string | undefined;
|
|
30
|
+
readonly recipientAddress: string | undefined;
|
|
31
|
+
readonly channelContractId: string | undefined;
|
|
32
|
+
readonly feeSponsorshipEnabled: boolean;
|
|
33
|
+
readonly feeSponsorship: {
|
|
34
|
+
readonly chargeEnabled: boolean;
|
|
35
|
+
readonly sessionEnabled: boolean;
|
|
36
|
+
};
|
|
37
|
+
readonly feeSponsorSecretKey: string | undefined;
|
|
38
|
+
readonly feeBumpSecretKey: string | undefined;
|
|
39
|
+
};
|
|
40
|
+
readonly services: {
|
|
41
|
+
readonly research: string;
|
|
42
|
+
readonly market: string;
|
|
43
|
+
readonly stream: string;
|
|
44
|
+
};
|
|
45
|
+
readonly contracts: {
|
|
46
|
+
readonly policyContractId: string | undefined;
|
|
47
|
+
readonly sessionRegistryContractId: string | undefined;
|
|
48
|
+
};
|
|
49
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { config as loadEnv } from 'dotenv';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
const repoRoot = resolve(moduleDir, '../../../');
|
|
7
|
+
loadEnv({ path: resolve(repoRoot, '.env') });
|
|
8
|
+
loadEnv({ path: resolve(repoRoot, '.env.local'), override: true });
|
|
9
|
+
loadEnv();
|
|
10
|
+
const envSchema = z.object({
|
|
11
|
+
NODE_ENV: z.string().default('development'),
|
|
12
|
+
XMPP_NETWORK: z.string().default('stellar:testnet'),
|
|
13
|
+
XMPP_PAYMENT_EXECUTION_MODE: z.enum(['mock', 'testnet']).default('mock'),
|
|
14
|
+
XMPP_RPC_URL: z.string().default('https://soroban-testnet.stellar.org'),
|
|
15
|
+
XMPP_NETWORK_PASSPHRASE: z.string().default('Test SDF Network ; September 2015'),
|
|
16
|
+
XMPP_GATEWAY_PORT: z.coerce.number().default(4300),
|
|
17
|
+
XMPP_DASHBOARD_PORT: z.coerce.number().default(4310),
|
|
18
|
+
XMPP_DASHBOARD_GATEWAY_URL: z.string().optional(),
|
|
19
|
+
XMPP_DAILY_BUDGET_USD: z.coerce.number().default(0.5),
|
|
20
|
+
XMPP_AGENT_SECRET_KEY: z.string().optional(),
|
|
21
|
+
XMPP_SMART_ACCOUNT_CONTRACT_ID: z.string().optional(),
|
|
22
|
+
XMPP_SMART_ACCOUNT_WASM_HASH: z
|
|
23
|
+
.string()
|
|
24
|
+
.default('3e51f5b222dec74650f0b33367acb42a41ce497f72639230463070e666abba2c'),
|
|
25
|
+
XMPP_WEBAUTHN_VERIFIER_ADDRESS: z
|
|
26
|
+
.string()
|
|
27
|
+
.default('CATPTBRWVMH5ZCIKO5HN2F4FMPXVZEXC56RKGHRXCM7EEZGGXK7PICEH'),
|
|
28
|
+
XMPP_ED25519_VERIFIER_ADDRESS: z
|
|
29
|
+
.string()
|
|
30
|
+
.default('CAIKK32K3BZJYTWVTXHZFPIEEDBR6YCVTGPABH4UQUQ4XFA3OLYXG27G'),
|
|
31
|
+
XMPP_SPENDING_LIMIT_POLICY_ADDRESS: z
|
|
32
|
+
.string()
|
|
33
|
+
.default('CBYLPYZGLQ6JVY2IQ5P23QLQPR3KAMMKMZLNWG6RUUKJDNYGPLVHK7U4'),
|
|
34
|
+
XMPP_THRESHOLD_POLICY_ADDRESS: z
|
|
35
|
+
.string()
|
|
36
|
+
.default('CDDQLFG7CV74QHWPSP6NZIPNBR2PPCMTUVYCJF4P3ONDYHODRFGR7LWC'),
|
|
37
|
+
X402_FACILITATOR_URL: z.string().default('http://localhost:4022'),
|
|
38
|
+
X402_FACILITATOR_API_KEY: z.string().optional(),
|
|
39
|
+
X402_MAX_TRANSACTION_FEE_STROOPS: z.coerce.number().default(2000000),
|
|
40
|
+
X402_RECIPIENT_ADDRESS: z.string().optional(),
|
|
41
|
+
FACILITATOR_STELLAR_PRIVATE_KEY: z.string().optional(),
|
|
42
|
+
MPP_SECRET_KEY: z.string().optional(),
|
|
43
|
+
MPP_RECIPIENT_ADDRESS: z.string().optional(),
|
|
44
|
+
MPP_CHANNEL_CONTRACT_ID: z.string().optional(),
|
|
45
|
+
XMPP_ENABLE_MPP_FEE_SPONSORSHIP: z
|
|
46
|
+
.enum(['true', 'false'])
|
|
47
|
+
.default('false')
|
|
48
|
+
.transform((value) => value === 'true'),
|
|
49
|
+
XMPP_ENABLE_MPP_CHARGE_FEE_SPONSORSHIP: z
|
|
50
|
+
.enum(['true', 'false'])
|
|
51
|
+
.optional()
|
|
52
|
+
.transform((value) => value === 'true'),
|
|
53
|
+
XMPP_ENABLE_MPP_SESSION_FEE_SPONSORSHIP: z
|
|
54
|
+
.enum(['true', 'false'])
|
|
55
|
+
.optional()
|
|
56
|
+
.transform((value) => value === 'true'),
|
|
57
|
+
XMPP_MPP_FEE_SPONSOR_SECRET_KEY: z.string().optional(),
|
|
58
|
+
XMPP_MPP_FEE_BUMP_SECRET_KEY: z.string().optional(),
|
|
59
|
+
XMPP_RESEARCH_API_URL: z.string().default('http://localhost:4101'),
|
|
60
|
+
XMPP_MARKET_API_URL: z.string().default('http://localhost:4102'),
|
|
61
|
+
XMPP_STREAM_API_URL: z.string().default('http://localhost:4103'),
|
|
62
|
+
XMPP_POLICY_CONTRACT_ID: z.string().optional(),
|
|
63
|
+
XMPP_SESSION_REGISTRY_CONTRACT_ID: z.string().optional(),
|
|
64
|
+
});
|
|
65
|
+
const env = envSchema.parse(process.env);
|
|
66
|
+
const mppFeeSponsorshipEnabled = env.XMPP_ENABLE_MPP_FEE_SPONSORSHIP;
|
|
67
|
+
const mppChargeFeeSponsorshipEnabled = env.XMPP_ENABLE_MPP_CHARGE_FEE_SPONSORSHIP ?? mppFeeSponsorshipEnabled;
|
|
68
|
+
const mppSessionFeeSponsorshipEnabled = env.XMPP_ENABLE_MPP_SESSION_FEE_SPONSORSHIP ?? mppFeeSponsorshipEnabled;
|
|
69
|
+
export const config = {
|
|
70
|
+
nodeEnv: env.NODE_ENV,
|
|
71
|
+
network: env.XMPP_NETWORK,
|
|
72
|
+
paymentExecutionMode: env.XMPP_PAYMENT_EXECUTION_MODE,
|
|
73
|
+
rpcUrl: env.XMPP_RPC_URL,
|
|
74
|
+
networkPassphrase: env.XMPP_NETWORK_PASSPHRASE,
|
|
75
|
+
gatewayPort: env.XMPP_GATEWAY_PORT,
|
|
76
|
+
dashboardPort: env.XMPP_DASHBOARD_PORT,
|
|
77
|
+
dashboardGatewayUrl: env.XMPP_DASHBOARD_GATEWAY_URL,
|
|
78
|
+
dailyBudgetUsd: env.XMPP_DAILY_BUDGET_USD,
|
|
79
|
+
facilitatorUrl: env.X402_FACILITATOR_URL,
|
|
80
|
+
wallet: {
|
|
81
|
+
agentSecretKey: env.XMPP_AGENT_SECRET_KEY,
|
|
82
|
+
smartAccountContractId: env.XMPP_SMART_ACCOUNT_CONTRACT_ID,
|
|
83
|
+
smartAccountWasmHash: env.XMPP_SMART_ACCOUNT_WASM_HASH,
|
|
84
|
+
webauthnVerifierAddress: env.XMPP_WEBAUTHN_VERIFIER_ADDRESS,
|
|
85
|
+
ed25519VerifierAddress: env.XMPP_ED25519_VERIFIER_ADDRESS,
|
|
86
|
+
spendingLimitPolicyAddress: env.XMPP_SPENDING_LIMIT_POLICY_ADDRESS,
|
|
87
|
+
thresholdPolicyAddress: env.XMPP_THRESHOLD_POLICY_ADDRESS,
|
|
88
|
+
},
|
|
89
|
+
x402: {
|
|
90
|
+
facilitatorUrl: env.X402_FACILITATOR_URL,
|
|
91
|
+
facilitatorApiKey: env.X402_FACILITATOR_API_KEY,
|
|
92
|
+
maxTransactionFeeStroops: env.X402_MAX_TRANSACTION_FEE_STROOPS,
|
|
93
|
+
facilitatorPrivateKey: env.FACILITATOR_STELLAR_PRIVATE_KEY,
|
|
94
|
+
recipientAddress: env.X402_RECIPIENT_ADDRESS,
|
|
95
|
+
},
|
|
96
|
+
mpp: {
|
|
97
|
+
secretKey: env.MPP_SECRET_KEY,
|
|
98
|
+
recipientAddress: env.MPP_RECIPIENT_ADDRESS,
|
|
99
|
+
channelContractId: env.MPP_CHANNEL_CONTRACT_ID,
|
|
100
|
+
feeSponsorshipEnabled: mppFeeSponsorshipEnabled,
|
|
101
|
+
feeSponsorship: {
|
|
102
|
+
chargeEnabled: mppChargeFeeSponsorshipEnabled,
|
|
103
|
+
sessionEnabled: mppSessionFeeSponsorshipEnabled,
|
|
104
|
+
},
|
|
105
|
+
feeSponsorSecretKey: env.XMPP_MPP_FEE_SPONSOR_SECRET_KEY,
|
|
106
|
+
feeBumpSecretKey: env.XMPP_MPP_FEE_BUMP_SECRET_KEY,
|
|
107
|
+
},
|
|
108
|
+
services: {
|
|
109
|
+
research: env.XMPP_RESEARCH_API_URL,
|
|
110
|
+
market: env.XMPP_MARKET_API_URL,
|
|
111
|
+
stream: env.XMPP_STREAM_API_URL,
|
|
112
|
+
},
|
|
113
|
+
contracts: {
|
|
114
|
+
policyContractId: env.XMPP_POLICY_CONTRACT_ID,
|
|
115
|
+
sessionRegistryContractId: env.XMPP_SESSION_REGISTRY_CONTRACT_ID,
|
|
116
|
+
},
|
|
117
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { RouteKind, XmppAgentPolicySnapshot, XmppContractAgentTreasuryState, XmppContractTreasurySnapshot, XmppSessionRecord } from '@xmpp/types';
|
|
2
|
+
export type PolicyRuntimeSnapshot = {
|
|
3
|
+
source: 'local' | 'contract' | 'fallback';
|
|
4
|
+
pauseFlag: boolean;
|
|
5
|
+
globalPolicy: {
|
|
6
|
+
maxSpendUsdCents: number;
|
|
7
|
+
allowUnknownServices: boolean;
|
|
8
|
+
allowPostAutopay: boolean;
|
|
9
|
+
} | null;
|
|
10
|
+
servicePolicy: {
|
|
11
|
+
serviceId: string;
|
|
12
|
+
enabled: boolean;
|
|
13
|
+
maxSpendUsdCents: number;
|
|
14
|
+
preferredRoute: string;
|
|
15
|
+
allowSessionReuse: boolean;
|
|
16
|
+
} | null;
|
|
17
|
+
};
|
|
18
|
+
export type AgentPolicyRuntimeSnapshot = {
|
|
19
|
+
source: 'local' | 'contract' | 'fallback';
|
|
20
|
+
agentPolicy: XmppAgentPolicySnapshot | null;
|
|
21
|
+
};
|
|
22
|
+
export type SessionRouteEventInput = {
|
|
23
|
+
sessionId: string;
|
|
24
|
+
serviceId: string;
|
|
25
|
+
route: RouteKind;
|
|
26
|
+
status: 'open' | 'reused' | 'closed';
|
|
27
|
+
callCount: number;
|
|
28
|
+
receiptId: string;
|
|
29
|
+
totalAmountUsdCents?: number;
|
|
30
|
+
};
|
|
31
|
+
export declare function getAgentPolicySnapshot(agentId: string): Promise<AgentPolicyRuntimeSnapshot>;
|
|
32
|
+
export declare function listAgentPolicySnapshots(): Promise<XmppAgentPolicySnapshot[]>;
|
|
33
|
+
export declare function getTreasurySnapshot(): Promise<XmppContractTreasurySnapshot | null>;
|
|
34
|
+
export declare function getAgentTreasuryState(agentId: string): Promise<XmppContractAgentTreasuryState | null>;
|
|
35
|
+
export declare function listAgentTreasuryStates(): Promise<XmppContractAgentTreasuryState[]>;
|
|
36
|
+
export declare function getPolicyRuntimeSnapshot(serviceId?: string): Promise<PolicyRuntimeSnapshot>;
|
|
37
|
+
export declare function recordTreasurySpend(input: {
|
|
38
|
+
agentId: string;
|
|
39
|
+
serviceId: string;
|
|
40
|
+
route: RouteKind;
|
|
41
|
+
amountUsdCents: number;
|
|
42
|
+
}): Promise<XmppContractAgentTreasuryState | null>;
|
|
43
|
+
export declare function recordSessionRouteEvent(input: SessionRouteEventInput): Promise<XmppSessionRecord | null>;
|
|
44
|
+
export declare function listAgentSessions(): Promise<XmppSessionRecord[]>;
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { Keypair } from '@stellar/stellar-sdk';
|
|
2
|
+
import { Client, basicNodeSigner } from '@stellar/stellar-sdk/contract';
|
|
3
|
+
import { config } from '@xmpp/config';
|
|
4
|
+
import { logger } from '@xmpp/logger';
|
|
5
|
+
let policyClientPromise;
|
|
6
|
+
let sessionRegistryClientPromise;
|
|
7
|
+
let policyClientDisabled = false;
|
|
8
|
+
let sessionRegistryClientDisabled = false;
|
|
9
|
+
function contractRuntimeEnabled() {
|
|
10
|
+
return process.env.VITEST !== 'true' && process.env.XMPP_DISABLE_CONTRACT_RUNTIME !== 'true';
|
|
11
|
+
}
|
|
12
|
+
function toNumber(value) {
|
|
13
|
+
return value == null ? 0 : Number(value);
|
|
14
|
+
}
|
|
15
|
+
function normalizeStringList(value) {
|
|
16
|
+
if (Array.isArray(value)) {
|
|
17
|
+
return value.map((entry) => String(entry));
|
|
18
|
+
}
|
|
19
|
+
if (value && typeof value === 'object' && Symbol.iterator in value) {
|
|
20
|
+
return [...value].map((entry) => String(entry));
|
|
21
|
+
}
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
function getAgentKeypair() {
|
|
25
|
+
if (!config.wallet.agentSecretKey) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
return Keypair.fromSecret(config.wallet.agentSecretKey);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
logger.warn({ error }, '[xMPP] failed to parse agent secret key for contract runtime');
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function getClientOptions(contractId) {
|
|
37
|
+
const keypair = getAgentKeypair();
|
|
38
|
+
if (!keypair) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
contractId,
|
|
43
|
+
rpcUrl: config.rpcUrl,
|
|
44
|
+
networkPassphrase: config.networkPassphrase,
|
|
45
|
+
allowHttp: config.rpcUrl.startsWith('http://'),
|
|
46
|
+
publicKey: keypair.publicKey(),
|
|
47
|
+
...basicNodeSigner(keypair, config.networkPassphrase),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async function createClient(contractId, label) {
|
|
51
|
+
const options = getClientOptions(contractId);
|
|
52
|
+
if (!options) {
|
|
53
|
+
logger.debug({ label }, '[xMPP] contract runtime disabled because no agent signer is available');
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
return (await Client.from(options));
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
logger.warn({ error, contractId, label }, '[xMPP] failed to create Soroban contract client');
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function hasMethod(client, method, label) {
|
|
65
|
+
if (typeof client[method] === 'function') {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
logger.warn({ label, method }, '[xMPP] contract method is unavailable on deployed contract');
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
async function getPolicyClient() {
|
|
72
|
+
if (!contractRuntimeEnabled() || !config.contracts.policyContractId || policyClientDisabled) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
policyClientPromise ??= createClient(config.contracts.policyContractId, 'policy');
|
|
76
|
+
const client = await policyClientPromise;
|
|
77
|
+
if (!client) {
|
|
78
|
+
policyClientDisabled = true;
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
if (!hasMethod(client, 'get_global_policy', 'policy') || !hasMethod(client, 'pause_flag', 'policy')) {
|
|
82
|
+
policyClientDisabled = true;
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
return client;
|
|
86
|
+
}
|
|
87
|
+
async function getSessionRegistryClient() {
|
|
88
|
+
if (!contractRuntimeEnabled() ||
|
|
89
|
+
!config.contracts.sessionRegistryContractId ||
|
|
90
|
+
sessionRegistryClientDisabled) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
sessionRegistryClientPromise ??= createClient(config.contracts.sessionRegistryContractId, 'session-registry');
|
|
94
|
+
const client = await sessionRegistryClientPromise;
|
|
95
|
+
if (!client) {
|
|
96
|
+
sessionRegistryClientDisabled = true;
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
if (!hasMethod(client, 'upsert_session', 'session-registry')) {
|
|
100
|
+
sessionRegistryClientDisabled = true;
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
return client;
|
|
104
|
+
}
|
|
105
|
+
function normalizeGlobalPolicy(policy) {
|
|
106
|
+
return {
|
|
107
|
+
maxSpendUsdCents: toNumber(policy.max_spend_usd_cents),
|
|
108
|
+
allowUnknownServices: policy.allow_unknown_services,
|
|
109
|
+
allowPostAutopay: policy.allow_post_autopay,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function normalizeServicePolicy(policy) {
|
|
113
|
+
if (!policy) {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
serviceId: policy.service_id,
|
|
118
|
+
enabled: policy.enabled,
|
|
119
|
+
maxSpendUsdCents: toNumber(policy.max_spend_usd_cents),
|
|
120
|
+
preferredRoute: policy.preferred_route,
|
|
121
|
+
allowSessionReuse: policy.allow_session_reuse,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function normalizeAgentPolicy(policy) {
|
|
125
|
+
if (!policy) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
agentId: policy.agent_id,
|
|
130
|
+
enabled: policy.enabled,
|
|
131
|
+
dailyBudgetUsd: toNumber(policy.daily_budget_usd_cents) / 100,
|
|
132
|
+
allowedServices: normalizeStringList(policy.allowed_services),
|
|
133
|
+
preferredRoutes: normalizeStringList(policy.preferred_routes),
|
|
134
|
+
autopayMethods: normalizeStringList(policy.autopay_methods),
|
|
135
|
+
source: 'contract',
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function normalizeTreasurySnapshot(snapshot) {
|
|
139
|
+
if (!snapshot) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
const sharedTreasuryUsd = toNumber(snapshot.shared_treasury_usd_cents) / 100;
|
|
143
|
+
const totalSpentUsd = toNumber(snapshot.total_spent_usd_cents) / 100;
|
|
144
|
+
return {
|
|
145
|
+
sharedTreasuryUsd,
|
|
146
|
+
totalSpentUsd,
|
|
147
|
+
remainingUsd: Math.max(0, sharedTreasuryUsd - totalSpentUsd),
|
|
148
|
+
paymentCount: Number(snapshot.payment_count ?? 0),
|
|
149
|
+
source: 'contract',
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function normalizeAgentTreasuryState(state) {
|
|
153
|
+
if (!state) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
agentId: state.agent_id,
|
|
158
|
+
spentUsd: toNumber(state.spent_usd_cents) / 100,
|
|
159
|
+
paymentCount: Number(state.payment_count ?? 0),
|
|
160
|
+
lastServiceId: state.last_service_id,
|
|
161
|
+
lastRoute: state.last_route,
|
|
162
|
+
source: 'contract',
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function normalizeSessionRecord(record) {
|
|
166
|
+
return {
|
|
167
|
+
sessionId: String(record.session_id ?? ''),
|
|
168
|
+
serviceId: String(record.service_id ?? ''),
|
|
169
|
+
agent: String(record.agent ?? ''),
|
|
170
|
+
channelContractId: String(record.channel_contract_id ?? ''),
|
|
171
|
+
route: String(record.route ?? ''),
|
|
172
|
+
status: String(record.status ?? ''),
|
|
173
|
+
totalAmountUsdCents: toNumber(record.total_amount_usd_cents),
|
|
174
|
+
callCount: Number(record.call_count ?? 0),
|
|
175
|
+
lastReceiptId: String(record.last_receipt_id ?? ''),
|
|
176
|
+
updatedAtLedger: Number(record.updated_at_ledger ?? 0),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
export async function getAgentPolicySnapshot(agentId) {
|
|
180
|
+
const client = await getPolicyClient();
|
|
181
|
+
if (!client || !hasMethod(client, 'get_agent_policy', 'policy')) {
|
|
182
|
+
return {
|
|
183
|
+
source: 'local',
|
|
184
|
+
agentPolicy: null,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
const tx = await client.get_agent_policy({ agent_id: agentId });
|
|
189
|
+
return {
|
|
190
|
+
source: 'contract',
|
|
191
|
+
agentPolicy: normalizeAgentPolicy(tx.result ?? null),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
logger.warn({ error, agentId }, '[xMPP] failed to read agent policy from contract, falling back');
|
|
196
|
+
return {
|
|
197
|
+
source: 'fallback',
|
|
198
|
+
agentPolicy: null,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
export async function listAgentPolicySnapshots() {
|
|
203
|
+
const client = await getPolicyClient();
|
|
204
|
+
if (!client || !hasMethod(client, 'list_agent_policies', 'policy')) {
|
|
205
|
+
return [];
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
const tx = await client.list_agent_policies();
|
|
209
|
+
const result = tx.result;
|
|
210
|
+
return Array.isArray(result)
|
|
211
|
+
? result.filter((entry) => Boolean(entry)).flatMap((entry) => {
|
|
212
|
+
const normalized = normalizeAgentPolicy(entry);
|
|
213
|
+
return normalized ? [normalized] : [];
|
|
214
|
+
})
|
|
215
|
+
: [];
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
logger.warn({ error }, '[xMPP] failed to list agent policies from contract');
|
|
219
|
+
return [];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
export async function getTreasurySnapshot() {
|
|
223
|
+
const client = await getPolicyClient();
|
|
224
|
+
if (!client || !hasMethod(client, 'get_treasury_snapshot', 'policy')) {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
const tx = await client.get_treasury_snapshot();
|
|
229
|
+
return normalizeTreasurySnapshot(tx.result ?? null);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
logger.warn({ error }, '[xMPP] failed to read treasury snapshot from contract');
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
export async function getAgentTreasuryState(agentId) {
|
|
237
|
+
const client = await getPolicyClient();
|
|
238
|
+
if (!client || !hasMethod(client, 'get_agent_treasury_state', 'policy')) {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
try {
|
|
242
|
+
const tx = await client.get_agent_treasury_state({ agent_id: agentId });
|
|
243
|
+
return normalizeAgentTreasuryState(tx.result ?? null);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
logger.warn({ error, agentId }, '[xMPP] failed to read agent treasury state from contract');
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
export async function listAgentTreasuryStates() {
|
|
251
|
+
const client = await getPolicyClient();
|
|
252
|
+
if (!client || !hasMethod(client, 'list_agent_treasury_states', 'policy')) {
|
|
253
|
+
return [];
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const tx = await client.list_agent_treasury_states();
|
|
257
|
+
const result = tx.result;
|
|
258
|
+
return Array.isArray(result)
|
|
259
|
+
? result.flatMap((entry) => {
|
|
260
|
+
const normalized = normalizeAgentTreasuryState(entry);
|
|
261
|
+
return normalized ? [normalized] : [];
|
|
262
|
+
})
|
|
263
|
+
: [];
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
logger.warn({ error }, '[xMPP] failed to list agent treasury states from contract');
|
|
267
|
+
return [];
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
export async function getPolicyRuntimeSnapshot(serviceId) {
|
|
271
|
+
const client = await getPolicyClient();
|
|
272
|
+
if (!client) {
|
|
273
|
+
return {
|
|
274
|
+
source: 'local',
|
|
275
|
+
pauseFlag: false,
|
|
276
|
+
globalPolicy: null,
|
|
277
|
+
servicePolicy: null,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
const globalPolicyTx = await client.get_global_policy();
|
|
282
|
+
const pauseFlagTx = await client.pause_flag();
|
|
283
|
+
const servicePolicyTx = serviceId && hasMethod(client, 'get_service_policy', 'policy')
|
|
284
|
+
? await client.get_service_policy({ service_id: serviceId })
|
|
285
|
+
: null;
|
|
286
|
+
return {
|
|
287
|
+
source: 'contract',
|
|
288
|
+
pauseFlag: Boolean(pauseFlagTx.result),
|
|
289
|
+
globalPolicy: normalizeGlobalPolicy(globalPolicyTx.result),
|
|
290
|
+
servicePolicy: normalizeServicePolicy(servicePolicyTx?.result ?? null),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
logger.warn({ error, serviceId }, '[xMPP] failed to read policy from contract, falling back');
|
|
295
|
+
return {
|
|
296
|
+
source: 'fallback',
|
|
297
|
+
pauseFlag: false,
|
|
298
|
+
globalPolicy: null,
|
|
299
|
+
servicePolicy: null,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
export async function recordTreasurySpend(input) {
|
|
304
|
+
const client = await getPolicyClient();
|
|
305
|
+
if (!client || !hasMethod(client, 'record_treasury_spend', 'policy')) {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
try {
|
|
309
|
+
const tx = await client.record_treasury_spend({
|
|
310
|
+
agent_id: input.agentId,
|
|
311
|
+
service_id: input.serviceId,
|
|
312
|
+
route: input.route,
|
|
313
|
+
amount_usd_cents: BigInt(input.amountUsdCents),
|
|
314
|
+
});
|
|
315
|
+
const sent = await tx.signAndSend();
|
|
316
|
+
return normalizeAgentTreasuryState(sent.result);
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
logger.warn({ error, input }, '[xMPP] failed to record treasury spend in contract');
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
export async function recordSessionRouteEvent(input) {
|
|
324
|
+
const client = await getSessionRegistryClient();
|
|
325
|
+
const keypair = getAgentKeypair();
|
|
326
|
+
if (!client || !keypair) {
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
const tx = await client.upsert_session({
|
|
331
|
+
agent: keypair.publicKey(),
|
|
332
|
+
session_id: input.sessionId,
|
|
333
|
+
service_id: input.serviceId,
|
|
334
|
+
channel_contract_id: config.mpp.channelContractId ?? '',
|
|
335
|
+
route: input.route,
|
|
336
|
+
total_amount_usd_cents: BigInt(input.totalAmountUsdCents ?? 0),
|
|
337
|
+
call_count: input.callCount,
|
|
338
|
+
last_receipt_id: input.receiptId,
|
|
339
|
+
status: input.status,
|
|
340
|
+
});
|
|
341
|
+
const sent = await tx.signAndSend();
|
|
342
|
+
return normalizeSessionRecord(sent.result);
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
logger.warn({ error, input }, '[xMPP] failed to write session route event to contract');
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
export async function listAgentSessions() {
|
|
350
|
+
const client = await getSessionRegistryClient();
|
|
351
|
+
const keypair = getAgentKeypair();
|
|
352
|
+
if (!client || !keypair || !hasMethod(client, 'list_agent_sessions', 'session-registry')) {
|
|
353
|
+
return [];
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
const tx = await client.list_agent_sessions({ agent: keypair.publicKey() });
|
|
357
|
+
const result = tx.result;
|
|
358
|
+
return Array.isArray(result) ? result.map(normalizeSessionRecord) : [];
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
logger.warn({ error }, '[xMPP] failed to list agent sessions from contract');
|
|
362
|
+
return [];
|
|
363
|
+
}
|
|
364
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import pino from 'pino';
|
|
2
|
+
export const logger = pino({
|
|
3
|
+
name: 'xmpp',
|
|
4
|
+
level: process.env.LOG_LEVEL ?? 'info',
|
|
5
|
+
redact: {
|
|
6
|
+
paths: [
|
|
7
|
+
'req.headers.authorization',
|
|
8
|
+
'req.headers.x-api-key',
|
|
9
|
+
'req.headers.cookie',
|
|
10
|
+
'req.body.headers.authorization',
|
|
11
|
+
'req.body.headers.x-api-key',
|
|
12
|
+
'req.body.options.idempotencyKey',
|
|
13
|
+
'err.config.headers.authorization',
|
|
14
|
+
'err.config.headers.x-api-key',
|
|
15
|
+
],
|
|
16
|
+
censor: '[REDACTED]',
|
|
17
|
+
},
|
|
18
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PolicyDecision } from '@xmpp/types';
|
|
2
|
+
export declare function isAllowedDomain(url: string): boolean;
|
|
3
|
+
export declare function evaluatePolicy(url: string): PolicyDecision;
|
|
4
|
+
export declare function evaluatePolicyForRequest(input: {
|
|
5
|
+
url: string;
|
|
6
|
+
method?: string;
|
|
7
|
+
serviceId?: string;
|
|
8
|
+
}): Promise<PolicyDecision>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { getPolicyRuntimeSnapshot } from '@xmpp/contract-runtime';
|
|
2
|
+
const allowedHosts = new Set(['localhost', '127.0.0.1']);
|
|
3
|
+
const blockedPathPrefixes = ['/admin', '/internal', '/unsafe'];
|
|
4
|
+
export function isAllowedDomain(url) {
|
|
5
|
+
const parsed = new URL(url);
|
|
6
|
+
return allowedHosts.has(parsed.hostname);
|
|
7
|
+
}
|
|
8
|
+
export function evaluatePolicy(url) {
|
|
9
|
+
const parsed = new URL(url);
|
|
10
|
+
if (!allowedHosts.has(parsed.hostname)) {
|
|
11
|
+
return {
|
|
12
|
+
allowed: false,
|
|
13
|
+
reason: 'xMPP policy allows automatic payment only to approved local demo hosts.',
|
|
14
|
+
code: 'blocked-domain',
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
if (blockedPathPrefixes.some((prefix) => parsed.pathname.startsWith(prefix))) {
|
|
18
|
+
return {
|
|
19
|
+
allowed: false,
|
|
20
|
+
reason: 'xMPP policy blocks sensitive admin or unsafe routes from automatic payment.',
|
|
21
|
+
code: 'blocked-path',
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
return {
|
|
25
|
+
allowed: true,
|
|
26
|
+
reason: 'xMPP policy approved this request for automatic payment routing.',
|
|
27
|
+
code: 'allowed',
|
|
28
|
+
source: 'local',
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export async function evaluatePolicyForRequest(input) {
|
|
32
|
+
const localDecision = evaluatePolicy(input.url);
|
|
33
|
+
if (!localDecision.allowed) {
|
|
34
|
+
return localDecision;
|
|
35
|
+
}
|
|
36
|
+
const runtime = await getPolicyRuntimeSnapshot(input.serviceId);
|
|
37
|
+
if (runtime.pauseFlag) {
|
|
38
|
+
return {
|
|
39
|
+
allowed: false,
|
|
40
|
+
reason: 'xMPP policy contract is paused for automatic payment execution.',
|
|
41
|
+
code: 'paused',
|
|
42
|
+
source: runtime.source,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const method = (input.method ?? 'GET').toUpperCase();
|
|
46
|
+
if (method !== 'GET' && input.serviceId == null) {
|
|
47
|
+
return {
|
|
48
|
+
allowed: false,
|
|
49
|
+
reason: 'xMPP requires an explicit service id before automatic payment can proceed on non-GET requests.',
|
|
50
|
+
code: 'blocked-service',
|
|
51
|
+
source: runtime.source,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
if (method !== 'GET' && runtime.globalPolicy == null) {
|
|
55
|
+
return {
|
|
56
|
+
allowed: false,
|
|
57
|
+
reason: 'xMPP blocks automatic payment on non-GET routes unless policy explicitly enables it.',
|
|
58
|
+
code: 'blocked-method',
|
|
59
|
+
source: runtime.source,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
if (method !== 'GET' && runtime.globalPolicy && !runtime.globalPolicy.allowPostAutopay) {
|
|
63
|
+
return {
|
|
64
|
+
allowed: false,
|
|
65
|
+
reason: 'xMPP policy blocks automatic payment on non-GET routes unless explicitly enabled.',
|
|
66
|
+
code: 'blocked-method',
|
|
67
|
+
source: runtime.source,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (input.serviceId == null && runtime.globalPolicy && !runtime.globalPolicy.allowUnknownServices) {
|
|
71
|
+
return {
|
|
72
|
+
allowed: false,
|
|
73
|
+
reason: 'xMPP policy requires a known service id before automatic payment can proceed.',
|
|
74
|
+
code: 'blocked-service',
|
|
75
|
+
source: runtime.source,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
if (runtime.servicePolicy && !runtime.servicePolicy.enabled) {
|
|
79
|
+
return {
|
|
80
|
+
allowed: false,
|
|
81
|
+
reason: 'xMPP service policy disabled automatic payment for this service.',
|
|
82
|
+
code: 'blocked-service',
|
|
83
|
+
source: runtime.source,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
...localDecision,
|
|
88
|
+
source: runtime.source,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { evaluatePolicy, isAllowedDomain } from './index.js';
|
|
3
|
+
describe('policy engine', () => {
|
|
4
|
+
it('allows local demo services', () => {
|
|
5
|
+
expect(isAllowedDomain('http://localhost:4101/research?q=stellar')).toBe(true);
|
|
6
|
+
expect(evaluatePolicy('http://localhost:4101/research?q=stellar')).toMatchObject({ allowed: true, code: 'allowed' });
|
|
7
|
+
});
|
|
8
|
+
it('blocks non-local domains', () => {
|
|
9
|
+
expect(isAllowedDomain('https://example.com/paid')).toBe(false);
|
|
10
|
+
expect(evaluatePolicy('https://example.com/paid')).toMatchObject({
|
|
11
|
+
allowed: false,
|
|
12
|
+
code: 'blocked-domain',
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
it('blocks unsafe local admin routes', () => {
|
|
16
|
+
expect(evaluatePolicy('http://localhost:4102/admin/export')).toMatchObject({
|
|
17
|
+
allowed: false,
|
|
18
|
+
code: 'blocked-path',
|
|
19
|
+
});
|
|
20
|
+
});
|
|
21
|
+
});
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
export type RouteKind = 'x402' | 'mpp-charge' | 'mpp-session-open' | 'mpp-session-reuse';
|
|
2
|
+
export type PaymentExecutionMode = 'mock' | 'testnet';
|
|
3
|
+
export type PaymentExecutionStatus = 'mock-paid' | 'ready-for-testnet' | 'settled-testnet' | 'missing-config';
|
|
4
|
+
export type RouteContext = {
|
|
5
|
+
url: string;
|
|
6
|
+
method: string;
|
|
7
|
+
serviceId?: string;
|
|
8
|
+
projectedRequests?: number;
|
|
9
|
+
streaming?: boolean;
|
|
10
|
+
};
|
|
11
|
+
export type ServiceCatalogEntry = {
|
|
12
|
+
serviceId: string;
|
|
13
|
+
displayName: string;
|
|
14
|
+
description: string;
|
|
15
|
+
baseUrl: string;
|
|
16
|
+
source?: 'static' | 'discovered' | 'hybrid' | 'fallback';
|
|
17
|
+
capabilities: {
|
|
18
|
+
x402: boolean;
|
|
19
|
+
mppCharge: boolean;
|
|
20
|
+
mppSession: boolean;
|
|
21
|
+
};
|
|
22
|
+
pricing: {
|
|
23
|
+
x402PerCallUsd: number;
|
|
24
|
+
mppChargePerCallUsd: number;
|
|
25
|
+
mppSessionOpenUsd: number;
|
|
26
|
+
mppSessionPerCallUsd: number;
|
|
27
|
+
};
|
|
28
|
+
routingHints: {
|
|
29
|
+
breakEvenCalls: number;
|
|
30
|
+
streamingPreferred: boolean;
|
|
31
|
+
preferredSingleCall: Extract<RouteKind, 'x402' | 'mpp-charge'>;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
export type RouteScoreBreakdown = {
|
|
35
|
+
route: RouteKind;
|
|
36
|
+
supported: boolean;
|
|
37
|
+
estimatedTotalUsd: number;
|
|
38
|
+
savingsVsNaiveUsd: number;
|
|
39
|
+
totalScore: number;
|
|
40
|
+
reasons: string[];
|
|
41
|
+
};
|
|
42
|
+
export type RouteDecision = {
|
|
43
|
+
route: RouteKind;
|
|
44
|
+
reason: string;
|
|
45
|
+
score: number;
|
|
46
|
+
projectedRequests?: number;
|
|
47
|
+
estimatedTotalUsd?: number;
|
|
48
|
+
savingsVsNaiveUsd?: number;
|
|
49
|
+
service?: ServiceCatalogEntry;
|
|
50
|
+
breakdown?: RouteScoreBreakdown[];
|
|
51
|
+
};
|
|
52
|
+
export type ChallengeKind = 'x402' | 'mpp-charge' | 'mpp-session';
|
|
53
|
+
export type PaymentChallenge = {
|
|
54
|
+
kind: ChallengeKind;
|
|
55
|
+
service: string;
|
|
56
|
+
amountUsd: number;
|
|
57
|
+
asset: 'USDC_TESTNET';
|
|
58
|
+
retryHeaderName: string;
|
|
59
|
+
retryHeaderValue: string;
|
|
60
|
+
sessionId?: string;
|
|
61
|
+
};
|
|
62
|
+
export type XmppFetchOptions = Omit<RouteContext, 'url' | 'method'> & {
|
|
63
|
+
agentId?: string;
|
|
64
|
+
maxAutoPayUsd?: number;
|
|
65
|
+
idempotencyKey?: string;
|
|
66
|
+
};
|
|
67
|
+
export type XmppAgentProfile = {
|
|
68
|
+
agentId: string;
|
|
69
|
+
displayName: string;
|
|
70
|
+
role: 'shared' | 'research' | 'market';
|
|
71
|
+
description: string;
|
|
72
|
+
dailyBudgetUsd: number;
|
|
73
|
+
allowedServices: string[];
|
|
74
|
+
preferredRoutes: RouteKind[];
|
|
75
|
+
autopayMethods: string[];
|
|
76
|
+
enabled?: boolean;
|
|
77
|
+
policySource?: 'local' | 'contract' | 'fallback' | 'merged';
|
|
78
|
+
};
|
|
79
|
+
export type XmppSignedReceipt = {
|
|
80
|
+
receiptId: string;
|
|
81
|
+
issuedAt: string;
|
|
82
|
+
network: string;
|
|
83
|
+
agent: string;
|
|
84
|
+
serviceId: string;
|
|
85
|
+
url: string;
|
|
86
|
+
method: string;
|
|
87
|
+
route: RouteKind;
|
|
88
|
+
amountUsd: number;
|
|
89
|
+
txHash?: string;
|
|
90
|
+
explorerUrl?: string;
|
|
91
|
+
paymentReference?: string;
|
|
92
|
+
signature: string;
|
|
93
|
+
};
|
|
94
|
+
export type XmppSmartAccountExecution = {
|
|
95
|
+
configured: boolean;
|
|
96
|
+
preferred: boolean;
|
|
97
|
+
supported: boolean;
|
|
98
|
+
used: boolean;
|
|
99
|
+
contractId?: string | null;
|
|
100
|
+
fallbackReason?: string;
|
|
101
|
+
};
|
|
102
|
+
export type PaymentExecutionMetadata = {
|
|
103
|
+
mode: PaymentExecutionMode;
|
|
104
|
+
status: PaymentExecutionStatus;
|
|
105
|
+
route: RouteKind;
|
|
106
|
+
receiptId: string;
|
|
107
|
+
missingConfig?: string[];
|
|
108
|
+
evidenceHeaders?: Record<string, string>;
|
|
109
|
+
signedReceipt?: XmppSignedReceipt;
|
|
110
|
+
settlementStrategy?: 'keypair' | 'smart-account' | 'keypair-fallback';
|
|
111
|
+
executionNote?: string;
|
|
112
|
+
feeSponsored?: boolean;
|
|
113
|
+
feeSponsorPublicKey?: string;
|
|
114
|
+
feeBumpPublicKey?: string;
|
|
115
|
+
smartAccount?: XmppSmartAccountExecution;
|
|
116
|
+
};
|
|
117
|
+
export type PolicyDecision = {
|
|
118
|
+
allowed: boolean;
|
|
119
|
+
reason: string;
|
|
120
|
+
code: 'allowed' | 'blocked-domain' | 'blocked-path' | 'blocked-method' | 'blocked-service' | 'blocked-agent' | 'blocked-budget' | 'blocked-idempotency' | 'paused';
|
|
121
|
+
source?: 'local' | 'contract' | 'fallback';
|
|
122
|
+
};
|
|
123
|
+
export type PaymentExecutionResult = {
|
|
124
|
+
response: Response;
|
|
125
|
+
metadata: PaymentExecutionMetadata;
|
|
126
|
+
};
|
|
127
|
+
export type XmppFetchMetadata = {
|
|
128
|
+
route: RouteKind;
|
|
129
|
+
challenge?: PaymentChallenge;
|
|
130
|
+
retried: boolean;
|
|
131
|
+
execution?: PaymentExecutionMetadata;
|
|
132
|
+
policy?: PolicyDecision;
|
|
133
|
+
budget?: XmppBudgetSnapshot;
|
|
134
|
+
idempotentReplay?: boolean;
|
|
135
|
+
};
|
|
136
|
+
export type XmppSessionRecord = {
|
|
137
|
+
sessionId: string;
|
|
138
|
+
serviceId: string;
|
|
139
|
+
agent: string;
|
|
140
|
+
channelContractId: string;
|
|
141
|
+
route: string;
|
|
142
|
+
status: string;
|
|
143
|
+
totalAmountUsdCents: number;
|
|
144
|
+
callCount: number;
|
|
145
|
+
lastReceiptId: string;
|
|
146
|
+
updatedAtLedger: number;
|
|
147
|
+
};
|
|
148
|
+
export type WorkflowEstimateStep = {
|
|
149
|
+
url: string;
|
|
150
|
+
method?: string;
|
|
151
|
+
serviceId?: string;
|
|
152
|
+
projectedRequests: number;
|
|
153
|
+
streaming?: boolean;
|
|
154
|
+
};
|
|
155
|
+
export type WorkflowEstimateLineItem = {
|
|
156
|
+
serviceId: string;
|
|
157
|
+
displayName: string;
|
|
158
|
+
route: RouteKind;
|
|
159
|
+
projectedRequests: number;
|
|
160
|
+
estimatedCostUsd: number;
|
|
161
|
+
savingsVsNaiveUsd: number;
|
|
162
|
+
reason: string;
|
|
163
|
+
};
|
|
164
|
+
export type WorkflowEstimateResult = {
|
|
165
|
+
totalEstimatedCostUsd: number;
|
|
166
|
+
naiveX402CostUsd: number;
|
|
167
|
+
savingsVsNaiveUsd: number;
|
|
168
|
+
breakdown: WorkflowEstimateLineItem[];
|
|
169
|
+
};
|
|
170
|
+
export type XmppBudgetSnapshot = {
|
|
171
|
+
agentId: string;
|
|
172
|
+
agentDisplayName: string;
|
|
173
|
+
agentSpentThisSessionUsd: number;
|
|
174
|
+
agentRemainingDailyBudgetUsd: number;
|
|
175
|
+
spentThisSessionUsd: number;
|
|
176
|
+
remainingDailyBudgetUsd: number;
|
|
177
|
+
callsThisService: number;
|
|
178
|
+
projectedCostIfRepeated5xUsd: number;
|
|
179
|
+
recommendation: string;
|
|
180
|
+
};
|
|
181
|
+
export type XmppRouteEvent = {
|
|
182
|
+
id: string;
|
|
183
|
+
timestamp: string;
|
|
184
|
+
agentId: string;
|
|
185
|
+
url: string;
|
|
186
|
+
method: string;
|
|
187
|
+
serviceId: string;
|
|
188
|
+
route: RouteKind;
|
|
189
|
+
status: 'settled' | 'denied' | 'preview';
|
|
190
|
+
amountUsd: number;
|
|
191
|
+
projectedRequests: number;
|
|
192
|
+
policyCode?: PolicyDecision['code'];
|
|
193
|
+
receiptId?: string;
|
|
194
|
+
txHash?: string;
|
|
195
|
+
explorerUrl?: string;
|
|
196
|
+
sessionId?: string;
|
|
197
|
+
signedReceipt?: XmppSignedReceipt;
|
|
198
|
+
feeSponsored?: boolean;
|
|
199
|
+
feeSponsorPublicKey?: string;
|
|
200
|
+
settlementStrategy?: PaymentExecutionMetadata['settlementStrategy'];
|
|
201
|
+
executionNote?: string;
|
|
202
|
+
};
|
|
203
|
+
export type XmppAgentStateSummary = {
|
|
204
|
+
agentId: string;
|
|
205
|
+
displayName: string;
|
|
206
|
+
role: XmppAgentProfile['role'];
|
|
207
|
+
description: string;
|
|
208
|
+
dailyBudgetUsd: number;
|
|
209
|
+
spentThisSessionUsd: number;
|
|
210
|
+
remainingDailyBudgetUsd: number;
|
|
211
|
+
routeCounts: Record<RouteKind, number>;
|
|
212
|
+
allowedServices: string[];
|
|
213
|
+
preferredRoutes: RouteKind[];
|
|
214
|
+
enabled?: boolean;
|
|
215
|
+
policySource?: XmppAgentProfile['policySource'];
|
|
216
|
+
autopayMethods?: string[];
|
|
217
|
+
};
|
|
218
|
+
export type XmppAgentPolicySnapshot = {
|
|
219
|
+
agentId: string;
|
|
220
|
+
enabled: boolean;
|
|
221
|
+
dailyBudgetUsd: number;
|
|
222
|
+
allowedServices: string[];
|
|
223
|
+
preferredRoutes: RouteKind[];
|
|
224
|
+
autopayMethods: string[];
|
|
225
|
+
source: 'contract' | 'local' | 'fallback';
|
|
226
|
+
};
|
|
227
|
+
export type XmppContractTreasurySnapshot = {
|
|
228
|
+
sharedTreasuryUsd: number;
|
|
229
|
+
totalSpentUsd: number;
|
|
230
|
+
remainingUsd: number;
|
|
231
|
+
paymentCount: number;
|
|
232
|
+
source: 'contract' | 'local' | 'fallback';
|
|
233
|
+
};
|
|
234
|
+
export type XmppContractAgentTreasuryState = {
|
|
235
|
+
agentId: string;
|
|
236
|
+
spentUsd: number;
|
|
237
|
+
paymentCount: number;
|
|
238
|
+
lastServiceId: string;
|
|
239
|
+
lastRoute: string;
|
|
240
|
+
source: 'contract' | 'local' | 'fallback';
|
|
241
|
+
};
|
|
242
|
+
export type XmppOperatorState = {
|
|
243
|
+
sharedTreasuryUsd: number;
|
|
244
|
+
sharedTreasuryRemainingUsd: number;
|
|
245
|
+
dailyBudgetUsd: number;
|
|
246
|
+
spentThisSessionUsd: number;
|
|
247
|
+
remainingDailyBudgetUsd: number;
|
|
248
|
+
sessionSavingsUsd: number;
|
|
249
|
+
routeCounts: Record<RouteKind, number>;
|
|
250
|
+
serviceSpendUsd: Record<string, number>;
|
|
251
|
+
serviceCallCounts: Record<string, number>;
|
|
252
|
+
agentProfiles: XmppAgentProfile[];
|
|
253
|
+
agentStates: XmppAgentStateSummary[];
|
|
254
|
+
contractAgentPolicies?: XmppAgentPolicySnapshot[];
|
|
255
|
+
contractTreasury?: XmppContractTreasurySnapshot | null;
|
|
256
|
+
contractAgentTreasuryStates?: XmppContractAgentTreasuryState[];
|
|
257
|
+
openSessions: Array<Pick<XmppSessionRecord, 'sessionId' | 'serviceId' | 'callCount'>>;
|
|
258
|
+
recentEvents: XmppRouteEvent[];
|
|
259
|
+
};
|
|
260
|
+
export type XmppReceiptVerificationResult = {
|
|
261
|
+
valid: boolean;
|
|
262
|
+
agent: string;
|
|
263
|
+
receiptId: string;
|
|
264
|
+
};
|
|
265
|
+
export type XmppWalletInfo = {
|
|
266
|
+
connected: boolean;
|
|
267
|
+
paymentExecutionMode: PaymentExecutionMode;
|
|
268
|
+
network: string;
|
|
269
|
+
rpcUrl: string;
|
|
270
|
+
agentPublicKey: string | null;
|
|
271
|
+
settlementStrategy: 'smart-account-ready' | 'smart-account-x402-preferred' | 'smart-account-partial-fallback' | 'keypair-live';
|
|
272
|
+
smartAccount: {
|
|
273
|
+
ready: boolean;
|
|
274
|
+
mode: 'inactive' | 'x402-only' | 'full';
|
|
275
|
+
routeCoverage: 'inactive' | 'x402-only';
|
|
276
|
+
demoReady: boolean;
|
|
277
|
+
guardedFallback: boolean;
|
|
278
|
+
contractId: string | null;
|
|
279
|
+
wasmHash: string;
|
|
280
|
+
webauthnVerifierAddress: string;
|
|
281
|
+
ed25519VerifierAddress: string;
|
|
282
|
+
spendingLimitPolicyAddress: string;
|
|
283
|
+
thresholdPolicyAddress: string;
|
|
284
|
+
preferredRoutes: RouteKind[];
|
|
285
|
+
fallbackRoutes: RouteKind[];
|
|
286
|
+
supportedRoutes: RouteKind[];
|
|
287
|
+
unsupportedRoutes: RouteKind[];
|
|
288
|
+
unsupportedReason: string | null;
|
|
289
|
+
configuredMaxTransactionFeeStroops: number;
|
|
290
|
+
effectiveMaxTransactionFeeStroops: number;
|
|
291
|
+
feeFloorApplied: boolean;
|
|
292
|
+
preflightFailures: string[];
|
|
293
|
+
coverageMessage: string;
|
|
294
|
+
message: string;
|
|
295
|
+
operatorNotes: string[];
|
|
296
|
+
};
|
|
297
|
+
feeSponsorship: {
|
|
298
|
+
enabled: boolean;
|
|
299
|
+
available: boolean;
|
|
300
|
+
mppChargeEnabled: boolean;
|
|
301
|
+
mppSessionEnabled: boolean;
|
|
302
|
+
sponsorPublicKey: string | null;
|
|
303
|
+
feeBumpPublicKey: string | null;
|
|
304
|
+
message: string;
|
|
305
|
+
};
|
|
306
|
+
missingSecrets: string[];
|
|
307
|
+
message: string;
|
|
308
|
+
};
|
|
309
|
+
export type XmppHealthStatus = {
|
|
310
|
+
ok: boolean;
|
|
311
|
+
service: string;
|
|
312
|
+
network: string;
|
|
313
|
+
paymentExecutionMode: PaymentExecutionMode;
|
|
314
|
+
services: Record<string, string>;
|
|
315
|
+
smartAccount: {
|
|
316
|
+
configured: boolean;
|
|
317
|
+
routeCoverage: 'inactive' | 'x402-only';
|
|
318
|
+
x402Preferred: boolean;
|
|
319
|
+
mppFallback: boolean;
|
|
320
|
+
demoReady: boolean;
|
|
321
|
+
guardedFallback: boolean;
|
|
322
|
+
unsupportedRoutes: RouteKind[];
|
|
323
|
+
unsupportedReason: string | null;
|
|
324
|
+
configuredMaxTransactionFeeStroops: number;
|
|
325
|
+
effectiveMaxTransactionFeeStroops: number;
|
|
326
|
+
feeFloorApplied: boolean;
|
|
327
|
+
preflightFailures: string[];
|
|
328
|
+
};
|
|
329
|
+
};
|
|
330
|
+
export type XmppCatalogResponse = {
|
|
331
|
+
services: ServiceCatalogEntry[];
|
|
332
|
+
};
|
|
333
|
+
export type XmppPolicyPreviewResponse = {
|
|
334
|
+
policy: PolicyDecision;
|
|
335
|
+
routePreview: RouteDecision;
|
|
336
|
+
};
|
|
337
|
+
export type XmppGatewayFetchResponse = {
|
|
338
|
+
status: number;
|
|
339
|
+
routePreview: RouteDecision;
|
|
340
|
+
payment?: XmppFetchMetadata;
|
|
341
|
+
responseHeaders: Record<string, string>;
|
|
342
|
+
body: unknown;
|
|
343
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@vinaystwt/xmpp-policy-engine",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Service, budget, agent, and contract-aware policy evaluation for xMPP.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "dist/policy-engine/src/index.js",
|
|
8
|
+
"types": "dist/policy-engine/src/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"LICENSE"
|
|
12
|
+
],
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"homepage": "https://github.com/Vinaystwt/xMPP#readme",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/Vinaystwt/xMPP.git",
|
|
18
|
+
"directory": "packages/policy-engine"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/Vinaystwt/xMPP/issues"
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"xmpp",
|
|
25
|
+
"policy",
|
|
26
|
+
"stellar",
|
|
27
|
+
"agents"
|
|
28
|
+
],
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/policy-engine/src/index.d.ts",
|
|
32
|
+
"import": "./dist/policy-engine/src/index.js",
|
|
33
|
+
"default": "./dist/policy-engine/src/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -p tsconfig.json",
|
|
41
|
+
"dev": "tsc -p tsconfig.json --watch",
|
|
42
|
+
"lint": "eslint src",
|
|
43
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
44
|
+
"test": "vitest run --passWithNoTests"
|
|
45
|
+
},
|
|
46
|
+
"dependencies": {
|
|
47
|
+
"@vinaystwt/xmpp-contract-runtime": "0.1.0",
|
|
48
|
+
"@vinaystwt/xmpp-types": "0.1.0"
|
|
49
|
+
}
|
|
50
|
+
}
|