@eloxiv/cli 0.0.0-stage → 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.
Files changed (294) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/AgentSkills.d.ts +51 -0
  4. package/dist/AgentSkills.d.ts.map +1 -0
  5. package/dist/AgentSkills.js +264 -0
  6. package/dist/AgentSkills.js.map +1 -0
  7. package/dist/AgentWeb.d.ts +83 -0
  8. package/dist/AgentWeb.d.ts.map +1 -0
  9. package/dist/AgentWeb.js +436 -0
  10. package/dist/AgentWeb.js.map +1 -0
  11. package/dist/App.d.ts +213 -0
  12. package/dist/App.d.ts.map +1 -0
  13. package/dist/App.js +357 -0
  14. package/dist/App.js.map +1 -0
  15. package/dist/Blueprint.d.ts +47 -0
  16. package/dist/Blueprint.d.ts.map +1 -0
  17. package/dist/Blueprint.js +241 -0
  18. package/dist/Blueprint.js.map +1 -0
  19. package/dist/Brand.d.ts +42 -0
  20. package/dist/Brand.d.ts.map +1 -0
  21. package/dist/Brand.js +370 -0
  22. package/dist/Brand.js.map +1 -0
  23. package/dist/Changelog.d.ts +22 -0
  24. package/dist/Changelog.d.ts.map +1 -0
  25. package/dist/Changelog.js +117 -0
  26. package/dist/Changelog.js.map +1 -0
  27. package/dist/Cli.d.ts +17 -0
  28. package/dist/Cli.d.ts.map +1 -0
  29. package/dist/Cli.js +810 -0
  30. package/dist/Cli.js.map +1 -0
  31. package/dist/DbAdmin.d.ts +18 -0
  32. package/dist/DbAdmin.d.ts.map +1 -0
  33. package/dist/DbAdmin.js +91 -0
  34. package/dist/DbAdmin.js.map +1 -0
  35. package/dist/Dependencies.d.ts +53 -0
  36. package/dist/Dependencies.d.ts.map +1 -0
  37. package/dist/Dependencies.js +132 -0
  38. package/dist/Dependencies.js.map +1 -0
  39. package/dist/Deploy.d.ts +39 -0
  40. package/dist/Deploy.d.ts.map +1 -0
  41. package/dist/Deploy.js +458 -0
  42. package/dist/Deploy.js.map +1 -0
  43. package/dist/Docs.d.ts +71 -0
  44. package/dist/Docs.d.ts.map +1 -0
  45. package/dist/Docs.js +240 -0
  46. package/dist/Docs.js.map +1 -0
  47. package/dist/Doctor.d.ts +56 -0
  48. package/dist/Doctor.d.ts.map +1 -0
  49. package/dist/Doctor.js +368 -0
  50. package/dist/Doctor.js.map +1 -0
  51. package/dist/Dossier.d.ts +23 -0
  52. package/dist/Dossier.d.ts.map +1 -0
  53. package/dist/Dossier.js +92 -0
  54. package/dist/Dossier.js.map +1 -0
  55. package/dist/Emit.d.ts +26 -0
  56. package/dist/Emit.d.ts.map +1 -0
  57. package/dist/Emit.js +51 -0
  58. package/dist/Emit.js.map +1 -0
  59. package/dist/Errors.d.ts +26 -0
  60. package/dist/Errors.d.ts.map +1 -0
  61. package/dist/Errors.js +17 -0
  62. package/dist/Errors.js.map +1 -0
  63. package/dist/Evals.d.ts +52 -0
  64. package/dist/Evals.d.ts.map +1 -0
  65. package/dist/Evals.js +126 -0
  66. package/dist/Evals.js.map +1 -0
  67. package/dist/Files.d.ts +47 -0
  68. package/dist/Files.d.ts.map +1 -0
  69. package/dist/Files.js +145 -0
  70. package/dist/Files.js.map +1 -0
  71. package/dist/Generate.d.ts +80 -0
  72. package/dist/Generate.d.ts.map +1 -0
  73. package/dist/Generate.js +310 -0
  74. package/dist/Generate.js.map +1 -0
  75. package/dist/Guards.d.ts +45 -0
  76. package/dist/Guards.d.ts.map +1 -0
  77. package/dist/Guards.js +530 -0
  78. package/dist/Guards.js.map +1 -0
  79. package/dist/Inspect.d.ts +125 -0
  80. package/dist/Inspect.d.ts.map +1 -0
  81. package/dist/Inspect.js +270 -0
  82. package/dist/Inspect.js.map +1 -0
  83. package/dist/Keychain.d.ts +57 -0
  84. package/dist/Keychain.d.ts.map +1 -0
  85. package/dist/Keychain.js +73 -0
  86. package/dist/Keychain.js.map +1 -0
  87. package/dist/Lock.d.ts +13 -0
  88. package/dist/Lock.d.ts.map +1 -0
  89. package/dist/Lock.js +145 -0
  90. package/dist/Lock.js.map +1 -0
  91. package/dist/Mcp.d.ts +91 -0
  92. package/dist/Mcp.d.ts.map +1 -0
  93. package/dist/Mcp.js +128 -0
  94. package/dist/Mcp.js.map +1 -0
  95. package/dist/Merge.d.ts +18 -0
  96. package/dist/Merge.d.ts.map +1 -0
  97. package/dist/Merge.js +43 -0
  98. package/dist/Merge.js.map +1 -0
  99. package/dist/Migrate.d.ts +78 -0
  100. package/dist/Migrate.d.ts.map +1 -0
  101. package/dist/Migrate.js +288 -0
  102. package/dist/Migrate.js.map +1 -0
  103. package/dist/Plugins.d.ts +36 -0
  104. package/dist/Plugins.d.ts.map +1 -0
  105. package/dist/Plugins.js +304 -0
  106. package/dist/Plugins.js.map +1 -0
  107. package/dist/Postgres.d.ts +73 -0
  108. package/dist/Postgres.d.ts.map +1 -0
  109. package/dist/Postgres.js +294 -0
  110. package/dist/Postgres.js.map +1 -0
  111. package/dist/Publish.d.ts +23 -0
  112. package/dist/Publish.d.ts.map +1 -0
  113. package/dist/Publish.js +59 -0
  114. package/dist/Publish.js.map +1 -0
  115. package/dist/Registry.d.ts +539 -0
  116. package/dist/Registry.d.ts.map +1 -0
  117. package/dist/Registry.js +340 -0
  118. package/dist/Registry.js.map +1 -0
  119. package/dist/Remote.d.ts +90 -0
  120. package/dist/Remote.d.ts.map +1 -0
  121. package/dist/Remote.js +1006 -0
  122. package/dist/Remote.js.map +1 -0
  123. package/dist/Run.d.ts +120 -0
  124. package/dist/Run.d.ts.map +1 -0
  125. package/dist/Run.js +477 -0
  126. package/dist/Run.js.map +1 -0
  127. package/dist/SyncGen.d.ts +118 -0
  128. package/dist/SyncGen.d.ts.map +1 -0
  129. package/dist/SyncGen.js +392 -0
  130. package/dist/SyncGen.js.map +1 -0
  131. package/dist/Update.d.ts +301 -0
  132. package/dist/Update.d.ts.map +1 -0
  133. package/dist/Update.js +627 -0
  134. package/dist/Update.js.map +1 -0
  135. package/dist/bin.d.ts +3 -0
  136. package/dist/bin.d.ts.map +1 -0
  137. package/dist/bin.js +42 -0
  138. package/dist/bin.js.map +1 -0
  139. package/dist/docs/backlog.md +56 -0
  140. package/dist/docs/ci.md +277 -0
  141. package/dist/docs/cli.md +696 -0
  142. package/dist/docs/connectors/google.md +115 -0
  143. package/dist/docs/connectors/http-openapi.md +7 -0
  144. package/dist/docs/connectors/mcp.md +8 -0
  145. package/dist/docs/connectors/microsoft-graph.md +75 -0
  146. package/dist/docs/connectors/openai.md +25 -0
  147. package/dist/docs/connectors/slack.md +162 -0
  148. package/dist/docs/connectors/workos.md +39 -0
  149. package/dist/docs/contracts/README.md +173 -0
  150. package/dist/docs/contracts/action-consent.md +92 -0
  151. package/dist/docs/contracts/action-registry.md +85 -0
  152. package/dist/docs/contracts/actor.md +100 -0
  153. package/dist/docs/contracts/agent-resources.md +90 -0
  154. package/dist/docs/contracts/agent-runtime.md +257 -0
  155. package/dist/docs/contracts/approvals.md +126 -0
  156. package/dist/docs/contracts/audit.md +75 -0
  157. package/dist/docs/contracts/auth-provider.md +74 -0
  158. package/dist/docs/contracts/calendar-provider.md +46 -0
  159. package/dist/docs/contracts/client-sdk.md +245 -0
  160. package/dist/docs/contracts/collab-document.md +151 -0
  161. package/dist/docs/contracts/command.md +44 -0
  162. package/dist/docs/contracts/connections.md +235 -0
  163. package/dist/docs/contracts/context-accounting.md +50 -0
  164. package/dist/docs/contracts/daemon.md +243 -0
  165. package/dist/docs/contracts/db-tx.md +53 -0
  166. package/dist/docs/contracts/delegation.md +68 -0
  167. package/dist/docs/contracts/device-control.md +103 -0
  168. package/dist/docs/contracts/directory-provider.md +36 -0
  169. package/dist/docs/contracts/directory.md +161 -0
  170. package/dist/docs/contracts/document-source.md +33 -0
  171. package/dist/docs/contracts/files.md +115 -0
  172. package/dist/docs/contracts/flags.md +83 -0
  173. package/dist/docs/contracts/host.md +68 -0
  174. package/dist/docs/contracts/http-api.md +43 -0
  175. package/dist/docs/contracts/ingestion.md +130 -0
  176. package/dist/docs/contracts/ingress.md +141 -0
  177. package/dist/docs/contracts/invocation.md +260 -0
  178. package/dist/docs/contracts/local-client.md +108 -0
  179. package/dist/docs/contracts/locale.md +56 -0
  180. package/dist/docs/contracts/machine-identity.md +117 -0
  181. package/dist/docs/contracts/mail-provider.md +49 -0
  182. package/dist/docs/contracts/memory.md +53 -0
  183. package/dist/docs/contracts/messaging.md +40 -0
  184. package/dist/docs/contracts/metering.md +139 -0
  185. package/dist/docs/contracts/model-provider.md +84 -0
  186. package/dist/docs/contracts/module-manifest.md +213 -0
  187. package/dist/docs/contracts/notification-channel.md +90 -0
  188. package/dist/docs/contracts/notifications.md +123 -0
  189. package/dist/docs/contracts/outbox.md +80 -0
  190. package/dist/docs/contracts/privacy.md +110 -0
  191. package/dist/docs/contracts/progress.md +52 -0
  192. package/dist/docs/contracts/query-surface.md +108 -0
  193. package/dist/docs/contracts/readiness.md +63 -0
  194. package/dist/docs/contracts/release.md +142 -0
  195. package/dist/docs/contracts/result-rendering.md +61 -0
  196. package/dist/docs/contracts/sandbox.md +186 -0
  197. package/dist/docs/contracts/scheduler.md +148 -0
  198. package/dist/docs/contracts/screen-context.md +81 -0
  199. package/dist/docs/contracts/search.md +120 -0
  200. package/dist/docs/contracts/secrets.md +74 -0
  201. package/dist/docs/contracts/settings.md +109 -0
  202. package/dist/docs/contracts/sharing.md +77 -0
  203. package/dist/docs/contracts/slot.md +48 -0
  204. package/dist/docs/contracts/space.md +67 -0
  205. package/dist/docs/contracts/storage-adapter.md +45 -0
  206. package/dist/docs/contracts/storage-backend.md +56 -0
  207. package/dist/docs/contracts/sync.md +213 -0
  208. package/dist/docs/contracts/telemetry.md +80 -0
  209. package/dist/docs/contracts/theme-tokens.md +50 -0
  210. package/dist/docs/contracts/tool-source.md +58 -0
  211. package/dist/docs/contracts/versioning.md +99 -0
  212. package/dist/docs/contracts/view.md +65 -0
  213. package/dist/docs/contracts/work-items.md +99 -0
  214. package/dist/docs/contracts/workflow.md +82 -0
  215. package/dist/docs/decisions.md +163 -0
  216. package/dist/docs/example-app.md +192 -0
  217. package/dist/docs/getting-started.md +927 -0
  218. package/dist/docs/goal.md +54 -0
  219. package/dist/docs/parity.md +29 -0
  220. package/dist/docs/performance.md +129 -0
  221. package/dist/docs/registry/README.md +74 -0
  222. package/dist/docs/registry/app.md +38 -0
  223. package/dist/docs/registry/approvals-ui-foldkit.md +28 -0
  224. package/dist/docs/registry/calendar-ui-foldkit.md +27 -0
  225. package/dist/docs/registry/calendar.md +35 -0
  226. package/dist/docs/registry/chat-ui-foldkit.md +30 -0
  227. package/dist/docs/registry/desktop-rune.md +49 -0
  228. package/dist/docs/registry/desktop.md +32 -0
  229. package/dist/docs/registry/eloxiv-action.md +25 -0
  230. package/dist/docs/registry/eloxiv-connector.md +25 -0
  231. package/dist/docs/registry/eloxiv-module.md +25 -0
  232. package/dist/docs/registry/eloxiv-policy.md +25 -0
  233. package/dist/docs/registry/eloxiv-view.md +25 -0
  234. package/dist/docs/registry/hello-ui-foldkit.md +29 -0
  235. package/dist/docs/registry/hello.md +39 -0
  236. package/dist/docs/registry/home-ui-foldkit.md +27 -0
  237. package/dist/docs/registry/home.md +29 -0
  238. package/dist/docs/registry/inbox-ui-foldkit.md +27 -0
  239. package/dist/docs/registry/mail-ui-foldkit.md +27 -0
  240. package/dist/docs/registry/mail.md +34 -0
  241. package/dist/docs/registry/meeting-prep.md +26 -0
  242. package/dist/docs/registry/members-ui-foldkit.md +28 -0
  243. package/dist/docs/registry/mobile.md +37 -0
  244. package/dist/docs/registry/notes-ui-foldkit.md +27 -0
  245. package/dist/docs/registry/notes.md +26 -0
  246. package/dist/docs/registry/people-ui-foldkit.md +28 -0
  247. package/dist/docs/registry/people.md +38 -0
  248. package/dist/docs/registry/shell-foldkit.md +34 -0
  249. package/dist/docs/registry/theme.md +25 -0
  250. package/dist/docs/registry/ui-conformance.md +30 -0
  251. package/dist/docs/release.md +100 -0
  252. package/dist/docs/scaffold.md +826 -0
  253. package/dist/docs/security/threat-model.md +299 -0
  254. package/dist/docs/upstream/zero-cache-socket-handoff.md +105 -0
  255. package/dist/index.d.ts +8 -0
  256. package/dist/index.d.ts.map +1 -0
  257. package/dist/index.js +8 -0
  258. package/dist/index.js.map +1 -0
  259. package/package.json +48 -3
  260. package/src/AgentSkills.ts +329 -0
  261. package/src/AgentWeb.ts +507 -0
  262. package/src/App.ts +435 -0
  263. package/src/Blueprint.ts +276 -0
  264. package/src/Brand.ts +415 -0
  265. package/src/Changelog.ts +136 -0
  266. package/src/Cli.ts +1458 -0
  267. package/src/DbAdmin.ts +115 -0
  268. package/src/Dependencies.ts +170 -0
  269. package/src/Deploy.ts +563 -0
  270. package/src/Docs.ts +309 -0
  271. package/src/Doctor.ts +424 -0
  272. package/src/Dossier.ts +148 -0
  273. package/src/Emit.ts +68 -0
  274. package/src/Errors.ts +18 -0
  275. package/src/Evals.ts +153 -0
  276. package/src/Files.ts +152 -0
  277. package/src/Generate.ts +402 -0
  278. package/src/Guards.ts +541 -0
  279. package/src/Inspect.ts +358 -0
  280. package/src/Keychain.ts +107 -0
  281. package/src/Lock.ts +174 -0
  282. package/src/Mcp.ts +159 -0
  283. package/src/Merge.ts +70 -0
  284. package/src/Migrate.ts +331 -0
  285. package/src/Plugins.ts +347 -0
  286. package/src/Postgres.ts +353 -0
  287. package/src/Publish.ts +64 -0
  288. package/src/Registry.ts +405 -0
  289. package/src/Remote.ts +1158 -0
  290. package/src/Run.ts +541 -0
  291. package/src/SyncGen.ts +570 -0
  292. package/src/Update.ts +873 -0
  293. package/src/bin.ts +46 -0
  294. package/src/index.ts +7 -0
package/src/Guards.ts ADDED
@@ -0,0 +1,541 @@
1
+ /**
2
+ * The architecture and security guards `eloxiv doctor` runs over an app's own source (docs/cli.md, "doctor"). They
3
+ * are portable: plain reads of the app's files, no workspace or build needed, so a generated app checks itself the
4
+ * way Eloxiv's repository checks its registry. They read each code file's syntax tree (comments and strings are what
5
+ * they are, never mistaken for code), and what they cannot resolve fails rather than passes: a load whose path is
6
+ * computed (a template with expressions, a variable, `require` passed around or aliased, `createRequire`), an
7
+ * environment reached through an alias or a computed name, a secret split across strings (constant concatenations are
8
+ * folded first). The database still enforces the module boundary at run time (each module's role reaches only its own
9
+ * schema), so a guard is an early warning, not the boundary itself.
10
+ *
11
+ * - **module boundaries**: a module, connector or skill loads another module's code only through its contract
12
+ * (`modules/<other>/contract.ts`), and loads nothing it cannot be checked for (a computed `import()`);
13
+ * - **sync engine**: nothing imports `@rocicorp/zero` directly (decision 9: sync only through `@eloxiv/client`);
14
+ * - **kernel in UI**: no shell or UI file imports `@eloxiv/kernel` (the kernel has no UI; UI items are templates);
15
+ * - **ambient credentials**: module, connector and skill code reads no environment (`process.env` and the like):
16
+ * credentials come scoped to an actor and organisation through Connections, Secrets and Settings;
17
+ * - **secrets in source**: no private key or provider token in the app's files, and no `.env` file tracked by git.
18
+ */
19
+ import { parse } from "@babel/parser"
20
+ import { spawnSync } from "node:child_process"
21
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
22
+ import { dirname, extname, join, relative, resolve, sep } from "node:path"
23
+
24
+ export type GuardRule =
25
+ | "module boundaries"
26
+ | "sync engine"
27
+ | "kernel in UI"
28
+ | "ambient credentials"
29
+ | "secrets in source"
30
+
31
+ export const GUARD_RULES: ReadonlyArray<GuardRule> = [
32
+ "module boundaries",
33
+ "sync engine",
34
+ "kernel in UI",
35
+ "ambient credentials",
36
+ "secrets in source",
37
+ ]
38
+
39
+ export interface GuardFinding {
40
+ readonly rule: GuardRule
41
+ /** Relative to the app, with `/`. */
42
+ readonly file: string
43
+ readonly line: number
44
+ readonly detail: string
45
+ }
46
+
47
+ const SOURCE = new Set([".ts", ".tsx", ".mts", ".cts", ".js", ".mjs", ".cjs", ".jsx"])
48
+ const SKIP = new Set(["node_modules", "dist", ".eloxiv", ".git", "target", ".vite"])
49
+ /** Where the app's own code lives (the server entry and composition at the root are checked for secrets only). */
50
+ const CODE_DIRS = ["modules", "connectors", "skills", "shell-foldkit", "shell", "desktop/src"]
51
+ const SECRET_DIRS = [...CODE_DIRS, "server", "deploy", "themes"]
52
+
53
+ const walk = (root: string, sub: string, out: Array<string>, filter: (file: string) => boolean) => {
54
+ const dir = join(root, sub)
55
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return
56
+ for (const name of readdirSync(dir)) {
57
+ if (SKIP.has(name)) continue
58
+ const path = join(dir, name)
59
+ const info = statSync(path, { throwIfNoEntry: false })
60
+ if (info === undefined) continue
61
+ if (info.isDirectory()) walk(root, join(sub, name), out, filter)
62
+ else if (filter(path) && info.size < 2_000_000) out.push(path)
63
+ }
64
+ }
65
+
66
+ const lineOf = (text: string, index: number) => text.slice(0, index).split("\n").length
67
+
68
+ /** What a code file loads, what it reaches of the environment, and the constant strings it holds, from its tree. */
69
+ export interface SourceReading {
70
+ /** Every module specifier it loads with a literal path, with its line. */
71
+ readonly found: ReadonlyArray<{ readonly specifier: string; readonly line: number }>
72
+ /** Loads that cannot be checked (a computed path, `require` passed around), with why. */
73
+ readonly unresolved: ReadonlyArray<{ readonly line: number; readonly detail: string }>
74
+ /** Reads of the environment (`process`, `Bun`, `Deno`, `import.meta.env`), however reached. */
75
+ readonly environment: ReadonlyArray<{ readonly line: number; readonly detail: string }>
76
+ /** Every constant string (literals, and concatenations of constants folded), with its line. */
77
+ readonly strings: ReadonlyArray<{ readonly value: string; readonly line: number }>
78
+ }
79
+
80
+ /** The globals that hold the environment, and the objects the global scope is reached through. */
81
+ const ENVIRONMENT = new Set(["process", "Bun", "Deno"])
82
+ const GLOBAL_OBJECTS = new Set(["globalThis", "global", "window", "self"])
83
+ const SKIPPED_KEYS = new Set(["loc", "start", "end", "extra", "leadingComments", "trailingComments", "innerComments"])
84
+ const PROCESS_MODULES: ReadonlySet<unknown> = new Set(["process", "node:process"])
85
+ const SCOPED = "credentials and settings come scoped through Connections, Secrets and Settings"
86
+
87
+ /** The nodes that open a scope. */
88
+ const SCOPE_NODES = new Set([
89
+ "Program",
90
+ "BlockStatement",
91
+ "StaticBlock",
92
+ "TSModuleBlock",
93
+ "SwitchStatement",
94
+ "FunctionDeclaration",
95
+ "FunctionExpression",
96
+ "ArrowFunctionExpression",
97
+ "ObjectMethod",
98
+ "ClassMethod",
99
+ "ClassPrivateMethod",
100
+ "ClassExpression",
101
+ "CatchClause",
102
+ "ForStatement",
103
+ "ForInStatement",
104
+ "ForOfStatement",
105
+ ])
106
+
107
+ /**
108
+ * The names a scope's node binds itself: its statements' declarations (a `var` counted in its own block, so a read
109
+ * of it outside that block is taken for the global: it fails closed), its parameters, a function or class
110
+ * expression's own name, a catch clause's parameter, a loop's declaration.
111
+ */
112
+ const bindingsOf = (node: any): ReadonlySet<string> => {
113
+ const names = new Set<string>()
114
+ const add = (pattern: any): void => {
115
+ if (pattern === null || pattern === undefined) return
116
+ if (pattern.type === "Identifier") names.add(pattern.name)
117
+ else if (pattern.type === "ObjectPattern")
118
+ for (const p of pattern.properties) add(p.type === "RestElement" ? p.argument : p.value)
119
+ else if (pattern.type === "ArrayPattern") for (const e of pattern.elements) add(e)
120
+ else if (pattern.type === "AssignmentPattern") add(pattern.left)
121
+ else if (pattern.type === "RestElement") add(pattern.argument)
122
+ else if (pattern.type === "TSParameterProperty") add(pattern.parameter)
123
+ }
124
+ const declaration = (d: any) => {
125
+ if (d?.type === "VariableDeclaration") for (const v of d.declarations) add(v.id)
126
+ }
127
+ const statements = (body: ReadonlyArray<any>) => {
128
+ for (const statement of body) {
129
+ const d =
130
+ (statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration") &&
131
+ statement.declaration
132
+ ? statement.declaration
133
+ : statement
134
+ declaration(d)
135
+ if (
136
+ (d.type === "FunctionDeclaration" ||
137
+ d.type === "ClassDeclaration" ||
138
+ d.type === "TSEnumDeclaration" ||
139
+ d.type === "TSModuleDeclaration") &&
140
+ d.id?.type === "Identifier"
141
+ )
142
+ names.add(d.id.name)
143
+ if (d.type === "ImportDeclaration") for (const specifier of d.specifiers) names.add(specifier.local.name)
144
+ }
145
+ }
146
+ switch (node.type) {
147
+ case "Program":
148
+ case "BlockStatement":
149
+ case "StaticBlock":
150
+ case "TSModuleBlock":
151
+ statements(node.body)
152
+ break
153
+ case "SwitchStatement":
154
+ statements(node.cases.flatMap((c: any) => c.consequent))
155
+ break
156
+ case "CatchClause":
157
+ add(node.param)
158
+ break
159
+ case "ForStatement":
160
+ declaration(node.init)
161
+ break
162
+ case "ForInStatement":
163
+ case "ForOfStatement":
164
+ declaration(node.left)
165
+ break
166
+ case "ClassExpression":
167
+ add(node.id)
168
+ break
169
+ default:
170
+ // A function: its parameters, and a function expression's own name.
171
+ for (const param of node.params ?? []) add(param)
172
+ if (node.type === "FunctionExpression") add(node.id)
173
+ }
174
+ return names
175
+ }
176
+
177
+ /** Read a code file's syntax tree. Throws when it is not code the parser reads. */
178
+ export const readSource = (text: string, file = "source.ts"): SourceReading => {
179
+ const ast = parse(text, {
180
+ sourceType: "unambiguous",
181
+ sourceFilename: file,
182
+ plugins: ["typescript", "jsx", "importAttributes"],
183
+ createImportExpressions: true,
184
+ })
185
+ const found: Array<{ specifier: string; line: number }> = []
186
+ const unresolved: Array<{ line: number; detail: string }> = []
187
+ const environment: Array<{ line: number; detail: string }> = []
188
+ const strings: Array<{ value: string; line: number }> = []
189
+ const lineAt = (node: any) => node?.loc?.start.line ?? 0
190
+ // The file's constant strings, by the name of the `const` they are bound to.
191
+ const constants = new Map<string, any>()
192
+ const collect = (node: any): void => {
193
+ if (node === null || typeof node !== "object") return
194
+ if (Array.isArray(node)) return node.forEach(collect)
195
+ if (node.type === "VariableDeclarator" && node.id?.type === "Identifier" && node.init)
196
+ constants.set(node.id.name, node.init)
197
+ for (const [key, value] of Object.entries(node)) if (!SKIPPED_KEYS.has(key)) collect(value)
198
+ }
199
+ collect(ast.program)
200
+ // Names imported whole from `process` (a default or namespace import), and its `env`: each is the environment.
201
+ const environmentImports = new Set<string>()
202
+ for (const statement of ast.program.body as Array<any>) {
203
+ if (statement.type !== "ImportDeclaration" || !PROCESS_MODULES.has(statement.source.value)) continue
204
+ for (const specifier of statement.specifiers) {
205
+ const imported =
206
+ specifier.type !== "ImportSpecifier"
207
+ ? undefined
208
+ : specifier.imported.type === "Identifier"
209
+ ? specifier.imported.name
210
+ : specifier.imported.value
211
+ if (specifier.type !== "ImportSpecifier" || imported === "env" || imported === "default")
212
+ environmentImports.add(specifier.local.name)
213
+ }
214
+ }
215
+ // The scopes around the node being read, innermost last, each with the names it binds: a local named like a global
216
+ // is that global only outside the scope that declares it.
217
+ const scopes: Array<ReadonlySet<string>> = []
218
+ const scopeOf = (name: string) => {
219
+ for (let i = scopes.length - 1; i >= 0; i--) if (scopes[i]!.has(name)) return i
220
+ return -1
221
+ }
222
+ /** A node's constant string value, folding `+` of constants and `const` names bound to them (none if not one). */
223
+ const constantOf = (node: any, seen = new Set<string>()): string | undefined => {
224
+ if (node === null || node === undefined) return undefined
225
+ if (node.type === "StringLiteral") return node.value
226
+ if (node.type === "TemplateLiteral") {
227
+ let out = node.quasis[0]?.value.cooked ?? ""
228
+ for (let i = 0; i < node.expressions.length; i++) {
229
+ const part = constantOf(node.expressions[i], seen)
230
+ if (part === undefined) return undefined
231
+ out += part + (node.quasis[i + 1]?.value.cooked ?? "")
232
+ }
233
+ return out
234
+ }
235
+ if (node.type === "BinaryExpression" && node.operator === "+") {
236
+ const left = constantOf(node.left, seen)
237
+ const right = left === undefined ? undefined : constantOf(node.right, seen)
238
+ return right === undefined ? undefined : left! + right
239
+ }
240
+ if (node.type === "Identifier" && constants.has(node.name) && !seen.has(node.name)) {
241
+ seen.add(node.name)
242
+ return constantOf(constants.get(node.name), seen)
243
+ }
244
+ if (
245
+ node.type === "TSAsExpression" ||
246
+ node.type === "TSSatisfiesExpression" ||
247
+ node.type === "ParenthesizedExpression"
248
+ )
249
+ return constantOf(node.expression, seen)
250
+ return undefined
251
+ }
252
+ /** A load's path: a constant string, or a finding. */
253
+ const load = (how: string, argument: any, at: any) => {
254
+ const specifier = constantOf(argument)
255
+ if (specifier === undefined)
256
+ unresolved.push({ line: lineAt(at), detail: `a computed ${how} cannot be checked: load a literal path` })
257
+ else found.push({ specifier, line: lineAt(at) })
258
+ // `process` taken whole as a value (`require`, `import()`): the environment.
259
+ if (specifier !== undefined && PROCESS_MODULES.has(specifier) && (how === "require()" || how === "import()"))
260
+ environment.push({ line: lineAt(at), detail: `loads ${specifier}: ${SCOPED}` })
261
+ }
262
+ /** An expression without the type assertions and parentheses around it (\`(globalThis as any)\` is \`globalThis\`). */
263
+ const unwrap = (node: any): any =>
264
+ node?.type === "TSAsExpression" ||
265
+ node?.type === "TSSatisfiesExpression" ||
266
+ node?.type === "TSNonNullExpression" ||
267
+ node?.type === "TSTypeAssertion" ||
268
+ node?.type === "ParenthesizedExpression"
269
+ ? unwrap(node.expression)
270
+ : node
271
+ const isGlobal = (node: any, names: ReadonlySet<string>) => {
272
+ const bare = unwrap(node)
273
+ return bare?.type === "Identifier" && names.has(bare.name) && scopeOf(bare.name) === -1
274
+ }
275
+ /** The name a member access reads, when it is constant. */
276
+ const memberName = (node: any): string | undefined =>
277
+ node.computed ? constantOf(node.property) : node.property?.type === "Identifier" ? node.property.name : undefined
278
+
279
+ const visit = (node: any, parent: any, key: string | undefined): void => {
280
+ if (node === null || typeof node !== "object") return
281
+ if (Array.isArray(node)) {
282
+ for (const child of node) visit(child, parent, key)
283
+ return
284
+ }
285
+ const scoped = SCOPE_NODES.has(node.type)
286
+ if (scoped) scopes.push(bindingsOf(node))
287
+ switch (node.type) {
288
+ case "ImportDeclaration":
289
+ case "ExportAllDeclaration":
290
+ load("import", node.source, node)
291
+ break
292
+ case "ExportNamedDeclaration":
293
+ if (node.source) load("export", node.source, node)
294
+ break
295
+ case "ImportExpression":
296
+ load("import()", node.source, node)
297
+ break
298
+ case "TSImportEqualsDeclaration":
299
+ if (node.moduleReference?.type === "TSExternalModuleReference")
300
+ load("import = require()", node.moduleReference.expression, node)
301
+ break
302
+ case "TSImportType":
303
+ load("type import()", node.argument, node)
304
+ break
305
+ case "CallExpression": {
306
+ const callee = node.callee
307
+ if (callee.type === "Import") load("import()", node.arguments[0], node)
308
+ else if (isGlobal(callee, new Set(["require"]))) load("require()", node.arguments[0], node)
309
+ else if (callee.type === "Identifier" && callee.name === "createRequire")
310
+ unresolved.push({
311
+ line: lineAt(node),
312
+ detail: "createRequire() makes a require that loads anything: it cannot be checked",
313
+ })
314
+ else if (callee.type === "MemberExpression" && memberName(callee) === "resolve") {
315
+ if (isGlobal(callee.object, new Set(["require"]))) load("require.resolve()", node.arguments[0], node)
316
+ else if (callee.object.type === "MetaProperty") load("import.meta.resolve()", node.arguments[0], node)
317
+ }
318
+ break
319
+ }
320
+ case "Identifier": {
321
+ // A global reached by its name, in a place it is read (not a property name, a declaration or a key).
322
+ const read =
323
+ !(parent?.type === "MemberExpression" && key === "property" && !parent.computed) &&
324
+ !(
325
+ (parent?.type === "ObjectProperty" || parent?.type === "ObjectMethod") &&
326
+ key === "key" &&
327
+ !parent.computed
328
+ ) &&
329
+ !(parent?.type === "TSQualifiedName") &&
330
+ !(parent?.type === "TSTypeReference" && key === "typeName")
331
+ const imported = parent?.type?.startsWith("Import") === true
332
+ if (read && !imported && environmentImports.has(node.name) && scopeOf(node.name) === 0)
333
+ environment.push({ line: lineAt(node), detail: `reads ${node.name}, imported from process: ${SCOPED}` })
334
+ if (read && isGlobal(node, ENVIRONMENT))
335
+ environment.push({
336
+ line: lineAt(node),
337
+ detail: `reads ${node.name}: credentials and settings come scoped through Connections, Secrets and Settings`,
338
+ })
339
+ // \`require\` passed around or aliased (anything but a direct call or require.resolve) loads unchecked.
340
+ const called =
341
+ (parent?.type === "CallExpression" && key === "callee") ||
342
+ (parent?.type === "MemberExpression" && key === "object" && memberName(parent) === "resolve")
343
+ if (read && !called && isGlobal(node, new Set(["require"])))
344
+ unresolved.push({
345
+ line: lineAt(node),
346
+ detail: "require used as a value cannot be checked: call it with a literal path",
347
+ })
348
+ break
349
+ }
350
+ case "MemberExpression": {
351
+ if (node.object?.type === "MetaProperty" && memberName(node) === "env")
352
+ environment.push({
353
+ line: lineAt(node),
354
+ detail:
355
+ "reads import.meta.env: credentials and settings come scoped through Connections, Secrets and Settings",
356
+ })
357
+ if (isGlobal(node.object, GLOBAL_OBJECTS)) {
358
+ const name = memberName(node)
359
+ const object = unwrap(node.object).name
360
+ if (name === undefined)
361
+ environment.push({ line: lineAt(node), detail: `reads ${object} by a computed name: it cannot be checked` })
362
+ else if (ENVIRONMENT.has(name))
363
+ environment.push({
364
+ line: lineAt(node),
365
+ detail: `reads ${object}.${name}: credentials and settings come scoped through Connections, Secrets and Settings`,
366
+ })
367
+ else if (name === "require")
368
+ unresolved.push({
369
+ line: lineAt(node),
370
+ detail: `${object}.require cannot be checked: import a literal path`,
371
+ })
372
+ }
373
+ break
374
+ }
375
+ }
376
+ // Every constant string, folded where it is built (an inner piece of a concatenation is read as part of it).
377
+ const folds =
378
+ node.type === "StringLiteral" ||
379
+ (node.type === "TemplateLiteral" && parent?.type !== "TaggedTemplateExpression") ||
380
+ (node.type === "BinaryExpression" && node.operator === "+")
381
+ const inner = parent?.type === "BinaryExpression" && parent.operator === "+"
382
+ if (folds && !inner) {
383
+ const value = constantOf(node)
384
+ if (value !== undefined) strings.push({ value, line: lineAt(node) })
385
+ }
386
+ for (const [childKey, value] of Object.entries(node))
387
+ if (!SKIPPED_KEYS.has(childKey) && value && typeof value === "object") visit(value, node, childKey)
388
+ if (scoped) scopes.pop()
389
+ }
390
+ visit(ast.program, undefined, undefined)
391
+ return { found, unresolved, environment, strings }
392
+ }
393
+
394
+ /** Every module specifier `text` loads, with its line, and the lines of loads that cannot be checked. */
395
+ export const specifiers = (text: string) => {
396
+ const reading = readSource(text)
397
+ return { found: reading.found, computed: reading.unresolved.map((u) => u.line) }
398
+ }
399
+
400
+ const SECRET_PATTERNS: ReadonlyArray<readonly [RegExp, string]> = [
401
+ [/-----BEGIN (?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY-----/, "a private key"],
402
+ [/\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{24,}/, "an OpenAI or Anthropic API key"],
403
+ [/\bxox[abposr]-[A-Za-z0-9-]{10,}/, "a Slack token"],
404
+ [/\bgh[pousr]_[A-Za-z0-9]{36,}\b|\bgithub_pat_[A-Za-z0-9_]{40,}/, "a GitHub token"],
405
+ [/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key id"],
406
+ [/\bAIza[0-9A-Za-z_-]{35}\b/, "a Google API key"],
407
+ [/\belxk_[A-Za-z0-9_-]{20,}/, "an Eloxiv API token"],
408
+ ]
409
+
410
+ /** The module directory (`modules/<name>`) a path of the app is in, if any. */
411
+ const moduleOf = (rel: string) => {
412
+ const parts = rel.split("/")
413
+ return parts[0] === "modules" && parts.length > 2 ? parts[1] : undefined
414
+ }
415
+
416
+ const isContract = (rel: string) => /^modules\/[^/]+\/contract(\.(ts|tsx|mts|js|mjs))?$/.test(rel)
417
+
418
+ /** Run every guard over the app in `dir`. */
419
+ export const guardFindings = (dir: string): ReadonlyArray<GuardFinding> => {
420
+ const root = resolve(dir)
421
+ const findings: Array<GuardFinding> = []
422
+ const rel = (file: string) => relative(root, file).split(sep).join("/")
423
+ const code: Array<string> = []
424
+ for (const sub of CODE_DIRS) walk(root, sub, code, (file) => SOURCE.has(extname(file)))
425
+ /** Secrets found in a file's constant strings (a key split across strings, folded), by file. */
426
+ const folded = new Map<string, ReadonlyArray<{ readonly value: string; readonly line: number }>>()
427
+ for (const file of code) {
428
+ const path = rel(file)
429
+ const text = readFileSync(file, "utf8")
430
+ const area = path.split("/")[0]!
431
+ const ui = area === "shell-foldkit" || area === "shell" || area === "desktop"
432
+ let reading: SourceReading
433
+ try {
434
+ reading = readSource(text, path)
435
+ } catch (error) {
436
+ findings.push({
437
+ rule: "module boundaries",
438
+ file: path,
439
+ line: 1,
440
+ detail: `cannot be read as code, so it cannot be checked: ${error instanceof Error ? error.message : String(error)}`,
441
+ })
442
+ continue
443
+ }
444
+ folded.set(file, reading.strings)
445
+ for (const { specifier, line } of reading.found) {
446
+ if (specifier === "@rocicorp/zero" || specifier.startsWith("@rocicorp/zero/")) {
447
+ findings.push({
448
+ rule: "sync engine",
449
+ file: path,
450
+ line,
451
+ detail: `imports ${specifier}: reach sync through @eloxiv/client (decision 9)`,
452
+ })
453
+ }
454
+ if (ui && (specifier === "@eloxiv/kernel" || specifier.startsWith("@eloxiv/kernel/"))) {
455
+ findings.push({
456
+ rule: "kernel in UI",
457
+ file: path,
458
+ line,
459
+ detail: `imports ${specifier}: UI talks to the kernel through @eloxiv/client`,
460
+ })
461
+ }
462
+ if (!ui && specifier.startsWith(".")) {
463
+ const target = rel(resolve(dirname(file), specifier))
464
+ const parts = target.split("/")
465
+ const other = parts[0] === "modules" && parts.length > 1 ? parts[1] : undefined
466
+ if (other !== undefined && other !== moduleOf(path) && !isContract(target)) {
467
+ findings.push({
468
+ rule: "module boundaries",
469
+ file: path,
470
+ line,
471
+ detail: `loads ${target}: another module's code only through modules/${other}/contract.ts`,
472
+ })
473
+ }
474
+ }
475
+ }
476
+ if (!ui) {
477
+ for (const { line, detail } of reading.unresolved)
478
+ findings.push({ rule: "module boundaries", file: path, line, detail })
479
+ for (const { line, detail } of reading.environment)
480
+ findings.push({ rule: "ambient credentials", file: path, line, detail })
481
+ }
482
+ }
483
+ const scanned: Array<string> = []
484
+ for (const sub of SECRET_DIRS) walk(root, sub, scanned, (file) => !file.endsWith(".lock") && extname(file) !== ".png")
485
+ for (const name of readdirSync(root)) {
486
+ const file = join(root, name)
487
+ if (statSync(file).isFile() && /\.(ts|js|mjs|json|toml|ya?ml|md)$/.test(name) && !name.endsWith(".lock.json"))
488
+ scanned.push(file)
489
+ }
490
+ for (const file of scanned) {
491
+ const text = readFileSync(file, "utf8")
492
+ if (text.includes("\u0000")) continue
493
+ const seen = new Set<string>()
494
+ for (const [pattern, what] of SECRET_PATTERNS) {
495
+ const match = pattern.exec(text)
496
+ if (match !== null) {
497
+ seen.add(what)
498
+ findings.push({
499
+ rule: "secrets in source",
500
+ file: rel(file),
501
+ line: lineOf(text, match.index),
502
+ detail: `holds ${what}: move it to the host's secrets`,
503
+ })
504
+ }
505
+ }
506
+ // A secret split across strings, found once its constant pieces are put together.
507
+ for (const { value, line } of folded.get(file) ?? []) {
508
+ for (const [pattern, what] of SECRET_PATTERNS) {
509
+ if (seen.has(what) || !pattern.test(value)) continue
510
+ seen.add(what)
511
+ findings.push({
512
+ rule: "secrets in source",
513
+ file: rel(file),
514
+ line,
515
+ detail: `holds ${what}, put together from pieces: move it to the host's secrets`,
516
+ })
517
+ }
518
+ }
519
+ }
520
+ // A .env file committed to the app's git repository (when it is one).
521
+ const tracked = spawnSync("git", ["ls-files", "--", ".env", "*.env", "**/.env", ".env.*", "**/.env.*"], {
522
+ cwd: root,
523
+ encoding: "utf8",
524
+ })
525
+ if (tracked.status === 0) {
526
+ for (const file of tracked.stdout.split("\n").filter((f) => f !== "" && !/\.(example|sample|template)$/.test(f))) {
527
+ findings.push({
528
+ rule: "secrets in source",
529
+ file,
530
+ line: 1,
531
+ detail:
532
+ "an environment file tracked by git: remove it from the repository (git rm --cached) and rotate what it held",
533
+ })
534
+ }
535
+ }
536
+ // Sorted by file, line, rule and detail: the same order on every runtime and file system.
537
+ const order = (x: string, y: string) => (x < y ? -1 : x > y ? 1 : 0)
538
+ return findings.sort(
539
+ (a, b) => order(a.file, b.file) || a.line - b.line || order(a.rule, b.rule) || order(a.detail, b.detail),
540
+ )
541
+ }