osuite 2.11.2 → 2.13.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.
@@ -0,0 +1,395 @@
1
+ import { canonicalJson, createApiClient, sha256 } from '../runtime/protocol.mjs';
2
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, COMPACT_TRANSFER_LEASE_PROFILE as COMPACT,
3
+ CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES, ENDPOINT, ControlledTransferError,
4
+ configuration, fail, identifier, inspectCapabilities, issuerIdentity, prepareLeaseFormat, record, reviewFields, snapshot } from './contract.mjs';
5
+ import { verifyPreparation, verifyReceipt } from './verification.mjs';
6
+ import { normalizeProjection, snapshotWithProjection } from './projection.mjs';
7
+
8
+ const MAX_HOT_OPERATIONS = 16;
9
+ const MAX_OPERATION_RECORDS = 65536;
10
+ const bit = ordinal => 1n << BigInt(ordinal);
11
+ const preparationBinding = prepared => sha256(canonicalJson([
12
+ prepared.grantId, prepared.preparationDigest, prepared.lease, prepared.effects,
13
+ ]));
14
+
15
+ export function createControlledTransfers(options) {
16
+ const config = configuration(options);
17
+ const api = createApiClient(config, { timeoutMs: config.timeoutMs, maxResponseBytes: CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES });
18
+ let issuer = config.issuerPublicKey ? issuerIdentity(config.issuerPublicKey) : null;
19
+ const operations = new Map();
20
+ const hot = new Map();
21
+
22
+ function operationFor(operationId) {
23
+ let operation = operations.get(operationId);
24
+ if (!operation) {
25
+ if (operations.size >= MAX_OPERATION_RECORDS) fail('CLIENT_CAPACITY_EXCEEDED', { operationId, reason: 'operation-record-limit' });
26
+ operation = { operationId, acknowledged: 0n, receiptMask: 0n };
27
+ operations.set(operationId, operation);
28
+ }
29
+ return operation;
30
+ }
31
+
32
+ const active = operation => operation.preparing || operation.recoveringPreparation || operation.executing || operation.reading;
33
+ function keepHot(operation) {
34
+ if (!hot.has(operation.operationId) && hot.size >= MAX_HOT_OPERATIONS) {
35
+ const entry = [...hot].find(([, candidate]) => !active(candidate));
36
+ if (!entry) fail('CLIENT_CAPACITY_EXCEEDED', { operationId: operation.operationId, reason: 'active-operation-limit' });
37
+ const [id, previous] = entry;
38
+ previous.prepared = null;
39
+ previous.completed = null;
40
+ hot.delete(id);
41
+ }
42
+ hot.delete(operation.operationId);
43
+ hot.set(operation.operationId, operation);
44
+ }
45
+
46
+ function releaseIdle(operation) {
47
+ if (active(operation)) return;
48
+ if (!operation.prepared && !operation.completed?.size) hot.delete(operation.operationId);
49
+ // Only a preflight that never observed or sent an operation may be forgotten.
50
+ if (!operation.seen && !operation.unknown) {
51
+ hot.delete(operation.operationId);
52
+ operations.delete(operation.operationId);
53
+ }
54
+ }
55
+
56
+ function checkBinding(operation, prepared, statusRead = false) {
57
+ const code = statusRead ? 'INVALID_STATUS' : 'OPERATION_CONFLICT';
58
+ if ((operation.grantId !== undefined && operation.grantId !== prepared.grantId)
59
+ || (operation.effectCount !== undefined && operation.effectCount !== prepared.effects.length)) fail(code);
60
+ if (!operation.binding) return;
61
+ if (operation.binding !== preparationBinding(prepared)
62
+ || ((!statusRead || operation.actionId) && (operation.actionId !== prepared.actionId || operation.fingerprint !== prepared.fingerprint))
63
+ || (!statusRead && operation.preparationState !== prepared.state)) fail(code);
64
+ }
65
+
66
+ function rememberPreparation(operation, prepared, statusRead = false) {
67
+ checkBinding(operation, prepared, statusRead);
68
+ keepHot(operation);
69
+ operation.grantId = prepared.grantId;
70
+ operation.leaseFormat = prepared.lease.payload.profile;
71
+ operation.binding = preparationBinding(prepared);
72
+ operation.effectCount = prepared.effects.length;
73
+ operation.actionId = prepared.actionId;
74
+ operation.fingerprint = prepared.fingerprint;
75
+ operation.preparationState = prepared.state;
76
+ operation.prepared = prepared;
77
+ operation.seen = true;
78
+ }
79
+
80
+ function receiptDigest(operation, ordinal) {
81
+ return operation.receiptMask & bit(ordinal)
82
+ ? operation.receiptDigests.toString('hex', ordinal * 32, (ordinal + 1) * 32) : null;
83
+ }
84
+
85
+ function checkReceipt(operation, ordinal, receipt, code) {
86
+ const digest = sha256(canonicalJson(receipt)), previous = receiptDigest(operation, ordinal);
87
+ if (previous && previous !== digest) fail(code);
88
+ return digest;
89
+ }
90
+
91
+ function rememberReceipt(operation, ordinal, receipt, acknowledged = false) {
92
+ const digest = checkReceipt(operation, ordinal, receipt, 'INVALID_RECEIPT');
93
+ operation.receiptDigests ??= Buffer.alloc(operation.effectCount * 32);
94
+ Buffer.from(digest, 'hex').copy(operation.receiptDigests, ordinal * 32);
95
+ operation.receiptMask |= bit(ordinal);
96
+ if (acknowledged) operation.acknowledged |= bit(ordinal);
97
+ }
98
+
99
+ function replayResult(operationId, prepared, receipt, projection) {
100
+ return snapshotWithProjection({ profile: PROFILE, operationId, state: 'already_committed', receipt,
101
+ projection, ...reviewFields(prepared, config.baseUrl), newlyCommitted: false });
102
+ }
103
+
104
+ async function recover(operation) {
105
+ const observed = await status(operation.operationId);
106
+ if (operation.unknown) throw operation.unknown;
107
+ const prepared = observed.prepared ?? operation.prepared;
108
+ if (!prepared) throw unknown(operation.operationId, 'MISSING_HISTORICAL_PREPARATION');
109
+ return { observed, prepared };
110
+ }
111
+
112
+ async function capabilities() {
113
+ const response = await api.request('GET', ENDPOINT);
114
+ if (!response.ok) fail('CAPABILITY_UNAVAILABLE', { reason: response.error, httpStatus: response.status });
115
+ const value = inspectCapabilities(response.body);
116
+ if (value.issuerPublicKey) {
117
+ const advertised = issuerIdentity(value.issuerPublicKey, 'INVALID_CAPABILITY');
118
+ if (issuer && issuer.fingerprint !== advertised.fingerprint) fail('CAPABILITY_MISMATCH');
119
+ issuer = advertised;
120
+ }
121
+ return value;
122
+ }
123
+
124
+ async function requireCapability() {
125
+ const value = await capabilities();
126
+ if (!value.configured || !value.resourceEnforced || !issuer) fail('PROFILE_UNAVAILABLE');
127
+ return value;
128
+ }
129
+
130
+ function unknown(operationId, reason, httpStatus = null) {
131
+ const error = new ControlledTransferError('OUTCOME_UNKNOWN', { operationId, reason, httpStatus });
132
+ const operation = operationFor(operationId);
133
+ operation.unknown = error;
134
+ return error;
135
+ }
136
+
137
+ async function post(kind, operationId, fields) {
138
+ if (operations.get(operationId)?.unknown) throw operations.get(operationId).unknown;
139
+ const response = await api.request('POST', ENDPOINT, { profile: PROFILE, agent_id: config.agentId,
140
+ kind, operationId, timestamp: Date.now(), ...fields });
141
+ if (!response.ok) throw unknown(operationId, response.error, response.status);
142
+ let body;
143
+ try {
144
+ body = kind === 'execute' ? snapshotWithProjection(response.body) : snapshot(response.body);
145
+ } catch { throw unknown(operationId, 'INVALID_RESPONSE'); }
146
+ if (body.profile !== PROFILE || body.operationId !== operationId) {
147
+ throw unknown(operationId, 'RESPONSE_BINDING_MISMATCH');
148
+ }
149
+ return body;
150
+ }
151
+
152
+ function checkPrepareChoice(operation, grantId, leaseFormat) {
153
+ if ((operation.grantId !== undefined && operation.grantId !== grantId)
154
+ || (operation.preparingGrantId !== undefined && operation.preparingGrantId !== grantId)) fail('OPERATION_CONFLICT');
155
+ if ((operation.leaseFormat !== undefined && operation.leaseFormat !== leaseFormat)
156
+ || (operation.preparingFormat !== undefined && operation.preparingFormat !== leaseFormat)) fail('LEASE_FORMAT_CONFLICT');
157
+ }
158
+
159
+ function prepareOnce(operation, grantId, leaseFormat, work, recovery = false) {
160
+ const slot = recovery ? 'recoveringPreparation' : 'preparing';
161
+ operation.preparingGrantId = grantId;
162
+ operation.preparingFormat = leaseFormat;
163
+ operation[slot] = Promise.resolve().then(work).finally(() => {
164
+ operation[slot] = null;
165
+ operation.preparingGrantId = undefined;
166
+ operation.preparingFormat = undefined;
167
+ releaseIdle(operation);
168
+ });
169
+ return operation[slot];
170
+ }
171
+
172
+ async function prepare(operationId, grantId, options) {
173
+ if (!identifier(operationId)) fail('INVALID_OPERATION_ID');
174
+ if (!identifier(grantId)) fail('INVALID_GRANT_ID');
175
+ const existing = operations.get(operationId);
176
+ if (existing?.unknown) throw existing.unknown;
177
+ const leaseFormat = prepareLeaseFormat(options);
178
+ if (existing) {
179
+ checkPrepareChoice(existing, grantId, leaseFormat);
180
+ if (existing.prepared) { keepHot(existing); return existing.prepared; }
181
+ if (existing.preparing || existing.recoveringPreparation) return existing.preparing ?? existing.recoveringPreparation;
182
+ if (existing.executing) fail('EXECUTION_IN_PROGRESS');
183
+ return prepareOnce(existing, grantId, leaseFormat, async () => {
184
+ const { prepared } = await recover(existing);
185
+ checkPrepareChoice(existing, grantId, leaseFormat);
186
+ return prepared;
187
+ }, true);
188
+ }
189
+ const operation = operationFor(operationId);
190
+ operation.grantId = grantId;
191
+ try { keepHot(operation); } catch (error) { releaseIdle(operation); throw error; }
192
+ return prepareOnce(operation, grantId, leaseFormat, async () => {
193
+ let capability;
194
+ try { capability = await requireCapability(); } catch (error) {
195
+ if (operation.unknown) throw operation.unknown;
196
+ throw error;
197
+ }
198
+ if (operation.reading) await operation.reading;
199
+ if (operation.unknown) throw operation.unknown;
200
+ checkPrepareChoice(operation, grantId, leaseFormat);
201
+ if (operation.prepared) return operation.prepared;
202
+ if (operation.seen) throw unknown(operationId, 'MISSING_HISTORICAL_PREPARATION');
203
+ if (leaseFormat === COMPACT) {
204
+ if (!capability.leaseFormats.supported.includes(COMPACT)) fail('LEASE_FORMAT_UNSUPPORTED');
205
+ if (!capability.leaseFormats.compactIssuanceEnabled) fail('COMPACT_LEASE_ISSUANCE_DISABLED');
206
+ }
207
+ operation.seen = true;
208
+ const body = await post('prepare', operationId, { grantId, ...(leaseFormat === COMPACT ? { leaseFormat } : {}) });
209
+ try {
210
+ const verified = verifyPreparation(body, { config, issuer, operationId, grantId });
211
+ if (verified.lease.payload.profile !== leaseFormat) fail('LEASE_FORMAT_CONFLICT');
212
+ rememberPreparation(operation, snapshot({ ...verified, ...reviewFields(verified, config.baseUrl) }));
213
+ }
214
+ catch { throw unknown(operationId, 'INVALID_PREPARATION'); }
215
+ return operation.prepared;
216
+ });
217
+ }
218
+
219
+ async function execute(prepared, ordinal = 0) {
220
+ prepared = snapshot(prepared, 'INVALID_PREPARATION');
221
+ if (!record(prepared) || !identifier(prepared.operationId) || !identifier(prepared.grantId) || !record(prepared.lease)) fail('INVALID_PREPARATION');
222
+ if (!Number.isSafeInteger(ordinal) || ordinal < 0 || ordinal >= prepared.effects?.length) fail('INVALID_ORDINAL');
223
+ const operationId = prepared.operationId;
224
+ let operation = operations.get(operationId);
225
+ if (operation?.unknown) throw operation.unknown;
226
+ if (operation && operation.grantId !== undefined && operation.grantId !== prepared.grantId) fail('OPERATION_CONFLICT');
227
+ if (operation?.preparing && !operation.prepared) fail('PREPARATION_IN_PROGRESS');
228
+ if (operation) checkBinding(operation, prepared);
229
+ const previous = operation?.prepared ?? operation?.executing?.prepared;
230
+ if (previous && ['grantId', 'preparationDigest', 'actionId', 'fingerprint', 'lease', 'effects', 'state']
231
+ .some(field => canonicalJson(prepared[field]) !== canonicalJson(previous[field]))) fail('OPERATION_CONFLICT');
232
+ if (!operation) {
233
+ operation = operationFor(operationId);
234
+ operation.grantId = prepared.grantId;
235
+ }
236
+ if (operation.completed?.has(ordinal)) {
237
+ keepHot(operation);
238
+ const completed = operation.completed.get(ordinal);
239
+ return snapshotWithProjection({ ...completed, state: 'already_committed', newlyCommitted: false,
240
+ projection: normalizeProjection(completed.projection, { cached: true }) });
241
+ }
242
+ if (operation.acknowledged & bit(ordinal)) {
243
+ const recovered = await recover(operation);
244
+ const effect = recovered.observed.effects[ordinal];
245
+ if (!effect?.receiptVerified || receiptDigest(operation, ordinal) !== sha256(canonicalJson(effect.receipt))) {
246
+ throw unknown(operationId, 'INVALID_HISTORICAL_RECEIPT');
247
+ }
248
+ return replayResult(operationId, recovered.prepared, effect.receipt, recovered.observed.projection);
249
+ }
250
+ if (operation.executing) {
251
+ if (operation.executing.ordinal !== ordinal) fail('EXECUTION_IN_PROGRESS');
252
+ return operation.executing.promise;
253
+ }
254
+ try { keepHot(operation); } catch (error) { releaseIdle(operation); throw error; }
255
+ const pending = { ordinal, prepared };
256
+ operation.executing = pending;
257
+ pending.promise = (async () => {
258
+ if (operation.reading) await operation.reading;
259
+ if (operation.unknown) throw operation.unknown;
260
+ const capability = await requireCapability();
261
+ if (operation.unknown) throw operation.unknown;
262
+ prepared = verifyPreparation(prepared, { config, issuer, operationId, grantId: prepared.grantId });
263
+ checkBinding(operation, prepared);
264
+ if (prepared.state === 'denied') fail('PREPARATION_DENIED');
265
+ if (!prepared.actionId) fail('APPROVAL_NOT_BOUND');
266
+ if (prepared.lease.payload.profile === COMPACT && !capability.leaseFormats.supported.includes(COMPACT)) {
267
+ fail('LEASE_FORMAT_UNSUPPORTED');
268
+ }
269
+ // Reuse the immutable snapshot, rather than retaining another full copy per execution.
270
+ prepared = operation.prepared ?? prepared;
271
+ rememberPreparation(operation, prepared);
272
+ pending.dispatched = true;
273
+ const binding = capability.executionTransport === 'bound-reference-v1'
274
+ ? { preparationDigest: prepared.preparationDigest } : { lease: prepared.lease };
275
+ const body = await post('execute', operationId, { ...binding, ordinal });
276
+ let result;
277
+ if (body.state === 'denied' && identifier(body.code) && body.receipt == null) {
278
+ result = snapshotWithProjection({ ...body, ...reviewFields(prepared, config.baseUrl), newlyCommitted: false });
279
+ } else if (['committed', 'already_committed'].includes(body.state)) {
280
+ let receipt;
281
+ try { receipt = verifyReceipt(body.receipt, { issuer, config, prepared, ordinal, historical: body.state === 'already_committed',
282
+ sourcePrepared: body.receipt?.payload?.operationId !== operationId
283
+ ? operations.get(body.receipt?.payload?.operationId)?.prepared : undefined }); }
284
+ catch { throw unknown(operationId, 'INVALID_RECEIPT'); }
285
+ result = snapshotWithProjection({ ...body, receipt, ...reviewFields(prepared, config.baseUrl), newlyCommitted: body.state === 'committed' });
286
+ rememberReceipt(operation, ordinal, receipt, true);
287
+ operation.completed ??= new Map();
288
+ operation.completed.set(ordinal, result);
289
+ } else { throw unknown(operationId, 'INVALID_EXECUTION_RESPONSE'); }
290
+ return result;
291
+ })().catch(error => {
292
+ if (operation.unknown) throw operation.unknown;
293
+ if (pending.dispatched) throw unknown(operationId, 'INVALID_EXECUTION_RESPONSE');
294
+ throw error;
295
+ });
296
+ try { return await pending.promise; }
297
+ catch (error) { throw operation.unknown ?? error; }
298
+ finally {
299
+ operation.executing = null;
300
+ releaseIdle(operation);
301
+ }
302
+ }
303
+
304
+ function unknownStatus(operationId, reason, httpStatus = null, prepared, projection) {
305
+ const error = unknown(operationId, reason, httpStatus);
306
+ return snapshotWithProjection({ profile: PROFILE, operationId, state: 'unknown', code: error.code,
307
+ reason, httpStatus, lastDenial: null, effects: [], newlyCommitted: false, projection,
308
+ ...reviewFields(operations.get(operationId), config.baseUrl), recovery: error.recovery,
309
+ ...(prepared ? { prepared } : {}) });
310
+ }
311
+
312
+ async function status(operationId) {
313
+ if (!identifier(operationId)) fail('INVALID_OPERATION_ID');
314
+ const operation = operationFor(operationId);
315
+ if (operation.reading) return operation.reading;
316
+ try { keepHot(operation); } catch (error) { releaseIdle(operation); throw error; }
317
+ operation.reading = readStatus(operationId, operation);
318
+ try { return await operation.reading; }
319
+ finally { operation.reading = null; releaseIdle(operation); }
320
+ }
321
+
322
+ async function readStatus(operationId, operation) {
323
+ const response = await api.request('GET', `${ENDPOINT}?operationId=${encodeURIComponent(operationId)}&agent_id=${encodeURIComponent(config.agentId)}`);
324
+ if (!response.ok) return unknownStatus(operationId, response.error, response.status);
325
+ try {
326
+ const body = snapshotWithProjection(response.body, 'INVALID_STATUS');
327
+ if (!record(body) || body.profile !== PROFILE || body.operationId !== operationId
328
+ || !['committed', 'partially_committed', 'denied', 'awaiting_approval', 'ready', 'unknown'].includes(body.state)
329
+ || !(body.actionId === null || identifier(body.actionId))
330
+ || !(body.lastDenial === null || identifier(body.lastDenial))
331
+ || !Array.isArray(body.effects) || body.effects.length > 64
332
+ || (body.state === 'ready' && !body.actionId)) fail('INVALID_STATUS');
333
+ const hasPrepared = Object.hasOwn(body, 'prepared');
334
+ if (!issuer && (hasPrepared || body.effects.some(effect => effect?.state === 'committed'))) await capabilities();
335
+ let prepared = operation?.prepared;
336
+ if (!prepared && operation.binding && !hasPrepared) fail('INVALID_STATUS');
337
+ if (hasPrepared) {
338
+ const verified = verifyPreparation(body.prepared, { config, issuer, operationId,
339
+ grantId: operation?.grantId ?? body.prepared?.grantId, checkExpiry: false, historical: true });
340
+ checkBinding(operation, verified, true);
341
+ const previous = prepared ?? operation?.executing?.prepared;
342
+ if (previous && (['grantId', 'preparationDigest', 'lease', 'effects']
343
+ .some(field => canonicalJson(verified[field]) !== canonicalJson(previous[field]))
344
+ || (previous.actionId && (verified.actionId !== previous.actionId || verified.fingerprint !== previous.fingerprint)))) {
345
+ fail('INVALID_STATUS');
346
+ }
347
+ prepared = snapshot({ ...verified, ...reviewFields(verified, config.baseUrl) });
348
+ }
349
+ if (prepared && body.actionId !== prepared.actionId) fail('INVALID_STATUS');
350
+ if (body.state === 'unknown') return unknownStatus(operationId, 'OWNER_OUTCOME_UNKNOWN', null,
351
+ hasPrepared ? prepared : undefined, body.projection);
352
+ if (!body.effects.length || (prepared && body.effects.length !== prepared.effects.length)
353
+ || (operation.effectCount !== undefined && body.effects.length !== operation.effectCount)) fail('INVALID_STATUS');
354
+ let committed = 0;
355
+ const payments = new Set();
356
+ const effects = body.effects.map((effect, ordinal) => {
357
+ if (!record(effect) || effect.ordinal !== ordinal || !identifier(effect.paymentId)
358
+ || payments.has(effect.paymentId) || !['committed', 'not_committed'].includes(effect.state)
359
+ || (prepared && effect.paymentId !== prepared.effects[ordinal].paymentId)) fail('INVALID_STATUS');
360
+ payments.add(effect.paymentId);
361
+ if (effect.state !== 'committed') {
362
+ if (effect.receipt != null || receiptDigest(operation, ordinal)) fail('INVALID_STATUS');
363
+ return { ...effect, receiptVerified: false };
364
+ }
365
+ const receipt = verifyReceipt(effect.receipt, { issuer, config, prepared, ordinal, historical: true,
366
+ sourcePrepared: effect.receipt?.payload?.operationId !== operationId
367
+ ? operations.get(effect.receipt?.payload?.operationId)?.prepared : undefined,
368
+ operationId, actionId: body.actionId, paymentId: effect.paymentId });
369
+ checkReceipt(operation, ordinal, receipt, 'INVALID_STATUS');
370
+ committed++;
371
+ return { ...effect, receipt, receiptVerified: true };
372
+ });
373
+ if ((body.state === 'committed' && committed !== effects.length)
374
+ || (body.state === 'partially_committed' && (committed === 0 || committed === effects.length))
375
+ || (['denied', 'awaiting_approval', 'ready'].includes(body.state) && committed !== 0)) fail('INVALID_STATUS');
376
+ if (hasPrepared) {
377
+ // Recover the original lease without replacing any physical-outcome uncertainty fence.
378
+ rememberPreparation(operation, prepared, true);
379
+ }
380
+ operation.seen = true;
381
+ operation.effectCount = effects.length;
382
+ for (const effect of effects) if (effect.receiptVerified) {
383
+ rememberReceipt(operation, effect.ordinal, effect.receipt);
384
+ if (operation.acknowledged & bit(effect.ordinal)) {
385
+ operation.completed ??= new Map();
386
+ operation.completed.set(effect.ordinal, replayResult(operationId, prepared, effect.receipt, body.projection));
387
+ }
388
+ }
389
+ return snapshotWithProjection({ ...body, effects, ...reviewFields(body, config.baseUrl), newlyCommitted: false,
390
+ ...(hasPrepared ? { prepared } : {}) });
391
+ } catch (error) { return unknownStatus(operationId, error.code ?? 'INVALID_STATUS'); }
392
+ }
393
+
394
+ return Object.freeze({ capabilities, prepare, execute, status });
395
+ }
@@ -0,0 +1,153 @@
1
+ import { createPrivateKey, createPublicKey } from 'node:crypto';
2
+ import { types } from 'node:util';
3
+ import { canonicalJson, sha256, validatedBaseUrl } from '../runtime/protocol.mjs';
4
+
5
+ export const CONTROLLED_TRANSFER_PROFILE = 'matoi.controlled-transfer.v1';
6
+ export const COMPACT_TRANSFER_LEASE_PROFILE = 'matoi.controlled-transfer.lease.v2';
7
+ export const TRANSFER_PASS_BUILDER_PROFILE = 'matoi.controlled-transfer.pass.v1';
8
+ export const CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES = 1024 * 1024;
9
+ export const RECEIPT_PROFILE = 'matoi.controlled-transfer.receipt.v1';
10
+ export const ENDPOINT = '/api/matoi/transfers';
11
+ export const QUALIFICATIONS = Object.freeze(['not-qualified', 'integrated-tested', 'deployment-qualified']);
12
+ const MAX_SNAPSHOT_NODES = 65536;
13
+ const reserved = new Set([...Object.getOwnPropertyNames(Object.prototype), 'prototype', 'toJSON']);
14
+ const wellFormed = value => !/[\uD800-\uDFFF]/u.test(value);
15
+ export const identifier = value => typeof value === 'string'
16
+ && /^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$/.test(value) && !reserved.has(value);
17
+ export const digest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
18
+ export const record = value => value !== null && typeof value === 'object' && !types.isProxy(value)
19
+ && !Array.isArray(value) && [Object.prototype, null].includes(Object.getPrototypeOf(value));
20
+
21
+ export class ControlledTransferError extends Error {
22
+ constructor(code, details = {}) {
23
+ const unknown = code === 'OUTCOME_UNKNOWN';
24
+ super(`Matoi ${code}${unknown ? ': execution is not disproved; read status for the same operation, do not resend.' : ''}`);
25
+ this.name = 'ControlledTransferError';
26
+ this.code = code;
27
+ this.operationId = details.operationId ?? null;
28
+ this.reason = details.reason ?? null;
29
+ this.httpStatus = details.httpStatus ?? null;
30
+ this.retryAutomatically = false;
31
+ this.recovery = Object.freeze({ method: unknown ? 'status' : null,
32
+ operationId: this.operationId, preserveOperationId: true,
33
+ message: unknown ? 'Read status only. A missing result is not proof of non-execution. Do not resend or replace the operation ID.'
34
+ : 'Inspect configuration or current authority. No automatic retry is permitted.' });
35
+ }
36
+ }
37
+ export function fail(code, details) { throw new ControlledTransferError(code, details); }
38
+
39
+ // Snapshot descriptors, rather than invoke caller accessors or toJSON methods.
40
+ export function snapshot(input, code = 'INVALID_RESPONSE') {
41
+ const ancestors = new Set();
42
+ let nodes = 0;
43
+ function copy(value, depth) {
44
+ if (++nodes > MAX_SNAPSHOT_NODES || depth > 24) fail(code);
45
+ if (value === null || typeof value === 'boolean') return value;
46
+ if (typeof value === 'string' && value.length <= CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES && wellFormed(value)) return value;
47
+ if (Number.isSafeInteger(value) && !Object.is(value, -0)) return value;
48
+ if (!value || typeof value !== 'object' || types.isProxy(value) || ancestors.has(value)) fail(code);
49
+ const array = Array.isArray(value);
50
+ if (array ? Object.getPrototypeOf(value) !== Array.prototype : !record(value)) fail(code);
51
+ const descriptors = Object.getOwnPropertyDescriptors(value), keys = Reflect.ownKeys(descriptors);
52
+ if (keys.some(key => typeof key !== 'string' || reserved.has(key)
53
+ || !wellFormed(key) || !Object.hasOwn(descriptors[key], 'value')
54
+ || (!descriptors[key].enumerable && !(array && key === 'length')))) fail(code);
55
+ if (array && (value.length > MAX_SNAPSHOT_NODES || keys.length !== value.length + 1
56
+ || keys.some(key => key !== 'length' && !/^(0|[1-9][0-9]*)$/.test(key)))) fail(code);
57
+ ancestors.add(value);
58
+ const result = array ? [] : {};
59
+ for (const key of keys) if (!(array && key === 'length')) result[key] = copy(descriptors[key].value, depth + 1);
60
+ ancestors.delete(value);
61
+ return Object.freeze(result);
62
+ }
63
+ const result = copy(input, 0);
64
+ if (Buffer.byteLength(canonicalJson(result)) > CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES) fail(code);
65
+ return result;
66
+ }
67
+
68
+ export function issuerIdentity(pem, code = 'INVALID_CONFIGURATION') {
69
+ try {
70
+ if (typeof pem !== 'string' || pem.length > 2048) throw new Error();
71
+ const match = /^-----BEGIN PUBLIC KEY-----\n([A-Za-z0-9+/=\n]+)\n-----END PUBLIC KEY-----$/.exec(pem.replace(/\r\n/g, '\n').trim());
72
+ if (!match) throw new Error();
73
+ const encoded = match[1].replace(/\n/g, ''), der = Buffer.from(encoded, 'base64');
74
+ if (der.toString('base64') !== encoded) throw new Error();
75
+ const key = createPublicKey({ key: der, format: 'der', type: 'spki' });
76
+ if (key.asymmetricKeyType !== 'ed25519' || !key.export({ type: 'spki', format: 'der' }).equals(der)) throw new Error();
77
+ return Object.freeze({ key, fingerprint: sha256(key.export({ type: 'spki', format: 'der' })) });
78
+ } catch { fail(code); }
79
+ }
80
+
81
+ function plainOptions(value) {
82
+ return record(value) && Reflect.ownKeys(value).every(key => typeof key === 'string'
83
+ && !reserved.has(key) && Object.hasOwn(Object.getOwnPropertyDescriptor(value, key), 'value'));
84
+ }
85
+
86
+ export function configuration(options) {
87
+ if (Number(process.versions.node.split('.')[0]) !== 24) fail('NODE_24_REQUIRED');
88
+ if (!plainOptions(options) || Object.keys(options).some(key => key !== 'config') || !plainOptions(options.config)) {
89
+ fail('INVALID_CONFIGURATION');
90
+ }
91
+ const input = options.config, baseUrl = validatedBaseUrl(input.baseUrl);
92
+ const timeoutMs = input.timeoutMs ?? 2500;
93
+ if (!baseUrl || typeof input.apiKey !== 'string' || !/^[\x21-\x7e]{1,4096}$/.test(input.apiKey)
94
+ || !identifier(input.orgId) || !identifier(input.agentId)
95
+ || (input.keyId !== undefined && !identifier(input.keyId))
96
+ || input.signatureMode !== 'required' || input.guardFailureMode !== 'block'
97
+ || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000
98
+ || typeof input.privateKeyBase64 !== 'string' || input.privateKeyBase64.length > 32768
99
+ || !/^[A-Za-z0-9+/]+={0,2}$/.test(input.privateKeyBase64)) fail('INVALID_CONFIGURATION');
100
+ try {
101
+ const key = createPrivateKey(Buffer.from(input.privateKeyBase64, 'base64'));
102
+ if (key.asymmetricKeyType !== 'rsa') throw new Error();
103
+ } catch { fail('INVALID_CONFIGURATION'); }
104
+ if (input.issuerPublicKey != null) issuerIdentity(input.issuerPublicKey);
105
+ const trustedIssuerPublicKeys = snapshot(input.trustedIssuerPublicKeys ?? [], 'INVALID_CONFIGURATION');
106
+ if (!Array.isArray(trustedIssuerPublicKeys) || trustedIssuerPublicKeys.length > 8) fail('INVALID_CONFIGURATION');
107
+ const roots = trustedIssuerPublicKeys.map(pem => issuerIdentity(pem).fingerprint);
108
+ if (new Set(roots).size !== roots.length) fail('INVALID_CONFIGURATION');
109
+ return Object.freeze({ baseUrl, apiKey: input.apiKey, orgId: input.orgId, agentId: input.agentId,
110
+ keyId: input.keyId, privateKeyBase64: input.privateKeyBase64, signatureMode: 'required',
111
+ guardFailureMode: 'block', timeoutMs, issuerPublicKey: input.issuerPublicKey ?? null, trustedIssuerPublicKeys });
112
+ }
113
+
114
+ export function inspectCapabilities(input) {
115
+ const value = snapshot(input, 'INVALID_CAPABILITY');
116
+ if (!record(value) || value.profile !== CONTROLLED_TRANSFER_PROFILE || value.scope !== 'controlled-ledger') {
117
+ fail('CAPABILITY_MISMATCH');
118
+ }
119
+ if (value.installed !== true || typeof value.configured !== 'boolean' || typeof value.resourceEnforced !== 'boolean'
120
+ || !record(value.qualification) || !QUALIFICATIONS.includes(value.qualification.status)
121
+ || !(value.issuerPublicKey === null || typeof value.issuerPublicKey === 'string')
122
+ || (value.configured && !value.issuerPublicKey)) fail('INVALID_CAPABILITY');
123
+ if (value.issuerPublicKey !== null) issuerIdentity(value.issuerPublicKey, 'INVALID_CAPABILITY');
124
+ if (value.executionTransport !== undefined && value.executionTransport !== 'bound-reference-v1') fail('INVALID_CAPABILITY');
125
+ if (!Object.hasOwn(value, 'leaseFormats')) {
126
+ return Object.freeze({ ...value, leaseFormats: Object.freeze({ supported: Object.freeze([CONTROLLED_TRANSFER_PROFILE]),
127
+ default: CONTROLLED_TRANSFER_PROFILE, compactIssuanceEnabled: false }) });
128
+ }
129
+ const formats = value.leaseFormats;
130
+ if (!record(formats) || Object.keys(formats).length !== 3
131
+ || !['supported', 'default', 'compactIssuanceEnabled'].every(key => Object.hasOwn(formats, key))
132
+ || !Array.isArray(formats.supported) || ![1, 2].includes(formats.supported.length)
133
+ || formats.supported[0] !== CONTROLLED_TRANSFER_PROFILE
134
+ || (formats.supported.length === 2 && formats.supported[1] !== COMPACT_TRANSFER_LEASE_PROFILE)
135
+ || formats.default !== CONTROLLED_TRANSFER_PROFILE || typeof formats.compactIssuanceEnabled !== 'boolean'
136
+ || (formats.compactIssuanceEnabled && formats.supported.length !== 2)) fail('INVALID_CAPABILITY');
137
+ return value;
138
+ }
139
+
140
+ export function prepareLeaseFormat(options) {
141
+ if (options === undefined) return CONTROLLED_TRANSFER_PROFILE;
142
+ const code = 'INVALID_PREPARE_OPTIONS', value = snapshot(options, code);
143
+ if (!record(value) || Object.keys(value).some(key => key !== 'leaseFormat')
144
+ || (Object.hasOwn(value, 'leaseFormat')
145
+ && ![CONTROLLED_TRANSFER_PROFILE, COMPACT_TRANSFER_LEASE_PROFILE].includes(value.leaseFormat))) fail(code);
146
+ return Object.hasOwn(value, 'leaseFormat') ? value.leaseFormat : CONTROLLED_TRANSFER_PROFILE;
147
+ }
148
+
149
+ export function reviewFields(prepared, baseUrl) {
150
+ const actionId = prepared?.actionId ?? null;
151
+ return { actionId, reviewUrl: actionId ? `${baseUrl}/approvals?action=${encodeURIComponent(actionId)}` : null,
152
+ retryAutomatically: false };
153
+ }
@@ -0,0 +1,103 @@
1
+ import { createControlledTransfers } from './client.mjs';
2
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, ControlledTransferError, fail,
3
+ identifier, record, snapshot } from './contract.mjs';
4
+ import { snapshotWithProjection } from './projection.mjs';
5
+
6
+ const instructions = 'Only the Matoi controlled-ledger transfer profile is covered, not arbitrary MCP tools or direct resource access. '
7
+ + 'Financial transfers require native Studio review on the slow-approved route. Preparation and status never execute. '
8
+ + 'Do not auto-approve or resend mutations. OUTCOME_UNKNOWN requires status-only recovery with the original operation ID. '
9
+ + 'Projection freshness describes only the derived evidence view, never execution authority. '
10
+ + 'A pending, stale, failed or unavailable view does not invalidate a verified receipt or permit resending.';
11
+ const idSchema = { type: 'string', minLength: 1, maxLength: 128, pattern: '^[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}$' };
12
+ const tool = (name, description, properties, required, readOnly = false) => ({ name, description,
13
+ inputSchema: { type: 'object', properties, required, additionalProperties: false },
14
+ annotations: { readOnlyHint: readOnly, destructiveHint: name === 'osuite_transfer_execute', idempotentHint: readOnly } });
15
+ const tools = snapshot([
16
+ tool('osuite_transfer_prepare', 'Prepare one signed controlled-ledger transfer operation for native Studio review. Never executes or approves.',
17
+ { operationId: idSchema, grantId: idSchema }, ['operationId', 'grantId']),
18
+ tool('osuite_transfer_execute', 'Explicitly request one ordinal of the exact signed preparation. The server enforces native approval; never retry automatically.',
19
+ { prepared: { type: 'object', description: 'The unchanged signed preparation returned by prepare or verified status recovery.' },
20
+ ordinal: { type: 'integer', minimum: 0, maximum: 63, default: 0 } }, ['prepared']),
21
+ tool('osuite_transfer_status', 'Read the original operation and verify available signed evidence. No preparation, approval, execution or automatic retry.',
22
+ { operationId: idSchema }, ['operationId'], true),
23
+ ]);
24
+
25
+ const preparationFields = ['profile', 'operationId', 'grantId', 'preparationDigest', 'actionId', 'fingerprint',
26
+ 'lease', 'effects', 'state', 'code', 'reviewUrl', 'retryAutomatically'];
27
+ const publicFields = [...preparationFields, 'receipt', 'newlyCommitted', 'lastDenial', 'reason', 'httpStatus', 'recovery'];
28
+ const effectFields = ['operation', 'paymentId', 'sourceAccount', 'destination', 'asset', 'network', 'amountMinor', 'decimals'];
29
+ function select(value, keys) {
30
+ return Object.fromEntries(keys.filter(key => Object.hasOwn(value, key)).map(key => [key, value[key]]));
31
+ }
32
+
33
+ function publicResult(value, executing) {
34
+ // Do not echo configuration, arbitrary server metadata or caller arguments into the model context.
35
+ const result = select(value, publicFields);
36
+ if (value.effects) result.effects = value.effects.map(effect => select(effect, effect.operation === 'transfer'
37
+ ? effectFields : ['ordinal', 'paymentId', 'state', 'receipt', 'receiptVerified']));
38
+ if (value.prepared) result.prepared = select(value.prepared, preparationFields);
39
+ result.effect_executed = value.state === 'unknown' || value.code === 'OUTCOME_UNKNOWN'
40
+ ? null : executing && value.state === 'committed' && value.newlyCommitted === true;
41
+ result.retryAutomatically = false;
42
+ return snapshotWithProjection({ ...result, projection: value.projection });
43
+ }
44
+
45
+ function response(value, executing = false) {
46
+ const data = publicResult(value, executing);
47
+ return Object.freeze({ content: Object.freeze([Object.freeze({ type: 'text', text: JSON.stringify(data) })]),
48
+ structuredContent: data, ...(['denied', 'unknown', 'rejected'].includes(data.state) ? { isError: true } : {}) });
49
+ }
50
+
51
+ export function createControlledTransferMcpServer(config) {
52
+ const client = createControlledTransfers({ config });
53
+
54
+ async function callTool(name, args = {}) {
55
+ try {
56
+ const definition = tools.find(item => item.name === name);
57
+ if (!definition) fail('UNKNOWN_TOOL');
58
+ args = snapshot(args, 'INVALID_TOOL_ARGUMENTS');
59
+ if (!record(args) || Object.keys(args).some(key => !Object.hasOwn(definition.inputSchema.properties, key))
60
+ || definition.inputSchema.required.some(key => !Object.hasOwn(args, key))) fail('INVALID_TOOL_ARGUMENTS');
61
+ if (name === 'osuite_transfer_execute') {
62
+ if (!record(args.prepared)) fail('INVALID_PREPARATION');
63
+ return response(await client.execute(args.prepared, args.ordinal), true);
64
+ }
65
+ if (!identifier(args.operationId)) fail('INVALID_OPERATION_ID');
66
+ if (name === 'osuite_transfer_prepare') {
67
+ if (!identifier(args.grantId)) fail('INVALID_GRANT_ID');
68
+ return response(await client.prepare(args.operationId, args.grantId));
69
+ }
70
+ return response(await client.status(args.operationId));
71
+ } catch (error) {
72
+ const known = error instanceof ControlledTransferError;
73
+ const code = known ? error.code : 'REQUEST_FAILED';
74
+ return response({ profile: PROFILE, operationId: known ? error.operationId : null,
75
+ state: code === 'OUTCOME_UNKNOWN' ? 'unknown' : 'rejected', code, newlyCommitted: false,
76
+ ...(known ? { reason: error.reason, httpStatus: error.httpStatus, recovery: error.recovery } : {}) });
77
+ }
78
+ }
79
+
80
+ const listTools = () => Object.freeze({ tools });
81
+ async function handleRequest(input) {
82
+ let request;
83
+ try { request = snapshot(input, 'INVALID_REQUEST'); } catch { /* Return a protocol error without echoing input. */ }
84
+ if (!record(request) || request.jsonrpc !== '2.0' || typeof request.method !== 'string'
85
+ || (Object.hasOwn(request, 'id') && request.id !== null && typeof request.id !== 'string' && !Number.isSafeInteger(request.id))) {
86
+ return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } };
87
+ }
88
+ if (!Object.hasOwn(request, 'id')) return null;
89
+ const envelope = { jsonrpc: '2.0', id: request.id };
90
+ if (request.method === 'initialize') return { ...envelope, result: {
91
+ protocolVersion: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25'].includes(request.params?.protocolVersion)
92
+ ? request.params.protocolVersion : '2025-11-25',
93
+ capabilities: { tools: {} }, serverInfo: { name: 'osuite_controlled_transfers', version: '1' }, instructions,
94
+ } };
95
+ if (request.method === 'ping') return { ...envelope, result: {} };
96
+ if (request.method === 'tools/list') return { ...envelope, result: listTools() };
97
+ if (request.method === 'tools/call') return { ...envelope,
98
+ result: await callTool(request.params?.name, request.params?.arguments ?? {}) };
99
+ return { ...envelope, error: { code: -32601, message: 'Method not found' } };
100
+ }
101
+
102
+ return Object.freeze({ tools, listTools, callTool, handleRequest });
103
+ }