@jackwener/opencli 1.6.7 → 1.6.9

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 (122) hide show
  1. package/README.md +5 -1
  2. package/README.zh-CN.md +8 -3
  3. package/dist/clis/1688/assets.d.ts +42 -0
  4. package/dist/clis/1688/assets.js +204 -0
  5. package/dist/clis/1688/assets.test.d.ts +1 -0
  6. package/dist/clis/1688/assets.test.js +39 -0
  7. package/dist/clis/1688/download.d.ts +9 -0
  8. package/dist/clis/1688/download.js +76 -0
  9. package/dist/clis/1688/download.test.d.ts +1 -0
  10. package/dist/clis/1688/download.test.js +31 -0
  11. package/dist/clis/1688/shared.d.ts +10 -0
  12. package/dist/clis/1688/shared.js +43 -0
  13. package/dist/clis/jianyu/search.d.ts +14 -0
  14. package/dist/clis/jianyu/search.js +135 -0
  15. package/dist/clis/jianyu/search.test.d.ts +1 -0
  16. package/dist/clis/jianyu/search.test.js +23 -0
  17. package/dist/clis/linux-do/topic-content.d.ts +35 -0
  18. package/dist/clis/linux-do/topic-content.js +154 -0
  19. package/dist/clis/linux-do/topic-content.test.d.ts +1 -0
  20. package/dist/clis/linux-do/topic-content.test.js +59 -0
  21. package/dist/clis/linux-do/topic.yaml +1 -16
  22. package/dist/clis/quark/ls.d.ts +1 -0
  23. package/dist/clis/quark/ls.js +63 -0
  24. package/dist/clis/quark/mkdir.d.ts +1 -0
  25. package/dist/clis/quark/mkdir.js +36 -0
  26. package/dist/clis/quark/mv.d.ts +1 -0
  27. package/dist/clis/quark/mv.js +53 -0
  28. package/dist/clis/quark/rename.d.ts +1 -0
  29. package/dist/clis/quark/rename.js +26 -0
  30. package/dist/clis/quark/rm.d.ts +1 -0
  31. package/dist/clis/quark/rm.js +24 -0
  32. package/dist/clis/quark/save.d.ts +1 -0
  33. package/dist/clis/quark/save.js +80 -0
  34. package/dist/clis/quark/share-tree.d.ts +1 -0
  35. package/dist/clis/quark/share-tree.js +45 -0
  36. package/dist/clis/quark/utils.d.ts +50 -0
  37. package/dist/clis/quark/utils.js +146 -0
  38. package/dist/clis/quark/utils.test.d.ts +1 -0
  39. package/dist/clis/quark/utils.test.js +58 -0
  40. package/dist/clis/twitter/reply.js +3 -8
  41. package/dist/clis/twitter/reply.test.js +5 -5
  42. package/dist/clis/xiaohongshu/note.js +8 -3
  43. package/dist/clis/xiaohongshu/note.test.js +11 -0
  44. package/dist/clis/xueqiu/groups.yaml +23 -0
  45. package/dist/clis/xueqiu/kline.yaml +65 -0
  46. package/dist/clis/xueqiu/watchlist.yaml +9 -9
  47. package/dist/clis/zhihu/answer.d.ts +1 -0
  48. package/dist/clis/zhihu/answer.js +194 -0
  49. package/dist/clis/zhihu/answer.test.d.ts +1 -0
  50. package/dist/clis/zhihu/answer.test.js +81 -0
  51. package/dist/clis/zhihu/comment.d.ts +1 -0
  52. package/dist/clis/zhihu/comment.js +335 -0
  53. package/dist/clis/zhihu/comment.test.d.ts +1 -0
  54. package/dist/clis/zhihu/comment.test.js +54 -0
  55. package/dist/clis/zhihu/favorite.d.ts +1 -0
  56. package/dist/clis/zhihu/favorite.js +224 -0
  57. package/dist/clis/zhihu/favorite.test.d.ts +1 -0
  58. package/dist/clis/zhihu/favorite.test.js +196 -0
  59. package/dist/clis/zhihu/follow.d.ts +1 -0
  60. package/dist/clis/zhihu/follow.js +80 -0
  61. package/dist/clis/zhihu/follow.test.d.ts +1 -0
  62. package/dist/clis/zhihu/follow.test.js +45 -0
  63. package/dist/clis/zhihu/like.d.ts +1 -0
  64. package/dist/clis/zhihu/like.js +91 -0
  65. package/dist/clis/zhihu/like.test.d.ts +1 -0
  66. package/dist/clis/zhihu/like.test.js +64 -0
  67. package/dist/clis/zhihu/target.d.ts +24 -0
  68. package/dist/clis/zhihu/target.js +91 -0
  69. package/dist/clis/zhihu/target.test.d.ts +1 -0
  70. package/dist/clis/zhihu/target.test.js +77 -0
  71. package/dist/clis/zhihu/write-shared.d.ts +32 -0
  72. package/dist/clis/zhihu/write-shared.js +221 -0
  73. package/dist/clis/zhihu/write-shared.test.d.ts +1 -0
  74. package/dist/clis/zhihu/write-shared.test.js +175 -0
  75. package/dist/src/analysis.d.ts +2 -0
  76. package/dist/src/analysis.js +6 -0
  77. package/dist/src/browser/bridge.d.ts +2 -0
  78. package/dist/src/browser/bridge.js +30 -24
  79. package/dist/src/browser/cdp.js +96 -0
  80. package/dist/src/browser/daemon-client.d.ts +17 -8
  81. package/dist/src/browser/daemon-client.js +12 -13
  82. package/dist/src/browser/daemon-client.test.js +32 -25
  83. package/dist/src/browser/index.d.ts +2 -1
  84. package/dist/src/browser/index.js +1 -1
  85. package/dist/src/browser.test.js +2 -3
  86. package/dist/src/build-manifest.d.ts +3 -1
  87. package/dist/src/build-manifest.js +10 -7
  88. package/dist/src/build-manifest.test.js +8 -4
  89. package/dist/src/cli.d.ts +2 -1
  90. package/dist/src/cli.js +48 -46
  91. package/dist/src/clis/binance/commands.test.d.ts +1 -0
  92. package/dist/src/clis/binance/commands.test.js +54 -0
  93. package/dist/src/commanderAdapter.js +19 -6
  94. package/dist/src/commands/daemon.js +2 -10
  95. package/dist/src/diagnostic.d.ts +28 -2
  96. package/dist/src/diagnostic.js +263 -25
  97. package/dist/src/diagnostic.test.js +220 -1
  98. package/dist/src/discovery.js +7 -17
  99. package/dist/src/doctor.d.ts +2 -0
  100. package/dist/src/doctor.js +59 -31
  101. package/dist/src/doctor.test.js +89 -16
  102. package/dist/src/download/progress.js +7 -2
  103. package/dist/src/execution.js +1 -13
  104. package/dist/src/explore.d.ts +0 -2
  105. package/dist/src/explore.js +61 -38
  106. package/dist/src/extension-manifest-regression.test.js +0 -1
  107. package/dist/src/generate.d.ts +3 -6
  108. package/dist/src/generate.js +4 -8
  109. package/dist/src/package-paths.d.ts +8 -0
  110. package/dist/src/package-paths.js +41 -0
  111. package/dist/src/plugin-scaffold.js +1 -3
  112. package/dist/src/plugin.d.ts +2 -1
  113. package/dist/src/plugin.js +25 -8
  114. package/dist/src/plugin.test.js +16 -1
  115. package/dist/src/record.d.ts +1 -2
  116. package/dist/src/record.js +14 -52
  117. package/dist/src/synthesize.d.ts +0 -2
  118. package/dist/src/synthesize.js +8 -4
  119. package/package.json +3 -3
  120. package/dist/cli-manifest.json +0 -17250
  121. package/dist/src/browser/discover.d.ts +0 -15
  122. package/dist/src/browser/discover.js +0 -19
@@ -4,36 +4,254 @@
4
4
  * When OPENCLI_DIAGNOSTIC=1, failed commands emit a JSON RepairContext to stderr
5
5
  * containing the error, adapter source, and browser state (DOM snapshot, network
6
6
  * requests, console errors). AI Agents consume this to diagnose and fix adapters.
7
+ *
8
+ * Safety boundaries:
9
+ * - Sensitive headers/cookies are redacted before emission
10
+ * - Individual fields are capped to prevent unbounded output
11
+ * - Network response bodies from authenticated requests are stripped
12
+ * - Total output is capped to MAX_DIAGNOSTIC_BYTES
7
13
  */
8
14
  import * as fs from 'node:fs';
15
+ import * as path from 'node:path';
9
16
  import { CliError, getErrorMessage } from './errors.js';
10
17
  import { fullName } from './registry.js';
18
+ // ── Size budgets ─────────────────────────────────────────────────────────────
19
+ /** Maximum bytes for the entire diagnostic JSON output. */
20
+ export const MAX_DIAGNOSTIC_BYTES = 256 * 1024; // 256 KB
21
+ /** Maximum characters for DOM snapshot. */
22
+ const MAX_SNAPSHOT_CHARS = 100_000;
23
+ /** Maximum characters for adapter source. */
24
+ const MAX_SOURCE_CHARS = 50_000;
25
+ /** Maximum number of network requests to include. */
26
+ const MAX_NETWORK_REQUESTS = 50;
27
+ /** Maximum number of captured interceptor payloads to include. */
28
+ const MAX_CAPTURED_PAYLOADS = 20;
29
+ /** Maximum characters for a single network request body. */
30
+ const MAX_REQUEST_BODY_CHARS = 4_000;
31
+ /** Maximum characters for error stack trace. */
32
+ const MAX_STACK_CHARS = 5_000;
33
+ /** Maximum nesting depth for arbitrary captured payloads. */
34
+ const MAX_CAPTURED_DEPTH = 4;
35
+ /** Maximum object keys or array items to keep per nesting level. */
36
+ const MAX_CAPTURED_CHILDREN = 20;
37
+ // ── Sensitive data patterns ──────────────────────────────────────────────────
38
+ const SENSITIVE_HEADERS = new Set([
39
+ 'authorization',
40
+ 'cookie',
41
+ 'set-cookie',
42
+ 'x-csrf-token',
43
+ 'x-xsrf-token',
44
+ 'proxy-authorization',
45
+ 'x-api-key',
46
+ 'x-auth-token',
47
+ ]);
48
+ const SENSITIVE_URL_PARAMS = /([?&])(token|key|secret|password|auth|access_token|api_key|session_id|csrf)=[^&]*/gi;
49
+ /** Patterns that match inline secrets in free-text strings (error messages, stack traces, console output, DOM). */
50
+ const SENSITIVE_TEXT_PATTERNS = [
51
+ // Bearer tokens
52
+ { pattern: /Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi, replacement: 'Bearer [REDACTED]' },
53
+ // Generic "token=...", "key=...", etc. in non-URL text
54
+ { pattern: /(token|secret|password|api_key|apikey|access_token|session_id)[=:]\s*['"]?[A-Za-z0-9\-._~+/]{8,}['"]?/gi, replacement: '$1=[REDACTED]' },
55
+ // Cookie header values (key=value pairs)
56
+ { pattern: /(cookie[=:]\s*)[^\n;]{10,}/gi, replacement: '$1[REDACTED]' },
57
+ // JWT-like tokens (three base64 segments separated by dots)
58
+ { pattern: /eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, replacement: '[REDACTED_JWT]' },
59
+ ];
60
+ // ── Redaction helpers ────────────────────────────────────────────────────────
61
+ /** Truncate a string to maxLen, appending a truncation marker. */
62
+ export function truncate(str, maxLen) {
63
+ if (str.length <= maxLen)
64
+ return str;
65
+ return str.slice(0, maxLen) + `\n...[truncated, ${str.length - maxLen} chars omitted]`;
66
+ }
67
+ /** Redact sensitive query parameters from a URL. */
68
+ export function redactUrl(url) {
69
+ return url.replace(SENSITIVE_URL_PARAMS, '$1$2=[REDACTED]');
70
+ }
71
+ /** Redact inline secrets from free-text strings (error messages, stack traces, console output, DOM). */
72
+ export function redactText(text) {
73
+ let result = text;
74
+ for (const { pattern, replacement } of SENSITIVE_TEXT_PATTERNS) {
75
+ // Reset lastIndex for global regexps
76
+ pattern.lastIndex = 0;
77
+ result = result.replace(pattern, replacement);
78
+ }
79
+ return result;
80
+ }
81
+ /** Redact sensitive headers from a headers object. */
82
+ function redactHeaders(headers) {
83
+ if (!headers || typeof headers !== 'object')
84
+ return headers;
85
+ const result = {};
86
+ for (const [key, value] of Object.entries(headers)) {
87
+ result[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? '[REDACTED]' : value;
88
+ }
89
+ return result;
90
+ }
91
+ /** Recursively sanitize arbitrary captured response content for diagnostic output. */
92
+ function sanitizeCapturedValue(value, depth = 0) {
93
+ if (typeof value === 'string') {
94
+ return redactText(truncate(value, MAX_REQUEST_BODY_CHARS));
95
+ }
96
+ if (value === null || typeof value === 'number' || typeof value === 'boolean') {
97
+ return value;
98
+ }
99
+ if (depth >= MAX_CAPTURED_DEPTH) {
100
+ return '[truncated: max depth reached]';
101
+ }
102
+ if (Array.isArray(value)) {
103
+ const items = value
104
+ .slice(0, MAX_CAPTURED_CHILDREN)
105
+ .map(item => sanitizeCapturedValue(item, depth + 1));
106
+ if (value.length > MAX_CAPTURED_CHILDREN) {
107
+ items.push(`[truncated, ${value.length - MAX_CAPTURED_CHILDREN} items omitted]`);
108
+ }
109
+ return items;
110
+ }
111
+ if (!value || typeof value !== 'object') {
112
+ return value;
113
+ }
114
+ const entries = Object.entries(value);
115
+ const result = {};
116
+ for (const [key, child] of entries.slice(0, MAX_CAPTURED_CHILDREN)) {
117
+ result[key] = sanitizeCapturedValue(child, depth + 1);
118
+ }
119
+ if (entries.length > MAX_CAPTURED_CHILDREN) {
120
+ result.__truncated__ = `[${entries.length - MAX_CAPTURED_CHILDREN} fields omitted]`;
121
+ }
122
+ return result;
123
+ }
124
+ /** Redact sensitive data from a single network request entry. */
125
+ function redactNetworkRequest(req) {
126
+ if (!req || typeof req !== 'object')
127
+ return req;
128
+ const r = req;
129
+ const redacted = { ...r };
130
+ // Redact URL
131
+ if (typeof redacted.url === 'string') {
132
+ redacted.url = redactUrl(redacted.url);
133
+ }
134
+ // Redact headers
135
+ if (redacted.headers && typeof redacted.headers === 'object') {
136
+ redacted.headers = redactHeaders(redacted.headers);
137
+ }
138
+ if (redacted.requestHeaders && typeof redacted.requestHeaders === 'object') {
139
+ redacted.requestHeaders = redactHeaders(redacted.requestHeaders);
140
+ }
141
+ if (redacted.responseHeaders && typeof redacted.responseHeaders === 'object') {
142
+ redacted.responseHeaders = redactHeaders(redacted.responseHeaders);
143
+ }
144
+ // Truncate response body
145
+ if (typeof redacted.body === 'string') {
146
+ redacted.body = truncate(redacted.body, MAX_REQUEST_BODY_CHARS);
147
+ }
148
+ if ('responseBody' in redacted) {
149
+ redacted.responseBody = sanitizeCapturedValue(redacted.responseBody);
150
+ }
151
+ if ('responsePreview' in redacted) {
152
+ redacted.responsePreview = sanitizeCapturedValue(redacted.responsePreview);
153
+ }
154
+ return redacted;
155
+ }
156
+ // ── Timeout helper ───────────────────────────────────────────────────────────
157
+ /** Timeout for page state collection (prevents hang when CDP connection is stuck). */
158
+ const PAGE_STATE_TIMEOUT_MS = 5_000;
159
+ function withTimeout(promise, ms, fallback) {
160
+ return Promise.race([
161
+ promise,
162
+ new Promise(resolve => setTimeout(() => resolve(fallback), ms)),
163
+ ]);
164
+ }
165
+ // ── Source path resolution ───────────────────────────────────────────────────
166
+ /**
167
+ * Resolve the editable source file path for an adapter.
168
+ *
169
+ * Priority:
170
+ * 1. cmd.source (set for FS-scanned YAML/TS and manifest lazy-loaded TS)
171
+ * 2. cmd._modulePath (set for manifest lazy-loaded TS, points to dist/)
172
+ *
173
+ * For dist/ paths, attempt to map back to the original .ts source file.
174
+ * Skip manifest: prefixed pseudo-paths (YAML commands inlined in manifest).
175
+ */
176
+ export function resolveAdapterSourcePath(cmd) {
177
+ const candidates = [];
178
+ // cmd.source may be a real file path or 'manifest:site/name'
179
+ if (cmd.source && !cmd.source.startsWith('manifest:')) {
180
+ candidates.push(cmd.source);
181
+ }
182
+ if (cmd._modulePath) {
183
+ candidates.push(cmd._modulePath);
184
+ }
185
+ for (const candidate of candidates) {
186
+ // Try to map dist/ compiled JS back to source .ts
187
+ const sourceTs = mapDistToSource(candidate);
188
+ if (sourceTs && fs.existsSync(sourceTs))
189
+ return sourceTs;
190
+ // Try the candidate directly (YAML files, user clis, etc.)
191
+ if (fs.existsSync(candidate))
192
+ return candidate;
193
+ }
194
+ return candidates[0]; // Return best guess even if file doesn't exist
195
+ }
196
+ /** Map a dist/clis/xxx.js path back to clis/xxx.ts source. */
197
+ function mapDistToSource(filePath) {
198
+ // dist/clis/site/command.js → clis/site/command.ts
199
+ const normalized = filePath.replace(/\\/g, '/');
200
+ const distClisMatch = normalized.match(/^(.*)\/dist\/clis\/(.+)\.js$/);
201
+ if (distClisMatch) {
202
+ return path.join(distClisMatch[1], 'clis', distClisMatch[2] + '.ts');
203
+ }
204
+ return null;
205
+ }
11
206
  // ── Diagnostic collection ────────────────────────────────────────────────────
12
207
  /** Whether diagnostic mode is enabled. */
13
208
  export function isDiagnosticEnabled() {
14
209
  return process.env.OPENCLI_DIAGNOSTIC === '1';
15
210
  }
16
- /** Safely collect page diagnostic state. Individual failures are swallowed. */
211
+ function normalizeInterceptedRequests(interceptedRequests) {
212
+ return interceptedRequests.slice(0, MAX_CAPTURED_PAYLOADS).map(responseBody => ({
213
+ source: 'interceptor',
214
+ responseBody: sanitizeCapturedValue(responseBody),
215
+ }));
216
+ }
217
+ /** Safely collect page diagnostic state with redaction, size caps, and timeout. */
17
218
  async function collectPageState(page) {
18
- try {
19
- const [url, snapshot, networkRequests, consoleErrors] = await Promise.all([
20
- page.getCurrentUrl?.().catch(() => null) ?? Promise.resolve(null),
21
- page.snapshot().catch(() => '(snapshot unavailable)'),
22
- page.networkRequests().catch(() => []),
23
- page.consoleMessages('error').catch(() => []),
24
- ]);
25
- return { url: url ?? 'unknown', snapshot, networkRequests, consoleErrors };
26
- }
27
- catch {
28
- return undefined;
29
- }
219
+ const collect = async () => {
220
+ try {
221
+ const [url, snapshot, networkRequests, interceptedRequests, consoleErrors] = await Promise.all([
222
+ page.getCurrentUrl?.().catch(() => null) ?? Promise.resolve(null),
223
+ page.snapshot().catch(() => '(snapshot unavailable)'),
224
+ page.networkRequests().catch(() => []),
225
+ page.getInterceptedRequests().catch(() => []),
226
+ page.consoleMessages('error').catch(() => []),
227
+ ]);
228
+ const rawUrl = url ?? 'unknown';
229
+ const capturedResponses = normalizeInterceptedRequests(interceptedRequests);
230
+ return {
231
+ url: redactUrl(rawUrl),
232
+ snapshot: redactText(truncate(snapshot, MAX_SNAPSHOT_CHARS)),
233
+ networkRequests: networkRequests
234
+ .slice(0, MAX_NETWORK_REQUESTS)
235
+ .map(redactNetworkRequest),
236
+ capturedPayloads: capturedResponses,
237
+ consoleErrors: consoleErrors
238
+ .slice(0, 50)
239
+ .map(e => typeof e === 'string' ? redactText(e) : e),
240
+ };
241
+ }
242
+ catch {
243
+ return undefined;
244
+ }
245
+ };
246
+ return withTimeout(collect(), PAGE_STATE_TIMEOUT_MS, undefined);
30
247
  }
31
- /** Read adapter source file content. */
32
- function readAdapterSource(modulePath) {
33
- if (!modulePath)
248
+ /** Read adapter source file content with size cap. */
249
+ function readAdapterSource(sourcePath) {
250
+ if (!sourcePath)
34
251
  return undefined;
35
252
  try {
36
- return fs.readFileSync(modulePath, 'utf-8');
253
+ const content = fs.readFileSync(sourcePath, 'utf-8');
254
+ return truncate(content, MAX_SOURCE_CHARS);
37
255
  }
38
256
  catch {
39
257
  return undefined;
@@ -42,30 +260,50 @@ function readAdapterSource(modulePath) {
42
260
  /** Build a RepairContext from an error, command metadata, and optional page state. */
43
261
  export function buildRepairContext(err, cmd, pageState) {
44
262
  const isCliError = err instanceof CliError;
263
+ const sourcePath = resolveAdapterSourcePath(cmd);
45
264
  return {
46
265
  error: {
47
266
  code: isCliError ? err.code : 'UNKNOWN',
48
- message: getErrorMessage(err),
49
- hint: isCliError ? err.hint : undefined,
50
- stack: err instanceof Error ? err.stack : undefined,
267
+ message: redactText(getErrorMessage(err)),
268
+ hint: isCliError && err.hint ? redactText(err.hint) : undefined,
269
+ stack: err instanceof Error ? redactText(truncate(err.stack ?? '', MAX_STACK_CHARS)) : undefined,
51
270
  },
52
271
  adapter: {
53
272
  site: cmd.site,
54
273
  command: fullName(cmd),
55
- sourcePath: cmd._modulePath,
56
- source: readAdapterSource(cmd._modulePath),
274
+ sourcePath,
275
+ source: readAdapterSource(sourcePath),
57
276
  },
58
277
  page: pageState,
59
278
  timestamp: new Date().toISOString(),
60
279
  };
61
280
  }
62
- /** Collect full diagnostic context including page state. */
281
+ /** Collect full diagnostic context including page state (with timeout). */
63
282
  export async function collectDiagnostic(err, cmd, page) {
64
283
  const pageState = page ? await collectPageState(page) : undefined;
65
284
  return buildRepairContext(err, cmd, pageState);
66
285
  }
67
- /** Emit diagnostic JSON to stderr. */
286
+ /** Emit diagnostic JSON to stderr, enforcing total size cap. */
68
287
  export function emitDiagnostic(ctx) {
69
288
  const marker = '___OPENCLI_DIAGNOSTIC___';
70
- process.stderr.write(`\n${marker}\n${JSON.stringify(ctx)}\n${marker}\n`);
289
+ let json = JSON.stringify(ctx);
290
+ // Enforce total output budget — drop page state (largest section) first if over budget
291
+ if (json.length > MAX_DIAGNOSTIC_BYTES && ctx.page) {
292
+ const trimmed = {
293
+ ...ctx,
294
+ page: {
295
+ ...ctx.page,
296
+ snapshot: '[omitted: over size budget]',
297
+ networkRequests: [],
298
+ capturedPayloads: [],
299
+ },
300
+ };
301
+ json = JSON.stringify(trimmed);
302
+ }
303
+ // If still over budget, drop page entirely
304
+ if (json.length > MAX_DIAGNOSTIC_BYTES) {
305
+ const minimal = { ...ctx, page: undefined };
306
+ json = JSON.stringify(minimal);
307
+ }
308
+ process.stderr.write(`\n${marker}\n${json}\n${marker}\n`);
71
309
  }
@@ -1,5 +1,5 @@
1
1
  import { describe, it, expect, vi, afterEach } from 'vitest';
2
- import { buildRepairContext, isDiagnosticEnabled, emitDiagnostic } from './diagnostic.js';
2
+ import { buildRepairContext, collectDiagnostic, isDiagnosticEnabled, emitDiagnostic, truncate, redactUrl, redactText, resolveAdapterSourcePath, MAX_DIAGNOSTIC_BYTES, } from './diagnostic.js';
3
3
  import { SelectorError, CommandExecutionError } from './errors.js';
4
4
  function makeCmd(overrides = {}) {
5
5
  return {
@@ -31,6 +31,80 @@ describe('isDiagnosticEnabled', () => {
31
31
  expect(isDiagnosticEnabled()).toBe(false);
32
32
  });
33
33
  });
34
+ describe('truncate', () => {
35
+ it('returns short strings unchanged', () => {
36
+ expect(truncate('hello', 100)).toBe('hello');
37
+ });
38
+ it('truncates long strings with marker', () => {
39
+ const long = 'a'.repeat(200);
40
+ const result = truncate(long, 50);
41
+ expect(result.length).toBeLessThan(200);
42
+ expect(result).toContain('...[truncated,');
43
+ expect(result).toContain('150 chars omitted]');
44
+ });
45
+ });
46
+ describe('redactUrl', () => {
47
+ it('redacts sensitive query parameters', () => {
48
+ expect(redactUrl('https://api.com/v1?token=abc123&q=test'))
49
+ .toBe('https://api.com/v1?token=[REDACTED]&q=test');
50
+ });
51
+ it('redacts multiple sensitive params', () => {
52
+ const url = 'https://api.com?api_key=xxx&secret=yyy&page=1';
53
+ const result = redactUrl(url);
54
+ expect(result).toContain('api_key=[REDACTED]');
55
+ expect(result).toContain('secret=[REDACTED]');
56
+ expect(result).toContain('page=1');
57
+ });
58
+ it('leaves clean URLs unchanged', () => {
59
+ expect(redactUrl('https://example.com/page?q=test')).toBe('https://example.com/page?q=test');
60
+ });
61
+ });
62
+ describe('redactText', () => {
63
+ it('redacts Bearer tokens', () => {
64
+ expect(redactText('Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.test'))
65
+ .toContain('Bearer [REDACTED]');
66
+ });
67
+ it('redacts JWT tokens', () => {
68
+ const jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U';
69
+ expect(redactText(`token is ${jwt}`)).toContain('[REDACTED_JWT]');
70
+ expect(redactText(`token is ${jwt}`)).not.toContain('eyJhbGci');
71
+ });
72
+ it('redacts inline token=value patterns', () => {
73
+ expect(redactText('failed with token=abc123def456')).toContain('token=[REDACTED]');
74
+ });
75
+ it('redacts cookie values', () => {
76
+ const result = redactText('cookie: session=abc123; user=xyz789; path=/');
77
+ expect(result).toContain('[REDACTED]');
78
+ expect(result).not.toContain('session=abc123');
79
+ });
80
+ it('leaves normal text unchanged', () => {
81
+ expect(redactText('Error: element not found')).toBe('Error: element not found');
82
+ });
83
+ });
84
+ describe('resolveAdapterSourcePath', () => {
85
+ it('returns source when it is a real file path (not manifest:)', () => {
86
+ const cmd = makeCmd({ source: '/home/user/.opencli/clis/arxiv/search.yaml' });
87
+ expect(resolveAdapterSourcePath(cmd)).toBe('/home/user/.opencli/clis/arxiv/search.yaml');
88
+ });
89
+ it('skips manifest: pseudo-paths and falls back to _modulePath', () => {
90
+ const cmd = makeCmd({ source: 'manifest:arxiv/search', _modulePath: '/pkg/dist/clis/arxiv/search.js' });
91
+ // Should try to map dist→source, but since files don't exist on disk, returns _modulePath
92
+ const result = resolveAdapterSourcePath(cmd);
93
+ expect(result).toBeDefined();
94
+ expect(result).not.toContain('manifest:');
95
+ });
96
+ it('returns undefined when only manifest: pseudo-path and no _modulePath', () => {
97
+ const cmd = makeCmd({ source: 'manifest:test/cmd' });
98
+ expect(resolveAdapterSourcePath(cmd)).toBeUndefined();
99
+ });
100
+ it('prefers _modulePath mapped to .ts over dist .js', () => {
101
+ // This test verifies the mapping logic without requiring files on disk
102
+ const cmd = makeCmd({ _modulePath: '/project/dist/clis/site/cmd.js' });
103
+ const result = resolveAdapterSourcePath(cmd);
104
+ // Since neither .ts nor .js exists, returns _modulePath as best guess
105
+ expect(result).toBe('/project/dist/clis/site/cmd.js');
106
+ });
107
+ });
34
108
  describe('buildRepairContext', () => {
35
109
  it('captures CliError fields', () => {
36
110
  const err = new SelectorError('.missing-element', 'Element removed');
@@ -64,6 +138,21 @@ describe('buildRepairContext', () => {
64
138
  const ctx = buildRepairContext(new Error('boom'), makeCmd());
65
139
  expect(ctx.page).toBeUndefined();
66
140
  });
141
+ it('truncates long stack traces', () => {
142
+ const err = new Error('boom');
143
+ err.stack = 'x'.repeat(10_000);
144
+ const ctx = buildRepairContext(err, makeCmd());
145
+ expect(ctx.error.stack.length).toBeLessThan(10_000);
146
+ expect(ctx.error.stack).toContain('truncated');
147
+ });
148
+ it('redacts sensitive data in error message and stack', () => {
149
+ const err = new Error('Request failed with Bearer eyJhbGciOiJIUzI1NiJ9.test.sig');
150
+ const ctx = buildRepairContext(err, makeCmd());
151
+ expect(ctx.error.message).toContain('Bearer [REDACTED]');
152
+ expect(ctx.error.message).not.toContain('eyJhbGci');
153
+ // Stack also gets redacted
154
+ expect(ctx.error.stack).toContain('Bearer [REDACTED]');
155
+ });
67
156
  });
68
157
  describe('emitDiagnostic', () => {
69
158
  it('writes delimited JSON to stderr', () => {
@@ -81,4 +170,134 @@ describe('emitDiagnostic', () => {
81
170
  expect(parsed.error.code).toBe('COMMAND_EXEC');
82
171
  writeSpy.mockRestore();
83
172
  });
173
+ it('drops page snapshot when over size budget', () => {
174
+ const writeSpy = vi.spyOn(process.stderr, 'write').mockReturnValue(true);
175
+ const ctx = {
176
+ error: { code: 'COMMAND_EXEC', message: 'boom' },
177
+ adapter: { site: 'test', command: 'test/cmd' },
178
+ page: {
179
+ url: 'https://example.com',
180
+ snapshot: 'x'.repeat(MAX_DIAGNOSTIC_BYTES + 1000),
181
+ networkRequests: [],
182
+ consoleErrors: [],
183
+ },
184
+ timestamp: new Date().toISOString(),
185
+ };
186
+ emitDiagnostic(ctx);
187
+ const output = writeSpy.mock.calls.map(c => c[0]).join('');
188
+ const match = output.match(/___OPENCLI_DIAGNOSTIC___\n(.*)\n___OPENCLI_DIAGNOSTIC___/);
189
+ expect(match).toBeTruthy();
190
+ const parsed = JSON.parse(match[1]);
191
+ // Page snapshot should be replaced or page dropped entirely
192
+ expect(parsed.page?.snapshot !== ctx.page.snapshot || parsed.page === undefined).toBe(true);
193
+ expect(match[1].length).toBeLessThanOrEqual(MAX_DIAGNOSTIC_BYTES);
194
+ writeSpy.mockRestore();
195
+ });
196
+ it('redacts sensitive headers in network requests', () => {
197
+ const pageState = {
198
+ url: 'https://example.com',
199
+ snapshot: '<div/>',
200
+ networkRequests: [{
201
+ url: 'https://api.com/data?token=secret123',
202
+ headers: { authorization: 'Bearer xyz', 'content-type': 'application/json' },
203
+ body: '{"data": "ok"}',
204
+ }],
205
+ consoleErrors: [],
206
+ };
207
+ // Build context manually to test redaction via collectPageState
208
+ // Since collectPageState is private, test the output of buildRepairContext
209
+ // with already-collected page state — redaction happens in collectPageState.
210
+ // For unit test, verify redactUrl directly (tested above) and trust integration.
211
+ expect(redactUrl('https://api.com/data?token=secret123')).toContain('[REDACTED]');
212
+ });
213
+ });
214
+ function makePage(overrides = {}) {
215
+ return {
216
+ goto: vi.fn(),
217
+ evaluate: vi.fn(),
218
+ getCookies: vi.fn(),
219
+ snapshot: vi.fn().mockResolvedValue('<div>...</div>'),
220
+ click: vi.fn(),
221
+ typeText: vi.fn(),
222
+ pressKey: vi.fn(),
223
+ scrollTo: vi.fn(),
224
+ getFormState: vi.fn(),
225
+ wait: vi.fn(),
226
+ tabs: vi.fn(),
227
+ selectTab: vi.fn(),
228
+ networkRequests: vi.fn().mockResolvedValue([]),
229
+ consoleMessages: vi.fn().mockResolvedValue([]),
230
+ scroll: vi.fn(),
231
+ autoScroll: vi.fn(),
232
+ installInterceptor: vi.fn(),
233
+ getInterceptedRequests: vi.fn().mockResolvedValue([]),
234
+ waitForCapture: vi.fn(),
235
+ screenshot: vi.fn(),
236
+ getCurrentUrl: vi.fn().mockResolvedValue('https://example.com/page'),
237
+ ...overrides,
238
+ };
239
+ }
240
+ describe('collectDiagnostic', () => {
241
+ it('keeps intercepted payloads in a dedicated capturedPayloads field', async () => {
242
+ const page = makePage({
243
+ networkRequests: vi.fn().mockResolvedValue([{ url: '/api/data', status: 200 }]),
244
+ getInterceptedRequests: vi.fn().mockResolvedValue([{ items: [{ id: 1 }] }]),
245
+ });
246
+ const ctx = await collectDiagnostic(new Error('boom'), makeCmd(), page);
247
+ expect(ctx.page?.networkRequests).toEqual([
248
+ { url: '/api/data', status: 200 },
249
+ ]);
250
+ expect(ctx.page?.capturedPayloads).toEqual([
251
+ { source: 'interceptor', responseBody: { items: [{ id: 1 }] } },
252
+ ]);
253
+ });
254
+ it('preserves the previous network request output when interception is empty', async () => {
255
+ const page = makePage({
256
+ networkRequests: vi.fn().mockResolvedValue([{ url: '/api/data', status: 200 }]),
257
+ getInterceptedRequests: vi.fn().mockResolvedValue([]),
258
+ });
259
+ const ctx = await collectDiagnostic(new Error('boom'), makeCmd(), page);
260
+ expect(ctx.page?.networkRequests).toEqual([{ url: '/api/data', status: 200 }]);
261
+ expect(ctx.page?.capturedPayloads).toEqual([]);
262
+ });
263
+ it('swallows intercepted request failures and still returns page state', async () => {
264
+ const page = makePage({
265
+ networkRequests: vi.fn().mockResolvedValue([{ url: '/api/data', status: 200 }]),
266
+ getInterceptedRequests: vi.fn().mockRejectedValue(new Error('interceptor unavailable')),
267
+ });
268
+ const ctx = await collectDiagnostic(new Error('boom'), makeCmd(), page);
269
+ expect(ctx.page).toEqual({
270
+ url: 'https://example.com/page',
271
+ snapshot: '<div>...</div>',
272
+ networkRequests: [{ url: '/api/data', status: 200 }],
273
+ capturedPayloads: [],
274
+ consoleErrors: [],
275
+ });
276
+ });
277
+ it('redacts and truncates intercepted payloads recursively', async () => {
278
+ const page = makePage({
279
+ getInterceptedRequests: vi.fn().mockResolvedValue([{
280
+ token: 'token=abc123def456ghi789',
281
+ nested: {
282
+ cookie: 'cookie: session=super-secret-cookie-value',
283
+ body: 'x'.repeat(5000),
284
+ },
285
+ }]),
286
+ });
287
+ const ctx = await collectDiagnostic(new Error('boom'), makeCmd(), page);
288
+ const payload = ctx.page?.capturedPayloads?.[0];
289
+ const body = payload.responseBody.nested.body;
290
+ expect(payload).toEqual({
291
+ source: 'interceptor',
292
+ responseBody: {
293
+ token: 'token=[REDACTED]',
294
+ nested: {
295
+ cookie: 'cookie: [REDACTED]',
296
+ body,
297
+ },
298
+ },
299
+ });
300
+ expect(body).toContain('[truncated,');
301
+ expect(body.length).toBeLessThan(5000);
302
+ });
84
303
  });
@@ -15,6 +15,7 @@ import yaml from 'js-yaml';
15
15
  import { Strategy, registerCommand } from './registry.js';
16
16
  import { getErrorMessage } from './errors.js';
17
17
  import { log } from './logger.js';
18
+ import { findPackageRoot, getCliManifestPath, getFetchAdaptersScriptPath } from './package-paths.js';
18
19
  /** User runtime directory: ~/.opencli */
19
20
  export const USER_OPENCLI_DIR = path.join(os.homedir(), '.opencli');
20
21
  /** User CLIs directory: ~/.opencli/clis */
@@ -31,18 +32,7 @@ function parseStrategy(rawStrategy, fallback = Strategy.COOKIE) {
31
32
  return Strategy[key] ?? fallback;
32
33
  }
33
34
  import { isRecord } from './utils.js';
34
- /**
35
- * Find the package root (directory containing package.json).
36
- * Dev: import.meta.url is in src/ → one level up.
37
- * Prod: import.meta.url is in dist/src/ → two levels up.
38
- */
39
- function findPackageRoot() {
40
- let dir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
41
- if (!fs.existsSync(path.join(dir, 'package.json'))) {
42
- dir = path.resolve(dir, '..');
43
- }
44
- return dir;
45
- }
35
+ const PACKAGE_ROOT = findPackageRoot(fileURLToPath(import.meta.url));
46
36
  /**
47
37
  * Ensure ~/.opencli/node_modules/@jackwener/opencli symlink exists so that
48
38
  * user CLIs in ~/.opencli/clis/ can `import { cli } from '@jackwener/opencli/registry'`.
@@ -65,7 +55,7 @@ export async function ensureUserCliCompatShims(baseDir = USER_OPENCLI_DIR) {
65
55
  await fs.promises.writeFile(pkgJsonPath, pkgJsonContent, 'utf-8');
66
56
  }
67
57
  // Create node_modules/@jackwener/opencli symlink pointing to the installed package root.
68
- const opencliRoot = findPackageRoot();
58
+ const opencliRoot = PACKAGE_ROOT;
69
59
  const symlinkDir = path.join(baseDir, 'node_modules', '@jackwener');
70
60
  const symlinkPath = path.join(symlinkDir, 'opencli');
71
61
  try {
@@ -116,7 +106,7 @@ export async function ensureUserAdapters() {
116
106
  log.info('First run detected — copying adapters (one-time setup)...');
117
107
  try {
118
108
  const { execFileSync } = await import('node:child_process');
119
- const scriptPath = path.join(findPackageRoot(), 'scripts', 'fetch-adapters.js');
109
+ const scriptPath = getFetchAdaptersScriptPath(PACKAGE_ROOT);
120
110
  execFileSync(process.execPath, [scriptPath], {
121
111
  stdio: 'inherit',
122
112
  env: { ...process.env, _OPENCLI_FIRST_RUN: '1' },
@@ -135,7 +125,7 @@ export async function ensureUserAdapters() {
135
125
  export async function discoverClis(...dirs) {
136
126
  // Fast path: try manifest first (production / post-build)
137
127
  for (const dir of dirs) {
138
- const manifestPath = path.resolve(dir, '..', 'cli-manifest.json');
128
+ const manifestPath = getCliManifestPath(dir);
139
129
  try {
140
130
  await fs.promises.access(manifestPath);
141
131
  const loaded = await loadFromManifest(manifestPath, dir);
@@ -173,7 +163,7 @@ async function loadFromManifest(manifestPath, clisDir) {
173
163
  columns: entry.columns,
174
164
  pipeline: entry.pipeline,
175
165
  timeoutSeconds: entry.timeout,
176
- source: `manifest:${entry.site}/${entry.name}`,
166
+ source: entry.sourceFile ? path.resolve(clisDir, entry.sourceFile) : `manifest:${entry.site}/${entry.name}`,
177
167
  deprecated: entry.deprecated,
178
168
  replacedBy: entry.replacedBy,
179
169
  navigateBefore: entry.navigateBefore,
@@ -196,7 +186,7 @@ async function loadFromManifest(manifestPath, clisDir) {
196
186
  args: entry.args ?? [],
197
187
  columns: entry.columns,
198
188
  timeoutSeconds: entry.timeout,
199
- source: modulePath,
189
+ source: entry.sourceFile ? path.resolve(clisDir, entry.sourceFile) : modulePath,
200
190
  deprecated: entry.deprecated,
201
191
  replacedBy: entry.replacedBy,
202
192
  navigateBefore: entry.navigateBefore,
@@ -17,7 +17,9 @@ export type ConnectivityResult = {
17
17
  export type DoctorReport = {
18
18
  cliVersion?: string;
19
19
  daemonRunning: boolean;
20
+ daemonFlaky?: boolean;
20
21
  extensionConnected: boolean;
22
+ extensionFlaky?: boolean;
21
23
  extensionVersion?: string;
22
24
  connectivity?: ConnectivityResult;
23
25
  sessions?: Array<{