@kurvball/rehearse 1.12.0 → 1.12.1

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.
@@ -11,6 +11,7 @@ export declare class Stopped extends Error {
11
11
  constructor(failure: Exclude<Failure, 'usage'>, says: string);
12
12
  }
13
13
  export declare const treeOf: (page: Page) => Promise<string>;
14
+ export declare const seenTree: (page: Page) => Promise<string>;
14
15
  export declare function calm(page: Page): Promise<string>;
15
16
  export declare const failed: (command: Verb | null, at: number, failure: Failure, says: string, driver?: string | null) => DriveResult;
16
17
  export declare function act(page: Page, command: Command, at?: number): Promise<DriveResult>;
@@ -4,6 +4,7 @@ import { RehearseError } from '../errors.js';
4
4
  import { fill, fillEnv } from '../manifest/index.js';
5
5
  import { FAILURE_WORDS, stepCommand, } from './grammar.js';
6
6
  import { ambiguousWords, findNamed, namedIn, notFoundWords, sameWords } from './names.js';
7
+ import { noteSecretsOn, rememberSecretFields, secretsHidden, secretsHiddenInWords } from './secrets.js';
7
8
  export const ACT_MS = 5_000;
8
9
  const CALM_MS = 120;
9
10
  const CALM_LIMIT_MS = 4_000;
@@ -43,6 +44,7 @@ export class Stopped extends Error {
43
44
  }
44
45
  }
45
46
  export const treeOf = (page) => page.locator('body').ariaSnapshot({ timeout: ACT_MS });
47
+ export const seenTree = (page) => secretsHidden(page.locator('body'), () => calm(page));
46
48
  export async function calm(page) {
47
49
  const begun = Date.now();
48
50
  let last = await treeOf(page).catch(() => '');
@@ -58,17 +60,17 @@ export async function calm(page) {
58
60
  async function theOne(page, name, role) {
59
61
  const found = findNamed(namedIn(await treeOf(page)), name, role);
60
62
  if (found.found === 'none')
61
- throw new Stopped('not_found', notFoundWords(name, role, found.near));
63
+ throw new Stopped('not_found', await secretsHiddenInWords(page, notFoundWords(name, role, found.near)));
62
64
  if (found.found === 'many')
63
- throw new Stopped('ambiguous', ambiguousWords(name, found.many));
65
+ throw new Stopped('ambiguous', await secretsHiddenInWords(page, ambiguousWords(name, found.many)));
64
66
  const { one } = found;
65
67
  const at = page.getByRole(one.role, { name: one.raw, exact: true });
66
68
  const count = await at.count();
67
69
  if (count === 1)
68
70
  return { named: one, at };
69
71
  if (count === 0)
70
- throw new Stopped('not_found', notFoundWords(name, role, []));
71
- const lines = await Promise.all((await at.all()).map(async (each) => (await each.ariaSnapshot()).split('\n')[0].trim()));
72
+ throw new Stopped('not_found', await secretsHiddenInWords(page, notFoundWords(name, role, [])));
73
+ const lines = await Promise.all((await at.all()).map(async (each) => (await secretsHidden(each, () => each.ariaSnapshot())).split('\n')[0].trim()));
72
74
  throw new Stopped('ambiguous', sameWords(one, lines));
73
75
  }
74
76
  const timedOut = (error) => error instanceof Error && error.name === 'TimeoutError';
@@ -91,6 +93,15 @@ export const failed = (command, at, failure, says, driver = 'browser') => ({
91
93
  driver,
92
94
  });
93
95
  export async function act(page, command, at = Date.now()) {
96
+ await noteSecretsOn(page);
97
+ try {
98
+ return await acted(page, command, at);
99
+ }
100
+ finally {
101
+ await noteSecretsOn(page);
102
+ }
103
+ }
104
+ async function acted(page, command, at) {
94
105
  try {
95
106
  switch (command.command) {
96
107
  case 'click': {
@@ -129,10 +140,12 @@ export async function act(page, command, at = Date.now()) {
129
140
  return done('key', at);
130
141
  case 'snapshot': {
131
142
  if (command.name === null)
132
- return done('snapshot', at, { tree: await calm(page) });
143
+ return done('snapshot', at, { tree: await seenTree(page) });
133
144
  await calm(page);
134
145
  const { at: target } = await theOne(page, command.name, command.role);
135
- return done('snapshot', at, { tree: await target.ariaSnapshot({ timeout: ACT_MS }) });
146
+ return done('snapshot', at, {
147
+ tree: await secretsHidden(target, () => target.ariaSnapshot({ timeout: ACT_MS })),
148
+ });
136
149
  }
137
150
  case 'screenshot': {
138
151
  mkdirSync(path.dirname(path.resolve(command.file)), { recursive: true });
@@ -167,6 +180,7 @@ export async function contextFor(browser, url, signIn, colorScheme = 'light', vi
167
180
  url: new URL(url).origin,
168
181
  ...(c.path && { url: undefined, domain: new URL(url).hostname, path: c.path }),
169
182
  })));
183
+ await rememberSecretFields(context);
170
184
  if (signIn?.storage && Object.keys(signIn.storage).length)
171
185
  await context.addInitScript((values) => {
172
186
  for (const [k, v] of Object.entries(values))
@@ -9,6 +9,7 @@ import { startPieceServer } from '../kinds/index.js';
9
9
  import { applyWorld, baseVars } from '../run/index.js';
10
10
  import { runningServices, bringDown, bringUp, freePort, stateDir } from '../services/index.js';
11
11
  import { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
12
+ import { noteSecretsOn } from './secrets.js';
12
13
  import { driveArgv, parseDrive } from './grammar.js';
13
14
  import { forgetDriving, writeDriving } from './state.js';
14
15
  import { readScenarios } from '../scenarios/index.js';
@@ -95,6 +96,7 @@ async function open() {
95
96
  }
96
97
  await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
97
98
  await calm(page);
99
+ await noteSecretsOn(page);
98
100
  }
99
101
  async function stop() {
100
102
  await context?.close().catch(() => undefined);
@@ -1,4 +1,5 @@
1
- export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, signInBySteps, signInOf, type SignIn, } from './browser.ts';
1
+ export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, seenTree, signInBySteps, signInOf, type SignIn, } from './browser.ts';
2
2
  export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, type DriveResult, type Step, type Verb, } from './grammar.ts';
3
3
  export { findNamed, namedIn } from './names.ts';
4
+ export { HIDDEN_VALUE, secretsHidden, TREE_WITHHELD, withValuesHidden } from './secrets.ts';
4
5
  export { forgetDriving, readDriving, writeDriving } from './state.ts';
@@ -1,4 +1,5 @@
1
- export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, signInBySteps, signInOf, } from './browser.js';
1
+ export { act, calm, contextFor, errorsOf, failed, FIXED_TIME, launch, seenTree, signInBySteps, signInOf, } from './browser.js';
2
2
  export { driveArgv, exitOf, parseDrive, resultText, stepCommand, stepOf, stepWords, STEP_FLAGS, STEP_WORDS, VERBS, } from './grammar.js';
3
3
  export { findNamed, namedIn } from './names.js';
4
+ export { HIDDEN_VALUE, secretsHidden, TREE_WITHHELD, withValuesHidden } from './secrets.js';
4
5
  export { forgetDriving, readDriving, writeDriving } from './state.js';
@@ -0,0 +1,8 @@
1
+ import type { BrowserContext, Locator, Page } from 'playwright-core';
2
+ export declare const HIDDEN_VALUE = "\u2039secret\u203A";
3
+ export declare const TREE_WITHHELD = "\u2039withheld: Rehearse could not read which fields hold secrets on this page\u203A";
4
+ export declare const rememberSecretFields: (context: BrowserContext) => Promise<void>;
5
+ export declare function withValuesHidden(tree: string, values: readonly string[]): string;
6
+ export declare function secretsHidden<T extends string | null>(scope: Locator, take: () => Promise<T>): Promise<T>;
7
+ export declare function noteSecretsOn(page: Page): Promise<void>;
8
+ export declare function secretsHiddenInWords(page: Page, words: string): Promise<string>;
@@ -0,0 +1,201 @@
1
+ export const HIDDEN_VALUE = '‹secret›';
2
+ export const TREE_WITHHELD = '‹withheld: Rehearse could not read which fields hold secrets on this page›';
3
+ const SECRET_AUTOCOMPLETE = [
4
+ 'current-password',
5
+ 'new-password',
6
+ 'one-time-code',
7
+ 'cc-number',
8
+ 'cc-csc',
9
+ 'cc-exp',
10
+ 'cc-exp-month',
11
+ 'cc-exp-year',
12
+ ];
13
+ const SHORT = 4;
14
+ const DROPPED_BY_THE_TREE = /[\u200b\u00ad]/g;
15
+ const TAB = 9;
16
+ const NEW_LINE = 10;
17
+ const RETURN = 13;
18
+ const holdsControl = (value) => [...value].some((ch) => {
19
+ const code = ch.charCodeAt(0);
20
+ return ((code < 32 && code !== TAB && code !== NEW_LINE && code !== RETURN) || (code >= 127 && code <= 159));
21
+ });
22
+ const WORDS_APART = '(?:\\s|\\\\n|\\\\t|\\\\r)+';
23
+ const remembered = new WeakMap();
24
+ export const rememberSecretFields = async (context) => {
25
+ await context.addInitScript(() => {
26
+ const memory = window;
27
+ const seen = new WeakSet();
28
+ const values = new Set();
29
+ memory.rehearseWasSecret = seen;
30
+ memory.rehearseSecretValues = values;
31
+ const isPassword = (el) => el instanceof HTMLInputElement && el.type === 'password';
32
+ const secretTokens = [
33
+ 'current-password',
34
+ 'new-password',
35
+ 'one-time-code',
36
+ 'cc-number',
37
+ 'cc-csc',
38
+ 'cc-exp',
39
+ 'cc-exp-month',
40
+ 'cc-exp-year',
41
+ ];
42
+ const keep = (event) => {
43
+ const target = event.composedPath()[0];
44
+ if (!(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) || !target.value)
45
+ return;
46
+ const tokens = (target.getAttribute('autocomplete') ?? '').toLowerCase().split(/\s+/);
47
+ if (isPassword(target) || tokens.some((t) => secretTokens.includes(t)))
48
+ values.add(target.value);
49
+ };
50
+ document.addEventListener('input', keep, true);
51
+ document.addEventListener('change', keep, true);
52
+ new MutationObserver((records) => {
53
+ for (const r of records)
54
+ if (r.type === 'attributes' && (r.oldValue ?? '').toLowerCase() === 'password') {
55
+ seen.add(r.target);
56
+ const value = r.target.value;
57
+ if (value)
58
+ values.add(value);
59
+ }
60
+ }).observe(document, {
61
+ subtree: true,
62
+ attributes: true,
63
+ attributeFilter: ['type'],
64
+ attributeOldValue: true,
65
+ });
66
+ });
67
+ };
68
+ async function secretValuesOn(page) {
69
+ try {
70
+ return await page.evaluate((autocomplete) => {
71
+ const memory = window;
72
+ const fields = [];
73
+ const visit = (node) => {
74
+ for (const el of Array.from(node.querySelectorAll('*'))) {
75
+ if (el.matches('input, textarea, select'))
76
+ fields.push(el);
77
+ if (el.shadowRoot)
78
+ visit(el.shadowRoot);
79
+ }
80
+ };
81
+ visit(document);
82
+ const values = [...(memory.rehearseSecretValues ?? [])];
83
+ for (const el of fields) {
84
+ const style = getComputedStyle(el);
85
+ const tokens = (el.getAttribute('autocomplete') ?? '').toLowerCase().split(/\s+/);
86
+ const secret = (el instanceof HTMLInputElement && el.type === 'password') ||
87
+ memory.rehearseWasSecret?.has(el) === true ||
88
+ tokens.some((t) => autocomplete.includes(t)) ||
89
+ (style.webkitTextSecurity ?? 'none') !== 'none' ||
90
+ /text-security/i.test(style.fontFamily);
91
+ if (!secret)
92
+ continue;
93
+ if (el instanceof HTMLSelectElement)
94
+ for (const o of Array.from(el.selectedOptions))
95
+ values.push(o.text, o.value, o.label, o.getAttribute('aria-label') ?? '');
96
+ else
97
+ values.push(el.value);
98
+ }
99
+ return values.filter((v) => v.trim().length > 0);
100
+ }, SECRET_AUTOCOMPLETE);
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ }
106
+ const escaped = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
107
+ function patternOf(value) {
108
+ const words = value.split(/[\s ]+/).filter(Boolean);
109
+ if (words.length === 0)
110
+ return null;
111
+ const forms = (word) => `(?:${[
112
+ ...new Set([
113
+ word,
114
+ JSON.stringify(word).slice(1, -1),
115
+ word.replace(/'/g, "''"),
116
+ JSON.stringify(word).slice(1, -1).replace(/'/g, "''"),
117
+ ]),
118
+ ]
119
+ .map(escaped)
120
+ .join('|')})`;
121
+ const body = words.map(forms).join(WORDS_APART);
122
+ return new RegExp(words.join(' ').length < SHORT ? `(?<![\\w])${body}(?![\\w])` : body, 'g');
123
+ }
124
+ const patternsOf = (values) => [...new Set(values.flatMap((v) => [v, v.replace(DROPPED_BY_THE_TREE, '')]))]
125
+ .sort((a, b) => b.length - a.length)
126
+ .flatMap((v) => patternOf(v) ?? []);
127
+ const hiddenIn = (text, patterns) => patterns.reduce((out, p) => out.replace(p, HIDDEN_VALUE), text);
128
+ const LINE = /^(\s*-\s+'?)([\w/-]+)(.*)$/;
129
+ function hiddenInRest(rest, patterns) {
130
+ let out = '';
131
+ let i = 0;
132
+ while (i < rest.length) {
133
+ const c = rest[i];
134
+ if (c === '"') {
135
+ let j = i + 1;
136
+ while (j < rest.length && rest[j] !== '"')
137
+ j += rest[j] === '\\' ? 2 : 1;
138
+ out += `"${hiddenIn(rest.slice(i + 1, j), patterns)}"`;
139
+ i = j + 1;
140
+ }
141
+ else if (c === '[') {
142
+ const j = rest.indexOf(']', i);
143
+ const end = j === -1 ? rest.length : j + 1;
144
+ out += rest.slice(i, end);
145
+ i = end;
146
+ }
147
+ else if (rest.startsWith(': ', i)) {
148
+ return `${out}: ${hiddenIn(rest.slice(i + 2), patterns)}`;
149
+ }
150
+ else {
151
+ out += c;
152
+ i += 1;
153
+ }
154
+ }
155
+ return out;
156
+ }
157
+ export function withValuesHidden(tree, values) {
158
+ const patterns = patternsOf(values);
159
+ if (patterns.length === 0)
160
+ return tree;
161
+ return tree
162
+ .split('\n')
163
+ .map((line) => {
164
+ const m = LINE.exec(line);
165
+ return m ? `${m[1]}${m[2]}${hiddenInRest(m[3], patterns)}` : hiddenIn(line, patterns);
166
+ })
167
+ .join('\n');
168
+ }
169
+ async function valuesKnownOn(page) {
170
+ const now = await secretValuesOn(page);
171
+ if (now === null)
172
+ return null;
173
+ const known = remembered.get(page) ?? new Set();
174
+ for (const v of now)
175
+ known.add(v);
176
+ remembered.set(page, known);
177
+ return [...known];
178
+ }
179
+ export async function secretsHidden(scope, take) {
180
+ const page = scope.page();
181
+ const before = await valuesKnownOn(page);
182
+ const tree = await take();
183
+ const after = await valuesKnownOn(page);
184
+ if (tree === null)
185
+ return tree;
186
+ if (before === null || after === null)
187
+ return TREE_WITHHELD;
188
+ const values = [...before, ...after];
189
+ if (values.some(holdsControl))
190
+ return TREE_WITHHELD;
191
+ return withValuesHidden(tree, values);
192
+ }
193
+ export async function noteSecretsOn(page) {
194
+ await valuesKnownOn(page);
195
+ }
196
+ export async function secretsHiddenInWords(page, words) {
197
+ const values = await valuesKnownOn(page);
198
+ if (values === null || values.some(holdsControl))
199
+ return TREE_WITHHELD;
200
+ return hiddenIn(words, patternsOf(values));
201
+ }
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import path from 'node:path';
3
3
  import { jsonDifferences, noCounts, setAsideText, textDifferences, } from '../../compare/index.js';
4
- import { act, calm, contextFor, driveArgv, errorsOf, FIXED_TIME, launch, signInBySteps, signInOf, stepCommand, stepOf, stepWords, } from '../../drive/index.js';
4
+ import { act, contextFor, driveArgv, errorsOf, FIXED_TIME, launch, seenTree, signInBySteps, signInOf, stepCommand, stepOf, stepWords, } from '../../drive/index.js';
5
5
  import { errorText } from '../../errors.js';
6
6
  import { sh, tail } from '../../exec.js';
7
7
  import { fill, fillEnv, hashOf, readYaml } from '../../manifest/index.js';
@@ -202,7 +202,7 @@ async function throughBrowser(s, ctx, browser, url) {
202
202
  let ok = true;
203
203
  try {
204
204
  await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
205
- const tree = await calm(page);
205
+ const tree = await seenTree(page);
206
206
  await page.screenshot({ path: shot(1) });
207
207
  shots.set(1, shot(1));
208
208
  steps.push({
@@ -233,7 +233,7 @@ async function throughBrowser(s, ctx, browser, url) {
233
233
  ? step
234
234
  : { ...step, with: fill(step.with, { token: person ? (ctx.tokens[person] ?? '') : '' }) };
235
235
  const did = await act(page, stepCommand(filled));
236
- const tree = did.ok ? (did.tree ?? (await calm(page))) : null;
236
+ const tree = did.ok ? (did.tree ?? (await seenTree(page))) : null;
237
237
  if (did.ok) {
238
238
  await page.screenshot({ path: shot(n) });
239
239
  shots.set(n, shot(n));
@@ -296,7 +296,7 @@ async function upAgainWhereTheWorldStarts(ctx, running) {
296
296
  const cantBeBroughtUpAfresh = (service, afterAnotherFlow) => `${service} can't be brought up afresh (it needs a down command, and an up that hands over to a daemon), so this flow started ${afterAnotherFlow ? 'where the last one left the app' : 'with the app as it found it'}.`;
297
297
  registerRunner({
298
298
  kind: 'flow',
299
- version: 'flow/3',
299
+ version: 'flow/4',
300
300
  services: (s) => (s.service ? [s.service] : []),
301
301
  async run(scenarios, asGiven) {
302
302
  let ctx = asGiven;
@@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import path from 'node:path';
5
5
  import { jsonDifferences, noCounts, setAsideText, textDifferences, } from '../../compare/index.js';
6
- import { calm, contextFor, errorsOf, FIXED_TIME, launch } from '../../drive/index.js';
6
+ import { calm, contextFor, errorsOf, FIXED_TIME, launch, secretsHidden } from '../../drive/index.js';
7
7
  import { errorText } from '../../errors.js';
8
8
  import { hashOf } from '../../manifest/index.js';
9
9
  import { registerReader, toPosix } from '../../scenarios/index.js';
@@ -130,7 +130,9 @@ async function observe(page, url, shot, errors) {
130
130
  ? null
131
131
  : `It never rendered${errors.length ? `: ${errors[0]}` : ' within 20 seconds'}`;
132
132
  const root = page.locator(`#${ROOT_ID}`);
133
- const tree = threw ? null : await root.ariaSnapshot({ timeout: 5_000 }).catch(() => null);
133
+ const tree = threw
134
+ ? null
135
+ : await secretsHidden(root, () => root.ariaSnapshot({ timeout: 5_000 }).catch(() => null));
134
136
  let violations = [];
135
137
  if (!threw) {
136
138
  await page.addScriptTag({ content: axe() });
@@ -258,7 +260,7 @@ export async function runPieces(scenarios, ctx, browser) {
258
260
  }
259
261
  registerRunner({
260
262
  kind: 'piece',
261
- version: 'piece/2',
263
+ version: 'piece/3',
262
264
  services: () => [],
263
265
  run: (scenarios, ctx) => runPieces(scenarios, ctx),
264
266
  compare(base, head, rules, counts, _s, m) {
@@ -112,6 +112,15 @@ function artifactsToPublish(m, c, placed) {
112
112
  };
113
113
  return { published, copies };
114
114
  }
115
+ const TREES_HIDE_SECRETS_FROM = { flow: 4, piece: 3 };
116
+ function takenBeforeSecretsWereHidden(ob) {
117
+ const kind = ob.scenario.kind;
118
+ const from = TREES_HIDE_SECRETS_FROM[kind];
119
+ if (from === undefined)
120
+ return false;
121
+ const [runnerKind, version] = (ob.runner ?? '').split('/');
122
+ return runnerKind !== kind || !(Number(version) >= from);
123
+ }
115
124
  function readObservation(file) {
116
125
  if (!file || !existsSync(file))
117
126
  return null;
@@ -125,6 +134,8 @@ function readObservation(file) {
125
134
  const invalid = validate('observation', read);
126
135
  if (invalid.length > 0)
127
136
  throw new RehearseError('no_comparison', `${file} isn't an observation Rehearse can read (${invalid[0].says}): run rehearse compare again.`);
137
+ if (takenBeforeSecretsWereHidden(read))
138
+ throw new RehearseError('stale_comparison', `${file} was taken by a Rehearse that kept secret fields' values in its trees: run rehearse compare again before copying the stage.`);
128
139
  return read;
129
140
  }
130
141
  const shownRef = (s) => ({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kurvball/rehearse",
3
- "version": "1.12.0",
3
+ "version": "1.12.1",
4
4
  "description": "Rehearse a change before it ships: bring the product up, sign in as named people, start from named worlds, and compare any scenario on the base and on the head.",
5
5
  "homepage": "https://rehearse.kurvball.ca/",
6
6
  "repository": {