@attested-intelligence/aga-mcp-server 2.2.0 → 2.2.1

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 (80) hide show
  1. package/README.md +77 -65
  2. package/dist/adapters/openclaw.d.ts +0 -1
  3. package/dist/adapters/openclaw.d.ts.map +1 -1
  4. package/dist/adapters/openclaw.js +0 -1
  5. package/dist/adapters/openclaw.js.map +1 -1
  6. package/dist/proxy/evaluator.d.ts +0 -1
  7. package/dist/proxy/evaluator.d.ts.map +1 -1
  8. package/dist/proxy/evaluator.js +0 -1
  9. package/dist/proxy/evaluator.js.map +1 -1
  10. package/dist/proxy/index.d.ts +0 -1
  11. package/dist/proxy/index.d.ts.map +1 -1
  12. package/dist/proxy/index.js +0 -1
  13. package/dist/proxy/index.js.map +1 -1
  14. package/dist/proxy/profiles.d.ts +0 -1
  15. package/dist/proxy/profiles.d.ts.map +1 -1
  16. package/dist/proxy/profiles.js +0 -1
  17. package/dist/proxy/profiles.js.map +1 -1
  18. package/dist/proxy/server.d.ts +0 -1
  19. package/dist/proxy/server.d.ts.map +1 -1
  20. package/dist/proxy/server.js +0 -1
  21. package/dist/proxy/server.js.map +1 -1
  22. package/dist/proxy/stdio-bridge.d.ts +0 -1
  23. package/dist/proxy/stdio-bridge.d.ts.map +1 -1
  24. package/dist/proxy/stdio-bridge.js +0 -1
  25. package/dist/proxy/stdio-bridge.js.map +1 -1
  26. package/dist/proxy/types.d.ts +0 -1
  27. package/dist/proxy/types.d.ts.map +1 -1
  28. package/dist/proxy/types.js +0 -1
  29. package/dist/proxy/types.js.map +1 -1
  30. package/dist/proxy/verify.d.ts +0 -1
  31. package/dist/proxy/verify.d.ts.map +1 -1
  32. package/dist/proxy/verify.js +0 -1
  33. package/dist/proxy/verify.js.map +1 -1
  34. package/package.json +92 -97
  35. package/SECURITY.md +0 -59
  36. package/independent-verifier/README.md +0 -31
  37. package/independent-verifier/package.json +0 -18
  38. package/independent-verifier/verify.ts +0 -211
  39. package/src/adapters/openclaw.ts +0 -125
  40. package/src/core/artifact.ts +0 -45
  41. package/src/core/attestation.ts +0 -33
  42. package/src/core/behavioral.ts +0 -132
  43. package/src/core/bundle.ts +0 -45
  44. package/src/core/chain.ts +0 -72
  45. package/src/core/checkpoint.ts +0 -22
  46. package/src/core/delegation.ts +0 -146
  47. package/src/core/disclosure.ts +0 -32
  48. package/src/core/identity.ts +0 -62
  49. package/src/core/index.ts +0 -14
  50. package/src/core/portal.ts +0 -117
  51. package/src/core/quarantine.ts +0 -16
  52. package/src/core/receipt.ts +0 -33
  53. package/src/core/subject.ts +0 -11
  54. package/src/core/types.ts +0 -285
  55. package/src/crypto/hash.ts +0 -33
  56. package/src/crypto/index.ts +0 -5
  57. package/src/crypto/merkle.ts +0 -43
  58. package/src/crypto/salt.ts +0 -18
  59. package/src/crypto/sign.ts +0 -42
  60. package/src/crypto/types.ts +0 -19
  61. package/src/index.ts +0 -12
  62. package/src/middleware/governance.ts +0 -95
  63. package/src/middleware/index.ts +0 -1
  64. package/src/proxy/evaluator.ts +0 -176
  65. package/src/proxy/index.ts +0 -259
  66. package/src/proxy/profiles.ts +0 -48
  67. package/src/proxy/server.ts +0 -499
  68. package/src/proxy/stdio-bridge.ts +0 -171
  69. package/src/proxy/types.ts +0 -40
  70. package/src/proxy/verify.ts +0 -202
  71. package/src/server.ts +0 -435
  72. package/src/storage/index.ts +0 -3
  73. package/src/storage/interface.ts +0 -21
  74. package/src/storage/memory.ts +0 -27
  75. package/src/storage/sqlite.ts +0 -45
  76. package/src/tools/README.md +0 -13
  77. package/src/utils/canonical.ts +0 -14
  78. package/src/utils/constants.ts +0 -3
  79. package/src/utils/timestamp.ts +0 -12
  80. package/src/utils/uuid.ts +0 -2
@@ -1,125 +0,0 @@
1
- /**
2
- * OpenClaw Config Adapter
3
- * Detects and patches openclaw.json to route MCP servers through the AGA governance proxy.
4
- *
5
- * All OpenClaw assumptions are documented inline. When a real OpenClaw instance
6
- * becomes available, validate each assumption.
7
- *
8
- * Patent: USPTO App. No. 19/433,835
9
- * Copyright (c) 2026 Attested Intelligence Holdings LLC
10
- * SPDX-License-Identifier: MIT
11
- */
12
-
13
- import * as fs from 'node:fs';
14
- import * as path from 'node:path';
15
- import * as os from 'node:os';
16
-
17
- // ── Assumptions ──────────────────────────────────────────────
18
- // ASSUMPTION 1: OpenClaw stores its config at ~/.openclaw/openclaw.json
19
- // Source: OpenClaw documentation pattern (similar to Claude Desktop, Cursor)
20
- // Fallback: Accept explicit path via detect(configPath?)
21
- //
22
- // ASSUMPTION 2: Config has a "mcpServers" field with server entries
23
- // Source: MCP client config convention (matches Claude Desktop format)
24
- // Format: { "mcpServers": { "name": { "command": "...", "args": [...] } } }
25
- //
26
- // ASSUMPTION 3: Each server entry has "command" + "args" (stdio) or "url" (HTTP)
27
- // Source: MCP transport specification
28
- // Fallback: Skip entries that don't match either pattern
29
-
30
- export interface McpServerConfig {
31
- name: string;
32
- command?: string;
33
- args?: string[];
34
- url?: string;
35
- env?: Record<string, string>;
36
- [key: string]: unknown;
37
- }
38
-
39
- export interface AgentConfigAdapter {
40
- detect(configPath?: string): Promise<{ found: boolean; path: string; version?: string }>;
41
- readMcpServers(): Promise<McpServerConfig[]>;
42
- patchMcpServers(proxyPort: number, originals: McpServerConfig[]): Promise<void>;
43
- restore(): Promise<void>;
44
- }
45
-
46
- export class OpenClawAdapter implements AgentConfigAdapter {
47
- private configPath: string | null = null;
48
- private backupPath: string | null = null;
49
-
50
- private getDefaultPath(): string {
51
- return path.join(os.homedir(), '.openclaw', 'openclaw.json');
52
- }
53
-
54
- async detect(configPath?: string): Promise<{ found: boolean; path: string; version?: string }> {
55
- const p = configPath ?? this.getDefaultPath();
56
- this.configPath = p;
57
- this.backupPath = p + '.aga-backup';
58
-
59
- if (!fs.existsSync(p)) {
60
- return { found: false, path: p };
61
- }
62
-
63
- try {
64
- const config = JSON.parse(fs.readFileSync(p, 'utf-8'));
65
- return {
66
- found: true,
67
- path: p,
68
- version: config.version ?? config.openclaw_version ?? undefined,
69
- };
70
- } catch {
71
- return { found: false, path: p };
72
- }
73
- }
74
-
75
- async readMcpServers(): Promise<McpServerConfig[]> {
76
- if (!this.configPath) throw new Error('Call detect() first');
77
-
78
- const config = JSON.parse(fs.readFileSync(this.configPath, 'utf-8'));
79
- const servers = config.mcpServers ?? {};
80
- return Object.entries(servers).map(([name, entry]) => ({
81
- name,
82
- ...(entry as Record<string, unknown>),
83
- }));
84
- }
85
-
86
- async patchMcpServers(proxyPort: number, originals: McpServerConfig[]): Promise<void> {
87
- if (!this.configPath || !this.backupPath) throw new Error('Call detect() first');
88
-
89
- // Backup original
90
- const originalContent = fs.readFileSync(this.configPath, 'utf-8');
91
- fs.writeFileSync(this.backupPath, originalContent);
92
-
93
- const config = JSON.parse(originalContent);
94
-
95
- // Rewrite each MCP server entry to point at the proxy
96
- // The proxy will forward to the original command/URL
97
- for (const server of originals) {
98
- if (config.mcpServers?.[server.name]) {
99
- const original = config.mcpServers[server.name];
100
-
101
- // Store original config for the proxy to use
102
- config.mcpServers[server.name] = {
103
- // Point at proxy instead
104
- url: `http://127.0.0.1:${proxyPort}`,
105
- // Preserve metadata
106
- _aga_original: original,
107
- _aga_governed: true,
108
- };
109
- }
110
- }
111
-
112
- fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2));
113
- }
114
-
115
- async restore(): Promise<void> {
116
- if (!this.configPath || !this.backupPath) throw new Error('Call detect() first');
117
-
118
- if (fs.existsSync(this.backupPath)) {
119
- fs.copyFileSync(this.backupPath, this.configPath);
120
- fs.unlinkSync(this.backupPath);
121
- } else {
122
- throw new Error('No backup found - cannot restore');
123
- }
124
- }
125
- }
@@ -1,45 +0,0 @@
1
- import { signStr, sigToB64, b64ToSig, pkToHex, hexToPk, verifyStr } from '../crypto/sign.js';
2
- import { sha256Str } from '../crypto/hash.js';
3
- import { canonicalize } from '../utils/canonical.js';
4
- import { utcNow } from '../utils/timestamp.js';
5
- import { SCHEMA_VERSION, PROTOCOL_VERSION } from '../utils/constants.js';
6
- import type { KeyPair, HashHex } from '../crypto/types.js';
7
- import type { PolicyArtifact, SubjectIdentifier, EnforcementParams, DisclosurePolicy, EvidenceCommitmentRecord } from './types.js';
8
-
9
- export interface ArtifactInput {
10
- subject_identifier: SubjectIdentifier;
11
- policy_reference: HashHex;
12
- policy_version: number;
13
- sealed_hash: HashHex;
14
- seal_salt: string;
15
- enforcement_parameters: EnforcementParams;
16
- disclosure_policy: DisclosurePolicy;
17
- evidence_commitments: EvidenceCommitmentRecord[];
18
- issuer_keypair: KeyPair;
19
- effective_timestamp?: string;
20
- expiration_timestamp?: string | null;
21
- }
22
-
23
- export function generateArtifact(input: ArtifactInput): PolicyArtifact {
24
- const now = utcNow();
25
- const unsigned: Omit<PolicyArtifact, 'signature'> = {
26
- schema_version: SCHEMA_VERSION, protocol_version: PROTOCOL_VERSION,
27
- subject_identifier: input.subject_identifier, policy_reference: input.policy_reference,
28
- policy_version: input.policy_version, sealed_hash: input.sealed_hash,
29
- seal_salt: input.seal_salt, issued_timestamp: now,
30
- effective_timestamp: input.effective_timestamp ?? now,
31
- expiration_timestamp: input.expiration_timestamp ?? null,
32
- issuer_identifier: pkToHex(input.issuer_keypair.publicKey),
33
- enforcement_parameters: input.enforcement_parameters,
34
- disclosure_policy: input.disclosure_policy,
35
- evidence_commitments: input.evidence_commitments,
36
- };
37
- return { ...unsigned, signature: sigToB64(signStr(canonicalize(unsigned), input.issuer_keypair.secretKey)) };
38
- }
39
-
40
- export function hashArtifact(a: PolicyArtifact): HashHex { return sha256Str(canonicalize(a)); }
41
-
42
- export function verifyArtifactSignature(a: PolicyArtifact, issuerPkHex: string): boolean {
43
- const { signature, ...unsigned } = a;
44
- return verifyStr(b64ToSig(signature), canonicalize(unsigned), hexToPk(issuerPkHex));
45
- }
@@ -1,33 +0,0 @@
1
- import { saltedCommitment, generateSalt } from '../crypto/salt.js';
2
- import { sha256HexCat } from '../crypto/hash.js';
3
- import type { SubjectIdentifier, EvidenceCommitmentRecord } from './types.js';
4
- import type { HashHex, SaltHex } from '../crypto/types.js';
5
-
6
- export interface AttestationInput {
7
- subject_identifier: SubjectIdentifier;
8
- policy_reference: HashHex;
9
- evidence_items: Array<{ label: string; content: string }>;
10
- }
11
-
12
- export interface AttestationResult {
13
- success: boolean;
14
- sealed_hash: HashHex | null;
15
- seal_salt: SaltHex | null;
16
- evidence_commitments: EvidenceCommitmentRecord[];
17
- rejection_reason: string | null;
18
- }
19
-
20
- export function performAttestation(input: AttestationInput): AttestationResult {
21
- const evidence_commitments = input.evidence_items.map(item => {
22
- const { commitment, salt } = saltedCommitment(item.content);
23
- return { commitment, salt, label: item.label };
24
- });
25
- const seal_salt = generateSalt();
26
- const sealed_hash = sha256HexCat(
27
- input.subject_identifier.bytes_hash,
28
- input.subject_identifier.metadata_hash,
29
- input.policy_reference,
30
- seal_salt
31
- );
32
- return { success: true, sealed_hash, seal_salt, evidence_commitments, rejection_reason: null };
33
- }
@@ -1,132 +0,0 @@
1
- /**
2
- * Behavioral Drift Detection.
3
- * NIST-2025-0035: "Governance mechanisms must measure behavioral outputs
4
- * and decision patterns in addition to static artifacts."
5
- *
6
- * Tracks tool invocation patterns and compares against a behavioral
7
- * baseline sealed in the policy artifact.
8
- */
9
- import { sha256Str } from '../crypto/hash.js';
10
- import type { HashHex } from '../crypto/types.js';
11
-
12
- export interface ToolInvocation {
13
- tool_name: string;
14
- timestamp: string;
15
- args_hash: HashHex; // hash of args, not args themselves (privacy)
16
- }
17
-
18
- export interface BehavioralBaseline {
19
- /** Allowed tools in this policy context */
20
- permitted_tools: string[];
21
- /** Maximum invocations per tool per measurement window */
22
- rate_limits: Record<string, number>;
23
- /** Forbidden tool sequences (e.g., read_secret then send_email) */
24
- forbidden_sequences: string[][];
25
- /** Measurement window in milliseconds */
26
- window_ms: number;
27
- }
28
-
29
- export interface BehavioralMeasurement {
30
- window_start: string;
31
- window_end: string;
32
- invocations: ToolInvocation[];
33
- violations: BehavioralViolation[];
34
- behavioral_hash: HashHex; // hash of the behavioral pattern
35
- drift_detected: boolean;
36
- }
37
-
38
- export type BehavioralViolation =
39
- | { type: 'UNAUTHORIZED_TOOL'; tool: string }
40
- | { type: 'RATE_EXCEEDED'; tool: string; count: number; limit: number }
41
- | { type: 'FORBIDDEN_SEQUENCE'; sequence: string[] };
42
-
43
- export class BehavioralMonitor {
44
- private invocations: ToolInvocation[] = [];
45
- private baseline: BehavioralBaseline | null = null;
46
-
47
- setBaseline(baseline: BehavioralBaseline): void {
48
- this.baseline = baseline;
49
- }
50
-
51
- recordInvocation(toolName: string, argsHash: HashHex): void {
52
- this.invocations.push({
53
- tool_name: toolName,
54
- timestamp: new Date().toISOString(),
55
- args_hash: argsHash,
56
- });
57
- }
58
-
59
- measure(): BehavioralMeasurement {
60
- if (!this.baseline) {
61
- return {
62
- window_start: '', window_end: '', invocations: [],
63
- violations: [], behavioral_hash: sha256Str('no-baseline'),
64
- drift_detected: false,
65
- };
66
- }
67
-
68
- const now = Date.now();
69
- const windowStart = now - this.baseline.window_ms;
70
- const windowInvocations = this.invocations.filter(
71
- i => Date.parse(i.timestamp) >= windowStart
72
- );
73
-
74
- const violations: BehavioralViolation[] = [];
75
-
76
- // Check unauthorized tools
77
- for (const inv of windowInvocations) {
78
- if (!this.baseline.permitted_tools.includes(inv.tool_name)) {
79
- violations.push({ type: 'UNAUTHORIZED_TOOL', tool: inv.tool_name });
80
- }
81
- }
82
-
83
- // Check rate limits
84
- const counts: Record<string, number> = {};
85
- for (const inv of windowInvocations) {
86
- counts[inv.tool_name] = (counts[inv.tool_name] ?? 0) + 1;
87
- }
88
- for (const [tool, count] of Object.entries(counts)) {
89
- const limit = this.baseline.rate_limits[tool];
90
- if (limit !== undefined && count > limit) {
91
- violations.push({ type: 'RATE_EXCEEDED', tool, count, limit });
92
- }
93
- }
94
-
95
- // Check forbidden sequences
96
- const toolSequence = windowInvocations.map(i => i.tool_name);
97
- for (const forbidden of this.baseline.forbidden_sequences) {
98
- if (containsSubsequence(toolSequence, forbidden)) {
99
- violations.push({ type: 'FORBIDDEN_SEQUENCE', sequence: forbidden });
100
- }
101
- }
102
-
103
- // Compute behavioral hash (pattern fingerprint)
104
- const pattern = windowInvocations.map(i => i.tool_name).join('|');
105
- const behavioral_hash = sha256Str(pattern);
106
-
107
- return {
108
- window_start: new Date(windowStart).toISOString(),
109
- window_end: new Date(now).toISOString(),
110
- invocations: windowInvocations,
111
- violations,
112
- behavioral_hash,
113
- drift_detected: violations.length > 0,
114
- };
115
- }
116
-
117
- reset(): void {
118
- this.invocations = [];
119
- }
120
- }
121
-
122
- function containsSubsequence(haystack: string[], needle: string[]): boolean {
123
- if (needle.length === 0) return true;
124
- let ni = 0;
125
- for (const h of haystack) {
126
- if (h === needle[ni]) {
127
- ni++;
128
- if (ni === needle.length) return true;
129
- }
130
- }
131
- return false;
132
- }
@@ -1,45 +0,0 @@
1
- import { signStr, sigToB64, b64ToSig, hexToPk, verifyStr, pkToHex } from '../crypto/sign.js';
2
- import { verifyProof } from '../crypto/merkle.js';
3
- import { canonicalize } from '../utils/canonical.js';
4
- import type { KeyPair, MerkleInclusionProof } from '../crypto/types.js';
5
- import type { EvidenceBundle, PolicyArtifact, SignedReceipt, CheckpointReference, VerificationTier } from './types.js';
6
-
7
- /**
8
- * Generate an evidence bundle. Original signature preserved for backward compatibility.
9
- * Tiered bundle generation (CAISI §3b):
10
- * BRONZE - artifact + receipts only (proofs omitted)
11
- * SILVER - artifact + receipts + Merkle proofs
12
- * GOLD - artifact + receipts + Merkle proofs + anchor checkpoint reference
13
- */
14
- export function generateBundle(artifact: PolicyArtifact, receipts: SignedReceipt[], proofs: MerkleInclusionProof[], checkpoint: CheckpointReference, kp: KeyPair, tier?: VerificationTier): EvidenceBundle {
15
- const effectiveTier = tier ?? 'GOLD';
16
- const bundleProofs = effectiveTier === 'BRONZE' ? [] : proofs;
17
- const bundleCheckpoint: CheckpointReference = effectiveTier === 'GOLD' ? checkpoint : {
18
- ...checkpoint,
19
- transaction_id: effectiveTier === 'BRONZE' ? '' : checkpoint.transaction_id,
20
- anchor_network: effectiveTier === 'BRONZE' ? '' : checkpoint.anchor_network,
21
- };
22
- const unsigned = { artifact, receipts, merkle_proofs: bundleProofs, checkpoint_reference: bundleCheckpoint, public_key: pkToHex(kp.publicKey), verification_tier: effectiveTier };
23
- return { ...unsigned, bundle_signature: sigToB64(signStr(canonicalize(unsigned), kp.secretKey)) };
24
- }
25
-
26
- export interface VerificationResult {
27
- step1_artifact_sig: boolean; step2_receipt_sigs: boolean;
28
- step3_merkle_proofs: boolean; step4_anchor: 'SKIPPED_OFFLINE' | boolean;
29
- overall: boolean; errors: string[];
30
- }
31
-
32
- export function verifyBundleOffline(bundle: EvidenceBundle, pinnedPkHex: string): VerificationResult {
33
- const errors: string[] = [];
34
- const { signature: aSig, ...aU } = bundle.artifact;
35
- const s1 = verifyStr(b64ToSig(aSig), canonicalize(aU), hexToPk(pinnedPkHex));
36
- if (!s1) errors.push('Artifact signature failed');
37
- let s2 = true;
38
- for (const r of bundle.receipts) {
39
- const { portal_signature, ...rU } = r;
40
- if (!verifyStr(b64ToSig(portal_signature), canonicalize(rU), hexToPk(bundle.public_key))) { s2 = false; errors.push(`Receipt ${r.receipt_id} sig failed`); }
41
- }
42
- let s3 = true;
43
- for (const p of bundle.merkle_proofs) { if (!verifyProof(p)) { s3 = false; errors.push(`Merkle proof failed leaf ${p.leafIndex}`); } }
44
- return { step1_artifact_sig: s1, step2_receipt_sigs: s2, step3_merkle_proofs: s3, step4_anchor: 'SKIPPED_OFFLINE', overall: s1 && s2 && s3, errors };
45
- }
package/src/core/chain.ts DELETED
@@ -1,72 +0,0 @@
1
- import { sha256Str } from '../crypto/hash.js';
2
- import { signStr, sigToB64, pkToHex } from '../crypto/sign.js';
3
- import { canonicalize } from '../utils/canonical.js';
4
- import { utcNow } from '../utils/timestamp.js';
5
- import { uuid } from '../utils/uuid.js';
6
- import { SCHEMA_VERSION, PROTOCOL_VERSION, TAXONOMY_VERSION } from '../utils/constants.js';
7
- import type { KeyPair, HashHex } from '../crypto/types.js';
8
- import type { ContinuityEvent, GenesisPayload, StructuralMetadata, EventType } from './types.js';
9
-
10
- /** Leaf hash from structural metadata ONLY. Payload EXCLUDED. Uses "||" delimiter. */
11
- export function computeLeafHash(m: StructuralMetadata): HashHex {
12
- return sha256Str([
13
- m.schema_version, m.protocol_version, m.event_type, m.event_id,
14
- String(m.sequence_number), m.timestamp, m.previous_leaf_hash ?? 'NULL'
15
- ].join('||'));
16
- }
17
-
18
- export function computePayloadHash(payload: unknown): HashHex {
19
- return sha256Str(canonicalize(payload));
20
- }
21
-
22
- function buildEvent(type: EventType, payload: unknown, seq: number, prevLeaf: HashHex | null, kp: KeyPair): ContinuityEvent {
23
- const id = uuid(), ts = utcNow();
24
- const meta: StructuralMetadata = {
25
- schema_version: SCHEMA_VERSION, protocol_version: PROTOCOL_VERSION,
26
- event_type: type, event_id: id, sequence_number: seq,
27
- timestamp: ts, previous_leaf_hash: prevLeaf,
28
- };
29
- const leafHash = computeLeafHash(meta);
30
- const payloadHash = computePayloadHash(payload);
31
- const sig = signStr(canonicalize({ ...meta, leaf_hash: leafHash, payload, payload_hash: payloadHash }), kp.secretKey);
32
- return {
33
- schema_version: SCHEMA_VERSION, protocol_version: PROTOCOL_VERSION,
34
- event_type: type, event_id: id, sequence_number: seq,
35
- timestamp: ts, previous_leaf_hash: prevLeaf,
36
- leaf_hash: leafHash, payload, payload_hash: payloadHash,
37
- event_signature: sigToB64(sig),
38
- };
39
- }
40
-
41
- export function createGenesisEvent(kp: KeyPair, specHash: HashHex): ContinuityEvent {
42
- const payload: GenesisPayload = {
43
- protocol_version: PROTOCOL_VERSION, taxonomy_version: TAXONOMY_VERSION,
44
- root_fingerprint: pkToHex(kp.publicKey), specification_hash: specHash, marker: 'GENESIS',
45
- };
46
- return buildEvent('GENESIS', payload, 0, null, kp);
47
- }
48
-
49
- export function appendEvent(type: EventType, payload: unknown, prev: ContinuityEvent, kp: KeyPair): ContinuityEvent {
50
- return buildEvent(type, payload, prev.sequence_number + 1, prev.leaf_hash, kp);
51
- }
52
-
53
- export function verifyChainIntegrity(events: ContinuityEvent[]): {
54
- valid: boolean; brokenAt: number | null; error: string | null;
55
- } {
56
- for (let i = 0; i < events.length; i++) {
57
- const e = events[i];
58
- const meta: StructuralMetadata = {
59
- schema_version: e.schema_version, protocol_version: e.protocol_version,
60
- event_type: e.event_type, event_id: e.event_id,
61
- sequence_number: e.sequence_number, timestamp: e.timestamp,
62
- previous_leaf_hash: e.previous_leaf_hash,
63
- };
64
- if (e.leaf_hash !== computeLeafHash(meta))
65
- return { valid: false, brokenAt: e.sequence_number, error: `Leaf hash mismatch at seq ${e.sequence_number}` };
66
- if (i > 0 && e.previous_leaf_hash !== events[i - 1].leaf_hash)
67
- return { valid: false, brokenAt: e.sequence_number, error: `Chain linkage broken at seq ${e.sequence_number}` };
68
- if (e.payload_hash !== computePayloadHash(e.payload))
69
- return { valid: false, brokenAt: e.sequence_number, error: `Payload hash mismatch at seq ${e.sequence_number}` };
70
- }
71
- return { valid: true, brokenAt: null, error: null };
72
- }
@@ -1,22 +0,0 @@
1
- import { buildMerkleTree, inclusionProof } from '../crypto/merkle.js';
2
- import { utcNow } from '../utils/timestamp.js';
3
- import { uuid } from '../utils/uuid.js';
4
- import type { ContinuityEvent, CheckpointReference, AnchorBatchPayload } from './types.js';
5
- import type { MerkleInclusionProof } from '../crypto/types.js';
6
-
7
- export function createCheckpoint(events: ContinuityEvent[], anchorNetwork = 'local'): { checkpoint: CheckpointReference; payload: AnchorBatchPayload } {
8
- if (!events.length) throw new Error('No events to checkpoint');
9
- const { root } = buildMerkleTree(events.map(e => e.leaf_hash));
10
- const checkpoint: CheckpointReference = {
11
- merkle_root: root, batch_start_sequence: events[0].sequence_number,
12
- batch_end_sequence: events[events.length - 1].sequence_number,
13
- anchor_network: anchorNetwork, transaction_id: `${anchorNetwork}:${uuid()}`, timestamp: utcNow(),
14
- };
15
- return { checkpoint, payload: { checkpoint_reference: checkpoint, leaf_count: events.length } };
16
- }
17
-
18
- export function eventInclusionProof(events: ContinuityEvent[], targetSeq: number): MerkleInclusionProof {
19
- const idx = events.findIndex(e => e.sequence_number === targetSeq);
20
- if (idx === -1) throw new Error(`Sequence ${targetSeq} not in batch`);
21
- return inclusionProof(events.map(e => e.leaf_hash), idx);
22
- }
@@ -1,146 +0,0 @@
1
- /**
2
- * Constrained Sub-Agent Delegation.
3
- * NCCoE filing: "Scope can only diminish through delegation, never expand."
4
- *
5
- * Primary agent's portal issues a derived artifact to secondary agent:
6
- * - TTL <= parent's remaining TTL
7
- * - Scope can only diminish, never expand
8
- * - Secondary's genesis links to parent's chain
9
- */
10
- import { generateArtifact, hashArtifact } from './artifact.js';
11
- import { isExpired } from '../utils/timestamp.js';
12
- import type { PolicyArtifact, EnforcementAction, MeasurementType } from './types.js';
13
- import type { KeyPair } from '../crypto/types.js';
14
-
15
- export interface DelegationRequest {
16
- /** Subset of parent's enforcement triggers */
17
- enforcement_triggers: EnforcementAction[];
18
- /** Subset of parent's measurement types */
19
- measurement_types: MeasurementType[];
20
- /** Requested TTL in seconds (will be clamped to parent remaining) */
21
- requested_ttl_seconds: number;
22
- /** Description of the delegation purpose */
23
- delegation_purpose: string;
24
- }
25
-
26
- export interface DelegationResult {
27
- success: boolean;
28
- child_artifact?: PolicyArtifact;
29
- child_artifact_hash?: string;
30
- parent_artifact_hash: string;
31
- effective_ttl_seconds?: number;
32
- scope_reduction?: {
33
- triggers_removed: string[];
34
- measurement_types_removed: string[];
35
- };
36
- error?: string;
37
- }
38
-
39
- /**
40
- * Derive a constrained artifact from a parent artifact.
41
- * Key rule: scope can only diminish, never expand.
42
- */
43
- export function deriveArtifact(
44
- parentArtifact: PolicyArtifact,
45
- request: DelegationRequest,
46
- issuerKP: KeyPair
47
- ): DelegationResult {
48
- const parentHash = hashArtifact(parentArtifact);
49
-
50
- // Validate parent is not expired
51
- if (isExpired(parentArtifact.issued_timestamp, parentArtifact.enforcement_parameters.ttl_seconds)) {
52
- return { success: false, parent_artifact_hash: parentHash, error: 'Parent artifact TTL has expired' };
53
- }
54
-
55
- // Calculate parent remaining TTL
56
- const parentIssuedMs = Date.parse(parentArtifact.issued_timestamp);
57
- const parentExpiresMs = parentIssuedMs + (parentArtifact.enforcement_parameters.ttl_seconds * 1000);
58
- const remainingMs = parentExpiresMs - Date.now();
59
- const remainingSeconds = Math.max(0, Math.floor(remainingMs / 1000));
60
-
61
- // Clamp child TTL to parent remaining
62
- const effectiveTTL = Math.min(request.requested_ttl_seconds, remainingSeconds);
63
- if (effectiveTTL <= 0) {
64
- return { success: false, parent_artifact_hash: parentHash, error: 'No remaining TTL to delegate' };
65
- }
66
-
67
- // Validate triggers are subset of parent
68
- const parentTriggers = new Set(parentArtifact.enforcement_parameters.enforcement_triggers);
69
- const invalidTriggers = request.enforcement_triggers.filter(t => !parentTriggers.has(t));
70
- if (invalidTriggers.length > 0) {
71
- return { success: false, parent_artifact_hash: parentHash, error: `Cannot expand scope: triggers [${invalidTriggers.join(', ')}] not in parent` };
72
- }
73
-
74
- // Validate measurement types are subset of parent
75
- const parentTypes = new Set<string>(parentArtifact.enforcement_parameters.measurement_types);
76
- const invalidTypes = request.measurement_types.filter(t => !parentTypes.has(t));
77
- if (invalidTypes.length > 0) {
78
- return { success: false, parent_artifact_hash: parentHash, error: `Cannot expand scope: measurement types [${invalidTypes.join(', ')}] not in parent` };
79
- }
80
-
81
- // Build constrained child artifact
82
- const childArtifact = generateArtifact({
83
- subject_identifier: parentArtifact.subject_identifier,
84
- policy_reference: parentArtifact.policy_reference,
85
- policy_version: parentArtifact.policy_version,
86
- sealed_hash: parentArtifact.sealed_hash,
87
- seal_salt: parentArtifact.seal_salt,
88
- enforcement_parameters: {
89
- measurement_cadence_ms: parentArtifact.enforcement_parameters.measurement_cadence_ms,
90
- ttl_seconds: effectiveTTL,
91
- enforcement_triggers: request.enforcement_triggers,
92
- re_attestation_required: parentArtifact.enforcement_parameters.re_attestation_required,
93
- measurement_types: request.measurement_types,
94
- },
95
- disclosure_policy: parentArtifact.disclosure_policy, // cannot expand
96
- evidence_commitments: parentArtifact.evidence_commitments,
97
- issuer_keypair: issuerKP,
98
- });
99
-
100
- // Track scope reduction
101
- const triggersRemoved = [...parentTriggers].filter(t => !request.enforcement_triggers.includes(t as EnforcementAction));
102
- const typesRemoved = [...parentTypes].filter(t => !request.measurement_types.includes(t as MeasurementType));
103
-
104
- return {
105
- success: true,
106
- child_artifact: childArtifact,
107
- child_artifact_hash: hashArtifact(childArtifact),
108
- parent_artifact_hash: parentHash,
109
- effective_ttl_seconds: effectiveTTL,
110
- scope_reduction: {
111
- triggers_removed: triggersRemoved,
112
- measurement_types_removed: typesRemoved,
113
- },
114
- };
115
- }
116
-
117
- /**
118
- * Validate that a child artifact is a valid delegation of a parent.
119
- */
120
- export function validateDelegation(parent: PolicyArtifact, child: PolicyArtifact): { valid: boolean; errors: string[] } {
121
- const errors: string[] = [];
122
-
123
- // TTL must be <= parent TTL
124
- if (child.enforcement_parameters.ttl_seconds > parent.enforcement_parameters.ttl_seconds) {
125
- errors.push(`Child TTL (${child.enforcement_parameters.ttl_seconds}s) exceeds parent (${parent.enforcement_parameters.ttl_seconds}s)`);
126
- }
127
-
128
- // Triggers must be subset
129
- const pTriggers = new Set<string>(parent.enforcement_parameters.enforcement_triggers);
130
- for (const t of child.enforcement_parameters.enforcement_triggers) {
131
- if (!pTriggers.has(t)) errors.push(`Child trigger '${t}' not in parent scope`);
132
- }
133
-
134
- // Measurement types must be subset
135
- const pTypes = new Set<string>(parent.enforcement_parameters.measurement_types);
136
- for (const t of child.enforcement_parameters.measurement_types) {
137
- if (!pTypes.has(t)) errors.push(`Child measurement type '${t}' not in parent scope`);
138
- }
139
-
140
- // Subject must match
141
- if (child.subject_identifier.bytes_hash !== parent.subject_identifier.bytes_hash) {
142
- errors.push('Child subject bytes_hash does not match parent');
143
- }
144
-
145
- return { valid: errors.length === 0, errors };
146
- }
@@ -1,32 +0,0 @@
1
- import { signStr, sigToB64 } from '../crypto/sign.js';
2
- import { canonicalize } from '../utils/canonical.js';
3
- import { utcNow } from '../utils/timestamp.js';
4
- import { uuid } from '../utils/uuid.js';
5
- import type { KeyPair } from '../crypto/types.js';
6
- import type { DisclosureRequest, DisclosurePolicy, SubstitutionReceipt, DisclosureMode } from './types.js';
7
-
8
- export interface DisclosureResult {
9
- permitted: boolean; disclosed_claim_id: string | null; disclosed_value: unknown;
10
- mode: DisclosureMode; was_substituted: boolean; substitution_receipt: SubstitutionReceipt | null;
11
- }
12
-
13
- export function processDisclosure(req: DisclosureRequest, policy: DisclosurePolicy, values: Record<string, unknown>, policyVersion: number, chainSeq: number, kp: KeyPair): DisclosureResult {
14
- const claim = policy.claims_taxonomy.find(c => c.claim_id === req.requested_claim_id);
15
- if (!claim) return { permitted: false, disclosed_claim_id: null, disclosed_value: null, mode: req.mode, was_substituted: false, substitution_receipt: null };
16
- if (claim.permitted_modes.includes(req.mode))
17
- return { permitted: true, disclosed_claim_id: claim.claim_id, disclosed_value: fv(values[claim.claim_id], req.mode), mode: req.mode, was_substituted: false, substitution_receipt: null };
18
- for (const subId of claim.substitutes) {
19
- const sub = policy.claims_taxonomy.find(c => c.claim_id === subId);
20
- if (sub?.permitted_modes.includes(req.mode) && !sub.inference_risks.includes(req.requested_claim_id))
21
- return { permitted: true, disclosed_claim_id: subId, disclosed_value: fv(values[subId], req.mode), mode: req.mode, was_substituted: true,
22
- substitution_receipt: sr(req.requested_claim_id, subId, policyVersion, 'SENSITIVITY_DENIED', chainSeq, kp) };
23
- }
24
- return { permitted: false, disclosed_claim_id: null, disclosed_value: null, mode: req.mode, was_substituted: false,
25
- substitution_receipt: sr(req.requested_claim_id, null, policyVersion, 'NO_PERMITTED_SUBSTITUTE', chainSeq, kp) };
26
- }
27
-
28
- function fv(v: unknown, m: DisclosureMode): unknown { return m === 'PROOF_ONLY' ? v != null : v; }
29
- function sr(orig: string, sub: string | null, pv: number, reason: string, seq: number, kp: KeyPair): SubstitutionReceipt {
30
- const u = { receipt_id: uuid(), original_claim_id: orig, substitute_claim_id: sub, policy_version: pv, reason_code: reason, timestamp: utcNow(), chain_sequence_ref: seq };
31
- return { ...u, signature: sigToB64(signStr(canonicalize(u), kp.secretKey)) };
32
- }