@nightloom/isy 1.0.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 (223) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -0
  3. package/dist/agents/claude.d.ts +6 -0
  4. package/dist/agents/claude.js +66 -0
  5. package/dist/agents/claude.js.map +1 -0
  6. package/dist/agents/codex-records.d.ts +34 -0
  7. package/dist/agents/codex-records.js +492 -0
  8. package/dist/agents/codex-records.js.map +1 -0
  9. package/dist/agents/codex.d.ts +5 -0
  10. package/dist/agents/codex.js +205 -0
  11. package/dist/agents/codex.js.map +1 -0
  12. package/dist/agents/index.d.ts +25 -0
  13. package/dist/agents/index.js +50 -0
  14. package/dist/agents/index.js.map +1 -0
  15. package/dist/agents/kimi-records.d.ts +24 -0
  16. package/dist/agents/kimi-records.js +252 -0
  17. package/dist/agents/kimi-records.js.map +1 -0
  18. package/dist/agents/kimi-wire.d.ts +8 -0
  19. package/dist/agents/kimi-wire.js +158 -0
  20. package/dist/agents/kimi-wire.js.map +1 -0
  21. package/dist/agents/kimi.d.ts +6 -0
  22. package/dist/agents/kimi.js +332 -0
  23. package/dist/agents/kimi.js.map +1 -0
  24. package/dist/agents/types.d.ts +83 -0
  25. package/dist/agents/types.js +2 -0
  26. package/dist/agents/types.js.map +1 -0
  27. package/dist/alert.d.ts +24 -0
  28. package/dist/alert.js +68 -0
  29. package/dist/alert.js.map +1 -0
  30. package/dist/api.d.ts +103 -0
  31. package/dist/api.js +171 -0
  32. package/dist/api.js.map +1 -0
  33. package/dist/commands/analyze.d.ts +61 -0
  34. package/dist/commands/analyze.js +198 -0
  35. package/dist/commands/analyze.js.map +1 -0
  36. package/dist/commands/check.d.ts +55 -0
  37. package/dist/commands/check.js +180 -0
  38. package/dist/commands/check.js.map +1 -0
  39. package/dist/commands/commit.d.ts +26 -0
  40. package/dist/commands/commit.js +130 -0
  41. package/dist/commands/commit.js.map +1 -0
  42. package/dist/commands/health.d.ts +47 -0
  43. package/dist/commands/health.js +366 -0
  44. package/dist/commands/health.js.map +1 -0
  45. package/dist/commands/init.d.ts +3 -0
  46. package/dist/commands/init.js +173 -0
  47. package/dist/commands/init.js.map +1 -0
  48. package/dist/commands/logout.d.ts +1 -0
  49. package/dist/commands/logout.js +30 -0
  50. package/dist/commands/logout.js.map +1 -0
  51. package/dist/commands/notes.d.ts +11 -0
  52. package/dist/commands/notes.js +49 -0
  53. package/dist/commands/notes.js.map +1 -0
  54. package/dist/commands/scan.d.ts +47 -0
  55. package/dist/commands/scan.js +199 -0
  56. package/dist/commands/scan.js.map +1 -0
  57. package/dist/commands/settings.d.ts +15 -0
  58. package/dist/commands/settings.js +94 -0
  59. package/dist/commands/settings.js.map +1 -0
  60. package/dist/commands/status.d.ts +61 -0
  61. package/dist/commands/status.js +151 -0
  62. package/dist/commands/status.js.map +1 -0
  63. package/dist/commands/upload.d.ts +42 -0
  64. package/dist/commands/upload.js +429 -0
  65. package/dist/commands/upload.js.map +1 -0
  66. package/dist/config.d.ts +4 -0
  67. package/dist/config.js +32 -0
  68. package/dist/config.js.map +1 -0
  69. package/dist/detectors.d.ts +43 -0
  70. package/dist/detectors.js +1026 -0
  71. package/dist/detectors.js.map +1 -0
  72. package/dist/git.d.ts +22 -0
  73. package/dist/git.js +68 -0
  74. package/dist/git.js.map +1 -0
  75. package/dist/githook.d.ts +71 -0
  76. package/dist/githook.js +238 -0
  77. package/dist/githook.js.map +1 -0
  78. package/dist/hook.d.ts +39 -0
  79. package/dist/hook.js +173 -0
  80. package/dist/hook.js.map +1 -0
  81. package/dist/index.d.ts +2 -0
  82. package/dist/index.js +205 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/log.d.ts +19 -0
  85. package/dist/log.js +97 -0
  86. package/dist/log.js.map +1 -0
  87. package/dist/mask-paths.d.ts +75 -0
  88. package/dist/mask-paths.js +364 -0
  89. package/dist/mask-paths.js.map +1 -0
  90. package/dist/pairing.d.ts +60 -0
  91. package/dist/pairing.js +137 -0
  92. package/dist/pairing.js.map +1 -0
  93. package/dist/parser.d.ts +48 -0
  94. package/dist/parser.js +516 -0
  95. package/dist/parser.js.map +1 -0
  96. package/dist/paths.d.ts +41 -0
  97. package/dist/paths.js +181 -0
  98. package/dist/paths.js.map +1 -0
  99. package/dist/plan.d.ts +25 -0
  100. package/dist/plan.js +39 -0
  101. package/dist/plan.js.map +1 -0
  102. package/dist/queue.d.ts +26 -0
  103. package/dist/queue.js +120 -0
  104. package/dist/queue.js.map +1 -0
  105. package/dist/redact.d.ts +29 -0
  106. package/dist/redact.js +254 -0
  107. package/dist/redact.js.map +1 -0
  108. package/dist/spawn.d.ts +13 -0
  109. package/dist/spawn.js +32 -0
  110. package/dist/spawn.js.map +1 -0
  111. package/dist/stage0.d.ts +20 -0
  112. package/dist/stage0.js +90 -0
  113. package/dist/stage0.js.map +1 -0
  114. package/dist/state.d.ts +84 -0
  115. package/dist/state.js +150 -0
  116. package/dist/state.js.map +1 -0
  117. package/dist/test/analyze.test.d.ts +1 -0
  118. package/dist/test/analyze.test.js +408 -0
  119. package/dist/test/analyze.test.js.map +1 -0
  120. package/dist/test/check.test.d.ts +1 -0
  121. package/dist/test/check.test.js +193 -0
  122. package/dist/test/check.test.js.map +1 -0
  123. package/dist/test/cli.test.d.ts +1 -0
  124. package/dist/test/cli.test.js +132 -0
  125. package/dist/test/cli.test.js.map +1 -0
  126. package/dist/test/codex.test.d.ts +1 -0
  127. package/dist/test/codex.test.js +585 -0
  128. package/dist/test/codex.test.js.map +1 -0
  129. package/dist/test/commit.test.d.ts +1 -0
  130. package/dist/test/commit.test.js +430 -0
  131. package/dist/test/commit.test.js.map +1 -0
  132. package/dist/test/git.test.d.ts +1 -0
  133. package/dist/test/git.test.js +75 -0
  134. package/dist/test/git.test.js.map +1 -0
  135. package/dist/test/health.test.d.ts +1 -0
  136. package/dist/test/health.test.js +156 -0
  137. package/dist/test/health.test.js.map +1 -0
  138. package/dist/test/hook.test.d.ts +1 -0
  139. package/dist/test/hook.test.js +144 -0
  140. package/dist/test/hook.test.js.map +1 -0
  141. package/dist/test/kimi.test.d.ts +1 -0
  142. package/dist/test/kimi.test.js +349 -0
  143. package/dist/test/kimi.test.js.map +1 -0
  144. package/dist/test/mask-paths.test.d.ts +1 -0
  145. package/dist/test/mask-paths.test.js +230 -0
  146. package/dist/test/mask-paths.test.js.map +1 -0
  147. package/dist/test/notes.test.d.ts +1 -0
  148. package/dist/test/notes.test.js +41 -0
  149. package/dist/test/notes.test.js.map +1 -0
  150. package/dist/test/pairing.test.d.ts +1 -0
  151. package/dist/test/pairing.test.js +138 -0
  152. package/dist/test/pairing.test.js.map +1 -0
  153. package/dist/test/parser.test.d.ts +1 -0
  154. package/dist/test/parser.test.js +312 -0
  155. package/dist/test/parser.test.js.map +1 -0
  156. package/dist/test/plan.test.d.ts +1 -0
  157. package/dist/test/plan.test.js +34 -0
  158. package/dist/test/plan.test.js.map +1 -0
  159. package/dist/test/redact.test.d.ts +1 -0
  160. package/dist/test/redact.test.js +303 -0
  161. package/dist/test/redact.test.js.map +1 -0
  162. package/dist/test/settings.test.d.ts +1 -0
  163. package/dist/test/settings.test.js +32 -0
  164. package/dist/test/settings.test.js.map +1 -0
  165. package/dist/test/stage0.test.d.ts +1 -0
  166. package/dist/test/stage0.test.js +607 -0
  167. package/dist/test/stage0.test.js.map +1 -0
  168. package/dist/test/sweep.test.d.ts +1 -0
  169. package/dist/test/sweep.test.js +298 -0
  170. package/dist/test/sweep.test.js.map +1 -0
  171. package/dist/test/update.test.d.ts +1 -0
  172. package/dist/test/update.test.js +26 -0
  173. package/dist/test/update.test.js.map +1 -0
  174. package/dist/test/upload.test.d.ts +1 -0
  175. package/dist/test/upload.test.js +331 -0
  176. package/dist/test/upload.test.js.map +1 -0
  177. package/dist/types.d.ts +142 -0
  178. package/dist/types.js +2 -0
  179. package/dist/types.js.map +1 -0
  180. package/dist/update.d.ts +17 -0
  181. package/dist/update.js +46 -0
  182. package/dist/update.js.map +1 -0
  183. package/package.json +60 -0
  184. package/src/agents/claude.ts +89 -0
  185. package/src/agents/codex-records.ts +533 -0
  186. package/src/agents/codex.ts +238 -0
  187. package/src/agents/index.ts +58 -0
  188. package/src/agents/kimi-records.ts +274 -0
  189. package/src/agents/kimi-wire.ts +179 -0
  190. package/src/agents/kimi.ts +390 -0
  191. package/src/agents/types.ts +92 -0
  192. package/src/alert.ts +68 -0
  193. package/src/api.ts +269 -0
  194. package/src/commands/analyze.ts +308 -0
  195. package/src/commands/check.ts +239 -0
  196. package/src/commands/commit.ts +179 -0
  197. package/src/commands/health.ts +444 -0
  198. package/src/commands/init.ts +186 -0
  199. package/src/commands/logout.ts +33 -0
  200. package/src/commands/notes.ts +57 -0
  201. package/src/commands/scan.ts +278 -0
  202. package/src/commands/settings.ts +107 -0
  203. package/src/commands/status.ts +236 -0
  204. package/src/commands/upload.ts +524 -0
  205. package/src/config.ts +33 -0
  206. package/src/detectors.ts +1138 -0
  207. package/src/git.ts +86 -0
  208. package/src/githook.ts +269 -0
  209. package/src/hook.ts +237 -0
  210. package/src/index.ts +229 -0
  211. package/src/log.ts +113 -0
  212. package/src/mask-paths.ts +434 -0
  213. package/src/pairing.ts +190 -0
  214. package/src/parser.ts +581 -0
  215. package/src/paths.ts +191 -0
  216. package/src/plan.ts +56 -0
  217. package/src/queue.ts +145 -0
  218. package/src/redact.ts +335 -0
  219. package/src/spawn.ts +33 -0
  220. package/src/stage0.ts +121 -0
  221. package/src/state.ts +208 -0
  222. package/src/types.ts +165 -0
  223. package/src/update.ts +46 -0
@@ -0,0 +1,434 @@
1
+ /**
2
+ * Absolute paths, rewritten so they say where a file is without saying whose
3
+ * machine it is on.
4
+ *
5
+ * A transcript records paths as the agent saw them —
6
+ * `/home/alice/work/isy/src/a.ts` — and those strings reach a pull request
7
+ * comment, the report page and a third-party model gateway. The account name in
8
+ * the second segment is the leak; the rest is information a reviewer wants.
9
+ * So a path is rewritten rather than blanked:
10
+ *
11
+ * inside the working directory → `src/a.ts`
12
+ * elsewhere under a home → `~/.config/gh/hosts.yml`
13
+ * anywhere else → left alone
14
+ *
15
+ * The repository-relative form is not a compromise, it is the form the rest of
16
+ * ISY already wants: `context.ts:wasRead` and `detectors.ts:samePath` both
17
+ * compare by suffix precisely because a transcript
18
+ * is absolute and GitHub is not, and `report.ts:fileAnchor` hashes the path
19
+ * GitHub uses. Masking makes those comparisons exact instead of lucky.
20
+ *
21
+ * Shared with the server through `isy/mask-paths`: the comment and the report
22
+ * page must mask identically, and transcripts uploaded before this existed are
23
+ * still on disk and still get published from.
24
+ */
25
+
26
+ /** The marker vocabulary the whole redaction speaks. `redact.ts` re-exports it. */
27
+ export const REDACTION_MARKER = "ISY_REDACTED";
28
+
29
+ export function marker(type: string): string {
30
+ return `[${REDACTION_MARKER}:${type}]`;
31
+ }
32
+
33
+ /** A machine on somebody's network, and a checkout keyed by an absolute path. */
34
+ const MASK_HOST = marker("host");
35
+ const MASK_PROJECT = marker("project");
36
+
37
+ export interface MaskRoots {
38
+ /** Where the session ran. Paths under it become repository-relative. */
39
+ cwd?: string;
40
+ /** The developer's home. Paths under it become `~/…`. */
41
+ home?: string;
42
+ }
43
+
44
+ /** `MaskRoots` split into segments once, ready for the segment-by-segment match. */
45
+ export interface PreparedRoots {
46
+ cwd?: string[];
47
+ home?: string[];
48
+ }
49
+
50
+ const SEPARATOR = /[\\/]/;
51
+
52
+ function split(value: string): string[] {
53
+ return value.split(SEPARATOR).filter((part) => part.length > 0);
54
+ }
55
+
56
+ /**
57
+ * A root as the matcher wants it, or nothing when it names no segments. `/` is
58
+ * the case that matters: an agent started at the root of the filesystem — a
59
+ * container, some CI images — would otherwise hand `strip` an empty prefix,
60
+ * which matches every path there is and leaves the whole tree unmasked.
61
+ */
62
+ function prepare(value: string | readonly string[] | undefined): string[] | undefined {
63
+ if (value === undefined) return undefined;
64
+ const parts = typeof value === "string" ? split(value) : [...value];
65
+ return parts.length > 0 ? parts : undefined;
66
+ }
67
+
68
+ /**
69
+ * The home directory a working directory implies: `/home/alice/work/isy` can
70
+ * only sit under `/home/alice`. Worth deriving, because knowing the account
71
+ * name beats recognising the shape of one — with a home root, `/home/alice`
72
+ * masks exactly and `/home/dashboard` (a route in somebody's source) is left
73
+ * alone instead of collapsing to `~`.
74
+ */
75
+ function homeOf(cwd: readonly string[]): string[] | undefined {
76
+ const depth = accountAt(cwd);
77
+ return depth < 0 || cwd.length <= depth ? undefined : cwd.slice(0, depth + 1);
78
+ }
79
+
80
+ /**
81
+ * Roots as the matcher wants them. Accepts them already split so a caller
82
+ * masking every string of a transcript does not re-split its own working
83
+ * directory a hundred thousand times.
84
+ */
85
+ export function resolveRoots(roots: MaskRoots | PreparedRoots): PreparedRoots {
86
+ const cwd = prepare(roots.cwd);
87
+ const home = prepare(roots.home) ?? (cwd && homeOf(cwd));
88
+ return {
89
+ ...(cwd ? { cwd } : {}),
90
+ ...(home ? { home } : {}),
91
+ };
92
+ }
93
+
94
+ /**
95
+ * One path segment: everything a path can hold that prose around it cannot.
96
+ * Colons, ampersands and parentheses are excluded so a compiler error
97
+ * (`at /home/a/x.ts:12:3`), a shell line (`cd /home/a && make`) and a stack
98
+ * frame (`(/home/a/x.ts)`) each end the path where the path actually ends.
99
+ */
100
+ const SEG = /[^\s"'`<>:;,|&$*?()[\]{}\\/]/;
101
+
102
+ /**
103
+ * A scheme makes it a URL, and `https://example.com/home/alice/x` names a page
104
+ * rather than this machine. Matched first, so no path rule sees a hostname.
105
+ */
106
+ const URL_LIKE = /[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'`<>]*/;
107
+
108
+ /**
109
+ * The two schemes that are the exception: they carry a path on this machine
110
+ * rather than an address on the network. Node, vitest and Next print
111
+ * `imported from file:///home/alice/…` on an unresolved import, and that lands
112
+ * in a tool result like any other line of stdout; an editor spells the same
113
+ * path `vscode://file/home/alice/…`. The scheme is kept, the path masked.
114
+ */
115
+ const LOCAL_URL = /^((?:file|vscode(?:-insiders)?):\/\/(?:file)?)(\/[^\s"'`<>]*)$/;
116
+
117
+ /**
118
+ * `\\host\share\…`. The lookbehind keeps a drive letter out: a transcript line
119
+ * that failed to parse is masked as text, and in JSON a Windows path is
120
+ * written `C:\\Users\\alice\\a.ts` — read as a share, that pair of slashes
121
+ * makes `Users` a hostname and leaves `alice` standing. A backslash is in the
122
+ * class for the same reason one step further out: `in\\\\n/home/alice/…` is an
123
+ * escaped escape, and read as a share it made `n` the host and left the whole
124
+ * path behind it standing — a share's tail is not local and is never stripped.
125
+ */
126
+ const UNC = new RegExp(
127
+ `(?<![A-Za-z0-9:~\\\\])\\\\\\\\${SEG.source}+(?:[\\\\/]+${SEG.source}+)*[\\\\/]?`,
128
+ );
129
+
130
+ /** Separators repeat for the same reason: JSON doubles every backslash. */
131
+ const WINDOWS = new RegExp(
132
+ `(?<![A-Za-z0-9])[A-Za-z]:[\\\\/]+(?:${SEG.source}+[\\\\/]+)*${SEG.source}*`,
133
+ );
134
+
135
+ /**
136
+ * The lookbehind is what keeps `and/or` and `2024/01/02` out: a slash that
137
+ * continues a word does not open a path. Nothing else belongs in the class —
138
+ * a diff line is `+/home/alice/…` and `-/home/alice/…`, and excluding `+` and
139
+ * `-` let the output of `git diff` carry an account name through untouched.
140
+ * `~` stays, and that is all idempotence needs: masking twice is masking once,
141
+ * because `./dist/b.js` and `100%/x` are under no root and come back unchanged.
142
+ *
143
+ * The inner lookbehind is the one exception to the letter rule: a letter that
144
+ * is itself behind a backslash ends an escape sequence rather than a word. Tool
145
+ * output reaches a transcript JSON-encoded twice often enough for that to
146
+ * matter — Prisma reports `invocation in\\n/home/alice/…`, and read as a word
147
+ * `in\\n` carried the account name through untouched.
148
+ */
149
+ const POSIX = new RegExp(
150
+ `(?<!~)(?<!(?<!\\\\)[A-Za-z0-9])\\/(?:${SEG.source}+\\/)*${SEG.source}+\\/?`,
151
+ );
152
+
153
+ /**
154
+ * A path that climbs out of the tree before it names one: `../../../../home/…`,
155
+ * an import written with one `..` too many. Without this the match would open
156
+ * at the first slash and leave the climb behind, so the account name would be
157
+ * rewritten but `..` would be left glued to the file it named.
158
+ */
159
+ const RELATIVE_CLIMB = new RegExp(
160
+ `(?<![A-Za-z0-9~.])(?:\\.\\.?[\\\\/])+(?:${SEG.source}+[\\\\/])*${SEG.source}+[\\\\/]?`,
161
+ );
162
+
163
+ const CANDIDATE = new RegExp(
164
+ `(${URL_LIKE.source})|${UNC.source}|${WINDOWS.source}|${RELATIVE_CLIMB.source}|${POSIX.source}`,
165
+ "g",
166
+ );
167
+
168
+ /** Trailing sentence punctuation belongs to the sentence, not to the file. */
169
+ const TRAILING = /[.,;:!?]+$/;
170
+
171
+ /**
172
+ * Claude Code names a session directory after the checkout it belongs to, with
173
+ * every non-alphanumeric turned into a dash (`paths.ts:projectSlug`), so
174
+ * `-home-alice-work-isy` is an absolute path with the slashes filed off and no
175
+ * `~` rule will ever see it. Two dashes past the home prefix keep an ordinary
176
+ * `-home-dir` file out.
177
+ *
178
+ * The boundary is a name character rather than a separator because a slug turns
179
+ * up outside a path at all: `ls ~/.claude/projects` prints one per line, and a
180
+ * slug behind a newline is as much the account name as one behind a slash.
181
+ */
182
+ const PROJECT_SLUG =
183
+ /(?<![A-Za-z0-9._-])-(?:home|root|users|[a-z]-users)-[A-Za-z0-9._-]*-[A-Za-z0-9._-]+(?![A-Za-z0-9._-])/gi;
184
+
185
+ /**
186
+ * `-home-alice`: the slug of a session that ran in the home directory itself.
187
+ * `PROJECT_SLUG` cannot reach it — the segment it demands past the account is
188
+ * exactly what keeps `-home-dir` out — so this one is settled against the home
189
+ * we were told instead of against the shape. That is the trade `homeOf` already
190
+ * makes: knowing the account name beats recognising one, and with no home
191
+ * known nothing here fires at all.
192
+ */
193
+ const HOME_SLUG =
194
+ /(?<![A-Za-z0-9._-])-(?:home|root|users|[a-z]-users)-[A-Za-z0-9._]+(?![A-Za-z0-9._-])/gi;
195
+
196
+ function maskSlugs(value: string, home: readonly string[] | undefined): string {
197
+ const masked = value.replace(PROJECT_SLUG, MASK_PROJECT);
198
+ if (!home) return masked;
199
+ const slug = `-${home.join("-")}`.toLowerCase();
200
+ return masked.replace(HOME_SLUG, (match) => (match.toLowerCase() === slug ? MASK_PROJECT : match));
201
+ }
202
+
203
+ /**
204
+ * The path with `root` taken off the front, or nothing when it is not under it.
205
+ * Compared segment by segment so `/home/a/repo` does not swallow
206
+ * `/home/a/repository`, and case-insensitively because macOS and Windows are —
207
+ * only the prefix is compared, so the tail still comes back exactly as written.
208
+ */
209
+ function strip(parts: readonly string[], root: readonly string[] | undefined): string[] | undefined {
210
+ if (!root || parts.length < root.length) return undefined;
211
+ for (let i = 0; i < root.length; i += 1) {
212
+ if (parts[i]!.toLowerCase() !== root[i]!.toLowerCase()) return undefined;
213
+ }
214
+ return parts.slice(root.length);
215
+ }
216
+
217
+ /** Entries under `/Users` that macOS creates and nobody is called. */
218
+ const NOT_AN_ACCOUNT: ReadonlySet<string> = new Set(["shared", "public", "default"]);
219
+
220
+ /**
221
+ * Which segment of a path would be the account name, or -1 when the path is
222
+ * not shaped like a home at all. `/home/alice/…` and `/Users/alice/…` name it
223
+ * second; `C:\Users\alice\…` and the Git Bash spelling `/c/Users/alice/…`
224
+ * name it third.
225
+ *
226
+ * The spellings are exact because the near misses are ordinary text:
227
+ * `/users/42/profile` is a URL and `/root/app` is a `WORKDIR`, and neither
228
+ * holds an account name to lose. Windows keeps its case-insensitive match —
229
+ * the filesystem is, and `C:\users\alice` is the same directory.
230
+ */
231
+ function accountAt(parts: readonly string[]): number {
232
+ const head = parts[0] ?? "";
233
+ if (head === "home" || head === "Users") return 1;
234
+ if (/^[a-z]:?$/i.test(head) && (parts[1] ?? "").toLowerCase() === "users") return 2;
235
+ return -1;
236
+ }
237
+
238
+ /**
239
+ * A home directory recognised by its shape rather than by a root we were told:
240
+ * the last resort, for a transcript that names no working directory and for the
241
+ * text the model writes, where the server knows nothing about the machine.
242
+ *
243
+ * A segment past the account name is required. `/home/dashboard` is a route in
244
+ * somebody's source far more often than it is a home, and `~` is all that would
245
+ * have survived of it — this rule runs over `old_string` and `new_string` too,
246
+ * where a rewritten path is a rewritten literal.
247
+ *
248
+ * ponytail: a name is a name, so a container's `/home/node/app` masks like a
249
+ * developer's. It has to: the second account on a machine is somebody too, and
250
+ * only a home root says which one the session belongs to. That root is what
251
+ * `resolveRoots` derives from the working directory, and with it the developer's
252
+ * own home is stripped exactly rather than recognised — this rule is left
253
+ * holding the cases where the machine is a stranger.
254
+ */
255
+ function genericHome(parts: readonly string[]): string[] | undefined {
256
+ const account = accountAt(parts);
257
+ if (account < 0 || parts.length <= account + 1) return undefined;
258
+ if (NOT_AN_ACCOUNT.has((parts[account] ?? "").toLowerCase())) return undefined;
259
+ return parts.slice(account + 1);
260
+ }
261
+
262
+ /** `\` when the path was written the Windows way, so a `~` path keeps its shape. */
263
+ function joiner(value: string): string {
264
+ return value.includes("\\") ? "\\" : "/";
265
+ }
266
+
267
+ /** One whole path, masked. Returns the input when there is nothing personal in it. */
268
+ function maskOne(value: string, roots: PreparedRoots): string {
269
+ // `\\host\share\…`: the first segment is a machine on someone's network.
270
+ if (value.startsWith("\\\\")) {
271
+ return maskSlugs(value.replace(/^\\\\[^\\/]*/, `\\\\${MASK_HOST}`), roots.home);
272
+ }
273
+
274
+ const parts = split(value);
275
+ if (parts.length === 0) return value;
276
+ const trailing = SEPARATOR.test(value.slice(-1)) ? "/" : "";
277
+
278
+ // `../../../../home/alice/x`: an import written with one `..` too many, which
279
+ // an agent produces often enough to matter. The match opens at the first
280
+ // slash, so the segments arrive with the relative prefix still on them and no
281
+ // root can match. Dropping it loses nothing — a `..` above the root names no
282
+ // directory the path was pointing at — and `value` is what comes back when
283
+ // no root matches anyway, so an ordinary relative path is untouched.
284
+ const anchor = parts.findIndex((part) => part !== "." && part !== "..");
285
+ const rooted = anchor < 0 ? [] : parts.slice(anchor);
286
+
287
+ // Repository-relative, always with forward slashes: this form is compared
288
+ // against the paths GitHub reports, and those are POSIX whatever the machine.
289
+ const inCwd = strip(rooted, roots.cwd);
290
+ if (inCwd) return inCwd.length === 0 ? "." : maskSlugs(`${inCwd.join("/")}${trailing}`, roots.home);
291
+
292
+ const inHome = strip(rooted, roots.home) ?? genericHome(rooted);
293
+ if (inHome) {
294
+ if (inHome.length === 0) return "~";
295
+ const sep = joiner(value);
296
+ return maskSlugs(`~${sep}${inHome.join(sep)}${trailing === "" ? "" : sep}`, roots.home);
297
+ }
298
+
299
+ return maskSlugs(value, roots.home);
300
+ }
301
+
302
+ /** Whether the string is a path outright, rather than text that may hold one. */
303
+ export function looksAbsolute(value: string): boolean {
304
+ return /^(?:\\\\|[\\/]|[A-Za-z]:[\\/])/.test(value);
305
+ }
306
+
307
+ /**
308
+ * Every absolute path inside a stretch of text — a shell command, a compiler
309
+ * error, a line of stdout. `onMask` is called once per path actually rewritten,
310
+ * so the redaction summary can count them the way it counts secrets.
311
+ */
312
+ export function maskPaths(
313
+ text: string,
314
+ roots: MaskRoots | PreparedRoots,
315
+ onMask?: (amount: number) => void,
316
+ ): string {
317
+ const resolved = resolveRoots(roots);
318
+ let masked = 0;
319
+
320
+ const rewrite = (match: string, url: string | undefined): string => {
321
+ if (url !== undefined) {
322
+ const local = LOCAL_URL.exec(url);
323
+ if (!local) return match;
324
+ const inside = maskOne(local[2]!, resolved);
325
+ if (inside !== local[2]) masked += 1;
326
+ return `${local[1]}${inside}`;
327
+ }
328
+
329
+ const cut = TRAILING.exec(match);
330
+ const path = cut ? match.slice(0, -cut[0].length) : match;
331
+ const tail = cut ? cut[0] : "";
332
+ if (path.length === 0) return match;
333
+
334
+ const rewritten = maskOne(path, resolved);
335
+ if (rewritten !== path) masked += 1;
336
+ return `${rewritten}${tail}`;
337
+ };
338
+
339
+ // Every path rule needs a separator, so text without one holds no path — but
340
+ // it can still hold a slug, which is a path with the slashes filed off.
341
+ const paths =
342
+ text.includes("/") || text.includes("\\") ? text.replace(CANDIDATE, rewrite) : text;
343
+
344
+ // Slugs last, over the whole text: `ls ~/.claude/projects` prints one per
345
+ // line, and a pass that only rewrites paths never sees one standing alone.
346
+ const result = maskSlugs(paths, resolved.home);
347
+ if (result !== paths) masked += 1;
348
+
349
+ if (masked > 0) onMask?.(masked);
350
+ return result;
351
+ }
352
+
353
+ /**
354
+ * A value that is a path and nothing else — `file_path`, `cwd`, `filePath`.
355
+ * Handled apart from `maskPaths` because such a value may hold a space, which
356
+ * inside free text is where a path ends.
357
+ */
358
+ export function maskPath(
359
+ value: string,
360
+ roots: MaskRoots | PreparedRoots,
361
+ onMask?: (amount: number) => void,
362
+ ): string {
363
+ if (!looksAbsolute(value)) return maskPaths(value, roots, onMask);
364
+
365
+ const masked = maskOne(value, resolveRoots(roots));
366
+ if (masked !== value) onMask?.(1);
367
+ return masked;
368
+ }
369
+
370
+ /** The keys whose value is a path outright, wherever it sits in a record. */
371
+ export const PATH_KEYS: ReadonlySet<string> = new Set([
372
+ "cwd",
373
+ "file",
374
+ "filePath",
375
+ "file_path",
376
+ "notebook_path",
377
+ "path",
378
+ ]);
379
+
380
+ /**
381
+ * The working directory a transcript record names, which is the root every
382
+ * other path in that transcript is relative to. One rule, two callers: the
383
+ * client learns it while redacting, the server while reading a transcript back
384
+ * off disk — and they must agree, or a comment and a report page would spell
385
+ * the same file two ways.
386
+ */
387
+ export function rootOf(record: unknown): string | undefined {
388
+ if (typeof record !== "object" || record === null) return undefined;
389
+ const cwd = (record as { cwd?: unknown }).cwd;
390
+ return typeof cwd === "string" && cwd.length > 0 ? cwd : undefined;
391
+ }
392
+
393
+ /**
394
+ * Every string anywhere in a value, masked. Used where a whole record has to
395
+ * come out clean and naming the fields one by one would mean a leak per field
396
+ * missed — a tool result nests its payload differently for every tool, and the
397
+ * transcript format is undocumented and moves between CLI versions.
398
+ */
399
+ export function maskDeep<T>(
400
+ value: T,
401
+ roots: MaskRoots | PreparedRoots,
402
+ onMask?: (amount: number) => void,
403
+ ): T {
404
+ return walk(value, resolveRoots(roots), onMask) as T;
405
+ }
406
+
407
+ function walk(
408
+ value: unknown,
409
+ roots: PreparedRoots,
410
+ onMask: ((amount: number) => void) | undefined,
411
+ key?: string,
412
+ ): unknown {
413
+ if (typeof value === "string") {
414
+ return (key && PATH_KEYS.has(key) ? maskPath : maskPaths)(value, roots, onMask);
415
+ }
416
+
417
+ // The key travels into the array: `{"paths": ["/home/alice/My Notes/a.md"]}`
418
+ // is a list of paths outright, and read as free text it would end at the space.
419
+ if (Array.isArray(value)) return value.map((item) => walk(item, roots, onMask, key));
420
+
421
+ if (typeof value === "object" && value !== null) {
422
+ const result: Record<string, unknown> = {};
423
+ for (const [entryKey, entryValue] of Object.entries(value)) {
424
+ // A key is a path as often as a value is: Claude Code keys its per-file
425
+ // state by absolute path, so a walk down the values alone left the
426
+ // account name standing in every key of that map. The original key is
427
+ // what travels down as `key` — `PATH_KEYS` names fields, not paths.
428
+ result[maskPath(entryKey, roots, onMask)] = walk(entryValue, roots, onMask, entryKey);
429
+ }
430
+ return result;
431
+ }
432
+
433
+ return value;
434
+ }
package/src/pairing.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { errorMessage, logLine } from "./log.js";
2
+
3
+ /**
4
+ * Being handed a key by the browser instead of asking for one to be pasted.
5
+ *
6
+ * `isy init` used to open the sign-in page, print a token there and wait for
7
+ * the reader to carry it back across the screen — or, if they closed the page,
8
+ * to run a second command with it. The terminal is still open, so it can wait
9
+ * to be told: this opens a pairing on the server, sends the browser to the keys
10
+ * screen with the half of it a human reads, and polls for the answer with the
11
+ * half that never left this machine — so the key is handed back to something
12
+ * no browser, and no one reading over a shoulder, could have seen.
13
+ *
14
+ * Every failure here is soft. The paste is still on offer the whole time, so a
15
+ * server too old to know this route, a browser on another machine, and a
16
+ * pairing that timed out all end in the same place they did before.
17
+ */
18
+
19
+ /** The pairing as the server described it. */
20
+ export interface Pairing {
21
+ /** The secret this machine polls with. Not in the URL, not in the browser. */
22
+ deviceCode: string;
23
+ /** `ABCD-EFGH` — printed here and shown on the page, so the two can be compared. */
24
+ userCode: string;
25
+ /** Where to send the browser. Built by the server: only it knows the dashboard's address. */
26
+ connectUrl: string;
27
+ expiresInMs: number;
28
+ pollIntervalMs: number;
29
+ }
30
+
31
+ export interface PairedKey {
32
+ token: string;
33
+ /** Whose account handed the key over. Printed, because it is the one thing worth checking. */
34
+ githubLogin?: string;
35
+ }
36
+
37
+ const OPEN_TIMEOUT_MS = 10_000;
38
+ const POLL_TIMEOUT_MS = 10_000;
39
+ const DEFAULT_POLL_INTERVAL_MS = 2000;
40
+ /** Matches `PAIRING_TTL_MS` on the server; used only if the answer left it out. */
41
+ const DEFAULT_EXPIRY_MS = 10 * 60 * 1000;
42
+
43
+ function isNumber(value: unknown): value is number {
44
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
45
+ }
46
+
47
+ /** Never throws: an older server answers 404 here, and that is a fallback, not an error. */
48
+ export function parsePairing(value: unknown): Pairing | undefined {
49
+ if (typeof value !== "object" || value === null) return undefined;
50
+ const record = value as Record<string, unknown>;
51
+ if (typeof record.deviceCode !== "string" || record.deviceCode.length === 0) return undefined;
52
+ if (typeof record.userCode !== "string" || record.userCode.length === 0) return undefined;
53
+ if (typeof record.connectUrl !== "string" || !/^https?:\/\//.test(record.connectUrl)) {
54
+ return undefined;
55
+ }
56
+ return {
57
+ deviceCode: record.deviceCode,
58
+ userCode: record.userCode,
59
+ connectUrl: record.connectUrl,
60
+ expiresInMs: isNumber(record.expiresInMs) ? record.expiresInMs : DEFAULT_EXPIRY_MS,
61
+ pollIntervalMs: isNumber(record.pollIntervalMs)
62
+ ? record.pollIntervalMs
63
+ : DEFAULT_POLL_INTERVAL_MS,
64
+ };
65
+ }
66
+
67
+ export async function openPairing(baseUrl: string): Promise<Pairing | undefined> {
68
+ try {
69
+ const response = await fetch(new URL("/api/v1/cli/pairings", baseUrl), {
70
+ method: "POST",
71
+ headers: { "content-type": "application/json" },
72
+ body: "{}",
73
+ signal: AbortSignal.timeout(OPEN_TIMEOUT_MS),
74
+ });
75
+ if (!response.ok) {
76
+ logLine(`init: pairing unavailable (${response.status})`);
77
+ return undefined;
78
+ }
79
+ return parsePairing(await response.json().catch(() => undefined));
80
+ } catch (error) {
81
+ logLine(`init: pairing unavailable (${errorMessage(error)})`);
82
+ return undefined;
83
+ }
84
+ }
85
+
86
+ export type PollOutcome =
87
+ | { status: "pending" }
88
+ | { status: "ready"; key: PairedKey }
89
+ /** The pairing is gone: taken, expired, or never known here. */
90
+ | { status: "expired" }
91
+ /** The server could not be reached this time. Polling keeps going. */
92
+ | { status: "unreachable"; error: string };
93
+
94
+ /**
95
+ * The poll's own timeout, plus whatever the caller uses to give up.
96
+ *
97
+ * Both, not either: a request still in flight holds the event loop open, so a
98
+ * paste that ended the wait would otherwise leave `isy init` looking hung for
99
+ * as long as the timeout. `AbortSignal.any` is Node 20.3; on anything older the
100
+ * timeout alone still ends it, just later.
101
+ */
102
+ function untilEither(signal: AbortSignal | undefined, ms: number): AbortSignal {
103
+ const timeout = AbortSignal.timeout(ms);
104
+ if (!signal) return timeout;
105
+ return typeof AbortSignal.any === "function" ? AbortSignal.any([signal, timeout]) : timeout;
106
+ }
107
+
108
+ export async function pollPairing(
109
+ baseUrl: string,
110
+ deviceCode: string,
111
+ signal?: AbortSignal,
112
+ ): Promise<PollOutcome> {
113
+ let response: Response;
114
+ try {
115
+ response = await fetch(
116
+ new URL(`/api/v1/cli/pairings/${encodeURIComponent(deviceCode)}`, baseUrl),
117
+ { signal: untilEither(signal, POLL_TIMEOUT_MS) },
118
+ );
119
+ } catch (error) {
120
+ return { status: "unreachable", error: errorMessage(error) };
121
+ }
122
+
123
+ if (response.status === 404) return { status: "expired" };
124
+ if (!response.ok) return { status: "unreachable", error: `server returned ${response.status}` };
125
+
126
+ const body: unknown = await response.json().catch(() => undefined);
127
+ if (typeof body !== "object" || body === null) return { status: "pending" };
128
+ const record = body as Record<string, unknown>;
129
+ if (record.status !== "ready" || typeof record.token !== "string") return { status: "pending" };
130
+
131
+ return {
132
+ status: "ready",
133
+ key: {
134
+ token: record.token,
135
+ ...(typeof record.githubLogin === "string" && record.githubLogin.length > 0
136
+ ? { githubLogin: record.githubLogin }
137
+ : {}),
138
+ },
139
+ };
140
+ }
141
+
142
+ /** Resolves when the sleep is over, or at once when the wait is abandoned. */
143
+ function sleep(ms: number, signal: AbortSignal): Promise<void> {
144
+ return new Promise((resolve) => {
145
+ if (signal.aborted) {
146
+ resolve();
147
+ return;
148
+ }
149
+ // Not `unref`ed: between two polls this timer is the only thing left on the
150
+ // event loop when there is no TTY to hold stdin open, and a loop that empties
151
+ // is a process that exits — `isy init` would end mid-wait, having printed a
152
+ // URL and asked for nothing. Giving up early is what the abort is for, and it
153
+ // resolves this sleep on the spot.
154
+ const timer = setTimeout(done, ms);
155
+ signal.addEventListener("abort", done, { once: true });
156
+ function done() {
157
+ clearTimeout(timer);
158
+ signal.removeEventListener("abort", done);
159
+ resolve();
160
+ }
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Ask until the browser answers, the pairing expires, or the caller gives up —
166
+ * the last of which is what happens when the reader pasted a key instead.
167
+ *
168
+ * A poll that could not reach the server is not the end: the machine that just
169
+ * opened a browser is not always the one with the steady connection, and the
170
+ * pairing outlives a few failed asks. Only the deadline and an explicit
171
+ * `expired` stop the loop.
172
+ */
173
+ export async function awaitPairedKey(
174
+ baseUrl: string,
175
+ pairing: Pairing,
176
+ signal: AbortSignal,
177
+ now: () => number = Date.now,
178
+ ): Promise<PairedKey | undefined> {
179
+ const deadline = now() + pairing.expiresInMs;
180
+
181
+ while (!signal.aborted && now() < deadline) {
182
+ const outcome = await pollPairing(baseUrl, pairing.deviceCode, signal);
183
+ if (outcome.status === "ready") return outcome.key;
184
+ if (outcome.status === "expired") return undefined;
185
+ if (outcome.status === "unreachable") logLine(`init: pairing poll failed: ${outcome.error}`);
186
+ await sleep(pairing.pollIntervalMs, signal);
187
+ }
188
+
189
+ return undefined;
190
+ }