envshed 0.18.0 → 0.20.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 (258) hide show
  1. package/README.md +1 -0
  2. package/bin/envshed.js +1 -1
  3. package/dist/agent/claude-code-hook.d.ts +9 -0
  4. package/dist/agent/claude-code-hook.d.ts.map +1 -0
  5. package/dist/agent/claude-code-hook.js +55 -0
  6. package/dist/agent/claude-code-hook.js.map +1 -0
  7. package/dist/agent/claude-code-hook.test.d.ts +2 -0
  8. package/dist/agent/claude-code-hook.test.d.ts.map +1 -0
  9. package/dist/agent/claude-code-hook.test.js +200 -0
  10. package/dist/agent/claude-code-hook.test.js.map +1 -0
  11. package/dist/agent/claude-code.d.ts +3 -0
  12. package/dist/agent/claude-code.d.ts.map +1 -0
  13. package/dist/agent/claude-code.js +206 -0
  14. package/dist/agent/claude-code.js.map +1 -0
  15. package/dist/agent/claude-code.test.d.ts +2 -0
  16. package/dist/agent/claude-code.test.d.ts.map +1 -0
  17. package/dist/agent/claude-code.test.js +302 -0
  18. package/dist/agent/claude-code.test.js.map +1 -0
  19. package/dist/agent/guard.d.ts +8 -0
  20. package/dist/agent/guard.d.ts.map +1 -0
  21. package/dist/agent/guard.js +361 -0
  22. package/dist/agent/guard.js.map +1 -0
  23. package/dist/agent/guard.test.d.ts +2 -0
  24. package/dist/agent/guard.test.d.ts.map +1 -0
  25. package/dist/agent/guard.test.js +271 -0
  26. package/dist/agent/guard.test.js.map +1 -0
  27. package/dist/agent/hook-main.d.ts +8 -0
  28. package/dist/agent/hook-main.d.ts.map +1 -0
  29. package/dist/agent/hook-main.js +45 -0
  30. package/dist/agent/hook-main.js.map +1 -0
  31. package/dist/agent/hook-messages.d.ts +7 -0
  32. package/dist/agent/hook-messages.d.ts.map +1 -0
  33. package/dist/agent/hook-messages.js +18 -0
  34. package/dist/agent/hook-messages.js.map +1 -0
  35. package/dist/agent/registry.d.ts +5 -0
  36. package/dist/agent/registry.d.ts.map +1 -0
  37. package/dist/agent/registry.js +6 -0
  38. package/dist/agent/registry.js.map +1 -0
  39. package/dist/agent/skill-content.d.ts +6 -0
  40. package/dist/agent/skill-content.d.ts.map +1 -0
  41. package/dist/agent/skill-content.js +62 -0
  42. package/dist/agent/skill-content.js.map +1 -0
  43. package/dist/agent/skill-content.test.d.ts +2 -0
  44. package/dist/agent/skill-content.test.d.ts.map +1 -0
  45. package/dist/agent/skill-content.test.js +15 -0
  46. package/dist/agent/skill-content.test.js.map +1 -0
  47. package/dist/agent/types.d.ts +35 -0
  48. package/dist/agent/types.d.ts.map +1 -0
  49. package/dist/agent/types.js +9 -0
  50. package/dist/agent/types.js.map +1 -0
  51. package/dist/commands/agent-session.d.ts +11 -0
  52. package/dist/commands/agent-session.d.ts.map +1 -0
  53. package/dist/commands/agent-session.js +300 -0
  54. package/dist/commands/agent-session.js.map +1 -0
  55. package/dist/commands/agent-session.test.d.ts +2 -0
  56. package/dist/commands/agent-session.test.d.ts.map +1 -0
  57. package/dist/commands/agent-session.test.js +381 -0
  58. package/dist/commands/agent-session.test.js.map +1 -0
  59. package/dist/commands/agent.d.ts +15 -0
  60. package/dist/commands/agent.d.ts.map +1 -0
  61. package/dist/commands/agent.js +114 -0
  62. package/dist/commands/agent.js.map +1 -0
  63. package/dist/commands/agent.test.d.ts +2 -0
  64. package/dist/commands/agent.test.d.ts.map +1 -0
  65. package/dist/commands/agent.test.js +132 -0
  66. package/dist/commands/agent.test.js.map +1 -0
  67. package/dist/commands/completions.d.ts.map +1 -1
  68. package/dist/commands/completions.js +37 -3
  69. package/dist/commands/completions.js.map +1 -1
  70. package/dist/commands/login.d.ts.map +1 -1
  71. package/dist/commands/login.js +42 -4
  72. package/dist/commands/login.js.map +1 -1
  73. package/dist/commands/login.test.js +55 -5
  74. package/dist/commands/login.test.js.map +1 -1
  75. package/dist/commands/pull.d.ts.map +1 -1
  76. package/dist/commands/pull.js +2 -1
  77. package/dist/commands/pull.js.map +1 -1
  78. package/dist/commands/request.d.ts +25 -0
  79. package/dist/commands/request.d.ts.map +1 -0
  80. package/dist/commands/request.js +157 -0
  81. package/dist/commands/request.js.map +1 -0
  82. package/dist/commands/request.test.d.ts +2 -0
  83. package/dist/commands/request.test.d.ts.map +1 -0
  84. package/dist/commands/request.test.js +177 -0
  85. package/dist/commands/request.test.js.map +1 -0
  86. package/dist/commands/run-redact.test.d.ts +2 -0
  87. package/dist/commands/run-redact.test.d.ts.map +1 -0
  88. package/dist/commands/run-redact.test.js +520 -0
  89. package/dist/commands/run-redact.test.js.map +1 -0
  90. package/dist/commands/run.d.ts +7 -1
  91. package/dist/commands/run.d.ts.map +1 -1
  92. package/dist/commands/run.js +167 -32
  93. package/dist/commands/run.js.map +1 -1
  94. package/dist/commands/run.test.js +227 -2
  95. package/dist/commands/run.test.js.map +1 -1
  96. package/dist/commands/scan.d.ts +9 -0
  97. package/dist/commands/scan.d.ts.map +1 -0
  98. package/dist/commands/scan.js +324 -0
  99. package/dist/commands/scan.js.map +1 -0
  100. package/dist/commands/scan.test.d.ts +2 -0
  101. package/dist/commands/scan.test.d.ts.map +1 -0
  102. package/dist/commands/scan.test.js +334 -0
  103. package/dist/commands/scan.test.js.map +1 -0
  104. package/dist/commands/token.d.ts.map +1 -1
  105. package/dist/commands/token.js +28 -11
  106. package/dist/commands/token.js.map +1 -1
  107. package/dist/commands/token.test.js +41 -7
  108. package/dist/commands/token.test.js.map +1 -1
  109. package/dist/commands/whoami.d.ts.map +1 -1
  110. package/dist/commands/whoami.js +8 -1
  111. package/dist/commands/whoami.js.map +1 -1
  112. package/dist/commands/whoami.test.js +16 -0
  113. package/dist/commands/whoami.test.js.map +1 -1
  114. package/dist/config-token.test.d.ts +2 -0
  115. package/dist/config-token.test.d.ts.map +1 -0
  116. package/dist/config-token.test.js +134 -0
  117. package/dist/config-token.test.js.map +1 -0
  118. package/dist/config.d.ts +16 -0
  119. package/dist/config.d.ts.map +1 -1
  120. package/dist/config.js +65 -3
  121. package/dist/config.js.map +1 -1
  122. package/dist/entry.d.ts +3 -0
  123. package/dist/entry.d.ts.map +1 -0
  124. package/dist/entry.js +15 -0
  125. package/dist/entry.js.map +1 -0
  126. package/dist/i18n.d.ts.map +1 -1
  127. package/dist/i18n.js +4 -16
  128. package/dist/i18n.js.map +1 -1
  129. package/dist/index.js +6 -0
  130. package/dist/index.js.map +1 -1
  131. package/dist/lib/agent-mode.d.ts +16 -0
  132. package/dist/lib/agent-mode.d.ts.map +1 -0
  133. package/dist/lib/agent-mode.js +24 -0
  134. package/dist/lib/agent-mode.js.map +1 -0
  135. package/dist/lib/agent-mode.test.d.ts +2 -0
  136. package/dist/lib/agent-mode.test.d.ts.map +1 -0
  137. package/dist/lib/agent-mode.test.js +35 -0
  138. package/dist/lib/agent-mode.test.js.map +1 -0
  139. package/dist/lib/agent-sessions.d.ts +37 -0
  140. package/dist/lib/agent-sessions.d.ts.map +1 -0
  141. package/dist/lib/agent-sessions.js +64 -0
  142. package/dist/lib/agent-sessions.js.map +1 -0
  143. package/dist/lib/allow-file.d.ts +21 -0
  144. package/dist/lib/allow-file.d.ts.map +1 -0
  145. package/dist/lib/allow-file.js +63 -0
  146. package/dist/lib/allow-file.js.map +1 -0
  147. package/dist/lib/allow-file.test.d.ts +2 -0
  148. package/dist/lib/allow-file.test.d.ts.map +1 -0
  149. package/dist/lib/allow-file.test.js +58 -0
  150. package/dist/lib/allow-file.test.js.map +1 -0
  151. package/dist/lib/command-spawn.d.ts +35 -0
  152. package/dist/lib/command-spawn.d.ts.map +1 -0
  153. package/dist/lib/command-spawn.js +67 -0
  154. package/dist/lib/command-spawn.js.map +1 -0
  155. package/dist/lib/command-spawn.process.test.d.ts +2 -0
  156. package/dist/lib/command-spawn.process.test.d.ts.map +1 -0
  157. package/dist/lib/command-spawn.process.test.js +43 -0
  158. package/dist/lib/command-spawn.process.test.js.map +1 -0
  159. package/dist/lib/command-spawn.test.d.ts +2 -0
  160. package/dist/lib/command-spawn.test.d.ts.map +1 -0
  161. package/dist/lib/command-spawn.test.js +80 -0
  162. package/dist/lib/command-spawn.test.js.map +1 -0
  163. package/dist/lib/duration.d.ts +3 -0
  164. package/dist/lib/duration.d.ts.map +1 -0
  165. package/dist/lib/duration.js +10 -0
  166. package/dist/lib/duration.js.map +1 -0
  167. package/dist/lib/duration.test.d.ts +2 -0
  168. package/dist/lib/duration.test.d.ts.map +1 -0
  169. package/dist/lib/duration.test.js +17 -0
  170. package/dist/lib/duration.test.js.map +1 -0
  171. package/dist/lib/env-format.d.ts +3 -0
  172. package/dist/lib/env-format.d.ts.map +1 -0
  173. package/dist/lib/env-format.js +20 -0
  174. package/dist/lib/env-format.js.map +1 -0
  175. package/dist/lib/history-clean.d.ts +42 -0
  176. package/dist/lib/history-clean.d.ts.map +1 -0
  177. package/dist/lib/history-clean.js +507 -0
  178. package/dist/lib/history-clean.js.map +1 -0
  179. package/dist/lib/history-clean.test.d.ts +2 -0
  180. package/dist/lib/history-clean.test.d.ts.map +1 -0
  181. package/dist/lib/history-clean.test.js +451 -0
  182. package/dist/lib/history-clean.test.js.map +1 -0
  183. package/dist/lib/history-scan.d.ts +108 -0
  184. package/dist/lib/history-scan.d.ts.map +1 -0
  185. package/dist/lib/history-scan.js +318 -0
  186. package/dist/lib/history-scan.js.map +1 -0
  187. package/dist/lib/history-scan.test.d.ts +2 -0
  188. package/dist/lib/history-scan.test.d.ts.map +1 -0
  189. package/dist/lib/history-scan.test.js +160 -0
  190. package/dist/lib/history-scan.test.js.map +1 -0
  191. package/dist/lib/keychain.d.ts +28 -0
  192. package/dist/lib/keychain.d.ts.map +1 -0
  193. package/dist/lib/keychain.js +87 -0
  194. package/dist/lib/keychain.js.map +1 -0
  195. package/dist/lib/keychain.test.d.ts +2 -0
  196. package/dist/lib/keychain.test.d.ts.map +1 -0
  197. package/dist/lib/keychain.test.js +128 -0
  198. package/dist/lib/keychain.test.js.map +1 -0
  199. package/dist/lib/locale-env.d.ts +3 -0
  200. package/dist/lib/locale-env.d.ts.map +1 -0
  201. package/dist/lib/locale-env.js +21 -0
  202. package/dist/lib/locale-env.js.map +1 -0
  203. package/dist/lib/oidc.d.ts +22 -0
  204. package/dist/lib/oidc.d.ts.map +1 -0
  205. package/dist/lib/oidc.js +84 -0
  206. package/dist/lib/oidc.js.map +1 -0
  207. package/dist/lib/oidc.test.d.ts +2 -0
  208. package/dist/lib/oidc.test.d.ts.map +1 -0
  209. package/dist/lib/oidc.test.js +107 -0
  210. package/dist/lib/oidc.test.js.map +1 -0
  211. package/dist/lib/redact.d.ts +60 -0
  212. package/dist/lib/redact.d.ts.map +1 -0
  213. package/dist/lib/redact.js +222 -0
  214. package/dist/lib/redact.js.map +1 -0
  215. package/dist/lib/redact.test.d.ts +2 -0
  216. package/dist/lib/redact.test.d.ts.map +1 -0
  217. package/dist/lib/redact.test.js +259 -0
  218. package/dist/lib/redact.test.js.map +1 -0
  219. package/dist/lib/redacted-output.d.ts +35 -0
  220. package/dist/lib/redacted-output.d.ts.map +1 -0
  221. package/dist/lib/redacted-output.js +155 -0
  222. package/dist/lib/redacted-output.js.map +1 -0
  223. package/dist/lib/secret-detector.d.ts +26 -0
  224. package/dist/lib/secret-detector.d.ts.map +1 -0
  225. package/dist/lib/secret-detector.js +332 -0
  226. package/dist/lib/secret-detector.js.map +1 -0
  227. package/dist/lib/secret-detector.test.d.ts +2 -0
  228. package/dist/lib/secret-detector.test.d.ts.map +1 -0
  229. package/dist/lib/secret-detector.test.js +207 -0
  230. package/dist/lib/secret-detector.test.js.map +1 -0
  231. package/dist/lib/shell-parse.d.ts +17 -0
  232. package/dist/lib/shell-parse.d.ts.map +1 -0
  233. package/dist/lib/shell-parse.js +191 -0
  234. package/dist/lib/shell-parse.js.map +1 -0
  235. package/dist/lib/shell-parse.test.d.ts +2 -0
  236. package/dist/lib/shell-parse.test.d.ts.map +1 -0
  237. package/dist/lib/shell-parse.test.js +41 -0
  238. package/dist/lib/shell-parse.test.js.map +1 -0
  239. package/dist/lib/token-input.d.ts +6 -0
  240. package/dist/lib/token-input.d.ts.map +1 -0
  241. package/dist/lib/token-input.js +42 -0
  242. package/dist/lib/token-input.js.map +1 -0
  243. package/dist/lib/token-input.test.d.ts +2 -0
  244. package/dist/lib/token-input.test.d.ts.map +1 -0
  245. package/dist/lib/token-input.test.js +38 -0
  246. package/dist/lib/token-input.test.js.map +1 -0
  247. package/dist/locales/en.json +222 -6
  248. package/dist/locales/es.json +219 -3
  249. package/dist/locales/pt-BR.json +219 -3
  250. package/dist/utils.d.ts +1 -1
  251. package/dist/utils.d.ts.map +1 -1
  252. package/dist/utils.js +5 -24
  253. package/dist/utils.js.map +1 -1
  254. package/dist/utils.test.js +14 -0
  255. package/dist/utils.test.js.map +1 -1
  256. package/package.json +7 -3
  257. package/dist/bin/envshed-linux-x64 +0 -4
  258. package/dist/bundle.cjs +0 -48909
@@ -0,0 +1,10 @@
1
+ const UNIT_SECONDS = { s: 1, m: 60, h: 3600, d: 86400 };
2
+ /** Parses `90s`, `10m`, `2h`, `1d` or bare seconds into seconds. Null if invalid. */
3
+ export function parseDurationSeconds(input) {
4
+ const match = /^(\d+)([smhd]?)$/.exec(input.trim());
5
+ if (!match)
6
+ return null;
7
+ const seconds = Number(match[1]) * UNIT_SECONDS[match[2] || "s"];
8
+ return seconds > 0 && Number.isSafeInteger(seconds) ? seconds : null;
9
+ }
10
+ //# sourceMappingURL=duration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duration.js","sourceRoot":"","sources":["../../src/lib/duration.ts"],"names":[],"mappings":"AAAA,MAAM,YAAY,GAA2B,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC;AAEhF,qFAAqF;AACrF,MAAM,UAAU,oBAAoB,CAAC,KAAa;IAChD,MAAM,KAAK,GAAG,kBAAkB,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IACpD,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC;IACxB,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;IACjE,OAAO,OAAO,GAAG,CAAC,IAAI,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;AACvE,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=duration.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duration.test.d.ts","sourceRoot":"","sources":["../../src/lib/duration.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { parseDurationSeconds } from "./duration.js";
3
+ describe("parseDurationSeconds", () => {
4
+ it.each([
5
+ ["90s", 90],
6
+ ["10m", 600],
7
+ ["2h", 7200],
8
+ ["1d", 86400],
9
+ ["45", 45],
10
+ ])("parses %s", (input, expected) => {
11
+ expect(parseDurationSeconds(input)).toBe(expected);
12
+ });
13
+ it.each(["", "0", "0m", "-5m", "10x", "1.5h", "soon"])("rejects %s", (input) => {
14
+ expect(parseDurationSeconds(input)).toBeNull();
15
+ });
16
+ });
17
+ //# sourceMappingURL=duration.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"duration.test.js","sourceRoot":"","sources":["../../src/lib/duration.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AAErD,QAAQ,CAAC,sBAAsB,EAAE,GAAG,EAAE;IACpC,EAAE,CAAC,IAAI,CAAC;QACN,CAAC,KAAK,EAAE,EAAE,CAAC;QACX,CAAC,KAAK,EAAE,GAAG,CAAC;QACZ,CAAC,IAAI,EAAE,IAAI,CAAC;QACZ,CAAC,IAAI,EAAE,KAAK,CAAC;QACb,CAAC,IAAI,EAAE,EAAE,CAAC;KACX,CAAC,CAAC,WAAW,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE;QAClC,MAAM,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACrD,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,YAAY,EAAE,CAAC,KAAK,EAAE,EAAE;QAC7E,MAAM,CAAC,oBAAoB,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC;IACjD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,3 @@
1
+ /** Emit the dotenv dialect without changing literal backslashes or quote characters. */
2
+ export declare function formatEnvAssignment(key: string, value: string): string;
3
+ //# sourceMappingURL=env-format.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env-format.d.ts","sourceRoot":"","sources":["../../src/lib/env-format.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAWtE"}
@@ -0,0 +1,20 @@
1
+ /** Emit the dotenv dialect without changing literal backslashes or quote characters. */
2
+ export function formatEnvAssignment(key, value) {
3
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
4
+ throw new Error("INVALID_SECRET_KEY");
5
+ if (value.includes("\r"))
6
+ throw new Error("ENV_VALUE_REQUIRES_JSON_FORMAT");
7
+ if (!/[\s#'"`]/.test(value))
8
+ return `${key}=${value}`;
9
+ // dotenv only expands backslash-n/r inside double quotes. Prefer single
10
+ // quotes/backticks for literal backslashes or embedded double quotes.
11
+ if (!value.includes('"') && !value.includes("\\"))
12
+ return `${key}="${value}"`;
13
+ if (!value.includes("'"))
14
+ return `${key}='${value}'`;
15
+ if (!value.includes("`"))
16
+ return `${key}=\`${value}\``;
17
+ // No lossless delimiter remains. Fail rather than export a changed secret.
18
+ throw new Error("ENV_VALUE_REQUIRES_JSON_FORMAT");
19
+ }
20
+ //# sourceMappingURL=env-format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env-format.js","sourceRoot":"","sources":["../../src/lib/env-format.ts"],"names":[],"mappings":"AAAA,wFAAwF;AACxF,MAAM,UAAU,mBAAmB,CAAC,GAAW,EAAE,KAAa;IAC5D,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;IACjF,IAAI,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;IAC5E,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC;IACtD,wEAAwE;IACxE,sEAAsE;IACtE,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC;QAAE,OAAO,GAAG,GAAG,KAAK,KAAK,GAAG,CAAC;IAC9E,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,GAAG,KAAK,KAAK,GAAG,CAAC;IACrD,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,GAAG,MAAM,KAAK,IAAI,CAAC;IACvD,2EAA2E;IAC3E,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;AACpD,CAAC"}
@@ -0,0 +1,42 @@
1
+ import { type ReadOptions, type ValueMatcher } from "./history-scan.js";
2
+ import { type DetectOptions } from "./secret-detector.js";
3
+ export type CleanErrorCode = "no-keychain" | "no-backup" | "bad-id" | "key-missing" | "backup-corrupt";
4
+ /** Carries a code only, so it can never carry file content. */
5
+ export declare class CleanError extends Error {
6
+ readonly code: CleanErrorCode;
7
+ constructor(code: CleanErrorCode);
8
+ }
9
+ export interface CleanContext {
10
+ matcher: ValueMatcher;
11
+ detect: DetectOptions;
12
+ read?: ReadOptions;
13
+ }
14
+ export declare function cleanText(text: string, context: CleanContext): string;
15
+ /** Rewrites only string content, so everything else on the line keeps its exact bytes. */
16
+ export declare function cleanLine(bytes: Buffer, context: CleanContext): Buffer;
17
+ export interface CleanResult {
18
+ backupId: string | null;
19
+ cleaned: Array<{
20
+ file: string;
21
+ lines: number;
22
+ }>;
23
+ /** The file changed while being processed, usually a session still in use. */
24
+ busy: string[];
25
+ failed: string[];
26
+ }
27
+ export declare function cleanFiles(files: string[], backupDir: string, context: CleanContext): Promise<CleanResult>;
28
+ export interface UndoResult {
29
+ backupId: string;
30
+ restoredFiles: string[];
31
+ restoredLines: number;
32
+ /** Lines edited since the clean, or files gone. Left as they are; the backup is kept. */
33
+ conflicts: Array<{
34
+ file: string;
35
+ lines: number;
36
+ }>;
37
+ }
38
+ /** Restores the lines of one backup, or the newest. Newer lines appended to a file are kept. */
39
+ export declare function undoClean(backupDir: string, requestedId?: string, read?: ReadOptions): Promise<UndoResult>;
40
+ /** Deletes every backup and its key. After this, a clean cannot be undone. */
41
+ export declare function forgetBackups(backupDir: string): number;
42
+ //# sourceMappingURL=history-clean.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history-clean.d.ts","sourceRoot":"","sources":["../../src/lib/history-clean.ts"],"names":[],"mappings":"AAIA,OAAO,EAML,KAAK,WAAW,EAChB,KAAK,YAAY,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAsB,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAc9E,MAAM,MAAM,cAAc,GAAG,aAAa,GAAG,WAAW,GAAG,QAAQ,GAAG,aAAa,GAAG,gBAAgB,CAAC;AAEvG,+DAA+D;AAC/D,qBAAa,UAAW,SAAQ,KAAK;aACP,IAAI,EAAE,cAAc;gBAApB,IAAI,EAAE,cAAc;CAGjD;AAwID,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,YAAY,CAAC;IACtB,MAAM,EAAE,aAAa,CAAC;IACtB,IAAI,CAAC,EAAE,WAAW,CAAC;CACpB;AAED,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,MAAM,CA+BrE;AASD,0FAA0F;AAC1F,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,MAAM,CAuBtE;AAgMD,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAChD,8EAA8E;IAC9E,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,MAAM,EAAE,MAAM,EAAE,CAAC;CAClB;AAED,wBAAsB,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CA8BhH;AAaD,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,EAAE,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,yFAAyF;IACzF,SAAS,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACnD;AA+CD,gGAAgG;AAChG,wBAAsB,SAAS,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAmBhH;AAOD,8EAA8E;AAC9E,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CASvD"}
@@ -0,0 +1,507 @@
1
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { keychainDelete, keychainGet, keychainSet } from "./keychain.js";
5
+ import { decodeToken, forEachStringToken, isJsonLine, readLines, TEMP_FILE_MARKER, } from "./history-scan.js";
6
+ import { detectKnownFormats } from "./secret-detector.js";
7
+ /**
8
+ * Removes found values from history files and can put them back. The original
9
+ * lines live only in a backup encrypted with AES-256-GCM, under a random key held
10
+ * by the OS keychain. With no keychain there is no clean: a key stored beside the
11
+ * backup would make it a plaintext copy with extra steps.
12
+ */
13
+ const MAGIC = Buffer.from("ENVSHEDBK1\n");
14
+ const ID_PATTERN = /^\d{8}T\d{6}-[0-9a-f]{8}$/;
15
+ const IV_BYTES = 12;
16
+ const TAG_BYTES = 16;
17
+ /** Carries a code only, so it can never carry file content. */
18
+ export class CleanError extends Error {
19
+ code;
20
+ constructor(code) {
21
+ super(code);
22
+ this.code = code;
23
+ }
24
+ }
25
+ const accountFor = (id) => `scan-backup-${id}`;
26
+ const backupPath = (dir, id) => path.join(dir, `${id}.bak`);
27
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
28
+ const tempPathFor = (file) => `${file}${TEMP_FILE_MARKER}${randomBytes(4).toString("hex")}`;
29
+ function newBackupId() {
30
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").slice(0, 15);
31
+ return `${stamp}-${randomBytes(4).toString("hex")}`;
32
+ }
33
+ class BackupWriter {
34
+ id;
35
+ key;
36
+ file;
37
+ handle;
38
+ frames = 0;
39
+ constructor(id, key, file, handle) {
40
+ this.id = id;
41
+ this.key = key;
42
+ this.file = file;
43
+ this.handle = handle;
44
+ }
45
+ /** Stores the key first. Nothing has been touched yet if that fails. */
46
+ static async create(dir) {
47
+ const id = newBackupId();
48
+ const key = randomBytes(32);
49
+ if (!keychainSet(accountFor(id), key.toString("hex")))
50
+ throw new CleanError("no-keychain");
51
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
52
+ fs.chmodSync(dir, 0o700);
53
+ const file = backupPath(dir, id);
54
+ const handle = await fs.promises.open(file, "wx", 0o600);
55
+ await handle.write(MAGIC);
56
+ return new BackupWriter(id, key, file, handle);
57
+ }
58
+ /** Durable before it returns: the caller only rewrites the history file afterwards. */
59
+ async append(frame) {
60
+ const iv = randomBytes(IV_BYTES);
61
+ const cipher = createCipheriv("aes-256-gcm", this.key, iv);
62
+ cipher.setAAD(Buffer.from(`${this.id}:${this.frames}`));
63
+ const body = Buffer.concat([cipher.update(JSON.stringify(frame), "utf8"), cipher.final()]);
64
+ const length = Buffer.alloc(4);
65
+ length.writeUInt32BE(body.length);
66
+ await this.handle.write(Buffer.concat([length, iv, cipher.getAuthTag(), body]));
67
+ await this.handle.sync();
68
+ this.frames++;
69
+ }
70
+ /** Returns whether a backup was kept. An empty one is removed along with its key. */
71
+ async finish() {
72
+ await this.handle.close();
73
+ if (this.frames > 0)
74
+ return true;
75
+ fs.rmSync(this.file, { force: true });
76
+ keychainDelete(accountFor(this.id));
77
+ return false;
78
+ }
79
+ }
80
+ function readFrames(file, id, key) {
81
+ const data = fs.readFileSync(file);
82
+ if (!data.subarray(0, MAGIC.length).equals(MAGIC))
83
+ throw new CleanError("backup-corrupt");
84
+ const frames = [];
85
+ let at = MAGIC.length;
86
+ const header = 4 + IV_BYTES + TAG_BYTES;
87
+ // A cut-off last frame is what a crash mid-write leaves. Its file was never rewritten.
88
+ while (at + header <= data.length) {
89
+ const length = data.readUInt32BE(at);
90
+ if (at + header + length > data.length)
91
+ break;
92
+ const iv = data.subarray(at + 4, at + 4 + IV_BYTES);
93
+ const tag = data.subarray(at + 4 + IV_BYTES, at + header);
94
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
95
+ decipher.setAAD(Buffer.from(`${id}:${frames.length}`));
96
+ decipher.setAuthTag(tag);
97
+ try {
98
+ const plain = Buffer.concat([decipher.update(data.subarray(at + header, at + header + length)), decipher.final()]);
99
+ frames.push(JSON.parse(plain.toString("utf8")));
100
+ }
101
+ catch {
102
+ throw new CleanError("backup-corrupt");
103
+ }
104
+ at += header + length;
105
+ }
106
+ return frames;
107
+ }
108
+ /** Overlapping spans become one, named after the one that starts first and runs longest. */
109
+ function applySpans(text, spans) {
110
+ const merged = [];
111
+ for (const span of [...spans].sort((a, b) => a.start - b.start || b.end - a.end)) {
112
+ const last = merged[merged.length - 1];
113
+ if (last && span.start < last.end)
114
+ last.end = Math.max(last.end, span.end);
115
+ else
116
+ merged.push({ ...span });
117
+ }
118
+ let result = "";
119
+ let at = 0;
120
+ for (const span of merged) {
121
+ result += `${text.slice(at, span.start)}[ENVSHED:${span.label}]`;
122
+ at = span.end;
123
+ }
124
+ return result + text.slice(at);
125
+ }
126
+ /** Where the END marker at or after `from` finishes, or -1. Works on text and on bytes alike. */
127
+ function keyEndAfter(text, from) {
128
+ const marker = text.indexOf("-----END ", from);
129
+ if (marker === -1)
130
+ return -1;
131
+ const close = text.indexOf("-----", marker + 9);
132
+ return close === -1 ? -1 : close + 5;
133
+ }
134
+ /** The `private-key` rule stops at the header. The body is the secret, so the span runs through the END marker. */
135
+ function formatSpanEnd(text, rule, end) {
136
+ if (rule !== "private-key")
137
+ return end;
138
+ const close = keyEndAfter(text, end);
139
+ return close === -1 ? text.length : close;
140
+ }
141
+ export function cleanText(text, context) {
142
+ const { matcher, detect } = context;
143
+ let result = text;
144
+ if (!matcher.isEmpty) {
145
+ const bytes = Buffer.from(result, "utf8");
146
+ const raw = [];
147
+ matcher.scan(bytes, 0, (pattern, end) => {
148
+ const info = matcher.patterns[pattern];
149
+ raw.push({ start: end - info.length, end, label: info.owners[0].key });
150
+ });
151
+ if (raw.length > 0) {
152
+ // Patterns are valid UTF-8, so both ends fall on character boundaries.
153
+ const toChars = (offset) => bytes.subarray(0, offset).toString("utf8").length;
154
+ result = applySpans(result, raw.map((span) => ({ start: toChars(span.start), end: toChars(span.end), label: span.label })));
155
+ }
156
+ }
157
+ const findings = detectKnownFormats(result, detect);
158
+ if (findings.length > 0) {
159
+ // Detector offsets refer to the NFC form. The original line is in the backup either way.
160
+ const normalized = result.normalize("NFC");
161
+ result = applySpans(normalized, findings.map((f) => ({ start: f.start, end: formatSpanEnd(normalized, f.rule, f.end), label: f.rule })));
162
+ }
163
+ return result;
164
+ }
165
+ /**
166
+ * The body of this key is in other strings, such as an array with one line per string.
167
+ * Those cannot be told from ordinary strings, so the header stays and the re-scan
168
+ * goes on reporting the key. Rewriting it alone would make the file look clean.
169
+ */
170
+ const KEY_HEADER_ENDS_STRING = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----\s*$/;
171
+ /** Rewrites only string content, so everything else on the line keeps its exact bytes. */
172
+ export function cleanLine(bytes, context) {
173
+ const text = bytes.toString("utf8");
174
+ if (!Buffer.from(text, "utf8").equals(bytes))
175
+ return bytes; // not UTF-8, so left alone and reported by the re-scan
176
+ if (!isJsonLine(text)) {
177
+ const cleaned = cleanText(text, context);
178
+ return cleaned === text ? bytes : Buffer.from(cleaned, "utf8");
179
+ }
180
+ let result = "";
181
+ let at = 0;
182
+ forEachStringToken(text, (start, end) => {
183
+ // `at` only moves past tokens that changed, so the bytes between stay exact.
184
+ const decoded = decodeToken(text.slice(start, end));
185
+ if (decoded === null || KEY_HEADER_ENDS_STRING.test(decoded))
186
+ return;
187
+ const cleaned = cleanText(decoded, context);
188
+ if (cleaned === decoded)
189
+ return;
190
+ result += text.slice(at, start) + JSON.stringify(cleaned);
191
+ at = end;
192
+ });
193
+ if (at === 0)
194
+ return bytes;
195
+ result += text.slice(at);
196
+ return isJsonLine(result) ? Buffer.from(result, "utf8") : bytes;
197
+ }
198
+ /** A key longer than this is not one: the header was only mentioned. */
199
+ const MAX_KEY_LINES = 1024;
200
+ /** A run this long at the end of a line is key material even with no END marker to confirm it. */
201
+ const MIN_KEY_RUN = 16;
202
+ /** An RFC 1421 header inside an encrypted key, such as `DEK-Info: AES-128-CBC,ABCDEF`. */
203
+ const KEY_PEM_HEADER = /^[A-Za-z][A-Za-z-]*: \S/;
204
+ /**
205
+ * Whether a line could sit inside a key, and whether it is plainly key material.
206
+ * A long run counts behind any prefix, such as a log prefix. A short one, the last
207
+ * line of a body, must be the whole line after a line number or end in padding.
208
+ * Prose ending in a word is neither, so a header that was only mentioned wipes nothing.
209
+ */
210
+ function keyLineShape(text) {
211
+ const tail = text.slice(-256).trim();
212
+ const run = /[A-Za-z0-9+/=]*$/.exec(tail)?.[0] ?? "";
213
+ const material = run.length >= MIN_KEY_RUN;
214
+ const bare = tail.replace(/^\d+[\t\u2192:|]\s*/, "");
215
+ const possible = tail === "" || material || run.endsWith("=") || /^[A-Za-z0-9+/=]+$/.test(bare) || KEY_PEM_HEADER.test(bare);
216
+ return { possible, material };
217
+ }
218
+ /** Whether this line leaves a key open: a header whose END marker is not on the line. */
219
+ function opensKey(bytes, detect) {
220
+ if (!bytes.includes("-----BEGIN "))
221
+ return false;
222
+ const text = bytes.toString("utf8");
223
+ if (!Buffer.from(text, "utf8").equals(bytes) || isJsonLine(text))
224
+ return false; // cleanLine leaves the header as it is
225
+ const normalized = text.normalize("NFC");
226
+ const last = detectKnownFormats(text, detect).filter((finding) => finding.rule === "private-key").pop();
227
+ return last !== undefined && keyEndAfter(normalized, last.end) === -1;
228
+ }
229
+ /**
230
+ * Finds what one line at a time cannot see, using the same continuous match as the
231
+ * scan: vault values with a newline in them, and the lines of a key after its header.
232
+ * Holds offsets only, never content.
233
+ */
234
+ async function findMultilineCuts(file, context) {
235
+ const { matcher, detect, read } = context;
236
+ const ranges = [];
237
+ const keepLines = new Set();
238
+ const oversized = [];
239
+ const newline = Buffer.from("\n");
240
+ // `start` is where the lines after the header begin, `end` where the last line known to be key material finishes.
241
+ let key = null;
242
+ const closeKey = () => {
243
+ if (key && key.end > key.start)
244
+ ranges.push({ start: key.start, end: key.end, label: "private-key" });
245
+ key = null;
246
+ };
247
+ let offset = 0;
248
+ let state = 0;
249
+ for await (const piece of readLines(file, read)) {
250
+ const { bytes } = piece;
251
+ const pieceStart = offset;
252
+ const pieceEnd = offset + bytes.length;
253
+ const hasNewline = piece.type !== "fragment" && piece.newline;
254
+ offset = pieceEnd + (hasNewline ? 1 : 0);
255
+ if (!matcher.isEmpty) {
256
+ const hit = (pattern, end) => {
257
+ const info = matcher.patterns[pattern];
258
+ const start = end - info.length;
259
+ if (start < pieceStart || end > pieceEnd)
260
+ ranges.push({ start, end, label: info.owners[0].key });
261
+ };
262
+ state = matcher.scan(bytes, state, (pattern, end) => hit(pattern, pieceStart + end));
263
+ if (hasNewline)
264
+ state = matcher.scan(newline, state, (pattern) => hit(pattern, pieceEnd + 1));
265
+ }
266
+ if (piece.type !== "line") {
267
+ oversized.push([pieceStart, pieceEnd]);
268
+ if (key)
269
+ keepLines.add(key.header);
270
+ key = null;
271
+ continue;
272
+ }
273
+ if (key) {
274
+ const close = keyEndAfter(bytes, 0);
275
+ const text = bytes.toString("utf8");
276
+ const shape = keyLineShape(text);
277
+ if (close !== -1 && !isJsonLine(text)) {
278
+ key.end = pieceStart + close;
279
+ closeKey();
280
+ }
281
+ else if (text.trim() === "" || (shape.possible && !isJsonLine(text))) {
282
+ if (shape.material)
283
+ key.end = pieceEnd;
284
+ if (++key.lines > MAX_KEY_LINES)
285
+ closeKey();
286
+ }
287
+ else {
288
+ closeKey();
289
+ }
290
+ }
291
+ if (!key && hasNewline && opensKey(bytes, detect)) {
292
+ key = { header: pieceStart, start: pieceEnd + 1, end: pieceEnd + 1, lines: 0 };
293
+ }
294
+ }
295
+ closeKey();
296
+ // An oversized line is written back as it is, so a value running through one stays whole for the re-scan.
297
+ const kept = ranges.filter((range) => !oversized.some(([start, end]) => range.start < end && start < range.end));
298
+ const merged = [];
299
+ for (const range of kept.sort((a, b) => a.start - b.start || b.end - a.end)) {
300
+ const last = merged[merged.length - 1];
301
+ if (last && range.start < last.end)
302
+ last.end = Math.max(last.end, range.end);
303
+ else
304
+ merged.push({ ...range });
305
+ }
306
+ return { ranges: merged, keepLines };
307
+ }
308
+ /**
309
+ * Replaces the parts of a line inside `ranges` (sorted). Every touched line keeps a
310
+ * marker and so stays a line: undo finds lines by number, and an empty last line
311
+ * with no newline would not be read back at all.
312
+ */
313
+ function cutLine(bytes, lineStart, ranges, from) {
314
+ const lineEnd = lineStart + bytes.length;
315
+ const parts = [];
316
+ let at = 0;
317
+ for (let i = from; i < ranges.length && ranges[i].start < lineEnd; i++) {
318
+ const start = Math.max(ranges[i].start - lineStart, 0);
319
+ const end = Math.min(ranges[i].end - lineStart, bytes.length);
320
+ if (end <= start)
321
+ continue;
322
+ parts.push(bytes.subarray(at, start), Buffer.from(`[ENVSHED:${ranges[i].label}]`));
323
+ at = end;
324
+ }
325
+ if (parts.length === 0)
326
+ return null;
327
+ parts.push(bytes.subarray(at));
328
+ return Buffer.concat(parts);
329
+ }
330
+ async function replaceFile(temp, file, stat) {
331
+ await fs.promises.utimes(temp, stat.atime, stat.mtime); // tools sort sessions by this date
332
+ await fs.promises.rename(temp, file);
333
+ }
334
+ const isUnchanged = (file, stat) => {
335
+ const now = fs.statSync(file);
336
+ return now.size === stat.size && now.mtimeMs === stat.mtimeMs;
337
+ };
338
+ async function writeCleanedCopy(file, temp, mode, context) {
339
+ const changes = [];
340
+ const { ranges, keepLines } = await findMultilineCuts(file, context);
341
+ const handle = await fs.promises.open(temp, "wx", mode);
342
+ try {
343
+ let index = 0;
344
+ let offset = 0;
345
+ let nextRange = 0;
346
+ for await (const piece of readLines(file, context.read)) {
347
+ const lineStart = offset;
348
+ offset += piece.bytes.length + (piece.type !== "fragment" && piece.newline ? 1 : 0);
349
+ // An oversized line cannot be parsed in memory, so it stays and the re-scan reports it.
350
+ if (piece.type === "fragment") {
351
+ await handle.write(piece.bytes);
352
+ continue;
353
+ }
354
+ let output = piece.bytes;
355
+ if (piece.type === "line" && !keepLines.has(lineStart)) {
356
+ while (nextRange < ranges.length && ranges[nextRange].end <= lineStart)
357
+ nextRange++;
358
+ const cut = cutLine(piece.bytes, lineStart, ranges, nextRange);
359
+ output = cleanLine(cut ?? piece.bytes, context);
360
+ if (output !== piece.bytes) {
361
+ changes.push({ i: index, original: piece.bytes.toString("base64"), cleaned: sha256(output) });
362
+ }
363
+ }
364
+ await handle.write(output);
365
+ if (piece.newline)
366
+ await handle.write("\n");
367
+ index++;
368
+ }
369
+ await handle.sync();
370
+ }
371
+ finally {
372
+ await handle.close();
373
+ }
374
+ return changes;
375
+ }
376
+ export async function cleanFiles(files, backupDir, context) {
377
+ const backup = await BackupWriter.create(backupDir);
378
+ const result = { backupId: null, cleaned: [], busy: [], failed: [] };
379
+ for (const file of files) {
380
+ const temp = tempPathFor(file);
381
+ try {
382
+ const stat = fs.statSync(file);
383
+ const changes = await writeCleanedCopy(file, temp, stat.mode & 0o777, context);
384
+ if (changes.length === 0)
385
+ continue;
386
+ if (!isUnchanged(file, stat)) {
387
+ result.busy.push(file);
388
+ continue;
389
+ }
390
+ await backup.append({ path: file, changes });
391
+ if (!isUnchanged(file, stat)) {
392
+ result.busy.push(file);
393
+ continue;
394
+ }
395
+ await replaceFile(temp, file, stat);
396
+ result.cleaned.push({ file, lines: changes.length });
397
+ }
398
+ catch {
399
+ result.failed.push(file);
400
+ }
401
+ finally {
402
+ fs.rmSync(temp, { force: true });
403
+ }
404
+ }
405
+ if (await backup.finish())
406
+ result.backupId = backup.id;
407
+ return result;
408
+ }
409
+ function latestBackupId(dir) {
410
+ let names;
411
+ try {
412
+ names = fs.readdirSync(dir);
413
+ }
414
+ catch {
415
+ return null;
416
+ }
417
+ const ids = names.filter((n) => n.endsWith(".bak")).map((n) => n.slice(0, -4)).filter((id) => ID_PATTERN.test(id));
418
+ return ids.sort().pop() ?? null;
419
+ }
420
+ async function restoreFile(frame, read) {
421
+ let stat;
422
+ try {
423
+ stat = fs.statSync(frame.path);
424
+ }
425
+ catch {
426
+ return { restored: 0, conflicts: frame.changes.length };
427
+ }
428
+ const pending = new Map(frame.changes.map((change) => [change.i, change]));
429
+ let restored = 0;
430
+ const temp = tempPathFor(frame.path);
431
+ try {
432
+ const handle = await fs.promises.open(temp, "wx", stat.mode & 0o777);
433
+ try {
434
+ let index = 0;
435
+ for await (const piece of readLines(frame.path, read)) {
436
+ if (piece.type === "fragment") {
437
+ await handle.write(piece.bytes);
438
+ continue;
439
+ }
440
+ const change = pending.get(index);
441
+ if (change && piece.type === "line" && sha256(piece.bytes) === change.cleaned) {
442
+ await handle.write(Buffer.from(change.original, "base64"));
443
+ pending.delete(index);
444
+ restored++;
445
+ }
446
+ else {
447
+ await handle.write(piece.bytes);
448
+ }
449
+ if (piece.newline)
450
+ await handle.write("\n");
451
+ index++;
452
+ }
453
+ await handle.sync();
454
+ }
455
+ finally {
456
+ await handle.close();
457
+ }
458
+ if (restored > 0 && isUnchanged(frame.path, stat)) {
459
+ await replaceFile(temp, frame.path, stat);
460
+ return { restored, conflicts: pending.size };
461
+ }
462
+ return { restored: 0, conflicts: frame.changes.length };
463
+ }
464
+ finally {
465
+ fs.rmSync(temp, { force: true });
466
+ }
467
+ }
468
+ /** Restores the lines of one backup, or the newest. Newer lines appended to a file are kept. */
469
+ export async function undoClean(backupDir, requestedId, read) {
470
+ if (requestedId !== undefined && !ID_PATTERN.test(requestedId))
471
+ throw new CleanError("bad-id");
472
+ const id = requestedId ?? latestBackupId(backupDir);
473
+ if (!id || !fs.existsSync(backupPath(backupDir, id)))
474
+ throw new CleanError("no-backup");
475
+ const hexKey = keychainGet(accountFor(id));
476
+ if (!hexKey)
477
+ throw new CleanError("key-missing");
478
+ const frames = readFrames(backupPath(backupDir, id), id, Buffer.from(hexKey, "hex"));
479
+ const result = { backupId: id, restoredFiles: [], restoredLines: 0, conflicts: [] };
480
+ for (const frame of frames) {
481
+ const { restored, conflicts } = await restoreFile(frame, read);
482
+ if (restored > 0)
483
+ result.restoredFiles.push(frame.path);
484
+ result.restoredLines += restored;
485
+ if (conflicts > 0)
486
+ result.conflicts.push({ file: frame.path, lines: conflicts });
487
+ }
488
+ if (result.conflicts.length === 0)
489
+ deleteBackup(backupDir, id);
490
+ return result;
491
+ }
492
+ function deleteBackup(backupDir, id) {
493
+ fs.rmSync(backupPath(backupDir, id), { force: true });
494
+ keychainDelete(accountFor(id));
495
+ }
496
+ /** Deletes every backup and its key. After this, a clean cannot be undone. */
497
+ export function forgetBackups(backupDir) {
498
+ let count = 0;
499
+ let id = latestBackupId(backupDir);
500
+ while (id) {
501
+ deleteBackup(backupDir, id);
502
+ count++;
503
+ id = latestBackupId(backupDir);
504
+ }
505
+ return count;
506
+ }
507
+ //# sourceMappingURL=history-clean.js.map