@nexart/mcp-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/CONTRIBUTING.md +56 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +14 -0
  5. package/README.md +340 -2
  6. package/SECURITY.md +76 -0
  7. package/THIRD_PARTY_NOTICES.md +111 -0
  8. package/dist/adapters.d.ts +16 -0
  9. package/dist/adapters.js +48 -0
  10. package/dist/approve-public.d.ts +2 -0
  11. package/dist/approve-public.js +65 -0
  12. package/dist/contracts.d.ts +48 -0
  13. package/dist/contracts.js +34 -0
  14. package/dist/create-confidential.d.ts +2 -0
  15. package/dist/create-confidential.js +34 -0
  16. package/dist/instrumentation/openai-worker.d.ts +1 -0
  17. package/dist/instrumentation/openai-worker.js +26 -0
  18. package/dist/instrumentation/openai.d.ts +51 -0
  19. package/dist/instrumentation/openai.js +197 -0
  20. package/dist/limits.d.ts +15 -0
  21. package/dist/limits.js +62 -0
  22. package/dist/lookup/contracts.d.ts +38 -0
  23. package/dist/lookup/contracts.js +22 -0
  24. package/dist/lookup/verify.d.ts +54 -0
  25. package/dist/lookup/verify.js +110 -0
  26. package/dist/network/client.d.ts +26 -0
  27. package/dist/network/client.js +188 -0
  28. package/dist/network/contracts.d.ts +104 -0
  29. package/dist/network/contracts.js +54 -0
  30. package/dist/network-tools.d.ts +5 -0
  31. package/dist/network-tools.js +32 -0
  32. package/dist/owner/create.d.ts +52 -0
  33. package/dist/owner/create.js +117 -0
  34. package/dist/owner/custody.d.ts +33 -0
  35. package/dist/owner/custody.js +200 -0
  36. package/dist/owner/host.d.ts +10 -0
  37. package/dist/owner/host.js +70 -0
  38. package/dist/owner/publisher.d.ts +21 -0
  39. package/dist/owner/publisher.js +27 -0
  40. package/dist/owner/reconcile.d.ts +16 -0
  41. package/dist/owner/reconcile.js +109 -0
  42. package/dist/receipts/contracts.d.ts +72 -0
  43. package/dist/receipts/contracts.js +33 -0
  44. package/dist/receipts/verify.d.ts +4 -0
  45. package/dist/receipts/verify.js +104 -0
  46. package/dist/record/contracts.d.ts +281 -0
  47. package/dist/record/contracts.js +70 -0
  48. package/dist/record/customer.d.ts +40 -0
  49. package/dist/record/customer.js +99 -0
  50. package/dist/record/policy.d.ts +46 -0
  51. package/dist/record/policy.js +67 -0
  52. package/dist/record/publication.d.ts +23 -0
  53. package/dist/record/publication.js +148 -0
  54. package/dist/record/record.d.ts +12 -0
  55. package/dist/record/record.js +93 -0
  56. package/dist/record/state.d.ts +44 -0
  57. package/dist/record/state.js +84 -0
  58. package/dist/record-tools.d.ts +10 -0
  59. package/dist/record-tools.js +85 -0
  60. package/dist/recover-confidential.d.ts +2 -0
  61. package/dist/recover-confidential.js +13 -0
  62. package/dist/results.d.ts +8 -0
  63. package/dist/results.js +83 -0
  64. package/dist/server.d.ts +2 -0
  65. package/dist/server.js +39 -0
  66. package/dist/stdio.d.ts +2 -0
  67. package/dist/stdio.js +104 -0
  68. package/dist/trust/lifecycle.d.ts +13 -0
  69. package/dist/trust/lifecycle.js +42 -0
  70. package/dist/trust/policy.d.ts +14 -0
  71. package/dist/trust/policy.js +6 -0
  72. package/dist/verify.d.ts +3 -0
  73. package/dist/verify.js +56 -0
  74. package/dist/write/approval.d.ts +5 -0
  75. package/dist/write/approval.js +95 -0
  76. package/dist/write/attest.d.ts +14 -0
  77. package/dist/write/attest.js +140 -0
  78. package/dist/write/config.d.ts +11 -0
  79. package/dist/write/config.js +12 -0
  80. package/dist/write/contracts.d.ts +229 -0
  81. package/dist/write/contracts.js +61 -0
  82. package/dist/write/post.d.ts +11 -0
  83. package/dist/write/post.js +105 -0
  84. package/dist/write/profile.d.ts +19 -0
  85. package/dist/write/profile.js +114 -0
  86. package/dist/write/seal.d.ts +3 -0
  87. package/dist/write/seal.js +49 -0
  88. package/dist/write-tools.d.ts +4 -0
  89. package/dist/write-tools.js +36 -0
  90. package/docs/age-version-compatibility.md +46 -0
  91. package/docs/architecture.md +72 -0
  92. package/docs/compatibility.md +163 -0
  93. package/docs/contracts.md +127 -0
  94. package/docs/examples/customer-claude-desktop.json +14 -0
  95. package/docs/examples/customer-consent.json +15 -0
  96. package/docs/examples/customer-custody.json +8 -0
  97. package/docs/examples/customer-policy.json +43 -0
  98. package/docs/licensing-review.md +109 -0
  99. package/docs/milestone-1-validation.md +110 -0
  100. package/docs/milestone-2.md +291 -0
  101. package/docs/milestone-3.2.md +291 -0
  102. package/docs/milestone-3.md +274 -0
  103. package/docs/milestone-4a.md +221 -0
  104. package/docs/milestone-4b1.md +220 -0
  105. package/docs/milestone-4b2.md +260 -0
  106. package/docs/public-default.md +263 -0
  107. package/docs/recording-schema-compatibility.md +46 -0
  108. package/docs/release.md +311 -0
  109. package/docs/security-fixes.md +47 -0
  110. package/docs/security.md +195 -0
  111. package/docs/standalone-acceptance.md +81 -0
  112. package/docs/validation.md +85 -0
  113. package/package.json +51 -4
  114. package/server.json +20 -0
@@ -0,0 +1,200 @@
1
+ import { constants, openSync, closeSync, writeFileSync, fsyncSync, mkdirSync, readFileSync, fstatSync, realpathSync, statSync, } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { verifyCerV2, verifyConfidentialV2, } from '@nexart/ai-execution';
6
+ import { ownerDirectory, prepareOwnerConfidential } from './create.js';
7
+ import { boundedInput, validV2 } from '../write/profile.js';
8
+ const LIMIT = 262_144;
9
+ const digest = (data) => createHash('sha256').update(data).digest('hex');
10
+ export class EncryptedCustodyError extends Error {
11
+ reasonCode;
12
+ constructor(reasonCode) {
13
+ super(reasonCode);
14
+ this.reasonCode = reasonCode;
15
+ }
16
+ }
17
+ export function checkEncryptedCustody(config) {
18
+ try {
19
+ checkConfiguration(config);
20
+ }
21
+ catch (error) {
22
+ if (error instanceof EncryptedCustodyError)
23
+ throw error;
24
+ throw new EncryptedCustodyError('ENCRYPTED_CUSTODY_CONFIGURATION_REQUIRED');
25
+ }
26
+ }
27
+ /** Stable releases only, with age's optional v prefix. No prerelease/build suffixes. */
28
+ function supportedAgeVersion(output) {
29
+ const match = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(output.trim());
30
+ if (!match)
31
+ return false;
32
+ const major = Number(match[1]), minor = Number(match[2]), patch = Number(match[3]);
33
+ return [major, minor, patch].every(Number.isSafeInteger) &&
34
+ major === 1 && (minor > 2 || (minor === 2 && patch >= 1));
35
+ }
36
+ function checkConfiguration(config) {
37
+ ownerDirectory(config.directory);
38
+ if (config.ownerApproved !== true || config.decryptionIdentityExcluded !== true ||
39
+ !/^age1[023456789acdefghjklmnpqrstuvwxyz]{58}$/.test(config.recipient) ||
40
+ !isAbsolute(config.ageExecutable) || realpathSync(config.ageExecutable) !== config.ageExecutable ||
41
+ !statSync(config.ageExecutable).isFile())
42
+ throw Error('ENCRYPTED_CUSTODY_CONFIGURATION_REQUIRED');
43
+ const version = spawnSync(config.ageExecutable, ['--version'], {
44
+ env: {}, encoding: 'utf8', timeout: 5_000, maxBuffer: 1024,
45
+ });
46
+ if (version.error || version.signal || version.status !== 0)
47
+ throw new EncryptedCustodyError('AGE_VERSION_CHECK_FAILED');
48
+ if (!supportedAgeVersion(version.stdout))
49
+ throw new EncryptedCustodyError('AGE_VERSION_UNSUPPORTED');
50
+ }
51
+ function encrypt(config, bytes) {
52
+ try {
53
+ const result = spawnSync(config.ageExecutable, ['--encrypt', '--recipient', config.recipient], {
54
+ input: bytes, env: {}, timeout: 10_000, maxBuffer: LIMIT,
55
+ });
56
+ const header = Buffer.from('age-encryption.org/v1\n');
57
+ if (result.status !== 0 || !result.stdout?.subarray(0, header.length).equals(header))
58
+ throw Error('ENCRYPTION');
59
+ return result.stdout;
60
+ }
61
+ catch {
62
+ throw new EncryptedCustodyError('RECOVERY_ENCRYPTION_FAILED');
63
+ }
64
+ }
65
+ /** Check actual recipient parsing/executable before a paid provider call. */
66
+ export function preflightEncryptedCustody(config) {
67
+ checkEncryptedCustody(config);
68
+ encrypt(config, '{"format":"nexart-custody-preflight-v1"}');
69
+ }
70
+ function exclusive(path, bytes) {
71
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
72
+ try {
73
+ writeFileSync(fd, bytes);
74
+ fsyncSync(fd);
75
+ }
76
+ finally {
77
+ closeSync(fd);
78
+ }
79
+ }
80
+ function syncDirectory(path) {
81
+ const fd = openSync(path, constants.O_RDONLY);
82
+ try {
83
+ fsyncSync(fd);
84
+ }
85
+ finally {
86
+ closeSync(fd);
87
+ }
88
+ }
89
+ function privateBytes(path) {
90
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
91
+ try {
92
+ const s = fstatSync(fd);
93
+ if (!s.isFile() || s.uid !== process.getuid?.() || s.nlink !== 1 ||
94
+ (s.mode & 0o777) !== 0o600 || s.size > LIMIT)
95
+ throw Error('UNSAFE_RECOVERY_FILE');
96
+ return readFileSync(fd);
97
+ }
98
+ finally {
99
+ closeSync(fd);
100
+ }
101
+ }
102
+ /** Verifies every protected domain, not just a selectively supplied subset. */
103
+ export function verifyRecovery(bundle, recovery) {
104
+ if (recovery.format !== 'nexart-encrypted-recovery-v1' || recovery.certificateHash !== bundle.certificateHash ||
105
+ !verifyCerV2(bundle).ok || !Array.isArray(recovery.openings))
106
+ throw Error('RECOVERY_BINDING_FAILED');
107
+ // Enumerate commitment domains from the actual confidential snapshot.
108
+ const s = bundle.snapshot;
109
+ const domains = ['input', 'output', 'instruction'].filter(k => s[k]?.mode === 'confidential');
110
+ if (Array.isArray(s.decisionRefs))
111
+ s.decisionRefs.forEach((v, i) => {
112
+ if (v?.ref?.mode === 'confidential')
113
+ domains.push(`decisionRef:${i}`);
114
+ });
115
+ if (!domains.includes('input') || !domains.includes('output') ||
116
+ recovery.openings.length !== domains.length ||
117
+ new Set(recovery.openings.map(o => o.field)).size !== domains.length ||
118
+ recovery.openings.some(o => !domains.includes(o.field)))
119
+ throw Error('RECOVERY_DOMAINS_FAILED');
120
+ const inputs = recovery.openings.map(o => {
121
+ const plaintext = o.field.startsWith('decisionRef:')
122
+ ? recovery.snapshot.decisionRefs?.[Number(o.field.slice(12))]?.ref
123
+ : recovery.snapshot[o.field];
124
+ if (plaintext === undefined)
125
+ throw Error('RECOVERY_PLAINTEXT_REQUIRED');
126
+ return { field: o.field, salt: o.salt, plaintext: plaintext };
127
+ });
128
+ if (verifyConfidentialV2(bundle, inputs).state !== 'VERIFIED')
129
+ throw Error('RECOVERY_OPENINGS_FAILED');
130
+ }
131
+ /** No plaintext files. Partial ciphertext is preserved, never overwritten/retried. */
132
+ export function retainEncrypted(bundle, snapshot, openings, config) {
133
+ checkEncryptedCustody(config);
134
+ if (!validV2(bundle) || boundedInput(bundle))
135
+ throw Error('INVALID_CUSTODY_CER');
136
+ const recovery = { format: 'nexart-encrypted-recovery-v1', certificateHash: bundle.certificateHash, snapshot, openings };
137
+ try {
138
+ verifyRecovery(bundle, recovery);
139
+ }
140
+ catch {
141
+ throw new EncryptedCustodyError('RECOVERY_BINDING_FAILED');
142
+ }
143
+ const plaintext = JSON.stringify(recovery);
144
+ if (Buffer.byteLength(plaintext) > LIMIT / 2)
145
+ throw Error('RECOVERY_LIMIT');
146
+ const ciphertext = encrypt(config, plaintext);
147
+ const dir = join(config.directory, bundle.certificateHash.replace(':', '-'));
148
+ try {
149
+ mkdirSync(dir, { mode: 0o700 });
150
+ exclusive(join(dir, 'recovery.age'), ciphertext);
151
+ syncDirectory(dir);
152
+ exclusive(join(dir, 'cer.json'), JSON.stringify(bundle));
153
+ exclusive(join(dir, 'committed.json'), JSON.stringify({
154
+ format: 'nexart-custody-commit-v1', certificateHash: bundle.certificateHash,
155
+ recoveryFormat: recovery.format, ciphertextSha256: digest(ciphertext),
156
+ recipientSha256: digest(config.recipient),
157
+ }));
158
+ syncDirectory(dir);
159
+ syncDirectory(config.directory);
160
+ }
161
+ catch {
162
+ throw new EncryptedCustodyError('ENCRYPTED_CUSTODY_DURABILITY_FAILED');
163
+ }
164
+ }
165
+ export function createEncryptedConfidential(raw, config) {
166
+ const { cer, openings, execution } = prepareOwnerConfidential(raw);
167
+ retainEncrypted(cer, execution, openings, config);
168
+ return cer;
169
+ }
170
+ /** Owner-side only. Run away from the agent; identity is never an MCP/config field.
171
+ * Returns verification summary only, never decrypted recovery content. */
172
+ export function recoverEncrypted(directory, identityFile, ageExecutable) {
173
+ try {
174
+ ownerDirectory(directory);
175
+ const bundle = JSON.parse(privateBytes(join(directory, 'cer.json')).toString());
176
+ const commit = JSON.parse(privateBytes(join(directory, 'committed.json')).toString());
177
+ const ciphertext = privateBytes(join(directory, 'recovery.age'));
178
+ if (commit.format !== 'nexart-custody-commit-v1' || commit.certificateHash !== bundle.certificateHash ||
179
+ commit.recoveryFormat !== 'nexart-encrypted-recovery-v1' ||
180
+ commit.ciphertextSha256 !== digest(ciphertext))
181
+ throw Error('BINDING');
182
+ // Ensure owner-only identity file; decrypt streams in memory, never to disk/stdout.
183
+ privateBytes(identityFile).fill(0);
184
+ if (!isAbsolute(ageExecutable) || realpathSync(ageExecutable) !== ageExecutable)
185
+ throw Error('EXECUTABLE');
186
+ const r = spawnSync(ageExecutable, ['--decrypt', '--identity', identityFile], {
187
+ input: ciphertext, env: {}, timeout: 10_000, maxBuffer: LIMIT,
188
+ });
189
+ if (r.status !== 0)
190
+ throw Error('DECRYPTION');
191
+ const recovery = JSON.parse(r.stdout.toString());
192
+ r.stdout.fill(0);
193
+ verifyRecovery(bundle, recovery);
194
+ return { certificateHash: bundle.certificateHash, openings: 'verified', custody: 'encrypted_owner_recipient' };
195
+ }
196
+ catch {
197
+ throw Error('OWNER_RECOVERY_FAILED');
198
+ }
199
+ }
200
+ //# sourceMappingURL=custody.js.map
@@ -0,0 +1,10 @@
1
+ /** Code-integrity checks plus an EXTERNAL administrator-enforced isolation
2
+ * prerequisite. This does not discover same-UID agents or prove human presence.
3
+ * Milestone 4A deliberately retains the existing conservative Mac boundary. */
4
+ export declare function requireIsolatedMac(): {
5
+ platform: string;
6
+ administratorProvisioned: boolean;
7
+ ownerUidMatched: boolean;
8
+ installationRootControlled: boolean;
9
+ agentIsolation: string;
10
+ };
@@ -0,0 +1,70 @@
1
+ import { lstatSync, realpathSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { dirname, resolve, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { spawnSync } from 'node:child_process';
5
+ const POLICY = '/Library/Application Support/NexArt/public-acceptance-host.json';
6
+ function rootControlled(path, checked) {
7
+ let current = path;
8
+ while (true) {
9
+ if (checked.has(current))
10
+ return;
11
+ const stat = lstatSync(current);
12
+ if (stat.uid !== 0 || (stat.mode & 0o022) || stat.isSymbolicLink())
13
+ throw Error('ROOT_CONTROL_REQUIRED');
14
+ const acl = spawnSync('/bin/ls', ['-lde', current], {
15
+ env: { PATH: '/usr/bin:/bin', LC_ALL: 'C' }, encoding: 'utf8', timeout: 5000,
16
+ });
17
+ if (acl.status !== 0 || /^\S{10}\+/.test(acl.stdout) || acl.stdout.includes('\n 0:'))
18
+ throw Error('ACL_ISOLATION_NOT_ESTABLISHED');
19
+ checked.add(current);
20
+ if (current === dirname(current))
21
+ return;
22
+ current = dirname(current);
23
+ }
24
+ }
25
+ /** Code-integrity checks plus an EXTERNAL administrator-enforced isolation
26
+ * prerequisite. This does not discover same-UID agents or prove human presence.
27
+ * Milestone 4A deliberately retains the existing conservative Mac boundary. */
28
+ export function requireIsolatedMac() {
29
+ if (process.platform !== 'darwin' || process.getuid?.() === 0 ||
30
+ process.env.REPL_ID !== undefined || process.env.REPLIT_DEV_DOMAIN !== undefined ||
31
+ process.env.NODE_OPTIONS || process.env.NODE_PATH || process.execArgv.length)
32
+ throw Error('ISOLATED_MAC_REQUIRED');
33
+ const checked = new Set();
34
+ rootControlled(POLICY, checked);
35
+ const stat = lstatSync(POLICY);
36
+ if (!stat.isFile() || stat.nlink !== 1 || stat.size > 4096)
37
+ throw Error('HOST_POLICY_REJECTED');
38
+ const policy = JSON.parse(readFileSync(POLICY, 'utf8'));
39
+ if (Object.keys(policy).sort().join(',') !== 'agentAccess,installationRoot,nodeExecutable,ownerUid,version' ||
40
+ policy.version !== 1 || policy.ownerUid !== process.getuid?.() ||
41
+ policy.agentAccess !== 'denied_by_administrator' ||
42
+ policy.nodeExecutable !== realpathSync(process.execPath))
43
+ throw Error('HOST_POLICY_REJECTED');
44
+ const root = realpathSync(policy.installationRoot);
45
+ if (root !== resolve(policy.installationRoot) || root === '/' ||
46
+ !fileURLToPath(import.meta.url).startsWith(root + sep))
47
+ throw Error('INSTALLATION_REJECTED');
48
+ rootControlled(root, checked);
49
+ rootControlled(realpathSync(process.execPath), checked);
50
+ const visited = new Set();
51
+ function walk(path) {
52
+ const actual = realpathSync(path);
53
+ if (actual !== root && !actual.startsWith(root + sep))
54
+ throw Error('INSTALLATION_ESCAPE');
55
+ if (visited.has(actual))
56
+ return;
57
+ visited.add(actual);
58
+ rootControlled(actual, checked);
59
+ const stat = lstatSync(actual);
60
+ if (stat.isDirectory())
61
+ for (const child of readdirSync(actual))
62
+ walk(`${actual}/${child}`);
63
+ else if (!stat.isFile() || stat.nlink !== 1)
64
+ throw Error('INSTALLATION_REJECTED');
65
+ }
66
+ walk(root);
67
+ return { platform: 'darwin', administratorProvisioned: true, ownerUidMatched: true,
68
+ installationRootControlled: true, agentIsolation: 'external_administrator_enforced' };
69
+ }
70
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1,21 @@
1
+ import { type OwnerPublicationOptions } from '../record/publication.js';
2
+ import type { PreparedRecord, PublicationResult } from '../record/contracts.js';
3
+ /** Owner-only library factory. No environment bypass, automatic MCP registration,
4
+ * shell-based approval, credential export or per-CER prompt synthesis.
5
+ * Agent-exclusion provisioning remains an external security prerequisite. */
6
+ export declare function createIsolatedOwnerPublisher(options: OwnerPublicationOptions): Readonly<{
7
+ publish(record: PreparedRecord): Promise<PublicationResult>;
8
+ reconcile(certificateHash: string): Promise<{
9
+ state: string;
10
+ certificateHash: string;
11
+ noRetry: boolean;
12
+ nodeConfirmedVisibility: any;
13
+ receiptSignature: "valid" | "invalid" | "not_performed";
14
+ hashBinding: "not_performed" | "match" | "mismatch";
15
+ signerTrust: "not_established" | "trusted_under_policy" | "rejected";
16
+ } | {
17
+ state: string;
18
+ certificateHash: string;
19
+ noRetry: boolean;
20
+ }>;
21
+ }>;
@@ -0,0 +1,27 @@
1
+ import { requireIsolatedMac } from './host.js';
2
+ import { publishForTrustedApplication } from '../record/publication.js';
3
+ import { reconcileOwnerAttempt } from './reconcile.js';
4
+ /** Owner-only library factory. No environment bypass, automatic MCP registration,
5
+ * shell-based approval, credential export or per-CER prompt synthesis.
6
+ * Agent-exclusion provisioning remains an external security prerequisite. */
7
+ export function createIsolatedOwnerPublisher(options) {
8
+ return Object.freeze({
9
+ async publish(record) {
10
+ try {
11
+ requireIsolatedMac();
12
+ }
13
+ catch {
14
+ return { authorization: 'setup_required', submission: 'not_sent',
15
+ nodeConfirmedVisibility: null, reasonCode: 'OWNER_ISOLATION_REQUIRED',
16
+ receiptSignature: 'not_performed', hashBinding: 'not_performed',
17
+ signerTrust: 'not_established', reservedAttempts: null };
18
+ }
19
+ return publishForTrustedApplication(record, options);
20
+ },
21
+ async reconcile(certificateHash) {
22
+ requireIsolatedMac();
23
+ return reconcileOwnerAttempt(certificateHash, options);
24
+ },
25
+ });
26
+ }
27
+ //# sourceMappingURL=publisher.js.map
@@ -0,0 +1,16 @@
1
+ import type { OwnerPublicationOptions } from '../record/publication.js';
2
+ /** Owner-authorized GET reconciliation only. Never grants, retries, refunds local
3
+ * allowance, changes visibility or removes attempt state. No raw proof returned. */
4
+ export declare function reconcileOwnerAttempt(certificateHash: string, options: OwnerPublicationOptions, request?: typeof fetch, recheck?: () => void): Promise<{
5
+ state: string;
6
+ certificateHash: string;
7
+ noRetry: boolean;
8
+ nodeConfirmedVisibility: any;
9
+ receiptSignature: "valid" | "invalid" | "not_performed";
10
+ hashBinding: "not_performed" | "match" | "mismatch";
11
+ signerTrust: "not_established" | "trusted_under_policy" | "rejected";
12
+ } | {
13
+ state: string;
14
+ certificateHash: string;
15
+ noRetry: boolean;
16
+ }>;
@@ -0,0 +1,109 @@
1
+ import { join } from 'node:path';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { verifyConfidentialV2 } from '@nexart/ai-execution';
4
+ import { readOwnerInput, ownerDirectory } from './create.js';
5
+ import { attemptName, durableExclusive, attemptSchema } from '../record/state.js';
6
+ import { controlDigest, ownerPolicy, evaluatePolicy } from '../record/policy.js';
7
+ import { NODE_ORIGIN, NodeNetwork } from '../network/client.js';
8
+ import { hashSchema } from '../network/contracts.js';
9
+ import { validV2 } from '../write/profile.js';
10
+ import { verifyReceipt } from '../receipts/verify.js';
11
+ import { TRUST_POLICY } from '../trust/policy.js';
12
+ /** Owner-authorized GET reconciliation only. Never grants, retries, refunds local
13
+ * allowance, changes visibility or removes attempt state. No raw proof returned. */
14
+ export async function reconcileOwnerAttempt(certificateHash, options, request = globalThis.fetch, recheck) {
15
+ try {
16
+ return await readOwnerAttempt(certificateHash, options, request, recheck);
17
+ }
18
+ catch (error) {
19
+ // JSON parse errors, fetch errors and filesystem diagnostics can contain
20
+ // raw Node data or owner paths. Only known constant reason codes may escape.
21
+ const safe = new Set(['ATTEMPT_BINDING_REJECTED', 'OWNER_READ_NOT_AUTHORIZED',
22
+ 'OWNER_RESPONSE_REJECTED', 'OWNER_RESPONSE_TOO_LARGE', 'OWNER_RESPONSE_TOO_DEEP',
23
+ 'OWNER_PROOF_BINDING_REJECTED']);
24
+ throw Error(error instanceof Error && safe.has(error.message)
25
+ ? error.message : 'OWNER_RECONCILIATION_FAILED_NO_RETRY');
26
+ }
27
+ }
28
+ async function readOwnerAttempt(certificateHash, options, request, recheck) {
29
+ hashSchema.parse(certificateHash);
30
+ ownerDirectory(options.stateDirectory);
31
+ const file = join(options.stateDirectory, `${attemptName(options.accountContext, certificateHash)}.attempt.json`);
32
+ const attempt = attemptSchema.parse(readOwnerInput(file));
33
+ if (attempt.accountContext !== options.accountContext || attempt.certificateHash !== certificateHash)
34
+ throw Error('ATTEMPT_BINDING_REJECTED');
35
+ const policy = ownerPolicy.parse(readOwnerInput(options.policyFile));
36
+ const key = options.credential();
37
+ if (!key || /[\r\n]/.test(key) || policy.accountContext !== options.accountContext ||
38
+ policy.credentialContext !== options.credentialContext ||
39
+ policy.credentialFingerprint !== controlDigest(key))
40
+ throw Error('OWNER_READ_NOT_AUTHORIZED');
41
+ if (recheck) {
42
+ evaluatePolicy(policy, { body: attempt.body, certificateHash, visibility: attempt.visibility,
43
+ captureSource: attempt.captureSource }, options.accountContext, options.credentialContext, key);
44
+ recheck();
45
+ }
46
+ const response = await request(`${NODE_ORIGIN}/api/proofs/${encodeURIComponent(certificateHash)}`, {
47
+ method: 'GET', redirect: 'manual', credentials: 'omit', cache: 'no-store',
48
+ signal: AbortSignal.timeout(10_000),
49
+ headers: { Accept: 'application/json', Authorization: `Bearer ${key}` },
50
+ });
51
+ if (response.status !== 200 || !/^application\/json(?:\s*;|$)/i.test(response.headers.get('content-type') ?? '')) {
52
+ await response.body?.cancel();
53
+ return { state: 'unresolved', certificateHash, noRetry: true };
54
+ }
55
+ const reader = response.body?.getReader();
56
+ if (!reader)
57
+ throw Error('OWNER_RESPONSE_REJECTED');
58
+ let size = 0;
59
+ const chunks = [];
60
+ try {
61
+ while (true) {
62
+ const part = await reader.read();
63
+ if (part.done)
64
+ break;
65
+ if ((size += part.value.byteLength) > 1_048_576)
66
+ throw Error('OWNER_RESPONSE_TOO_LARGE');
67
+ chunks.push(part.value);
68
+ }
69
+ }
70
+ finally {
71
+ await reader.cancel().catch(() => { });
72
+ reader.releaseLock();
73
+ }
74
+ // Bound lexical nesting before parsing untrusted Node data.
75
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
76
+ let depth = 0, quoted = false, escaped = false;
77
+ for (const c of text) {
78
+ if (quoted) {
79
+ if (escaped)
80
+ escaped = false;
81
+ else if (c === '\\')
82
+ escaped = true;
83
+ else if (c === '"')
84
+ quoted = false;
85
+ }
86
+ else if (c === '"')
87
+ quoted = true;
88
+ else if (c === '[' || c === '{') {
89
+ if (++depth > 64)
90
+ throw Error('OWNER_RESPONSE_TOO_DEEP');
91
+ }
92
+ else if (c === ']' || c === '}')
93
+ depth--;
94
+ }
95
+ const proof = JSON.parse(text);
96
+ if (proof.certificateHash !== certificateHash || proof.status !== 'ATTESTED' ||
97
+ proof.visibilityState !== attempt.visibility || !isDeepStrictEqual(proof.proofJson, JSON.parse(attempt.body)) ||
98
+ !validV2(proof.proofJson) || verifyConfidentialV2(proof.proofJson).state !== 'AUTHENTIC')
99
+ throw Error('OWNER_PROOF_BINDING_REJECTED');
100
+ const receipt = await verifyReceipt({
101
+ source: 'inline', certificateHash, receipt: proof.meta?.receipt, signatureB64Url: proof.meta?.receiptSignature,
102
+ }, new NodeNetwork(request), TRUST_POLICY);
103
+ const outcome = { state: 'owner_reported_persisted', certificateHash, noRetry: true,
104
+ nodeConfirmedVisibility: proof.visibilityState, receiptSignature: receipt.signature,
105
+ hashBinding: receipt.hashBinding, signerTrust: receipt.signerTrust };
106
+ durableExclusive(`${file}.reconciliation.json`, outcome);
107
+ return outcome;
108
+ }
109
+ //# sourceMappingURL=reconcile.js.map
@@ -0,0 +1,72 @@
1
+ import * as z from 'zod/v4';
2
+ export declare const RECEIPT_TOOL: "nexart_verify_node_receipt";
3
+ export declare const receiptSchema: z.ZodObject<{
4
+ receiptVersion: z.ZodLiteral<"attestation.receipt.v1">;
5
+ attestationId: z.ZodString;
6
+ certificateHash: z.ZodString;
7
+ nodeRuntimeHash: z.ZodString;
8
+ protocolVersion: z.ZodEnum<{
9
+ "1.2.0": "1.2.0";
10
+ "1.3.0": "1.3.0";
11
+ "1.3.1": "1.3.1";
12
+ }>;
13
+ nodeId: z.ZodString;
14
+ attestorKeyId: z.ZodString;
15
+ attestedAt: z.ZodOptional<z.ZodString>;
16
+ timestampType: z.ZodOptional<z.ZodString>;
17
+ timestampStatus: z.ZodOptional<z.ZodString>;
18
+ timestampProvider: z.ZodOptional<z.ZodString>;
19
+ }, z.core.$strict>;
20
+ export declare const receiptInput: z.ZodObject<{
21
+ source: z.ZodEnum<{
22
+ inline: "inline";
23
+ public_lookup: "public_lookup";
24
+ }>;
25
+ certificateHash: z.ZodString;
26
+ receipt: z.ZodOptional<z.ZodUnknown>;
27
+ signatureB64Url: z.ZodOptional<z.ZodString>;
28
+ }, z.core.$strict>;
29
+ export declare const receiptOutput: z.ZodObject<{
30
+ contractVersion: z.ZodLiteral<"1">;
31
+ reasonCode: z.ZodString;
32
+ signature: z.ZodEnum<{
33
+ valid: "valid";
34
+ invalid: "invalid";
35
+ not_performed: "not_performed";
36
+ }>;
37
+ hashBinding: z.ZodEnum<{
38
+ not_performed: "not_performed";
39
+ match: "match";
40
+ mismatch: "mismatch";
41
+ }>;
42
+ nodeIdentity: z.ZodEnum<{
43
+ not_established: "not_established";
44
+ match: "match";
45
+ mismatch: "mismatch";
46
+ }>;
47
+ keyStatus: z.ZodEnum<{
48
+ unknown: "unknown";
49
+ active: "active";
50
+ deprecated: "deprecated";
51
+ revoked: "revoked";
52
+ unavailable: "unavailable";
53
+ }>;
54
+ keyLifecycle: z.ZodEnum<{
55
+ valid: "valid";
56
+ invalid: "invalid";
57
+ unknown: "unknown";
58
+ }>;
59
+ lifecycleCode: z.ZodString;
60
+ signerTrust: z.ZodEnum<{
61
+ not_established: "not_established";
62
+ trusted_under_policy: "trusted_under_policy";
63
+ rejected: "rejected";
64
+ }>;
65
+ artifactIntegrity: z.ZodLiteral<"not_performed">;
66
+ sdk: z.ZodNullable<z.ZodObject<{
67
+ ok: z.ZodBoolean;
68
+ code: z.ZodString;
69
+ }, z.core.$strict>>;
70
+ limitations: z.ZodArray<z.ZodString>;
71
+ }, z.core.$strict>;
72
+ export type ReceiptOutput = z.infer<typeof receiptOutput>;
@@ -0,0 +1,33 @@
1
+ import * as z from 'zod/v4';
2
+ import { boundedString, hashSchema } from '../network/contracts.js';
3
+ export const RECEIPT_TOOL = 'nexart_verify_node_receipt';
4
+ export const receiptSchema = z.strictObject({
5
+ receiptVersion: z.literal('attestation.receipt.v1'),
6
+ attestationId: boundedString, certificateHash: hashSchema, nodeRuntimeHash: hashSchema,
7
+ protocolVersion: z.enum(['1.2.0', '1.3.0', '1.3.1']),
8
+ nodeId: boundedString, attestorKeyId: boundedString,
9
+ attestedAt: z.string().max(64).optional(),
10
+ timestampType: boundedString.optional(), timestampStatus: boundedString.optional(),
11
+ timestampProvider: boundedString.optional(),
12
+ });
13
+ // Receipt remains unknown at the MCP boundary so unsupported versions have explicit outcomes.
14
+ export const receiptInput = z.strictObject({
15
+ source: z.enum(['inline', 'public_lookup']),
16
+ certificateHash: hashSchema,
17
+ receipt: z.unknown().optional(),
18
+ signatureB64Url: z.string().min(1).max(128).optional(),
19
+ });
20
+ export const receiptOutput = z.strictObject({
21
+ contractVersion: z.literal('1'), reasonCode: z.string().max(96),
22
+ signature: z.enum(['valid', 'invalid', 'not_performed']),
23
+ hashBinding: z.enum(['match', 'mismatch', 'not_performed']),
24
+ nodeIdentity: z.enum(['match', 'mismatch', 'not_established']),
25
+ keyStatus: z.enum(['active', 'deprecated', 'revoked', 'unknown', 'unavailable']),
26
+ keyLifecycle: z.enum(['valid', 'invalid', 'unknown']),
27
+ lifecycleCode: z.string().max(96),
28
+ signerTrust: z.enum(['trusted_under_policy', 'rejected', 'not_established']),
29
+ artifactIntegrity: z.literal('not_performed'),
30
+ sdk: z.strictObject({ ok: z.boolean(), code: z.string().max(96) }).nullable(),
31
+ limitations: z.array(z.string().max(256)).max(12),
32
+ });
33
+ //# sourceMappingURL=contracts.js.map
@@ -0,0 +1,4 @@
1
+ import { NodeNetwork } from '../network/client.js';
2
+ import { type TrustPolicy } from '../trust/policy.js';
3
+ import { type ReceiptOutput } from './contracts.js';
4
+ export declare function verifyReceipt(args: unknown, network: NodeNetwork, policy?: TrustPolicy, signal?: AbortSignal): Promise<ReceiptOutput>;