@aithorized/core 0.4.0 → 0.5.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/README.md CHANGED
@@ -1,30 +1,109 @@
1
- # @aithorized/core
1
+ <p align="center">
2
+ <a href="https://aithorized.dev">
3
+ <img src="https://aithorized.dev/mark.svg" alt="aithorized" width="56" />
4
+ </a>
5
+ </p>
2
6
 
3
- The deterministic core of [aithorized](https://aithorized.dev): what the SDK, the MCP proxy and the hooks use to decide whether a tool call may run. No network and no state. Node 20 or later.
7
+ <h1 align="center">@aithorized/core</h1>
8
+
9
+ <p align="center">
10
+ Deterministic crypto core and fail-closed policy engine for <a href="https://aithorized.dev">aithorized</a>.
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://www.npmjs.com/package/@aithorized/core"><img src="https://img.shields.io/npm/v/@aithorized/core?color=10B981" alt="npm version" /></a>
15
+ <a href="https://github.com/JMBargueno/aithorized-oss/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-10B981" alt="MIT License" /></a>
16
+ <a href="https://docs.aithorized.dev"><img src="https://img.shields.io/badge/docs-docs.aithorized.dev-0EA5E9" alt="Documentation" /></a>
17
+ </p>
18
+
19
+ ---
20
+
21
+ `@aithorized/core` is the deterministic heart of **aithorized**: what the SDK, MCP proxy, CLI, and hooks use to decide whether a tool call may run and to cryptographically verify signed human decisions. No network calls and no internal state. Requires **Node.js >= 20**.
22
+
23
+ > Most integrations should install [`@aithorized/sdk`](https://www.npmjs.com/package/@aithorized/sdk) instead. Use `@aithorized/core` when you want to evaluate policies offline, verify decision bundles directly, or port the protocol to another language using the test vectors.
24
+
25
+ ## Install
4
26
 
5
27
  ```bash
6
28
  npm install @aithorized/core
7
29
  ```
8
30
 
9
- Most integrations want [`@aithorized/sdk`](https://www.npmjs.com/package/@aithorized/sdk) instead. Use this package to verify decisions yourself, or to port the protocol to another language.
31
+ ## Subpath exports
32
+
33
+ | Import | Purpose | Browser-safe |
34
+ |---|---|---|
35
+ | `@aithorized/core` | Full crypto core, policy engine, decision-bundle verification, lifecycle & preview helpers | Node >= 20 |
36
+ | `@aithorized/core/policy` | Policy evaluation, matching, command analysis, and policy packs | Yes |
37
+ | `@aithorized/core/kill-switch` | Local pause notice helpers | Node >= 20 |
38
+ | `@aithorized/core/vectors` | Loaders for the `test-vectors/` fixtures | Node >= 20 |
10
39
 
11
40
  ## What is in it
12
41
 
13
- - **Canonical JSON and hashing**: RFC 8785 (JCS) and the SHA-256 payload hash every signature commits to.
14
- - **Signatures**: ECDSA P-256 for device decisions and Ed25519 for policy bundles, with domain-separated signing inputs.
15
- - **Policy**: loading, matching, evaluation, and a merge that can only make a policy stricter.
16
- - **Verification**: `verifyDecisionBundle` checks a signed decision against the payload that is about to run.
17
- - **Lifecycle helpers**: the local deadline and the redaction of previews.
42
+ - **Canonical JSON & hashing**: RFC 8785 (`jcs`) and SHA-256 payload hashing (`payloadHash`, `feedbackHash`, `checkPayloadHash`) that every signature commits to.
43
+ - **Domain-separated signatures**: ECDSA P-256 (`signEcdsaP256`, `verifyEcdsaP256`, `normalizeEcdsaLowS`) for device decisions and Ed25519 (`signEd25519`, `verifyEd25519`) for policy bundles, with explicit domain tags (`DECISION_DOMAIN`, `ACTION_DOMAIN`, `HTTP_DOMAIN`, `WS_DOMAIN`, `ENROLL_DOMAIN`).
44
+ - **Policy engine**: `loadPolicyYaml`, `parsePolicyJson`, `evaluatePolicy`, `explainEvaluation`, `simulatePolicy`, `mergePolicies` (a merge can only make a policy stricter), and built-in `POLICY_PACKS` (`getPolicyPack`, `applyPolicyPack`).
45
+ - **Command analysis**: `analyzeCommand`, `splitShellSegments`, `tokenizeSegment` for inspecting shell commands before matching rules.
46
+ - **Verification**: `verifyDecisionBundle` and `verifyBundle` validate signed decisions and policy bundles against pinned keys and the exact canonical payload about to run.
47
+ - **Lifecycle & preview helpers**: `createLocalDeadline`, `awaitResolutionBeforeDeadline`, `redactForPreview`, `createUnifiedDiffPreview`, `runPreviewProviders`.
48
+
49
+ ## Quick examples
50
+
51
+ ### Evaluate a policy locally
52
+
53
+ ```ts
54
+ import { evaluatePolicy, loadPolicyYaml } from '@aithorized/core/policy';
55
+
56
+ const doc = loadPolicyYaml(`
57
+ version: 1
58
+ defaults:
59
+ unmatched: require_approval
60
+ rules:
61
+ - id: allow-reads
62
+ match:
63
+ tool: "^(read_file|list_dir)$"
64
+ effect: allow
65
+ - id: guard-prod-refunds
66
+ match:
67
+ tool: "stripe.refund"
68
+ environment: prod
69
+ effect: require_approval
70
+ risk: high
71
+ `);
18
72
 
19
- | Import | |
20
- |---|---|
21
- | `@aithorized/core` | Everything above |
22
- | `@aithorized/core/policy` | Policy evaluation only, safe for browsers |
23
- | `@aithorized/core/kill-switch` | Local pause helpers |
24
- | `@aithorized/core/vectors` | Loaders for the test vectors |
73
+ const result = evaluatePolicy(doc, {
74
+ tool: 'stripe.refund',
75
+ args: { charge: 'ch_1', amount: 45000 },
76
+ environment: 'prod'
77
+ });
78
+
79
+ console.log(result.effect); // 'require_approval'
80
+ ```
81
+
82
+ ### Verify a signed decision bundle
83
+
84
+ ```ts
85
+ import { payloadHash, verifyDecisionBundle } from '@aithorized/core';
86
+
87
+ const hash = payloadHash('stripe.refund', { charge: 'ch_1', amount: 45000 });
88
+ const verification = verifyDecisionBundle(decisionBundle, {
89
+ expectedPayloadHash: hash,
90
+ pinnedDirectoryKeys: directoryKeys
91
+ });
92
+
93
+ if (!verification.ok) {
94
+ throw new Error(`Verification failed: ${verification.code}`);
95
+ }
96
+ ```
25
97
 
26
98
  ## Test vectors
27
99
 
28
- `test-vectors/` ships with the package: canonical JSON, payload hashes, signing inputs, policy evaluation and bundle verification, as JSON. An implementation in another language is correct when it reproduces them byte for byte.
100
+ `test-vectors/` ships inside the npm package: canonical JSON, payload hashes, signing inputs, policy evaluation, and bundle verification as JSON fixtures. An implementation in another language is conformant when it reproduces every vector byte for byte.
101
+
102
+ ## Links
103
+
104
+ - Documentation: <https://docs.aithorized.dev>
105
+ - Source: <https://github.com/JMBargueno/aithorized-oss/tree/main/packages/core>
106
+
107
+ ## License
29
108
 
30
- MIT.
109
+ MIT
@@ -0,0 +1,40 @@
1
+ /**
2
+ * `@aithorized/core/audit`: re-check an audit hash chain anywhere WebCrypto exists (a browser, Node 20+, Deno), with
3
+ * nothing from `node:crypto`. The rules are the backend's (docs/02 section 5):
4
+ *
5
+ * hash = "sha256:" + base64url(SHA-256(JCS({ prevHash, event })))
6
+ * event = { seq, ts, tenantId, type, actor?, subject?, detail? }
7
+ *
8
+ * and the first event of a tenant chains after `sha256:` + base64url(SHA-256("aithorized-audit-genesis")).
9
+ */
10
+ export interface ChainedAuditEvent {
11
+ seq: number;
12
+ ts: string;
13
+ tenantId: string;
14
+ type: string;
15
+ actor?: string;
16
+ subject?: string;
17
+ detail?: Record<string, unknown>;
18
+ prevHash: string;
19
+ hash: string;
20
+ }
21
+ export interface AuditChainResult {
22
+ valid: boolean;
23
+ /** Events re-hashed before the result (all of them when valid). */
24
+ checked: number;
25
+ /** The first event whose link or hash does not match. */
26
+ firstBadSeq?: number;
27
+ /** The hash the next event must chain after: the last good event's (or the starting point). */
28
+ headHash: string;
29
+ }
30
+ /** The event body exactly as it was hashed at append time. */
31
+ export declare function auditEventBody(event: Omit<ChainedAuditEvent, 'prevHash' | 'hash'>): Record<string, unknown>;
32
+ /** The prevHash of a tenant's first event. */
33
+ export declare function auditGenesisHash(): Promise<string>;
34
+ /** The hash an event must carry, given the hash it chains after. */
35
+ export declare function auditEventHash(prevHash: string, event: Omit<ChainedAuditEvent, 'prevHash' | 'hash'>): Promise<string>;
36
+ /**
37
+ * Re-hash consecutive events of one tenant, oldest first. Starts from the genesis unless `after` gives the hash of
38
+ * the event just before the first one (to check a long chain page by page).
39
+ */
40
+ export declare function verifyAuditChainAsync(events: readonly ChainedAuditEvent[], after?: string): Promise<AuditChainResult>;
package/dist/audit.js ADDED
@@ -0,0 +1,47 @@
1
+ import { jcs } from './crypto/jcs.js';
2
+ const GENESIS_INPUT = 'aithorized-audit-genesis';
3
+ /** The event body exactly as it was hashed at append time. */
4
+ export function auditEventBody(event) {
5
+ const body = { seq: event.seq, ts: event.ts, tenantId: event.tenantId, type: event.type };
6
+ if (event.actor !== undefined)
7
+ body.actor = event.actor;
8
+ if (event.subject !== undefined)
9
+ body.subject = event.subject;
10
+ if (event.detail !== undefined)
11
+ body.detail = event.detail;
12
+ return body;
13
+ }
14
+ /** The prevHash of a tenant's first event. */
15
+ export async function auditGenesisHash() {
16
+ return 'sha256:' + (await sha256Base64url(GENESIS_INPUT));
17
+ }
18
+ /** The hash an event must carry, given the hash it chains after. */
19
+ export async function auditEventHash(prevHash, event) {
20
+ return 'sha256:' + (await sha256Base64url(jcs({ prevHash, event: auditEventBody(event) })));
21
+ }
22
+ /**
23
+ * Re-hash consecutive events of one tenant, oldest first. Starts from the genesis unless `after` gives the hash of
24
+ * the event just before the first one (to check a long chain page by page).
25
+ */
26
+ export async function verifyAuditChainAsync(events, after) {
27
+ let prev = after ?? (await auditGenesisHash());
28
+ let checked = 0;
29
+ for (const event of events) {
30
+ if (event.prevHash !== prev || (await auditEventHash(event.prevHash, event)) !== event.hash) {
31
+ return { valid: false, checked, firstBadSeq: event.seq, headHash: prev };
32
+ }
33
+ prev = event.hash;
34
+ checked += 1;
35
+ }
36
+ return { valid: true, checked, headHash: prev };
37
+ }
38
+ async function sha256Base64url(text) {
39
+ const subtle = globalThis.crypto?.subtle;
40
+ if (!subtle)
41
+ throw new Error('WebCrypto (crypto.subtle) is not available');
42
+ const digest = new Uint8Array(await subtle.digest('SHA-256', new TextEncoder().encode(text)));
43
+ let binary = '';
44
+ for (const byte of digest)
45
+ binary += String.fromCharCode(byte);
46
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
47
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aithorized/core",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Deterministic crypto core and policy engine for aithorized (JCS RFC 8785, payload hashing, domain-separated ECDSA/Ed25519 signatures, fail-closed policy evaluation).",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -16,6 +16,10 @@
16
16
  "types": "./dist/policy/browser.d.ts",
17
17
  "default": "./dist/policy/browser.js"
18
18
  },
19
+ "./audit": {
20
+ "types": "./dist/audit.d.ts",
21
+ "default": "./dist/audit.js"
22
+ },
19
23
  "./kill-switch": {
20
24
  "types": "./dist/kill-switch.d.ts",
21
25
  "default": "./dist/kill-switch.js"