@vinaystwt/xmpp-http-interceptor 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.
Files changed (32) hide show
  1. package/LICENSE +21 -0
  2. package/dist/config/src/index.d.ts +49 -0
  3. package/dist/config/src/index.js +117 -0
  4. package/dist/contract-runtime/src/index.d.ts +44 -0
  5. package/dist/contract-runtime/src/index.js +364 -0
  6. package/dist/http-interceptor/src/agents.d.ts +5 -0
  7. package/dist/http-interceptor/src/agents.js +88 -0
  8. package/dist/http-interceptor/src/agents.test.d.ts +1 -0
  9. package/dist/http-interceptor/src/agents.test.js +35 -0
  10. package/dist/http-interceptor/src/idempotency.d.ts +68 -0
  11. package/dist/http-interceptor/src/idempotency.js +149 -0
  12. package/dist/http-interceptor/src/idempotency.test.d.ts +1 -0
  13. package/dist/http-interceptor/src/idempotency.test.js +75 -0
  14. package/dist/http-interceptor/src/index.d.ts +10 -0
  15. package/dist/http-interceptor/src/index.js +870 -0
  16. package/dist/http-interceptor/src/index.test.d.ts +1 -0
  17. package/dist/http-interceptor/src/index.test.js +131 -0
  18. package/dist/http-interceptor/src/state.d.ts +17 -0
  19. package/dist/http-interceptor/src/state.js +188 -0
  20. package/dist/logger/src/index.d.ts +2 -0
  21. package/dist/logger/src/index.js +18 -0
  22. package/dist/payment-adapters/src/index.d.ts +27 -0
  23. package/dist/payment-adapters/src/index.js +512 -0
  24. package/dist/policy-engine/src/index.d.ts +8 -0
  25. package/dist/policy-engine/src/index.js +90 -0
  26. package/dist/router/src/index.d.ts +23 -0
  27. package/dist/router/src/index.js +432 -0
  28. package/dist/types/src/index.d.ts +343 -0
  29. package/dist/types/src/index.js +1 -0
  30. package/dist/wallet/src/index.d.ts +14 -0
  31. package/dist/wallet/src/index.js +250 -0
  32. package/package.json +56 -0
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,35 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { applyAgentPolicy } from './agents.js';
3
+ describe('agent policy merge', () => {
4
+ it('overlays contract-backed budget, routes, services, and methods on the local agent profile', () => {
5
+ const profile = {
6
+ agentId: 'research-agent',
7
+ displayName: 'Research Agent',
8
+ role: 'research',
9
+ description: 'Local profile',
10
+ dailyBudgetUsd: 0.15,
11
+ allowedServices: ['research-api'],
12
+ preferredRoutes: ['x402'],
13
+ autopayMethods: ['GET'],
14
+ enabled: true,
15
+ policySource: 'local',
16
+ };
17
+ const policy = {
18
+ agentId: 'research-agent',
19
+ enabled: false,
20
+ dailyBudgetUsd: 0.2,
21
+ allowedServices: ['research-api', 'stream-api'],
22
+ preferredRoutes: ['x402', 'mpp-session-reuse'],
23
+ autopayMethods: ['get', 'head'],
24
+ source: 'contract',
25
+ };
26
+ expect(applyAgentPolicy(profile, policy)).toMatchObject({
27
+ enabled: false,
28
+ dailyBudgetUsd: 0.2,
29
+ allowedServices: ['research-api', 'stream-api'],
30
+ preferredRoutes: ['x402', 'mpp-session-reuse'],
31
+ autopayMethods: ['GET', 'HEAD'],
32
+ policySource: 'merged',
33
+ });
34
+ });
35
+ });
@@ -0,0 +1,68 @@
1
+ import type { XmppFetchMetadata, XmppFetchOptions } from '@xmpp/types';
2
+ type IdempotencySnapshot = {
3
+ fingerprint: string;
4
+ storedAt: number;
5
+ inflight: boolean;
6
+ response?: {
7
+ status: number;
8
+ statusText: string;
9
+ headers: Record<string, string>;
10
+ body: string;
11
+ metadata: XmppFetchMetadata;
12
+ };
13
+ };
14
+ export declare function inspectIdempotency(url: string, method: string, init?: RequestInit, options?: XmppFetchOptions): {
15
+ allowed: true;
16
+ code?: undefined;
17
+ reason?: undefined;
18
+ idempotencyKey?: undefined;
19
+ fingerprint?: undefined;
20
+ replay?: undefined;
21
+ response?: undefined;
22
+ } | {
23
+ allowed: false;
24
+ code: string;
25
+ reason: string;
26
+ idempotencyKey?: undefined;
27
+ fingerprint?: undefined;
28
+ replay?: undefined;
29
+ response?: undefined;
30
+ } | {
31
+ allowed: true;
32
+ idempotencyKey: string;
33
+ fingerprint: string;
34
+ code?: undefined;
35
+ reason?: undefined;
36
+ replay?: undefined;
37
+ response?: undefined;
38
+ } | {
39
+ allowed: true;
40
+ idempotencyKey: string;
41
+ fingerprint: string;
42
+ replay: true;
43
+ response: {
44
+ status: number;
45
+ statusText: string;
46
+ headers: Record<string, string>;
47
+ body: string;
48
+ metadata: XmppFetchMetadata;
49
+ };
50
+ code?: undefined;
51
+ reason?: undefined;
52
+ };
53
+ export declare function storeIdempotentResponse(idempotencyKey: string, fingerprint: string, response: Response, metadata: XmppFetchMetadata): Promise<void>;
54
+ export declare function clearIdempotentReservation(idempotencyKey: string, fingerprint: string): void;
55
+ export declare function buildIdempotentReplay(snapshot: IdempotencySnapshot['response']): {
56
+ response: Response;
57
+ metadata: {
58
+ idempotentReplay: boolean;
59
+ route: import("@xmpp/types").RouteKind;
60
+ challenge?: import("@xmpp/types").PaymentChallenge;
61
+ retried: boolean;
62
+ execution?: import("@xmpp/types").PaymentExecutionMetadata;
63
+ policy?: import("@xmpp/types").PolicyDecision;
64
+ budget?: import("@xmpp/types").XmppBudgetSnapshot;
65
+ };
66
+ } | null;
67
+ export declare function resetIdempotencyCache(): void;
68
+ export {};
@@ -0,0 +1,149 @@
1
+ import { createHash } from 'node:crypto';
2
+ const IDEMPOTENCY_TTL_MS = 60 * 60 * 1000;
3
+ const idempotencyCache = new Map();
4
+ function normalizeBody(body) {
5
+ if (body == null) {
6
+ return '';
7
+ }
8
+ if (typeof body === 'string') {
9
+ return body;
10
+ }
11
+ if (body instanceof URLSearchParams) {
12
+ return body.toString();
13
+ }
14
+ if (body instanceof FormData) {
15
+ const entries = [];
16
+ body.forEach((value, key) => {
17
+ entries.push(`${key}=${typeof value === 'string' ? value : value.name}`);
18
+ });
19
+ return entries.join('&');
20
+ }
21
+ return '[stream]';
22
+ }
23
+ function cleanupExpired() {
24
+ const cutoff = Date.now() - IDEMPOTENCY_TTL_MS;
25
+ for (const [key, snapshot] of idempotencyCache.entries()) {
26
+ if (snapshot.storedAt < cutoff) {
27
+ idempotencyCache.delete(key);
28
+ }
29
+ }
30
+ }
31
+ function buildFingerprint(url, method, init) {
32
+ const headers = new Headers(init?.headers);
33
+ const headerPairs = [];
34
+ headers.forEach((value, key) => {
35
+ headerPairs.push(`${key.toLowerCase()}=${value}`);
36
+ });
37
+ headerPairs.sort();
38
+ return createHash('sha256')
39
+ .update(JSON.stringify({
40
+ url,
41
+ method: method.toUpperCase(),
42
+ headers: headerPairs,
43
+ body: normalizeBody(init?.body),
44
+ }))
45
+ .digest('hex');
46
+ }
47
+ function resolveIdempotencyKey(init, options) {
48
+ const headers = new Headers(init?.headers);
49
+ return (options?.idempotencyKey ??
50
+ headers.get('idempotency-key') ??
51
+ headers.get('x-idempotency-key') ??
52
+ undefined);
53
+ }
54
+ export function inspectIdempotency(url, method, init, options) {
55
+ cleanupExpired();
56
+ const upperMethod = method.toUpperCase();
57
+ if (upperMethod === 'GET' || upperMethod === 'HEAD') {
58
+ return { allowed: true };
59
+ }
60
+ const idempotencyKey = resolveIdempotencyKey(init, options);
61
+ if (!idempotencyKey) {
62
+ return {
63
+ allowed: false,
64
+ code: 'missing-key',
65
+ reason: 'Automatic payment for non-GET requests requires an idempotency key.',
66
+ };
67
+ }
68
+ const fingerprint = buildFingerprint(url, upperMethod, init);
69
+ const existing = idempotencyCache.get(idempotencyKey);
70
+ if (!existing) {
71
+ idempotencyCache.set(idempotencyKey, {
72
+ fingerprint,
73
+ storedAt: Date.now(),
74
+ inflight: true,
75
+ });
76
+ return {
77
+ allowed: true,
78
+ idempotencyKey,
79
+ fingerprint,
80
+ };
81
+ }
82
+ if (existing.fingerprint !== fingerprint) {
83
+ return {
84
+ allowed: false,
85
+ code: 'mismatch',
86
+ reason: 'This idempotency key was already used for a different request payload.',
87
+ };
88
+ }
89
+ if (existing.inflight || !existing.response) {
90
+ return {
91
+ allowed: false,
92
+ code: 'inflight',
93
+ reason: 'An idempotent request with this key is already in progress.',
94
+ };
95
+ }
96
+ return {
97
+ allowed: true,
98
+ idempotencyKey,
99
+ fingerprint,
100
+ replay: true,
101
+ response: existing.response,
102
+ };
103
+ }
104
+ export async function storeIdempotentResponse(idempotencyKey, fingerprint, response, metadata) {
105
+ const body = await response.clone().text();
106
+ const headers = {};
107
+ response.headers.forEach((value, key) => {
108
+ headers[key] = value;
109
+ });
110
+ idempotencyCache.set(idempotencyKey, {
111
+ fingerprint,
112
+ storedAt: Date.now(),
113
+ inflight: false,
114
+ response: {
115
+ status: response.status,
116
+ statusText: response.statusText,
117
+ headers,
118
+ body,
119
+ metadata,
120
+ },
121
+ });
122
+ }
123
+ export function clearIdempotentReservation(idempotencyKey, fingerprint) {
124
+ const existing = idempotencyCache.get(idempotencyKey);
125
+ if (existing && existing.fingerprint === fingerprint && existing.inflight) {
126
+ idempotencyCache.delete(idempotencyKey);
127
+ }
128
+ }
129
+ export function buildIdempotentReplay(snapshot) {
130
+ if (!snapshot) {
131
+ return null;
132
+ }
133
+ const headers = new Headers(snapshot.headers);
134
+ headers.set('x-xmpp-idempotency-replay', 'true');
135
+ return {
136
+ response: new Response(snapshot.body, {
137
+ status: snapshot.status,
138
+ statusText: snapshot.statusText,
139
+ headers,
140
+ }),
141
+ metadata: {
142
+ ...snapshot.metadata,
143
+ idempotentReplay: true,
144
+ },
145
+ };
146
+ }
147
+ export function resetIdempotencyCache() {
148
+ idempotencyCache.clear();
149
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,75 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { buildIdempotentReplay, inspectIdempotency, resetIdempotencyCache, storeIdempotentResponse, } from './idempotency.js';
3
+ describe('idempotency', () => {
4
+ afterEach(() => {
5
+ resetIdempotencyCache();
6
+ });
7
+ it('requires an idempotency key for non-GET payment requests', () => {
8
+ const result = inspectIdempotency('http://localhost:4102/order', 'POST', {
9
+ body: JSON.stringify({ symbol: 'XLM' }),
10
+ headers: { 'content-type': 'application/json' },
11
+ });
12
+ expect(result).toMatchObject({
13
+ allowed: false,
14
+ code: 'missing-key',
15
+ });
16
+ });
17
+ it('replays a previously stored response for the same request fingerprint', async () => {
18
+ const first = inspectIdempotency('http://localhost:4102/order', 'POST', {
19
+ body: JSON.stringify({ symbol: 'XLM' }),
20
+ headers: { 'content-type': 'application/json' },
21
+ }, {
22
+ idempotencyKey: 'order-1',
23
+ });
24
+ expect(first.allowed).toBe(true);
25
+ if (!first.allowed ||
26
+ !('idempotencyKey' in first) ||
27
+ !('fingerprint' in first) ||
28
+ typeof first.idempotencyKey !== 'string' ||
29
+ typeof first.fingerprint !== 'string') {
30
+ throw new Error('expected idempotency reservation to succeed');
31
+ }
32
+ await storeIdempotentResponse(first.idempotencyKey, first.fingerprint, new Response(JSON.stringify({ ok: true }), {
33
+ status: 200,
34
+ headers: { 'content-type': 'application/json' },
35
+ }), {
36
+ route: 'mpp-charge',
37
+ retried: true,
38
+ });
39
+ const second = inspectIdempotency('http://localhost:4102/order', 'POST', {
40
+ body: JSON.stringify({ symbol: 'XLM' }),
41
+ headers: { 'content-type': 'application/json' },
42
+ }, {
43
+ idempotencyKey: 'order-1',
44
+ });
45
+ expect(second).toMatchObject({
46
+ allowed: true,
47
+ replay: true,
48
+ idempotencyKey: 'order-1',
49
+ });
50
+ if (!second.allowed || !('response' in second) || !second.response) {
51
+ throw new Error('expected idempotent replay to be available');
52
+ }
53
+ const replay = buildIdempotentReplay(second.response);
54
+ expect(replay?.metadata.idempotentReplay).toBe(true);
55
+ });
56
+ it('rejects idempotency key reuse with a different request body', () => {
57
+ const first = inspectIdempotency('http://localhost:4102/order', 'POST', {
58
+ body: JSON.stringify({ symbol: 'XLM' }),
59
+ headers: { 'content-type': 'application/json' },
60
+ }, {
61
+ idempotencyKey: 'order-1',
62
+ });
63
+ expect(first.allowed).toBe(true);
64
+ const second = inspectIdempotency('http://localhost:4102/order', 'POST', {
65
+ body: JSON.stringify({ symbol: 'BTC' }),
66
+ headers: { 'content-type': 'application/json' },
67
+ }, {
68
+ idempotencyKey: 'order-1',
69
+ });
70
+ expect(second).toMatchObject({
71
+ allowed: false,
72
+ code: 'mismatch',
73
+ });
74
+ });
75
+ });
@@ -0,0 +1,10 @@
1
+ import type { XmppAgentProfile, XmppFetchMetadata, XmppFetchOptions } from '@xmpp/types';
2
+ import { getXmppOperatorState, listLocalSessions } from './state.js';
3
+ import { listXmppAgentProfiles } from './agents.js';
4
+ export declare function getXmppMetadata(resp: Response): XmppFetchMetadata | undefined;
5
+ export { getXmppOperatorState, listLocalSessions, listXmppAgentProfiles };
6
+ export declare function resetXmppRuntimeState(): void;
7
+ export { resetXmppRuntimeState as resetXmppOperatorState };
8
+ export declare function getEffectiveXmppAgentProfile(agentId?: string): Promise<XmppAgentProfile>;
9
+ export declare function listEffectiveXmppAgentProfiles(): Promise<XmppAgentProfile[]>;
10
+ export declare function xmppFetch(input: RequestInfo | URL, init?: RequestInit, options?: XmppFetchOptions): Promise<Response>;