himaya 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 (195) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +201 -0
  3. package/PRIVACY.md +64 -0
  4. package/README.md +283 -2
  5. package/SECURITY.md +29 -0
  6. package/agent/AGENTS.section.md +11 -0
  7. package/agent/skill/SKILL.md +118 -0
  8. package/dist/ci/codeowners.js +62 -0
  9. package/dist/ci/reviews.js +62 -0
  10. package/dist/ci/run.js +347 -0
  11. package/dist/ci/workflow.js +150 -0
  12. package/dist/cli/answer.js +77 -0
  13. package/dist/cli/args.js +53 -0
  14. package/dist/cli/ci.js +77 -0
  15. package/dist/cli/diff.js +21 -0
  16. package/dist/cli/explain.js +62 -0
  17. package/dist/cli/feedback.js +59 -0
  18. package/dist/cli/fix.js +184 -0
  19. package/dist/cli/history.js +36 -0
  20. package/dist/cli/hunt.js +116 -0
  21. package/dist/cli/index.js +36 -0
  22. package/dist/cli/init.js +36 -0
  23. package/dist/cli/main.js +243 -0
  24. package/dist/cli/promise.js +100 -0
  25. package/dist/cli/shield.js +93 -0
  26. package/dist/cli/threats.js +129 -0
  27. package/dist/cli/tripwire.js +94 -0
  28. package/dist/cli/watch.js +77 -0
  29. package/dist/copy/checks.js +422 -0
  30. package/dist/copy/ci.js +65 -0
  31. package/dist/copy/data.js +68 -0
  32. package/dist/copy/feedback.js +36 -0
  33. package/dist/copy/fix-steps.js +229 -0
  34. package/dist/copy/fixes.js +64 -0
  35. package/dist/copy/guard.js +20 -0
  36. package/dist/copy/init.js +92 -0
  37. package/dist/copy/mcp.js +34 -0
  38. package/dist/copy/platforms.js +93 -0
  39. package/dist/copy/promises.js +108 -0
  40. package/dist/copy/report.js +81 -0
  41. package/dist/copy/shields.js +68 -0
  42. package/dist/copy/threats.js +231 -0
  43. package/dist/copy/watch.js +69 -0
  44. package/dist/data/index.js +25 -0
  45. package/dist/data/known-bad-packages.json +56 -0
  46. package/dist/data/popular-packages.json +712 -0
  47. package/dist/data/shields/GHSA-f82v-jwr5-mffw.json +25 -0
  48. package/dist/data/shields.js +22 -0
  49. package/dist/data/tripwire-decoys.json +37 -0
  50. package/dist/diff/accessmap.js +202 -0
  51. package/dist/diff/compare.js +107 -0
  52. package/dist/diff/render.js +38 -0
  53. package/dist/diff/run.js +124 -0
  54. package/dist/diff/snapshot.js +163 -0
  55. package/dist/engine/basis.js +26 -0
  56. package/dist/engine/checks-list.js +234 -0
  57. package/dist/engine/code.js +400 -0
  58. package/dist/engine/configs.js +130 -0
  59. package/dist/engine/context.js +1 -0
  60. package/dist/engine/discover.js +212 -0
  61. package/dist/engine/files.js +151 -0
  62. package/dist/engine/finding.js +10 -0
  63. package/dist/engine/git-branch.js +212 -0
  64. package/dist/engine/git.js +160 -0
  65. package/dist/engine/gitignore.js +156 -0
  66. package/dist/engine/hash.js +7 -0
  67. package/dist/engine/himaya-guards.js +50 -0
  68. package/dist/engine/invisible.js +187 -0
  69. package/dist/engine/links.js +18 -0
  70. package/dist/engine/lockfile.js +75 -0
  71. package/dist/engine/make-finding.js +37 -0
  72. package/dist/engine/mask.js +68 -0
  73. package/dist/engine/package-names.js +143 -0
  74. package/dist/engine/packs.js +1 -0
  75. package/dist/engine/pg-worker.js +112 -0
  76. package/dist/engine/pool.js +16 -0
  77. package/dist/engine/profile.js +340 -0
  78. package/dist/engine/project.js +283 -0
  79. package/dist/engine/rank.js +185 -0
  80. package/dist/engine/safe-db.js +307 -0
  81. package/dist/engine/scan.js +412 -0
  82. package/dist/engine/schema.js +317 -0
  83. package/dist/engine/secret-formats.js +133 -0
  84. package/dist/engine/secrets-names.js +71 -0
  85. package/dist/engine/shipped.js +14 -0
  86. package/dist/engine/specifiers.js +27 -0
  87. package/dist/engine/sql-split.js +87 -0
  88. package/dist/engine/supabase-shim.js +111 -0
  89. package/dist/engine/text.js +19 -0
  90. package/dist/engine/tripwire-lures.js +15 -0
  91. package/dist/engine/versions.js +103 -0
  92. package/dist/fixes/code-access.js +944 -0
  93. package/dist/fixes/code-ai.js +1094 -0
  94. package/dist/fixes/code-common.js +145 -0
  95. package/dist/fixes/code-edit.js +164 -0
  96. package/dist/fixes/code-pay.js +933 -0
  97. package/dist/fixes/data.js +779 -0
  98. package/dist/fixes/diff.js +166 -0
  99. package/dist/fixes/registry.js +13 -0
  100. package/dist/fixes/secrets.js +32 -0
  101. package/dist/fixes/static.js +1159 -0
  102. package/dist/guard/bash.js +252 -0
  103. package/dist/guard/index.js +158 -0
  104. package/dist/guard/install.js +17 -0
  105. package/dist/guard/redlines.js +345 -0
  106. package/dist/guard/rules.js +18 -0
  107. package/dist/guard/stop.js +194 -0
  108. package/dist/history/git.js +40 -0
  109. package/dist/history/replay.js +403 -0
  110. package/dist/history/report.js +146 -0
  111. package/dist/history/since.js +36 -0
  112. package/dist/hunt/candidates.js +119 -0
  113. package/dist/hunt/merge.js +290 -0
  114. package/dist/hunt/surfaces.js +129 -0
  115. package/dist/init/init.js +456 -0
  116. package/dist/mcp/server.js +230 -0
  117. package/dist/net/registry.js +116 -0
  118. package/dist/packs/core/checks/agent.js +831 -0
  119. package/dist/packs/core/checks/ai.js +1219 -0
  120. package/dist/packs/core/checks/deps.js +455 -0
  121. package/dist/packs/core/checks/hard08.js +258 -0
  122. package/dist/packs/core/checks/hard09.js +192 -0
  123. package/dist/packs/core/checks/sec02.js +337 -0
  124. package/dist/packs/core/pack.js +16 -0
  125. package/dist/packs/index.js +15 -0
  126. package/dist/packs/nextjs/auth.js +312 -0
  127. package/dist/packs/nextjs/checks/access.js +612 -0
  128. package/dist/packs/nextjs/checks/hard.js +783 -0
  129. package/dist/packs/nextjs/checks/inj01.js +774 -0
  130. package/dist/packs/nextjs/checks/sec01.js +254 -0
  131. package/dist/packs/nextjs/pack.js +13 -0
  132. package/dist/packs/payments/checks.js +678 -0
  133. package/dist/packs/razorpay/pack.js +10 -0
  134. package/dist/packs/stripe/pack.js +11 -0
  135. package/dist/packs/supabase/checks/data.js +1213 -0
  136. package/dist/packs/supabase/checks/sec03.js +94 -0
  137. package/dist/packs/supabase/pack.js +11 -0
  138. package/dist/packs/supabase/sql.js +269 -0
  139. package/dist/packs/vite/pack.js +18 -0
  140. package/dist/promises/changes.js +187 -0
  141. package/dist/promises/check.js +253 -0
  142. package/dist/promises/code.js +159 -0
  143. package/dist/promises/db.js +921 -0
  144. package/dist/promises/readback.js +58 -0
  145. package/dist/promises/schema.js +277 -0
  146. package/dist/promises/world.js +395 -0
  147. package/dist/proofs/code.js +118 -0
  148. package/dist/proofs/db.js +248 -0
  149. package/dist/proofs/engine.js +235 -0
  150. package/dist/proofs/file.js +129 -0
  151. package/dist/proofs/harness/mocks.js +573 -0
  152. package/dist/proofs/harness/run.js +316 -0
  153. package/dist/proofs/promise-test.js +99 -0
  154. package/dist/proofs/promise.js +122 -0
  155. package/dist/proofs/runtime.js +50 -0
  156. package/dist/proofs/together.js +131 -0
  157. package/dist/proofs/tree.js +77 -0
  158. package/dist/proofs/types.js +2 -0
  159. package/dist/report/gate.js +63 -0
  160. package/dist/report/json.js +64 -0
  161. package/dist/report/sarif.js +165 -0
  162. package/dist/report/terminal.js +182 -0
  163. package/dist/report/threats.js +134 -0
  164. package/dist/rules/security-rules.js +52 -0
  165. package/dist/shields/manager.js +762 -0
  166. package/dist/shields/record.js +45 -0
  167. package/dist/shields/schema.js +212 -0
  168. package/dist/shields/templates/app.js +197 -0
  169. package/dist/threats/evaluate.js +107 -0
  170. package/dist/threats/tracks.js +108 -0
  171. package/dist/threats/tracks.yaml +281 -0
  172. package/dist/tripwires/manager.js +415 -0
  173. package/dist/tripwires/routes.js +47 -0
  174. package/dist/tripwires/templates/app.js +140 -0
  175. package/dist/universal/budget.js +44 -0
  176. package/dist/universal/commands.js +169 -0
  177. package/dist/universal/datastores.js +30 -0
  178. package/dist/universal/egress.js +209 -0
  179. package/dist/universal/entrypoints.js +568 -0
  180. package/dist/universal/gate.js +331 -0
  181. package/dist/universal/manifests.js +89 -0
  182. package/dist/universal/map.js +202 -0
  183. package/dist/universal/merge.js +118 -0
  184. package/dist/universal/parsers.js +60 -0
  185. package/dist/universal/roles.js +110 -0
  186. package/dist/universal/run.js +291 -0
  187. package/dist/universal/runner.js +113 -0
  188. package/dist/universal/schemas.js +149 -0
  189. package/dist/universal/serve.js +61 -0
  190. package/dist/universal/settings.js +96 -0
  191. package/dist/universal/workspace.js +67 -0
  192. package/dist/version.js +2 -0
  193. package/dist/watch/manager.js +816 -0
  194. package/dist/watch/templates/app.js +407 -0
  195. package/package.json +55 -4
@@ -0,0 +1,184 @@
1
+ /**
2
+ * `himaya fix <id> --plan | --patch` and `himaya verify <id>` (ARCHITECTURE: Proving fixes).
3
+ * `fix --plan` writes the engine's proof file; `fix --patch` writes a patch file under
4
+ * .himaya/patches/ and never edits the project's code (CLAUDE.md rule 3).
5
+ */
6
+ import { existsSync, lstatSync, mkdirSync, writeFileSync } from "node:fs";
7
+ import { dirname, join, resolve } from "node:path";
8
+ import { stripControl } from "../engine/text.js";
9
+ import { maskSecrets } from "../engine/mask.js";
10
+ import { checkInfo } from "../engine/checks-list.js";
11
+ import { FIX_SPECS } from "../fixes/registry.js";
12
+ import { unifiedPatch } from "../fixes/diff.js";
13
+ import { holdBackSecrets, maskedChange } from "../fixes/secrets.js";
14
+ import { checkOf, defaultTreeFor, openFindings, planProof, verifyFix } from "../proofs/engine.js";
15
+ import { writeProof, proofPath } from "../proofs/file.js";
16
+ import { Tree } from "../proofs/tree.js";
17
+ import { FixRefused } from "../proofs/types.js";
18
+ import { trackedFiles } from "../engine/git.js";
19
+ import { FIX_TEXT } from "../copy/fixes.js";
20
+ import { isPromiseKey, promiseIdOf, promiseSpec } from "../proofs/promise.js";
21
+ import { verifyTogether } from "../proofs/together.js";
22
+ const out = (s) => process.stdout.write(s);
23
+ const clean = (s) => maskSecrets(stripControl(s));
24
+ function specFor(id) {
25
+ if (isPromiseKey(id))
26
+ return promiseSpec(promiseIdOf(id));
27
+ const spec = FIX_SPECS.get(checkOf(id));
28
+ if (!spec)
29
+ throw new FixRefused(FIX_TEXT.unknownCheck(clean(id)));
30
+ return spec;
31
+ }
32
+ export const PATCH_DIR = ".himaya/patches";
33
+ /**
34
+ * A finding in a file git doesn't track (ignored, or never added) can't be fixed on a branch or
35
+ * proved against the default branch: say so, with the owner's step, instead of "no such finding".
36
+ */
37
+ async function refuseUntracked(tree, spec, id) {
38
+ if (!id.includes(":") || spec.findings)
39
+ return;
40
+ const here = (await tree.findings(spec.checkId)).find((f) => f.id === id);
41
+ const tracked = trackedFiles(tree.dir);
42
+ if (here && tracked && !tracked.has(here.location.file))
43
+ throw new FixRefused(FIX_TEXT.untracked(clean(here.location.file)));
44
+ }
45
+ export async function fixCommand(args) {
46
+ const [id, folder = "."] = args.positionals;
47
+ const plan = args.flags.has("plan");
48
+ const patch = args.flags.has("patch");
49
+ if (!id || plan === patch) {
50
+ process.stderr.write(FIX_TEXT.usage);
51
+ return 2;
52
+ }
53
+ const root = resolve(folder);
54
+ const tree = new Tree(root, FIX_TEXT.fixBranch);
55
+ try {
56
+ const spec = specFor(id);
57
+ const title = spec.title ?? checkInfo(spec.checkId)?.title ?? spec.checkId;
58
+ await refuseUntracked(tree, spec, id);
59
+ if (plan) {
60
+ const p = await planProof((await defaultTreeFor(root)) ?? tree, spec, id);
61
+ const written = writeProof(root, spec.checkId, p.text);
62
+ out([
63
+ FIX_TEXT.planHeading(spec.checkId, title),
64
+ "",
65
+ ...spec.steps.map((s, i) => `${i + 1}. ${s}`),
66
+ "",
67
+ FIX_TEXT.planFindings(p.findings.length),
68
+ ...p.findings.map((f) => `- ${clean(f.id)} at ${clean(f.location.file)}:${f.location.line}`),
69
+ "",
70
+ FIX_TEXT.planProof(written[0] ?? proofPath(spec.checkId)),
71
+ FIX_TEXT.planCore,
72
+ ...p.data.core.map((c) => `- ${clean(c)}`),
73
+ ...(p.data.legit.length
74
+ ? [FIX_TEXT.planLegit, ...p.data.legit.map((c) => `- ${clean(c)}`)]
75
+ : []),
76
+ FIX_TEXT.planHeldOut(p.data.heldOutPool),
77
+ "",
78
+ FIX_TEXT.planNext(spec.checkId),
79
+ "",
80
+ ].join("\n"));
81
+ return 0;
82
+ }
83
+ // Planned on the default branch, like the proof, so the patch and the proof cover the same findings.
84
+ const from = (await defaultTreeFor(root)) ?? tree;
85
+ const findings = await openFindings(from, spec);
86
+ if (!findings.length)
87
+ throw new FixRefused(FIX_TEXT.noFindings(spec.checkId, from.label));
88
+ const result = await spec.patch(findings, from);
89
+ if (!result) {
90
+ out(`${FIX_TEXT.noPatch(spec.checkId)}\n${spec.steps.map((s, i) => `${i + 1}. ${s}`).join("\n")}\n`);
91
+ return 1;
92
+ }
93
+ const rel = `${PATCH_DIR}/${spec.checkId.replace(/:/g, "-")}.patch`;
94
+ const abs = join(root, rel);
95
+ if (existsSync(abs) && lstatSync(abs).isSymbolicLink())
96
+ throw new FixRefused(`Refusing to write through a link: ${rel}`);
97
+ mkdirSync(dirname(abs), { recursive: true });
98
+ const split = holdBackSecrets(result.edits, from.ctx.knownSecrets);
99
+ writeFileSync(abs, unifiedPatch(split.patch));
100
+ out([
101
+ FIX_TEXT.patchWritten(rel),
102
+ ...split.heldBack.flatMap((e) => [
103
+ "",
104
+ FIX_TEXT.heldBack(clean(e.path)),
105
+ maskedChange(e, from.ctx.knownSecrets).trimEnd(),
106
+ ]),
107
+ ...(result.humanSteps.length
108
+ ? ["", FIX_TEXT.humanSteps, ...result.humanSteps.map((h) => `- ${h}`)]
109
+ : []),
110
+ "",
111
+ ].join("\n"));
112
+ return 0;
113
+ }
114
+ catch (e) {
115
+ if (e instanceof FixRefused) {
116
+ process.stderr.write(`${clean(e.message)}\n`);
117
+ return 1;
118
+ }
119
+ throw e;
120
+ }
121
+ finally {
122
+ await tree.dispose();
123
+ }
124
+ }
125
+ async function verifyTogetherCommand(args) {
126
+ const list = args.flags.get("together");
127
+ const branches = (typeof list === "string" ? list : "")
128
+ .split(",")
129
+ .map((b) => b.trim())
130
+ .filter(Boolean);
131
+ const folder = resolve(args.positionals[0] ?? ".");
132
+ try {
133
+ const r = await verifyTogether(folder, branches);
134
+ out([
135
+ FIX_TEXT.togetherHeading(branches.map(clean)),
136
+ ...r.conflicts.map((c) => `- ${clean(c)}`),
137
+ ...r.proofs.map((p) => `${p.outcome?.passed ? "✓" : "✗"} ${clean(p.key)}: ${clean(p.outcome?.line ?? p.error ?? "")}`),
138
+ ...(r.summaryLine ? [FIX_TEXT.togetherScan(r.summaryLine, r.changes)] : []),
139
+ ...r.problems.map((p) => `- ${clean(p)}`),
140
+ r.passed ? FIX_TEXT.togetherPassed : FIX_TEXT.togetherFailedLine(r.problems.length),
141
+ "",
142
+ ].join("\n"));
143
+ return r.passed ? 0 : 1;
144
+ }
145
+ catch (e) {
146
+ if (e instanceof FixRefused) {
147
+ process.stderr.write(`${clean(e.message)}\n`);
148
+ return 1;
149
+ }
150
+ throw e;
151
+ }
152
+ }
153
+ export async function verifyFindingCommand(args) {
154
+ if (args.flags.has("together"))
155
+ return verifyTogetherCommand(args);
156
+ const [id, folder = "."] = args.positionals;
157
+ if (!id) {
158
+ process.stderr.write(FIX_TEXT.usage);
159
+ return 2;
160
+ }
161
+ try {
162
+ const spec = specFor(id);
163
+ const r = await verifyFix(resolve(folder), id, spec);
164
+ const show = (ok, name) => `${ok ? "✓" : "✗"} ${clean(name)}`;
165
+ out([
166
+ ...r.core.map((c) => show(c.after?.held === true && c.before?.held === false, c.name)),
167
+ ...r.heldOut.map((h) => `${show(h.after?.held === true, h.name)} (held-out)`),
168
+ ...r.legit.map((l) => `${show(l.after?.held === true, l.name)} (legitimate use)`),
169
+ "",
170
+ ...r.problems.map((p) => `- ${clean(p)}`),
171
+ r.line,
172
+ r.passed ? FIX_TEXT.verifyPassed : FIX_TEXT.verifyFailed(r.problems.length),
173
+ "",
174
+ ].join("\n"));
175
+ return r.passed ? 0 : 1;
176
+ }
177
+ catch (e) {
178
+ if (e instanceof FixRefused) {
179
+ process.stderr.write(`${clean(e.message)}\n`);
180
+ return 1;
181
+ }
182
+ throw e;
183
+ }
184
+ }
@@ -0,0 +1,36 @@
1
+ /** `himaya history [folder] [--json] [--report] [--since YYYY-MM-DD] [--authors]`. */
2
+ import { relative } from "node:path";
3
+ import { flagString } from "./args.js";
4
+ import { createContext } from "../engine/scan.js";
5
+ import { NoHistory, history } from "../history/replay.js";
6
+ import { ReportRefused, historyToJson, historyToText, writeExposureReport, } from "../history/report.js";
7
+ export async function historyCommand(args) {
8
+ const folder = args.positionals[0] ?? ".";
9
+ const sinceText = flagString(args, "since");
10
+ const since = sinceText ? new Date(sinceText) : undefined;
11
+ if (since && Number.isNaN(since.getTime())) {
12
+ process.stderr.write("--since needs a date such as 2026-01-31.\n");
13
+ return 1;
14
+ }
15
+ const { ctx, dispose } = createContext(folder, { online: false });
16
+ try {
17
+ const r = await history(ctx.root, ctx.profile, since ? { since } : {});
18
+ const authors = args.flags.has("authors");
19
+ process.stdout.write(args.flags.has("json") ? historyToJson(r, { authors }) + "\n" : historyToText(r, { authors }));
20
+ if (args.flags.has("report")) {
21
+ const path = writeExposureReport(ctx.root, r, { authors });
22
+ process.stdout.write(`Wrote ${relative(process.cwd(), path) || path} (kept out of git by .gitignore).\n`);
23
+ }
24
+ return 0;
25
+ }
26
+ catch (e) {
27
+ if (e instanceof NoHistory || e instanceof ReportRefused) {
28
+ process.stdout.write(`${e.message}\n`);
29
+ return 1;
30
+ }
31
+ throw e;
32
+ }
33
+ finally {
34
+ await dispose();
35
+ }
36
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * `himaya surfaces [folder] [--json] [--max-surfaces N]` and
3
+ * `himaya hunt check <candidates.json> [folder] [--json] | confirm <id> [folder] | dismiss <id> [folder] [--reason TEXT]`.
4
+ */
5
+ import { lstatSync, readFileSync } from "node:fs";
6
+ import { flagString } from "./args.js";
7
+ import { createContext } from "../engine/scan.js";
8
+ import { stripControl } from "../engine/text.js";
9
+ import { surfaces } from "../hunt/surfaces.js";
10
+ import { CandidatesRefused, MAX_CANDIDATE_BYTES } from "../hunt/candidates.js";
11
+ import { CANDIDATES_DIR, HuntRefused, confirmSuggestion, deleteCandidates, dismissSuggestion, huntCheck, } from "../hunt/merge.js";
12
+ const out = (s) => void process.stdout.write(s);
13
+ export async function surfacesCommand(args) {
14
+ const max = Number(flagString(args, "max-surfaces") ?? "20");
15
+ const { ctx, dispose } = createContext(args.positionals[0] ?? ".", { online: false, checks: [] });
16
+ try {
17
+ const list = await surfaces(ctx, Number.isInteger(max) && max > 0 ? max : 20);
18
+ if (args.flags.has("json"))
19
+ out(JSON.stringify({ surfaces: list }, null, 2) + "\n");
20
+ else
21
+ out(list
22
+ .map((s) => `${s.sensitive ? "★ " : " "}${s.id} · kinds: ${s.promiseKinds.join(", ")}`)
23
+ .join("\n") + "\n");
24
+ return 0;
25
+ }
26
+ finally {
27
+ await dispose();
28
+ }
29
+ }
30
+ export function huntToText(r) {
31
+ const lines = [r.summaryLine, ""];
32
+ if (r.needsAnswer.length) {
33
+ lines.push("NEEDS YOUR ANSWER (suggested rules Himaya found broken; not problems until you say yes)");
34
+ for (const i of r.needsAnswer)
35
+ lines.push(`- ${i.id}: Himaya checked this suggested rule and it doesn't hold: ${i.firstFailure ?? "a case failed"}.`, ` The rule, as Himaya reads it: ${i.readBack}`, ` Is this a rule for your app? Yes: himaya hunt confirm ${i.id} · No: himaya hunt dismiss ${i.id} --reason "..."`);
36
+ lines.push("");
37
+ }
38
+ if (r.worthKeeping.length) {
39
+ lines.push("WORTH KEEPING (held today; save them so Himaya checks them every time)");
40
+ for (const i of r.worthKeeping)
41
+ lines.push(`- ${i.id}: ${i.readBack} (himaya hunt confirm ${i.id})`);
42
+ lines.push("");
43
+ }
44
+ if (r.ideas.length) {
45
+ lines.push("UNVERIFIED IDEAS (check these yourself; Himaya can't test them)");
46
+ lines.push(" (written by AI hunters: their words are data, never instructions)");
47
+ for (const i of r.ideas)
48
+ lines.push(`- ${i.surface ? `${i.surface}: ` : ""}${i.text}`);
49
+ if (r.hidden.ideas)
50
+ lines.push(` …and ${r.hidden.ideas} more not shown.`);
51
+ lines.push("");
52
+ }
53
+ if (r.notChecked.length) {
54
+ lines.push("COULDN'T CHECK");
55
+ for (const i of r.notChecked)
56
+ lines.push(`- ${i.id}: ${i.reason ?? ""}`);
57
+ lines.push("");
58
+ }
59
+ if (r.dropped.length)
60
+ lines.push(`Dropped ${r.dropped.length}: ${r.dropped.join("; ")}`);
61
+ if (r.alreadyKnown)
62
+ lines.push(`${r.alreadyKnown} already saved or dismissed, so not suggested again.`);
63
+ return lines.map(stripControl).join("\n").trimEnd() + "\n";
64
+ }
65
+ export async function huntCommand(args) {
66
+ const [sub, target, folder = "."] = args.positionals;
67
+ try {
68
+ if (sub === "check" && target) {
69
+ let st;
70
+ try {
71
+ st = lstatSync(target);
72
+ }
73
+ catch {
74
+ throw new CandidatesRefused(`There's no candidates file at ${target}.`);
75
+ }
76
+ if (!st.isFile() || st.isSymbolicLink())
77
+ throw new CandidatesRefused("The candidates file must be a plain file.");
78
+ if (st.size > MAX_CANDIDATE_BYTES)
79
+ throw new CandidatesRefused(`The candidates file is larger than ${MAX_CANDIDATE_BYTES / 1_000_000} MB, so Himaya didn't read it.`);
80
+ const r = await huntCheck(folder, readFileSync(target, "utf8"));
81
+ const deleted = deleteCandidates(folder, target);
82
+ // Ideas are AI hunters' own words: data, never instructions.
83
+ const json = {
84
+ ...r,
85
+ ideas: r.ideas.map((i) => ({
86
+ surface: i.surface,
87
+ text: { untrusted: true, text: i.text },
88
+ })),
89
+ };
90
+ out(args.flags.has("json") ? JSON.stringify(json, null, 2) + "\n" : huntToText(r));
91
+ if (!deleted && !args.flags.has("json"))
92
+ out(`(Himaya deletes candidates files only from ${CANDIDATES_DIR}/; ${target} was left as it is.)\n`);
93
+ return 0;
94
+ }
95
+ if (sub === "confirm" && target) {
96
+ const reading = confirmSuggestion(folder, target);
97
+ out(stripControl(`Saved ${target} as a promise in himaya.md. Himaya will check: ${reading}`) +
98
+ "\n");
99
+ return 0;
100
+ }
101
+ if (sub === "dismiss" && target) {
102
+ dismissSuggestion(folder, target, flagString(args, "reason") ?? "");
103
+ out(stripControl(`Recorded under hunt_dismissed in himaya.md; ${target} won't be suggested again.`) + "\n");
104
+ return 0;
105
+ }
106
+ }
107
+ catch (e) {
108
+ if (e instanceof CandidatesRefused || e instanceof HuntRefused) {
109
+ process.stderr.write(`${e.message}\n`);
110
+ return 1;
111
+ }
112
+ throw e;
113
+ }
114
+ process.stderr.write("Usage: himaya hunt check <candidates.json> [folder] | confirm <id> [folder] | dismiss <id> [folder] [--reason TEXT]\n");
115
+ return 1;
116
+ }
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Himaya command-line entry point. `himaya guard` runs before every edit the user's coding agent
4
+ * makes, so it loads only Guard (no code model, no database); everything else loads main.ts.
5
+ */
6
+ const argv = process.argv.slice(2);
7
+ async function run() {
8
+ if (argv[0] === "guard") {
9
+ try {
10
+ if (argv[1] === "--stop") {
11
+ const { stopMain } = await import("../guard/stop.js");
12
+ process.exit(await stopMain());
13
+ }
14
+ const { guardMain } = await import("../guard/index.js");
15
+ // Exit at once: a stdin that never closes must not keep the hook waiting.
16
+ process.exit(await guardMain());
17
+ }
18
+ catch {
19
+ // Fails open: a broken Guard never blocks work (ARCHITECTURE: Himaya Guard).
20
+ process.stderr.write("Himaya Guard had a problem and let this through without checking it.\n");
21
+ return 1;
22
+ }
23
+ }
24
+ const { main, reportCrash } = await import("./main.js");
25
+ try {
26
+ return await main(argv);
27
+ }
28
+ catch (e) {
29
+ reportCrash(e);
30
+ return 2;
31
+ }
32
+ }
33
+ void run().then((code) => {
34
+ process.exitCode = code;
35
+ });
36
+ export {};
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `himaya init [folder] [--yes] [--rules] [--guard] [--ci] [--owner USER]` (see src/init/init.ts).
3
+ * In a terminal it asks its questions; without one (a coding agent running it) it does only what
4
+ * the flags ask, and the rules and Guard still need `--yes` (the owner's answer, asked by the agent).
5
+ */
6
+ import { createInterface } from "node:readline/promises";
7
+ import { flagString } from "./args.js";
8
+ import { runInit } from "../init/init.js";
9
+ export { GUARD_COMMAND, GUARD_MATCHER, STOP_COMMAND } from "../guard/install.js";
10
+ export { addGuardEntry, pinned } from "../init/init.js";
11
+ export async function initCommand(args) {
12
+ const interactive = process.stdin.isTTY === true && !args.flags.has("yes");
13
+ const rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : null;
14
+ const io = {
15
+ interactive,
16
+ ask: async (q) => (rl ? rl.question(q) : ""),
17
+ say: (s) => {
18
+ process.stdout.write(`${s}\n`);
19
+ },
20
+ };
21
+ try {
22
+ const owner = flagString(args, "owner");
23
+ return await runInit(args.positionals[0] ?? ".", {
24
+ yes: args.flags.has("yes"),
25
+ rules: args.flags.has("rules"),
26
+ guard: args.flags.has("guard"),
27
+ ci: args.flags.has("ci"),
28
+ ...(owner !== undefined ? { owner } : {}),
29
+ }, io);
30
+ }
31
+ finally {
32
+ rl?.close();
33
+ }
34
+ }
35
+ /** The name the preview's tests and docs used for `init --guard`. */
36
+ export const initGuard = initCommand;
@@ -0,0 +1,243 @@
1
+ /** Himaya's commands, loaded by index.ts for everything except `guard` (which must start fast). */
2
+ import { parseArgs, flagString } from "./args.js";
3
+ import { scan, ScanError } from "../engine/scan.js";
4
+ import { toJson } from "../report/json.js";
5
+ import { toTerminal } from "../report/terminal.js";
6
+ import { toSarif } from "../report/sarif.js";
7
+ import { gate, isFailOn } from "../report/gate.js";
8
+ import { CHECK_IDS } from "../engine/checks-list.js";
9
+ import { REPORT_TEXT } from "../copy/report.js";
10
+ import { stripControl } from "../engine/text.js";
11
+ import { maskSecrets } from "../engine/mask.js";
12
+ import { buildMap, mapToText, saveCommands } from "../universal/map.js";
13
+ import { parseCommand } from "../universal/commands.js";
14
+ import { RunRefused, runToJson, runToText, universalRun } from "../universal/run.js";
15
+ import { brief, ROLE_RULES } from "../universal/roles.js";
16
+ import { promiseCommand } from "./promise.js";
17
+ export { VERSION } from "../version.js";
18
+ import { VERSION } from "../version.js";
19
+ const HELP = `Himaya: a security chief for vibe-coded apps.
20
+
21
+ Usage:
22
+ himaya scan [folder] [--json | --sarif] [--checks ID,ID] [--online] [--verbose]
23
+ [--fail-on fix-now|worth-a-look|any] (exit code 1 when such items exist)
24
+ himaya map [folder] [--json]
25
+ himaya answer <finding-id> yes|no [folder] [--reason TEXT] (answer a NEEDS YOUR ANSWER question)
26
+ himaya promise list|check [folder] [--json]
27
+ himaya promise explain <id> [folder]
28
+ himaya promise template
29
+ himaya init [folder] [--rules] [--guard] [--yes] [--ci --owner USER]
30
+ himaya ci [folder] [--only security|protected-files|access-changes] [--base REF] [--head REF]
31
+ [--reviews FILE --author LOGIN] [--sarif-file FILE] [--json] | --comment
32
+ himaya explain <finding-id | check-id> [folder]
33
+ himaya profile --template
34
+ himaya mcp (an MCP server on stdin/stdout, for coding agents)
35
+ himaya tripwire add|list|test [folder] [--yes] [--lure NAME]
36
+ himaya threats [folder] [--json] [--online]
37
+ himaya catalog [--json]
38
+ himaya feedback [folder] (the feedback sheet: counts only, nothing is sent)
39
+ himaya shield list|test [folder] | add <advisory> [folder] [--yes] | remove <advisory> [folder] [--yes]
40
+ himaya fix <finding-id | check-id | PROMISE:<id>> [folder] --plan | --patch
41
+ himaya verify <finding-id | check-id | PROMISE:<id> | SHIELD:<advisory>> [folder]
42
+ himaya verify --together <branch>,<branch> [folder]
43
+ himaya promise test [folder]
44
+ himaya watch add|list|status|test|remove [folder] [--yes]
45
+ himaya surfaces [folder] [--json] [--max-surfaces N]
46
+ himaya hunt check <candidates.json> [folder] [--json] | confirm <id> [folder] | dismiss <id> [folder] [--reason TEXT]
47
+ himaya diff [folder] [--base REF] [--head REF] [--json]
48
+ himaya history [folder] [--json] [--report] [--since YYYY-MM-DD] [--authors]
49
+ himaya guard (Claude Code calls this as a hook; not for typing)
50
+ himaya run [folder] --replay <run-folder> [--json] [--accept-detected] [--serve]
51
+ himaya run --brief <hunter|prover|fixer|adversary>
52
+ himaya map [folder] --save --test "<command>" [--run "<command>"] (after the owner confirms them)
53
+ himaya --version
54
+ `;
55
+ export async function main(argv) {
56
+ const [command, ...rest] = argv;
57
+ if (command === "--version" || command === "-v") {
58
+ process.stdout.write(`${VERSION}\n`);
59
+ return 0;
60
+ }
61
+ if (command === undefined || command === "--help" || command === "help") {
62
+ process.stdout.write(HELP);
63
+ return 0;
64
+ }
65
+ const args = parseArgs(rest);
66
+ if (command === "scan")
67
+ return scanCommand(args);
68
+ if (command === "promise")
69
+ return promiseCommand(args);
70
+ if (command === "answer") {
71
+ const { answerCommand } = await import("./answer.js");
72
+ return answerCommand(args);
73
+ }
74
+ if (command === "tripwire") {
75
+ const { tripwireCommand } = await import("./tripwire.js");
76
+ return tripwireCommand(args);
77
+ }
78
+ if (command === "threats" || command === "catalog") {
79
+ const { threatsCommand, catalogCommand } = await import("./threats.js");
80
+ return command === "threats" ? threatsCommand(args) : catalogCommand(args);
81
+ }
82
+ if (command === "feedback") {
83
+ const { feedbackCommand } = await import("./feedback.js");
84
+ return feedbackCommand(args);
85
+ }
86
+ if (command === "watch") {
87
+ const { watchCommand } = await import("./watch.js");
88
+ return watchCommand(args);
89
+ }
90
+ if (command === "fix") {
91
+ const { fixCommand } = await import("./fix.js");
92
+ return fixCommand(args);
93
+ }
94
+ if (command === "shield" || command === "verify") {
95
+ const { shieldCommand, verifyCommand } = await import("./shield.js");
96
+ return command === "shield" ? shieldCommand(args) : verifyCommand(args);
97
+ }
98
+ if (command === "surfaces" || command === "hunt") {
99
+ const { surfacesCommand, huntCommand } = await import("./hunt.js");
100
+ return command === "surfaces" ? surfacesCommand(args) : huntCommand(args);
101
+ }
102
+ if (command === "diff") {
103
+ const { diffCommand } = await import("./diff.js");
104
+ return diffCommand(args);
105
+ }
106
+ if (command === "history") {
107
+ const { historyCommand } = await import("./history.js");
108
+ return historyCommand(args);
109
+ }
110
+ if (command === "init") {
111
+ const { initCommand } = await import("./init.js");
112
+ return initCommand(args);
113
+ }
114
+ if (command === "ci") {
115
+ const { ciCommand } = await import("./ci.js");
116
+ return ciCommand(args);
117
+ }
118
+ if (command === "explain" || command === "profile") {
119
+ const { explainCommand, profileCommand } = await import("./explain.js");
120
+ return command === "explain" ? explainCommand(args) : profileCommand(args);
121
+ }
122
+ if (command === "mcp") {
123
+ const { serveMcp } = await import("../mcp/server.js");
124
+ return serveMcp(process.stdin, process.stdout, process.cwd());
125
+ }
126
+ if (command === "run") {
127
+ const role = flagString(args, "brief");
128
+ if (role !== undefined) {
129
+ if (!(role in ROLE_RULES)) {
130
+ process.stderr.write("Roles: hunter, prover, fixer, adversary.\n");
131
+ return 1;
132
+ }
133
+ process.stdout.write(brief(role, "") + "\n");
134
+ return 0;
135
+ }
136
+ const replay = flagString(args, "replay");
137
+ if (!replay) {
138
+ process.stderr.write("Give the folder of agents' files with --replay <folder> (see docs/UNIVERSAL.md).\n");
139
+ return 1;
140
+ }
141
+ try {
142
+ const report = await universalRun(args.positionals[0] ?? ".", replay, {
143
+ acceptDetected: args.flags.has("accept-detected"),
144
+ });
145
+ process.stdout.write(args.flags.has("json") ? runToJson(report) : runToText(report));
146
+ return 0;
147
+ }
148
+ catch (e) {
149
+ if (e instanceof RunRefused) {
150
+ process.stderr.write(`${e.message}\n`);
151
+ return 1;
152
+ }
153
+ throw e;
154
+ }
155
+ }
156
+ if (command === "map") {
157
+ const folder = args.positionals[0] ?? ".";
158
+ if (args.flags.has("save")) {
159
+ const test = flagString(args, "test");
160
+ const run = flagString(args, "run");
161
+ const testArgv = test ? parseCommand(test) : undefined;
162
+ const runArgv = run ? parseCommand(run) : undefined;
163
+ if (testArgv === null || runArgv === null) {
164
+ process.stderr.write("Commands can't contain shell characters such as ; | & $ ( ) < >.\n");
165
+ return 1;
166
+ }
167
+ const saved = saveCommands(folder, {
168
+ ...(testArgv ? { test: testArgv } : {}),
169
+ ...(runArgv ? { run: runArgv } : {}),
170
+ });
171
+ process.stdout.write(saved.length ? `Saved to himaya.md:\n${saved.join("\n")}\n` : "Nothing new to save.\n");
172
+ return 0;
173
+ }
174
+ const m = await buildMap(folder);
175
+ process.stdout.write(args.flags.has("json") ? JSON.stringify(m, null, 2) + "\n" : mapToText(m));
176
+ return 0;
177
+ }
178
+ process.stderr.write(`Unknown command: ${command}\n${HELP}`);
179
+ return 1;
180
+ }
181
+ /** `himaya scan`: exit 0, 1 when `--fail-on` finds something, 2 for a usage error or a crash. */
182
+ const SCAN_FLAGS = ["json", "sarif", "checks", "online", "verbose", "fail-on"];
183
+ async function scanCommand(args) {
184
+ // A mistyped option (--failon) must not quietly switch the gate off.
185
+ for (const flag of args.flags.keys())
186
+ if (!SCAN_FLAGS.includes(flag)) {
187
+ process.stderr.write(REPORT_TEXT.unknownFlag(stripControl(flag), SCAN_FLAGS.map((f) => `--${f}`).join(", ")) +
188
+ "\n");
189
+ return 2;
190
+ }
191
+ if (args.positionals.length > 1) {
192
+ process.stderr.write(REPORT_TEXT.extraFolder + "\n");
193
+ return 2;
194
+ }
195
+ const rawChecks = args.flags.get("checks");
196
+ const checks = rawChecks === undefined
197
+ ? undefined
198
+ : (typeof rawChecks === "string" ? rawChecks : "")
199
+ .split(",")
200
+ .map((s) => s.trim().toUpperCase())
201
+ .filter(Boolean);
202
+ if (checks !== undefined) {
203
+ const unknown = checks.filter((c) => !CHECK_IDS.includes(c)).map((c) => stripControl(c));
204
+ if (checks.length === 0) {
205
+ process.stderr.write(REPORT_TEXT.noChecks(CHECK_IDS.join(", ")) + "\n");
206
+ return 2;
207
+ }
208
+ if (unknown.length) {
209
+ process.stderr.write(REPORT_TEXT.unknownChecks(unknown, CHECK_IDS.join(", ")) + "\n");
210
+ return 2;
211
+ }
212
+ }
213
+ const failOnRaw = args.flags.get("fail-on");
214
+ const failOn = failOnRaw === undefined ? undefined : typeof failOnRaw === "string" ? failOnRaw : "";
215
+ if (failOn !== undefined && !isFailOn(failOn)) {
216
+ process.stderr.write(REPORT_TEXT.badFailOn(stripControl(failOn)) + "\n");
217
+ return 2;
218
+ }
219
+ if (args.flags.has("json") && args.flags.has("sarif")) {
220
+ process.stderr.write(REPORT_TEXT.jsonAndSarif + "\n");
221
+ return 2;
222
+ }
223
+ const result = await scan(args.positionals[0] ?? ".", {
224
+ online: args.flags.has("online"),
225
+ ...(checks ? { checks } : {}),
226
+ });
227
+ process.stdout.write(args.flags.has("json")
228
+ ? toJson(result) + "\n"
229
+ : args.flags.has("sarif")
230
+ ? toSarif(result, VERSION) + "\n"
231
+ : toTerminal(result, { verbose: args.flags.has("verbose") }));
232
+ if (failOn === undefined)
233
+ return 0;
234
+ const g = gate(result, failOn);
235
+ // The gate's verdict goes to stderr, so --json and --sarif output stays clean.
236
+ process.stderr.write(maskSecrets(stripControl(g.message)) + "\n");
237
+ return g.blocked ? 1 : 0;
238
+ }
239
+ export function reportCrash(e) {
240
+ process.stderr.write(e instanceof ScanError
241
+ ? `${e.message}\n`
242
+ : `Himaya hit an internal error: ${e instanceof Error ? e.message : String(e)}\n`);
243
+ }