afyx-engineering-kit 0.0.0-stage → 0.1.0-alpha.4

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 (208) hide show
  1. package/.afyx-source-revision +1 -0
  2. package/LICENSE +21 -0
  3. package/README.md +377 -2
  4. package/SECURITY.md +74 -0
  5. package/afyx-context/LICENSE +21 -0
  6. package/afyx-context/README.md +155 -0
  7. package/afyx-context/afyx-context.json +30 -0
  8. package/afyx-context/contracts/integration-v1.schema.json +34 -0
  9. package/afyx-context/package-lock.json +53 -0
  10. package/afyx-context/package.json +34 -0
  11. package/afyx-context/scripts/benchmark.mjs +39 -0
  12. package/afyx-context/scripts/build.mjs +15 -0
  13. package/afyx-context/scripts/comparative-benchmark.mjs +342 -0
  14. package/afyx-context/scripts/comparative-worker.mjs +74 -0
  15. package/afyx-context/scripts/graph-integration-e2e.mjs +188 -0
  16. package/afyx-context/scripts/integrated-dogfood.mjs +309 -0
  17. package/afyx-context/src/budget.js +166 -0
  18. package/afyx-context/src/cli.js +110 -0
  19. package/afyx-context/src/coordination.js +343 -0
  20. package/afyx-context/src/engine.js +198 -0
  21. package/afyx-context/src/errors.js +14 -0
  22. package/afyx-context/src/graph-integration-worker.js +70 -0
  23. package/afyx-context/src/graph-integration.js +373 -0
  24. package/afyx-context/src/graph-mcp-bridge.js +103 -0
  25. package/afyx-context/src/index.js +25 -0
  26. package/afyx-context/src/integrations.js +87 -0
  27. package/afyx-context/src/memory.js +255 -0
  28. package/afyx-context/src/storage.js +364 -0
  29. package/afyx-context/test-fixtures/coordination-worker.mjs +52 -0
  30. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__init__.py +1 -0
  31. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__manifest__.py +4 -0
  32. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py +1 -0
  33. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/sale_order.py +5 -0
  34. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py +1 -0
  35. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__manifest__.py +10 -0
  36. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/__init__.py +2 -0
  37. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order.py +20 -0
  38. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order_audit.py +11 -0
  39. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/security/ir.model.access.csv +2 -0
  40. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/views/sale_order_views.xml +14 -0
  41. package/afyx-forge/LICENSE +55 -0
  42. package/afyx-forge/README.md +126 -0
  43. package/afyx-forge/afyx-forge.json +28 -0
  44. package/afyx-forge/bin/afyx-forge +4 -0
  45. package/afyx-forge/bin/afyx-forge.cmd +3 -0
  46. package/afyx-forge/bin/afyx-forge.js +16 -0
  47. package/afyx-forge/contracts/forge-plan-v1.schema.json +172 -0
  48. package/afyx-forge/package.json +26 -0
  49. package/afyx-forge/src/classifier.js +190 -0
  50. package/afyx-forge/src/cli.js +111 -0
  51. package/afyx-forge/src/doctor.js +105 -0
  52. package/afyx-forge/src/guidance.js +120 -0
  53. package/afyx-forge/src/index.js +273 -0
  54. package/afyx-forge/src/planning.js +107 -0
  55. package/afyx-forge/src/policy.js +109 -0
  56. package/afyx-forge/src/workflow-refiner.js +151 -0
  57. package/afyx-graph/afyx-graph.json +20 -0
  58. package/afyx-graph/engine/LICENSE +21 -0
  59. package/afyx-graph/engine/README.md +104 -0
  60. package/afyx-graph/engine/release/RELEASE-MANIFEST.json +21 -0
  61. package/afyx-graph/engine/release/SHA256SUMS +2 -0
  62. package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
  63. package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
  64. package/afyx-graph/engine/scripts/distribution-contract.mjs +212 -0
  65. package/afyx-graph/engine/scripts/distribution-product.json +33 -0
  66. package/bin/afyx-engineering-kit.mjs +61 -0
  67. package/install.ps1 +1053 -0
  68. package/install.sh +617 -0
  69. package/package.json +66 -4
  70. package/scripts/afyx-capability-orchestrator.mjs +752 -0
  71. package/scripts/afyx-claude-integration.mjs +547 -0
  72. package/scripts/afyx-context-artifact.mjs +105 -0
  73. package/scripts/afyx-credential-broker.mjs +75 -0
  74. package/scripts/afyx-doctor.ps1 +152 -0
  75. package/scripts/afyx-doctor.sh +146 -0
  76. package/scripts/afyx-forge-artifact.mjs +183 -0
  77. package/scripts/afyx-global-routing-policy.md +12 -0
  78. package/scripts/afyx-global-routing.mjs +168 -0
  79. package/scripts/afyx-graph-artifact.mjs +178 -0
  80. package/scripts/afyx-host-adapters.mjs +543 -0
  81. package/scripts/afyx-host-bridge-lifecycle.mjs +174 -0
  82. package/scripts/afyx-host-bridge.mjs +288 -0
  83. package/scripts/afyx-integration-contracts.mjs +825 -0
  84. package/scripts/afyx-mcp-integration.mjs +528 -0
  85. package/scripts/afyx-modular-integration.mjs +361 -0
  86. package/scripts/afyx-modular-runtime.mjs +451 -0
  87. package/scripts/afyx-native-skill-host.mjs +124 -0
  88. package/scripts/afyx-npm-installer.mjs +486 -0
  89. package/scripts/afyx-project.ps1 +205 -0
  90. package/scripts/afyx-project.sh +207 -0
  91. package/scripts/afyx-provider-backup.mjs +1206 -0
  92. package/scripts/afyx-provider-integration.mjs +724 -0
  93. package/scripts/afyx-provider-inventory.mjs +147 -0
  94. package/scripts/afyx-security-auditor.mjs +224 -0
  95. package/scripts/afyx-skill-engineering.mjs +354 -0
  96. package/scripts/afyx-tool-family-routing.mjs +64 -0
  97. package/scripts/afyx-universal-runtime.mjs +530 -0
  98. package/scripts/alpha_acceptance_preflight.py +240 -0
  99. package/scripts/benchmark-graph-memory.mjs +96 -0
  100. package/scripts/benchmark_capability_orchestrator.mjs +64 -0
  101. package/scripts/build-windows-installer.ps1 +259 -0
  102. package/scripts/build_forge_synthetic_image.py +328 -0
  103. package/scripts/check-reference-staleness.py +71 -0
  104. package/scripts/components.json +254 -0
  105. package/scripts/contracts/afyx-capability-request-v1.schema.json +189 -0
  106. package/scripts/contracts/afyx-capability-result-v1.schema.json +32 -0
  107. package/scripts/dogfood_engineering_comparison.mjs +303 -0
  108. package/scripts/engineering-assurance.json +28 -0
  109. package/scripts/install-afyx-context.ps1 +142 -0
  110. package/scripts/install-afyx-context.sh +126 -0
  111. package/scripts/install-afyx-forge.ps1 +265 -0
  112. package/scripts/install-afyx-forge.sh +273 -0
  113. package/scripts/install-afyx-graph.ps1 +571 -0
  114. package/scripts/install-afyx-graph.sh +438 -0
  115. package/scripts/install-codex-usage-tracker.ps1 +172 -0
  116. package/scripts/lib/AfyxComponents.psm1 +399 -0
  117. package/scripts/lib/AfyxSkillLifecycle.psm1 +289 -0
  118. package/scripts/lib/AfyxTerminal.psm1 +838 -0
  119. package/scripts/lib/afyx-components.sh +256 -0
  120. package/scripts/lib/afyx-skill-lifecycle.sh +271 -0
  121. package/scripts/link-global-dev.ps1 +193 -0
  122. package/scripts/link-global-dev.sh +130 -0
  123. package/scripts/phase8-paired-evidence.mjs +195 -0
  124. package/scripts/phase8-representative-workload.mjs +771 -0
  125. package/scripts/phase8-session-recorder.mjs +157 -0
  126. package/scripts/phase8_event_ledger.py +248 -0
  127. package/scripts/phase8_evidence_discovery.py +189 -0
  128. package/scripts/prepare-g6-package.mjs +349 -0
  129. package/scripts/resolve-git-release-artifacts.mjs +321 -0
  130. package/scripts/stage-npm-release.mjs +94 -0
  131. package/scripts/validate-afyx-graph.py +203 -0
  132. package/scripts/validate-components.py +194 -0
  133. package/scripts/validate-engineering-assurance.py +281 -0
  134. package/scripts/verify-graph-archive.mjs +64 -0
  135. package/skills/afyx-context/SKILL.md +26 -0
  136. package/skills/afyx-engineering-expert/README.md +42 -0
  137. package/skills/afyx-engineering-expert/SKILL.md +70 -0
  138. package/skills/afyx-engineering-expert/assets/result-template.md +15 -0
  139. package/skills/afyx-engineering-expert/references/ai-ml-engineer.md +17 -0
  140. package/skills/afyx-engineering-expert/references/business-analyst.md +17 -0
  141. package/skills/afyx-engineering-expert/references/clean-code-engineer.md +26 -0
  142. package/skills/afyx-engineering-expert/references/code-reviewer.md +24 -0
  143. package/skills/afyx-engineering-expert/references/cybersecurity-devsecops.md +17 -0
  144. package/skills/afyx-engineering-expert/references/data-analyst-bi.md +24 -0
  145. package/skills/afyx-engineering-expert/references/data-engineer.md +24 -0
  146. package/skills/afyx-engineering-expert/references/database-administrator.md +17 -0
  147. package/skills/afyx-engineering-expert/references/debugging-specialist.md +24 -0
  148. package/skills/afyx-engineering-expert/references/embedded-iot-engineer.md +24 -0
  149. package/skills/afyx-engineering-expert/references/erp-technical-specialist.md +17 -0
  150. package/skills/afyx-engineering-expert/references/hardware-diagnostics-auditor.md +24 -0
  151. package/skills/afyx-engineering-expert/references/hardware-electronics-engineer.md +24 -0
  152. package/skills/afyx-engineering-expert/references/integration-engineer.md +24 -0
  153. package/skills/afyx-engineering-expert/references/legacy-modernization-engineer.md +24 -0
  154. package/skills/afyx-engineering-expert/references/llmops-prompt-engineer.md +24 -0
  155. package/skills/afyx-engineering-expert/references/network-engineer.md +24 -0
  156. package/skills/afyx-engineering-expert/references/performance-benchmark-engineer.md +24 -0
  157. package/skills/afyx-engineering-expert/references/platform-engineer.md +24 -0
  158. package/skills/afyx-engineering-expert/references/product-manager.md +17 -0
  159. package/skills/afyx-engineering-expert/references/qa-engineer.md +17 -0
  160. package/skills/afyx-engineering-expert/references/site-reliability-engineer.md +17 -0
  161. package/skills/afyx-engineering-expert/references/software-engineer.md +17 -0
  162. package/skills/afyx-engineering-expert/references/solutions-architect.md +17 -0
  163. package/skills/afyx-engineering-expert/references/specialists-index.md +33 -0
  164. package/skills/afyx-engineering-expert/references/subject-matter-expert.md +17 -0
  165. package/skills/afyx-engineering-expert/references/system-analyst.md +17 -0
  166. package/skills/afyx-engineering-expert/references/technical-project-manager.md +24 -0
  167. package/skills/afyx-engineering-expert/references/technical-writer.md +24 -0
  168. package/skills/afyx-engineering-expert/references/ui-ux-designer.md +17 -0
  169. package/skills/afyx-engineering-expert/workflows/ai-data-erp.md +20 -0
  170. package/skills/afyx-engineering-expert/workflows/debugging.md +10 -0
  171. package/skills/afyx-engineering-expert/workflows/discovery-design.md +11 -0
  172. package/skills/afyx-engineering-expert/workflows/implementation.md +12 -0
  173. package/skills/afyx-engineering-expert/workflows/incident-reliability.md +12 -0
  174. package/skills/afyx-engineering-expert/workflows/review-audit.md +13 -0
  175. package/skills/afyx-forge/SKILL.md +43 -0
  176. package/skills/afyx-forge/references/adaptive-policy.md +19 -0
  177. package/skills/efficient-coding/SKILL.md +33 -0
  178. package/skills/efficient-coding/references/investigation.md +27 -0
  179. package/skills/efficient-coding/references/token-efficiency.md +25 -0
  180. package/skills/efficient-coding/references/tool-routing.md +13 -0
  181. package/skills/odoo-engineering/SKILL.md +33 -0
  182. package/skills/odoo-engineering/references/common.md +9 -0
  183. package/skills/odoo-engineering/references/odoo-10.md +32 -0
  184. package/skills/odoo-engineering/references/odoo-11.md +26 -0
  185. package/skills/odoo-engineering/references/odoo-12.md +31 -0
  186. package/skills/odoo-engineering/references/odoo-13.md +27 -0
  187. package/skills/odoo-engineering/references/odoo-14.md +31 -0
  188. package/skills/odoo-engineering/references/odoo-15.md +34 -0
  189. package/skills/odoo-engineering/references/odoo-16.md +37 -0
  190. package/skills/odoo-engineering/references/odoo-17.md +37 -0
  191. package/skills/odoo-engineering/references/odoo-18.md +48 -0
  192. package/skills/odoo-engineering/references/odoo-19.md +43 -0
  193. package/skills/odoo-engineering/references/odoo-20.md +39 -0
  194. package/skills/odoo-engineering/references/reference-schema.md +16 -0
  195. package/skills/odoo-engineering/references/version-detection.md +13 -0
  196. package/tools/codex-usage/CodexUsage.psm1 +496 -0
  197. package/tools/codex-usage/codex-usage-doctor.ps1 +150 -0
  198. package/tools/codex-usage/codex-usage-pricing.json +25 -0
  199. package/tools/codex-usage/codex-usage-stop.ps1 +167 -0
  200. package/tools/codex-usage/codex-usage-watch.ps1 +250 -0
  201. package/tools/codex-usage/vscode-user-task.json +31 -0
  202. package/tools/windows-setup/SetupBootstrapper.cs +258 -0
  203. package/uninstall.ps1 +189 -0
  204. package/uninstall.sh +167 -0
  205. package/update.ps1 +95 -0
  206. package/update.sh +67 -0
  207. package/verify.ps1 +411 -0
  208. package/verify.sh +265 -0
@@ -0,0 +1,147 @@
1
+ #!/usr/bin/env node
2
+ // Read-only inventory for installer presentation. Provider configuration remains
3
+ // owned by afyx-provider-integration.mjs.
4
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { delimiter, join, resolve } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { spawnSync } from 'node:child_process';
9
+
10
+ const catalog = [
11
+ { id: 'antigravity', name: 'Antigravity', supported: true, commands: ['agy', 'antigravity'] },
12
+ { id: 'claude', name: 'Claude Code', supported: true, commands: ['claude'], extension: 'anthropic.claude-code' },
13
+ { id: 'codex', name: 'Codex', supported: true, commands: ['codex'], extension: 'openai.chatgpt' },
14
+ { id: 'cursor', name: 'Cursor', supported: false, future: true, commands: ['cursor'] },
15
+ { id: 'opencode', name: 'OpenCode', supported: false, future: true, commands: ['opencode'] },
16
+ ];
17
+
18
+ function commandPath(name, env, platform) {
19
+ const suffixes = platform === 'win32' ? ['.exe', '.cmd', '.bat'] : [''];
20
+ for (const directory of (env.PATH || '').split(delimiter).filter(Boolean)) {
21
+ for (const suffix of suffixes) {
22
+ const candidate = join(directory, name + suffix);
23
+ try {
24
+ if (!statSync(candidate).isFile()) continue;
25
+ if (platform !== 'win32' && !(statSync(candidate).mode & 0o111)) continue;
26
+ if (platform !== 'win32' && (candidate.toLowerCase().endsWith('.exe') || /^\/mnt\/[a-z]\//i.test(candidate))) continue;
27
+ return resolve(candidate);
28
+ } catch { /* absent PATH entry */ }
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+
34
+ function extensionProducts(home, platform) {
35
+ const roots = ['.vscode', '.vscode-insiders'];
36
+ if (platform !== 'win32') roots.push('.vscode-server');
37
+ const found = [];
38
+ for (const root of roots) {
39
+ const directory = join(home, root, 'extensions');
40
+ let names;
41
+ try { names = readdirSync(directory); } catch { continue; }
42
+ for (const name of names) {
43
+ if (!/^(openai\.chatgpt|anthropic\.claude-code)-/i.test(name)) continue;
44
+ const location = join(directory, name);
45
+ try {
46
+ const manifest = JSON.parse(readFileSync(join(location, 'package.json'), 'utf8'));
47
+ const id = `${manifest.publisher}.${manifest.name}`.toLowerCase();
48
+ if (!['openai.chatgpt', 'anthropic.claude-code'].includes(id)) continue;
49
+ found.push({ id, path: location, version: String(manifest.version || '') });
50
+ } catch { /* incomplete or unrecognized extension */ }
51
+ }
52
+ }
53
+ return found;
54
+ }
55
+
56
+ function knownDesktopPaths(env, platform) {
57
+ if (platform !== 'win32') return { antigravity: [], cursor: [] };
58
+ const appPath = (executable) => {
59
+ const reg = join(env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe');
60
+ for (const hive of ['HKCU', 'HKLM']) {
61
+ const key = `${hive}\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${executable}`;
62
+ const result = spawnSync(reg, ['query', key, '/ve'], { timeout: 1200,
63
+ maxBuffer: 8192, encoding: 'utf8', windowsHide: true });
64
+ if (result.status !== 0) continue;
65
+ const path = result.stdout.match(/REG_(?:EXPAND_)?SZ\s+([^\r\n]+)/)?.[1]?.trim();
66
+ if (path) return path;
67
+ }
68
+ return null;
69
+ };
70
+ return {
71
+ antigravity: [
72
+ env.LOCALAPPDATA && join(env.LOCALAPPDATA, 'Programs', 'Antigravity', 'Antigravity.exe'),
73
+ env.LOCALAPPDATA && join(env.LOCALAPPDATA, 'Programs', 'Google Antigravity', 'Antigravity.exe'),
74
+ env.ProgramFiles && join(env.ProgramFiles, 'Google', 'Antigravity', 'Antigravity.exe'),
75
+ appPath('Antigravity.exe'),
76
+ ].filter(Boolean),
77
+ cursor: [env.LOCALAPPDATA && join(env.LOCALAPPDATA, 'Programs', 'cursor', 'Cursor.exe'),
78
+ appPath('Cursor.exe')].filter(Boolean),
79
+ };
80
+ }
81
+
82
+ export function discoverProviderInventory({ platform = process.platform, env = process.env,
83
+ home = env.HOME || env.USERPROFILE || homedir(), probe = null } = {}) {
84
+ const commands = probe?.commands || null;
85
+ const extensions = probe?.extensions || extensionProducts(home, platform);
86
+ const desktops = probe?.desktops || knownDesktopPaths(env, platform);
87
+ const isFile = probe ? (path) => (probe.files || []).includes(path) : (path) => {
88
+ try { return statSync(path).isFile(); } catch { return false; }
89
+ };
90
+ const inventory = [];
91
+ for (const entry of catalog) {
92
+ const products = [];
93
+ for (const command of entry.commands) {
94
+ const location = commands ? commands[command] : commandPath(command, env, platform);
95
+ if (!location) continue;
96
+ if (platform !== 'win32' && (location.toLowerCase().endsWith('.exe') || /^\/mnt\/[a-z]\//i.test(location))) continue;
97
+ products.push({ type: 'CLI', name: `${entry.name} CLI`, path: location,
98
+ version: null, mcp: entry.supported, configuration: 'NOT_VERIFIED' });
99
+ break; // aliases identify one product
100
+ }
101
+ for (const location of desktops[entry.id] || []) {
102
+ if (isFile(location) && !products.some((product) => product.path.toLowerCase() === location.toLowerCase())) {
103
+ products.push({ type: 'IDE/Desktop', name: entry.name, path: location,
104
+ version: null, mcp: false, configuration: 'NOT_VERIFIED' });
105
+ }
106
+ }
107
+ for (const extension of extensions) {
108
+ if (extension.id?.toLowerCase() !== entry.extension) continue;
109
+ if (products.some((product) => product.path.toLowerCase() === extension.path.toLowerCase())) continue;
110
+ products.push({ type: 'VS Code Extension', name: entry.name, path: extension.path,
111
+ version: extension.version || null, mcp: entry.id === 'claude', configuration: 'NOT_VERIFIED' });
112
+ }
113
+ if (!entry.supported && !products.length) continue;
114
+ inventory.push({ id: entry.id, name: entry.name, supported: entry.supported,
115
+ status: entry.supported ? 'SUPPORTED' : entry.future ? 'COMING SOON' : 'UNSUPPORTED', installed: products.length > 0,
116
+ products });
117
+ }
118
+ return inventory.sort((a, b) => a.name.localeCompare(b.name, 'en', { sensitivity: 'base' }));
119
+ }
120
+
121
+ export function formatProviderInventory(inventory) {
122
+ const lines = [];
123
+ for (const provider of inventory.filter((item) => item.supported)) {
124
+ lines.push(provider.name);
125
+ if (!provider.products.length) lines.push(' - Unavailable');
126
+ for (const product of provider.products) lines.push(` + ${product.type} · Installed${product.version ? ` · ${product.version}` : ''}`);
127
+ }
128
+ const other = inventory.filter((item) => !item.supported && item.installed);
129
+ if (other.length) {
130
+ lines.push('OTHER DETECTED');
131
+ for (const provider of other) lines.push(` - ${provider.name} · ${provider.status}`);
132
+ }
133
+ return lines;
134
+ }
135
+
136
+ export function selectableProviderIds(inventory) {
137
+ return inventory.filter((provider) => provider.supported && provider.products.some((product) =>
138
+ product.type === 'CLI' || (provider.id === 'claude' && product.type === 'VS Code Extension')))
139
+ .map((provider) => provider.id);
140
+ }
141
+
142
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
143
+ const inventory = discoverProviderInventory();
144
+ if (process.argv.includes('--lines')) process.stdout.write(formatProviderInventory(inventory).join('\n') + '\n');
145
+ else if (process.argv.includes('--selected')) process.stdout.write(selectableProviderIds(inventory).join(',') + '\n');
146
+ else process.stdout.write(JSON.stringify(inventory) + '\n');
147
+ }
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * AFYX Engineering Kit - Native Read-Only Security Auditor
4
+ *
5
+ * Deterministic, source-grounded static security analysis for codebases.
6
+ * Audits source code for high-risk execution flaws:
7
+ * - Unsafe Subprocess Execution (arbitrary shell injection)
8
+ * - Hardcoded Secrets & Cryptographic Keys
9
+ * - Path Traversal & Unvalidated File Operations
10
+ * - Insecure Deserialization & Dynamic Code Evaluation
11
+ *
12
+ * Read-only by design; produces verifiable line-level evidence without mutation.
13
+ */
14
+
15
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
16
+ import { extname, join, relative, resolve } from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ export const SECURITY_AUDITOR_CONTRACT = 'afyx-security-audit-v1';
20
+
21
+ export const RISK_LEVELS = Object.freeze({
22
+ CRITICAL: 'CRITICAL',
23
+ HIGH: 'HIGH',
24
+ MEDIUM: 'MEDIUM',
25
+ LOW: 'LOW',
26
+ });
27
+
28
+ /**
29
+ * Deterministic detection signatures.
30
+ */
31
+ export const AUDIT_RULES = Object.freeze([
32
+ {
33
+ id: 'SEC-PROC-01',
34
+ category: 'UNSAFE_PROCESS_EXECUTION',
35
+ severity: RISK_LEVELS.HIGH,
36
+ title: 'Unsafe Subprocess Shell Invocation',
37
+ description: 'Direct invocation of system shell with potential command injection risks.',
38
+ patterns: [
39
+ /\bchild_process\s*\.\s*(?:exec|execSync)\s*\(/i,
40
+ /\b(?:cp|childProcess)\s*\.\s*(?:exec|execSync)\s*\(/i,
41
+ /\bexecSync\s*\([^,)]*shell\s*:\s*true/i,
42
+ /\bsubprocess\s*\.\s*(?:Popen|call|run|check_call|check_output)\s*\([^)]*shell\s*=\s*True/i,
43
+ /\bos\s*\.\s*system\s*\(/i,
44
+ ],
45
+ remediation: 'Use argument-array based subprocess invocation without shell: true (e.g. execFile or execFileSync).',
46
+ },
47
+ {
48
+ id: 'SEC-SECRET-01',
49
+ category: 'HARDCODED_SECRET',
50
+ severity: RISK_LEVELS.CRITICAL,
51
+ title: 'Hardcoded Private Key or Cryptographic Secret',
52
+ description: 'Embedded private cryptographic key or token detected in active source file.',
53
+ patterns: [
54
+ /-----BEGIN\s+(?:RSA|OPENSSH|EC|PGP|PRIVATE)\s+KEY-----/,
55
+ /\beyJ[a-zA-Z0-9_-]{10,}\.eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\b/,
56
+ /(?:api[_-]?key|secret[_-]?token|auth[_-]?token)\s*[:=]\s*['"][a-zA-Z0-9_\-]{24,}['"]/i,
57
+ ],
58
+ remediation: 'Extract credentials to environment variables or local secure vault; never commit secrets in code.',
59
+ },
60
+ {
61
+ id: 'SEC-EVAL-01',
62
+ category: 'INSECURE_EVAL_DESERIALIZE',
63
+ severity: RISK_LEVELS.CRITICAL,
64
+ title: 'Dynamic Code Evaluation or Insecure Deserialization',
65
+ description: 'Execution of dynamic strings as code or unsafe deserialization of untrusted payloads.',
66
+ patterns: [
67
+ /\beval\s*\([^)]{3,}\)/,
68
+ /\bnew\s+Function\s*\([^)]*\)/,
69
+ /\bpickle\s*\.\s*loads?\s*\(/,
70
+ /\byaml\s*\.\s*load\s*\([^,)]*Loader\s*=\s*(?:yaml\.)?(?:UnsafeLoader|Loader)\s*\)/,
71
+ ],
72
+ remediation: 'Use safe parsing (JSON.parse, ast.literal_eval, yaml.safe_load) rather than dynamic code execution.',
73
+ },
74
+ {
75
+ id: 'SEC-PATH-01',
76
+ category: 'PATH_TRAVERSAL',
77
+ severity: RISK_LEVELS.MEDIUM,
78
+ title: 'Potential Path Traversal Pattern',
79
+ description: 'Unvalidated relative path concatenation containing upward traversal indicators.',
80
+ patterns: [
81
+ /(?:readFile|createReadStream|open|unlink)\s*\([^)]*\.\.\//,
82
+ /(?:readFileSync|writeFileSync)\s*\([^)]*\.\.\//,
83
+ ],
84
+ remediation: 'Normalize paths using path.resolve and validate containment within authorized target root.',
85
+ },
86
+ ]);
87
+
88
+ const SCANNABLE_EXTENSIONS = new Set([
89
+ '.js', '.mjs', '.cjs', '.ts', '.tsx', '.py', '.sh', '.ps1', '.json', '.yaml', '.yml'
90
+ ]);
91
+
92
+ const IGNORED_DIRECTORIES = new Set([
93
+ 'node_modules', '.git', '.afyx-graph', 'dist', 'build', '.coverage', '__pycache__'
94
+ ]);
95
+
96
+ /**
97
+ * Scans a single text content for security violations.
98
+ */
99
+ export function auditContent(content, filePath = 'unknown') {
100
+ const findings = [];
101
+ const lines = content.split(/\r?\n/);
102
+
103
+ for (let lineIdx = 0; lineIdx < lines.length; lineIdx++) {
104
+ const line = lines[lineIdx];
105
+ for (const rule of AUDIT_RULES) {
106
+ for (const pattern of rule.patterns) {
107
+ if (pattern.test(line)) {
108
+ // Avoid triggering on comments explaining rules or test mocks
109
+ const trimmed = line.trim();
110
+ if (trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('*')) {
111
+ continue;
112
+ }
113
+ findings.push({
114
+ ruleId: rule.id,
115
+ category: rule.category,
116
+ severity: rule.severity,
117
+ title: rule.title,
118
+ filePath,
119
+ lineNumber: lineIdx + 1,
120
+ snippet: trimmed.slice(0, 120),
121
+ remediation: rule.remediation,
122
+ });
123
+ break; // Avoid duplicate reports for same rule on same line
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ return findings;
130
+ }
131
+
132
+ /**
133
+ * Recursively audits a directory tree.
134
+ */
135
+ export function auditDirectory(rootDir, { failOnSeverity = null } = {}) {
136
+ const resolvedRoot = resolve(rootDir);
137
+ const allFindings = [];
138
+ let scannedFilesCount = 0;
139
+
140
+ function walk(dir) {
141
+ let entries;
142
+ try {
143
+ entries = readdirSync(dir);
144
+ } catch {
145
+ return;
146
+ }
147
+
148
+ for (const entry of entries) {
149
+ if (IGNORED_DIRECTORIES.has(entry)) continue;
150
+ const fullPath = join(dir, entry);
151
+ let st;
152
+ try {
153
+ st = statSync(fullPath);
154
+ } catch {
155
+ continue;
156
+ }
157
+
158
+ if (st.isDirectory()) {
159
+ walk(fullPath);
160
+ } else if (st.isFile()) {
161
+ const ext = extname(entry).toLowerCase();
162
+ if (SCANNABLE_EXTENSIONS.has(ext)) {
163
+ scannedFilesCount++;
164
+ try {
165
+ const content = readFileSync(fullPath, 'utf8');
166
+ const relPath = relative(resolvedRoot, fullPath).replace(/\\/g, '/');
167
+ const fileFindings = auditContent(content, relPath);
168
+ allFindings.push(...fileFindings);
169
+ } catch {
170
+ // Unreadable file skipped cleanly
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+
177
+ walk(resolvedRoot);
178
+
179
+ const summary = {
180
+ critical: allFindings.filter((f) => f.severity === RISK_LEVELS.CRITICAL).length,
181
+ high: allFindings.filter((f) => f.severity === RISK_LEVELS.HIGH).length,
182
+ medium: allFindings.filter((f) => f.severity === RISK_LEVELS.MEDIUM).length,
183
+ low: allFindings.filter((f) => f.severity === RISK_LEVELS.LOW).length,
184
+ };
185
+
186
+ const hasFailingFindings = failOnSeverity === 'HIGH'
187
+ ? summary.critical > 0 || summary.high > 0
188
+ : summary.critical > 0;
189
+
190
+ return {
191
+ contract: SECURITY_AUDITOR_CONTRACT,
192
+ targetRoot: resolvedRoot,
193
+ scannedFilesCount,
194
+ status: allFindings.length === 0 ? 'PASS' : hasFailingFindings ? 'FAIL' : 'WARNING',
195
+ summary,
196
+ findings: allFindings,
197
+ };
198
+ }
199
+
200
+ // CLI entry point
201
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
202
+ const target = process.argv[2] || process.cwd();
203
+ const isJson = process.argv.includes('--json');
204
+ const report = auditDirectory(target);
205
+
206
+ if (isJson) {
207
+ console.log(JSON.stringify(report, null, 2));
208
+ } else {
209
+ console.log(`[security-audit] Target: ${report.targetRoot}`);
210
+ console.log(`[security-audit] Scanned Files: ${report.scannedFilesCount}`);
211
+ console.log(`[security-audit] Verdict: ${report.status} (Critical: ${report.summary.critical}, High: ${report.summary.high}, Medium: ${report.summary.medium})`);
212
+ if (report.findings.length > 0) {
213
+ console.log('\n--- Findings ---');
214
+ for (const f of report.findings) {
215
+ console.log(`[${f.severity}] ${f.ruleId}: ${f.title}`);
216
+ console.log(` File: ${f.filePath}:${f.lineNumber}`);
217
+ console.log(` Code: ${f.snippet}`);
218
+ console.log(` Fix: ${f.remediation}\n`);
219
+ }
220
+ }
221
+ }
222
+
223
+ if (report.status === 'FAIL') process.exit(1);
224
+ }