@nexart/mcp-server 0.0.0-stage → 0.2.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 (100) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/CONTRIBUTING.md +58 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +14 -0
  5. package/README.md +356 -2
  6. package/SECURITY.md +77 -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 +35 -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/json-schema.d.ts +9 -0
  21. package/dist/json-schema.js +20 -0
  22. package/dist/limits.d.ts +15 -0
  23. package/dist/limits.js +62 -0
  24. package/dist/lookup/contracts.d.ts +38 -0
  25. package/dist/lookup/contracts.js +23 -0
  26. package/dist/lookup/verify.d.ts +54 -0
  27. package/dist/lookup/verify.js +110 -0
  28. package/dist/network/client.d.ts +26 -0
  29. package/dist/network/client.js +188 -0
  30. package/dist/network/contracts.d.ts +104 -0
  31. package/dist/network/contracts.js +54 -0
  32. package/dist/network-tools.d.ts +5 -0
  33. package/dist/network-tools.js +32 -0
  34. package/dist/owner/create.d.ts +52 -0
  35. package/dist/owner/create.js +117 -0
  36. package/dist/owner/custody.d.ts +36 -0
  37. package/dist/owner/custody.js +210 -0
  38. package/dist/owner/host.d.ts +10 -0
  39. package/dist/owner/host.js +70 -0
  40. package/dist/owner/publisher.d.ts +21 -0
  41. package/dist/owner/publisher.js +27 -0
  42. package/dist/owner/reconcile.d.ts +16 -0
  43. package/dist/owner/reconcile.js +109 -0
  44. package/dist/protocol-safety.d.ts +3 -0
  45. package/dist/protocol-safety.js +16 -0
  46. package/dist/receipts/contracts.d.ts +72 -0
  47. package/dist/receipts/contracts.js +34 -0
  48. package/dist/receipts/verify.d.ts +4 -0
  49. package/dist/receipts/verify.js +104 -0
  50. package/dist/record/contracts.d.ts +323 -0
  51. package/dist/record/contracts.js +75 -0
  52. package/dist/record/customer.d.ts +40 -0
  53. package/dist/record/customer.js +99 -0
  54. package/dist/record/policy.d.ts +46 -0
  55. package/dist/record/policy.js +67 -0
  56. package/dist/record/publication.d.ts +23 -0
  57. package/dist/record/publication.js +148 -0
  58. package/dist/record/record.d.ts +15 -0
  59. package/dist/record/record.js +97 -0
  60. package/dist/record/state.d.ts +44 -0
  61. package/dist/record/state.js +84 -0
  62. package/dist/record-tools.d.ts +13 -0
  63. package/dist/record-tools.js +95 -0
  64. package/dist/recover-confidential.d.ts +2 -0
  65. package/dist/recover-confidential.js +13 -0
  66. package/dist/results.d.ts +8 -0
  67. package/dist/results.js +83 -0
  68. package/dist/server.d.ts +12 -0
  69. package/dist/server.js +39 -0
  70. package/dist/stdio.d.ts +2 -0
  71. package/dist/stdio.js +88 -0
  72. package/dist/trust/lifecycle.d.ts +13 -0
  73. package/dist/trust/lifecycle.js +42 -0
  74. package/dist/trust/policy.d.ts +14 -0
  75. package/dist/trust/policy.js +6 -0
  76. package/dist/verify.d.ts +3 -0
  77. package/dist/verify.js +56 -0
  78. package/dist/write/approval.d.ts +5 -0
  79. package/dist/write/approval.js +95 -0
  80. package/dist/write/attest.d.ts +17 -0
  81. package/dist/write/attest.js +141 -0
  82. package/dist/write/config.d.ts +11 -0
  83. package/dist/write/config.js +12 -0
  84. package/dist/write/contracts.d.ts +229 -0
  85. package/dist/write/contracts.js +61 -0
  86. package/dist/write/post.d.ts +11 -0
  87. package/dist/write/post.js +105 -0
  88. package/dist/write/profile.d.ts +19 -0
  89. package/dist/write/profile.js +114 -0
  90. package/dist/write/seal.d.ts +3 -0
  91. package/dist/write/seal.js +49 -0
  92. package/dist/write-tools.d.ts +4 -0
  93. package/dist/write-tools.js +36 -0
  94. package/docs/consumer-guide.md +133 -0
  95. package/docs/examples/customer-claude-desktop.json +14 -0
  96. package/docs/examples/customer-consent.json +15 -0
  97. package/docs/examples/customer-custody.json +8 -0
  98. package/docs/examples/customer-policy.json +43 -0
  99. package/package.json +58 -4
  100. package/server.json +20 -0
@@ -0,0 +1,117 @@
1
+ import { constants, openSync, fstatSync, closeSync, readFileSync, writeFileSync, lstatSync, realpathSync, mkdirSync, fsyncSync, } from 'node:fs';
2
+ import { isAbsolute, resolve, join, dirname } from 'node:path';
3
+ import * as z from 'zod/v4';
4
+ import { createSnapshotV2, sealConfidentialV2, verifyCerV2, verifyConfidentialV2 } from '@nexart/ai-execution';
5
+ import { sealInput } from '../write/contracts.js';
6
+ import { WRITE_LIMITS, boundedInput } from '../write/profile.js';
7
+ const options = z.strictObject({
8
+ execution: z.record(z.string(), z.unknown()), createdAt: z.string().min(1),
9
+ protectInstruction: z.boolean().optional(),
10
+ decisionRefIndexes: z.array(z.number().int().nonnegative()).optional(),
11
+ });
12
+ /** Local filesystem protection, NOT isolation from an agent with this UID.
13
+ * Call only on a genuinely isolated owner host. No MCP registration/import.
14
+ */
15
+ export function ownerDirectory(path) {
16
+ if (!isAbsolute(path) || realpathSync(path) !== resolve(path))
17
+ throw Error('UNSAFE_CUSTODY');
18
+ let parent = path;
19
+ while (true) {
20
+ const stat = lstatSync(parent);
21
+ // Root-owned sticky temporary ancestors cannot be renamed by other users;
22
+ // the actual vault itself must still be an exact owner-only 0700 directory.
23
+ const rootSticky = stat.uid === 0 && (stat.mode & 0o1000) !== 0;
24
+ if (stat.isSymbolicLink() || !stat.isDirectory() || ((stat.mode & 0o022) !== 0 && !rootSticky))
25
+ throw Error('UNSAFE_CUSTODY');
26
+ if (parent === dirname(parent))
27
+ break;
28
+ parent = dirname(parent);
29
+ }
30
+ const stat = lstatSync(path);
31
+ if (stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700)
32
+ throw Error('UNSAFE_CUSTODY');
33
+ return path;
34
+ }
35
+ export function readOwnerInput(path) {
36
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
37
+ try {
38
+ const stat = fstatSync(fd);
39
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.()
40
+ || (stat.mode & 0o777) !== 0o600 || stat.size > WRITE_LIMITS.inputBytes)
41
+ throw Error('UNSAFE_INPUT');
42
+ return JSON.parse(readFileSync(fd, 'utf8'));
43
+ }
44
+ finally {
45
+ closeSync(fd);
46
+ }
47
+ }
48
+ function durableFile(path, value) {
49
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
50
+ try {
51
+ writeFileSync(fd, JSON.stringify(value));
52
+ fsyncSync(fd);
53
+ }
54
+ finally {
55
+ closeSync(fd);
56
+ }
57
+ }
58
+ /** Owner expressly accepts plaintext + openings custody before calling.
59
+ * Fail closed: no CER export until recovery material is durably retained.
60
+ * On failure preserve private partial files for owner recovery, never delete.
61
+ */
62
+ export function prepareOwnerConfidential(raw) {
63
+ if (boundedInput(raw))
64
+ throw Error('INPUT_LIMIT');
65
+ const parsed = options.parse(raw);
66
+ const execution = sealInput.parse({
67
+ mode: 'from_execution', execution: parsed.execution, createdAt: parsed.createdAt,
68
+ });
69
+ if (execution.mode !== 'from_execution')
70
+ throw Error('INPUT');
71
+ if (parsed.protectInstruction && execution.execution.instruction === undefined)
72
+ throw Error('INSTRUCTION_ABSENT');
73
+ const snapshot = createSnapshotV2(execution.execution);
74
+ // No salt option is exposed. SDK 1.4.0 supplies fresh CSPRNG salts.
75
+ const { cer, openings } = sealConfidentialV2(snapshot, {
76
+ confidential: true, fields: parsed.protectInstruction ? ['input', 'output', 'instruction'] : ['input', 'output'],
77
+ decisionRefIndexes: parsed.decisionRefIndexes ?? [], createdAt: parsed.createdAt,
78
+ });
79
+ if (!verifyCerV2(cer).ok || verifyConfidentialV2(cer).state !== 'AUTHENTIC')
80
+ throw Error('SDK_VERIFICATION');
81
+ return { cer, openings, execution: execution.execution };
82
+ }
83
+ export function createOwnerConfidential(raw, custody) {
84
+ ownerDirectory(custody);
85
+ const { cer, openings, execution } = prepareOwnerConfidential(raw);
86
+ const dir = join(custody, cer.certificateHash.replace(':', '-'));
87
+ mkdirSync(dir, { mode: 0o700 }); // Exclusive transaction directory, no overwrites.
88
+ durableFile(join(dir, 'recovery.json'), {
89
+ format: 'nexart-owner-recovery-v1', certificateHash: cer.certificateHash,
90
+ // SDK openings contain salts, not content. Both are needed for later disclosure.
91
+ execution, openings,
92
+ });
93
+ const fd = openSync(dir, constants.O_RDONLY);
94
+ try {
95
+ fsyncSync(fd);
96
+ }
97
+ finally {
98
+ closeSync(fd);
99
+ }
100
+ durableFile(join(dir, 'cer.json'), cer);
101
+ const committed = openSync(dir, constants.O_RDONLY);
102
+ try {
103
+ fsyncSync(committed);
104
+ }
105
+ finally {
106
+ closeSync(committed);
107
+ }
108
+ const parent = openSync(custody, constants.O_RDONLY);
109
+ try {
110
+ fsyncSync(parent);
111
+ }
112
+ finally {
113
+ closeSync(parent);
114
+ }
115
+ return { certificateHash: cer.certificateHash };
116
+ }
117
+ //# sourceMappingURL=create.js.map
@@ -0,0 +1,36 @@
1
+ import { type CerAiExecutionBundleV2, type OpeningV2 } from '@nexart/ai-execution';
2
+ /** Trusted host configuration only. No private identity is accepted here. */
3
+ export interface EncryptedCustody {
4
+ directory: string;
5
+ ageExecutable: string;
6
+ recipient: string;
7
+ ownerApproved: true;
8
+ decryptionIdentityExcluded: true;
9
+ }
10
+ export declare class EncryptedCustodyError extends Error {
11
+ readonly reasonCode: 'ENCRYPTED_CUSTODY_CONFIGURATION_REQUIRED' | 'RECOVERY_ENCRYPTION_FAILED' | 'ENCRYPTED_CUSTODY_DURABILITY_FAILED' | 'RECOVERY_BINDING_FAILED' | 'AGE_VERSION_UNSUPPORTED' | 'AGE_VERSION_CHECK_FAILED';
12
+ constructor(reasonCode: 'ENCRYPTED_CUSTODY_CONFIGURATION_REQUIRED' | 'RECOVERY_ENCRYPTION_FAILED' | 'ENCRYPTED_CUSTODY_DURABILITY_FAILED' | 'RECOVERY_BINDING_FAILED' | 'AGE_VERSION_UNSUPPORTED' | 'AGE_VERSION_CHECK_FAILED');
13
+ }
14
+ export declare function checkEncryptedCustody(config: EncryptedCustody): void;
15
+ /** Shared in-memory encryption for a durable hosted storage port. No files or
16
+ * private identity, and no new commitment/encryption implementation. */
17
+ export declare function encryptRecoveryForRecipient(bundle: CerAiExecutionBundleV2, snapshot: Record<string, unknown>, openings: OpeningV2[], config: Pick<EncryptedCustody, 'recipient' | 'ageExecutable'>): Buffer;
18
+ /** Check actual recipient parsing/executable before a paid provider call. */
19
+ export declare function preflightEncryptedCustody(config: EncryptedCustody): void;
20
+ /** Verifies every protected domain, not just a selectively supplied subset. */
21
+ export declare function verifyRecovery(bundle: CerAiExecutionBundleV2, recovery: {
22
+ format: string;
23
+ certificateHash: string;
24
+ snapshot: Record<string, unknown>;
25
+ openings: OpeningV2[];
26
+ }): void;
27
+ /** No plaintext files. Partial ciphertext is preserved, never overwritten/retried. */
28
+ export declare function retainEncrypted(bundle: CerAiExecutionBundleV2, snapshot: Record<string, unknown>, openings: OpeningV2[], config: EncryptedCustody): void;
29
+ export declare function createEncryptedConfidential(raw: unknown, config: EncryptedCustody): CerAiExecutionBundleV2;
30
+ /** Owner-side only. Run away from the agent; identity is never an MCP/config field.
31
+ * Returns verification summary only, never decrypted recovery content. */
32
+ export declare function recoverEncrypted(directory: string, identityFile: string, ageExecutable: string): {
33
+ certificateHash: string;
34
+ openings: 'verified';
35
+ custody: 'encrypted_owner_recipient';
36
+ };
@@ -0,0 +1,210 @@
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
+ throw Error('ENCRYPTED_CUSTODY_CONFIGURATION_REQUIRED');
40
+ checkAgeRecipient(config);
41
+ }
42
+ function checkAgeRecipient(config) {
43
+ if (!/^age1[023456789acdefghjklmnpqrstuvwxyz]{58}$/.test(config.recipient) ||
44
+ !isAbsolute(config.ageExecutable) || realpathSync(config.ageExecutable) !== config.ageExecutable ||
45
+ !statSync(config.ageExecutable).isFile())
46
+ throw Error('ENCRYPTED_CUSTODY_CONFIGURATION_REQUIRED');
47
+ const version = spawnSync(config.ageExecutable, ['--version'], {
48
+ env: {}, encoding: 'utf8', timeout: 5_000, maxBuffer: 1024,
49
+ });
50
+ if (version.error || version.signal || version.status !== 0)
51
+ throw new EncryptedCustodyError('AGE_VERSION_CHECK_FAILED');
52
+ if (!supportedAgeVersion(version.stdout))
53
+ throw new EncryptedCustodyError('AGE_VERSION_UNSUPPORTED');
54
+ }
55
+ function encrypt(config, bytes) {
56
+ try {
57
+ const result = spawnSync(config.ageExecutable, ['--encrypt', '--recipient', config.recipient], {
58
+ input: bytes, env: {}, timeout: 10_000, maxBuffer: LIMIT,
59
+ });
60
+ const header = Buffer.from('age-encryption.org/v1\n');
61
+ if (result.status !== 0 || !result.stdout?.subarray(0, header.length).equals(header))
62
+ throw Error('ENCRYPTION');
63
+ return result.stdout;
64
+ }
65
+ catch {
66
+ throw new EncryptedCustodyError('RECOVERY_ENCRYPTION_FAILED');
67
+ }
68
+ }
69
+ /** Shared in-memory encryption for a durable hosted storage port. No files or
70
+ * private identity, and no new commitment/encryption implementation. */
71
+ export function encryptRecoveryForRecipient(bundle, snapshot, openings, config) {
72
+ checkAgeRecipient(config);
73
+ if (!validV2(bundle) || boundedInput(bundle))
74
+ throw Error('INVALID_CUSTODY_CER');
75
+ const recovery = { format: 'nexart-encrypted-recovery-v1', certificateHash: bundle.certificateHash, snapshot, openings };
76
+ try {
77
+ verifyRecovery(bundle, recovery);
78
+ }
79
+ catch {
80
+ throw new EncryptedCustodyError('RECOVERY_BINDING_FAILED');
81
+ }
82
+ const bytes = JSON.stringify(recovery);
83
+ if (Buffer.byteLength(bytes) > LIMIT / 2)
84
+ throw Error('RECOVERY_LIMIT');
85
+ return encrypt(config, bytes);
86
+ }
87
+ /** Check actual recipient parsing/executable before a paid provider call. */
88
+ export function preflightEncryptedCustody(config) {
89
+ checkEncryptedCustody(config);
90
+ encrypt(config, '{"format":"nexart-custody-preflight-v1"}');
91
+ }
92
+ function exclusive(path, bytes) {
93
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
94
+ try {
95
+ writeFileSync(fd, bytes);
96
+ fsyncSync(fd);
97
+ }
98
+ finally {
99
+ closeSync(fd);
100
+ }
101
+ }
102
+ function syncDirectory(path) {
103
+ const fd = openSync(path, constants.O_RDONLY);
104
+ try {
105
+ fsyncSync(fd);
106
+ }
107
+ finally {
108
+ closeSync(fd);
109
+ }
110
+ }
111
+ function privateBytes(path) {
112
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
113
+ try {
114
+ const s = fstatSync(fd);
115
+ if (!s.isFile() || s.uid !== process.getuid?.() || s.nlink !== 1 ||
116
+ (s.mode & 0o777) !== 0o600 || s.size > LIMIT)
117
+ throw Error('UNSAFE_RECOVERY_FILE');
118
+ return readFileSync(fd);
119
+ }
120
+ finally {
121
+ closeSync(fd);
122
+ }
123
+ }
124
+ /** Verifies every protected domain, not just a selectively supplied subset. */
125
+ export function verifyRecovery(bundle, recovery) {
126
+ if (recovery.format !== 'nexart-encrypted-recovery-v1' || recovery.certificateHash !== bundle.certificateHash ||
127
+ !verifyCerV2(bundle).ok || !Array.isArray(recovery.openings))
128
+ throw Error('RECOVERY_BINDING_FAILED');
129
+ // Enumerate commitment domains from the actual confidential snapshot.
130
+ const s = bundle.snapshot;
131
+ const domains = ['input', 'output', 'instruction'].filter(k => s[k]?.mode === 'confidential');
132
+ if (Array.isArray(s.decisionRefs))
133
+ s.decisionRefs.forEach((v, i) => {
134
+ if (v?.ref?.mode === 'confidential')
135
+ domains.push(`decisionRef:${i}`);
136
+ });
137
+ if (!domains.includes('input') || !domains.includes('output') ||
138
+ recovery.openings.length !== domains.length ||
139
+ new Set(recovery.openings.map(o => o.field)).size !== domains.length ||
140
+ recovery.openings.some(o => !domains.includes(o.field)))
141
+ throw Error('RECOVERY_DOMAINS_FAILED');
142
+ const inputs = recovery.openings.map(o => {
143
+ const plaintext = o.field.startsWith('decisionRef:')
144
+ ? recovery.snapshot.decisionRefs?.[Number(o.field.slice(12))]?.ref
145
+ : recovery.snapshot[o.field];
146
+ if (plaintext === undefined)
147
+ throw Error('RECOVERY_PLAINTEXT_REQUIRED');
148
+ return { field: o.field, salt: o.salt, plaintext: plaintext };
149
+ });
150
+ if (verifyConfidentialV2(bundle, inputs).state !== 'VERIFIED')
151
+ throw Error('RECOVERY_OPENINGS_FAILED');
152
+ }
153
+ /** No plaintext files. Partial ciphertext is preserved, never overwritten/retried. */
154
+ export function retainEncrypted(bundle, snapshot, openings, config) {
155
+ checkEncryptedCustody(config);
156
+ const ciphertext = encryptRecoveryForRecipient(bundle, snapshot, openings, config);
157
+ const dir = join(config.directory, bundle.certificateHash.replace(':', '-'));
158
+ try {
159
+ mkdirSync(dir, { mode: 0o700 });
160
+ exclusive(join(dir, 'recovery.age'), ciphertext);
161
+ syncDirectory(dir);
162
+ exclusive(join(dir, 'cer.json'), JSON.stringify(bundle));
163
+ exclusive(join(dir, 'committed.json'), JSON.stringify({
164
+ format: 'nexart-custody-commit-v1', certificateHash: bundle.certificateHash,
165
+ recoveryFormat: 'nexart-encrypted-recovery-v1', ciphertextSha256: digest(ciphertext),
166
+ recipientSha256: digest(config.recipient),
167
+ }));
168
+ syncDirectory(dir);
169
+ syncDirectory(config.directory);
170
+ }
171
+ catch {
172
+ throw new EncryptedCustodyError('ENCRYPTED_CUSTODY_DURABILITY_FAILED');
173
+ }
174
+ }
175
+ export function createEncryptedConfidential(raw, config) {
176
+ const { cer, openings, execution } = prepareOwnerConfidential(raw);
177
+ retainEncrypted(cer, execution, openings, config);
178
+ return cer;
179
+ }
180
+ /** Owner-side only. Run away from the agent; identity is never an MCP/config field.
181
+ * Returns verification summary only, never decrypted recovery content. */
182
+ export function recoverEncrypted(directory, identityFile, ageExecutable) {
183
+ try {
184
+ ownerDirectory(directory);
185
+ const bundle = JSON.parse(privateBytes(join(directory, 'cer.json')).toString());
186
+ const commit = JSON.parse(privateBytes(join(directory, 'committed.json')).toString());
187
+ const ciphertext = privateBytes(join(directory, 'recovery.age'));
188
+ if (commit.format !== 'nexart-custody-commit-v1' || commit.certificateHash !== bundle.certificateHash ||
189
+ commit.recoveryFormat !== 'nexart-encrypted-recovery-v1' ||
190
+ commit.ciphertextSha256 !== digest(ciphertext))
191
+ throw Error('BINDING');
192
+ // Ensure owner-only identity file; decrypt streams in memory, never to disk/stdout.
193
+ privateBytes(identityFile).fill(0);
194
+ if (!isAbsolute(ageExecutable) || realpathSync(ageExecutable) !== ageExecutable)
195
+ throw Error('EXECUTABLE');
196
+ const r = spawnSync(ageExecutable, ['--decrypt', '--identity', identityFile], {
197
+ input: ciphertext, env: {}, timeout: 10_000, maxBuffer: LIMIT,
198
+ });
199
+ if (r.status !== 0)
200
+ throw Error('DECRYPTION');
201
+ const recovery = JSON.parse(r.stdout.toString());
202
+ r.stdout.fill(0);
203
+ verifyRecovery(bundle, recovery);
204
+ return { certificateHash: bundle.certificateHash, openings: 'verified', custody: 'encrypted_owner_recipient' };
205
+ }
206
+ catch {
207
+ throw Error('OWNER_RECOVERY_FAILED');
208
+ }
209
+ }
210
+ //# 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,3 @@
1
+ import type { JSONRPCMessage } from '@modelcontextprotocol/server';
2
+ /** Redact diagnostics without replacing the SDK's protocol-era wire envelope. */
3
+ export declare function redactProtocolMessage(message: JSONRPCMessage): JSONRPCMessage;
@@ -0,0 +1,16 @@
1
+ /** Redact diagnostics without replacing the SDK's protocol-era wire envelope. */
2
+ export function redactProtocolMessage(message) {
3
+ if ('error' in message)
4
+ return {
5
+ ...message, error: { code: message.error.code, message: 'MCP request rejected' },
6
+ };
7
+ if ('result' in message && typeof message.result === 'object' &&
8
+ message.result !== null && 'isError' in message.result && message.result.isError === true) {
9
+ return { ...message, result: {
10
+ ...message.result, isError: true,
11
+ content: [{ type: 'text', text: 'Invalid MCP tool request' }],
12
+ } };
13
+ }
14
+ return message;
15
+ }
16
+ //# sourceMappingURL=protocol-safety.js.map