osuite 2.11.1 → 2.12.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,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
+ }
@@ -0,0 +1,57 @@
1
+ import { record, snapshot } from './contract.mjs';
2
+
3
+ const PROFILE = 'matoi.controlled-transfer.projection.v1';
4
+ const states = new Set(['current', 'pending_reconciliation', 'stale', 'failed', 'unavailable']);
5
+ const uuid = value => typeof value === 'string'
6
+ && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value);
7
+ const generation = value => typeof value === 'string' && /^(0|[1-9][0-9]{0,18})$/.test(value)
8
+ && BigInt(value) <= 9223372036854775807n;
9
+ const timestamp = value => typeof value === 'string' && value.length === 24
10
+ && Number.isFinite(Date.parse(value)) && new Date(value).toISOString() === value;
11
+ const errorCode = value => typeof value === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(value);
12
+ const fields = { incarnation: uuid, requestedGeneration: generation, projectedGeneration: generation,
13
+ artifactIncarnation: uuid, artifactGeneration: generation, generatedAt: timestamp, observedAt: timestamp,
14
+ lastError: errorCode };
15
+ const unavailable = Object.freeze({ profile: PROFILE, state: 'unavailable', scope: 'derived-view',
16
+ incarnation: null, requestedGeneration: null, projectedGeneration: null, artifactIncarnation: null,
17
+ artifactGeneration: null, generatedAt: null, observedAt: null, lastError: null, authorizesExecution: false });
18
+
19
+ export function normalizeProjection(value, { cached = false } = {}) {
20
+ if (!record(value)) return unavailable;
21
+ // Inspect only public scalar fields; auxiliary graphs, accessors and debug data
22
+ // must not participate in receipt validation or enter the model context.
23
+ const read = key => {
24
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
25
+ return descriptor ? descriptor.enumerable && Object.hasOwn(descriptor, 'value') ? descriptor.value : undefined : null;
26
+ };
27
+ const state = read('state');
28
+ if (read('profile') !== PROFILE || read('scope') !== 'derived-view'
29
+ || read('authorizesExecution') !== false || !states.has(state)) return unavailable;
30
+ const result = { ...unavailable, state };
31
+ for (const [key, valid] of Object.entries(fields)) {
32
+ const field = read(key);
33
+ if (field !== null && !valid(field)) return unavailable;
34
+ result[key] = field;
35
+ }
36
+ if (state !== 'unavailable' && result.observedAt === null) return unavailable;
37
+ // Check only wire consistency; canonical UTC timestamps sort chronologically.
38
+ if (state === 'current') {
39
+ if (result.incarnation === null || result.incarnation !== result.artifactIncarnation
40
+ || result.requestedGeneration === null || result.requestedGeneration === '0'
41
+ || result.requestedGeneration !== result.projectedGeneration || result.projectedGeneration !== result.artifactGeneration
42
+ || result.generatedAt === null || result.generatedAt > result.observedAt) return unavailable;
43
+ if (cached) result.state = 'stale';
44
+ }
45
+ return Object.freeze(result);
46
+ }
47
+
48
+ export function snapshotWithProjection(value, code) {
49
+ if (!record(value)) return snapshot(value, code);
50
+ const descriptors = Object.getOwnPropertyDescriptors(value);
51
+ const projection = normalizeProjection(descriptors.projection?.value);
52
+ delete descriptors.projection;
53
+ // Freshness has its own fixed bound and cannot spend the resource snapshot's
54
+ // byte/node budget. Keep all other descriptors subject to the existing checks.
55
+ const resource = snapshot(Object.defineProperties(Object.create(Object.getPrototypeOf(value)), descriptors), code);
56
+ return Object.freeze({ ...resource, projection });
57
+ }
@@ -0,0 +1,191 @@
1
+ import { verify } from 'node:crypto';
2
+ import { canonicalJson, sha256 } from '../runtime/protocol.mjs';
3
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, COMPACT_TRANSFER_LEASE_PROFILE as COMPACT,
4
+ TRANSFER_PASS_BUILDER_PROFILE, RECEIPT_PROFILE, digest, fail,
5
+ identifier, issuerIdentity, record, snapshot } from './contract.mjs';
6
+
7
+ const leaseFields = ['profile', 'id', 'orgId', 'actorId', 'keyId', 'grantId', 'operationId',
8
+ 'grantEpoch', 'authorityEpoch', 'issuedAt', 'expiresAt', 'issuer', 'workflowDigest',
9
+ 'evidenceDigest', 'effectDigests', 'context'];
10
+ const compactLeaseFields = [...leaseFields, 'transferProfile', 'passBuilder', 'passCommitments'];
11
+ const receiptFields = ['profile', 'issuer', 'receiptId', 'orgId', 'actorId', 'grantId', 'operationId',
12
+ 'ordinal', 'actionId', 'actionFingerprint', 'preparationDigest', 'authorityEpoch', 'grantEpoch',
13
+ 'effect', 'effectDigest', 'committedAt', 'state', 'evidenceDigest'];
14
+ const effectIds = ['paymentId', 'sourceAccount', 'destination', 'asset', 'network'];
15
+ const epoch = value => typeof value === 'string' && /^(0|[1-9][0-9]{0,37})$/.test(value);
16
+ const time = value => Number.isSafeInteger(value) && value >= 0;
17
+ const approvalFingerprint = value => typeof value === 'string' && /^(?:apfp_)?[a-f0-9]{64}$/.test(value);
18
+
19
+ function exact(value, keys, code, optional = []) {
20
+ if (!record(value) || keys.some(key => !Object.hasOwn(value, key))
21
+ || Object.keys(value).some(key => !keys.includes(key) && !optional.includes(key))) fail(code);
22
+ }
23
+
24
+ function checkedEffect(effect, code) {
25
+ exact(effect, ['operation', ...effectIds, 'amountMinor', 'decimals'], code);
26
+ if (effect.operation !== 'transfer' || effectIds.some(field => !identifier(effect[field]))
27
+ || typeof effect.amountMinor !== 'string' || !/^[1-9][0-9]{0,37}$/.test(effect.amountMinor)
28
+ || !Number.isInteger(effect.decimals) || effect.decimals < 0 || effect.decimals > 18) fail(code);
29
+ return effect;
30
+ }
31
+
32
+ // Finance's v1 domain separation; money stays a canonical integer string.
33
+ function effectDigest(effect, code) {
34
+ return sha256(canonicalJson([PROFILE, 'effect', checkedEffect(effect, code)]));
35
+ }
36
+
37
+ function signedPayload(envelope, issuer, fields, code, optional = []) {
38
+ exact(envelope, ['payload', 'signature'], code);
39
+ exact(envelope.payload, fields, code, optional);
40
+ if (!issuer || envelope.payload.issuer !== issuer.fingerprint
41
+ || typeof envelope.signature !== 'string' || !/^[A-Za-z0-9_-]{86}$/.test(envelope.signature)) fail(code);
42
+ const bytes = Buffer.from(envelope.signature, 'base64url');
43
+ if (bytes.length !== 64 || bytes.toString('base64url') !== envelope.signature) fail(code);
44
+ let valid = false;
45
+ try { valid = verify(null, Buffer.from(canonicalJson(envelope.payload)), issuer.key, bytes); } catch { /* Fail closed. */ }
46
+ if (!valid) fail(code);
47
+ return envelope.payload;
48
+ }
49
+
50
+ function verificationIssuer(envelope, issuer, config, historical) {
51
+ if (!historical || envelope?.payload?.issuer === issuer?.fingerprint) return issuer;
52
+ // Explicit caller configuration alone extends historical trust. A response's
53
+ // embedded public key or advertised key list is never a trust root.
54
+ return (config.trustedIssuerPublicKeys ?? []).map(pem => issuerIdentity(pem))
55
+ .find(key => key.fingerprint === envelope?.payload?.issuer) ?? null;
56
+ }
57
+
58
+ function verifyGate(payload, source, code) {
59
+ const lease = source?.lease.payload, compact = lease?.profile === COMPACT;
60
+ if (!Object.hasOwn(payload, 'gate')) {
61
+ if (compact) fail(code);
62
+ return;
63
+ }
64
+ const gate = payload.gate;
65
+ exact(gate, ['lane', 'admissionSequence', 'coreReceipt'], code);
66
+ if (gate.lane !== 'slow-approved' || !epoch(gate.admissionSequence)) fail(code);
67
+ exact(gate.coreReceipt, ['schema_version', 'pass_id', 'pass_hash', 'action_fingerprint',
68
+ 'lane', 'decision', 'reason', 'observed_at', 'sequence_number', 'receipt_hash'], code);
69
+ const { receipt_hash: receiptHash, ...core } = gate.coreReceipt;
70
+ const observedAt = Date.parse(core.observed_at);
71
+ if (core.schema_version !== 'osuite.action_pass.receipt.v1' || !identifier(core.pass_id)
72
+ || !digest(core.pass_hash) || !digest(core.action_fingerprint) || !digest(receiptHash)
73
+ || receiptHash !== sha256(canonicalJson(core)) || core.lane !== 'slow' || core.decision !== 'review'
74
+ || core.reason !== 'risk_exceeds_fast_lane' || core.sequence_number !== payload.ordinal
75
+ || typeof core.observed_at !== 'string' || !time(observedAt)
76
+ || new Date(observedAt).toISOString() !== core.observed_at || observedAt > payload.committedAt) fail(code);
77
+ if (lease) {
78
+ if (observedAt < lease.issuedAt) fail(code);
79
+ if (compact) {
80
+ const entry = lease.passCommitments?.[payload.ordinal];
81
+ if (!entry || core.pass_id !== entry.passId || core.pass_hash !== entry.passHash
82
+ || core.action_fingerprint !== entry.actionFingerprint) fail(code);
83
+ } else {
84
+ const pass = lease.passes?.[payload.ordinal];
85
+ if (pass && (core.pass_id !== pass.pass_id || core.pass_hash !== pass.pass_hash
86
+ || core.action_fingerprint !== pass.action_binding?.allowed_fingerprint)) fail(code);
87
+ }
88
+ }
89
+ }
90
+
91
+ function verifyCompactPayload(payload, count, code) {
92
+ if (payload.transferProfile !== PROFILE || payload.passBuilder !== TRANSFER_PASS_BUILDER_PROFILE
93
+ || ['orgId', 'actorId', 'keyId', 'grantId', 'operationId'].some(key =>
94
+ !identifier(payload[key]) || !/^[A-Za-z0-9]/.test(payload[key]))
95
+ || !Number.isFinite(new Date(payload.issuedAt).getTime()) || !Number.isFinite(new Date(payload.expiresAt).getTime())
96
+ || payload.expiresAt - payload.issuedAt > 300000
97
+ || payload.context.artifact_sha256 !== payload.workflowDigest
98
+ || payload.context.dependencies_sha256 !== payload.evidenceDigest
99
+ || !Array.isArray(payload.passCommitments) || payload.passCommitments.length !== count) fail(code);
100
+ const hashes = new Set();
101
+ for (const entry of payload.passCommitments) {
102
+ exact(entry, ['passHash', 'passId', 'actionFingerprint'], code);
103
+ if (!digest(entry.passHash) || !digest(entry.actionFingerprint)
104
+ || typeof entry.passId !== 'string' || !/^ap_[a-f0-9]{24}$/.test(entry.passId)
105
+ || hashes.has(entry.passHash)) fail(code);
106
+ hashes.add(entry.passHash);
107
+ }
108
+ }
109
+
110
+ export function verifyPreparation(input, { config, issuer, operationId, grantId, checkExpiry = true, historical = false }) {
111
+ const code = 'INVALID_PREPARATION', value = snapshot(input, code);
112
+ if (!record(value) || value.profile !== PROFILE || value.operationId !== operationId || value.grantId !== grantId
113
+ || !identifier(operationId) || !identifier(grantId)
114
+ || !['awaiting_approval', 'preparing', 'denied'].includes(value.state)
115
+ || (value.code !== undefined && !identifier(value.code))
116
+ || !digest(value.preparationDigest) || !Array.isArray(value.effects)
117
+ || value.effects.length < 1 || value.effects.length > 64) fail(code);
118
+ if (value.state !== 'preparing' ? !identifier(value.actionId) || !approvalFingerprint(value.fingerprint)
119
+ : !((value.actionId === null && value.fingerprint === null) || (identifier(value.actionId) && approvalFingerprint(value.fingerprint)))) fail(code);
120
+ const compact = value.lease?.payload?.profile === COMPACT;
121
+ const payload = signedPayload(value.lease, verificationIssuer(value.lease, issuer, config, historical),
122
+ compact ? compactLeaseFields : leaseFields, code, compact ? [] : ['passes']);
123
+ if (payload.profile !== (compact ? COMPACT : PROFILE) || payload.orgId !== config.orgId || payload.actorId !== config.agentId
124
+ || !identifier(payload.id) || !identifier(payload.keyId) || (config.keyId && payload.keyId !== config.keyId)
125
+ || payload.operationId !== operationId || payload.grantId !== grantId
126
+ || !epoch(payload.grantEpoch) || !epoch(payload.authorityEpoch)
127
+ || !time(payload.issuedAt) || !time(payload.expiresAt) || payload.expiresAt <= payload.issuedAt
128
+ || payload.issuedAt > Date.now() + 30000 || (checkExpiry && payload.expiresAt <= Date.now())
129
+ || !digest(payload.workflowDigest) || !digest(payload.evidenceDigest)
130
+ || !Array.isArray(payload.effectDigests) || payload.effectDigests.length !== value.effects.length
131
+ || payload.effectDigests.some(item => !digest(item))
132
+ || value.preparationDigest !== sha256(canonicalJson(payload))) fail(code);
133
+ exact(payload.context, ['artifact_sha256', 'config_sha256', 'dependencies_sha256'], code);
134
+ if (Object.values(payload.context).some(item => !digest(item))) fail(code);
135
+ if (compact) verifyCompactPayload(payload, value.effects.length, code);
136
+ // Passes are signed per-effect evidence, not a substitute for native Studio approval.
137
+ if (Object.hasOwn(payload, 'passes') && (!Array.isArray(payload.passes)
138
+ || payload.passes.length !== value.effects.length || payload.passes.some(pass => !record(pass)))) fail(code);
139
+ const payments = new Set();
140
+ for (const [ordinal, effect] of value.effects.entries()) {
141
+ if (effectDigest(effect, code) !== payload.effectDigests[ordinal] || payments.has(effect.paymentId)) fail(code);
142
+ payments.add(effect.paymentId);
143
+ }
144
+ return value;
145
+ }
146
+
147
+ function receiptPreparationBinding(payload, prepared, ordinal, original, code) {
148
+ const lease = prepared.lease.payload;
149
+ if (payload.grantId !== prepared.grantId || payload.effectDigest !== lease.effectDigests[ordinal]
150
+ || canonicalJson(payload.effect) !== canonicalJson(prepared.effects[ordinal])) fail(code);
151
+ if (original && (payload.issuer !== lease.issuer || payload.preparationDigest !== prepared.preparationDigest
152
+ || payload.actionFingerprint !== prepared.fingerprint || payload.evidenceDigest !== lease.evidenceDigest
153
+ || payload.authorityEpoch !== lease.authorityEpoch || payload.grantEpoch !== lease.grantEpoch
154
+ || payload.committedAt < lease.issuedAt || payload.committedAt >= lease.expiresAt)) fail(code);
155
+ }
156
+
157
+ export function verifyReceipt(input, { issuer, config, prepared, sourcePrepared, ordinal, historical = false,
158
+ operationId = prepared?.operationId, actionId = prepared?.actionId, paymentId = prepared?.effects[ordinal]?.paymentId }) {
159
+ const code = 'INVALID_RECEIPT', value = snapshot(input, code);
160
+ const payload = signedPayload(value, verificationIssuer(value, issuer, config, historical), receiptFields, code, ['gate']);
161
+ if (payload.profile !== RECEIPT_PROFILE || payload.state !== 'committed'
162
+ || payload.orgId !== config.orgId || payload.actorId !== config.agentId
163
+ || ['receiptId', 'orgId', 'actorId', 'grantId', 'operationId', 'actionId'].some(key => !identifier(payload[key]))
164
+ || !approvalFingerprint(payload.actionFingerprint)
165
+ || ['preparationDigest', 'effectDigest', 'evidenceDigest'].some(key => !digest(payload[key]))
166
+ || !epoch(payload.authorityEpoch) || !epoch(payload.grantEpoch)
167
+ || !Number.isSafeInteger(payload.ordinal) || payload.ordinal < 0 || payload.ordinal > 63
168
+ || !time(payload.committedAt) || payload.committedAt > Date.now() + 30000
169
+ || payload.effectDigest !== effectDigest(payload.effect, code) || payload.effect.paymentId !== paymentId) fail(code);
170
+ const earlierOperation = historical && payload.operationId !== operationId;
171
+ let source = earlierOperation ? null : prepared;
172
+ if (sourcePrepared != null) {
173
+ try {
174
+ source = verifyPreparation(sourcePrepared, { config, issuer, operationId: payload.operationId,
175
+ grantId: payload.grantId, checkExpiry: false, historical });
176
+ } catch { fail(code); }
177
+ receiptPreparationBinding(payload, source, payload.ordinal, true, code);
178
+ if (payload.actionId !== source.actionId) fail(code);
179
+ }
180
+ // An earlier operation's gate is bound only to its own known source, never to
181
+ // the current operation's ordinal. No source means signature/effect checks only.
182
+ verifyGate(payload, source, code);
183
+ if (prepared) {
184
+ receiptPreparationBinding(payload, prepared, ordinal, !earlierOperation, code);
185
+ } else if (earlierOperation) {
186
+ // A cold status read has no signed current lease to bind a historical payment.
187
+ fail(code);
188
+ }
189
+ if (!earlierOperation && (payload.operationId !== operationId || payload.ordinal !== ordinal || payload.actionId !== actionId)) fail(code);
190
+ return value;
191
+ }
@@ -0,0 +1,38 @@
1
+ import { createControlledTransferMcpServer } from './controlled-transfers/mcp.mjs';
2
+ import { CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES as MAX_FRAME_BYTES } from './controlled-transfers/contract.mjs';
3
+
4
+ const MAX_BUFFER_BYTES = 2 * MAX_FRAME_BYTES;
5
+
6
+ export async function runControlledTransferStdio(config, { input = process.stdin, output = process.stdout } = {}) {
7
+ const server = createControlledTransferMcpServer(config);
8
+ const write = payload => new Promise((resolve, reject) => {
9
+ if (payload === null) { resolve(); return; }
10
+ output.write(`${JSON.stringify(payload)}\n`, error => error ? reject(error) : resolve());
11
+ });
12
+ async function invalid(code, message) {
13
+ await write({ jsonrpc: '2.0', id: null, error: { code, message } });
14
+ return false;
15
+ }
16
+ async function dispatch(frame) {
17
+ if (frame.length > MAX_FRAME_BYTES) return invalid(-32600, 'Frame too large');
18
+ let request;
19
+ try { request = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(frame)); }
20
+ catch { return invalid(-32700, 'Parse error'); }
21
+ await write(await server.handleRequest(request));
22
+ return true;
23
+ }
24
+ let buffer = Buffer.alloc(0);
25
+ for await (const chunk of input) {
26
+ if (buffer.length + chunk.length > MAX_BUFFER_BYTES) return invalid(-32600, 'Input buffer limit exceeded');
27
+ buffer = Buffer.concat([buffer, chunk]);
28
+ let end;
29
+ // Await each request and output before consuming the next frame; no background mutation queue.
30
+ while ((end = buffer.indexOf(10)) !== -1) {
31
+ const frame = buffer.subarray(0, end);
32
+ buffer = buffer.subarray(end + 1);
33
+ if (!await dispatch(frame)) return false;
34
+ }
35
+ if (buffer.length > MAX_FRAME_BYTES) return invalid(-32600, 'Frame too large');
36
+ }
37
+ return buffer.length ? dispatch(buffer) : true;
38
+ }
@@ -0,0 +1,4 @@
1
+ export { createControlledTransfers } from './controlled-transfers/client.mjs';
2
+ export { createControlledTransferMcpServer } from './controlled-transfers/mcp.mjs';
3
+ export { ControlledTransferError, CONTROLLED_TRANSFER_PROFILE,
4
+ CONTROLLED_TRANSFER_MAX_ENVELOPE_BYTES } from './controlled-transfers/contract.mjs';
@@ -112,6 +112,7 @@ export function createStudioAuthority(config, journalPath) {
112
112
  reject(claimed ? 'OUTCOME_UNKNOWN' : 'CURRENT_AUTHORITY_UNAVAILABLE');
113
113
  } catch (error) {
114
114
  if (claimed) settle(phase === 'redeeming' ? 'uncertain_redemption' : 'uncertain_request');
115
+ if (!claimed && error?.name === 'OperationJournalError' && error.code === 'JOURNAL_BUSY') reject('JOURNAL_BUSY');
115
116
  throw error;
116
117
  }
117
118
  }
@@ -140,6 +140,12 @@ export function createGovernedTools({ config: rawConfig, namespace, journalPath,
140
140
  reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
141
141
  }
142
142
  if (!journal.settle(scope, operationId, owner, admitted.phase, 'dispatching')) reject('OPERATION_BUSY', status(local(operationId)));
143
+ // Durable local I/O can outlive the admission, even without an await.
144
+ if (aborted() || closed || performance.now() - admitted.receivedAt > 5000) {
145
+ try { journal.settle(scope, operationId, owner, 'dispatching', 'uncertain'); }
146
+ catch { /* The committed dispatch fence still forbids replay if cleanup cannot write. */ }
147
+ reject(aborted() ? 'ABORTED' : 'OUTCOME_UNKNOWN', status(local(operationId)));
148
+ }
143
149
  let result, resultDigest = null, state = 'completed', thrown = false;
144
150
  try { result = await execute(invocation.params); }
145
151
  catch { thrown = true; state = 'uncertain'; }
@@ -198,7 +198,7 @@ export class OperationJournal {
198
198
  const config = dataObject(options, ['maxOperations', 'busyTimeoutMs', 'create'], 'JOURNAL_CONFIG');
199
199
  const create = config.create === undefined ? true : config.create;
200
200
  this.#maxOperations = config.maxOperations === undefined ? 10000 : config.maxOperations;
201
- this.#busyTimeoutMs = config.busyTimeoutMs === undefined ? 100 : config.busyTimeoutMs;
201
+ this.#busyTimeoutMs = config.busyTimeoutMs === undefined ? 1000 : config.busyTimeoutMs;
202
202
  if (typeof create !== 'boolean' || !Number.isSafeInteger(this.#maxOperations) || this.#maxOperations < 1
203
203
  || !Number.isSafeInteger(this.#busyTimeoutMs) || this.#busyTimeoutMs < 0 || this.#busyTimeoutMs > 5000) fail('JOURNAL_CONFIG');
204
204
  if (typeof path !== 'string' || !isAbsolute(path) || path.length > 4096 || path.includes('\0')
@@ -0,0 +1,44 @@
1
+ import { createControlledTransfers } from './controlled-transfers.mjs';
2
+ import { CONTROLLED_TRANSFER_PROFILE as PROFILE, QUALIFICATIONS, snapshot } from './controlled-transfers/contract.mjs';
3
+
4
+ export async function probeMatoiStatus({ config } = {}) {
5
+ const result = { profile: PROFILE, installed: true, localConfigured: false, configured: false,
6
+ capabilityAvailable: false, serverInstalled: null, serverConfigured: null,
7
+ scope: null, resourceEnforced: null, qualification: null, qualificationSource: null,
8
+ nodeVersion: process.versions.node, requiredNodeMajor: 24, code: null };
9
+ try {
10
+ const client = createControlledTransfers({ config });
11
+ result.localConfigured = true;
12
+ const capability = await client.capabilities();
13
+ return snapshot({ ...result, capabilityAvailable: true, serverInstalled: capability.installed,
14
+ serverConfigured: capability.configured, configured: capability.configured && capability.resourceEnforced,
15
+ scope: capability.scope, resourceEnforced: capability.resourceEnforced,
16
+ qualification: capability.qualification, qualificationSource: 'authenticated-capability' });
17
+ } catch (error) {
18
+ return snapshot({ ...result, code: error.code ?? 'PROBE_FAILED' });
19
+ }
20
+ }
21
+
22
+ export function formatMatoiStatus(input) {
23
+ let status;
24
+ try { status = snapshot(input); } catch { status = {}; }
25
+ const yesNo = value => value === true ? 'yes' : value === false ? 'no' : 'unknown';
26
+ const authenticated = status?.profile === PROFILE && status.capabilityAvailable === true
27
+ && status.qualificationSource === 'authenticated-capability';
28
+ const qualification = authenticated && QUALIFICATIONS.includes(status.qualification?.status)
29
+ ? `${status.qualification.status} (server-reported)` : 'unknown (not verified)';
30
+ const code = typeof status?.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(status.code) ? status.code : null;
31
+ return [
32
+ 'Matoi Controlled Transfers',
33
+ `SDK installed: ${yesNo(status?.installed)}`,
34
+ `Local strict configuration: ${yesNo(status?.localConfigured)}`,
35
+ `Profile configured: ${yesNo(authenticated ? status.serverConfigured : null)}`,
36
+ `Resource scope: ${authenticated && status.scope === 'controlled-ledger' ? 'controlled-ledger' : 'unknown'}`,
37
+ `Resource enforced: ${yesNo(authenticated ? status.resourceEnforced : null)}`,
38
+ `Qualification: ${qualification}`,
39
+ ...(code ? [`Diagnostic: ${code}`] : []),
40
+ 'Installing the SDK alone does not establish full-stack deployment protection.',
41
+ 'Ordinary SDK/Hook behavior is unchanged. Native Studio review is required.',
42
+ 'This probe only reads capabilities; it never prepares, approves or executes a transfer.',
43
+ ].join('\n');
44
+ }