@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,99 @@
1
+ import * as z from 'zod/v4';
2
+ import { dirname, isAbsolute } from 'node:path';
3
+ import { ownerDirectory, readOwnerInput } from '../owner/create.js';
4
+ import { reconcileOwnerAttempt } from '../owner/reconcile.js';
5
+ import { writeConfig } from '../write/config.js';
6
+ import { NodeNetwork } from '../network/client.js';
7
+ import { AttestPoster } from '../write/post.js';
8
+ import { WRITE_LIMITS } from '../write/profile.js';
9
+ import { controlDigest } from './policy.js';
10
+ import { publishWithPolicy, PublicationControlError } from './publication.js';
11
+ const label = z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/);
12
+ const path = z.string().min(1).refine(isAbsolute);
13
+ /** Local operator assertions, not protection from a same-UID agent. */
14
+ export const customerConsent = z.strictObject({
15
+ version: z.literal(1), mode: z.literal('customer_delegated'),
16
+ enabled: z.boolean(), automaticNodeSubmissions: z.boolean(),
17
+ publicDisclosureAcknowledged: z.boolean(), quotaConsumptionAcknowledged: z.boolean(),
18
+ revoked: z.boolean(), expiresAt: z.iso.datetime(),
19
+ accountContext: label, credentialContext: label,
20
+ policyFile: path, stateDirectory: path, approvalDirectory: path,
21
+ });
22
+ function readConsent(file) {
23
+ try {
24
+ if (!isAbsolute(file))
25
+ throw Error('PATH');
26
+ ownerDirectory(dirname(file));
27
+ const c = customerConsent.parse(readOwnerInput(file));
28
+ if (!c.enabled || !c.automaticNodeSubmissions ||
29
+ !c.publicDisclosureAcknowledged || !c.quotaConsumptionAcknowledged)
30
+ throw new PublicationControlError('CUSTOMER_CONSENT_REQUIRED');
31
+ if (c.revoked || Date.now() >= Date.parse(c.expiresAt))
32
+ throw new PublicationControlError('CUSTOMER_CONSENT_EXPIRED_OR_REVOKED');
33
+ return c;
34
+ }
35
+ catch (error) {
36
+ if (error instanceof PublicationControlError)
37
+ throw error;
38
+ throw new PublicationControlError('CUSTOMER_CERTIFICATION_CONFIG_INVALID');
39
+ }
40
+ }
41
+ function setupFailure(reasonCode) {
42
+ return { authorization: 'setup_required', submission: 'not_sent',
43
+ nodeConfirmedVisibility: null, reasonCode, receiptSignature: 'not_performed',
44
+ hashBinding: 'not_performed', signerTrust: 'not_established', reservedAttempts: null };
45
+ }
46
+ /** Explicit customer delegation. No Mac isolation claim and no credential
47
+ * discovery beyond the established NEXART_NODE_API_KEY callback.
48
+ * Dependencies are trusted library injection only, never MCP input or env. */
49
+ export function createCustomerPublisher(consentFile, credential = writeConfig().apiKey, dependencies = {}) {
50
+ // One bounded queue shared across this recording tool's calls.
51
+ const shared = { ...dependencies, network: dependencies.network ?? new NodeNetwork(undefined, WRITE_LIMITS.timeoutMs),
52
+ poster: dependencies.poster ?? new AttestPoster() };
53
+ const prepare = () => {
54
+ const consent = readConsent(consentFile);
55
+ const fingerprint = controlDigest(JSON.stringify(consent));
56
+ const recheck = () => {
57
+ if (controlDigest(JSON.stringify(readConsent(consentFile))) !== fingerprint)
58
+ throw new PublicationControlError('CUSTOMER_CONSENT_CHANGED');
59
+ };
60
+ const options = {
61
+ policyFile: consent.policyFile, stateDirectory: consent.stateDirectory,
62
+ approvalDirectory: consent.approvalDirectory, accountContext: consent.accountContext,
63
+ credentialContext: consent.credentialContext, credential,
64
+ };
65
+ return { options, recheck };
66
+ };
67
+ return Object.freeze({
68
+ async publish(record) {
69
+ try {
70
+ const { options, recheck } = prepare();
71
+ const key = credential();
72
+ if (!key || /[\r\n]/.test(key))
73
+ return setupFailure('NODE_CREDENTIAL_UNAVAILABLE');
74
+ return await publishWithPolicy(record, options, shared, { recheck });
75
+ }
76
+ catch (error) {
77
+ return setupFailure(error instanceof PublicationControlError
78
+ ? error.reasonCode : 'CUSTOMER_CERTIFICATION_CONFIG_INVALID');
79
+ }
80
+ },
81
+ /** Owner-invoked GET only; not exposed as a model-controlled MCP tool. */
82
+ async reconcile(certificateHash, request = globalThis.fetch) {
83
+ try {
84
+ const { options, recheck } = prepare();
85
+ recheck();
86
+ return await reconcileOwnerAttempt(certificateHash, options, (url, init) => {
87
+ recheck();
88
+ if (init?.method !== 'GET')
89
+ throw Error('GET_ONLY');
90
+ return request(url, init);
91
+ }, recheck);
92
+ }
93
+ catch {
94
+ throw Error('CUSTOMER_RECONCILIATION_FAILED_NO_RETRY');
95
+ }
96
+ },
97
+ });
98
+ }
99
+ //# sourceMappingURL=customer.js.map
@@ -0,0 +1,46 @@
1
+ import * as z from 'zod/v4';
2
+ import type { PreparedRecord } from './contracts.js';
3
+ export declare const ownerPolicy: z.ZodObject<{
4
+ version: z.ZodLiteral<1>;
5
+ id: z.ZodString;
6
+ revision: z.ZodNumber;
7
+ accountContext: z.ZodString;
8
+ credentialContext: z.ZodString;
9
+ credentialFingerprint: z.ZodString;
10
+ destination: z.ZodLiteral<"https://node.nexart.io/api/attest">;
11
+ evidenceTypes: z.ZodArray<z.ZodLiteral<"cer.ai.execution.v2">>;
12
+ captureSources: z.ZodArray<z.ZodEnum<{
13
+ producer_supplied: "producer_supplied";
14
+ instrumented_provider_call: "instrumented_provider_call";
15
+ }>>;
16
+ visibilities: z.ZodArray<z.ZodEnum<{
17
+ private: "private";
18
+ public: "public";
19
+ }>>;
20
+ requiredConfidentialFields: z.ZodArray<z.ZodEnum<{
21
+ output: "output";
22
+ input: "input";
23
+ instruction: "instruction";
24
+ decisionRefs: "decisionRefs";
25
+ }>>;
26
+ readableFields: z.ZodArray<z.ZodString>;
27
+ identityDisclosure: z.ZodDefault<z.ZodEnum<{
28
+ forbid: "forbid";
29
+ declared_allowlisted: "declared_allowlisted";
30
+ }>>;
31
+ nodeDisclosureProfile: z.ZodEnum<{
32
+ "ai-v2-resolver-reviewed-2026-11": "ai-v2-resolver-reviewed-2026-11";
33
+ "ai-v2-openai-disclosure-v1": "ai-v2-openai-disclosure-v1";
34
+ }>;
35
+ maximumCertifications: z.ZodNumber;
36
+ periodStartsAt: z.ZodISODateTime;
37
+ periodEndsAt: z.ZodISODateTime;
38
+ expiresAt: z.ZodISODateTime;
39
+ revoked: z.ZodBoolean;
40
+ }, z.core.$strict>;
41
+ export type OwnerPolicy = z.infer<typeof ownerPolicy>;
42
+ export declare const controlDigest: (text: string) => string;
43
+ export declare function readableLeafPaths(value: unknown, path?: string): string[];
44
+ /** A field allowlist is not a semantic PII detector. Approving readable paths
45
+ * authorizes their values; public metadata remains subject to the existing profile. */
46
+ export declare function evaluatePolicy(raw: unknown, record: PreparedRecord, account: string, credentialContext: string, key: string, now?: number): OwnerPolicy;
@@ -0,0 +1,67 @@
1
+ import * as z from 'zod/v4';
2
+ import { createHash } from 'node:crypto';
3
+ import { NODE_ORIGIN } from '../network/client.js';
4
+ import { disclosureEligible, LEGACY_DISCLOSURE, OPENAI_DISCLOSURE, validV2 } from '../write/profile.js';
5
+ const label = z.string().regex(/^[A-Za-z0-9._:-]{1,128}$/);
6
+ const date = z.iso.datetime();
7
+ export const ownerPolicy = z.strictObject({
8
+ version: z.literal(1), id: label, revision: z.number().int().positive(),
9
+ accountContext: label, credentialContext: label,
10
+ credentialFingerprint: z.string().regex(/^[0-9a-f]{64}$/),
11
+ destination: z.literal(`${NODE_ORIGIN}/api/attest`),
12
+ evidenceTypes: z.array(z.literal('cer.ai.execution.v2')).min(1).max(1),
13
+ captureSources: z.array(z.enum(['producer_supplied', 'instrumented_provider_call'])).min(1).max(2),
14
+ visibilities: z.array(z.enum(['public', 'private'])).min(1).max(2),
15
+ requiredConfidentialFields: z.array(z.enum(['input', 'output', 'instruction', 'decisionRefs'])).min(2).max(4),
16
+ // Exact JSON-pointer leaf paths, including array indices. No wildcards.
17
+ readableFields: z.array(z.string().regex(/^\/[A-Za-z0-9_/-]+$/)).min(1).max(256),
18
+ identityDisclosure: z.enum(['forbid', 'declared_allowlisted']).default('forbid'),
19
+ nodeDisclosureProfile: z.enum([LEGACY_DISCLOSURE, OPENAI_DISCLOSURE]),
20
+ maximumCertifications: z.number().int().min(1).max(1_000_000),
21
+ periodStartsAt: date, periodEndsAt: date, expiresAt: date, revoked: z.boolean(),
22
+ }).superRefine((p, ctx) => {
23
+ if (!p.requiredConfidentialFields.includes('input') || !p.requiredConfidentialFields.includes('output') ||
24
+ Date.parse(p.periodStartsAt) >= Date.parse(p.periodEndsAt) ||
25
+ Date.parse(p.expiresAt) > Date.parse(p.periodEndsAt))
26
+ ctx.addIssue({ code: 'custom', message: 'Invalid required protections or approved period' });
27
+ });
28
+ // Local control-plane digests only. CER hashes/commitments always come from SDK.
29
+ export const controlDigest = (text) => createHash('sha256').update(text).digest('hex');
30
+ export function readableLeafPaths(value, path = '') {
31
+ if (value === null || typeof value !== 'object')
32
+ return [path];
33
+ return Object.entries(value).flatMap(([key, child]) => readableLeafPaths(child, `${path}/${key}`));
34
+ }
35
+ /** A field allowlist is not a semantic PII detector. Approving readable paths
36
+ * authorizes their values; public metadata remains subject to the existing profile. */
37
+ export function evaluatePolicy(raw, record, account, credentialContext, key, now = Date.now()) {
38
+ const p = ownerPolicy.parse(raw);
39
+ if (p.revoked || now < Date.parse(p.periodStartsAt) || now >= Date.parse(p.periodEndsAt) ||
40
+ now >= Date.parse(p.expiresAt) || p.accountContext !== account ||
41
+ p.credentialContext !== credentialContext || p.credentialFingerprint !== controlDigest(key) ||
42
+ !key || /[\r\n]/.test(key))
43
+ throw Error('POLICY_AUTHORIZATION_DENIED');
44
+ const bundle = JSON.parse(record.body);
45
+ if (!validV2(bundle) || bundle.certificateHash !== record.certificateHash ||
46
+ !disclosureEligible(bundle, record.visibility, p.nodeDisclosureProfile) || !p.evidenceTypes.includes(bundle.bundleType) ||
47
+ !p.captureSources.includes(record.captureSource) || !p.visibilities.includes(record.visibility))
48
+ throw Error('POLICY_PROFILE_DENIED');
49
+ const s = bundle.snapshot;
50
+ if (s.identity !== undefined && p.identityDisclosure === 'forbid')
51
+ throw Error('POLICY_IDENTITY_DENIED');
52
+ for (const field of p.requiredConfidentialFields) {
53
+ if (field === 'decisionRefs') {
54
+ if (!Array.isArray(s.decisionRefs) || !s.decisionRefs.length)
55
+ throw Error('POLICY_PROTECTION_REQUIRED');
56
+ }
57
+ else {
58
+ const v = s[field];
59
+ if (!v || v._redacted !== true || v.mode !== 'confidential')
60
+ throw Error('POLICY_PROTECTION_REQUIRED');
61
+ }
62
+ }
63
+ if (readableLeafPaths(bundle).some(path => !p.readableFields.includes(path)))
64
+ throw Error('POLICY_DISCLOSURE_DENIED');
65
+ return p;
66
+ }
67
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1,23 @@
1
+ import { type AttestDependencies } from '../write/attest.js';
2
+ import type { PreparedRecord, PublicationResult } from './contracts.js';
3
+ /** Trusted application configuration, never MCP arguments. Isolated owner and
4
+ * explicitly consented customer delegation use the same exact-body pipeline. */
5
+ export interface OwnerPublicationOptions {
6
+ policyFile: string;
7
+ stateDirectory: string;
8
+ approvalDirectory: string;
9
+ accountContext: string;
10
+ credentialContext: string;
11
+ credential: () => string | undefined;
12
+ }
13
+ export declare function publishForTrustedApplication(record: PreparedRecord, options: OwnerPublicationOptions, dependencies?: AttestDependencies): Promise<PublicationResult>;
14
+ /** Only these constant control diagnostics may cross the publisher boundary. */
15
+ export declare class PublicationControlError extends Error {
16
+ readonly reasonCode: 'CUSTOMER_CONSENT_REQUIRED' | 'CUSTOMER_CONSENT_EXPIRED_OR_REVOKED' | 'CUSTOMER_CONSENT_CHANGED' | 'CUSTOMER_CERTIFICATION_CONFIG_INVALID';
17
+ constructor(reasonCode: 'CUSTOMER_CONSENT_REQUIRED' | 'CUSTOMER_CONSENT_EXPIRED_OR_REVOKED' | 'CUSTOMER_CONSENT_CHANGED' | 'CUSTOMER_CERTIFICATION_CONFIG_INVALID');
18
+ }
19
+ /** Shared transport, policy, approval and attempt core. No mode bypass flag.
20
+ * Customer entry validates consent; isolated entry retains requireIsolatedMac. */
21
+ export declare function publishWithPolicy(record: PreparedRecord, options: OwnerPublicationOptions, dependencies?: AttestDependencies, controls?: {
22
+ recheck: () => void;
23
+ }): Promise<PublicationResult>;
@@ -0,0 +1,148 @@
1
+ import { dirname, join } from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import { readOwnerInput, ownerDirectory } from '../owner/create.js';
4
+ import { issueApproval, consumeApproval } from '../write/approval.js';
5
+ import { attest } from '../write/attest.js';
6
+ import { writeConfig } from '../write/config.js';
7
+ import { AttestPoster } from '../write/post.js';
8
+ import { evaluatePolicy, controlDigest } from './policy.js';
9
+ import { reserveAttempt, retainOutcome, attemptName } from './state.js';
10
+ function denied(reasonCode) {
11
+ return { authorization: 'authorization_denied', submission: 'not_sent',
12
+ nodeConfirmedVisibility: null, reasonCode, receiptSignature: 'not_performed',
13
+ hashBinding: 'not_performed', signerTrust: 'not_established', reservedAttempts: null };
14
+ }
15
+ function readPolicy(path) {
16
+ ownerDirectory(dirname(path));
17
+ return readOwnerInput(path);
18
+ }
19
+ class PolicyBoundPoster extends AttestPoster {
20
+ delegate;
21
+ check;
22
+ constructor(delegate, check) {
23
+ super();
24
+ this.delegate = delegate;
25
+ this.check = check;
26
+ }
27
+ async submit(body, visibility, key, signal) {
28
+ this.check(body, visibility, key);
29
+ return this.delegate.submit(body, visibility, key, signal);
30
+ }
31
+ }
32
+ export async function publishForTrustedApplication(record, options, dependencies = {}) {
33
+ return publishWithPolicy(record, options, dependencies);
34
+ }
35
+ /** Only these constant control diagnostics may cross the publisher boundary. */
36
+ export class PublicationControlError extends Error {
37
+ reasonCode;
38
+ constructor(reasonCode) {
39
+ super(reasonCode);
40
+ this.reasonCode = reasonCode;
41
+ }
42
+ }
43
+ /** Shared transport, policy, approval and attempt core. No mode bypass flag.
44
+ * Customer entry validates consent; isolated entry retains requireIsolatedMac. */
45
+ export async function publishWithPolicy(record, options, dependencies = {}, controls) {
46
+ // Library-only dependency injection is identical to the existing attest API;
47
+ // neither dependencies nor owner configuration are accepted over MCP.
48
+ record = Object.freeze({ ...record });
49
+ let key = '', reservation;
50
+ let config;
51
+ let grantCreated = false;
52
+ let policyAuthorized = false;
53
+ let controlFailure;
54
+ const recheck = () => {
55
+ try {
56
+ controls?.recheck();
57
+ }
58
+ catch (error) {
59
+ if (error instanceof PublicationControlError)
60
+ controlFailure = error;
61
+ throw error;
62
+ }
63
+ };
64
+ try {
65
+ recheck();
66
+ const raw = readPolicy(options.policyFile);
67
+ key = options.credential() ?? '';
68
+ if (!key)
69
+ return { ...denied('NODE_CREDENTIAL_UNAVAILABLE'), authorization: 'setup_required' };
70
+ const policy = evaluatePolicy(raw, record, options.accountContext, options.credentialContext, key);
71
+ policyAuthorized = true;
72
+ ownerDirectory(options.approvalDirectory);
73
+ // Bind an immutable internal snapshot, not mutable caller objects.
74
+ const policyBytes = JSON.stringify(raw);
75
+ const bundle = JSON.parse(record.body);
76
+ if (JSON.stringify(bundle) !== record.body)
77
+ return denied('NONEXACT_BODY_REJECTED');
78
+ reservation = reserveAttempt(options.stateDirectory, policy, record, policyBytes);
79
+ // Recheck revocation/expiry/change after durable reservation and immediately
80
+ // before exact-body authorization. Changes burn this reservation, not retry.
81
+ const current = readPolicy(options.policyFile);
82
+ policyAuthorized = false;
83
+ recheck();
84
+ if (controlDigest(JSON.stringify(current)) !== controlDigest(policyBytes))
85
+ throw Error('POLICY_CHANGED');
86
+ evaluatePolicy(current, record, options.accountContext, options.credentialContext, key);
87
+ policyAuthorized = true;
88
+ config = writeConfig({
89
+ NEXART_ENABLE_ATTEST: 'true', NEXART_ENABLE_PUBLIC_ATTEST: 'true',
90
+ NEXART_PUBLIC_APPROVAL_DIRECTORY: options.approvalDirectory,
91
+ NEXART_NODE_ACCOUNT_CONTEXT: options.accountContext, NEXART_NODE_API_KEY: key,
92
+ });
93
+ if (record.visibility === 'public') {
94
+ issueApproval(config, record.body, key);
95
+ grantCreated = true;
96
+ }
97
+ const poster = new PolicyBoundPoster(dependencies.poster ?? new AttestPoster(), (body, visibility, credential) => {
98
+ policyAuthorized = false;
99
+ recheck();
100
+ if (body !== record.body || visibility !== record.visibility || credential !== key)
101
+ throw Error('EXACT_TRANSACTION_REQUIRED');
102
+ const latest = readPolicy(options.policyFile);
103
+ if (controlDigest(JSON.stringify(latest)) !== controlDigest(policyBytes))
104
+ throw Error('POLICY_CHANGED_BEFORE_POST');
105
+ evaluatePolicy(latest, record, options.accountContext, options.credentialContext, credential);
106
+ policyAuthorized = true;
107
+ });
108
+ const response = await attest({
109
+ certificateHash: record.certificateHash, bundle, visibility: record.visibility,
110
+ }, config, { ...dependencies, poster, disclosureProfile: policy.nodeDisclosureProfile });
111
+ const outcome = {
112
+ authorization: policyAuthorized ? 'policy_authorized' : 'authorization_denied',
113
+ // A consent callback failed before the delegate transport was invoked.
114
+ // Keep the burned reservation, but do not misreport an actual POST.
115
+ submission: controlFailure ? 'not_sent' : response.submission,
116
+ nodeConfirmedVisibility: response.nodeConfirmedVisibility, reasonCode: controlFailure?.reasonCode ?? response.reasonCode,
117
+ receiptSignature: response.receipt?.signature ?? 'not_performed',
118
+ hashBinding: response.receipt?.hashBinding ?? 'not_performed',
119
+ signerTrust: response.receipt?.signerTrust ?? 'not_established',
120
+ reservedAttempts: reservation.count,
121
+ };
122
+ // Exclusive outcome record; original marker is NEVER rewritten or removed.
123
+ retainOutcome(options.stateDirectory, reservation.file, outcome);
124
+ return outcome;
125
+ }
126
+ catch (error) {
127
+ // Reservation may have persisted even if fsync failed. Never clear state.
128
+ const persisted = existsSync(join(options.stateDirectory, `${attemptName(options.accountContext, record.certificateHash)}.attempt.json`));
129
+ return reservation || persisted
130
+ ? { ...denied('ATTEMPT_REQUIRES_OWNER_RECONCILIATION'), authorization: policyAuthorized ? 'policy_authorized' : 'authorization_denied',
131
+ submission: 'outcome_unknown', reservedAttempts: reservation?.count ?? null }
132
+ : controlFailure
133
+ ? { ...denied(controlFailure.reasonCode), authorization: 'setup_required' }
134
+ : denied(controls && error instanceof Error && [
135
+ 'PUBLISHER_LOCAL_BUDGET_EXHAUSTED', 'ATTEMPT_RESERVATION_BUSY',
136
+ 'POLICY_AUTHORIZATION_DENIED', 'POLICY_PROFILE_DENIED', 'POLICY_IDENTITY_DENIED',
137
+ 'POLICY_PROTECTION_REQUIRED', 'POLICY_DISCLOSURE_DENIED',
138
+ ].includes(error.message) ? error.message : 'OWNER_POLICY_OR_ATTEMPT_DENIED');
139
+ }
140
+ finally {
141
+ // Revoke a leftover public grant when validation/cancellation failed before
142
+ // consumption. The durable attempt still burns its local allowance.
143
+ if (grantCreated && config)
144
+ consumeApproval(config, record.body, key);
145
+ key = '';
146
+ }
147
+ }
148
+ //# sourceMappingURL=publication.js.map
@@ -0,0 +1,15 @@
1
+ import { type EncryptedCustody } from '../owner/custody.js';
2
+ import { type CaptureSource, type RecordResult, type PreparedRecord, type PublicationResult } from './contracts.js';
3
+ /** Trusted application configuration, never MCP arguments. Credential discovery
4
+ * belongs to the explicitly configured publisher, not this recording library. */
5
+ export interface RecordRuntime {
6
+ /** Trusted embedding port: must verify and durably retain encrypted recovery
7
+ * before returning the SDK CER. Never populated from environment/tool input. */
8
+ createConfidential?: (creation: unknown) => Promise<unknown>;
9
+ custodyDirectory?: string;
10
+ recoveryStorage?: 'unencrypted_owner_approved';
11
+ encryptedCustody?: EncryptedCustody;
12
+ captureSource?: CaptureSource;
13
+ publish?: (record: PreparedRecord) => Promise<PublicationResult>;
14
+ }
15
+ export declare function recordExecution(raw: unknown, runtime?: RecordRuntime): Promise<RecordResult>;
@@ -0,0 +1,97 @@
1
+ import { join } from 'node:path';
2
+ import { verifyConfidentialV2 } from '@nexart/ai-execution';
3
+ import { createOwnerConfidential, readOwnerInput } from '../owner/create.js';
4
+ import { createEncryptedConfidential, EncryptedCustodyError } from '../owner/custody.js';
5
+ import { boundedInput, validV2 } from '../write/profile.js';
6
+ import { recordInput } from './contracts.js';
7
+ export async function recordExecution(raw, runtime = {}) {
8
+ const result = {
9
+ contractVersion: '1', captureProvenance: runtime.captureSource ?? 'producer_supplied',
10
+ evidence: 'not_created', custody: 'not_performed', localIntegrity: 'not_performed',
11
+ certificationIntent: 'node', policyAuthorization: 'setup_required', submission: 'not_sent',
12
+ requestedVisibility: 'public', nodeConfirmedVisibility: null, certificateHash: null,
13
+ receiptSignature: 'not_performed', hashBinding: 'not_performed', signerTrust: 'not_established',
14
+ reasonCode: 'INVALID_ARGUMENTS',
15
+ usage: { authoritative: false, accountRemaining: null, scope: 'publisher_local', reservedAttempts: null },
16
+ };
17
+ try {
18
+ if (boundedInput(raw))
19
+ return result;
20
+ const parsed = recordInput.safeParse(raw);
21
+ if (!parsed.success)
22
+ return result;
23
+ const input = parsed.data, mode = input.certification?.mode ?? 'node';
24
+ const visibility = input.certification?.visibility ?? 'public';
25
+ result.certificationIntent = mode;
26
+ result.requestedVisibility = mode === 'node' ? visibility : null;
27
+ result.policyAuthorization = mode === 'local' ? 'not_required' : 'setup_required';
28
+ let bundle;
29
+ if (input.kind === 'execution') {
30
+ if (!runtime.createConfidential && !runtime.encryptedCustody && (!runtime.custodyDirectory || runtime.recoveryStorage !== 'unencrypted_owner_approved')) {
31
+ return { ...result, evidence: 'custody_failed', reasonCode: 'APPROVED_CUSTODY_REQUIRED' };
32
+ }
33
+ try {
34
+ // Protect instruction/decision references when present, as well as IO.
35
+ // No salt input and no opening output. Reuse the durable owner workflow.
36
+ const creation = {
37
+ execution: input.execution, createdAt: input.createdAt,
38
+ protectInstruction: input.execution.instruction !== undefined,
39
+ decisionRefIndexes: Array.isArray(input.execution.decisionRefs)
40
+ ? input.execution.decisionRefs.map((_, i) => i) : [],
41
+ };
42
+ if (runtime.createConfidential) {
43
+ bundle = await runtime.createConfidential(creation);
44
+ result.custody = 'encrypted_owner_recipient';
45
+ }
46
+ else if (runtime.encryptedCustody) {
47
+ bundle = createEncryptedConfidential(creation, runtime.encryptedCustody);
48
+ result.custody = 'encrypted_owner_recipient';
49
+ }
50
+ else {
51
+ const created = createOwnerConfidential(creation, runtime.custodyDirectory);
52
+ bundle = readOwnerInput(join(runtime.custodyDirectory, created.certificateHash.replace(':', '-'), 'cer.json'));
53
+ result.custody = 'unencrypted_owner_approved';
54
+ }
55
+ result.evidence = 'created_confidential';
56
+ }
57
+ catch (error) {
58
+ return { ...result, evidence: 'custody_failed', reasonCode: error instanceof EncryptedCustodyError
59
+ ? error.reasonCode : runtime.encryptedCustody
60
+ ? 'ENCRYPTED_CREATION_OR_CUSTODY_FAILED' : 'CONFIDENTIAL_CREATION_OR_CUSTODY_FAILED' };
61
+ }
62
+ }
63
+ else {
64
+ bundle = input.bundle;
65
+ result.evidence = 'existing_unchanged';
66
+ result.custody = 'external_existing_cer';
67
+ }
68
+ if (!validV2(bundle) || verifyConfidentialV2(bundle).state !== 'AUTHENTIC') {
69
+ return { ...result, evidence: 'invalid', localIntegrity: 'invalid', reasonCode: 'INVALID_CONFIDENTIAL_AI_V2' };
70
+ }
71
+ result.localIntegrity = 'valid';
72
+ result.certificateHash = bundle.certificateHash;
73
+ if (mode === 'local')
74
+ return { ...result, reasonCode: 'LOCAL_ONLY_EVIDENCE_SEALED' };
75
+ if (!runtime.publish)
76
+ return { ...result, reasonCode: 'OWNER_PUBLISHER_SETUP_REQUIRED' };
77
+ // Snapshot once; mutation of the caller object cannot change approved bytes.
78
+ const prepared = Object.freeze({
79
+ body: JSON.stringify(bundle), certificateHash: bundle.certificateHash,
80
+ visibility, captureSource: result.captureProvenance,
81
+ });
82
+ const published = await runtime.publish(prepared);
83
+ return {
84
+ ...result, policyAuthorization: published.authorization, submission: published.submission,
85
+ nodeConfirmedVisibility: published.nodeConfirmedVisibility, reasonCode: published.reasonCode,
86
+ receiptSignature: published.receiptSignature, hashBinding: published.hashBinding,
87
+ signerTrust: published.signerTrust,
88
+ usage: { ...result.usage, reservedAttempts: published.reservedAttempts },
89
+ };
90
+ }
91
+ catch {
92
+ // A custom trusted port may have sent before throwing; never imply safe retry.
93
+ return { ...result, reasonCode: 'OWNER_PUBLISHER_OUTCOME_UNKNOWN',
94
+ submission: runtime.publish && result.localIntegrity === 'valid' ? 'outcome_unknown' : 'not_sent' };
95
+ }
96
+ }
97
+ //# sourceMappingURL=record.js.map
@@ -0,0 +1,44 @@
1
+ import * as z from 'zod/v4';
2
+ import { type OwnerPolicy } from './policy.js';
3
+ import type { PreparedRecord } from './contracts.js';
4
+ export declare function durableExclusive(path: string, value: unknown): void;
5
+ export declare function attemptName(account: string, hash: string): string;
6
+ export interface Attempt {
7
+ version: 1;
8
+ accountContext: string;
9
+ policyId: string;
10
+ policyRevision: number;
11
+ policyDigest: string;
12
+ certificateHash: string;
13
+ body: string;
14
+ visibility: 'public' | 'private';
15
+ captureSource: string;
16
+ reservedAt: string;
17
+ state: 'potentially_sent_do_not_repeat';
18
+ }
19
+ export declare const attemptSchema: z.ZodObject<{
20
+ version: z.ZodLiteral<1>;
21
+ accountContext: z.ZodString;
22
+ policyId: z.ZodString;
23
+ policyRevision: z.ZodNumber;
24
+ policyDigest: z.ZodString;
25
+ certificateHash: z.ZodString;
26
+ body: z.ZodString;
27
+ visibility: z.ZodEnum<{
28
+ private: "private";
29
+ public: "public";
30
+ }>;
31
+ captureSource: z.ZodEnum<{
32
+ producer_supplied: "producer_supplied";
33
+ instrumented_provider_call: "instrumented_provider_call";
34
+ }>;
35
+ reservedAt: z.ZodISODateTime;
36
+ state: z.ZodLiteral<"potentially_sent_do_not_repeat">;
37
+ }, z.core.$strict>;
38
+ /** Synchronous lock/reserve spans processes. A stale lock is a fail-closed
39
+ * administrative reconciliation event, never an automatically cleared lock. */
40
+ export declare function reserveAttempt(stateDirectory: string, policy: OwnerPolicy, record: PreparedRecord, policyBytes: string, now?: number): {
41
+ file: string;
42
+ count: number;
43
+ };
44
+ export declare function retainOutcome(stateDirectory: string, file: string, outcome: unknown): void;
@@ -0,0 +1,84 @@
1
+ import { constants, openSync, writeFileSync, fsyncSync, closeSync, mkdirSync, rmdirSync, readdirSync, } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import * as z from 'zod/v4';
4
+ import { ownerDirectory, readOwnerInput } from '../owner/create.js';
5
+ import { controlDigest } from './policy.js';
6
+ import { boundedInput } from '../write/profile.js';
7
+ import { hashSchema } from '../network/contracts.js';
8
+ export function durableExclusive(path, value) {
9
+ const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
10
+ try {
11
+ writeFileSync(fd, JSON.stringify(value));
12
+ fsyncSync(fd);
13
+ }
14
+ finally {
15
+ closeSync(fd);
16
+ }
17
+ }
18
+ function syncDirectory(path) {
19
+ const fd = openSync(path, constants.O_RDONLY);
20
+ try {
21
+ fsyncSync(fd);
22
+ }
23
+ finally {
24
+ closeSync(fd);
25
+ }
26
+ }
27
+ export function attemptName(account, hash) {
28
+ return controlDigest(JSON.stringify({ account, hash }));
29
+ }
30
+ export const attemptSchema = z.strictObject({
31
+ version: z.literal(1), accountContext: z.string().min(1), policyId: z.string().min(1),
32
+ policyRevision: z.number().int().positive(), policyDigest: z.string().regex(/^[0-9a-f]{64}$/),
33
+ certificateHash: hashSchema, body: z.string().min(1), visibility: z.enum(['public', 'private']),
34
+ captureSource: z.enum(['producer_supplied', 'instrumented_provider_call']),
35
+ reservedAt: z.iso.datetime(), state: z.literal('potentially_sent_do_not_repeat'),
36
+ });
37
+ /** Synchronous lock/reserve spans processes. A stale lock is a fail-closed
38
+ * administrative reconciliation event, never an automatically cleared lock. */
39
+ export function reserveAttempt(stateDirectory, policy, record, policyBytes, now = Date.now()) {
40
+ ownerDirectory(stateDirectory);
41
+ const lock = join(stateDirectory, 'reservation.lock');
42
+ try {
43
+ mkdirSync(lock, { mode: 0o700 });
44
+ }
45
+ catch {
46
+ throw Error('ATTEMPT_RESERVATION_BUSY');
47
+ }
48
+ try {
49
+ let count = 0;
50
+ for (const name of readdirSync(stateDirectory)) {
51
+ if (!/^[0-9a-f]{64}\.attempt\.json$/.test(name))
52
+ continue;
53
+ const a = attemptSchema.parse(readOwnerInput(join(stateDirectory, name)));
54
+ if (name !== `${attemptName(a.accountContext, a.certificateHash)}.attempt.json`)
55
+ throw Error('ATTEMPT_STATE_REJECTED');
56
+ if (a.accountContext === policy.accountContext && a.policyId === policy.id &&
57
+ Date.parse(a.reservedAt) >= Date.parse(policy.periodStartsAt) &&
58
+ Date.parse(a.reservedAt) < Date.parse(policy.periodEndsAt))
59
+ count++;
60
+ }
61
+ if (count >= policy.maximumCertifications)
62
+ throw Error('PUBLISHER_LOCAL_BUDGET_EXHAUSTED');
63
+ const file = join(stateDirectory, `${attemptName(policy.accountContext, record.certificateHash)}.attempt.json`);
64
+ const attempt = {
65
+ version: 1, accountContext: policy.accountContext, policyId: policy.id, policyRevision: policy.revision,
66
+ policyDigest: controlDigest(policyBytes), certificateHash: record.certificateHash, body: record.body,
67
+ visibility: record.visibility, captureSource: record.captureSource,
68
+ reservedAt: new Date(now).toISOString(), state: 'potentially_sent_do_not_repeat',
69
+ };
70
+ if (boundedInput(attempt))
71
+ throw Error('ATTEMPT_STATE_TOO_LARGE');
72
+ durableExclusive(file, attempt);
73
+ syncDirectory(stateDirectory); // Must complete before any grant or POST.
74
+ return { file, count: count + 1 };
75
+ }
76
+ finally {
77
+ rmdirSync(lock);
78
+ }
79
+ }
80
+ export function retainOutcome(stateDirectory, file, outcome) {
81
+ durableExclusive(`${file}.outcome.json`, outcome);
82
+ syncDirectory(stateDirectory);
83
+ }
84
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1,13 @@
1
+ import type { McpServer } from '@modelcontextprotocol/server';
2
+ import { type EncryptedCustody } from './owner/custody.js';
3
+ import { type RecordResult } from './record/contracts.js';
4
+ import type { RecordRuntime } from './record/record.js';
5
+ export interface RecordingConfig {
6
+ enabled: boolean;
7
+ custody?: EncryptedCustody;
8
+ publish?: RecordRuntime['publish'];
9
+ /** Trusted hosted embedding only; no environment/stdio selector. */
10
+ execute?: (args: unknown) => Promise<RecordResult>;
11
+ }
12
+ export declare function recordingConfig(env?: NodeJS.ProcessEnv): RecordingConfig;
13
+ export declare function registerRecordingTool(server: McpServer, config?: RecordingConfig): void;