@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,83 @@
1
+ import { isObject } from './limits.js';
2
+ const FAMILIES = new Set([
3
+ 'cer.ai.execution.v1', 'cer.ai.execution.v2', 'cer.consequential.execution.v1',
4
+ 'cer.governed.execution.v1', 'cer.project.bundle.v1',
5
+ ]);
6
+ const PROTOCOLS = new Set(['1.2.0', '1.3.0', '1.3.1', 'jcs-v1']);
7
+ const LIMITATIONS = [
8
+ 'Integrity verification is not proof that a reported action, model response, state or outcome occurred.',
9
+ 'Node signatures, signer trust and cryptographic timestamps are not checked.',
10
+ 'Completeness and automatic capture of agent actions are not established.',
11
+ 'Confidential openings are not accepted or checked; committed plaintext is not verified.',
12
+ 'SDK diagnostic text and evidence identifiers are redacted; reason codes and check outcomes are preserved.',
13
+ ];
14
+ export function baseOutput(tool, bundle) {
15
+ const b = isObject(bundle) ? bundle : {};
16
+ const snapshot = isObject(b.snapshot) ? b.snapshot : {};
17
+ const protocol = snapshot.protocolVersion ?? b.protocolVersion;
18
+ return {
19
+ contractVersion: '1',
20
+ tool,
21
+ family: typeof b.bundleType === 'string' && FAMILIES.has(b.bundleType)
22
+ ? b.bundleType : null,
23
+ recordVersion: b.version === '0.1' || b.version === '0.2' ? b.version : null,
24
+ // Governed envelopes bind JCS but do not carry snapshot.protocolVersion.
25
+ protocol: typeof protocol === 'string' && PROTOCOLS.has(protocol)
26
+ ? protocol
27
+ : b.bundleType === 'cer.governed.execution.v1' ? 'jcs-v1' : null,
28
+ artifactIntegrity: 'not_performed',
29
+ reasonCode: 'NOT_PERFORMED',
30
+ sdk: null,
31
+ checks: {
32
+ nodeSignature: 'not_performed', signerTrust: 'not_established',
33
+ timestampCryptography: 'not_performed', confidentialOpenings: 'not_performed',
34
+ completeness: 'not_established',
35
+ },
36
+ limitations: [...LIMITATIONS],
37
+ };
38
+ }
39
+ /** Never echo SDK error text: it can contain attacker-controlled evidence. */
40
+ function diagnostics(value) {
41
+ return Array.isArray(value) ? value.map(() => 'REDACTED_DIAGNOSTIC') : [];
42
+ }
43
+ /**
44
+ * Deliberate disclosure allowlist, not an arbitrary result serializer.
45
+ * The scoped SDK `ok` remains exact; it is not Node authenticity or completeness.
46
+ */
47
+ export function projectSdkResult(raw) {
48
+ const safe = {
49
+ ok: raw.ok, code: raw.code, errors: diagnostics(raw.errors),
50
+ };
51
+ for (const field of [
52
+ 'assurance', 'verdict', 'projectHashValid', 'structuralValid', 'totalSteps',
53
+ 'passedSteps', 'failedSteps', 'certificateIntegrity', 'cageSchemaValidity',
54
+ 'causalGraphValidity', 'topologyValidation', 'resourceSafety',
55
+ 'stateHashVerification', 'producerAuthentication', 'completeness',
56
+ ]) {
57
+ if (raw[field] !== undefined)
58
+ safe[field] = raw[field];
59
+ }
60
+ if (Array.isArray(raw.details))
61
+ safe.details = diagnostics(raw.details);
62
+ if (Array.isArray(raw.warnings))
63
+ safe.warnings = diagnostics(raw.warnings);
64
+ if (Array.isArray(raw.relaxations))
65
+ safe.relaxations = raw.relaxations;
66
+ if (isObject(raw.verifiedUnder)) {
67
+ safe.verifiedUnder = {
68
+ protocolVersion: raw.verifiedUnder.protocolVersion,
69
+ canonicalization: raw.verifiedUnder.canonicalization,
70
+ };
71
+ }
72
+ if (isObject(raw.producerIdentity)) {
73
+ safe.producerIdentity = { status: raw.producerIdentity.status };
74
+ }
75
+ if (Array.isArray(raw.steps)) {
76
+ safe.steps = raw.steps.map((step, index) => {
77
+ const s = isObject(step) ? step : {};
78
+ return { index, ok: s.ok, code: s.code, errors: diagnostics(s.errors) };
79
+ });
80
+ }
81
+ return safe;
82
+ }
83
+ //# sourceMappingURL=results.js.map
@@ -0,0 +1,2 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ export declare function createServer(): McpServer;
package/dist/server.js ADDED
@@ -0,0 +1,39 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import { inputSchema, outputSchema, TOOL_NAMES } from './contracts.js';
3
+ import { verify } from './verify.js';
4
+ import { registerNetworkTools } from './network-tools.js';
5
+ import { registerWriteTools } from './write-tools.js';
6
+ import { registerRecordingTool } from './record-tools.js';
7
+ const DESCRIPTIONS = [
8
+ 'Verify inline AI CER V1/V2 integrity using the NexArt SDK. No signature, signer-trust or completeness claim.',
9
+ 'Verify inline consequential CER integrity. Producer identity and reported actions are not authenticated.',
10
+ 'Verify inline governed execution 0.1/0.2 with explicit version dispatch. No state-hash or producer authentication.',
11
+ 'Verify an inline Project Bundle and embedded AI CERs using the SDK; require project hash integrity.',
12
+ ];
13
+ export function createServer() {
14
+ const server = new McpServer({ name: 'nexart-mcp-server', version: '0.1.0' });
15
+ TOOL_NAMES.forEach((name, index) => {
16
+ server.registerTool(name, {
17
+ description: DESCRIPTIONS[index],
18
+ inputSchema,
19
+ outputSchema,
20
+ annotations: {
21
+ readOnlyHint: true, destructiveHint: false,
22
+ idempotentHint: true, openWorldHint: false,
23
+ },
24
+ }, (args, context) => {
25
+ const result = verify(name, args, context.mcpReq.signal);
26
+ return {
27
+ content: [{ type: 'text', text: JSON.stringify(result) }],
28
+ structuredContent: result,
29
+ };
30
+ });
31
+ });
32
+ registerNetworkTools(server);
33
+ registerWriteTools(server);
34
+ registerRecordingTool(server);
35
+ // The SDK may report parsing/validation exceptions containing input fragments.
36
+ server.server.onerror = () => { process.stderr.write('NEXART_MCP_PROTOCOL_ERROR\n'); };
37
+ return server;
38
+ }
39
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/stdio.js ADDED
@@ -0,0 +1,104 @@
1
+ #!/usr/bin/env node
2
+ import { Transform } from 'node:stream';
3
+ import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/stdio';
4
+ import { createServer } from './server.js';
5
+ import { LIMITS } from './limits.js';
6
+ /**
7
+ * Pre-parse byte/depth guard. MCP framing/parsing stays in the official SDK.
8
+ * No evidence is stored or logged. A hard framing limit closes the connection.
9
+ */
10
+ class InputGuard extends Transform {
11
+ bytes = 0;
12
+ depth = 0;
13
+ quoted = false;
14
+ escaped = false;
15
+ _transform(chunk, _encoding, done) {
16
+ for (const byte of chunk) {
17
+ if (byte === 10) {
18
+ this.bytes = 0;
19
+ this.depth = 0;
20
+ this.quoted = false;
21
+ this.escaped = false;
22
+ continue;
23
+ }
24
+ if (++this.bytes > LIMITS.frameBytes)
25
+ return done(new Error('FRAME_LIMIT'));
26
+ if (this.quoted) {
27
+ if (this.escaped)
28
+ this.escaped = false;
29
+ else if (byte === 92)
30
+ this.escaped = true;
31
+ else if (byte === 34)
32
+ this.quoted = false;
33
+ }
34
+ else if (byte === 34)
35
+ this.quoted = true;
36
+ else if (byte === 123 || byte === 91) {
37
+ // JSON-RPC envelope adds depth outside the tool arguments.
38
+ if (++this.depth > LIMITS.depth + 8)
39
+ return done(new Error('DEPTH_LIMIT'));
40
+ }
41
+ else if (byte === 125 || byte === 93)
42
+ this.depth--;
43
+ }
44
+ done(null, chunk);
45
+ }
46
+ }
47
+ /**
48
+ * Prevent SDK-generated validation errors from echoing attacker-controlled
49
+ * argument names or malformed JSON. SDK result wire encodings remain intact.
50
+ */
51
+ class SafeStdioTransport extends StdioServerTransport {
52
+ async close() {
53
+ await super.close();
54
+ // The SDK owns `guard`, not the original stdin: release that source too.
55
+ process.stdin.unpipe(guard);
56
+ process.stdin.destroy();
57
+ guard.destroy();
58
+ }
59
+ send(message) {
60
+ if ('error' in message) {
61
+ return super.send({
62
+ ...message, error: { code: message.error.code, message: 'MCP request rejected' },
63
+ });
64
+ }
65
+ if ('result' in message && typeof message.result === 'object' &&
66
+ message.result !== null && 'isError' in message.result &&
67
+ message.result.isError === true) {
68
+ return super.send({
69
+ ...message,
70
+ result: {
71
+ ...message.result,
72
+ isError: true,
73
+ content: [{ type: 'text', text: 'Invalid MCP tool request' }],
74
+ },
75
+ });
76
+ }
77
+ return super.send(message);
78
+ }
79
+ }
80
+ const guard = new InputGuard();
81
+ const transport = new SafeStdioTransport(guard, process.stdout, { maxBufferSize: LIMITS.frameBytes });
82
+ const handle = serveStdio(createServer, {
83
+ transport,
84
+ onerror: () => {
85
+ process.stderr.write('NEXART_MCP_PROTOCOL_ERROR\n');
86
+ },
87
+ });
88
+ guard.on('error', () => {
89
+ process.stderr.write('NEXART_MCP_INPUT_LIMIT\n');
90
+ process.stdin.unpipe(guard);
91
+ process.stdin.pause();
92
+ process.exitCode = 1;
93
+ void handle.close();
94
+ });
95
+ process.stdin.pipe(guard);
96
+ process.stdin.on('error', () => {
97
+ process.stderr.write('NEXART_MCP_INPUT_ERROR\n');
98
+ void handle.close();
99
+ });
100
+ for (const signal of ['SIGINT', 'SIGTERM']) {
101
+ process.once(signal, () => { void handle.close(); });
102
+ }
103
+ process.stderr.write('NEXART_MCP_READY\n');
104
+ //# sourceMappingURL=stdio.js.map
@@ -0,0 +1,13 @@
1
+ import type { ManifestKey } from '../network/contracts.js';
2
+ import type { ApprovedKeyPin } from './policy.js';
3
+ export declare const isoTime: (value: unknown) => value is string;
4
+ export declare function lifecycle(key: ManifestKey, attestedAt: string | undefined, pin?: ApprovedKeyPin): {
5
+ state: "invalid";
6
+ code: string;
7
+ } | {
8
+ state: "unknown";
9
+ code: string;
10
+ } | {
11
+ state: "valid";
12
+ code: string;
13
+ };
@@ -0,0 +1,42 @@
1
+ import { validateKeyLifecycle } from '@nexart/ai-execution';
2
+ import * as z from 'zod/v4';
3
+ export const isoTime = (value) => typeof value === 'string' && z.iso.datetime({ offset: true }).safeParse(value).success &&
4
+ Number.isFinite(Date.parse(value));
5
+ export function lifecycle(key, attestedAt, pin) {
6
+ if (key.revoked === true || key.status === 'revoked') {
7
+ return { state: 'invalid', code: 'KEY_REVOKED' };
8
+ }
9
+ if (!isoTime(attestedAt))
10
+ return { state: 'unknown', code: 'ATTESTATION_TIME_UNKNOWN' };
11
+ for (const date of [key.notBefore, key.notAfter, key.validFrom, key.validTo]) {
12
+ if (date != null && !isoTime(date))
13
+ return { state: 'unknown', code: 'KEY_LIFECYCLE_UNKNOWN' };
14
+ }
15
+ if ((key.notAfter && key.validTo && key.notAfter !== key.validTo) ||
16
+ (key.notBefore && key.validFrom && key.notBefore !== key.validFrom)) {
17
+ return { state: 'unknown', code: 'KEY_LIFECYCLE_CONFLICT' };
18
+ }
19
+ const exception = pin?.historicalValidity;
20
+ if (exception && (!isoTime(exception.notBefore) || !exception.provenance.trim())) {
21
+ return { state: 'unknown', code: 'HISTORICAL_PROVENANCE_MISSING' };
22
+ }
23
+ // No global exception: only a matched independently approved pin may supply provenance.
24
+ const notBefore = exception?.notBefore ?? key.notBefore ?? key.validFrom ?? undefined;
25
+ const notAfter = key.notAfter ?? key.validTo ?? undefined;
26
+ const result = validateKeyLifecycle({
27
+ kid: key.kid, revoked: false,
28
+ ...(notBefore ? { notBefore } : {}), ...(notAfter ? { notAfter } : {}),
29
+ }, attestedAt);
30
+ if (notAfter && Date.parse(attestedAt) > Date.parse(notAfter)) {
31
+ return { state: 'invalid', code: 'KEY_EXPIRED' };
32
+ }
33
+ if (!result.ok) {
34
+ // Earlier than discovery's notBefore is not proof of invalid historical signing.
35
+ return { state: 'unknown', code: 'HISTORICAL_LIFECYCLE_UNKNOWN' };
36
+ }
37
+ if (!key.status || key.revoked === undefined || (key.status === 'deprecated' && !notAfter)) {
38
+ return { state: 'unknown', code: 'KEY_LIFECYCLE_UNKNOWN' };
39
+ }
40
+ return { state: 'valid', code: 'OK' };
41
+ }
42
+ //# sourceMappingURL=lifecycle.js.map
@@ -0,0 +1,14 @@
1
+ export interface ApprovedKeyPin {
2
+ readonly kid: string;
3
+ /** Independently approved raw Ed25519 public key, not learned from discovery. */
4
+ readonly publicKeyB64Url: string;
5
+ readonly historicalValidity?: {
6
+ readonly notBefore: string;
7
+ readonly provenance: string;
8
+ };
9
+ }
10
+ export interface TrustPolicy {
11
+ readonly expectedNodeId: string;
12
+ readonly pins: readonly ApprovedKeyPin[];
13
+ }
14
+ export declare const TRUST_POLICY: TrustPolicy;
@@ -0,0 +1,6 @@
1
+ export const TRUST_POLICY = Object.freeze({
2
+ expectedNodeId: 'nexart-node-prod-1',
3
+ // Intentionally empty. Adding a pin or historical exception requires separate approval.
4
+ pins: Object.freeze([]),
5
+ });
6
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1,3 @@
1
+ import { type ToolName, type VerificationOutput } from './contracts.js';
2
+ /** Exported for tests/library callers; the MCP transport invokes this same path. */
3
+ export declare function verify(tool: ToolName, args: unknown, signal?: AbortSignal): VerificationOutput;
package/dist/verify.js ADDED
@@ -0,0 +1,56 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ import { inputSchema } from './contracts.js';
3
+ import { dispatch } from './adapters.js';
4
+ import { checkInput, isObject, LIMITS } from './limits.js';
5
+ import { baseOutput, projectSdkResult } from './results.js';
6
+ /** Exported for tests/library callers; the MCP transport invokes this same path. */
7
+ export function verify(tool, args, signal) {
8
+ const output = baseOutput(tool, null);
9
+ const reject = (code, invalid = false) => ({
10
+ ...output, reasonCode: code, artifactIntegrity: invalid ? 'invalid' : 'not_performed',
11
+ });
12
+ try {
13
+ const limit = checkInput(args);
14
+ if (limit)
15
+ return reject(limit);
16
+ const parsed = inputSchema.safeParse(args);
17
+ if (!parsed.success || !Object.hasOwn(parsed.data, 'bundle')) {
18
+ return reject('INVALID_ARGUMENTS');
19
+ }
20
+ Object.assign(output, baseOutput(tool, parsed.data.bundle));
21
+ if (signal?.aborted)
22
+ return reject('CANCELLED');
23
+ const bundle = parsed.data.bundle;
24
+ if (tool === 'nexart_verify_project_bundle' && isObject(bundle) &&
25
+ Array.isArray(bundle.stepRegistry) && bundle.stepRegistry.length > LIMITS.projectSteps) {
26
+ return reject('PROJECT_STEP_LIMIT');
27
+ }
28
+ const started = performance.now();
29
+ const outcome = dispatch(tool, bundle);
30
+ // Synchronous SDK work cannot be interrupted by a notification mid-call.
31
+ // This check only observes cancellation already delivered by the transport.
32
+ if (signal?.aborted)
33
+ return reject('CANCELLED');
34
+ if ('rejection' in outcome)
35
+ return reject(outcome.rejection, true);
36
+ const raw = outcome.result;
37
+ output.sdk = projectSdkResult(raw);
38
+ const projectHashRequired = tool !== 'nexart_verify_project_bundle' ||
39
+ raw.projectHashValid === true;
40
+ output.artifactIntegrity = raw.ok && projectHashRequired ? 'valid' : 'invalid';
41
+ output.reasonCode = raw.ok && !projectHashRequired ? 'PROJECT_HASH_NOT_VERIFIED' : raw.code;
42
+ // No falsely advertised hard deadline: benchmark findings are documented.
43
+ if (performance.now() - started > 1_000) {
44
+ output.limitations.push('Synchronous verification exceeded one second and could not be preempted.');
45
+ }
46
+ if (Buffer.byteLength(JSON.stringify(output)) > LIMITS.outputBytes) {
47
+ return { ...reject('OUTPUT_LIMIT_EXCEEDED'), sdk: null };
48
+ }
49
+ return output;
50
+ }
51
+ catch {
52
+ // Never include a thrown SDK message, stack, key, field value or path.
53
+ return reject('SDK_EXCEPTION');
54
+ }
55
+ }
56
+ //# sourceMappingURL=verify.js.map
@@ -0,0 +1,5 @@
1
+ import type { WriteConfig } from './config.js';
2
+ /** Only the separate owner-operated TTY command calls this. Not exposed over MCP. */
3
+ export declare function issueApproval(config: WriteConfig, body: string, key: string, now?: number): void;
4
+ /** Atomically claim once across processes. No grant identifiers enter tool arguments. */
5
+ export declare function consumeApproval(config: WriteConfig, body: string, key: string, now?: number): boolean;
@@ -0,0 +1,95 @@
1
+ import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { constants, lstatSync, openSync, fstatSync, readFileSync, closeSync, realpathSync, writeFileSync, renameSync, unlinkSync, } from 'node:fs';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { NODE_ORIGIN } from '../network/client.js';
5
+ import { PUBLIC_PROFILE } from './profile.js';
6
+ const MAX_AGE_MS = 300_000;
7
+ const GRANT_VERSION = 1;
8
+ /** Local approval authentication only; never used for NexArt CER/commitment crypto. */
9
+ function binding(body, key, account) {
10
+ return createHmac('sha256', key).update(JSON.stringify({
11
+ profile: PUBLIC_PROFILE, destination: `${NODE_ORIGIN}/api/attest`,
12
+ visibility: 'public', account, body,
13
+ })).digest('hex');
14
+ }
15
+ /** Domain-separated authentication of every persisted grant field. The digest
16
+ * binds the unchanged CER body, account, destination, profile and visibility. */
17
+ function grantMac(digest, issuedAt, expiresAt, key) {
18
+ return createHmac('sha256', key).update(JSON.stringify({
19
+ purpose: 'nexart.mcp.public-approval-grant', version: GRANT_VERSION,
20
+ profile: PUBLIC_PROFILE, digest, issuedAt, expiresAt,
21
+ })).digest('hex');
22
+ }
23
+ function directory(config) {
24
+ const path = config.approvalDirectory;
25
+ if (!path || !isAbsolute(path) || realpathSync(path) !== resolve(path))
26
+ throw Error('UNSAFE_DIRECTORY');
27
+ const stat = lstatSync(path);
28
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o777) !== 0o700 ||
29
+ stat.uid !== process.getuid?.())
30
+ throw Error('UNSAFE_DIRECTORY');
31
+ return path;
32
+ }
33
+ function context(config, body, key) {
34
+ if (!config.publicEnabled || !config.attestEnabled || !config.accountContext?.trim() || !key)
35
+ throw Error('DISABLED');
36
+ return { dir: directory(config), digest: binding(body, key, config.accountContext) };
37
+ }
38
+ /** Only the separate owner-operated TTY command calls this. Not exposed over MCP. */
39
+ export function issueApproval(config, body, key, now = Date.now()) {
40
+ const { dir, digest } = context(config, body, key);
41
+ if (!Number.isSafeInteger(now) || !Number.isSafeInteger(now + MAX_AGE_MS))
42
+ throw Error('INVALID_TIME');
43
+ const expiresAt = now + MAX_AGE_MS;
44
+ const file = join(dir, `${digest}.json`);
45
+ const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
46
+ try {
47
+ writeFileSync(fd, JSON.stringify({
48
+ version: GRANT_VERSION, profile: PUBLIC_PROFILE, digest, issuedAt: now, expiresAt,
49
+ mac: grantMac(digest, now, expiresAt, key),
50
+ }));
51
+ }
52
+ finally {
53
+ closeSync(fd);
54
+ }
55
+ }
56
+ /** Atomically claim once across processes. No grant identifiers enter tool arguments. */
57
+ export function consumeApproval(config, body, key, now = Date.now()) {
58
+ let claimed;
59
+ try {
60
+ const { dir, digest } = context(config, body, key);
61
+ claimed = join(dir, `.consumed-${randomUUID()}`);
62
+ renameSync(join(dir, `${digest}.json`), claimed);
63
+ const fd = openSync(claimed, constants.O_RDONLY | constants.O_NOFOLLOW);
64
+ try {
65
+ const stat = fstatSync(fd);
66
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() ||
67
+ (stat.mode & 0o777) !== 0o600 || stat.size > 1_024)
68
+ return false;
69
+ const data = JSON.parse(readFileSync(fd, 'utf8'));
70
+ return Object.keys(data).sort().join(',') === 'digest,expiresAt,issuedAt,mac,profile,version'
71
+ && data.version === GRANT_VERSION && data.profile === PUBLIC_PROFILE && data.digest === digest
72
+ && typeof data.issuedAt === 'number' && typeof data.expiresAt === 'number'
73
+ && Number.isSafeInteger(data.issuedAt) && Number.isSafeInteger(data.expiresAt) && Number.isSafeInteger(now)
74
+ && typeof data.mac === 'string' && /^[0-9a-f]{64}$/.test(data.mac)
75
+ && timingSafeEqual(Buffer.from(data.mac, 'hex'), Buffer.from(grantMac(digest, data.issuedAt, data.expiresAt, key), 'hex'))
76
+ && data.issuedAt <= now && data.expiresAt > now
77
+ && data.expiresAt - data.issuedAt > 0 && data.expiresAt - data.issuedAt <= MAX_AGE_MS;
78
+ }
79
+ finally {
80
+ closeSync(fd);
81
+ }
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ finally {
87
+ if (claimed) {
88
+ try {
89
+ unlinkSync(claimed);
90
+ }
91
+ catch { /* never expose paths */ }
92
+ }
93
+ }
94
+ }
95
+ //# sourceMappingURL=approval.js.map
@@ -0,0 +1,14 @@
1
+ import { NodeNetwork } from '../network/client.js';
2
+ import { type TrustPolicy } from '../trust/policy.js';
3
+ import { type AttestOutput } from './contracts.js';
4
+ import type { WriteConfig } from './config.js';
5
+ import { type DisclosureProfile } from './profile.js';
6
+ import { AttestPoster } from './post.js';
7
+ export interface AttestDependencies {
8
+ network?: NodeNetwork;
9
+ poster?: AttestPoster;
10
+ policy?: TrustPolicy;
11
+ /** Trusted embedding only; never a tool argument or environment selector. */
12
+ disclosureProfile?: DisclosureProfile;
13
+ }
14
+ export declare function attest(args: unknown, config: WriteConfig, dependencies?: AttestDependencies, signal?: AbortSignal): Promise<AttestOutput>;
@@ -0,0 +1,140 @@
1
+ import * as z from 'zod/v4';
2
+ import { NodeNetwork, safeFailure } from '../network/client.js';
3
+ import { boundedString, hashSchema } from '../network/contracts.js';
4
+ import { receiptSchema } from '../receipts/contracts.js';
5
+ import { verifyReceipt } from '../receipts/verify.js';
6
+ import { TRUST_POLICY } from '../trust/policy.js';
7
+ import { attestInput } from './contracts.js';
8
+ import { boundedInput, validV2, disclosureEligible, LEGACY_DISCLOSURE, WRITE_LIMITS } from './profile.js';
9
+ import { consumeApproval } from './approval.js';
10
+ import { AttestPoster, SubmissionFailure } from './post.js';
11
+ const signature = z.string().regex(/^[A-Za-z0-9_-]{86}$/);
12
+ const responseSchema = z.object({
13
+ ok: z.literal(true), bundleType: z.literal('cer.ai.execution.v2'),
14
+ certificateHash: hashSchema, attestationId: boundedString,
15
+ nodeRuntimeHash: hashSchema, protocolVersion: z.literal('1.3.1'),
16
+ issuedAt: z.string().min(1).max(64), kid: boundedString, attestorKeyId: boundedString,
17
+ visibility: z.enum(['private', 'public']), receipt: receiptSchema,
18
+ signature,
19
+ attestation: z.object({
20
+ attestationId: boundedString, attestedAt: z.string().min(1).max(64),
21
+ certificateHash: hashSchema, bundleType: z.literal('cer.ai.execution.v2'),
22
+ nodeRuntimeHash: hashSchema, protocolVersion: z.literal('1.3.1'),
23
+ }),
24
+ verificationEnvelope: z.object({
25
+ algorithm: z.literal('Ed25519'), canonicalization: z.literal('jcs'),
26
+ envelopeType: z.literal('nexart.verification.envelope.v2'), kid: boundedString,
27
+ attestation: z.object({
28
+ attestationId: boundedString, attestedAt: z.string().min(1).max(64), kid: boundedString,
29
+ nodeRuntimeHash: hashSchema, protocolVersion: z.literal('1.3.1'),
30
+ }),
31
+ }),
32
+ verificationEnvelopeSignature: signature,
33
+ });
34
+ export async function attest(args, config, dependencies = {}, signal) {
35
+ let output = {
36
+ contractVersion: '1', reasonCode: 'INVALID_ARGUMENTS', submission: 'not_sent',
37
+ artifactIntegrity: 'not_performed', confidentialProfile: 'not_performed',
38
+ commitments: 'not_performed', requestedVisibility: null, nodeConfirmedVisibility: null,
39
+ publicationAuthorization: 'not_required', independentVerification: 'not_checked',
40
+ identity: 'absent', certificateHash: null, receipt: null, verificationEnvelopeSignature: 'not_performed',
41
+ limitations: [
42
+ 'Node-reported persistence and visibility are operational assertions, not signed visibility guarantees.',
43
+ 'No openings are submitted; protected plaintext is not verified against commitments.',
44
+ 'Producer identity is declared, not authenticated; Node API-key auth is not producer authentication.',
45
+ 'Signature validity, key lifecycle, signer trust and execution truth are separate.',
46
+ 'Public responses may be cached or copied permanently; later hiding cannot recall them.',
47
+ 'A timeout or invalid response can follow a committed write; never retry automatically.',
48
+ ],
49
+ };
50
+ if (!config.attestEnabled)
51
+ return { ...output, reasonCode: 'WRITE_DISABLED' };
52
+ const limit = boundedInput(args);
53
+ if (limit)
54
+ return { ...output, reasonCode: limit };
55
+ const parsed = attestInput.safeParse(args);
56
+ if (!parsed.success)
57
+ return output;
58
+ const input = parsed.data;
59
+ output.requestedVisibility = input.visibility;
60
+ output.publicationAuthorization = input.visibility === 'public' ? 'denied' : 'not_required';
61
+ if (!validV2(input.bundle))
62
+ return { ...output, reasonCode: 'INVALID_AI_V2_CER', artifactIntegrity: 'invalid' };
63
+ const bundle = input.bundle;
64
+ output.artifactIntegrity = 'valid';
65
+ if (input.certificateHash !== bundle.certificateHash)
66
+ return { ...output, reasonCode: 'CERTIFICATE_HASH_MISMATCH' };
67
+ output.certificateHash = input.certificateHash;
68
+ output.identity = bundle.snapshot.identity ? 'producer_declared_not_authenticated' : 'absent';
69
+ if (!disclosureEligible(bundle, 'private', dependencies.disclosureProfile ?? LEGACY_DISCLOSURE)) {
70
+ return { ...output, reasonCode: 'CONFIDENTIAL_PROFILE_REQUIRED', confidentialProfile: 'ineligible' };
71
+ }
72
+ output.confidentialProfile = 'eligible';
73
+ output.commitments = 'authentic_without_openings';
74
+ if (input.visibility === 'public') {
75
+ if (!config.publicEnabled)
76
+ return { ...output, reasonCode: 'PUBLIC_CERTIFICATION_DISABLED' };
77
+ if (!disclosureEligible(bundle, 'public', dependencies.disclosureProfile ?? LEGACY_DISCLOSURE))
78
+ return { ...output, reasonCode: 'PUBLIC_DISCLOSURE_PROFILE_REJECTED' };
79
+ }
80
+ const key = config.apiKey();
81
+ if (!key || /[\r\n]/.test(key))
82
+ return { ...output, reasonCode: 'NODE_CREDENTIAL_UNAVAILABLE' };
83
+ const body = JSON.stringify(bundle); // Original CER, unchanged; no projection/resealing.
84
+ const network = dependencies.network ?? new NodeNetwork(undefined, WRITE_LIMITS.timeoutMs);
85
+ const poster = dependencies.poster ?? new AttestPoster();
86
+ let started = false;
87
+ let received;
88
+ try {
89
+ output = await network.run(signal, async (active) => {
90
+ active.throwIfAborted();
91
+ if (input.visibility === 'public') {
92
+ if (!consumeApproval(config, body, key))
93
+ return { ...output, reasonCode: 'PUBLIC_OWNER_APPROVAL_REQUIRED' };
94
+ output.publicationAuthorization = 'approved';
95
+ }
96
+ active.throwIfAborted();
97
+ started = true;
98
+ const raw = await poster.submit(body, input.visibility, key, active);
99
+ const result = responseSchema.safeParse(raw);
100
+ if (!result.success)
101
+ throw new SubmissionFailure('INVALID_ATTEST_RESPONSE', 'outcome_unknown');
102
+ const data = result.data, r = data.receipt, a = data.attestation, e = data.verificationEnvelope.attestation;
103
+ if (data.certificateHash !== input.certificateHash || r.certificateHash !== input.certificateHash ||
104
+ a.certificateHash !== input.certificateHash ||
105
+ data.visibility !== input.visibility ||
106
+ [r.attestationId, a.attestationId, e.attestationId].some(id => id !== data.attestationId) ||
107
+ [r.nodeRuntimeHash, a.nodeRuntimeHash, e.nodeRuntimeHash].some(hash => hash !== data.nodeRuntimeHash) ||
108
+ [r.attestorKeyId, e.kid, data.attestorKeyId, data.verificationEnvelope.kid].some(kid => kid !== data.kid) ||
109
+ r.protocolVersion !== data.protocolVersion ||
110
+ [r.attestedAt, a.attestedAt, e.attestedAt].some(time => time !== data.issuedAt) ||
111
+ !Number.isFinite(Date.parse(data.issuedAt))) {
112
+ throw new SubmissionFailure('ATTEST_RESPONSE_BINDING_MISMATCH', 'outcome_unknown');
113
+ }
114
+ received = { receipt: r, signature: data.signature };
115
+ return { ...output, submission: 'node_reported_accepted',
116
+ nodeConfirmedVisibility: data.visibility, reasonCode: 'NODE_REPORTED_ACCEPTED',
117
+ independentVerification: data.visibility === 'private'
118
+ ? 'not_public_under_reported_visibility' : 'not_checked',
119
+ receipt: null };
120
+ });
121
+ // Receipt verification uses its own bounded GET operation after the POST
122
+ // slot is released. Never lose reported persistence if this second phase fails.
123
+ if (received) {
124
+ const checked = await verifyReceipt({
125
+ source: 'inline', certificateHash: input.certificateHash,
126
+ receipt: received.receipt, signatureB64Url: received.signature,
127
+ }, network, dependencies.policy ?? TRUST_POLICY, signal);
128
+ output = { ...output, receipt: checked, reasonCode: checked.signature === 'valid'
129
+ && checked.hashBinding === 'match' ? 'NODE_REPORTED_ACCEPTED' : 'ACCEPTED_RECEIPT_NOT_VERIFIED' };
130
+ }
131
+ return output;
132
+ }
133
+ catch (error) {
134
+ if (error instanceof SubmissionFailure)
135
+ return { ...output, reasonCode: error.code, submission: error.outcome };
136
+ return { ...output, reasonCode: started ? 'SUBMISSION_OUTCOME_UNKNOWN' : safeFailure(error),
137
+ submission: started ? 'outcome_unknown' : 'not_sent' };
138
+ }
139
+ }
140
+ //# sourceMappingURL=attest.js.map
@@ -0,0 +1,11 @@
1
+ /** Host configuration is never part of MCP tool arguments. All writes default OFF. */
2
+ export interface WriteConfig {
3
+ sealEnabled: boolean;
4
+ attestEnabled: boolean;
5
+ discloseCer: boolean;
6
+ publicEnabled: boolean;
7
+ approvalDirectory: string | undefined;
8
+ accountContext: string | undefined;
9
+ apiKey: () => string | undefined;
10
+ }
11
+ export declare function writeConfig(env?: NodeJS.ProcessEnv): WriteConfig;