@getengram/cli 0.6.0 → 0.7.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 (208) hide show
  1. package/LICENSE +112 -0
  2. package/README.md +1 -1
  3. package/dist/commands/auth.d.ts.map +1 -1
  4. package/dist/commands/auth.js +38 -11
  5. package/dist/commands/auth.js.map +1 -1
  6. package/dist/commands/conversations.d.ts.map +1 -1
  7. package/dist/commands/conversations.js +8 -2
  8. package/dist/commands/conversations.js.map +1 -1
  9. package/dist/commands/exclude.d.ts.map +1 -1
  10. package/dist/commands/exclude.js +73 -21
  11. package/dist/commands/exclude.js.map +1 -1
  12. package/dist/commands/import.d.ts +30 -3
  13. package/dist/commands/import.d.ts.map +1 -1
  14. package/dist/commands/import.js +374 -45
  15. package/dist/commands/import.js.map +1 -1
  16. package/dist/commands/login.d.ts.map +1 -1
  17. package/dist/commands/login.js +144 -29
  18. package/dist/commands/login.js.map +1 -1
  19. package/dist/commands/search.js +2 -2
  20. package/dist/commands/search.js.map +1 -1
  21. package/dist/commands/status.d.ts +16 -0
  22. package/dist/commands/status.d.ts.map +1 -0
  23. package/dist/commands/status.js +51 -0
  24. package/dist/commands/status.js.map +1 -0
  25. package/dist/commands/store.d.ts.map +1 -1
  26. package/dist/commands/store.js +19 -3
  27. package/dist/commands/store.js.map +1 -1
  28. package/dist/commands/upgrade.d.ts +24 -0
  29. package/dist/commands/upgrade.d.ts.map +1 -1
  30. package/dist/commands/upgrade.js +64 -15
  31. package/dist/commands/upgrade.js.map +1 -1
  32. package/dist/commands/usage.d.ts +44 -0
  33. package/dist/commands/usage.d.ts.map +1 -1
  34. package/dist/commands/usage.js +79 -19
  35. package/dist/commands/usage.js.map +1 -1
  36. package/dist/commands/vault.d.ts +11 -2
  37. package/dist/commands/vault.d.ts.map +1 -1
  38. package/dist/commands/vault.js +372 -53
  39. package/dist/commands/vault.js.map +1 -1
  40. package/dist/config-file.d.ts +74 -0
  41. package/dist/config-file.d.ts.map +1 -0
  42. package/dist/config-file.js +152 -0
  43. package/dist/config-file.js.map +1 -0
  44. package/dist/config-guard.d.ts +96 -0
  45. package/dist/config-guard.d.ts.map +1 -0
  46. package/dist/config-guard.js +184 -0
  47. package/dist/config-guard.js.map +1 -0
  48. package/dist/config.d.ts +48 -4
  49. package/dist/config.d.ts.map +1 -1
  50. package/dist/config.js +101 -12
  51. package/dist/config.js.map +1 -1
  52. package/dist/daemon/as-root.d.ts +46 -0
  53. package/dist/daemon/as-root.d.ts.map +1 -0
  54. package/dist/daemon/as-root.js +64 -0
  55. package/dist/daemon/as-root.js.map +1 -0
  56. package/dist/daemon/backoff.d.ts +26 -0
  57. package/dist/daemon/backoff.d.ts.map +1 -0
  58. package/dist/daemon/backoff.js +37 -0
  59. package/dist/daemon/backoff.js.map +1 -0
  60. package/dist/daemon/codex-parser.d.ts +38 -4
  61. package/dist/daemon/codex-parser.d.ts.map +1 -1
  62. package/dist/daemon/codex-parser.js +111 -23
  63. package/dist/daemon/codex-parser.js.map +1 -1
  64. package/dist/daemon/command-path.d.ts +13 -0
  65. package/dist/daemon/command-path.d.ts.map +1 -0
  66. package/dist/daemon/command-path.js +35 -0
  67. package/dist/daemon/command-path.js.map +1 -0
  68. package/dist/daemon/commands.d.ts +153 -3
  69. package/dist/daemon/commands.d.ts.map +1 -1
  70. package/dist/daemon/commands.js +2775 -235
  71. package/dist/daemon/commands.js.map +1 -1
  72. package/dist/daemon/db.d.ts +255 -27
  73. package/dist/daemon/db.d.ts.map +1 -1
  74. package/dist/daemon/db.js +749 -53
  75. package/dist/daemon/db.js.map +1 -1
  76. package/dist/daemon/exclusions.d.ts +23 -3
  77. package/dist/daemon/exclusions.d.ts.map +1 -1
  78. package/dist/daemon/exclusions.js +91 -21
  79. package/dist/daemon/exclusions.js.map +1 -1
  80. package/dist/daemon/homebrew.d.ts +26 -0
  81. package/dist/daemon/homebrew.d.ts.map +1 -0
  82. package/dist/daemon/homebrew.js +43 -0
  83. package/dist/daemon/homebrew.js.map +1 -0
  84. package/dist/daemon/instance.d.ts +427 -0
  85. package/dist/daemon/instance.d.ts.map +1 -0
  86. package/dist/daemon/instance.js +1201 -0
  87. package/dist/daemon/instance.js.map +1 -0
  88. package/dist/daemon/key-source.d.ts +41 -0
  89. package/dist/daemon/key-source.d.ts.map +1 -0
  90. package/dist/daemon/key-source.js +89 -0
  91. package/dist/daemon/key-source.js.map +1 -0
  92. package/dist/daemon/launch.d.ts +56 -0
  93. package/dist/daemon/launch.d.ts.map +1 -0
  94. package/dist/daemon/launch.js +153 -0
  95. package/dist/daemon/launch.js.map +1 -0
  96. package/dist/daemon/launchd.d.ts +215 -0
  97. package/dist/daemon/launchd.d.ts.map +1 -0
  98. package/dist/daemon/launchd.js +527 -0
  99. package/dist/daemon/launchd.js.map +1 -0
  100. package/dist/daemon/login-start.d.ts +2 -0
  101. package/dist/daemon/login-start.d.ts.map +1 -0
  102. package/dist/daemon/login-start.js +25 -0
  103. package/dist/daemon/login-start.js.map +1 -0
  104. package/dist/daemon/ownership.d.ts +123 -0
  105. package/dist/daemon/ownership.d.ts.map +1 -0
  106. package/dist/daemon/ownership.js +245 -0
  107. package/dist/daemon/ownership.js.map +1 -0
  108. package/dist/daemon/package-runner.d.ts +28 -0
  109. package/dist/daemon/package-runner.d.ts.map +1 -0
  110. package/dist/daemon/package-runner.js +113 -0
  111. package/dist/daemon/package-runner.js.map +1 -0
  112. package/dist/daemon/parser.d.ts +50 -5
  113. package/dist/daemon/parser.d.ts.map +1 -1
  114. package/dist/daemon/parser.js +224 -47
  115. package/dist/daemon/parser.js.map +1 -1
  116. package/dist/daemon/powershell.d.ts +25 -0
  117. package/dist/daemon/powershell.d.ts.map +1 -0
  118. package/dist/daemon/powershell.js +30 -0
  119. package/dist/daemon/powershell.js.map +1 -0
  120. package/dist/daemon/preflight.d.ts +0 -17
  121. package/dist/daemon/preflight.d.ts.map +1 -1
  122. package/dist/daemon/preflight.js +32 -6
  123. package/dist/daemon/preflight.js.map +1 -1
  124. package/dist/daemon/prune.d.ts +101 -0
  125. package/dist/daemon/prune.d.ts.map +1 -0
  126. package/dist/daemon/prune.js +287 -0
  127. package/dist/daemon/prune.js.map +1 -0
  128. package/dist/daemon/queue-error.d.ts +47 -0
  129. package/dist/daemon/queue-error.d.ts.map +1 -0
  130. package/dist/daemon/queue-error.js +59 -0
  131. package/dist/daemon/queue-error.js.map +1 -0
  132. package/dist/daemon/root-daemon.d.ts +60 -0
  133. package/dist/daemon/root-daemon.d.ts.map +1 -0
  134. package/dist/daemon/root-daemon.js +86 -0
  135. package/dist/daemon/root-daemon.js.map +1 -0
  136. package/dist/daemon/scoop.d.ts +52 -0
  137. package/dist/daemon/scoop.d.ts.map +1 -0
  138. package/dist/daemon/scoop.js +84 -0
  139. package/dist/daemon/scoop.js.map +1 -0
  140. package/dist/daemon/scrubber.d.ts +456 -0
  141. package/dist/daemon/scrubber.d.ts.map +1 -0
  142. package/dist/daemon/scrubber.js +994 -0
  143. package/dist/daemon/scrubber.js.map +1 -0
  144. package/dist/daemon/status.d.ts +306 -11
  145. package/dist/daemon/status.d.ts.map +1 -1
  146. package/dist/daemon/status.js +568 -43
  147. package/dist/daemon/status.js.map +1 -1
  148. package/dist/daemon/supervise.d.ts +78 -0
  149. package/dist/daemon/supervise.d.ts.map +1 -0
  150. package/dist/daemon/supervise.js +121 -0
  151. package/dist/daemon/supervise.js.map +1 -0
  152. package/dist/daemon/supervisor.d.ts +18 -0
  153. package/dist/daemon/supervisor.d.ts.map +1 -0
  154. package/dist/daemon/supervisor.js +56 -0
  155. package/dist/daemon/supervisor.js.map +1 -0
  156. package/dist/daemon/syncer.d.ts +382 -21
  157. package/dist/daemon/syncer.d.ts.map +1 -1
  158. package/dist/daemon/syncer.js +1448 -178
  159. package/dist/daemon/syncer.js.map +1 -1
  160. package/dist/daemon/systemd.d.ts +109 -0
  161. package/dist/daemon/systemd.d.ts.map +1 -0
  162. package/dist/daemon/systemd.js +363 -0
  163. package/dist/daemon/systemd.js.map +1 -0
  164. package/dist/daemon/types.d.ts +58 -6
  165. package/dist/daemon/types.d.ts.map +1 -1
  166. package/dist/daemon/vault-changed.d.ts +29 -0
  167. package/dist/daemon/vault-changed.d.ts.map +1 -0
  168. package/dist/daemon/vault-changed.js +47 -0
  169. package/dist/daemon/vault-changed.js.map +1 -0
  170. package/dist/daemon/vault-key-missing.d.ts +70 -0
  171. package/dist/daemon/vault-key-missing.d.ts.map +1 -0
  172. package/dist/daemon/vault-key-missing.js +125 -0
  173. package/dist/daemon/vault-key-missing.js.map +1 -0
  174. package/dist/daemon/watcher.d.ts +87 -4
  175. package/dist/daemon/watcher.d.ts.map +1 -1
  176. package/dist/daemon/watcher.js +286 -36
  177. package/dist/daemon/watcher.js.map +1 -1
  178. package/dist/daemon/worker-main.js +363 -51
  179. package/dist/daemon/worker-main.js.map +1 -1
  180. package/dist/daemon/worker.js +19 -1
  181. package/dist/daemon/worker.js.map +1 -1
  182. package/dist/import-resume.d.ts +163 -0
  183. package/dist/import-resume.d.ts.map +1 -0
  184. package/dist/import-resume.js +267 -0
  185. package/dist/import-resume.js.map +1 -0
  186. package/dist/index.js +242 -33
  187. package/dist/index.js.map +1 -1
  188. package/dist/message-bounds.d.ts +52 -0
  189. package/dist/message-bounds.d.ts.map +1 -0
  190. package/dist/message-bounds.js +157 -0
  191. package/dist/message-bounds.js.map +1 -0
  192. package/dist/output.d.ts +14 -0
  193. package/dist/output.d.ts.map +1 -1
  194. package/dist/output.js +33 -5
  195. package/dist/output.js.map +1 -1
  196. package/dist/private-files.d.ts +126 -0
  197. package/dist/private-files.d.ts.map +1 -0
  198. package/dist/private-files.js +372 -0
  199. package/dist/private-files.js.map +1 -0
  200. package/dist/server-url.d.ts +31 -0
  201. package/dist/server-url.d.ts.map +1 -0
  202. package/dist/server-url.js +47 -0
  203. package/dist/server-url.js.map +1 -0
  204. package/dist/vault-key.d.ts +122 -0
  205. package/dist/vault-key.d.ts.map +1 -0
  206. package/dist/vault-key.js +273 -0
  207. package/dist/vault-key.js.map +1 -0
  208. package/package.json +11 -12
@@ -0,0 +1,994 @@
1
+ /**
2
+ * Value-exact secret scrubbing for captured transcripts.
3
+ *
4
+ * The problem this solves is structural, not a missing regex. Pattern-based
5
+ * redaction (services/conversation.ts → redact()) catches credentials that
6
+ * have a shape — sk_live_…, postgres://…, PEM blocks. It cannot catch the
7
+ * secrets people actually keep in a vault: a password, a passphrase, a PIN,
8
+ * a licence key, a recovery phrase. Measured on the shipped redactor, 12 of
9
+ * 17 realistic vault contents passed through verbatim. A four-digit PIN is
10
+ * indistinguishable from any other number; no pattern can fix that without
11
+ * destroying the memory it is meant to protect.
12
+ *
13
+ * Zero-knowledge makes it worse for the server specifically: it holds no
14
+ * plaintext vault values, so it can never build an exact denylist. Only the
15
+ * client can — the vault key lives here, and `engram vault get` decrypts on
16
+ * this machine every day. So this is where the exact match belongs.
17
+ *
18
+ * What it does: holds the plaintext of every named vault secret (and the
19
+ * vault key itself) in memory, and replaces exact occurrences in captured
20
+ * message content with `[VAULT:name]`: when a message is queued, and again
21
+ * when it is sent. That is the same token form the SDK's resolveSecrets
22
+ * understands, so a recalled memory still reads coherently and can still be
23
+ * resolved by a client with the key.
24
+ *
25
+ * Why twice (engram#588): a message can be queued before the vault has been
26
+ * read. Everything the watcher's first scan finds at start is, and so is
27
+ * anything captured while a read fails or while a replaced key's first read
28
+ * is in flight. Queueing can't wait for the read (the watcher's offset
29
+ * bookkeeping needs it synchronous, engram#370), so sending does: the syncer
30
+ * sends nothing until ready(), and scrubs each batch again against the set
31
+ * held at that moment. A token holds no value, so the second pass changes
32
+ * nothing else.
33
+ *
34
+ * ready() is true once a read through the current client has completed, or
35
+ * has failed in a way waiting can't fix: the server's own refusal, such as a
36
+ * key without the read scope. A failure that may pass is retried within
37
+ * seconds (READ_RETRY_MS), and sends wait:
38
+ * - until a read goes through, when the server couldn't be reached — the
39
+ * sends couldn't have gone out either;
40
+ * - for at most MAX_SERVER_HOLD_MS while the server answers with errors
41
+ * (an attempt that can't reach it starts that count again). Then sends
42
+ * resume with the secrets already known, so a broken vault endpoint
43
+ * can't stop capture, and the interval keeps reading.
44
+ *
45
+ * A vault key that is there but can't be read (engram#677) — a file of
46
+ * mode 000, a folder in its place, a link to nothing, an empty file —
47
+ * leaves nothing to read the vault with, nor to scrub its secrets with. It
48
+ * used to count as no key, and every secret went out as it was. Now sends
49
+ * wait for as long as it lasts: no bound releases them, since nothing
50
+ * would make them safe to send. Captures keep queueing meanwhile. The key
51
+ * is read again on READ_RETRY_MS; once it reads, the vault is read through
52
+ * it, and sends wait for that read like any other. A key file gone by then
53
+ * holds them still: it is likely being put back, and sending in between
54
+ * would send what the key protects. A restart starts without a key.
55
+ *
56
+ * The key is read again before each send, and on the interval (engram#693).
57
+ * It used to be read only at start: a key saved while the daemon ran went
58
+ * unused until a restart, and the secrets of the vault it opens went out as
59
+ * they were meanwhile. Now a key saved, or put in place of another, is used
60
+ * from the next send on: the vault is read through it first, and sends wait
61
+ * for that read, as at a start with a key. A key it replaced is scrubbed
62
+ * still, as is each way a key may be written. A key file deleted while its
63
+ * key is in use leaves that key in use, with the secrets read through it: a
64
+ * restart starts without it, and `engram status` says so. A key file that
65
+ * can't be read any more holds sends, as at start: the key in it may not be
66
+ * the one in use.
67
+ *
68
+ * A vault key that reads, but decrypts none of the vault's secrets
69
+ * (engram#694) — another machine's, or a new one made after the key was
70
+ * lost — sent every secret as it was, and only the log said so. Now sends
71
+ * wait while it lasts, as for a key that can't be read: no bound releases
72
+ * them. A secret that decrypted before, through this account, and hasn't
73
+ * been saved again since, is scrubbed with the value read then: a key
74
+ * replaced while the daemon runs holds sends only once a secret it can't
75
+ * scrub is saved, or at a restart. The hold lifts once a complete read
76
+ * finds none it can't scrub: each decrypts, or was deleted, or saved
77
+ * again with this key. Saved again one at a time, the first that decrypts
78
+ * doesn't lift it: what waits would go with the others in it. Nor does a
79
+ * restart meanwhile: status.json says the daemon before held, and
80
+ * worker-main goes on holding (continueMismatchHold). While it holds, the
81
+ * vault is listed again on
82
+ * MISMATCH_RETRY_MS, and read in full when the list changes, and at least
83
+ * every MISMATCH_REREAD_MS. A key that decrypts some of the secrets but
84
+ * not others, with no hold before, doesn't hold; `engram status` says how
85
+ * many it can't scrub.
86
+ *
87
+ * A secret saved with `engram vault set` while the daemon runs
88
+ * (engram#701) used to go out as it was until the interval read the vault
89
+ * again, up to 10 minutes later. Now `engram vault set` and `engram vault
90
+ * delete` leave a notice in ~/.engram (vault-changed.ts), which is looked
91
+ * for before each send and on the interval. A new one makes the next send
92
+ * wait for a read of the vault begun after it, as the first send waits
93
+ * for the first read. A read already under way when it came may have
94
+ * listed the vault before the change, so it doesn't count, and another
95
+ * follows it. A secret saved anywhere else, such as on another machine,
96
+ * is read on the interval still.
97
+ *
98
+ * What it never does: write a value to disk, include one in a log line, or
99
+ * send one anywhere. Values are refreshed from the vault on an interval and
100
+ * dropped on stop. The daemon already runs as the user who owns the 0600
101
+ * key file and already holds the API key; this adds no new trust boundary,
102
+ * only closes a leak inside the existing one.
103
+ */
104
+ import { engramCommand } from "./package-runner.js";
105
+ import { isRefusal } from "./status.js";
106
+ import { asVaultKeyProblem, sameVaultKey, vaultKeySpellings, VaultKeyMismatch, VaultKeyUnreadable, } from "../vault-key.js";
107
+ /** Values shorter than this are not scrubbed: too likely to be coincidence. */
108
+ export const MIN_SCRUB_LENGTH = 4;
109
+ /** After a read that may pass: retry in 10s → 30s → 1min → 1min … */
110
+ export const READ_RETRY_MS = [10_000, 30_000, 60_000];
111
+ /** The longest sends wait while the server answers but the vault won't read. */
112
+ export const MAX_SERVER_HOLD_MS = 15 * 60_000;
113
+ /**
114
+ * While sends wait for secrets the key doesn't decrypt (engram#694): list
115
+ * the vault again in 10 s → 30 s → 1 min → 2 min → 5 min → 5 min …
116
+ */
117
+ export const MISMATCH_RETRY_MS = [10_000, 30_000, 60_000, 120_000, 300_000];
118
+ /** …and read each secret again at least this often, though the list is the same. */
119
+ export const MISMATCH_REREAD_MS = 10 * 60_000;
120
+ /**
121
+ * While sends go, each secret is read again at least this often (engram#704).
122
+ * Between those reads, the interval lists the vault and reads no secret while
123
+ * the list is the same as at the last of them: a secret isn't saved again
124
+ * without its updatedAt changing. This covers what a list can't tell.
125
+ */
126
+ export const FULL_READ_MS = 6 * 60 * 60_000;
127
+ /**
128
+ * A read of each secret stands for a list the same as its own only when
129
+ * that list had been found this long before it (engram#704). updatedAt is
130
+ * to the second: a secret saved twice within the second it was read lists
131
+ * the same after as before. Once a second has passed since the list was
132
+ * first found, a secret saved again lists another updatedAt. The margin is
133
+ * for the time a request takes, and the clock.
134
+ */
135
+ export const SAME_LIST_MS = 60_000;
136
+ /** What a list says of each secret: its name, and when it was last saved. */
137
+ function fingerprint(entries) {
138
+ return JSON.stringify(entries
139
+ .map((e) => [e.name, e.updatedAt ?? null])
140
+ .sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)));
141
+ }
142
+ /** What the SDK throws for a request that failed. */
143
+ const REQUEST_ERRORS = new Set(["EngramError", "AuthenticationError", "NotFoundError", "TimeoutError"]);
144
+ function failureOf(err) {
145
+ if (isRefusal(err))
146
+ return "refused";
147
+ const name = errorName(err);
148
+ if (name === "TimeoutError" || errorText(err).startsWith("Network error:"))
149
+ return "network";
150
+ return REQUEST_ERRORS.has(name) || name === "SyntaxError" ? "server" : "local";
151
+ }
152
+ /**
153
+ * A vault read that failed here, not in the request: the value doesn't
154
+ * decrypt with this vault key (engram#694). `engram vault list --check`
155
+ * judges each secret as the daemon does.
156
+ */
157
+ export function decryptFailed(err) {
158
+ return failureOf(err) === "local";
159
+ }
160
+ function errorName(err) {
161
+ const name = err !== null && typeof err === "object" ? err.name : undefined;
162
+ return typeof name === "string" ? name : "";
163
+ }
164
+ function errorText(err) {
165
+ return err instanceof Error ? err.message : String(err);
166
+ }
167
+ export class SecretScrubber {
168
+ vault;
169
+ log;
170
+ report;
171
+ /** name → plaintext. The only place plaintext lives, and only in memory. */
172
+ values = new Map();
173
+ timer = null;
174
+ stopped = false;
175
+ /** The read in flight, and the client it goes through. */
176
+ reading = null;
177
+ /**
178
+ * The client the set was read through in full, or that can't read the
179
+ * vault at all. Compared by identity: a replaced client isn't ready until
180
+ * a read through it settles.
181
+ */
182
+ settledFor = undefined;
183
+ /**
184
+ * The list that, found again by a re-read, stands for the value of each
185
+ * secret the read that settled read, and when that read was (engram#704).
186
+ * Set with settledFor, so a read through another client never finds it.
187
+ * Undefined: each secret is read next time.
188
+ */
189
+ settledPrint = undefined;
190
+ settledAt = 0;
191
+ /**
192
+ * The list the reads through the current client have found each time
193
+ * since it first did, and when that was: after the list that first found
194
+ * it came back (engram#704).
195
+ */
196
+ seenPrint = undefined;
197
+ seenAt = 0;
198
+ /** Why the last read through the current client fell short. */
199
+ lastFailure = undefined;
200
+ retryAt = 0;
201
+ retryStep = 0;
202
+ /** Since when reads have failed with an answer from the server; 0 if not. */
203
+ serverFailingSince = 0;
204
+ /** The hold outlasted MAX_SERVER_HOLD_MS: sends go with what's known. */
205
+ released = false;
206
+ refusalLogged = false;
207
+ /** How many secrets don't decrypt with the key, as last said. */
208
+ undecryptable = 0;
209
+ /** Of those, how many have no value known from before, as last said. */
210
+ unscrubbed = 0;
211
+ /**
212
+ * Sends wait for secrets the key doesn't decrypt, with no value known
213
+ * from before (engram#694): from a complete read that found it decrypts
214
+ * none of the vault's secrets, or from the daemon before, until one finds
215
+ * none it can't scrub.
216
+ */
217
+ mismatch = undefined;
218
+ /** The list it was found with. Undefined: read each secret next time. */
219
+ mismatchPrint = undefined;
220
+ /** When each secret was last read while it holds. */
221
+ fullReadAt = 0;
222
+ /**
223
+ * The secrets whose value is known: name → when it was last saved, as
224
+ * listed when it decrypted through this account, with the key in use or
225
+ * one before it. Not saved again since, the value read then is its value.
226
+ */
227
+ own = new Map();
228
+ /** The vault key in use, trimmed: the one the vault is read with. */
229
+ vaultKey = undefined;
230
+ /**
231
+ * Each way the key in use, and each key before it, may be written
232
+ * (engram#693): scrubbed as "vault-key" along with the set. Only in
233
+ * memory, like the set, and dropped on stop.
234
+ */
235
+ keyForms = [];
236
+ /** Where the key is read again: before each send, and on the interval. */
237
+ keySource;
238
+ /** Why the vault key can't be read, while sends wait for it (engram#677). */
239
+ keyProblem = undefined;
240
+ keyRetryAt = 0;
241
+ keyRetryStep = 0;
242
+ /** The read of the key in flight. */
243
+ keyRead = null;
244
+ /** The key file went while its key was in use: said once (engram#693). */
245
+ keyGone = false;
246
+ /** Where to look for notices that the vault changed (engram#701). */
247
+ changes = undefined;
248
+ /** The notice last seen. */
249
+ changeSeen = null;
250
+ /** How many new notices have been seen. */
251
+ changeCount = 0;
252
+ /** Told of each new notice (engram#698). */
253
+ onChange = undefined;
254
+ /**
255
+ * `key.source`: where the key is read again, before each send and on the
256
+ * interval (engram#693). Without one, `vaultKey` is the key for as long
257
+ * as the scrubber runs. `key.problem`: the key couldn't be read at start,
258
+ * so sends wait until it can be (engram#677); `vault` is null then, and
259
+ * `vaultKey` undefined. `report`: told what each complete read finds of
260
+ * secrets the key doesn't decrypt, and nothing on a new client
261
+ * (engram#694).
262
+ */
263
+ constructor(vault, vaultKey, log = () => { }, key, report) {
264
+ this.vault = vault;
265
+ this.log = log;
266
+ this.report = report;
267
+ // Known before any read: scrubbed from the first message queued.
268
+ if (vaultKey)
269
+ this.useKey(vaultKey);
270
+ this.keySource = key?.source;
271
+ if (key?.problem !== undefined) {
272
+ this.keyProblem = asVaultKeyProblem(key.problem);
273
+ // It was read just now.
274
+ this.keyRetryAt = Date.now() + READ_RETRY_MS[0];
275
+ this.keyRetryStep = 1;
276
+ }
277
+ }
278
+ /** True when there is anything to scrub against. */
279
+ get active() {
280
+ return this.values.size > 0 || this.keyForms.length > 0;
281
+ }
282
+ /** Names currently loaded. Safe to log. */
283
+ get names() {
284
+ return [...this.values.keys()];
285
+ }
286
+ /**
287
+ * Why sends wait, while ready() is false: a VaultKeyUnreadable while the
288
+ * key can't be read, a VaultKeyMismatch while they wait for secrets it
289
+ * doesn't decrypt (engram#694), else why the vault couldn't be read
290
+ * through the current client.
291
+ */
292
+ get failure() {
293
+ return this.keyProblem ?? this.mismatch ?? this.lastFailure;
294
+ }
295
+ /**
296
+ * Read every secret's plaintext. A call while a read through the same
297
+ * client is in flight joins it. Failures are non-fatal and never shrink
298
+ * the set: a secret that can't be read keeps the value already known for
299
+ * it, so a transient error can never turn scrubbing off silently in the
300
+ * middle of a session.
301
+ */
302
+ refresh() {
303
+ if (this.stopped)
304
+ return Promise.resolve();
305
+ const vault = this.vault;
306
+ if (this.reading && this.reading.vault === vault)
307
+ return this.reading.done;
308
+ const read = { vault, count: this.changeCount, done: Promise.resolve() };
309
+ read.done = this.read(vault, read.count)
310
+ .catch((err) => {
311
+ this.fellShort(vault, err, "server");
312
+ this.log(`vault scrubber: read failed (${errorText(err)})`);
313
+ })
314
+ .catch(() => { }) // a log that throws: ready() mustn't
315
+ .finally(() => {
316
+ if (this.reading !== read)
317
+ return;
318
+ this.reading = null;
319
+ // The vault changed while it was under way (engram#701): read it
320
+ // again, and a ready() waiting on this read waits for that one.
321
+ if (read.count !== this.changeCount)
322
+ void this.refresh();
323
+ });
324
+ this.reading = read;
325
+ return read.done;
326
+ }
327
+ /**
328
+ * Whether captured messages may be sent now (engram#588). True once the
329
+ * set covers the vault, or the vault can't be read with this key at all,
330
+ * or the server has failed the read for MAX_SERVER_HOLD_MS. Until then it
331
+ * waits for a read through the current client that is in flight, and
332
+ * retries a failed one when its retry is due — at the bound too, so the
333
+ * hold isn't released on an answer that's out of date.
334
+ *
335
+ * A set already read in full doesn't wait for the periodic re-read: that
336
+ * only refreshes it. A released hold doesn't retry either: the interval
337
+ * reads, and the flush loop doesn't add a read every few seconds.
338
+ *
339
+ * Before any of it, the key is read again (engram#693): one saved, or put
340
+ * in place of the one in use, since the last send is the one the vault is
341
+ * read with now, and ready() waits for that read. A key that can't be read
342
+ * (engram#677) is read again only when its retry is due, and until it
343
+ * reads, ready() is false, however long that takes.
344
+ *
345
+ * A key that decrypts none of the vault's secrets (engram#694) holds the
346
+ * same way: no bound releases it. The vault is listed again when its
347
+ * retry is due, on MISMATCH_RETRY_MS.
348
+ *
349
+ * First of all, a new notice that the vault changed (engram#701) means
350
+ * the set no longer covers it: ready() waits for a read begun after the
351
+ * notice, at once, and as for the first read.
352
+ */
353
+ async ready() {
354
+ if (this.stopped)
355
+ return false;
356
+ this.checkChanges();
357
+ if (this.keySource !== undefined && (this.keyProblem === undefined || Date.now() >= this.keyRetryAt)) {
358
+ await this.checkKey();
359
+ if (this.stopped)
360
+ return false;
361
+ }
362
+ if (this.keyProblem !== undefined)
363
+ return false;
364
+ if (this.settled())
365
+ return true;
366
+ await this.inFlight();
367
+ if (this.settled())
368
+ return true;
369
+ if (this.released)
370
+ return true;
371
+ if (Date.now() >= this.retryAt) {
372
+ await this.refresh();
373
+ await this.inFlight();
374
+ if (this.settled())
375
+ return true;
376
+ }
377
+ if (!this.pastBound())
378
+ return false;
379
+ this.released = true;
380
+ this.log(`vault scrubber: the vault has failed to read for ${MAX_SERVER_HOLD_MS / 60_000} minutes — ` +
381
+ `sending with the ${this.values.size} secret(s) already known, and still retrying ` +
382
+ `(${errorText(this.lastFailure)})`);
383
+ return true;
384
+ }
385
+ /**
386
+ * Read the vault through a new client: the daemon's API key was replaced
387
+ * (engram#587), or it signed out. Reads at once, and ready() waits for
388
+ * that read. Until it settles, the current set stays in force, and a read
389
+ * that fails keeps it too. What was found of the key against the vault
390
+ * goes (engram#694): it may be another account's vault.
391
+ */
392
+ reconnect(vault) {
393
+ this.mismatch = undefined;
394
+ this.own = new Map();
395
+ this.undecryptable = 0;
396
+ this.unscrubbed = 0;
397
+ this.tell({ secrets: 0, unscrubbed: 0, decrypted: 0, held: false });
398
+ return this.readThrough(vault);
399
+ }
400
+ /**
401
+ * Read through `vault` from now on: a new client, or the vault read with
402
+ * a new key. Reads each secret, though the list is the same: a new key
403
+ * may decrypt what the last one didn't (engram#694).
404
+ */
405
+ readThrough(vault) {
406
+ this.vault = vault;
407
+ this.mismatchPrint = undefined;
408
+ this.settledFor = undefined;
409
+ this.seenPrint = undefined;
410
+ this.lastFailure = undefined;
411
+ this.retryAt = 0;
412
+ this.retryStep = 0;
413
+ this.serverFailingSince = 0;
414
+ this.released = false;
415
+ this.refusalLogged = false;
416
+ return this.refresh();
417
+ }
418
+ /**
419
+ * The daemon before this one held sends for secrets its vault key didn't
420
+ * decrypt (engram#694), and `found` is what its last complete read found.
421
+ * They wait still, as if this one had held them: no bound releases them,
422
+ * until a complete read finds none it can't scrub. One that finds a
423
+ * secret it can't scrub goes on holding, though the key decrypts others,
424
+ * as saving them again one at a time does. Call before start().
425
+ */
426
+ continueMismatchHold(found) {
427
+ this.mismatch = new VaultKeyMismatch(Math.max(1, found.secrets), Math.max(0, found.decrypted));
428
+ this.undecryptable = this.mismatch.secrets;
429
+ this.unscrubbed = Math.max(1, found.unscrubbed);
430
+ this.log("vault scrubber: the daemon before held sends for secrets its vault key didn't decrypt — " +
431
+ "holding them still, until a read of the vault finds none that can't be scrubbed");
432
+ }
433
+ /**
434
+ * Look for notices that the vault changed (engram#701), before each send
435
+ * and on the interval: `engram vault set` and `engram vault delete` leave
436
+ * one. The notice there now changes nothing: start() reads the vault
437
+ * anyway. Call before start(). `onChange`: told of each new notice, after
438
+ * the scrubber has taken it in (engram#698).
439
+ */
440
+ followChanges(changes, onChange) {
441
+ this.changes = changes;
442
+ this.onChange = onChange;
443
+ this.changeSeen = this.noticeNow();
444
+ }
445
+ /** The notice there now. A reader that throws finds none. */
446
+ noticeNow() {
447
+ try {
448
+ return this.changes?.() ?? null;
449
+ }
450
+ catch {
451
+ return null;
452
+ }
453
+ }
454
+ /**
455
+ * A new notice that the vault changed (engram#701): the set may not cover
456
+ * the vault now. The next send waits for a read begun after it, which
457
+ * ready() starts at once. A hold released at the bound tries once more
458
+ * before it lets sends go, and one for secrets the key doesn't decrypt
459
+ * reads each secret, though the list is the same. A notice removed, or
460
+ * one that can't be read, changes nothing, nor does the same one read
461
+ * again after: each notice says something of its own.
462
+ */
463
+ checkChanges() {
464
+ const notice = this.noticeNow();
465
+ if (notice === null || notice === this.changeSeen)
466
+ return;
467
+ this.changeSeen = notice;
468
+ this.changeCount++;
469
+ this.settledFor = undefined;
470
+ this.retryAt = 0;
471
+ this.released = false;
472
+ this.mismatchPrint = undefined;
473
+ this.log("vault scrubber: the vault changed — reading it again before sending");
474
+ try {
475
+ this.onChange?.();
476
+ }
477
+ catch {
478
+ // Nothing of it reaches ready(), which mustn't throw.
479
+ }
480
+ }
481
+ /** Read now and on an interval: the key too, on the interval. */
482
+ start(intervalMs = 10 * 60_000) {
483
+ this.stopped = false;
484
+ // stop() dropped its spellings.
485
+ if (this.vaultKey !== undefined)
486
+ this.useKey(this.vaultKey);
487
+ void this.refresh();
488
+ this.timer = setInterval(() => void this.tick(), intervalMs);
489
+ this.timer.unref?.();
490
+ }
491
+ /** The interval's read: the key, then the vault (engram#693). */
492
+ async tick() {
493
+ // Seen now, the notice needs no read but this one (engram#701).
494
+ this.checkChanges();
495
+ const vault = this.vault;
496
+ if (this.keySource !== undefined)
497
+ await this.checkKey();
498
+ // Read through another client since, which a new key reads through.
499
+ if (this.vault === vault)
500
+ await this.refresh();
501
+ }
502
+ stop() {
503
+ this.stopped = true;
504
+ if (this.timer)
505
+ clearInterval(this.timer);
506
+ this.timer = null;
507
+ // Drop plaintext the moment it is no longer needed. A read still in
508
+ // flight finds the scrubber stopped and keeps nothing.
509
+ this.values.clear();
510
+ this.keyForms = [];
511
+ this.own = new Map();
512
+ this.settledFor = undefined;
513
+ this.seenPrint = undefined;
514
+ this.serverFailingSince = 0;
515
+ this.released = false;
516
+ this.mismatch = undefined;
517
+ this.mismatchPrint = undefined;
518
+ this.fullReadAt = 0;
519
+ this.undecryptable = 0;
520
+ this.unscrubbed = 0;
521
+ }
522
+ /**
523
+ * Replace every exact occurrence of a known secret with its token, and of
524
+ * each way a vault key in use, or used before, may be written. Longest
525
+ * values first, so a secret that contains another secret is replaced
526
+ * whole rather than leaving a readable fragment behind.
527
+ */
528
+ scrub(text) {
529
+ if (!text || !this.active)
530
+ return { text, replaced: [] };
531
+ const ordered = [...this.values.entries()];
532
+ const known = new Set(this.values.values());
533
+ for (const form of this.keyForms) {
534
+ if (known.has(form))
535
+ continue;
536
+ known.add(form);
537
+ ordered.push(["vault-key", form]);
538
+ }
539
+ ordered.sort((a, b) => b[1].length - a[1].length);
540
+ let out = text;
541
+ // A name's count, whichever of its values was found.
542
+ const counts = new Map();
543
+ for (const [name, value] of ordered) {
544
+ let count = 0;
545
+ let idx = out.indexOf(value);
546
+ if (idx === -1)
547
+ continue;
548
+ const token = `[VAULT:${name}]`;
549
+ while (idx !== -1) {
550
+ out = out.slice(0, idx) + token + out.slice(idx + value.length);
551
+ count++;
552
+ idx = out.indexOf(value, idx + token.length);
553
+ }
554
+ counts.set(name, (counts.get(name) ?? 0) + count);
555
+ }
556
+ return { text: out, replaced: [...counts].map(([name, count]) => ({ name, count })) };
557
+ }
558
+ /**
559
+ * Scrub `key` from now on, each way it may be written, and the keys
560
+ * before it still (engram#693): a key quoted after it was replaced is no
561
+ * less a leak.
562
+ */
563
+ useKey(key) {
564
+ const text = key.trim();
565
+ this.vaultKey = text;
566
+ const forms = vaultKeySpellings(text).filter((form) => form.length >= MIN_SCRUB_LENGTH);
567
+ this.keyForms = [...new Set([...forms, ...this.keyForms])];
568
+ if (text.length >= MIN_SCRUB_LENGTH)
569
+ this.values.set("vault-key", text);
570
+ }
571
+ /** Read the key again: one read at a time. */
572
+ checkKey() {
573
+ this.keyRead ??= this.readKey()
574
+ // A log that throws: the hold stays until it has been lifted in full,
575
+ // and ready() mustn't throw.
576
+ .catch(() => { })
577
+ .finally(() => {
578
+ this.keyRead = null;
579
+ });
580
+ return this.keyRead;
581
+ }
582
+ /**
583
+ * The key, read again. The one in use, however written: nothing more to
584
+ * read, and a hold for it is lifted. The first, or another: scrub it from
585
+ * now on (and the one before it still), and read the vault with it, which
586
+ * sends wait for. It can't be read: hold sends, and try again on
587
+ * READ_RETRY_MS. It isn't there: while holding, still wait, for the key
588
+ * put back or a restart (engram#677); else go on with the key in use.
589
+ */
590
+ async readKey() {
591
+ const source = this.keySource;
592
+ if (source === undefined)
593
+ return;
594
+ if (this.keyProblem !== undefined) {
595
+ // The next try, should this one fall short in any way.
596
+ this.keyRetryAt = Date.now() + READ_RETRY_MS[Math.min(this.keyRetryStep, READ_RETRY_MS.length - 1)];
597
+ this.keyRetryStep++;
598
+ }
599
+ let key;
600
+ try {
601
+ key = await source.read();
602
+ }
603
+ catch (err) {
604
+ if (!this.stopped)
605
+ this.holdForKey(asVaultKeyProblem(err));
606
+ return;
607
+ }
608
+ if (this.stopped)
609
+ return;
610
+ if (key === undefined) {
611
+ if (this.keyProblem !== undefined) {
612
+ this.holdForKey(new VaultKeyUnreadable("isn't there any more", "gone"));
613
+ }
614
+ else if (this.vaultKey !== undefined && !this.keyGone) {
615
+ this.keyGone = true;
616
+ this.log("vault scrubber: ~/.engram/vault-key isn't there any more — still scrubbing with the key " +
617
+ "read before, and the secrets read with it. A restart starts without a key.");
618
+ }
619
+ return;
620
+ }
621
+ this.keyGone = false;
622
+ if (this.vaultKey !== undefined && sameVaultKey(key, this.vaultKey)) {
623
+ // Written another way, perhaps: that is scrubbed too.
624
+ this.useKey(key);
625
+ if (this.keyProblem !== undefined) {
626
+ this.liftKeyHold();
627
+ this.log("vault scrubber: the vault key can be read again — sending what was held");
628
+ }
629
+ return;
630
+ }
631
+ let vault;
632
+ try {
633
+ vault = source.vaultWith(key.trim());
634
+ }
635
+ catch (err) {
636
+ // Nothing to read the vault with: as a key that can't be read.
637
+ this.holdForKey(this.keyProblem ?? asVaultKeyProblem(err));
638
+ return;
639
+ }
640
+ const held = this.keyProblem !== undefined;
641
+ const first = this.vaultKey === undefined;
642
+ this.useKey(key);
643
+ // Lifted, and at once the read through `vault` starts: ready() waits
644
+ // for that read, as after any new client. The same account's vault: a
645
+ // hold for a key that doesn't match it stays until that read is done,
646
+ // and a value read with the key before is its value still (engram#694).
647
+ this.liftKeyHold();
648
+ const done = this.readThrough(vault);
649
+ this.log(held
650
+ ? first
651
+ ? "vault scrubber: the vault key can be read now — reading the vault before sending what was held"
652
+ : "vault scrubber: the vault key can be read now, and it is another key — reading the vault " +
653
+ "with it before sending what was held"
654
+ : first
655
+ ? "vault scrubber: on — a vault key was saved; reading the vault with it before sending"
656
+ : "vault scrubber: the vault key was replaced — reading the vault with the new one before " +
657
+ "sending (the one it replaced is still scrubbed)");
658
+ await done;
659
+ }
660
+ /**
661
+ * Sends wait for the key (engram#677): said when it starts, and again
662
+ * when why changes.
663
+ */
664
+ holdForKey(problem) {
665
+ if (this.keyProblem === undefined) {
666
+ this.keyProblem = problem;
667
+ this.keyRetryAt = Date.now() + READ_RETRY_MS[0];
668
+ this.keyRetryStep = 1;
669
+ this.log(`vault scrubber: holding sends — ${problem.message}. Capture goes on, and what it ` +
670
+ "captures is sent once the key can be read.");
671
+ return;
672
+ }
673
+ const changed = problem.message !== this.keyProblem.message;
674
+ this.keyProblem = problem;
675
+ if (changed)
676
+ this.log(`vault scrubber: still holding sends — ${problem.message}`);
677
+ }
678
+ liftKeyHold() {
679
+ this.keyProblem = undefined;
680
+ this.keyRetryAt = 0;
681
+ this.keyRetryStep = 0;
682
+ }
683
+ settled() {
684
+ return !this.stopped && this.settledFor === this.vault;
685
+ }
686
+ /** Wait for reads through the current client, including one a reconnect
687
+ * starts meanwhile. */
688
+ async inFlight() {
689
+ while (this.reading && this.reading.vault === this.vault)
690
+ await this.reading.done;
691
+ }
692
+ /**
693
+ * A read through `vault` fell short of the vault: not ready, and retry on
694
+ * READ_RETRY_MS. Only the server's answers count toward the bound — while
695
+ * it can't be reached, nothing can be sent anyway, and a set cut short by
696
+ * an outage mustn't go out the moment the network returns.
697
+ */
698
+ fellShort(vault, err, failure) {
699
+ if (this.stopped || vault !== this.vault)
700
+ return;
701
+ this.settledFor = undefined;
702
+ this.lastFailure = err;
703
+ this.retryAt = Date.now() + READ_RETRY_MS[Math.min(this.retryStep, READ_RETRY_MS.length - 1)];
704
+ this.retryStep++;
705
+ if (failure === "network") {
706
+ this.serverFailingSince = 0;
707
+ this.released = false;
708
+ }
709
+ else if (this.serverFailingSince === 0) {
710
+ this.serverFailingSince = Date.now();
711
+ }
712
+ }
713
+ /**
714
+ * The server has failed the read for MAX_SERVER_HOLD_MS, and sends don't
715
+ * wait for secrets the key doesn't decrypt (engram#694): sending then
716
+ * would send what can't be scrubbed.
717
+ */
718
+ pastBound() {
719
+ return (!this.stopped &&
720
+ this.mismatch === undefined &&
721
+ this.serverFailingSince !== 0 &&
722
+ Date.now() - this.serverFailingSince >= MAX_SERVER_HOLD_MS);
723
+ }
724
+ async read(vault, count) {
725
+ const next = new Map();
726
+ // The key itself is the most damaging thing to leak, and `engram vault
727
+ // keygen` without --save prints it to the terminal.
728
+ if (this.vaultKey && this.vaultKey.length >= MIN_SCRUB_LENGTH) {
729
+ next.set("vault-key", this.vaultKey);
730
+ }
731
+ // A periodic re-read of a set already read in full through this client:
732
+ // a secret it fails to read keeps its value from that set, which stays
733
+ // complete.
734
+ const rereading = this.settledFor === vault;
735
+ // The failure that leaves this read short of the vault, if any.
736
+ let short = null;
737
+ let refused = undefined;
738
+ // What the read finds of the key against the vault (engram#694): the
739
+ // secrets it decrypts, those it doesn't, and of those, the ones with no
740
+ // value known from before. Counted only when each secret got an answer.
741
+ let decrypted = 0;
742
+ let undecryptable = 0;
743
+ let unknown = 0;
744
+ let counted = true;
745
+ // Whether a list the same as this one stands for this read until
746
+ // FULL_READ_MS has passed (engram#704): the list dates each secret, each
747
+ // read says what its value is, and the list had been found SAME_LIST_MS
748
+ // before this one was asked for.
749
+ let reusable = true;
750
+ const own = new Map();
751
+ let print;
752
+ if (vault) {
753
+ let entries = [];
754
+ let listed = false;
755
+ const asked = Date.now();
756
+ try {
757
+ entries = await vault.list();
758
+ listed = true;
759
+ }
760
+ catch (err) {
761
+ const failure = failureOf(err);
762
+ if (failure === "refused") {
763
+ refused = err;
764
+ }
765
+ else {
766
+ counted = false;
767
+ this.log(`vault scrubber: reading the vault failed, keeping the ${this.values.size} secret(s) ` +
768
+ `already known (${errorText(err)})`);
769
+ // A list that didn't come back is a gap of unknown size.
770
+ if (!rereading)
771
+ short = { err, failure: failure === "network" ? "network" : "server" };
772
+ }
773
+ // Nothing was read: every secret already known stays in force.
774
+ for (const [name, value] of this.values)
775
+ next.set(name, value);
776
+ for (const [name, saved] of this.own)
777
+ own.set(name, saved);
778
+ }
779
+ if (listed) {
780
+ print = fingerprint(entries);
781
+ if (vault === this.vault && print !== this.seenPrint) {
782
+ this.seenPrint = print;
783
+ this.seenAt = Date.now();
784
+ }
785
+ if (this.seenPrint !== print || asked - this.seenAt < SAME_LIST_MS)
786
+ reusable = false;
787
+ if (this.mismatch !== undefined &&
788
+ print === this.mismatchPrint &&
789
+ Date.now() - this.fullReadAt < MISMATCH_REREAD_MS) {
790
+ // Nothing listed has changed since the read that held sends: each
791
+ // would read as it did then.
792
+ if (this.stopped || vault !== this.vault)
793
+ return;
794
+ this.serverFailingSince = 0;
795
+ this.mismatchRetry();
796
+ return;
797
+ }
798
+ // The set was read in full through this client, and nothing listed
799
+ // has changed since (engram#704): each secret would read as it did
800
+ // then, and each read writes an audit row on the server. What was
801
+ // found of the key against the vault stands too.
802
+ if (rereading && print === this.settledPrint && Date.now() - this.settledAt < FULL_READ_MS)
803
+ return;
804
+ if (!entries.every((e) => typeof e.updatedAt === "string"))
805
+ reusable = false;
806
+ }
807
+ // After a request that got no answer, the rest would only wait out the
808
+ // same timeout.
809
+ let unreachable = null;
810
+ for (const { name, updatedAt } of entries) {
811
+ let err;
812
+ if (unreachable) {
813
+ err = unreachable.err;
814
+ }
815
+ else {
816
+ try {
817
+ const value = await vault.get(name);
818
+ // Deleted since it was listed: nothing to scrub, nor to count.
819
+ if (typeof value !== "string") {
820
+ reusable = false;
821
+ continue;
822
+ }
823
+ decrypted++;
824
+ own.set(name, updatedAt);
825
+ if (value.length >= MIN_SCRUB_LENGTH)
826
+ next.set(name, value);
827
+ continue;
828
+ }
829
+ catch (e) {
830
+ err = e;
831
+ }
832
+ }
833
+ // One unreadable secret must not block the rest, nor drop the value
834
+ // already known for it (engram#588).
835
+ const previous = this.values.get(name);
836
+ if (previous !== undefined)
837
+ next.set(name, previous);
838
+ if (this.own.has(name))
839
+ own.set(name, this.own.get(name));
840
+ const failure = failureOf(err);
841
+ if (failure === "refused") {
842
+ refused ??= err;
843
+ continue;
844
+ }
845
+ if (failure === "local") {
846
+ undecryptable++;
847
+ // Its value is known still if it decrypted before, through this
848
+ // account, and hasn't been saved again since.
849
+ if (!(this.own.has(name) && this.own.get(name) === updatedAt))
850
+ unknown++;
851
+ continue;
852
+ }
853
+ counted = false;
854
+ if (failure === "network")
855
+ unreachable = { err };
856
+ if (!(rereading && previous !== undefined) && (short === null || failure === "network")) {
857
+ short = { err, failure };
858
+ }
859
+ }
860
+ }
861
+ // The client was replaced mid-read (the API key changed): this set is
862
+ // the old client's, and the read through the new one decides. Applying
863
+ // it could put an account's secrets in place of the current one's after
864
+ // the current one had loaded. A stopped scrubber keeps nothing.
865
+ if (this.stopped || vault !== this.vault)
866
+ return;
867
+ const before = this.values.size;
868
+ this.values = next;
869
+ this.own = own;
870
+ if (next.size !== before) {
871
+ this.log(`vault scrubber: protecting ${next.size} secret(s)`);
872
+ }
873
+ // The vault changed while this read was under way (engram#701): it may
874
+ // have listed the vault before the change. What it read is in force,
875
+ // but the read that follows it decides the rest.
876
+ if (count !== this.changeCount)
877
+ return;
878
+ if (short) {
879
+ this.fellShort(vault, short.err, short.failure);
880
+ return;
881
+ }
882
+ // Only a read in which each secret got an answer says what the key
883
+ // decrypts: a hold for it starts, or ends, only on one (engram#694).
884
+ if (counted) {
885
+ // Once sends wait, they wait until none is left that can't be
886
+ // scrubbed: saved again one at a time, the first that decrypts
887
+ // mustn't send what waits with the others in it.
888
+ const hold = unknown > 0 && (decrypted === 0 || this.mismatch !== undefined);
889
+ this.tell({ secrets: undecryptable, unscrubbed: unknown, decrypted, held: hold });
890
+ if (hold) {
891
+ this.holdForMismatch(new VaultKeyMismatch(undecryptable, decrypted), unknown, print);
892
+ return;
893
+ }
894
+ if (this.mismatch !== undefined)
895
+ this.liftMismatch(decrypted, undecryptable, refused);
896
+ this.sayUndecryptable(undecryptable, unknown);
897
+ }
898
+ this.settledFor = vault;
899
+ this.settledPrint = reusable && counted && refused === undefined ? print : undefined;
900
+ this.settledAt = Date.now();
901
+ this.lastFailure = undefined;
902
+ this.retryAt = 0;
903
+ this.retryStep = 0;
904
+ this.serverFailingSince = 0;
905
+ this.released = false;
906
+ if (refused !== undefined && !this.refusalLogged) {
907
+ this.refusalLogged = true;
908
+ this.log(`vault scrubber: this API key can't read the vault — scrubbing only the ${next.size} ` +
909
+ `secret(s) already known (${errorText(refused)})`);
910
+ }
911
+ }
912
+ /**
913
+ * Sends wait for secrets the key doesn't decrypt, with no value known
914
+ * from before (engram#694): no bound releases them. Said when it starts,
915
+ * and again when the count changes, or the vault read with a new key
916
+ * finds the same. The vault is listed again on MISMATCH_RETRY_MS.
917
+ */
918
+ holdForMismatch(mismatch, unknown, print) {
919
+ const was = this.mismatch;
920
+ // Each secret read again, as after a new key.
921
+ const recheck = this.mismatchPrint === undefined;
922
+ this.mismatch = mismatch;
923
+ this.mismatchPrint = print;
924
+ this.fullReadAt = Date.now();
925
+ this.settledFor = undefined;
926
+ this.lastFailure = undefined;
927
+ this.serverFailingSince = 0;
928
+ this.released = false;
929
+ if (was === undefined)
930
+ this.retryStep = 0;
931
+ this.mismatchRetry();
932
+ this.undecryptable = mismatch.secrets;
933
+ this.unscrubbed = unknown;
934
+ if (was === undefined) {
935
+ const one = mismatch.secrets === 1;
936
+ this.log(`vault scrubber: holding sends — ${mismatch.message}, so ${one ? "it" : "they"} can't ` +
937
+ `${unknown < mismatch.secrets ? "all " : ""}be scrubbed. Capture goes on, and what it ` +
938
+ `captures is sent once ${one ? "the secret decrypts, or is" : "the secrets decrypt, or are"} ` +
939
+ `deleted. See '${engramCommand("status")}'.`);
940
+ }
941
+ else if (was.secrets !== mismatch.secrets || recheck) {
942
+ this.log(`vault scrubber: still holding sends — ${mismatch.message}`);
943
+ }
944
+ }
945
+ /** The next read while sends wait for secrets the key doesn't decrypt. */
946
+ mismatchRetry() {
947
+ this.retryAt = Date.now() + MISMATCH_RETRY_MS[Math.min(this.retryStep, MISMATCH_RETRY_MS.length - 1)];
948
+ this.retryStep++;
949
+ }
950
+ /**
951
+ * A complete read finds none it can't scrub (engram#694): what waits goes.
952
+ * Those the key doesn't decrypt, if any, have a value known from before.
953
+ */
954
+ liftMismatch(decrypted, undecryptable, refused) {
955
+ this.mismatch = undefined;
956
+ this.mismatchPrint = undefined;
957
+ const why = undecryptable === 0 && decrypted > 0
958
+ ? "the vault key decrypts the vault's secrets now"
959
+ : undecryptable === 0 && refused !== undefined
960
+ ? "this API key can't read the vault now"
961
+ : "the vault holds no secret now that can't be scrubbed";
962
+ this.log(`vault scrubber: ${why} — sending what was held`);
963
+ }
964
+ /**
965
+ * Say what a complete read finds of the secrets the key doesn't decrypt,
966
+ * when that changes: those with no value known from before go out as
967
+ * they are; the rest are scrubbed with the value read before, until a
968
+ * restart (engram#694).
969
+ */
970
+ sayUndecryptable(undecryptable, unknown) {
971
+ if (undecryptable === this.undecryptable && unknown === this.unscrubbed)
972
+ return;
973
+ this.undecryptable = undecryptable;
974
+ this.unscrubbed = unknown;
975
+ if (unknown > 0) {
976
+ this.log(`vault scrubber: ${unknown} secret(s) don't decrypt with this vault key, ` +
977
+ `so they can't be scrubbed`);
978
+ }
979
+ else if (undecryptable > 0) {
980
+ this.log(`vault scrubber: ${undecryptable} secret(s) don't decrypt with this vault key — scrubbing ` +
981
+ "them with the value read before, which a restart won't have");
982
+ }
983
+ }
984
+ /** Tell the daemon's status what a read found (engram#694). */
985
+ tell(found) {
986
+ try {
987
+ this.report?.(found);
988
+ }
989
+ catch {
990
+ // A status that can't be written changes nothing here.
991
+ }
992
+ }
993
+ }
994
+ //# sourceMappingURL=scrubber.js.map