@attested-intelligence/aga-mcp-server 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.
- package/AGA_MCP_SERVER_SPEC.md +632 -0
- package/LICENSE +21 -0
- package/README.md +42 -0
- package/dist/core/artifact.d.ts +19 -0
- package/dist/core/artifact.d.ts.map +1 -0
- package/dist/core/artifact.js +27 -0
- package/dist/core/artifact.js.map +1 -0
- package/dist/core/attestation.d.ts +19 -0
- package/dist/core/attestation.d.ts.map +1 -0
- package/dist/core/attestation.js +12 -0
- package/dist/core/attestation.js.map +1 -0
- package/dist/core/behavioral.d.ts +45 -0
- package/dist/core/behavioral.d.ts.map +1 -0
- package/dist/core/behavioral.js +88 -0
- package/dist/core/behavioral.js.map +1 -0
- package/dist/core/bundle.d.ts +13 -0
- package/dist/core/bundle.d.ts.map +1 -0
- package/dist/core/bundle.js +31 -0
- package/dist/core/bundle.js.map +1 -0
- package/dist/core/chain.d.ts +13 -0
- package/dist/core/chain.d.ts.map +1 -0
- package/dist/core/chain.js +63 -0
- package/dist/core/chain.js.map +1 -0
- package/dist/core/checkpoint.d.ts +8 -0
- package/dist/core/checkpoint.d.ts.map +1 -0
- package/dist/core/checkpoint.js +21 -0
- package/dist/core/checkpoint.js.map +1 -0
- package/dist/core/delegation.d.ts +37 -0
- package/dist/core/delegation.d.ts.map +1 -0
- package/dist/core/delegation.js +104 -0
- package/dist/core/delegation.js.map +1 -0
- package/dist/core/disclosure.d.ts +12 -0
- package/dist/core/disclosure.d.ts.map +1 -0
- package/dist/core/disclosure.js +25 -0
- package/dist/core/disclosure.js.map +1 -0
- package/dist/core/index.d.ts +12 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +12 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/portal.d.ts +28 -0
- package/dist/core/portal.d.ts.map +1 -0
- package/dist/core/portal.js +95 -0
- package/dist/core/portal.js.map +1 -0
- package/dist/core/quarantine.d.ts +8 -0
- package/dist/core/quarantine.d.ts.map +1 -0
- package/dist/core/quarantine.js +13 -0
- package/dist/core/quarantine.js.map +1 -0
- package/dist/core/receipt.d.ts +17 -0
- package/dist/core/receipt.d.ts.map +1 -0
- package/dist/core/receipt.js +17 -0
- package/dist/core/receipt.js.map +1 -0
- package/dist/core/subject.d.ts +4 -0
- package/dist/core/subject.d.ts.map +1 -0
- package/dist/core/subject.js +9 -0
- package/dist/core/subject.js.map +1 -0
- package/dist/core/types.d.ts +167 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +2 -0
- package/dist/core/types.js.map +1 -0
- package/dist/crypto/hash.d.ts +9 -0
- package/dist/crypto/hash.d.ts.map +1 -0
- package/dist/crypto/hash.js +30 -0
- package/dist/crypto/hash.js.map +1 -0
- package/dist/crypto/index.d.ts +6 -0
- package/dist/crypto/index.d.ts.map +1 -0
- package/dist/crypto/index.js +6 -0
- package/dist/crypto/index.js.map +1 -0
- package/dist/crypto/merkle.d.ts +8 -0
- package/dist/crypto/merkle.d.ts.map +1 -0
- package/dist/crypto/merkle.js +42 -0
- package/dist/crypto/merkle.js.map +1 -0
- package/dist/crypto/salt.d.ts +5 -0
- package/dist/crypto/salt.d.ts.map +1 -0
- package/dist/crypto/salt.js +14 -0
- package/dist/crypto/salt.js.map +1 -0
- package/dist/crypto/sign.d.ts +11 -0
- package/dist/crypto/sign.d.ts.map +1 -0
- package/dist/crypto/sign.js +37 -0
- package/dist/crypto/sign.js.map +1 -0
- package/dist/crypto/types.d.ts +24 -0
- package/dist/crypto/types.d.ts.map +1 -0
- package/dist/crypto/types.js +2 -0
- package/dist/crypto/types.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/governance.d.ts +27 -0
- package/dist/middleware/governance.d.ts.map +1 -0
- package/dist/middleware/governance.js +65 -0
- package/dist/middleware/governance.js.map +1 -0
- package/dist/middleware/index.d.ts +2 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +2 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/server.d.ts +13 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +369 -0
- package/dist/server.js.map +1 -0
- package/dist/storage/index.d.ts +4 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +3 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/interface.d.ts +21 -0
- package/dist/storage/interface.d.ts.map +1 -0
- package/dist/storage/interface.js +2 -0
- package/dist/storage/interface.js.map +1 -0
- package/dist/storage/memory.d.ts +26 -0
- package/dist/storage/memory.d.ts.map +1 -0
- package/dist/storage/memory.js +24 -0
- package/dist/storage/memory.js.map +1 -0
- package/dist/storage/sqlite.d.ts +25 -0
- package/dist/storage/sqlite.d.ts.map +1 -0
- package/dist/storage/sqlite.js +44 -0
- package/dist/storage/sqlite.js.map +1 -0
- package/dist/utils/canonical.d.ts +3 -0
- package/dist/utils/canonical.d.ts.map +1 -0
- package/dist/utils/canonical.js +17 -0
- package/dist/utils/canonical.js.map +1 -0
- package/dist/utils/constants.d.ts +4 -0
- package/dist/utils/constants.d.ts.map +1 -0
- package/dist/utils/constants.js +4 -0
- package/dist/utils/constants.js.map +1 -0
- package/dist/utils/timestamp.d.ts +4 -0
- package/dist/utils/timestamp.d.ts.map +1 -0
- package/dist/utils/timestamp.js +13 -0
- package/dist/utils/timestamp.js.map +1 -0
- package/dist/utils/uuid.d.ts +2 -0
- package/dist/utils/uuid.d.ts.map +1 -0
- package/dist/utils/uuid.js +3 -0
- package/dist/utils/uuid.js.map +1 -0
- package/package.json +45 -0
- package/src/core/artifact.ts +45 -0
- package/src/core/attestation.ts +33 -0
- package/src/core/behavioral.ts +132 -0
- package/src/core/bundle.ts +31 -0
- package/src/core/chain.ts +72 -0
- package/src/core/checkpoint.ts +22 -0
- package/src/core/delegation.ts +146 -0
- package/src/core/disclosure.ts +32 -0
- package/src/core/index.ts +11 -0
- package/src/core/portal.ts +96 -0
- package/src/core/quarantine.ts +16 -0
- package/src/core/receipt.ts +33 -0
- package/src/core/subject.ts +11 -0
- package/src/core/types.ts +244 -0
- package/src/crypto/hash.ts +33 -0
- package/src/crypto/index.ts +5 -0
- package/src/crypto/merkle.ts +43 -0
- package/src/crypto/salt.ts +18 -0
- package/src/crypto/sign.ts +35 -0
- package/src/crypto/types.ts +19 -0
- package/src/index.ts +12 -0
- package/src/middleware/governance.ts +95 -0
- package/src/middleware/index.ts +1 -0
- package/src/server.ts +436 -0
- package/src/storage/index.ts +3 -0
- package/src/storage/interface.ts +21 -0
- package/src/storage/memory.ts +27 -0
- package/src/storage/sqlite.ts +45 -0
- package/src/tools/README.md +13 -0
- package/src/utils/canonical.ts +14 -0
- package/src/utils/constants.ts +3 -0
- package/src/utils/timestamp.ts +12 -0
- package/src/utils/uuid.ts +2 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"canonical.d.ts","sourceRoot":"","sources":["../../src/utils/canonical.ts"],"names":[],"mappings":"AAAA,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CASlD;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAEjD"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function deepSortKeys(obj) {
|
|
2
|
+
if (obj === null || obj === undefined || typeof obj !== 'object')
|
|
3
|
+
return obj;
|
|
4
|
+
if (Array.isArray(obj))
|
|
5
|
+
return obj.map(deepSortKeys);
|
|
6
|
+
if (obj instanceof Uint8Array)
|
|
7
|
+
return obj;
|
|
8
|
+
const sorted = {};
|
|
9
|
+
for (const key of Object.keys(obj).sort()) {
|
|
10
|
+
sorted[key] = deepSortKeys(obj[key]);
|
|
11
|
+
}
|
|
12
|
+
return sorted;
|
|
13
|
+
}
|
|
14
|
+
export function canonicalize(obj) {
|
|
15
|
+
return JSON.stringify(deepSortKeys(obj));
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=canonical.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"canonical.js","sourceRoot":"","sources":["../../src/utils/canonical.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,YAAY,CAAC,GAAY;IACvC,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,OAAO,GAAG,CAAC;IAC7E,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;IACrD,IAAI,GAAG,YAAY,UAAU;QAAE,OAAO,GAAG,CAAC;IAC1C,MAAM,MAAM,GAA4B,EAAE,CAAC;IAC3C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAA8B,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QACrE,MAAM,CAAC,GAAG,CAAC,GAAG,YAAY,CAAE,GAA+B,CAAC,GAAG,CAAC,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,GAAY;IACvC,OAAO,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;AAC3C,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/utils/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,cAAc,UAAU,CAAC;AACtC,eAAO,MAAM,gBAAgB,UAAU,CAAC;AACxC,eAAO,MAAM,gBAAgB,UAAU,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/utils/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,cAAc,GAAG,OAAO,CAAC;AACtC,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AACxC,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function utcNow(): string;
|
|
2
|
+
export declare function isWithinPeriod(now: string, effective: string, expiration?: string | null): boolean;
|
|
3
|
+
export declare function isExpired(issuedAt: string, ttlSeconds: number): boolean;
|
|
4
|
+
//# sourceMappingURL=timestamp.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timestamp.d.ts","sourceRoot":"","sources":["../../src/utils/timestamp.ts"],"names":[],"mappings":"AAAA,wBAAgB,MAAM,IAAI,MAAM,CAAqC;AAErE,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,CAKlG;AAED,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAEvE"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function utcNow() { return new Date().toISOString(); }
|
|
2
|
+
export function isWithinPeriod(now, effective, expiration) {
|
|
3
|
+
const n = Date.parse(now);
|
|
4
|
+
if (n < Date.parse(effective))
|
|
5
|
+
return false;
|
|
6
|
+
if (expiration && n > Date.parse(expiration))
|
|
7
|
+
return false;
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
export function isExpired(issuedAt, ttlSeconds) {
|
|
11
|
+
return Date.now() > Date.parse(issuedAt) + ttlSeconds * 1000;
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=timestamp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"timestamp.js","sourceRoot":"","sources":["../../src/utils/timestamp.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,MAAM,KAAa,OAAO,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;AAErE,MAAM,UAAU,cAAc,CAAC,GAAW,EAAE,SAAiB,EAAE,UAA0B;IACvF,MAAM,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1B,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,UAAU,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3D,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,QAAgB,EAAE,UAAkB;IAC5D,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,UAAU,GAAG,IAAI,CAAC;AAC/D,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uuid.d.ts","sourceRoot":"","sources":["../../src/utils/uuid.ts"],"names":[],"mappings":"AACA,wBAAgB,IAAI,IAAI,MAAM,CAAiB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uuid.js","sourceRoot":"","sources":["../../src/utils/uuid.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,MAAM,CAAC;AAC1B,MAAM,UAAU,IAAI,KAAa,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@attested-intelligence/aga-mcp-server",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MCP server implementing the Attested Governance Artifact protocol — cryptographic compliance for autonomous systems",
|
|
5
|
+
"author": "NeuroCrypt",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "dist/index.js",
|
|
9
|
+
"types": "dist/index.d.ts",
|
|
10
|
+
"bin": { "aga-mcp-server": "dist/index.js" },
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsc",
|
|
13
|
+
"start": "node dist/index.js",
|
|
14
|
+
"dev": "tsx src/index.ts",
|
|
15
|
+
"test": "vitest run",
|
|
16
|
+
"test:watch": "vitest",
|
|
17
|
+
"test:crypto": "vitest run tests/crypto/",
|
|
18
|
+
"test:core": "vitest run tests/core/",
|
|
19
|
+
"test:integration": "vitest run tests/integration/",
|
|
20
|
+
"demo": "tsx scripts/demo.ts",
|
|
21
|
+
"benchmark": "tsx scripts/benchmark.ts",
|
|
22
|
+
"lint": "tsc --noEmit",
|
|
23
|
+
"prepublishOnly": "npm run build && npm run test"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@modelcontextprotocol/sdk": "^1.12.0",
|
|
27
|
+
"@noble/ed25519": "^2.1.0",
|
|
28
|
+
"@noble/hashes": "^1.7.0",
|
|
29
|
+
"uuid": "^11.1.0",
|
|
30
|
+
"zod": "^3.24.0"
|
|
31
|
+
},
|
|
32
|
+
"optionalDependencies": {
|
|
33
|
+
"better-sqlite3": "^11.7.0"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@types/better-sqlite3": "^7.6.12",
|
|
37
|
+
"@types/node": "^22.10.0",
|
|
38
|
+
"@types/uuid": "^10.0.0",
|
|
39
|
+
"tsx": "^4.19.0",
|
|
40
|
+
"typescript": "^5.7.0",
|
|
41
|
+
"vitest": "^2.1.0"
|
|
42
|
+
},
|
|
43
|
+
"engines": { "node": ">=20.0.0" },
|
|
44
|
+
"keywords": ["mcp","attestation","governance","ai-governance","neurocrypt","runtime-integrity","continuity-chain"]
|
|
45
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
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 } from './types.js';
|
|
6
|
+
|
|
7
|
+
export function generateBundle(artifact: PolicyArtifact, receipts: SignedReceipt[], proofs: MerkleInclusionProof[], checkpoint: CheckpointReference, kp: KeyPair): EvidenceBundle {
|
|
8
|
+
const unsigned = { artifact, receipts, merkle_proofs: proofs, checkpoint_reference: checkpoint, public_key: pkToHex(kp.publicKey) };
|
|
9
|
+
return { ...unsigned, bundle_signature: sigToB64(signStr(canonicalize(unsigned), kp.secretKey)) };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface VerificationResult {
|
|
13
|
+
step1_artifact_sig: boolean; step2_receipt_sigs: boolean;
|
|
14
|
+
step3_merkle_proofs: boolean; step4_anchor: 'SKIPPED_OFFLINE' | boolean;
|
|
15
|
+
overall: boolean; errors: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function verifyBundleOffline(bundle: EvidenceBundle, pinnedPkHex: string): VerificationResult {
|
|
19
|
+
const errors: string[] = [];
|
|
20
|
+
const { signature: aSig, ...aU } = bundle.artifact;
|
|
21
|
+
const s1 = verifyStr(b64ToSig(aSig), canonicalize(aU), hexToPk(pinnedPkHex));
|
|
22
|
+
if (!s1) errors.push('Artifact signature failed');
|
|
23
|
+
let s2 = true;
|
|
24
|
+
for (const r of bundle.receipts) {
|
|
25
|
+
const { portal_signature, ...rU } = r;
|
|
26
|
+
if (!verifyStr(b64ToSig(portal_signature), canonicalize(rU), hexToPk(bundle.public_key))) { s2 = false; errors.push(`Receipt ${r.receipt_id} sig failed`); }
|
|
27
|
+
}
|
|
28
|
+
let s3 = true;
|
|
29
|
+
for (const p of bundle.merkle_proofs) { if (!verifyProof(p)) { s3 = false; errors.push(`Merkle proof failed leaf ${p.leafIndex}`); } }
|
|
30
|
+
return { step1_artifact_sig: s1, step2_receipt_sigs: s2, step3_merkle_proofs: s3, step4_anchor: 'SKIPPED_OFFLINE', overall: s1 && s2 && s3, errors };
|
|
31
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
}
|