@vorionsys/basis 1.0.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 (174) hide show
  1. package/.env.example +22 -0
  2. package/AMOY-MIGRATION.md +188 -0
  3. package/DEPLOY-AMOY.md +368 -0
  4. package/DEPLOY-NOW.md +216 -0
  5. package/DEPLOYMENT.md +239 -0
  6. package/GET-WALLET.md +286 -0
  7. package/QUICK-WALLET-SETUP.md +268 -0
  8. package/README.md +195 -0
  9. package/artifacts/@openzeppelin/contracts/access/AccessControl.sol/AccessControl.dbg.json +4 -0
  10. package/artifacts/@openzeppelin/contracts/access/AccessControl.sol/AccessControl.json +236 -0
  11. package/artifacts/@openzeppelin/contracts/access/IAccessControl.sol/IAccessControl.dbg.json +4 -0
  12. package/artifacts/@openzeppelin/contracts/access/IAccessControl.sol/IAccessControl.json +204 -0
  13. package/artifacts/@openzeppelin/contracts/interfaces/IERC4906.sol/IERC4906.dbg.json +4 -0
  14. package/artifacts/@openzeppelin/contracts/interfaces/IERC4906.sol/IERC4906.json +328 -0
  15. package/artifacts/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors.dbg.json +4 -0
  16. package/artifacts/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors.json +113 -0
  17. package/artifacts/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors.dbg.json +4 -0
  18. package/artifacts/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors.json +97 -0
  19. package/artifacts/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors.dbg.json +4 -0
  20. package/artifacts/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors.json +114 -0
  21. package/artifacts/@openzeppelin/contracts/token/ERC721/ERC721.sol/ERC721.dbg.json +4 -0
  22. package/artifacts/@openzeppelin/contracts/token/ERC721/ERC721.sol/ERC721.json +444 -0
  23. package/artifacts/@openzeppelin/contracts/token/ERC721/IERC721.sol/IERC721.dbg.json +4 -0
  24. package/artifacts/@openzeppelin/contracts/token/ERC721/IERC721.sol/IERC721.json +296 -0
  25. package/artifacts/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol/IERC721Receiver.dbg.json +4 -0
  26. package/artifacts/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol/IERC721Receiver.json +45 -0
  27. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol/ERC721Enumerable.dbg.json +4 -0
  28. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol/ERC721Enumerable.json +521 -0
  29. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol/ERC721URIStorage.dbg.json +4 -0
  30. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol/ERC721URIStorage.json +476 -0
  31. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol/IERC721Enumerable.dbg.json +4 -0
  32. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol/IERC721Enumerable.json +352 -0
  33. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol/IERC721Metadata.dbg.json +4 -0
  34. package/artifacts/@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol/IERC721Metadata.json +341 -0
  35. package/artifacts/@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol/ERC721Utils.dbg.json +4 -0
  36. package/artifacts/@openzeppelin/contracts/token/ERC721/utils/ERC721Utils.sol/ERC721Utils.json +10 -0
  37. package/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.dbg.json +4 -0
  38. package/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.json +10 -0
  39. package/artifacts/@openzeppelin/contracts/utils/Panic.sol/Panic.dbg.json +4 -0
  40. package/artifacts/@openzeppelin/contracts/utils/Panic.sol/Panic.json +10 -0
  41. package/artifacts/@openzeppelin/contracts/utils/Strings.sol/Strings.dbg.json +4 -0
  42. package/artifacts/@openzeppelin/contracts/utils/Strings.sol/Strings.json +37 -0
  43. package/artifacts/@openzeppelin/contracts/utils/introspection/ERC165.sol/ERC165.dbg.json +4 -0
  44. package/artifacts/@openzeppelin/contracts/utils/introspection/ERC165.sol/ERC165.json +30 -0
  45. package/artifacts/@openzeppelin/contracts/utils/introspection/IERC165.sol/IERC165.dbg.json +4 -0
  46. package/artifacts/@openzeppelin/contracts/utils/introspection/IERC165.sol/IERC165.json +30 -0
  47. package/artifacts/@openzeppelin/contracts/utils/math/Math.sol/Math.dbg.json +4 -0
  48. package/artifacts/@openzeppelin/contracts/utils/math/Math.sol/Math.json +10 -0
  49. package/artifacts/@openzeppelin/contracts/utils/math/SafeCast.sol/SafeCast.dbg.json +4 -0
  50. package/artifacts/@openzeppelin/contracts/utils/math/SafeCast.sol/SafeCast.json +65 -0
  51. package/artifacts/@openzeppelin/contracts/utils/math/SignedMath.sol/SignedMath.dbg.json +4 -0
  52. package/artifacts/@openzeppelin/contracts/utils/math/SignedMath.sol/SignedMath.json +10 -0
  53. package/artifacts/build-info/357d1bba4062d461f497f221490811a3.json +1 -0
  54. package/artifacts/contracts/AgentCard.sol/AgentCard.dbg.json +4 -0
  55. package/artifacts/contracts/AgentCard.sol/AgentCard.json +1430 -0
  56. package/build_errors.txt +0 -0
  57. package/build_output.txt +0 -0
  58. package/cache/solidity-files-cache.json +885 -0
  59. package/contracts/AgentCard.sol +478 -0
  60. package/contracts/deploy/01-deploy-agentcard.ts +66 -0
  61. package/dist/index.d.ts.map +1 -0
  62. package/dist/index.js +12 -0
  63. package/dist/kya/accountability.d.ts.map +1 -0
  64. package/dist/kya/accountability.js +100 -0
  65. package/dist/kya/authorization.d.ts.map +1 -0
  66. package/dist/kya/authorization.js +258 -0
  67. package/dist/kya/behavior.d.ts.map +1 -0
  68. package/dist/kya/behavior.js +142 -0
  69. package/dist/kya/identity.d.ts.map +1 -0
  70. package/dist/kya/identity.js +187 -0
  71. package/dist/kya/index.d.ts.map +1 -0
  72. package/dist/kya/index.js +99 -0
  73. package/dist/kya/types.d.ts.map +1 -0
  74. package/dist/kya/types.js +5 -0
  75. package/dist/trust-1000-agents.test.d.ts.map +1 -0
  76. package/dist/trust-1000-agents.test.js +608 -0
  77. package/dist/trust-capabilities.d.ts.map +1 -0
  78. package/dist/trust-capabilities.js +478 -0
  79. package/dist/trust-factors.d.ts.map +1 -0
  80. package/dist/trust-factors.js +588 -0
  81. package/dist/trust-factors.test.d.ts.map +1 -0
  82. package/dist/trust-factors.test.js +179 -0
  83. package/dist/validation-gate.d.ts.map +1 -0
  84. package/dist/validation-gate.js +468 -0
  85. package/dist/validation-gate.test.d.ts.map +1 -0
  86. package/dist/validation-gate.test.js +419 -0
  87. package/hardhat.config.ts +55 -0
  88. package/package.json +57 -0
  89. package/scripts/certify-agent.ts +91 -0
  90. package/scripts/deploy-agentcard.ts +63 -0
  91. package/scripts/mint-agentcard.ts +87 -0
  92. package/specs/adversarial-sandbox-test-suite.md +1055 -0
  93. package/specs/kya-framework.md +910 -0
  94. package/specs/trust-factors-v2.md +437 -0
  95. package/src/index.ts +14 -0
  96. package/src/kya/accountability.ts +132 -0
  97. package/src/kya/authorization.ts +325 -0
  98. package/src/kya/behavior.ts +169 -0
  99. package/src/kya/identity.ts +224 -0
  100. package/src/kya/index.ts +125 -0
  101. package/src/kya/types.ts +242 -0
  102. package/src/trust-1000-agents.test.ts +745 -0
  103. package/src/trust-capabilities.ts +517 -0
  104. package/src/trust-factors.test.ts +241 -0
  105. package/src/trust-factors.ts +666 -0
  106. package/src/validation-gate.test.ts +531 -0
  107. package/src/validation-gate.ts +665 -0
  108. package/test-kya-simple.ts +258 -0
  109. package/test-kya.ts +245 -0
  110. package/tsconfig.json +14 -0
  111. package/typechain-types/@openzeppelin/contracts/access/AccessControl.ts +324 -0
  112. package/typechain-types/@openzeppelin/contracts/access/IAccessControl.ts +292 -0
  113. package/typechain-types/@openzeppelin/contracts/access/index.ts +5 -0
  114. package/typechain-types/@openzeppelin/contracts/index.ts +11 -0
  115. package/typechain-types/@openzeppelin/contracts/interfaces/IERC4906.ts +462 -0
  116. package/typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors.ts +69 -0
  117. package/typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors.ts +69 -0
  118. package/typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors.ts +69 -0
  119. package/typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/index.ts +6 -0
  120. package/typechain-types/@openzeppelin/contracts/interfaces/index.ts +6 -0
  121. package/typechain-types/@openzeppelin/contracts/token/ERC721/ERC721.ts +420 -0
  122. package/typechain-types/@openzeppelin/contracts/token/ERC721/IERC721.ts +393 -0
  123. package/typechain-types/@openzeppelin/contracts/token/ERC721/IERC721Receiver.ts +110 -0
  124. package/typechain-types/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.ts +470 -0
  125. package/typechain-types/@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.ts +489 -0
  126. package/typechain-types/@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.ts +443 -0
  127. package/typechain-types/@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.ts +420 -0
  128. package/typechain-types/@openzeppelin/contracts/token/ERC721/extensions/index.ts +7 -0
  129. package/typechain-types/@openzeppelin/contracts/token/ERC721/index.ts +8 -0
  130. package/typechain-types/@openzeppelin/contracts/token/index.ts +5 -0
  131. package/typechain-types/@openzeppelin/contracts/utils/Strings.ts +69 -0
  132. package/typechain-types/@openzeppelin/contracts/utils/index.ts +8 -0
  133. package/typechain-types/@openzeppelin/contracts/utils/introspection/ERC165.ts +94 -0
  134. package/typechain-types/@openzeppelin/contracts/utils/introspection/IERC165.ts +94 -0
  135. package/typechain-types/@openzeppelin/contracts/utils/introspection/index.ts +5 -0
  136. package/typechain-types/@openzeppelin/contracts/utils/math/SafeCast.ts +69 -0
  137. package/typechain-types/@openzeppelin/contracts/utils/math/index.ts +4 -0
  138. package/typechain-types/@openzeppelin/index.ts +5 -0
  139. package/typechain-types/common.ts +131 -0
  140. package/typechain-types/contracts/AgentCard.ts +1415 -0
  141. package/typechain-types/contracts/index.ts +4 -0
  142. package/typechain-types/factories/@openzeppelin/contracts/access/AccessControl__factory.ts +250 -0
  143. package/typechain-types/factories/@openzeppelin/contracts/access/IAccessControl__factory.ts +218 -0
  144. package/typechain-types/factories/@openzeppelin/contracts/access/index.ts +5 -0
  145. package/typechain-types/factories/@openzeppelin/contracts/index.ts +7 -0
  146. package/typechain-types/factories/@openzeppelin/contracts/interfaces/IERC4906__factory.ts +339 -0
  147. package/typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors__factory.ts +127 -0
  148. package/typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors__factory.ts +111 -0
  149. package/typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors__factory.ts +128 -0
  150. package/typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/index.ts +6 -0
  151. package/typechain-types/factories/@openzeppelin/contracts/interfaces/index.ts +5 -0
  152. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/ERC721__factory.ts +455 -0
  153. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/IERC721Receiver__factory.ts +59 -0
  154. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/IERC721__factory.ts +307 -0
  155. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable__factory.ts +535 -0
  156. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage__factory.ts +490 -0
  157. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable__factory.ts +366 -0
  158. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata__factory.ts +355 -0
  159. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/extensions/index.ts +7 -0
  160. package/typechain-types/factories/@openzeppelin/contracts/token/ERC721/index.ts +7 -0
  161. package/typechain-types/factories/@openzeppelin/contracts/token/index.ts +4 -0
  162. package/typechain-types/factories/@openzeppelin/contracts/utils/Strings__factory.ts +90 -0
  163. package/typechain-types/factories/@openzeppelin/contracts/utils/index.ts +6 -0
  164. package/typechain-types/factories/@openzeppelin/contracts/utils/introspection/ERC165__factory.ts +41 -0
  165. package/typechain-types/factories/@openzeppelin/contracts/utils/introspection/IERC165__factory.ts +41 -0
  166. package/typechain-types/factories/@openzeppelin/contracts/utils/introspection/index.ts +5 -0
  167. package/typechain-types/factories/@openzeppelin/contracts/utils/math/SafeCast__factory.ts +118 -0
  168. package/typechain-types/factories/@openzeppelin/contracts/utils/math/index.ts +4 -0
  169. package/typechain-types/factories/@openzeppelin/index.ts +4 -0
  170. package/typechain-types/factories/contracts/AgentCard__factory.ts +1480 -0
  171. package/typechain-types/factories/contracts/index.ts +4 -0
  172. package/typechain-types/factories/index.ts +5 -0
  173. package/typechain-types/index.ts +44 -0
  174. package/vitest.config.ts +8 -0
@@ -0,0 +1,325 @@
1
+ /**
2
+ * KYA Authorization Manager
3
+ * Capability-based access control + policy enforcement
4
+ */
5
+
6
+ import {
7
+ AuthorizationRequest,
8
+ AuthorizationDecision,
9
+ CapabilityToken,
10
+ PolicyBundle,
11
+ PolicyEngineConfig,
12
+ KYACapability,
13
+ } from './types.js';
14
+
15
+ export class AuthorizationManager {
16
+ private policyBundles: Map<string, PolicyBundle>;
17
+ private capabilities: Map<string, CapabilityToken[]>;
18
+
19
+ constructor(private config: PolicyEngineConfig) {
20
+ this.policyBundles = new Map();
21
+ this.capabilities = new Map();
22
+
23
+ // Load policy bundles
24
+ this.loadPolicyBundles();
25
+ }
26
+
27
+ /**
28
+ * Authorize agent action
29
+ */
30
+ async authorize(request: AuthorizationRequest): Promise<AuthorizationDecision> {
31
+ // 1. Get agent capabilities
32
+ const agentCapabilities = this.capabilities.get(request.agentDID) || [];
33
+
34
+ // 2. Find matching capability
35
+ const matchingCap = agentCapabilities.find(token =>
36
+ token.capabilities.some((cap: KYACapability) =>
37
+ this.matchesCapability(cap, request.action, request.resource)
38
+ )
39
+ );
40
+
41
+ if (!matchingCap) {
42
+ return {
43
+ allowed: false,
44
+ reason: 'No matching capability',
45
+ trustImpact: -10,
46
+ };
47
+ }
48
+
49
+ // 3. Check capability expiry
50
+ const now = new Date();
51
+ const notBefore = new Date(matchingCap.notBefore);
52
+ const notAfter = new Date(matchingCap.notAfter);
53
+
54
+ if (now < notBefore || now > notAfter) {
55
+ return {
56
+ allowed: false,
57
+ reason: 'Capability expired or not yet valid',
58
+ trustImpact: -5,
59
+ };
60
+ }
61
+
62
+ // 4. Evaluate conditions
63
+ const capability = matchingCap.capabilities.find((cap: KYACapability) =>
64
+ this.matchesCapability(cap, request.action, request.resource)
65
+ )!;
66
+
67
+ if (capability.conditions) {
68
+ const conditionsValid = await this.evaluateConditions(
69
+ capability.conditions,
70
+ request
71
+ );
72
+
73
+ if (!conditionsValid) {
74
+ return {
75
+ allowed: false,
76
+ reason: 'Capability conditions not met',
77
+ trustImpact: -5,
78
+ };
79
+ }
80
+ }
81
+
82
+ // 5. Check policy constraints
83
+ const policyViolations = await this.checkPolicyConstraints(request);
84
+
85
+ if (policyViolations.length > 0) {
86
+ return {
87
+ allowed: false,
88
+ reason: `Policy violations: ${policyViolations.join(', ')}`,
89
+ trustImpact: -20,
90
+ };
91
+ }
92
+
93
+ // 6. ALLOW
94
+ return {
95
+ allowed: true,
96
+ reason: 'Authorized',
97
+ conditions: capability.conditions,
98
+ trustImpact: 1,
99
+ };
100
+ }
101
+
102
+ /**
103
+ * Grant capability to agent
104
+ */
105
+ async grantCapability(
106
+ agentDID: string,
107
+ capabilityToken: CapabilityToken
108
+ ): Promise<void> {
109
+ const existing = this.capabilities.get(agentDID) || [];
110
+ existing.push(capabilityToken);
111
+ this.capabilities.set(agentDID, existing);
112
+ }
113
+
114
+ /**
115
+ * Revoke capability from agent
116
+ */
117
+ async revokeCapability(agentDID: string, capabilityId: string): Promise<void> {
118
+ const existing = this.capabilities.get(agentDID) || [];
119
+ const filtered = existing.filter(cap => cap.id !== capabilityId);
120
+ this.capabilities.set(agentDID, filtered);
121
+ }
122
+
123
+ // ============================================================================
124
+ // Private Methods
125
+ // ============================================================================
126
+
127
+ /**
128
+ * Check if capability matches action + resource
129
+ */
130
+ private matchesCapability(
131
+ capability: { action: string; resource: string },
132
+ action: string,
133
+ resource: string
134
+ ): boolean {
135
+ // Exact match
136
+ if (capability.action === action && capability.resource === resource) {
137
+ return true;
138
+ }
139
+
140
+ // Wildcard match
141
+ const actionMatch = this.matchesPattern(capability.action, action);
142
+ const resourceMatch = this.matchesPattern(capability.resource, resource);
143
+
144
+ return actionMatch && resourceMatch;
145
+ }
146
+
147
+ /**
148
+ * Pattern matching with wildcards
149
+ */
150
+ private matchesPattern(pattern: string, value: string): boolean {
151
+ if (pattern === '*') return true;
152
+ if (pattern === value) return true;
153
+
154
+ // Convert glob pattern to regex
155
+ const regexPattern = pattern
156
+ .replace(/\./g, '\\.')
157
+ .replace(/\*/g, '.*');
158
+
159
+ const regex = new RegExp(`^${regexPattern}$`);
160
+ return regex.test(value);
161
+ }
162
+
163
+ /**
164
+ * Evaluate capability conditions
165
+ */
166
+ private async evaluateConditions(
167
+ conditions: Record<string, unknown>,
168
+ request: AuthorizationRequest
169
+ ): Promise<boolean> {
170
+ // Example condition checks
171
+ if (conditions.maxFileSize && request.resource.startsWith('/')) {
172
+ // Would check actual file size
173
+ return true;
174
+ }
175
+
176
+ if (conditions.rateLimit) {
177
+ // Would check rate limiting
178
+ return true;
179
+ }
180
+
181
+ if (conditions.methods && Array.isArray(conditions.methods)) {
182
+ // Would check HTTP method
183
+ return true;
184
+ }
185
+
186
+ return true;
187
+ }
188
+
189
+ /**
190
+ * Check policy constraints (MUST NOT do)
191
+ */
192
+ private async checkPolicyConstraints(
193
+ request: AuthorizationRequest
194
+ ): Promise<string[]> {
195
+ const violations: string[] = [];
196
+
197
+ // Get applicable policy bundle
198
+ const policyBundle = this.policyBundles.get(this.config.defaultJurisdiction);
199
+
200
+ if (!policyBundle) {
201
+ return violations;
202
+ }
203
+
204
+ // Check each constraint
205
+ for (const constraint of policyBundle.constraints) {
206
+ const violated = await this.evaluateConstraint(constraint.rule, request);
207
+
208
+ if (violated) {
209
+ violations.push(constraint.description);
210
+
211
+ // Apply enforcement action
212
+ if (constraint.enforcement === 'block') {
213
+ // Already blocked by adding to violations
214
+ } else if (constraint.enforcement === 'warn') {
215
+ console.warn(`Policy warning: ${constraint.description}`);
216
+ } else if (constraint.enforcement === 'log') {
217
+ console.log(`Policy logged: ${constraint.description}`);
218
+ }
219
+ }
220
+ }
221
+
222
+ return violations;
223
+ }
224
+
225
+ /**
226
+ * Evaluate constraint rule (simplified)
227
+ */
228
+ private async evaluateConstraint(
229
+ rule: string,
230
+ request: AuthorizationRequest
231
+ ): Promise<boolean> {
232
+ // Would use CEL (Common Expression Language) or JSON Logic
233
+ // For now, simple keyword matching
234
+ if (rule.includes('no_credential_access') && request.resource.includes('credential')) {
235
+ return true;
236
+ }
237
+
238
+ if (rule.includes('no_external_code') && request.action.includes('code.execute')) {
239
+ return true;
240
+ }
241
+
242
+ return false;
243
+ }
244
+
245
+ /**
246
+ * Load policy bundles from configuration
247
+ */
248
+ private loadPolicyBundles(): void {
249
+ // Would load from files/database
250
+ // For now, create a default policy bundle
251
+ const defaultBundle: PolicyBundle = {
252
+ id: 'vorion-default-v1',
253
+ version: '1.0.0',
254
+ jurisdiction: 'Global',
255
+ constraints: [
256
+ {
257
+ id: 'no-credential-access',
258
+ description: 'Agents cannot access credential files',
259
+ rule: 'no_credential_access',
260
+ severity: 'critical',
261
+ enforcement: 'block',
262
+ },
263
+ {
264
+ id: 'no-external-code',
265
+ description: 'Agents cannot execute external code',
266
+ rule: 'no_external_code',
267
+ severity: 'high',
268
+ enforcement: 'block',
269
+ },
270
+ ],
271
+ obligations: [],
272
+ permissions: [],
273
+ };
274
+
275
+ this.policyBundles.set('Global', defaultBundle);
276
+ }
277
+ }
278
+
279
+ // ============================================================================
280
+ // Example Usage
281
+ // ============================================================================
282
+
283
+ /*
284
+ import { AuthorizationManager } from './authorization';
285
+
286
+ async function example() {
287
+ const authManager = new AuthorizationManager({
288
+ policyBundlesPath: './policies',
289
+ defaultJurisdiction: 'Global',
290
+ });
291
+
292
+ // Grant capability to agent
293
+ await authManager.grantCapability('did:vorion:agent:123', {
294
+ id: 'cap_001',
295
+ issuer: 'did:vorion:org:agentanchor',
296
+ subject: 'did:vorion:agent:123',
297
+ capabilities: [
298
+ {
299
+ action: 'file.write',
300
+ resource: '/data/user_documents/*',
301
+ conditions: {
302
+ maxFileSize: 10485760,
303
+ allowedExtensions: ['.txt', '.md', '.json'],
304
+ },
305
+ },
306
+ ],
307
+ notBefore: new Date().toISOString(),
308
+ notAfter: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
309
+ signature: '...',
310
+ });
311
+
312
+ // Check authorization
313
+ const decision = await authManager.authorize({
314
+ agentDID: 'did:vorion:agent:123',
315
+ action: 'file.write',
316
+ resource: '/data/user_documents/report.txt',
317
+ context: {
318
+ timestamp: Date.now(),
319
+ },
320
+ });
321
+
322
+ console.log('Authorized:', decision.allowed);
323
+ console.log('Reason:', decision.reason);
324
+ }
325
+ */
@@ -0,0 +1,169 @@
1
+ /**
2
+ * KYA Behavior Monitor
3
+ * Real-time anomaly detection + trust scoring
4
+ */
5
+
6
+ import { AnomalyAlert, BehaviorProfile, DatabaseConfig } from './types.js';
7
+
8
+ export class BehaviorMonitor {
9
+ private profiles: Map<string, BehaviorProfile>;
10
+ private trustScores: Map<string, number>;
11
+
12
+ constructor(private config: DatabaseConfig) {
13
+ this.profiles = new Map();
14
+ this.trustScores = new Map();
15
+ }
16
+
17
+ /**
18
+ * Detect anomalies in agent behavior
19
+ */
20
+ async detectAnomalies(agentDID: string): Promise<AnomalyAlert[]> {
21
+ const profile = await this.getBehaviorProfile(agentDID);
22
+ const alerts: AnomalyAlert[] = [];
23
+
24
+ // 1. Rate spike detection
25
+ const zScore =
26
+ (profile.recentWindow.actionsInLastHour - profile.baseline.actionsPerHour.mean) /
27
+ profile.baseline.actionsPerHour.stddev;
28
+
29
+ if (zScore > 3) {
30
+ alerts.push({
31
+ severity: 'high',
32
+ type: 'rate_spike',
33
+ description: `Action rate is ${zScore.toFixed(1)} standard deviations above baseline`,
34
+ evidence: {
35
+ baseline: profile.baseline.actionsPerHour.mean,
36
+ current: profile.recentWindow.actionsInLastHour,
37
+ },
38
+ recommendedAction: 'throttle',
39
+ trustImpact: -50,
40
+ });
41
+ }
42
+
43
+ // 2. Success rate drop
44
+ const successDrop =
45
+ profile.baseline.successRate.mean - profile.recentWindow.successRateLastHour;
46
+
47
+ if (successDrop > 0.2) {
48
+ alerts.push({
49
+ severity: 'medium',
50
+ type: 'success_rate_drop',
51
+ description: `Success rate dropped ${(successDrop * 100).toFixed(1)}%`,
52
+ evidence: {
53
+ baseline: profile.baseline.successRate.mean,
54
+ current: profile.recentWindow.successRateLastHour,
55
+ },
56
+ recommendedAction: 'warn',
57
+ trustImpact: -20,
58
+ });
59
+ }
60
+
61
+ // 3. New capability usage
62
+ if (profile.recentWindow.newActionsInLastHour.length > 3) {
63
+ alerts.push({
64
+ severity: 'low',
65
+ type: 'new_capabilities',
66
+ description: `Agent using ${profile.recentWindow.newActionsInLastHour.length} new capabilities`,
67
+ evidence: {
68
+ newActions: profile.recentWindow.newActionsInLastHour,
69
+ },
70
+ recommendedAction: 'log',
71
+ trustImpact: -5,
72
+ });
73
+ }
74
+
75
+ // 4. Suspicious resource access
76
+ const suspiciousResources = profile.recentWindow.newResourcesInLastHour.filter((r: string) =>
77
+ r.includes('.env') || r.includes('credentials') || r.includes('secret')
78
+ );
79
+
80
+ if (suspiciousResources.length > 0) {
81
+ alerts.push({
82
+ severity: 'critical',
83
+ type: 'suspicious_resource_access',
84
+ description: 'Agent accessing sensitive resources',
85
+ evidence: {
86
+ resources: suspiciousResources,
87
+ },
88
+ recommendedAction: 'suspend',
89
+ trustImpact: -150,
90
+ });
91
+ }
92
+
93
+ return alerts;
94
+ }
95
+
96
+ /**
97
+ * Get or create behavior profile for agent
98
+ */
99
+ async getBehaviorProfile(agentDID: string): Promise<BehaviorProfile> {
100
+ if (this.profiles.has(agentDID)) {
101
+ return this.profiles.get(agentDID)!;
102
+ }
103
+
104
+ // Create initial profile
105
+ const profile: BehaviorProfile = {
106
+ agentDID,
107
+ baseline: {
108
+ actionsPerHour: { mean: 10, stddev: 3 },
109
+ successRate: { mean: 0.95, stddev: 0.05 },
110
+ topActions: [],
111
+ topResources: [],
112
+ },
113
+ recentWindow: {
114
+ actionsInLastHour: 0,
115
+ successRateLastHour: 1.0,
116
+ newActionsInLastHour: [],
117
+ newResourcesInLastHour: [],
118
+ },
119
+ };
120
+
121
+ this.profiles.set(agentDID, profile);
122
+ return profile;
123
+ }
124
+
125
+ /**
126
+ * Update trust score from behavior
127
+ */
128
+ async updateTrustScoreFromBehavior(
129
+ agentDID: string,
130
+ anomalies: AnomalyAlert[]
131
+ ): Promise<number> {
132
+ const currentScore = this.trustScores.get(agentDID) || 500; // Default: T3
133
+
134
+ // Apply trust impact from anomalies
135
+ const totalImpact = anomalies.reduce((sum, alert) => sum + alert.trustImpact, 0);
136
+
137
+ // Update trust score
138
+ const newScore = Math.max(0, Math.min(1000, currentScore + totalImpact));
139
+
140
+ this.trustScores.set(agentDID, newScore);
141
+
142
+ // Take recommended actions
143
+ for (const alert of anomalies) {
144
+ switch (alert.recommendedAction) {
145
+ case 'suspend':
146
+ console.warn(`SUSPEND agent ${agentDID}:`, alert.description);
147
+ break;
148
+ case 'throttle':
149
+ console.warn(`THROTTLE agent ${agentDID}:`, alert.description);
150
+ break;
151
+ case 'warn':
152
+ console.warn(`WARNING for agent ${agentDID}:`, alert.description);
153
+ break;
154
+ case 'log':
155
+ console.log(`LOG for agent ${agentDID}:`, alert.description);
156
+ break;
157
+ }
158
+ }
159
+
160
+ return newScore;
161
+ }
162
+
163
+ /**
164
+ * Get current trust score
165
+ */
166
+ async getTrustScore(agentDID: string): Promise<number> {
167
+ return this.trustScores.get(agentDID) || 500;
168
+ }
169
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * KYA Identity Verification
3
+ * W3C DID resolution + Ed25519 signature verification
4
+ */
5
+
6
+ import * as ed from '@noble/ed25519';
7
+ import { Resolver } from 'did-resolver';
8
+ import {
9
+ DIDDocument,
10
+ DIDResolverConfig,
11
+ IdentityProof,
12
+ VerificationMethod,
13
+ } from './types.js';
14
+
15
+ export class IdentityVerifier {
16
+ private resolver: Resolver;
17
+ private cache: Map<string, DIDDocument>;
18
+
19
+ constructor(config: DIDResolverConfig) {
20
+ // Initialize DID resolver (would integrate with did-resolver library)
21
+ this.resolver = new Resolver({
22
+ // Custom resolver for did:vorion:
23
+ vorion: async (did: string) => {
24
+ return this.resolveVorionDID(did);
25
+ },
26
+ });
27
+
28
+ this.cache = new Map();
29
+ }
30
+
31
+ /**
32
+ * Verify agent identity using DID + signature
33
+ */
34
+ async verify(proof: IdentityProof): Promise<boolean> {
35
+ try {
36
+ // 1. Resolve DID document
37
+ const didDoc = await this.resolveDID(proof.did);
38
+
39
+ // 2. Extract verification method
40
+ const verificationMethod = didDoc.verificationMethod?.find(
41
+ (vm: VerificationMethod) => vm.type === 'Ed25519VerificationKey2020'
42
+ );
43
+
44
+ if (!verificationMethod) {
45
+ throw new Error('No Ed25519 verification method found');
46
+ }
47
+
48
+ // 3. Verify signature
49
+ const message = `${proof.challenge}:${proof.timestamp}`;
50
+ const messageBytes = new TextEncoder().encode(message);
51
+ const signatureBytes = this.hexToBytes(proof.signature);
52
+ const publicKeyBytes = this.multibaseToBytes(verificationMethod.publicKeyMultibase);
53
+
54
+ const isValid = await ed.verify(signatureBytes, messageBytes, publicKeyBytes);
55
+
56
+ // 4. Check timestamp freshness (prevent replay attacks)
57
+ const age = Date.now() - proof.timestamp;
58
+ if (age > 60000) { // 1 minute max
59
+ throw new Error('Proof too old (replay attack prevention)');
60
+ }
61
+
62
+ return isValid;
63
+ } catch (error) {
64
+ console.error('Identity verification failed:', error);
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Resolve DID to DID Document
71
+ */
72
+ async resolveDID(did: string): Promise<DIDDocument> {
73
+ // Check cache first
74
+ if (this.cache.has(did)) {
75
+ return this.cache.get(did)!;
76
+ }
77
+
78
+ // Resolve from network
79
+ const result = await this.resolver.resolve(did);
80
+
81
+ if (!result.didDocument) {
82
+ throw new Error(`Failed to resolve DID: ${did}`);
83
+ }
84
+
85
+ const didDoc = result.didDocument as DIDDocument;
86
+
87
+ // Cache for future lookups
88
+ this.cache.set(did, didDoc);
89
+
90
+ return didDoc;
91
+ }
92
+
93
+ /**
94
+ * Custom Vorion DID resolver
95
+ * Format: did:vorion:<method>:<identifier>
96
+ */
97
+ private async resolveVorionDID(did: string): Promise<any> {
98
+ // Parse DID
99
+ const parts = did.split(':');
100
+ if (parts.length < 4) {
101
+ throw new Error('Invalid Vorion DID format');
102
+ }
103
+
104
+ const method = parts[2]; // e.g., 'ed25519'
105
+ const identifier = parts[3]; // e.g., '5Z8K3q2YvU8pVzNxF9sT7bQw6JhR1XmDcL4nVk'
106
+
107
+ // Fetch from Vorion DID registry (would be actual API call)
108
+ // For now, return mock structure
109
+ return {
110
+ didDocument: {
111
+ '@context': [
112
+ 'https://www.w3.org/ns/did/v1',
113
+ 'https://vorion.org/ns/kya/v1',
114
+ ],
115
+ id: did,
116
+ controller: did,
117
+ verificationMethod: [
118
+ {
119
+ id: `${did}#keys-1`,
120
+ type: 'Ed25519VerificationKey2020',
121
+ controller: did,
122
+ publicKeyMultibase: `z${identifier}`,
123
+ },
124
+ ],
125
+ authentication: [`${did}#keys-1`],
126
+ assertionMethod: [`${did}#keys-1`],
127
+ service: [
128
+ {
129
+ id: `${did}#agentcard`,
130
+ type: 'AgentCard',
131
+ serviceEndpoint: `https://agentanchorai.com/cards/${identifier}`,
132
+ },
133
+ ],
134
+ kya: {
135
+ trustScore: 0,
136
+ tier: 'T0' as const,
137
+ certified: false,
138
+ capabilities: [],
139
+ restrictions: [],
140
+ },
141
+ },
142
+ };
143
+ }
144
+
145
+ /**
146
+ * Generate challenge for identity proof
147
+ */
148
+ generateChallenge(): string {
149
+ const bytes = new Uint8Array(32);
150
+ crypto.getRandomValues(bytes);
151
+ return this.bytesToHex(bytes);
152
+ }
153
+
154
+ /**
155
+ * Sign challenge with private key (for agents to use)
156
+ */
157
+ async signChallenge(challenge: string, privateKey: Uint8Array): Promise<string> {
158
+ const timestamp = Date.now();
159
+ const message = `${challenge}:${timestamp}`;
160
+ const messageBytes = new TextEncoder().encode(message);
161
+
162
+ const signature = await ed.sign(messageBytes, privateKey);
163
+
164
+ return this.bytesToHex(signature);
165
+ }
166
+
167
+ // ============================================================================
168
+ // Utility Methods
169
+ // ============================================================================
170
+
171
+ private hexToBytes(hex: string): Uint8Array {
172
+ const bytes = new Uint8Array(hex.length / 2);
173
+ for (let i = 0; i < hex.length; i += 2) {
174
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
175
+ }
176
+ return bytes;
177
+ }
178
+
179
+ private bytesToHex(bytes: Uint8Array): string {
180
+ return Array.from(bytes)
181
+ .map(b => b.toString(16).padStart(2, '0'))
182
+ .join('');
183
+ }
184
+
185
+ private multibaseToBytes(multibase: string): Uint8Array {
186
+ // Remove 'z' prefix (base58btc encoding)
187
+ const base58 = multibase.substring(1);
188
+
189
+ // Decode base58 (simplified, would use actual base58 library)
190
+ // For now, assume hex encoding
191
+ return this.hexToBytes(base58);
192
+ }
193
+ }
194
+
195
+ // ============================================================================
196
+ // Example Usage
197
+ // ============================================================================
198
+
199
+ /*
200
+ import { IdentityVerifier } from './identity';
201
+
202
+ async function example() {
203
+ const verifier = new IdentityVerifier({
204
+ networks: ['vorion', 'ethereum'],
205
+ cacheEnabled: true,
206
+ });
207
+
208
+ // Agent generates proof
209
+ const challenge = verifier.generateChallenge();
210
+ const privateKey = ed.utils.randomPrivateKey();
211
+ const signature = await verifier.signChallenge(challenge, privateKey);
212
+
213
+ // Verify identity
214
+ const isValid = await verifier.verify({
215
+ did: 'did:vorion:ed25519:5Z8K3q2YvU8pVzNxF9sT7bQw6JhR1XmDcL4nVk',
216
+ timestamp: Date.now(),
217
+ challenge,
218
+ signature,
219
+ publicKey: ed.utils.bytesToHex(await ed.getPublicKey(privateKey)),
220
+ });
221
+
222
+ console.log('Identity valid:', isValid);
223
+ }
224
+ */