@ultimat3/cli 31.27.0 → 31.28.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 (107) hide show
  1. package/CLAUDE.md +3 -1
  2. package/README.md +14 -4
  3. package/package.json +29 -29
  4. package/src/app-manifest.ts +6 -1
  5. package/src/cmd-doctor.ts +11 -3
  6. package/src/cmd-repro-spec.ts +13 -1
  7. package/src/cmd-repro.ts +37 -5
  8. package/src/cmd-upgrade-codemods.ts +71 -0
  9. package/src/cmd-upgrade-spec.ts +19 -5
  10. package/src/cmd-upgrade.ts +91 -34
  11. package/src/codemods/agents-dev-mcp.ts +50 -0
  12. package/src/codemods/authenticator-session-refusal.ts +214 -0
  13. package/src/codemods/biome-no-default-export.ts +58 -0
  14. package/src/codemods/bunfig-island-coverage.ts +33 -0
  15. package/src/codemods/chart-dashboard.ts +73 -0
  16. package/src/codemods/ci-e2e-browser-stock.ts +75 -0
  17. package/src/codemods/ci-e2e-browser.ts +63 -0
  18. package/src/codemods/codemod.ts +58 -0
  19. package/src/codemods/define-error-leaf.ts +73 -0
  20. package/src/codemods/docs-ci-parts.ts +65 -0
  21. package/src/codemods/docs-gate-prose.ts +53 -0
  22. package/src/codemods/docs-island-rows.ts +31 -0
  23. package/src/codemods/docs-shipped-guards.ts +100 -0
  24. package/src/codemods/docs-test-services.ts +62 -0
  25. package/src/codemods/engine-diff.ts +104 -0
  26. package/src/codemods/engine-edits.ts +111 -0
  27. package/src/codemods/engine-fs.ts +95 -0
  28. package/src/codemods/engine.ts +191 -0
  29. package/src/codemods/format-edited-hook-3122.ts +28 -0
  30. package/src/codemods/format-edited-hook.ts +152 -0
  31. package/src/codemods/helm-alerts-objective.ts +105 -0
  32. package/src/codemods/helm-alerts-stock.ts +108 -0
  33. package/src/codemods/index.ts +56 -0
  34. package/src/codemods/metrics-probe-healthz.ts +47 -0
  35. package/src/codemods/pending.ts +36 -0
  36. package/src/codemods/repro-gitignore.ts +40 -0
  37. package/src/codemods/runtime-pin-lines.ts +109 -0
  38. package/src/codemods/runtime-pin.ts +116 -0
  39. package/src/codemods/solid-floor.ts +63 -0
  40. package/src/codemods/test-ports.ts +86 -0
  41. package/src/codemods/test-suites.ts +37 -0
  42. package/src/codemods/theme-toggle-mount-over.ts +70 -0
  43. package/src/codemods/vendored-guards.ts +186 -0
  44. package/src/codemods/verify-floor-skips.ts +88 -0
  45. package/src/codemods/verify-floor-steps.ts +90 -0
  46. package/src/doctor-advisory-floors.ts +113 -0
  47. package/src/doctor-guards.ts +39 -86
  48. package/src/doctor-superseded.ts +67 -0
  49. package/src/error-codes-doctor.ts +12 -4
  50. package/src/error-codes.ts +6 -0
  51. package/src/exercise-database.ts +7 -2
  52. package/src/generate-files.ts +6 -5
  53. package/src/guards-built-in-codes.ts +36 -0
  54. package/src/guards-built-in-refusal.ts +25 -0
  55. package/src/guards-built-in.ts +134 -0
  56. package/src/guards-materialize.ts +42 -0
  57. package/src/guards-paths.ts +37 -0
  58. package/src/guards-shipped-names.ts +38 -0
  59. package/src/guards-vendored.ts +73 -0
  60. package/src/guards.ts +90 -34
  61. package/src/index.ts +10 -0
  62. package/src/lint-findings.ts +3 -3
  63. package/src/mcp-errors.ts +11 -1
  64. package/src/measure-scope.ts +23 -3
  65. package/src/messages-repro.ts +16 -2
  66. package/src/messages-upgrade.ts +15 -0
  67. package/src/messages.ts +1 -1
  68. package/src/repro-archive-collect.ts +161 -0
  69. package/src/repro-archive-write.ts +96 -0
  70. package/src/repro-archive.ts +161 -0
  71. package/src/repro-bundle.ts +8 -16
  72. package/src/repro-errors.ts +14 -2
  73. package/src/repro-framework.ts +53 -0
  74. package/src/repro-parse.ts +87 -0
  75. package/src/repro-redact.ts +218 -0
  76. package/src/repro-scrub.ts +257 -0
  77. package/src/superseded-match.ts +87 -0
  78. package/src/superseded.ts +84 -0
  79. package/src/templates/bun-image.ts +48 -0
  80. package/src/templates/github/ci.yml.ts +1 -1
  81. package/src/templates/guard-released-forms.ts +112 -0
  82. package/src/templates/guard-runtime-pin-test.ts +54 -0
  83. package/src/templates/guard-runtime-pin.ts +189 -0
  84. package/src/templates/scaffold-claude-agents.ts +6 -6
  85. package/src/templates/scaffold-claude-commands.ts +1 -1
  86. package/src/templates/scaffold-claude-hook.ts +18 -8
  87. package/src/templates/scaffold-claude.ts +2 -2
  88. package/src/templates/scaffold-docs.ts +26 -24
  89. package/src/templates/scaffold-guards.ts +73 -39
  90. package/src/templates/scaffold-repo.ts +2 -1
  91. package/src/unthrown-codes.ts +2 -0
  92. package/src/upgrade-bun-floor.ts +4 -0
  93. package/src/upgrade-clean-tree.ts +54 -0
  94. package/src/upgrade-gate-codemods-install.ts +40 -0
  95. package/src/upgrade-gate-codemods.ts +151 -0
  96. package/src/upgrade-gate.ts +38 -6
  97. package/src/upgrade-lock.ts +118 -0
  98. package/src/upgrade-plan.ts +2 -1
  99. package/src/upgrade-report-codemods.ts +54 -0
  100. package/src/upgrade-report.ts +52 -27
  101. package/src/upgrade-signals.ts +91 -0
  102. package/src/upgrade-unfinished.ts +61 -0
  103. package/wiki/CLI-Reference.md +58 -4
  104. package/wiki/Interface-Rules.md +17 -8
  105. package/wiki/Observability.md +1 -0
  106. package/wiki/Project-Layout.md +4 -4
  107. package/wiki/Upgrading.md +5 -0
@@ -0,0 +1,87 @@
1
+ // Single responsibility: a repro subject read from a file a stranger may have written (`--from`, a
2
+ // bundle `create-ultimate repro` opens). Every field the replay and the written test read is
3
+ // checked and the subject REBUILT from those alone — nothing unknown rides along — and a name,
4
+ // code, step or id holding a control character (a terminal escape, a line break) is refused.
5
+
6
+ import type { FailureBundle, FailureRead } from '@ultimat3/core';
7
+ import { isJsonObject } from '@ultimat3/core';
8
+ import type { JobFailure } from '@ultimat3/testing';
9
+ import type { ReproSubject } from './repro-bundle';
10
+
11
+ /** The actor a bundle carries; core's barrel names the bundle, not its parts. */
12
+ type FailureActor = NonNullable<FailureBundle['actor']>;
13
+
14
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: refusing them is the point.
15
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
16
+
17
+ /** A string a terminal or a `//` comment can print as it stands. */
18
+ const label = (value: unknown): value is string =>
19
+ typeof value === 'string' && !CONTROL.test(value);
20
+ const labelOrNull = (value: unknown): value is string | null => value === null || label(value);
21
+ const labels = (value: unknown): value is string[] => Array.isArray(value) && value.every(label);
22
+
23
+ function actorOf(value: unknown): FailureActor | null | undefined {
24
+ if (value === null) return null;
25
+ if (!isJsonObject(value)) return undefined;
26
+ const { kind, id, orgId, roles, scopes, permissions } = value;
27
+ if (!label(kind) || !label(id) || !labelOrNull(orgId)) return undefined;
28
+ if (!labels(roles) || !labels(scopes) || !labels(permissions)) return undefined;
29
+ return { kind, id, orgId, roles, scopes, permissions };
30
+ }
31
+
32
+ function readsOf(value: unknown): FailureRead[] | undefined {
33
+ if (!Array.isArray(value)) return undefined;
34
+ const reads: FailureRead[] = [];
35
+ for (const read of value) {
36
+ if (!isJsonObject(read) || !label(read['entity']) || !isJsonObject(read['row']))
37
+ return undefined;
38
+ if (!labels(read['masked'])) return undefined;
39
+ reads.push({ entity: read['entity'], row: read['row'], masked: read['masked'] });
40
+ }
41
+ return reads;
42
+ }
43
+
44
+ function bundleOf(value: Record<string, unknown>): FailureBundle | undefined {
45
+ const { id, fingerprint, code, operation, primitive, name, at, requestId, traceId, build } =
46
+ value;
47
+ if (!label(id) || !label(fingerprint) || !label(code) || !labelOrNull(operation))
48
+ return undefined;
49
+ if ((primitive !== 'action' && primitive !== 'query') || !label(name)) return undefined;
50
+ if (typeof at !== 'number' || !Number.isFinite(at)) return undefined;
51
+ if (!labelOrNull(requestId) || !labelOrNull(traceId) || !labelOrNull(build)) return undefined;
52
+ const actor = actorOf(value['actor']);
53
+ const reads = readsOf(value['reads']);
54
+ const { masked, flags, truncated } = value;
55
+ if (actor === undefined || reads === undefined || !labels(masked) || !isJsonObject(flags)) {
56
+ return undefined;
57
+ }
58
+ if (typeof truncated !== 'boolean') return undefined;
59
+ const input = value['input'] ?? null;
60
+ return {
61
+ ...{ id, fingerprint, code, operation, primitive, name, at, requestId, traceId, build },
62
+ ...{ input, masked, actor, flags, reads, truncated },
63
+ };
64
+ }
65
+
66
+ function failureOf(value: Record<string, unknown>): JobFailure | undefined {
67
+ const { jobId, name, masked, steps, code, step } = value;
68
+ if (!label(jobId) || !label(name) || !labels(masked) || !Array.isArray(steps)) return undefined;
69
+ if (!labelOrNull(code) || !labelOrNull(step)) return undefined;
70
+ const kept: { name: string; output: unknown }[] = [];
71
+ for (const entry of steps) {
72
+ if (!isJsonObject(entry) || !label(entry['name'])) return undefined;
73
+ kept.push({ name: entry['name'], output: entry['output'] ?? null });
74
+ }
75
+ return { jobId, name, input: value['input'] ?? null, masked, steps: kept, code, step };
76
+ }
77
+
78
+ /** The subject `value` is, rebuilt from its checked fields; `undefined` for anything else. */
79
+ export function parseReproSubject(value: unknown): ReproSubject | undefined {
80
+ if (!isJsonObject(value)) return undefined;
81
+ if ('jobId' in value) {
82
+ const failure = failureOf(value);
83
+ return failure === undefined ? undefined : { kind: 'job', failure };
84
+ }
85
+ const bundle = bundleOf(value);
86
+ return bundle === undefined ? undefined : { kind: 'request', bundle };
87
+ }
@@ -0,0 +1,218 @@
1
+ // Single responsibility: a repro subject as it may leave the app. Always: input masked by its
2
+ // `.sensitive()` schema and core's `captureValue`, rows minus sealed columns, undeclared entities
3
+ // dropped. By default, every value that is not a key becomes a stand-in the replay fills
4
+ // (`@ultimat3/testing`'s `repro-stand-in.ts`) and the actor's org a placeholder; `includeRows` opts out.
5
+
6
+ import type { FailureBundle, FailureRead } from '@ultimat3/core';
7
+ import { captureValue, REDACTED } from '@ultimat3/core';
8
+ import type { EntityDescription } from '@ultimat3/entity';
9
+ import { maskSensitive } from '@ultimat3/schema';
10
+ import type { ReproSubject } from './repro-bundle';
11
+
12
+ /** The actor a bundle carries; core's barrel names the bundle, not its parts. */
13
+ type FailureActor = NonNullable<FailureBundle['actor']>;
14
+
15
+ /** What the app declared, asked by name: the registries in production, a table in a test. */
16
+ export interface ReproLookups {
17
+ /** The input schema of the job, action or query `name`; `undefined` when none is registered. */
18
+ inputSchema(kind: 'job' | 'action' | 'query', name: string): unknown;
19
+ /** The entity `name`, its description and its sealed properties; `undefined` when undeclared. */
20
+ entity(
21
+ name: string,
22
+ ): { readonly description: EntityDescription; readonly sealed: readonly string[] } | undefined;
23
+ }
24
+
25
+ export interface RedactOptions {
26
+ /** `x repro --bundle --include-rows`: real non-key values. Secrets stay masked either way. */
27
+ readonly includeRows: boolean;
28
+ }
29
+
30
+ export interface RedactedSubject {
31
+ readonly subject: ReproSubject;
32
+ /** The declarations of the entities whose rows the reproducer seeds, by name. */
33
+ readonly entities: readonly EntityDescription[];
34
+ /** Entities whose read rows were dropped: not declared by this app. Sorted, unique. */
35
+ readonly dropped: readonly string[];
36
+ /** Every masked path in the subject: input paths bare, `<entity>:<path>`, `step:<name>:<path>`. */
37
+ readonly masked: readonly string[];
38
+ }
39
+
40
+ /** The actor's org, everywhere it appears: a uuid so a uuid column still takes it. */
41
+ export const ORG_STAND_IN = '00000000-0000-4000-8000-000000000001';
42
+
43
+ /** A key by its name: `id`, `postId`, `post_id`, `tagIds`. What seeding links rows by. */
44
+ const KEY_NAME = /^id$|Ids?$|_ids?$/;
45
+
46
+ const sorted = (paths: Iterable<string>): string[] => [...new Set(paths)].sort();
47
+
48
+ /**
49
+ * Every leaf not under a key name, replaced — `REDACTED` (which the replay fills from the schema)
50
+ * or, where `typed` asks for a shape the replay cannot rebuild, `0` for a number and the boolean as
51
+ * it was. Each replaced path is listed.
52
+ */
53
+ function standIn(value: unknown, at: string, masked: string[], typed: boolean, key = ''): unknown {
54
+ if (value === REDACTED || value === null || value === undefined) return value;
55
+ if (Array.isArray(value))
56
+ return value.map((entry) => standIn(entry, `${at}[]`, masked, typed, key));
57
+ if (typeof value === 'object') {
58
+ const out: Record<string, unknown> = {};
59
+ for (const [name, entry] of Object.entries(value)) {
60
+ const path = at === '' ? name : `${at}.${name}`;
61
+ Object.defineProperty(out, name, {
62
+ value: standIn(entry, path, masked, typed, name),
63
+ enumerable: true,
64
+ writable: true,
65
+ configurable: true,
66
+ });
67
+ }
68
+ return out;
69
+ }
70
+ if (KEY_NAME.test(key)) return value;
71
+ if (typed && typeof value === 'boolean') return value;
72
+ masked.push(at);
73
+ return typed && typeof value === 'number' ? 0 : REDACTED;
74
+ }
75
+
76
+ /** The input, masked by its schema's `.sensitive()` flags, core's capture rules, then stood in. */
77
+ function maskedInput(schema: unknown, input: unknown, options: RedactOptions) {
78
+ const flagged = schema === undefined ? input : maskSensitive(schema, input, REDACTED);
79
+ const { value, masked } = captureValue(flagged);
80
+ const paths = [...masked];
81
+ const kept = options.includeRows ? value : standIn(value, '', paths, false);
82
+ return { value: kept, masked: paths };
83
+ }
84
+
85
+ /** Every string leaf equal to the actor's org, replaced by `ORG_STAND_IN`. */
86
+ function withOrg(value: unknown, org: string): unknown {
87
+ if (value === org) return ORG_STAND_IN;
88
+ if (Array.isArray(value)) return value.map((entry) => withOrg(entry, org));
89
+ if (value === null || typeof value !== 'object') return value;
90
+ const out: Record<string, unknown> = {};
91
+ for (const [name, entry] of Object.entries(value)) {
92
+ Object.defineProperty(out, name, {
93
+ value: withOrg(entry, org),
94
+ enumerable: true,
95
+ writable: true,
96
+ configurable: true,
97
+ });
98
+ }
99
+ return out;
100
+ }
101
+
102
+ function redactJob(
103
+ subject: Extract<ReproSubject, { kind: 'job' }>,
104
+ lookups: ReproLookups,
105
+ options: RedactOptions,
106
+ ): RedactedSubject {
107
+ const { failure } = subject;
108
+ const input = maskedInput(lookups.inputSchema('job', failure.name), failure.input, options);
109
+ const stepMasks: string[] = [];
110
+ const steps = failure.steps.map((step) => {
111
+ const { value, masked } = captureValue(step.output);
112
+ const paths = [...masked];
113
+ const output = options.includeRows ? value : standIn(value, '', paths, true);
114
+ stepMasks.push(...sorted(paths).map((path) => `step:${step.name}:${path}`));
115
+ return { name: step.name, output };
116
+ });
117
+ const inputMasks = sorted([...failure.masked, ...input.masked]);
118
+ return {
119
+ subject: {
120
+ kind: 'job',
121
+ failure: { ...failure, input: input.value, masked: inputMasks, steps },
122
+ },
123
+ entities: [],
124
+ dropped: [],
125
+ masked: [...inputMasks, ...stepMasks],
126
+ };
127
+ }
128
+
129
+ /** The properties a row keeps under stand-ins: its primary key, its references, and key names. */
130
+ const keysOf = (description: EntityDescription): ReadonlySet<string> =>
131
+ new Set(
132
+ description.columns
133
+ .filter((column) => column.primaryKey || column.references !== null)
134
+ .map((column) => column.property),
135
+ );
136
+
137
+ function redactRead(
138
+ read: FailureRead,
139
+ declared: { readonly description: EntityDescription; readonly sealed: readonly string[] },
140
+ options: RedactOptions,
141
+ ): FailureRead {
142
+ const keys = keysOf(declared.description);
143
+ const row = Object.fromEntries(
144
+ Object.entries(read.row).filter(([property]) => !declared.sealed.includes(property)),
145
+ );
146
+ const { value, masked } = captureValue(row);
147
+ const paths = [...read.masked, ...masked];
148
+ const kept = value as Record<string, unknown>;
149
+ if (!options.includeRows) {
150
+ for (const [property, entry] of Object.entries(kept)) {
151
+ if (keys.has(property) || KEY_NAME.test(property) || entry === null || entry === REDACTED)
152
+ continue;
153
+ kept[property] = REDACTED;
154
+ paths.push(property);
155
+ }
156
+ }
157
+ return { entity: read.entity, row: kept, masked: sorted(paths) };
158
+ }
159
+
160
+ function redactRequest(
161
+ subject: Extract<ReproSubject, { kind: 'request' }>,
162
+ lookups: ReproLookups,
163
+ options: RedactOptions,
164
+ ): RedactedSubject {
165
+ const { bundle } = subject;
166
+ const input = maskedInput(
167
+ lookups.inputSchema(bundle.primitive, bundle.name),
168
+ bundle.input,
169
+ options,
170
+ );
171
+ const dropped = new Set<string>();
172
+ const kept = new Map<string, EntityDescription>();
173
+ const reads: FailureRead[] = [];
174
+ for (const read of bundle.reads) {
175
+ const declared = lookups.entity(read.entity);
176
+ if (declared === undefined) {
177
+ dropped.add(read.entity);
178
+ continue;
179
+ }
180
+ kept.set(read.entity, declared.description);
181
+ reads.push(redactRead(read, declared, options));
182
+ }
183
+ const inputMasks = sorted([...bundle.masked, ...input.masked]);
184
+ const org = options.includeRows ? null : (bundle.actor?.orgId ?? null);
185
+ const swap = <T>(value: T): T => (org === null ? value : (withOrg(value, org) as T));
186
+ const actor: FailureActor | null =
187
+ bundle.actor === null || org === null ? bundle.actor : { ...bundle.actor, orgId: ORG_STAND_IN };
188
+ return {
189
+ subject: {
190
+ kind: 'request',
191
+ bundle: {
192
+ ...bundle,
193
+ input: swap(input.value),
194
+ masked: inputMasks,
195
+ actor,
196
+ flags: captureValue(bundle.flags).value as Record<string, unknown>,
197
+ reads: swap(reads),
198
+ truncated: bundle.truncated || dropped.size > 0,
199
+ },
200
+ },
201
+ entities: [...kept.keys()].sort().map((name) => kept.get(name) as EntityDescription),
202
+ dropped: [...dropped].sort(),
203
+ masked: [
204
+ ...inputMasks,
205
+ ...sorted(reads.flatMap((read) => read.masked.map((path) => `${read.entity}:${path}`))),
206
+ ],
207
+ };
208
+ }
209
+
210
+ export function redactSubject(
211
+ subject: ReproSubject,
212
+ lookups: ReproLookups,
213
+ options: RedactOptions,
214
+ ): RedactedSubject {
215
+ return subject.kind === 'job'
216
+ ? redactJob(subject, lookups, options)
217
+ : redactRequest(subject, lookups, options);
218
+ }
@@ -0,0 +1,257 @@
1
+ // Single responsibility: what a repro bundle may say about the MACHINE and the people on it. The app
2
+ // root, home, secret-named / URL / dotenv env values (and a URL's credentials in every encoding),
3
+ // config hostnames, any URL's userinfo and query values, emails and IPs become tokens; a frame's
4
+ // absolute path is made relative. A value it was never told about is NOT found: say so to the user.
5
+
6
+ import { isRedactedKey } from '@ultimat3/core';
7
+
8
+ export interface ScrubEnv {
9
+ readonly name: string;
10
+ readonly value: string | undefined;
11
+ /** `process`: hidden only when secret-named or a URL. `dotenv`: an app file's, always hidden. */
12
+ readonly from: 'process' | 'dotenv';
13
+ }
14
+
15
+ export interface ScrubSources {
16
+ /** The app root, absolute. Becomes `.`. */
17
+ readonly root: string;
18
+ /** Every spelling of the home directory known here. Each becomes `~`. */
19
+ readonly homes: readonly string[];
20
+ readonly env: readonly ScrubEnv[];
21
+ /** Hostnames named by the config (and the machine's own); each becomes `[host]`. */
22
+ readonly hosts: readonly string[];
23
+ }
24
+
25
+ export interface ScrubReport {
26
+ /** Names (never values) of the env vars whose value was found and replaced, sorted. */
27
+ readonly env: readonly string[];
28
+ /** How many distinct hostnames were found and replaced. */
29
+ readonly hosts: number;
30
+ }
31
+
32
+ export interface Scrubber {
33
+ /** Every string leaf and key of a JSON-safe value, scrubbed. */
34
+ value(value: unknown): unknown;
35
+ /** A cause or a stack frame: scrubbed, then any absolute path left made relative. */
36
+ location(text: string): string;
37
+ report(): ScrubReport;
38
+ }
39
+
40
+ interface Needle {
41
+ readonly find: string;
42
+ readonly replace: string;
43
+ readonly env?: string;
44
+ readonly host?: true;
45
+ /** Matched as a whole token only: a URL's user `app` must not eat the `app` in `apps/`. */
46
+ readonly word?: true;
47
+ }
48
+
49
+ /** Shorter than this, a dotenv value is a flag (`true`, `3000`) that would match everywhere. */
50
+ const MIN_ENV_VALUE = 6;
51
+ /** A secret-NAMED var, or a URL's credential, hides from this length: a PIN is still a credential. */
52
+ const MIN_SECRET_VALUE = 3;
53
+ const LOOPBACK = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1', '[::1]']);
54
+
55
+ const parseUrl = (text: string): URL | undefined => {
56
+ if (!text.includes('://')) return undefined;
57
+ try {
58
+ return new URL(text.trim());
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ };
63
+
64
+ /** The hostname inside an env value or config string that is a URL or a DSN, else `undefined`. */
65
+ export function hostOf(text: string): string | undefined {
66
+ const host = parseUrl(text)?.hostname.toLowerCase();
67
+ return host === undefined || host === '' || LOOPBACK.has(host) ? undefined : host;
68
+ }
69
+
70
+ const decoded = (text: string): string => {
71
+ try {
72
+ return decodeURIComponent(text);
73
+ } catch {
74
+ return text;
75
+ }
76
+ };
77
+
78
+ /** Every spelling a credential travels in: as written, URL-decoded, and base64 (a Basic header). */
79
+ function credentialSpellings(value: string): string[] {
80
+ const url = parseUrl(value);
81
+ if (url === undefined || (url.username === '' && url.password === '')) {
82
+ return base64Of([value]);
83
+ }
84
+ const user = decoded(url.username);
85
+ const pass = decoded(url.password);
86
+ return [
87
+ url.username,
88
+ url.password,
89
+ user,
90
+ pass,
91
+ ...base64Of([`${user}:${pass}`, `${url.username}:${url.password}`]),
92
+ ];
93
+ }
94
+
95
+ /**
96
+ * Base64 of each text's UTF-8 bytes — what a Basic header holds; `btoa` alone throws past Latin-1
97
+ * (`pässwörd€`) and took `x repro --bundle` down with it. A spelling that cannot be built is
98
+ * skipped, never the scrub.
99
+ */
100
+ function base64Of(texts: readonly string[]): string[] {
101
+ const out: string[] = [];
102
+ for (const text of texts) {
103
+ try {
104
+ out.push(btoa(String.fromCharCode(...new TextEncoder().encode(text))));
105
+ } catch {
106
+ // One spelling fewer: the raw and decoded values are still needles.
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /** Both separators of a path, so a Windows root pasted either way is found. */
113
+ const spellings = (path: string): string[] =>
114
+ [...new Set([path, path.replaceAll('\\', '/'), path.replaceAll('/', '\\')])].filter(
115
+ (spelling) => spelling.length > 1,
116
+ );
117
+
118
+ function needlesOf(sources: ScrubSources): { paths: Needle[]; values: Needle[] } {
119
+ const paths = [
120
+ ...spellings(sources.root).map((find) => ({ find, replace: '.' })),
121
+ ...sources.homes.flatMap(spellings).map((find) => ({ find, replace: '~' })),
122
+ ];
123
+ const values: Needle[] = [];
124
+ const hosts = new Set(sources.hosts.map((host) => host.toLowerCase()));
125
+ for (const { name, value: raw, from } of sources.env) {
126
+ // Trimmed first: a dotenv `TOKEN="abc\n"` is held by the app, and reaches a log, as `abc`.
127
+ const value = raw?.trim();
128
+ if (value === undefined || value === '') continue;
129
+ const host = hostOf(value);
130
+ if (host !== undefined) hosts.add(host);
131
+ const secret = isRedactedKey(name);
132
+ const hidden = secret || host !== undefined || from === 'dotenv';
133
+ if (!hidden) continue;
134
+ const min = secret ? MIN_SECRET_VALUE : MIN_ENV_VALUE;
135
+ if (value.length >= min) values.push({ find: value, replace: `[env:${name}]`, env: name });
136
+ if (!secret && host === undefined) continue;
137
+ for (const find of credentialSpellings(value)) {
138
+ if (find.length >= MIN_SECRET_VALUE) {
139
+ values.push({ find, replace: `[env:${name}]`, env: name, word: true });
140
+ }
141
+ }
142
+ }
143
+ for (const host of hosts) {
144
+ if (host.length > 2 && !LOOPBACK.has(host))
145
+ values.push({ find: host, replace: '[host]', host: true });
146
+ }
147
+ // Longest first: a URL value is replaced whole before the host inside it is looked for.
148
+ const longest = (a: Needle, b: Needle): number => b.find.length - a.find.length;
149
+ return { paths: paths.sort(longest), values: values.sort(longest) };
150
+ }
151
+
152
+ const literal = (text: string): string => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
153
+
154
+ /** A URL in prose: its scheme, then everything up to a space, a quote or a bracket. */
155
+ const URL_TEXT = /\b[a-z][a-z0-9+.-]*:\/\/[^\s'"`<>()]+/gi;
156
+ /** Any URL's userinfo and query VALUES: credentials and tokens ride in both. */
157
+ function withoutUrlSecrets(text: string): string {
158
+ return text.replace(URL_TEXT, (url) =>
159
+ url
160
+ .replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, '$1[cred]@')
161
+ .replace(/\?[^#]*/, (query) => query.replace(/=[^&]*/g, '=[redacted]')),
162
+ );
163
+ }
164
+
165
+ const EMAIL = /(?<![\w.%+-])[\w.%+-]+@[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,}(?![\w-])/gi;
166
+ const OCTET = '(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)';
167
+ const IPV4 = new RegExp(`(?<![\\w.])(?:${OCTET}\\.){3}${OCTET}(?![\\w.])`, 'g');
168
+ const H = '[0-9a-f]{1,4}';
169
+ /** Eight groups, or a `::` with a group on at least one side: never a clock time or `A::b` in a word. */
170
+ const IPV6 = new RegExp(
171
+ `(?<![\\w:.])(?:(?:${H}:){7}${H}|(?:${H}:){1,7}:(?:${H}(?::${H}){0,5})?|::${H}(?::${H}){0,6})(?![\\w:])`,
172
+ 'gi',
173
+ );
174
+
175
+ /** The first segment of a path that is the machine's, whatever its extension. */
176
+ const SYSTEM_ROOT =
177
+ /^\/(?:home|Users|root|tmp|private|var|opt|usr|etc|srv|mnt|nix|snap|proc|run)\//;
178
+ /** An absolute POSIX path not glued to a word, a URL's `//`, or a token this file wrote. */
179
+ const POSIX_PATH = /(?<![\w.~\]:/>@-])\/(?:[^\s/():'"`,]+\/)*[^\s/():'"`,]+/g;
180
+ const WINDOWS_PATH = /\b[A-Za-z]:\\(?:[^\s\\():'"`,]+\\)*[^\s\\():'"`,]+/g;
181
+
182
+ /** A path that is the machine's: a known system root, or a file (its last segment has an extension). */
183
+ function relativePath(path: string, separator: '/' | '\\'): string {
184
+ const segments = path.split(separator);
185
+ const modules = segments.lastIndexOf('node_modules');
186
+ if (modules >= 0) return segments.slice(modules).join('/');
187
+ const last = segments.at(-1) ?? '';
188
+ const isFile = /\.[A-Za-z0-9]+$/.test(last.replace(/(?::\d+)+$/, ''));
189
+ if (separator === '/' && !isFile && !SYSTEM_ROOT.test(`${path}/`)) return path;
190
+ return `<abs>/${last}`;
191
+ }
192
+
193
+ /**
194
+ * A host is a whole name, and only where a host stands: `checkbox` keeps its `box`, and a host
195
+ * after one `/` (a path segment, a package scope's tail) or after a bare `@` is not one. After a
196
+ * URL's `//` or this file's own `[cred]@` it is.
197
+ */
198
+ const hostPattern = (host: string): RegExp =>
199
+ new RegExp(`(?<![\\w.-])(?<!(?:^|[^/])/)(?<!(?:^|[^\\]])@)${literal(host)}(?![\\w-])`, 'gi');
200
+
201
+ export function scrubberFor(sources: ScrubSources): Scrubber {
202
+ const { paths, values } = needlesOf(sources);
203
+ const hitEnv = new Set<string>();
204
+ const hitHosts = new Set<string>();
205
+ const replaceAll = (out: string, needles: readonly Needle[]): string => {
206
+ let next = out;
207
+ for (const needle of needles) {
208
+ const pattern =
209
+ needle.host === true
210
+ ? hostPattern(needle.find)
211
+ : needle.word === true
212
+ ? new RegExp(`(?<![\\w%+-])${literal(needle.find)}(?![\\w%+-])`, 'g')
213
+ : new RegExp(literal(needle.find), 'g');
214
+ if (!pattern.test(next)) continue;
215
+ next = next.replace(pattern, needle.replace);
216
+ if (needle.env !== undefined) hitEnv.add(needle.env);
217
+ if (needle.host === true) hitHosts.add(needle.find);
218
+ }
219
+ return next;
220
+ };
221
+ const envNeedles = values.filter((needle) => needle.host !== true);
222
+ const hostNeedles = values.filter((needle) => needle.host === true);
223
+ const text = (input: string): string => {
224
+ let out = input;
225
+ for (const needle of paths) out = out.replaceAll(needle.find, needle.replace);
226
+ out = withoutUrlSecrets(replaceAll(out, envNeedles));
227
+ return replaceAll(out, hostNeedles)
228
+ .replace(EMAIL, '[email]')
229
+ .replace(IPV4, '[ip]')
230
+ .replace(IPV6, '[ip]');
231
+ };
232
+ const value = (input: unknown, depth = 0): unknown => {
233
+ if (typeof input === 'string') return text(input);
234
+ if (input === null || typeof input !== 'object') return input;
235
+ if (depth > 32) return '[depth-limit]';
236
+ if (Array.isArray(input)) return input.map((entry) => value(entry, depth + 1));
237
+ const out: Record<string, unknown> = {};
238
+ for (const [key, entry] of Object.entries(input)) {
239
+ // `defineProperty`: a key named `__proto__` in captured input must stay a key.
240
+ Object.defineProperty(out, text(key), {
241
+ value: value(entry, depth + 1),
242
+ enumerable: true,
243
+ writable: true,
244
+ configurable: true,
245
+ });
246
+ }
247
+ return out;
248
+ };
249
+ return {
250
+ value: (input) => value(input),
251
+ location: (input) =>
252
+ text(input.replaceAll('file://', ''))
253
+ .replace(POSIX_PATH, (path) => relativePath(path, '/'))
254
+ .replace(WINDOWS_PATH, (path) => relativePath(path, '\\')),
255
+ report: () => ({ env: [...hitEnv].sort(), hosts: hitHosts.size }),
256
+ };
257
+ }
@@ -0,0 +1,87 @@
1
+ // The superseded-workaround matcher, pure over one file's text: its comment blocks, and which
2
+ // table rows one of them names (`superseded.ts`). No I/O — `doctor-superseded.ts` walks the app.
3
+
4
+ import type { SupersededWorkaround } from './superseded';
5
+ import { NEAR_LINES } from './superseded';
6
+
7
+ /** Consecutive comment lines, joined: a note wrapped over three lines is one sentence. */
8
+ export interface CommentBlock {
9
+ /** 1-based, inclusive. */
10
+ readonly start: number;
11
+ readonly end: number;
12
+ readonly text: string;
13
+ }
14
+
15
+ export interface SupersededHit {
16
+ readonly id: string;
17
+ /** `path:line` of the note's first line. */
18
+ readonly at: string;
19
+ }
20
+
21
+ const WHOLE = /^(?:\/\/+|\/\*+|\*+\/?|\{\/\*+)\s?(.*)$/;
22
+ const TAIL = /\s\/\/\s(.*)$/;
23
+
24
+ /** A whole-line comment's text, or the tail after a trailing ` // `; `undefined` for code. */
25
+ function commentText(line: string): string | undefined {
26
+ const whole = WHOLE.exec(line.trim());
27
+ if (whole !== null) return whole[1] ?? '';
28
+ return TAIL.exec(line)?.[1];
29
+ }
30
+
31
+ /** The code on a line: nothing for a whole-line comment, the head before a trailing ` // `. */
32
+ function codePart(line: string): string {
33
+ if (WHOLE.test(line.trim())) return '';
34
+ const tail = TAIL.exec(line);
35
+ return tail === null ? line : line.slice(0, tail.index);
36
+ }
37
+
38
+ /** Markdown is prose throughout: each paragraph is a block. Code reads its comments only. */
39
+ export function commentBlocks(path: string, text: string): readonly CommentBlock[] {
40
+ const prose = path.endsWith('.md');
41
+ const lines = text.split(/\r?\n/);
42
+ const blocks: CommentBlock[] = [];
43
+ let open: { start: number; parts: string[] } | undefined;
44
+ const close = (end: number): void => {
45
+ if (open !== undefined) blocks.push({ start: open.start, end, text: open.parts.join(' ') });
46
+ open = undefined;
47
+ };
48
+ lines.forEach((line, index) => {
49
+ const part = prose ? (line.trim() === '' ? undefined : line.trim()) : commentText(line);
50
+ if (part === undefined) {
51
+ close(index);
52
+ return;
53
+ }
54
+ if (open === undefined) open = { start: index + 1, parts: [] };
55
+ open.parts.push(part);
56
+ });
57
+ close(lines.length);
58
+ return blocks;
59
+ }
60
+
61
+ /** Every row a block of `text` names, once per block, in file order. */
62
+ export function matchSuperseded(
63
+ path: string,
64
+ text: string,
65
+ rows: readonly SupersededWorkaround[],
66
+ ): readonly SupersededHit[] {
67
+ const prose = path.endsWith('.md');
68
+ const blocks = commentBlocks(path, text);
69
+ const lines = text.split(/\r?\n/);
70
+ const hits: SupersededHit[] = [];
71
+ for (const block of blocks) {
72
+ for (const row of rows) {
73
+ if (!row.pattern.comment.every((pattern) => pattern.test(block.text))) continue;
74
+ const near = row.pattern.near;
75
+ if (near !== undefined) {
76
+ // Prose has no code to stand beside: a page quoting the workaround is not holding it.
77
+ if (prose) continue;
78
+ const from = Math.max(0, block.start - 1 - NEAR_LINES);
79
+ const window = lines.slice(from, block.end + NEAR_LINES);
80
+ // Code only: a note quoting `render: 'ssr'` is not the page declaring it.
81
+ if (!window.some((line) => near.test(codePart(line)))) continue;
82
+ }
83
+ hits.push({ id: row.id, at: `${path}:${block.start}` });
84
+ }
85
+ }
86
+ return hits;
87
+ }