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.
- package/CONTROLLED_TRANSFERS.md +652 -0
- package/GOVERNED_TOOLS.md +1 -1
- package/README.md +19 -3
- package/cli.js +86 -6
- package/controlled-transfers/cli-config.mjs +89 -0
- package/controlled-transfers/client.mjs +395 -0
- package/controlled-transfers/contract.mjs +153 -0
- package/controlled-transfers/mcp.mjs +103 -0
- package/controlled-transfers/projection.mjs +57 -0
- package/controlled-transfers/verification.mjs +191 -0
- package/controlled-transfers-stdio.mjs +38 -0
- package/controlled-transfers.mjs +4 -0
- package/credentials.js +5 -1
- package/governed-tools/journal.mjs +9 -3
- package/matoiDoctor.mjs +44 -0
- package/nativeDoctor.mjs +83 -0
- package/package.json +10 -1
|
@@ -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';
|
package/credentials.js
CHANGED
|
@@ -164,8 +164,12 @@ export function prepareCredentialFile(projectRoot, relativePath) {
|
|
|
164
164
|
return target;
|
|
165
165
|
}
|
|
166
166
|
|
|
167
|
-
export function writeCredentialFile(projectRoot, relativePath, body) {
|
|
167
|
+
export function writeCredentialFile(projectRoot, relativePath, body, options = {}) {
|
|
168
168
|
const target = prepareCredentialFile(projectRoot, relativePath);
|
|
169
|
+
// Interactive callers must not adopt a newer operator edit at this handoff.
|
|
170
|
+
if (Object.hasOwn(options, 'expectedStat') && !sameFile(options.expectedStat, target.stat)) {
|
|
171
|
+
throw new Error('Credential destination changed since it was read; refusing to replace it.');
|
|
172
|
+
}
|
|
169
173
|
atomicWrite(target, String(body), 0o600, { credential: true });
|
|
170
174
|
return { relativePath: target.relativePath, status: 'written' };
|
|
171
175
|
}
|
|
@@ -99,8 +99,8 @@ function maybeStat(path) {
|
|
|
99
99
|
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
function checkFile(stat) {
|
|
103
|
-
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !==
|
|
102
|
+
function checkFile(stat, expectedLinks = 1) {
|
|
103
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== expectedLinks
|
|
104
104
|
|| stat.uid !== process.getuid() || (stat.mode & 0o077)) fail('JOURNAL_PERMISSIONS');
|
|
105
105
|
}
|
|
106
106
|
|
|
@@ -258,7 +258,13 @@ export class OperationJournal {
|
|
|
258
258
|
const current = privateDirectory(this.#directory.path, false);
|
|
259
259
|
if (!sameFile(current.stat, this.#directory.stat)) fail('JOURNAL_PERMISSIONS');
|
|
260
260
|
for (const suffix of ['', '-wal', '-shm', '-journal']) {
|
|
261
|
-
|
|
261
|
+
let stat = maybeStat(`${this.#path}${suffix}`);
|
|
262
|
+
if (suffix && stat?.nlink === 0) {
|
|
263
|
+
// SQLite can retire a sidecar during lstat. Recheck once, retaining all
|
|
264
|
+
// type, ownership and mode checks on both observations.
|
|
265
|
+
checkFile(stat, 0);
|
|
266
|
+
stat = maybeStat(`${this.#path}${suffix}`);
|
|
267
|
+
}
|
|
262
268
|
if (stat) {
|
|
263
269
|
checkFile(stat);
|
|
264
270
|
if (!suffix && this.#file && !sameFile(stat, this.#file)) fail('JOURNAL_PERMISSIONS');
|
package/matoiDoctor.mjs
ADDED
|
@@ -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
|
+
}
|
package/nativeDoctor.mjs
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { createPrivateKey } from 'node:crypto';
|
|
2
|
+
import { statSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { inspectCredentialFile, readCredentialFile } from './credentials.js';
|
|
5
|
+
import { MCP_ENV_PATH, MCP_MIGRATION_PATH, SDK_ENV_PATH, parseInstallationIdentity } from './installationIdentity.js';
|
|
6
|
+
import { loadRuntimeConfig } from './runtime/config.mjs';
|
|
7
|
+
import { createApiClient, safeId, validatedBaseUrl } from './runtime/protocol.mjs';
|
|
8
|
+
import { resolveRemotePosture } from './runtime/posture.mjs';
|
|
9
|
+
|
|
10
|
+
function fail(code) { throw Object.assign(new Error(code), { code }); }
|
|
11
|
+
function parse(raw) {
|
|
12
|
+
if (Buffer.byteLength(raw) > 65536) fail('INVALID_CREDENTIAL_FILE');
|
|
13
|
+
const env = Object.create(null);
|
|
14
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
15
|
+
if (!line.trim() || line.trim().startsWith('#')) continue;
|
|
16
|
+
const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
|
|
17
|
+
if (!match || Object.hasOwn(env, match[1])) fail('INVALID_CREDENTIAL_FILE');
|
|
18
|
+
let value = match[2];
|
|
19
|
+
if (/^['"]/.test(value)) {
|
|
20
|
+
const quoted = value.match(/^(['"])(.*?)\1(?:\s+#.*)?$/);
|
|
21
|
+
if (!quoted) fail('INVALID_CREDENTIAL_FILE');
|
|
22
|
+
value = quoted[2];
|
|
23
|
+
} else value = value.replace(/\s+#.*$/, '');
|
|
24
|
+
env[match[1]] = value;
|
|
25
|
+
}
|
|
26
|
+
return env;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function loadNativeDoctorConfig({ projectRoot = process.cwd(), runtime, shellEnv = process.env }) {
|
|
30
|
+
if (!['sdk', 'mcp'].includes(runtime)) fail('INVALID_RUNTIME_OPTIONS');
|
|
31
|
+
const envPath = runtime === 'mcp' ? MCP_ENV_PATH : SDK_ENV_PATH;
|
|
32
|
+
try {
|
|
33
|
+
const files = [envPath, `${envPath}.identity.json`, `${envPath}.connect.json`, `${envPath}.connect.lock`, MCP_MIGRATION_PATH];
|
|
34
|
+
const checks = files.map(file => inspectCredentialFile(projectRoot, file));
|
|
35
|
+
if (checks.some(check => !check.safe)) fail('UNSAFE_CREDENTIALS');
|
|
36
|
+
if (checks.some(check => check.exists && /\.connect\.(json|lock)$/.test(check.relativePath))) fail('CONNECTION_RECOVERY_PENDING');
|
|
37
|
+
if (checks.at(-1).exists) fail('MCP_MIGRATION_PENDING');
|
|
38
|
+
if (checks[0].exists && statSync(path.join(projectRoot, envPath)).size > 65536) fail('INVALID_CREDENTIAL_FILE');
|
|
39
|
+
parseInstallationIdentity(readCredentialFile(projectRoot, `${envPath}.identity.json`), runtime);
|
|
40
|
+
const raw = readCredentialFile(projectRoot, envPath);
|
|
41
|
+
// Choose one complete bundle. Never borrow a missing field from another lane.
|
|
42
|
+
const source = raw === null ? shellEnv : parse(raw);
|
|
43
|
+
for (const [name, value] of Object.entries(source)) {
|
|
44
|
+
if (name.startsWith('OSUITE_') && source[name.replace(/^OSUITE_/, 'DASHCLAW_')] !== undefined
|
|
45
|
+
&& value !== source[name.replace(/^OSUITE_/, 'DASHCLAW_')]) fail('CREDENTIAL_SOURCE_CONFLICT');
|
|
46
|
+
}
|
|
47
|
+
for (const field of ['AGENT_ID', 'RUNTIME_ADAPTER_ID']) {
|
|
48
|
+
const value = source[`OSUITE_${field}`] ?? source[`DASHCLAW_${field}`];
|
|
49
|
+
if (typeof value !== 'string' || !value.trim()) fail('INVALID_CONFIGURATION');
|
|
50
|
+
}
|
|
51
|
+
if (Object.hasOwn(source, 'OSUITE_ORG_ID') || Object.hasOwn(source, 'DASHCLAW_ORG_ID')) {
|
|
52
|
+
if (!safeId(source.OSUITE_ORG_ID ?? source.DASHCLAW_ORG_ID)) fail('INVALID_CONFIGURATION');
|
|
53
|
+
}
|
|
54
|
+
const config = loadRuntimeConfig({ env: source, host: runtime, runtimeId: runtime });
|
|
55
|
+
if (config.runtimeId !== runtime || !safeId(config.agentId) || !config.apiKey || !validatedBaseUrl(config.baseUrl)
|
|
56
|
+
|| config.allowInsecureHttp || config.signatureMode !== 'required' || config.ruleRolloutCapability
|
|
57
|
+
|| (config.provider && config.provider !== runtime)) fail('INVALID_CONFIGURATION');
|
|
58
|
+
if (createPrivateKey(Buffer.from(config.privateKeyBase64, 'base64')).asymmetricKeyType !== 'rsa') fail('INVALID_CONFIGURATION');
|
|
59
|
+
return { ...config, provider: runtime };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (/^[A-Z][A-Z0-9_]+$/.test(error?.code || '')) throw error;
|
|
62
|
+
fail('INVALID_CONFIGURATION');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function diagnoseNativeRuntime(options) {
|
|
67
|
+
const config = loadNativeDoctorConfig(options);
|
|
68
|
+
// Diagnostic-only scratch state: no reusable grant/cache is persisted or exposed.
|
|
69
|
+
const values = new Map();
|
|
70
|
+
const store = {
|
|
71
|
+
read: key => values.get(key),
|
|
72
|
+
write: (key, value) => { values.set(key, value); return value; },
|
|
73
|
+
update: (key, fn) => { const value = fn(values.get(key)); values.set(key, value); return value; },
|
|
74
|
+
};
|
|
75
|
+
const remote = await resolveRemotePosture(config, { store, api: createApiClient(config, { maxResponseBytes: 1048576 }) });
|
|
76
|
+
if (!remote.available || remote.blocked || remote.source !== 'remote') fail('CURRENT_POSTURE_UNAVAILABLE');
|
|
77
|
+
if (!['enforce', 'strict'].includes(remote.posture.mode) || !remote.posture.require_signature
|
|
78
|
+
|| remote.posture.on_guard_unavailable !== 'block' || remote.posture.require_assumption_capture
|
|
79
|
+
|| !['enforce', 'strict'].includes(config.mode) || config.guardFailureMode !== 'block') fail('NATIVE_POSTURE_INCOMPATIBLE');
|
|
80
|
+
const orgId = store.read('posture')?.document?.org_id;
|
|
81
|
+
if (!safeId(orgId)) fail('CURRENT_POSTURE_UNAVAILABLE');
|
|
82
|
+
return { runtime: options.runtime, orgId, ready: true };
|
|
83
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "osuite",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.13.0",
|
|
4
4
|
"description": "OSuite governed action SDK for AI agents. Approve, replay, prove, and verify runtime decisions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -22,6 +22,9 @@
|
|
|
22
22
|
},
|
|
23
23
|
"./governed-tools": {
|
|
24
24
|
"import": "./governed-tools.mjs"
|
|
25
|
+
},
|
|
26
|
+
"./controlled-transfers": {
|
|
27
|
+
"import": "./controlled-transfers.mjs"
|
|
25
28
|
}
|
|
26
29
|
},
|
|
27
30
|
"files": [
|
|
@@ -36,6 +39,12 @@
|
|
|
36
39
|
"governed-tools/*.mjs",
|
|
37
40
|
"governed-tools/examples/*.mjs",
|
|
38
41
|
"GOVERNED_TOOLS.md",
|
|
42
|
+
"controlled-transfers.mjs",
|
|
43
|
+
"controlled-transfers-stdio.mjs",
|
|
44
|
+
"controlled-transfers/*.mjs",
|
|
45
|
+
"CONTROLLED_TRANSFERS.md",
|
|
46
|
+
"matoiDoctor.mjs",
|
|
47
|
+
"nativeDoctor.mjs",
|
|
39
48
|
"projectHooks.js",
|
|
40
49
|
"reviewSurface.js",
|
|
41
50
|
"osuite.js",
|