@mikeargento/bitgraph 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/LICENSE +9 -0
  2. package/NOTICE +14 -0
  3. package/README.md +175 -0
  4. package/dist/__tests__/canonical.test.d.ts +2 -0
  5. package/dist/__tests__/canonical.test.d.ts.map +1 -0
  6. package/dist/__tests__/canonical.test.js +162 -0
  7. package/dist/__tests__/canonical.test.js.map +1 -0
  8. package/dist/__tests__/commit-service.integration.test.d.ts +2 -0
  9. package/dist/__tests__/commit-service.integration.test.d.ts.map +1 -0
  10. package/dist/__tests__/commit-service.integration.test.js +95 -0
  11. package/dist/__tests__/commit-service.integration.test.js.map +1 -0
  12. package/dist/__tests__/constructor.test.d.ts +2 -0
  13. package/dist/__tests__/constructor.test.d.ts.map +1 -0
  14. package/dist/__tests__/constructor.test.js +267 -0
  15. package/dist/__tests__/constructor.test.js.map +1 -0
  16. package/dist/__tests__/hello-world.test.d.ts +2 -0
  17. package/dist/__tests__/hello-world.test.d.ts.map +1 -0
  18. package/dist/__tests__/hello-world.test.js +9 -0
  19. package/dist/__tests__/hello-world.test.js.map +1 -0
  20. package/dist/__tests__/policy-enforcement.test.d.ts +2 -0
  21. package/dist/__tests__/policy-enforcement.test.d.ts.map +1 -0
  22. package/dist/__tests__/policy-enforcement.test.js +188 -0
  23. package/dist/__tests__/policy-enforcement.test.js.map +1 -0
  24. package/dist/__tests__/proof-hash-regression.test.d.ts +2 -0
  25. package/dist/__tests__/proof-hash-regression.test.d.ts.map +1 -0
  26. package/dist/__tests__/proof-hash-regression.test.js +134 -0
  27. package/dist/__tests__/proof-hash-regression.test.js.map +1 -0
  28. package/dist/__tests__/proof-hash.test.d.ts +2 -0
  29. package/dist/__tests__/proof-hash.test.d.ts.map +1 -0
  30. package/dist/__tests__/proof-hash.test.js +134 -0
  31. package/dist/__tests__/proof-hash.test.js.map +1 -0
  32. package/dist/__tests__/verifier.test.d.ts +2 -0
  33. package/dist/__tests__/verifier.test.d.ts.map +1 -0
  34. package/dist/__tests__/verifier.test.js +457 -0
  35. package/dist/__tests__/verifier.test.js.map +1 -0
  36. package/dist/canonical.d.ts +54 -0
  37. package/dist/canonical.d.ts.map +1 -0
  38. package/dist/canonical.js +119 -0
  39. package/dist/canonical.js.map +1 -0
  40. package/dist/constructor.d.ts +66 -0
  41. package/dist/constructor.d.ts.map +1 -0
  42. package/dist/constructor.js +339 -0
  43. package/dist/constructor.js.map +1 -0
  44. package/dist/host.d.ts +138 -0
  45. package/dist/host.d.ts.map +1 -0
  46. package/dist/host.js +3 -0
  47. package/dist/host.js.map +1 -0
  48. package/dist/index.d.ts +20 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +9 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/policy.d.ts +68 -0
  53. package/dist/policy.d.ts.map +1 -0
  54. package/dist/policy.js +176 -0
  55. package/dist/policy.js.map +1 -0
  56. package/dist/proof-hash.d.ts +9 -0
  57. package/dist/proof-hash.d.ts.map +1 -0
  58. package/dist/proof-hash.js +75 -0
  59. package/dist/proof-hash.js.map +1 -0
  60. package/dist/types.d.ts +705 -0
  61. package/dist/types.d.ts.map +1 -0
  62. package/dist/types.js +3 -0
  63. package/dist/types.js.map +1 -0
  64. package/dist/verifier.d.ts +27 -0
  65. package/dist/verifier.d.ts.map +1 -0
  66. package/dist/verifier.js +844 -0
  67. package/dist/verifier.js.map +1 -0
  68. package/package.json +40 -0
  69. package/src/__tests__/canonical.test.ts +253 -0
  70. package/src/__tests__/commit-service.integration.test.ts +117 -0
  71. package/src/__tests__/constructor.test.ts +340 -0
  72. package/src/__tests__/hello-world.test.ts +10 -0
  73. package/src/__tests__/policy-enforcement.test.ts +226 -0
  74. package/src/__tests__/proof-hash-regression.test.ts +147 -0
  75. package/src/__tests__/proof-hash.test.ts +148 -0
  76. package/src/__tests__/verifier.test.ts +541 -0
  77. package/src/constructor.ts +435 -0
  78. package/src/host.ts +153 -0
  79. package/src/index.ts +51 -0
  80. package/src/policy.ts +239 -0
package/src/policy.ts ADDED
@@ -0,0 +1,239 @@
1
+ // Copyright (c) Mike Argento. All rights reserved. See LICENSE.
2
+
3
+ /**
4
+ * bitgraph-core Policy — parse, hash, and validate markdown policy documents.
5
+ *
6
+ * Policy documents are human-readable markdown files that define what an
7
+ * agent is allowed to do. The SHA-256 hash of the raw document bytes is
8
+ * included in the proof's signed body, cryptographically binding the
9
+ * proof to the exact policy that governed the action.
10
+ *
11
+ * Format:
12
+ * # Policy: <name>
13
+ * version: <version>
14
+ *
15
+ * ## Allowed Tools
16
+ * - tool_a
17
+ * - tool_b
18
+ *
19
+ * ## Limits
20
+ * - max_actions: 500
21
+ * - rate_limit: 10/min
22
+ *
23
+ * ## Time Window
24
+ * - hours: 9-17
25
+ *
26
+ * ## Require Approval
27
+ * - send_email
28
+ */
29
+
30
+ import { sha256 } from "@noble/hashes/sha256";
31
+ import type { PolicyBinding } from "@mikeargento/bitgraph-verify";
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // Policy document types
35
+ // ---------------------------------------------------------------------------
36
+
37
+ export interface PolicyDocument {
38
+ /** Human-readable policy name (from "# Policy: <name>"). */
39
+ name: string;
40
+ /** Version identifier (from "version: <version>"). */
41
+ version: string;
42
+ /** Structured rules parsed from the document. */
43
+ rules: PolicyRules;
44
+ /** The original raw markdown text. */
45
+ raw: string;
46
+ }
47
+
48
+ export interface PolicyRules {
49
+ /** Always true — BitGraph is default-deny. */
50
+ defaultDeny: true;
51
+ /** Tool names explicitly allowed by the policy. */
52
+ allowedTools?: string[] | undefined;
53
+ /** Maximum total actions permitted under this policy. */
54
+ maxActions?: number | undefined;
55
+ /** Maximum actions per minute. */
56
+ rateLimit?: number | undefined;
57
+ /** Allowed hours of operation (24h clock, 0-23). */
58
+ timeWindow?: { start: number; end: number } | undefined;
59
+ /** Tool names that require multi-sig / human approval. */
60
+ requireApproval?: string[] | undefined;
61
+ /** Arbitrary extension metadata. */
62
+ metadata?: Record<string, unknown> | undefined;
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Parsing
67
+ // ---------------------------------------------------------------------------
68
+
69
+ /**
70
+ * Parse a markdown policy document into structured rules.
71
+ *
72
+ * Extracts the policy name, version, and rule sections from a
73
+ * human-readable markdown format.
74
+ */
75
+ export function parsePolicy(markdown: string): PolicyDocument {
76
+ const lines = markdown.split("\n");
77
+ const name = extractField(lines, /^#\s+Policy:\s*(.+)/);
78
+ const version = extractField(lines, /^version:\s*(.+)/);
79
+
80
+ const rules: PolicyRules = { defaultDeny: true };
81
+
82
+ // Parse allowed tools section
83
+ const toolsSection = extractSection(lines, "Allowed Tools");
84
+ if (toolsSection.length > 0) {
85
+ rules.allowedTools = toolsSection
86
+ .map((line) => line.replace(/^[-*]\s*/, "").trim())
87
+ .filter(Boolean);
88
+ }
89
+
90
+ // Parse limits
91
+ const limitsSection = extractSection(lines, "Limits");
92
+ for (const line of limitsSection) {
93
+ const clean = line.replace(/^[-*]\s*/, "").trim();
94
+ const maxMatch = clean.match(/max_actions:\s*(\d+)/);
95
+ if (maxMatch?.[1]) rules.maxActions = parseInt(maxMatch[1], 10);
96
+ const rateMatch = clean.match(/rate_limit:\s*(\d+)/);
97
+ if (rateMatch?.[1]) rules.rateLimit = parseInt(rateMatch[1], 10);
98
+ }
99
+
100
+ // Parse time window
101
+ const timeSection = extractSection(lines, "Time Window");
102
+ for (const line of timeSection) {
103
+ const clean = line.replace(/^[-*]\s*/, "").trim();
104
+ const hoursMatch = clean.match(/hours:\s*(\d+)-(\d+)/);
105
+ if (hoursMatch?.[1] && hoursMatch[2]) {
106
+ rules.timeWindow = {
107
+ start: parseInt(hoursMatch[1], 10),
108
+ end: parseInt(hoursMatch[2], 10),
109
+ };
110
+ }
111
+ }
112
+
113
+ // Parse require approval
114
+ const approvalSection = extractSection(lines, "Require Approval");
115
+ if (approvalSection.length > 0) {
116
+ rules.requireApproval = approvalSection
117
+ .map((line) => line.replace(/^[-*]\s*/, "").trim())
118
+ .filter(Boolean);
119
+ }
120
+
121
+ return {
122
+ name: name ?? "Unnamed Policy",
123
+ version: version ?? "1.0",
124
+ rules,
125
+ raw: markdown,
126
+ };
127
+ }
128
+
129
+ function extractField(
130
+ lines: string[],
131
+ pattern: RegExp,
132
+ ): string | undefined {
133
+ for (const line of lines) {
134
+ const match = line.match(pattern);
135
+ if (match?.[1]) return match[1].trim();
136
+ }
137
+ return undefined;
138
+ }
139
+
140
+ function extractSection(lines: string[], sectionName: string): string[] {
141
+ const result: string[] = [];
142
+ let inSection = false;
143
+ for (const line of lines) {
144
+ if (line.match(new RegExp(`^##\\s+${sectionName}`, "i"))) {
145
+ inSection = true;
146
+ continue;
147
+ }
148
+ if (inSection && line.match(/^##\s+/)) break; // next section
149
+ if (inSection && line.trim()) result.push(line);
150
+ }
151
+ return result;
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // Hashing
156
+ // ---------------------------------------------------------------------------
157
+
158
+ /**
159
+ * Compute the SHA-256 hash of a policy document's raw text.
160
+ *
161
+ * Returns a Base64-standard (RFC 4648 §4) encoded digest suitable for
162
+ * inclusion in the proof's policy.digestB64 field.
163
+ */
164
+ export function hashPolicy(markdown: string): string {
165
+ const bytes = new TextEncoder().encode(markdown);
166
+ const hash = sha256(bytes);
167
+ return Buffer.from(hash).toString("base64");
168
+ }
169
+
170
+ /**
171
+ * Create a PolicyBinding from a raw markdown policy document.
172
+ *
173
+ * Convenience function that parses the document for name/version and
174
+ * computes the SHA-256 digest in one call.
175
+ */
176
+ export function createPolicyBinding(markdown: string): PolicyBinding {
177
+ const doc = parsePolicy(markdown);
178
+ const binding: PolicyBinding = {
179
+ digestB64: hashPolicy(markdown),
180
+ };
181
+ if (doc.name !== "Unnamed Policy") binding.name = doc.name;
182
+ if (doc.version !== "1.0") binding.version = doc.version;
183
+ return binding;
184
+ }
185
+
186
+ // ---------------------------------------------------------------------------
187
+ // Validation
188
+ // ---------------------------------------------------------------------------
189
+
190
+ export interface ActionValidationResult {
191
+ /** Whether the action is permitted under the policy rules. */
192
+ valid: boolean;
193
+ /** Human-readable reason when valid is false. */
194
+ reason?: string | undefined;
195
+ }
196
+
197
+ /**
198
+ * Validate that an action complies with the policy rules.
199
+ *
200
+ * Checks tool allowlist and time window constraints. Rate limiting
201
+ * and action counting require external state and are not checked here.
202
+ */
203
+ export function validateAction(
204
+ action: { tool: string; timestamp?: number | undefined },
205
+ rules: PolicyRules,
206
+ ): ActionValidationResult {
207
+ // Default deny — tool must be in allowed list
208
+ if (rules.allowedTools && !rules.allowedTools.includes(action.tool)) {
209
+ return {
210
+ valid: false,
211
+ reason: `Tool "${action.tool}" not in allowed list`,
212
+ };
213
+ }
214
+
215
+ // Time window check
216
+ if (rules.timeWindow && action.timestamp !== undefined) {
217
+ const hour = new Date(action.timestamp).getHours();
218
+ if (hour < rules.timeWindow.start || hour >= rules.timeWindow.end) {
219
+ return {
220
+ valid: false,
221
+ reason: `Action outside allowed hours (${rules.timeWindow.start}-${rules.timeWindow.end})`,
222
+ };
223
+ }
224
+ }
225
+
226
+ // Require approval check (advisory — returns valid but flags the tool)
227
+ // Actual approval enforcement happens at the proxy layer
228
+ if (
229
+ rules.requireApproval &&
230
+ rules.requireApproval.includes(action.tool)
231
+ ) {
232
+ return {
233
+ valid: true,
234
+ reason: `Tool "${action.tool}" requires approval`,
235
+ };
236
+ }
237
+
238
+ return { valid: true };
239
+ }