diff --git a/README.md b/README.md index 564c7e4..e8e383f 100644 --- a/README.md +++ b/README.md @@ -9,18 +9,18 @@ A local-only Firefox extension that records your job applications, what you sent ## The three claims - **Local only.** All data stays on your machine. The extension makes no network requests. -- **Nothing reads a page until you click.** It has no content scripts. It reads the current tab only after you click the toolbar button or press Alt+Shift+S by default. The one thing that runs without a click is the local automatic backup check. -- **It never submits anything.** It does not fill forms, apply for jobs or send data anywhere. +- **Nothing reads or touches a page until you click.** It has no content scripts. It reads the current tab only after you click the toolbar button or press Alt+Shift+S by default, and it writes into a form only after you click Fill in the popup. The one thing that runs without a click is the local automatic backup check. +- **It fills only when you click, and never submits.** Fill writes your saved details into empty fields and nothing else. Countersign never clicks a button, presses a key or submits a form, and it sends no data anywhere. ## How the claims are enforced Each claim is checked by the gate (`npm run gate`), which CI also runs. -| Claim | How it is enforced | -| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Local only | [`guard/build.test.ts`](guard/build.test.ts) scans every built `.js` and `.html` file for network APIs (`fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`, `sendBeacon`, `WebTransport`, `RTCPeerConnection`), checks that no built page loads a remote `src` or `href`, and asserts the manifest has no host permissions. [`eslint.config.js`](eslint.config.js) bans the same APIs in source (`no-restricted-globals`, `no-restricted-properties`, `no-restricted-syntax`). The Content Security Policy in [`wxt.config.ts`](wxt.config.ts) sets `default-src 'self'; ... connect-src 'none'`. | -| Nothing reads a page until you click | [`guard/build.test.ts`](guard/build.test.ts) asserts the built manifest declares no content scripts and no web-accessible resources. The permissions are listed below. The background event page runs only the local automatic backup check (on startup, install, a daily alarm and backup-counter changes) and never reads a tab ([`entrypoints/background.ts`](entrypoints/background.ts)). | -| It never submits anything | There is no code path that sends a request (see the first row), the manifest has no host access, and the CSP sets `form-action 'none'`, so a form on an extension page cannot post anywhere. The test asserts the exact CSP in the built manifest. | +| Claim | How it is enforced | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Local only | [`guard/build.test.ts`](guard/build.test.ts) scans every built `.js` and `.html` file for network APIs (`fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`, `sendBeacon`, `WebTransport`, `RTCPeerConnection`), checks that no built page loads a remote `src` or `href`, and asserts the manifest has no host permissions. [`eslint.config.js`](eslint.config.js) bans the same APIs in source (`no-restricted-globals`, `no-restricted-properties`, `no-restricted-syntax`). The Content Security Policy in [`wxt.config.ts`](wxt.config.ts) sets `default-src 'self'; ... connect-src 'none'`. | +| Nothing reads or touches a page until you click | [`guard/build.test.ts`](guard/build.test.ts) asserts the built manifest declares no content scripts and no web-accessible resources. The permissions are listed below. The background event page runs only the local automatic backup check (on startup, install, a daily alarm and backup-counter changes) and never reads a tab ([`entrypoints/background.ts`](entrypoints/background.ts)). The fill script is injected only by [`shell/fill/inject.ts`](shell/fill/inject.ts). Outside tests, lint rules in [`eslint.config.js`](eslint.config.js) check that only that file and `entrypoints/fill.ts` write the script's name or its hook's name as a literal, only [`shell/fill/controller.ts`](shell/fill/controller.ts) imports the injector, only `shell/ui/Popup.tsx` imports the controller (type imports are free), and only `shell/ui/FillSection.tsx` reads the controller's `fill()` (checked by literal property name). A controller test ([`shell/fill/controller.test.ts`](shell/fill/controller.test.ts)) shows that scanning never applies. The Fill button's click handler is the only caller of `fill()` ([`shell/ui/fill-section-source.test.ts`](shell/ui/fill-section-source.test.ts)). | +| It fills only when you click, and never submits | There is no code path that sends a request (see the first row), the manifest has no host access, and the CSP sets `form-action 'none'`, so a form on an extension page cannot post anywhere. The test asserts the exact CSP in the built manifest. For the fill script, a lint block in [`eslint.config.js`](eslint.config.js) covers `shell/fill/page/**` and `entrypoints/fill.ts`. It bans submit, requestSubmit, click, focus, blur, scrollIntoView and dispatchEvent, constructing events, console, storage, postMessage and cookie access, and the common ways of changing the page, such as creating, removing or moving elements, setting attributes, text, classes, styles or HTML, adding event listeners, resetting a form and `Object.assign`. That list is a denylist, so it is not a proof that no other change is possible. Only [`shell/fill/page/events.ts`](shell/fill/page/events.ts) may dispatch an event, and only a plain `input` or `change`. [`guard/build.test.ts`](guard/build.test.ts) scans the built `fill.js` for `submit`, `requestSubmit`, `click`, `KeyboardEvent`, `MouseEvent`, `PointerEvent` and `SubmitEvent`. A fixture test ([`shell/fill/page-apply.test.ts`](shell/fill/page-apply.test.ts)) fills a form and sees no submit, no new element and no new attribute. | Files are saved only through [`shell/files/download.ts`](shell/files/download.ts), which builds a local `blob:` URL. A lint rule in [`eslint.config.js`](eslint.config.js) rejects any other use of `downloads`, and [`guard/source-rules.test.ts`](guard/source-rules.test.ts) tests that rule. @@ -34,14 +34,15 @@ Stage 1 is the dashboard. Stage 2 adds saving a job from the page you are on, pl - **Applications list** with search, filters, manual entry, and a next-action date and who acts next. - **Save a job.** After you click the toolbar button (or press Alt+Shift+S by default; you can rebind it in about:addons), the popup reads the current tab once and offers the job for saving. Nothing is read before the click. +- **Fill a form.** In the popup, Fill writes your saved details and answers into the empty fields it recognises with certainty, then lists what it did not fill and why. It never changes a field that already has a value, and it never submits. Custom dropdowns and file uploads are listed for you to do yourself. - **Duplicate and repost facts.** When a job matches an application you already have, the popup says so ("already applied" or "possible match"). It also states the fact when you saved the same posting earlier, without judging it. - **Automatic backup.** Countersign saves `Countersign/countersign-backup.json` to your downloads folder, and the dashboard shows how old the last backup is. The backup file holds all your data, including your details and contacts, as plain text, so keep your downloads folder out of cloud sync if that matters to you. - **What I told them.** Per application, record the answers you gave. A warning appears when one differs from your canonical answer. - **Quiet list** (`#/quiet`) of applications with no response for a set number of days (a setting). You can close several at once. -- **Formhand log.** On an application, record the application site type and how filling went. You enter it by hand. +- **Fill log.** On an application, record the application site type and how filling went. You enter it by hand. - **Contacts** (`#/contacts`) with a log of reaching out, replies and referrals. The popup and the application page ask "anyone here?" and let you record that you checked and nobody was there. - **Deadlines** (`#/deadlines`): open tasks, next-action dates and quiet applications on one list, dated rows first. -- **My details** (`#/details`): 12 profile fields (name, email, phone, address, links) and your canonical answers, each with a copy button. Copying uses a click only, and nothing is typed into a page. +- **My details** (`#/details`): 14 profile fields (name, first and last name, email, phone, address, links) and your canonical answers, each with a copy button. Copying uses a click only. - **Application detail** with a status history. Entries can be backdated, and a mistaken status can be undone without deleting history. - **Resume and cover-letter records.** You attach a file to record which one you sent. Countersign stores the file name and a SHA-256 hash, not the file. - **Canonical answers** (for example work authorisation or salary range), each with its history of earlier values. diff --git a/core/src/fill/compare.test.ts b/core/src/fill/compare.test.ts new file mode 100644 index 0000000..ac7b35f --- /dev/null +++ b/core/src/fill/compare.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; +import { sameLink, samePhone, sameProfileValue, sameText } from './compare'; + +describe('sameText', () => { + it('ignores surrounding spaces and case', () => { + expect(sameText(' Sam ', 'sam')).toBe(true); + }); + + it('treats different words as different', () => { + expect(sameText('Sam', 'Samuel')).toBe(false); + }); +}); + +describe('samePhone', () => { + it.each([ + ['+1 (555) 010-0142', '555 010 0142', true], + ['555-010-0142', '5550100142', true], + ['555-010-0142', '555-010-0143', false], + ['0142', '10142', false], + ['5550100142', '99995550100142', false], + ['', '', false], + ['abc', 'def', false], + ])('samePhone(%j, %j) is %s', (a, b, expected) => { + expect(samePhone(a, b)).toBe(expected); + }); +}); + +describe('sameLink', () => { + it.each([ + ['https://www.example.com/in/sam/', 'example.com/in/sam', true], + ['HTTP://Example.com', 'example.com', true], + ['example.com/a', 'example.com/b', false], + ['https://example.com//', 'example.com', true], + ])('sameLink(%j, %j) is %s', (a, b, expected) => { + expect(sameLink(a, b)).toBe(expected); + }); +}); + +describe('sameProfileValue', () => { + it.each([ + ['phone', '+1 555 010 0142', '5550100142', true], + ['website', 'https://example.com/', 'example.com', true], + ['city', 'Springfield ', 'springfield', true], + ['email', 'a@example.com', 'b@example.com', false], + ] as const)( + 'sameProfileValue(%j, %j, %j) is %s', + (key, formValue, own, expected) => { + expect(sameProfileValue(key, formValue, own)).toBe(expected); + }, + ); +}); diff --git a/core/src/fill/compare.ts b/core/src/fill/compare.ts new file mode 100644 index 0000000..ba64d11 --- /dev/null +++ b/core/src/fill/compare.ts @@ -0,0 +1,52 @@ +import type { ProfileKey } from '../profile'; + +/** Trimmed, case-insensitive equality. */ +export function sameText(a: string, b: string): boolean { + return a.trim().toLowerCase() === b.trim().toLowerCase(); +} + +/** + * Equal digit strings match, as does a shorter number (at least 7 digits) + * that is the tail of a longer one with 1 to 3 extra leading digits. + */ +export function samePhone(a: string, b: string): boolean { + const digitsA = a.replace(/\D/g, ''); + const digitsB = b.replace(/\D/g, ''); + if (digitsA === digitsB) { + return digitsA !== ''; + } + const [short, long] = + digitsA.length <= digitsB.length ? [digitsA, digitsB] : [digitsB, digitsA]; + const extra = long.length - short.length; + return short.length >= 7 && long.endsWith(short) && extra >= 1 && extra <= 3; +} + +function normalizeLink(value: string): string { + let link = value.trim().toLowerCase(); + link = link.replace(/^https?:\/\//, ''); + link = link.replace(/^www\./, ''); + return link.replace(/\/+$/, ''); +} + +/** Compares URLs or domains, ignoring scheme, leading www. and trailing slashes. */ +export function sameLink(a: string, b: string): boolean { + return normalizeLink(a) === normalizeLink(b); +} + +/** Picks the comparison rule for a saved profile key. */ +export function sameProfileValue( + key: ProfileKey, + formValue: string, + own: string, +): boolean { + switch (key) { + case 'phone': + return samePhone(formValue, own); + case 'linkedin': + case 'github': + case 'website': + return sameLink(formValue, own); + default: + return sameText(formValue, own); + } +} diff --git a/core/src/fill/countries.test.ts b/core/src/fill/countries.test.ts new file mode 100644 index 0000000..0b9542e --- /dev/null +++ b/core/src/fill/countries.test.ts @@ -0,0 +1,313 @@ +import { describe, expect, it } from 'vitest'; +import { + COUNTRY_NAMES, + COUNTRY_TABLE, + EXPANDED_COUNTRY_TABLE, + EXPANDED_REGION_TABLE, + REGION_TABLE, + countryOf, + placesNamed, +} from './countries'; +import { normalizeLabel } from './normalize'; + +const PREFIX = 'are you authorized to work in '; + +describe('COUNTRY_NAMES', () => { + it('covers the UN members', () => { + expect(COUNTRY_NAMES.length).toBeGreaterThanOrEqual(200); + expect(new Set(COUNTRY_NAMES).size).toBe(COUNTRY_NAMES.length); + for (const name of [ + 'estonia', + 'papua new guinea', + 'south sudan', + 'timor leste', + 'eswatini', + 'north macedonia', + 'kiribati', + 'canada', + 'india', + 'germany', + ]) { + expect(COUNTRY_NAMES).toContain(name); + } + }); + + it('stores every name and alias in normalised form', () => { + for (const row of [ + ...COUNTRY_TABLE, + ...REGION_TABLE, + ...EXPANDED_COUNTRY_TABLE, + ...EXPANDED_REGION_TABLE, + ]) { + for (const name of row) { + expect(name).toBe(normalizeLabel(name)); + expect(name).not.toBe(''); + } + } + }); + + it('never repeats a name or alias across the whole table, derived forms included', () => { + const all = [...EXPANDED_COUNTRY_TABLE, ...EXPANDED_REGION_TABLE].flat(); + expect(new Set(all).size).toBe(all.length); + }); + + it('derives the and-less form of every name and alias with "and"', () => { + const base = new Set([...COUNTRY_TABLE, ...REGION_TABLE].flat()); + const expanded = new Set( + [...EXPANDED_COUNTRY_TABLE, ...EXPANDED_REGION_TABLE].flat(), + ); + for (const name of base) { + if (!name.split(' ').includes('and')) continue; + const derived = name + .split(' ') + .filter((word) => word !== 'and') + .join(' '); + expect(expanded.has(derived)).toBe(true); + } + }); +}); + +describe('countryOf', () => { + it('reads common spellings of the United States', () => { + for (const text of [ + 'United States', + 'USA', + 'U.S.', + 'us', + ' United States of America ', + ]) { + expect(countryOf(text)).toBe('united states'); + } + }); + + it('reads the United Kingdom', () => { + expect(countryOf('UK')).toBe('united kingdom'); + }); + + it('needs the whole string to be a place', () => { + expect(countryOf('Texas, USA')).toBeUndefined(); + expect(countryOf('')).toBeUndefined(); + expect(countryOf('EU')).toBeUndefined(); + expect(countryOf('Narnia')).toBeUndefined(); + }); + + it.each([ + ['usa', 'united states'], + ['u s a', 'united states'], + ['america', 'united states'], + ['england', 'united kingdom'], + ['scotland', 'united kingdom'], + ['wales', 'united kingdom'], + ['northern ireland', 'united kingdom'], + ['great britain', 'united kingdom'], + ['britain', 'united kingdom'], + ['u k', 'united kingdom'], + ['uae', 'united arab emirates'], + ['korea', 'south korea'], + ['republic of korea', 'south korea'], + ['russian federation', 'russia'], + ['czech republic', 'czechia'], + ['holland', 'netherlands'], + ['the netherlands', 'netherlands'], + ['cote d ivoire', 'ivory coast'], + ['côte d ivoire', 'ivory coast'], + ['turkiye', 'turkey'], + ['türkiye', 'turkey'], + ['burma', 'myanmar'], + ['the gambia', 'gambia'], + ['the bahamas', 'bahamas'], + ['cabo verde', 'cape verde'], + ['east timor', 'timor leste'], + ['swaziland', 'eswatini'], + ['macedonia', 'north macedonia'], + ['bosnia', 'bosnia and herzegovina'], + ['st lucia', 'saint lucia'], + ['holy see', 'vatican city'], + ['macao', 'macau'], + ['viet nam', 'vietnam'], + ['dr congo', 'democratic republic of the congo'], + ['dprk', 'north korea'], + ['hong kong', 'hong kong'], + ['kosovo', 'kosovo'], + ['taiwan', 'taiwan'], + ['palestine', 'palestine'], + ['puerto rico', 'puerto rico'], + ['vatican city', 'vatican city'], + ])('reads %s as %s', (text, expected) => { + expect(countryOf(text)).toBe(expected); + }); + + it.each(REGION_TABLE.flat())( + 'does not read the region %s as a country', + (name) => { + expect(countryOf(name)).toBeUndefined(); + }, + ); +}); + +describe('placesNamed', () => { + it('finds a country', () => { + expect(placesNamed(PREFIX + 'the united states')).toEqual([ + 'united states', + ]); + expect(placesNamed(PREFIX + 'estonia')).toEqual(['estonia']); + }); + + it('consumes what it matched', () => { + expect(placesNamed(PREFIX + 'papua new guinea')).toEqual([ + 'papua new guinea', + ]); + expect(placesNamed(PREFIX + 'nigeria')).toEqual(['nigeria']); + expect(placesNamed(PREFIX + 'dominican republic')).toEqual([ + 'dominican republic', + ]); + expect(placesNamed(PREFIX + 'south sudan')).toEqual(['south sudan']); + expect(placesNamed(PREFIX + 'equatorial guinea')).toEqual([ + 'equatorial guinea', + ]); + expect(placesNamed(PREFIX + 'northern ireland')).toEqual([ + 'united kingdom', + ]); + }); + + it('returns several places in order of first appearance, once each', () => { + expect(placesNamed(PREFIX + 'the us or canada')).toEqual([ + 'united states', + 'canada', + ]); + expect(placesNamed('canada or the us or canada')).toEqual([ + 'canada', + 'united states', + ]); + expect(placesNamed('usa or the united states')).toEqual(['united states']); + }); + + it('finds regions', () => { + expect(placesNamed(PREFIX + 'the eu')).toEqual(['european union']); + expect(placesNamed(PREFIX + 'the e u')).toEqual(['european union']); + expect(placesNamed(PREFIX + 'the european economic area')).toEqual(['eea']); + expect(placesNamed(PREFIX + 'europe')).toEqual(['europe']); + expect(placesNamed(PREFIX + 'the schengen area')).toEqual(['schengen']); + expect(placesNamed(PREFIX + 'emea')).toEqual(['emea']); + expect(placesNamed(PREFIX + 'latin america')).toEqual(['latin america']); + expect(placesNamed(PREFIX + 'north america')).toEqual(['north america']); + }); + + it('reads continents and regions as themselves, not as a country', () => { + for (const [text, expected] of [ + ['south america', 'south america'], + ['central america', 'central america'], + ['the americas', 'americas'], + ['asia', 'asia'], + ['africa', 'africa'], + ['the middle east', 'middle east'], + ['oceania', 'oceania'], + ['the caribbean', 'caribbean'], + ['asia pacific', 'apac'], + ['apac', 'apac'], + ] as const) { + expect(placesNamed(PREFIX + text)).toEqual([expected]); + } + }); + + it('keeps a country apart from a region that shares a word', () => { + expect(placesNamed(PREFIX + 'south africa')).toEqual(['south africa']); + expect(placesNamed(PREFIX + 'north korea')).toEqual(['north korea']); + expect(placesNamed(PREFIX + 'korea')).toEqual(['south korea']); + expect(placesNamed(PREFIX + 'north america or the us')).toEqual([ + 'north america', + 'united states', + ]); + }); + + it('names nothing for a generic question', () => { + expect(placesNamed(PREFIX + 'this country')).toEqual([]); + expect(placesNamed('')).toEqual([]); + }); + + it('accepts a known false alarm in the safe direction', () => { + expect(placesNamed('tell us about yourself')).toEqual(['united states']); + }); + + it('matches whole words only', () => { + expect(placesNamed('do you use indiana software')).toEqual([]); + expect(placesNamed('a business')).toEqual([]); + }); + + it.each([ + ['guinea bissau', 'guinea bissau'], + ['democratic republic of the congo', 'democratic republic of the congo'], + ['united states of america', 'united states'], + ['republic of korea', 'south korea'], + ['dr congo', 'democratic republic of the congo'], + ['democratic republic of congo', 'democratic republic of the congo'], + ['korea democratic people s republic of', 'north korea'], + ['korea republic of', 'south korea'], + ['congo democratic republic of the', 'democratic republic of the congo'], + ['congo republic of the', 'congo'], + ])('names only one place in %s', (text, expected) => { + expect(placesNamed(text)).toEqual([expected]); + }); + + it('reads a european country as Europe, and the union as the union', () => { + expect(placesNamed(PREFIX + 'a european country')).toEqual(['europe']); + expect(placesNamed(PREFIX + 'the european union')).toEqual([ + 'european union', + ]); + }); +}); + +describe('spellings without "and" and other added aliases', () => { + it.each([ + ['trinidad tobago', 'trinidad and tobago'], + ['antigua barbuda', 'antigua and barbuda'], + ['saint kitts nevis', 'saint kitts and nevis'], + ['saint vincent the grenadines', 'saint vincent and the grenadines'], + ['sao tome principe', 'sao tome and principe'], + ['bosnia herzegovina', 'bosnia and herzegovina'], + ['st kitts and nevis', 'saint kitts and nevis'], + ['st kitts nevis', 'saint kitts and nevis'], + ['st lucia', 'saint lucia'], + ['st vincent and the grenadines', 'saint vincent and the grenadines'], + ['st vincent the grenadines', 'saint vincent and the grenadines'], + ['u a e', 'united arab emirates'], + ['drc', 'democratic republic of the congo'], + ['d r c', 'democratic republic of the congo'], + ['democratic republic of congo', 'democratic republic of the congo'], + ['dr congo', 'democratic republic of the congo'], + ['congo kinshasa', 'democratic republic of the congo'], + ['congo brazzaville', 'congo'], + ['kyrgyz republic', 'kyrgyzstan'], + ['slovak republic', 'slovakia'], + ['lao pdr', 'laos'], + ['lao people s democratic republic', 'laos'], + ['syrian arab republic', 'syria'], + ['são tomé and príncipe', 'sao tome and principe'], + ['korea democratic people s republic of', 'north korea'], + ['korea republic of', 'south korea'], + ['congo democratic republic of the', 'democratic republic of the congo'], + ['congo republic of the', 'congo'], + ['brunei darussalam', 'brunei'], + ['federated states of micronesia', 'micronesia'], + ['state of palestine', 'palestine'], + ['vatican', 'vatican city'], + ['republic of the congo', 'congo'], + ['democratic people s republic of korea', 'north korea'], + ])('reads %s as %s in both lookups', (text, expected) => { + expect(countryOf(text)).toBe(expected); + expect(placesNamed(PREFIX + text)).toEqual([expected]); + }); + + it('reads european as a region only', () => { + expect(countryOf('European')).toBeUndefined(); + }); + + it('ignores a leading "the" when reading a country', () => { + expect(countryOf('The United States')).toBe('united states'); + expect(countryOf('the UK')).toBe('united kingdom'); + expect(countryOf('The Netherlands')).toBe('netherlands'); + expect(countryOf('The Gambia')).toBe('gambia'); + expect(countryOf('the')).toBeUndefined(); + expect(countryOf('The European Union')).toBeUndefined(); + }); +}); diff --git a/core/src/fill/countries.ts b/core/src/fill/countries.ts new file mode 100644 index 0000000..011e424 --- /dev/null +++ b/core/src/fill/countries.ts @@ -0,0 +1,366 @@ +import { normalizeLabel } from './normalize'; + +// One row per place: the canonical name first, then its aliases. Every entry is +// stored the way normalizeLabel writes it. The table exists so a question about +// another place is never answered with the owner's own country, so recognising +// one place too many is the safe direction. +export const COUNTRY_TABLE: readonly (readonly string[])[] = [ + ['afghanistan'], + ['albania'], + ['algeria'], + ['andorra'], + ['angola'], + ['antigua and barbuda'], + ['argentina'], + ['armenia'], + ['australia'], + ['austria'], + ['azerbaijan'], + ['bahamas', 'the bahamas'], + ['bahrain'], + ['bangladesh'], + ['barbados'], + ['belarus'], + ['belgium'], + ['belize'], + ['benin'], + ['bhutan'], + ['bolivia'], + ['bosnia and herzegovina', 'bosnia'], + ['botswana'], + ['brazil'], + ['brunei', 'brunei darussalam'], + ['bulgaria'], + ['burkina faso'], + ['burundi'], + ['cambodia'], + ['cameroon'], + ['canada'], + ['cape verde', 'cabo verde'], + ['central african republic'], + ['chad'], + ['chile'], + ['china'], + ['colombia'], + ['comoros'], + [ + 'congo', + 'republic of the congo', + 'congo brazzaville', + 'congo republic of the', + ], + ['costa rica'], + ['croatia'], + ['cuba'], + ['cyprus'], + ['czechia', 'czech republic'], + [ + 'democratic republic of the congo', + 'dr congo', + 'drc', + 'd r c', + 'democratic republic of congo', + 'congo kinshasa', + 'congo democratic republic of the', + ], + ['denmark'], + ['djibouti'], + ['dominica'], + ['dominican republic'], + ['ecuador'], + ['egypt'], + ['el salvador'], + ['equatorial guinea'], + ['eritrea'], + ['estonia'], + ['eswatini', 'swaziland'], + ['ethiopia'], + ['fiji'], + ['finland'], + ['france'], + ['gabon'], + ['gambia', 'the gambia'], + ['georgia'], + ['germany'], + ['ghana'], + ['greece'], + ['grenada'], + ['guatemala'], + ['guinea'], + ['guinea bissau'], + ['guyana'], + ['haiti'], + ['honduras'], + ['hungary'], + ['iceland'], + ['india'], + ['indonesia'], + ['iran'], + ['iraq'], + ['ireland'], + ['israel'], + ['italy'], + ['ivory coast', 'cote d ivoire', 'côte d ivoire'], + ['jamaica'], + ['japan'], + ['jordan'], + ['kazakhstan'], + ['kenya'], + ['kiribati'], + ['kuwait'], + ['kyrgyzstan', 'kyrgyz republic'], + ['laos', 'lao pdr', 'lao people s democratic republic'], + ['latvia'], + ['lebanon'], + ['lesotho'], + ['liberia'], + ['libya'], + ['liechtenstein'], + ['lithuania'], + ['luxembourg'], + ['madagascar'], + ['malawi'], + ['malaysia'], + ['maldives'], + ['mali'], + ['malta'], + ['marshall islands'], + ['mauritania'], + ['mauritius'], + ['mexico'], + ['micronesia', 'federated states of micronesia'], + ['moldova'], + ['monaco'], + ['mongolia'], + ['montenegro'], + ['morocco'], + ['mozambique'], + ['myanmar', 'burma'], + ['namibia'], + ['nauru'], + ['nepal'], + ['netherlands', 'the netherlands', 'holland'], + ['new zealand'], + ['nicaragua'], + ['niger'], + ['nigeria'], + [ + 'north korea', + 'dprk', + 'democratic people s republic of korea', + 'korea democratic people s republic of', + ], + ['north macedonia', 'macedonia'], + ['norway'], + ['oman'], + ['pakistan'], + ['palau'], + ['panama'], + ['papua new guinea'], + ['paraguay'], + ['peru'], + ['philippines'], + ['poland'], + ['portugal'], + ['qatar'], + ['romania'], + ['russia', 'russian federation'], + ['rwanda'], + ['saint kitts and nevis', 'st kitts and nevis'], + ['saint lucia', 'st lucia'], + ['saint vincent and the grenadines', 'st vincent and the grenadines'], + ['samoa'], + ['san marino'], + ['sao tome and principe', 'são tomé and príncipe'], + ['saudi arabia'], + ['senegal'], + ['serbia'], + ['seychelles'], + ['sierra leone'], + ['singapore'], + ['slovakia', 'slovak republic'], + ['slovenia'], + ['solomon islands'], + ['somalia'], + ['south africa'], + ['south korea', 'korea', 'republic of korea', 'korea republic of'], + ['south sudan'], + ['spain'], + ['sri lanka'], + ['sudan'], + ['suriname'], + ['sweden'], + ['switzerland'], + ['syria', 'syrian arab republic'], + ['tajikistan'], + ['tanzania'], + ['thailand'], + ['timor leste', 'east timor'], + ['togo'], + ['tonga'], + ['trinidad and tobago'], + ['tunisia'], + ['turkey', 'turkiye', 'türkiye'], + ['turkmenistan'], + ['tuvalu'], + ['uganda'], + ['ukraine'], + ['united arab emirates', 'uae', 'u a e'], + [ + 'united kingdom', + 'uk', + 'u k', + 'great britain', + 'britain', + 'england', + 'scotland', + 'wales', + 'northern ireland', + ], + [ + 'united states', + 'usa', + 'u s a', + 'us', + 'u s', + 'united states of america', + 'america', + ], + ['uruguay'], + ['uzbekistan'], + ['vanuatu'], + ['venezuela'], + ['vietnam', 'viet nam'], + ['yemen'], + ['zambia'], + ['zimbabwe'], + // Not UN members, but places a question can name. + ['kosovo'], + ['taiwan'], + ['hong kong'], + ['macau', 'macao'], + ['palestine', 'state of palestine'], + ['puerto rico'], + ['vatican city', 'vatican', 'holy see'], +]; + +// Regions are named by questions but are never a My details country. +export const REGION_TABLE: readonly (readonly string[])[] = [ + ['european union', 'eu', 'e u'], + ['europe', 'european'], + ['eea', 'european economic area'], + ['schengen'], + ['emea'], + ['apac', 'asia pacific'], + ['latin america'], + ['north america'], + ['south america'], + ['central america'], + ['americas', 'the americas'], + ['asia'], + ['africa'], + ['middle east'], + ['oceania'], + ['caribbean'], +]; + +/** Canonical country names, lower case. Regions are not included. */ +export const COUNTRY_NAMES: readonly string[] = COUNTRY_TABLE.map( + (row) => row[0]!, +); + +// normalizeLabel turns "&" into a space, so "Trinidad & Tobago" arrives as +// "trinidad tobago". Registers the "and"-less form of every name that has one, +// skipping a form that is already taken by another entry. +function withAndlessForms( + tables: readonly (readonly (readonly string[])[])[], +): (readonly string[])[][] { + const taken = new Set(tables.flat(2)); + return tables.map((table) => + table.map((row) => { + const expanded = [...row]; + for (const name of row) { + const words = name.split(' '); + if (!words.includes('and')) continue; + const derived = words.filter((word) => word !== 'and').join(' '); + if (derived === '' || taken.has(derived)) continue; + taken.add(derived); + expanded.push(derived); + } + return expanded; + }), + ); +} + +const [expandedCountries, expandedRegions] = withAndlessForms([ + COUNTRY_TABLE, + REGION_TABLE, +]); + +/** COUNTRY_TABLE with the derived "and"-less spellings added to each row. */ +export const EXPANDED_COUNTRY_TABLE: readonly (readonly string[])[] = + expandedCountries!; +/** REGION_TABLE with the derived "and"-less spellings added to each row. */ +export const EXPANDED_REGION_TABLE: readonly (readonly string[])[] = + expandedRegions!; + +const COUNTRY_BY_ALIAS = new Map(); +for (const row of EXPANDED_COUNTRY_TABLE) { + for (const alias of row) COUNTRY_BY_ALIAS.set(alias, row[0]!); +} + +interface Matcher { + readonly words: readonly string[]; + readonly length: number; + readonly canonical: string; +} + +// Longest first (more words, then more characters) so a shorter alias cannot +// match inside a longer one, such as "guinea" inside "papua new guinea". +const MATCHERS: readonly Matcher[] = [ + ...EXPANDED_COUNTRY_TABLE, + ...EXPANDED_REGION_TABLE, +] + .flatMap((row) => + row.map((alias) => ({ + words: alias.split(' '), + length: alias.length, + canonical: row[0]!, + })), + ) + .sort((a, b) => b.words.length - a.words.length || b.length - a.length); + +/** Reads a My details value as a country. The whole text must be one name. */ +export function countryOf(text: string): string | undefined { + const name = normalizeLabel(text); + const direct = COUNTRY_BY_ALIAS.get(name); + if (direct !== undefined || !name.startsWith('the ')) return direct; + return COUNTRY_BY_ALIAS.get(name.slice(4)); +} + +/** + * Every country and region a normalised question names, each once, in the + * order it first appears. Matches whole words and uses each word once. + */ +export function placesNamed(normalizedQuestion: string): string[] { + if (normalizedQuestion === '') return []; + const words = normalizedQuestion.split(' '); + const used = new Array(words.length).fill(false); + const firstSeen = new Map(); + for (const matcher of MATCHERS) { + const size = matcher.words.length; + for (let start = 0; start + size <= words.length; start++) { + if (!matcher.words.every((word, i) => words[start + i] === word)) + continue; + if (used.slice(start, start + size).some(Boolean)) continue; + used.fill(true, start, start + size); + const seen = firstSeen.get(matcher.canonical); + if (seen === undefined || start < seen) { + firstSeen.set(matcher.canonical, start); + } + } + } + return [...firstSeen.entries()] + .sort((a, b) => a[1] - b[1]) + .map(([name]) => name); +} diff --git a/core/src/fill/fit.test.ts b/core/src/fill/fit.test.ts new file mode 100644 index 0000000..81671c2 --- /dev/null +++ b/core/src/fill/fit.test.ts @@ -0,0 +1,299 @@ +import { describe, expect, it } from 'vitest'; +import { fitField, type OwnKind } from './fit'; +import type { ScannedField } from './types'; + +function field(overrides: Partial = {}): ScannedField { + return { + ref: 3, + control: 'text', + label: '', + autocomplete: '', + required: false, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + ...overrides, + }; +} + +const UNSUPPORTED = { fit: 'none', reason: 'unsupported_control' }; + +function select(options: string[], overrides: Partial = {}) { + return field({ control: 'select', options, ...overrides }); +} + +function group(options: string[], overrides: Partial = {}) { + return field({ control: 'choice_group', options, ...overrides }); +} + +describe('fitField: text', () => { + it.each(['text', 'textarea'] as const)('writes into %s', (control) => { + expect(fitField(field({ control }), 'text', 'Acme')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'value', value: 'Acme' }, + }); + }); + + it.each([field({ control: 'date' }), select(['Acme']), group(['Acme'])])( + 'does not fit $control', + (f) => { + expect(fitField(f, 'text', 'Acme')).toEqual(UNSUPPORTED); + }, + ); +}); + +describe('fitField: place', () => { + it('writes a value into a text control', () => { + expect(fitField(field(), 'place', 'Canada')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'value', value: 'Canada' }, + }); + }); + + it('picks the matching option in a select', () => { + expect( + fitField(select(['Canada', 'United States']), 'place', 'united states'), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 1 } }); + }); + + it('is unsupported with no equal option', () => { + expect(fitField(select(['Canada', 'Mexico']), 'place', 'France')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported with two equal options', () => { + expect(fitField(select(['Canada', ' canada ']), 'place', 'Canada')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported for a multi-select', () => { + expect( + fitField(select(['Canada'], { multiple: true }), 'place', 'Canada'), + ).toEqual(UNSUPPORTED); + }); + + it('is unsupported for a choice group', () => { + expect(fitField(group(['Canada']), 'place', 'Canada')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: yes_no', () => { + it('picks No in a Yes/No select', () => { + expect(fitField(select(['Yes', 'No']), 'yes_no', 'No')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 1 }, + }); + }); + + it('picks Yes in a No/Yes select', () => { + expect(fitField(select(['No', 'Yes']), 'yes_no', 'Yes')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 1 }, + }); + }); + + it('matches option text case-insensitively', () => { + expect(fitField(select(['yes', 'NO']), 'yes_no', 'No')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 1 }, + }); + }); + + it('is unsupported with a third option', () => { + expect(fitField(select(['Yes', 'No', 'Maybe']), 'yes_no', 'Yes')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported with two Yes options', () => { + expect(fitField(select(['Yes', 'Yes']), 'yes_no', 'Yes')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported for a multi-select', () => { + expect( + fitField(select(['Yes', 'No'], { multiple: true }), 'yes_no', 'Yes'), + ).toEqual(UNSUPPORTED); + }); + + it('writes into a radio group', () => { + expect(fitField(group(['Yes', 'No']), 'yes_no', 'Yes')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'option', index: 0 }, + }); + }); + + it('writes into an empty checkbox pair', () => { + expect( + fitField(group(['Yes', 'No'], { multiple: true }), 'yes_no', 'No'), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 1 } }); + }); + + it('holds when one checkbox is checked', () => { + expect( + fitField( + group(['Yes', 'No'], { multiple: true, checked: [0] }), + 'yes_no', + 'No', + ), + ).toEqual({ fit: 'holds', formValue: 'Yes' }); + }); + + it('holds with both checkboxes checked', () => { + expect( + fitField( + group(['Yes', 'No'], { multiple: true, checked: [0, 1] }), + 'yes_no', + 'No', + ), + ).toEqual({ fit: 'holds', formValue: 'Yes, No' }); + }); + + it('holds a radio group that arrives with several checked', () => { + expect( + fitField(group(['Yes', 'No'], { checked: [0, 1] }), 'yes_no', 'No'), + ).toEqual({ fit: 'holds', formValue: 'Yes, No' }); + }); + + it('is unsupported for a text control', () => { + expect(fitField(field(), 'yes_no', 'Yes')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: choice', () => { + it('picks the matching option', () => { + expect( + fitField( + select(['Yes', 'No', 'Depends on location']), + 'choice', + 'Depends on location', + ), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 2 } }); + }); + + it('is unsupported with no equal option', () => { + expect(fitField(select(['Yes', 'No']), 'choice', 'Maybe')).toEqual( + UNSUPPORTED, + ); + }); + + it('is unsupported when two options equal own', () => { + expect( + fitField(select(['Other', 'other', 'Mine']), 'choice', 'Other'), + ).toEqual(UNSUPPORTED); + }); + + it('writes into a checkbox group with one matching option', () => { + expect( + fitField(group(['Red', 'Blue'], { multiple: true }), 'choice', 'Blue'), + ).toEqual({ fit: 'write', write: { ref: 3, kind: 'option', index: 1 } }); + }); + + it('is unsupported for a multi-select', () => { + expect( + fitField(select(['Red'], { multiple: true }), 'choice', 'Red'), + ).toEqual(UNSUPPORTED); + }); + + it('is unsupported for a text control', () => { + expect(fitField(field(), 'choice', 'Red')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: date', () => { + it('writes into a date control', () => { + expect(fitField(field({ control: 'date' }), 'date', '2026-12-01')).toEqual({ + fit: 'write', + write: { ref: 3, kind: 'value', value: '2026-12-01' }, + }); + }); + + it('is unsupported for a text control', () => { + expect(fitField(field(), 'date', '2026-12-01')).toEqual(UNSUPPORTED); + }); +}); + +describe('fitField: custom and file', () => { + it.each(['text', 'place', 'yes_no', 'choice', 'date'] as OwnKind[])( + 'reports custom_control for %s', + (kind) => { + expect(fitField(field({ control: 'custom' }), kind, 'x')).toEqual({ + fit: 'none', + reason: 'custom_control', + }); + }, + ); + + it.each(['text', 'place', 'yes_no', 'choice', 'date'] as OwnKind[])( + 'reports unsupported_control for a file with %s', + (kind) => { + expect(fitField(field({ control: 'file' }), kind, 'x')).toEqual( + UNSUPPORTED, + ); + }, + ); +}); + +describe('fitField: holds', () => { + it('holds a text value', () => { + expect(fitField(field({ value: 'x' }), 'text', 'Acme')).toEqual({ + fit: 'holds', + formValue: 'x', + }); + }); + + it('holds a select value', () => { + expect( + fitField(select(['Yes', 'No'], { value: 'Yes' }), 'yes_no', 'No'), + ).toEqual({ fit: 'holds', formValue: 'Yes' }); + }); + + it('holds a select value even when no option equals own', () => { + expect( + fitField(select(['Red', 'Blue'], { value: 'Red' }), 'choice', 'Green'), + ).toEqual({ fit: 'holds', formValue: 'Red' }); + }); + + it('holds a date value', () => { + expect( + fitField( + field({ control: 'date', value: '2026-01-01' }), + 'date', + '2026-12-01', + ), + ).toEqual({ fit: 'holds', formValue: '2026-01-01' }); + }); +}); + +describe('fitField: truncated option lists', () => { + it('never picks from a truncated list', () => { + expect( + fitField( + select(['Canada', 'United States'], { optionsTruncated: true }), + 'place', + 'Canada', + ), + ).toEqual(UNSUPPORTED); + }); + + it('checks truncation before what the control holds', () => { + expect( + fitField( + select(['Canada'], { optionsTruncated: true, value: 'Canada' }), + 'place', + 'Canada', + ), + ).toEqual(UNSUPPORTED); + }); + + it('is unsupported for a truncated group', () => { + expect( + fitField(group(['Red'], { optionsTruncated: true }), 'choice', 'Red'), + ).toEqual(UNSUPPORTED); + }); +}); diff --git a/core/src/fill/fit.ts b/core/src/fill/fit.ts new file mode 100644 index 0000000..cf979d1 --- /dev/null +++ b/core/src/fill/fit.ts @@ -0,0 +1,105 @@ +import { sameText } from './compare'; +import type { FillWrite, ScannedField } from './types'; + +export type OwnKind = 'text' | 'place' | 'yes_no' | 'choice' | 'date'; + +export type FitResult = + | { fit: 'write'; write: FillWrite } + | { fit: 'holds'; formValue: string } + | { fit: 'none'; reason: 'custom_control' | 'unsupported_control' }; + +const UNSUPPORTED: FitResult = { fit: 'none', reason: 'unsupported_control' }; + +function isYesNo(options: string[]): boolean { + if (options.length !== 2) return false; + const [a, b] = options as [string, string]; + return ( + (sameText(a, 'Yes') && sameText(b, 'No')) || + (sameText(a, 'No') && sameText(b, 'Yes')) + ); +} + +function controlFits(field: ScannedField, kind: OwnKind): boolean { + const isSelect = field.control === 'select'; + const isGroup = field.control === 'choice_group'; + switch (kind) { + case 'text': + return field.control === 'text' || field.control === 'textarea'; + case 'place': + return ( + field.control === 'text' || + field.control === 'textarea' || + (isSelect && !field.multiple) + ); + case 'yes_no': + return ( + ((isSelect && !field.multiple) || isGroup) && isYesNo(field.options) + ); + case 'choice': + return (isSelect && !field.multiple) || isGroup; + case 'date': + return field.control === 'date'; + default: { + const unreachable: never = kind; + return unreachable; + } + } +} + +/** + * Decides whether one saved value can be written into one scanned control. + * Any doubt comes out as "holds" or "none", never as "write". + */ +export function fitField( + field: ScannedField, + kind: OwnKind, + own: string, +): FitResult { + // 1. Controls the filler never touches. + if (field.control === 'custom') { + return { fit: 'none', reason: 'custom_control' }; + } + if (field.control === 'file') return UNSUPPORTED; + + // 2. Does the control fit the kind. + if (!controlFits(field, kind)) return UNSUPPORTED; + + const isList = field.control === 'select' || field.control === 'choice_group'; + + // 3. A truncated option list cannot be trusted. + if (isList && field.optionsTruncated) return UNSUPPORTED; + + // 4. Never replace what is already there. + if (field.control === 'choice_group') { + if (field.checked.length > 0) { + const formValue = field.checked + .map((i) => field.options[i] ?? '') + .join(', '); + return { fit: 'holds', formValue }; + } + } else if (field.value !== '') { + return { fit: 'holds', formValue: field.value }; + } + + // 5. Pick the one matching option. + if (isList) { + let found = -1; + for (let i = 0; i < field.options.length; i++) { + if (sameText(field.options[i] ?? '', own)) { + if (found !== -1) return UNSUPPORTED; + found = i; + } + } + if (found === -1) return UNSUPPORTED; + return { + fit: 'write', + write: { ref: field.ref, kind: 'option', index: found }, + }; + } + + // 6. Plain value write. + return { + fit: 'write', + write: { ref: field.ref, kind: 'value', value: own }, + }; +} diff --git a/core/src/fill/normalize.test.ts b/core/src/fill/normalize.test.ts new file mode 100644 index 0000000..a93b6bc --- /dev/null +++ b/core/src/fill/normalize.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest'; +import { + containsPhrase, + hasNegation, + isPlaceholderOption, + normalizeLabel, +} from './normalize'; + +describe('normalizeLabel', () => { + it('lower-cases and drops required markers and stars', () => { + expect(normalizeLabel('First Name *')).toBe('first name'); + expect(normalizeLabel('E-mail (required)')).toBe('e mail'); + expect(normalizeLabel('Phone ✱')).toBe('phone'); + }); + + it('drops optional markers regardless of case', () => { + expect(normalizeLabel('State/Province (Optional)')).toBe('state province'); + }); + + it('turns punctuation into spaces and trims', () => { + expect(normalizeLabel(' LinkedIn URL: ')).toBe('linkedin url'); + expect(normalizeLabel('U.S.')).toBe('u s'); + }); + + it('returns an empty string for empty input', () => { + expect(normalizeLabel('')).toBe(''); + }); + + it('keeps words apart when a required marker sits between them', () => { + expect(normalizeLabel('Name(required)here')).toBe('name here'); + }); + + it('collapses repeated spaces inside a label', () => { + expect(normalizeLabel('FIRST NAME')).toBe('first name'); + }); + + it('drops a leading optional marker', () => { + expect(normalizeLabel('(Optional) City')).toBe('city'); + }); +}); + +describe('containsPhrase', () => { + it('matches a phrase of whole words inside the text', () => { + expect( + containsPhrase( + 'are you legally authorized to work in the united states', + 'authorized to work', + ), + ).toBe(true); + }); + + it('does not match a phrase that is only part of a word', () => { + expect( + containsPhrase('i am unauthorized to work', 'authorized to work'), + ).toBe(false); + }); + + it('matches a single whole word', () => { + expect(containsPhrase('salary', 'salary')).toBe(true); + }); + + it('does not match a word that only starts with the phrase', () => { + expect(containsPhrase('salaryman', 'salary')).toBe(false); + }); + + it('returns false for an empty phrase', () => { + expect(containsPhrase('salary', '')).toBe(false); + }); +}); + +describe('hasNegation', () => { + it.each([ + 'Are you not authorized', + "Don't you need sponsorship?", + 'Don’t you', + 'Donʼt you', + 'Don‘t you', + 'Don`t you', + 'without sponsorship', + 'no longer eligible', + 'no\nlonger eligible', + 'no longer eligible', + 'no longer eligible', + 'cannot work', + 'unless sponsored', + ])('is true for %j', (raw) => { + expect(hasNegation(raw)).toBe(true); + }); + + it.each(['Are you authorized to work?', 'Notice period', 'Notes', 'Nothing'])( + 'is false for %j', + (raw) => { + expect(hasNegation(raw)).toBe(false); + }, + ); +}); + +describe('isPlaceholderOption', () => { + it('treats an empty value as a placeholder at any index', () => { + expect(isPlaceholderOption('Choose one', '', 0)).toBe(true); + expect(isPlaceholderOption('No', '', 2)).toBe(true); + }); + + it('treats a leading select, choose, please or pick option as a placeholder', () => { + expect(isPlaceholderOption('Select...', 'Select...', 0)).toBe(true); + expect(isPlaceholderOption('Please select', 'p', 0)).toBe(true); + expect(isPlaceholderOption('Pick one', 'p', 0)).toBe(true); + }); + + it('treats a first option with no letters or digits as a placeholder', () => { + expect(isPlaceholderOption('--', 'x', 0)).toBe(true); + expect(isPlaceholderOption('--', 'x', 1)).toBe(false); + }); + + it('does not treat a word that only starts with a placeholder word as one', () => { + expect(isPlaceholderOption('Pickup', 'p', 0)).toBe(false); + expect(isPlaceholderOption('Selection', 's', 0)).toBe(false); + expect(isPlaceholderOption('Chooser', 'c', 0)).toBe(false); + }); + + it('keeps a real option that is not first', () => { + expect(isPlaceholderOption('Select Committee', 's', 1)).toBe(false); + }); + + it('keeps a real first option', () => { + expect(isPlaceholderOption('Yes', 'yes', 0)).toBe(false); + }); +}); diff --git a/core/src/fill/normalize.ts b/core/src/fill/normalize.ts new file mode 100644 index 0000000..c208db3 --- /dev/null +++ b/core/src/fill/normalize.ts @@ -0,0 +1,40 @@ +const NEGATION_WORDS = + /(? = {}): ScannedField { + nextRef += 1; + return { + ref: nextRef, + control: 'text', + label: '', + autocomplete: '', + required: false, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + ...overrides, + }; +} + +function scanOf(fields: ScannedField[], frames: string[] = []): FormScan { + return { fields, frames, truncated: false }; +} + +function answer(key: string, value: unknown): CanonicalAnswer { + const def = DEFAULT_ANSWERS.find((d) => d.key === key); + return { + id: `id-${key}`, + createdAt: '2026-11-20T00:00:00.000Z', + key, + label: def?.label ?? key, + type: def?.type, + value: value as AnswerValue, + }; +} + +const SALARY: AnswerValue = { + type: 'money_range', + min: 100000, + max: 120000, + currency: 'USD', + period: 'year', +}; + +const SAM_PROFILE: Record = { + full_name: 'Sam Example', + first_name: 'Sam', + last_name: 'Example', + email: 'sam@example.com', + phone: '555-010-0142', + address_line1: '12 Example Street', + address_line2: 'Unit 4', + city: 'Springfield', + region: 'Example State', + postal_code: '00000', + country: 'United States', + linkedin: 'https://example.com/in/sam', + github: 'https://example.com/sam', + website: 'https://example.com', +}; + +const SAM_ANSWERS: CanonicalAnswer[] = [ + answer('work_authorization', { type: 'yes_no', value: true }), + answer('sponsorship', { type: 'yes_no', value: false }), + answer('salary_range', SALARY), + answer('earliest_start_date', { type: 'date', value: '2026-12-01' }), + answer('relocation', { type: 'choice', value: 'Depends on location' }), + answer('reason_for_leaving', { + type: 'text', + value: 'Looking for a new challenge', + }), +]; + +const sam: PlanInput = { profile: { ...SAM_PROFILE }, answers: SAM_ANSWERS }; + +function withProfile(changes: Partial>): PlanInput { + return { profile: { ...SAM_PROFILE, ...changes }, answers: SAM_ANSWERS }; +} + +function withAnswers(answers: CanonicalAnswer[]): PlanInput { + return { profile: { ...SAM_PROFILE }, answers }; +} + +function yesNoSelect(label: string, overrides: Partial = {}) { + return field({ + control: 'select', + label, + options: ['Yes', 'No'], + ...overrides, + }); +} + +function expectNoBadWrites(plan: ReturnType): void { + for (const w of plan.writes) { + if (w.kind === 'value') { + expect(w.value).not.toBe('undefined'); + expect(w.value).not.toContain('[object'); + } + } +} + +const AUTH = 'Are you legally authorized to work'; + +describe('buildPlan: profile fields', () => { + it('fills an empty contact block', () => { + const fields = ['First name', 'Last name', 'Email', 'Phone'].map((label) => + field({ label }), + ); + const plan = buildPlan(scanOf(fields), sam); + expect(plan.rows.map((r) => r.status)).toEqual([ + 'will_fill', + 'will_fill', + 'will_fill', + 'will_fill', + ]); + expect(plan.writes).toEqual([ + { ref: fields[0]!.ref, kind: 'value', value: 'Sam' }, + { ref: fields[1]!.ref, kind: 'value', value: 'Example' }, + { ref: fields[2]!.ref, kind: 'value', value: 'sam@example.com' }, + { ref: fields[3]!.ref, kind: 'value', value: '555-010-0142' }, + ]); + }); + + it('matches, case and format aside', () => { + const email = field({ label: 'Email', value: 'SAM@example.com' }); + const phone = field({ label: 'Phone', value: '+1 555 010 0142' }); + const plan = buildPlan(scanOf([email, phone]), sam); + expect(plan.rows.map((r) => r.status)).toEqual(['matches', 'matches']); + expect(plan.writes).toEqual([]); + }); + + it('never replaces a value', () => { + const email = field({ label: 'Email', value: 'other@example.com' }); + const plan = buildPlan(scanOf([email]), sam); + expect(plan.rows[0]).toMatchObject({ + status: 'differs', + formValue: 'other@example.com', + ownValue: 'sam@example.com', + }); + expect(plan.rows[0]!.write).toBeUndefined(); + expect(plan.writes).toEqual([]); + }); + + it('reports no value when the profile lacks the key', () => { + const input = withProfile({ first_name: ' ' }); + const plan = buildPlan(scanOf([field({ label: 'First name' })]), input); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'no_value', + ownValue: '', + }); + const missing: PlanInput = { profile: {}, answers: [] }; + const again = buildPlan(scanOf([field({ label: 'First name' })]), missing); + expect(again.rows[0]!.reason).toBe('no_value'); + }); + + it('marks duplicated profile fields ambiguous and keeps the owner value', () => { + const fields = [ + field({ label: 'Name' }), + field({ label: 'Email' }), + field({ label: 'Name' }), + field({ label: 'Email' }), + ]; + const plan = buildPlan(scanOf(fields), sam); + expect(plan.rows.map((r) => r.reason)).toEqual([ + 'ambiguous', + 'ambiguous', + 'ambiguous', + 'ambiguous', + ]); + expect(plan.rows.map((r) => r.ownValue)).toEqual([ + 'Sam Example', + 'sam@example.com', + 'Sam Example', + 'sam@example.com', + ]); + expect(plan.writes).toEqual([]); + }); + + it('puts a country into a select and a text field', () => { + const select = field({ + control: 'select', + label: 'Country', + options: ['Canada', 'United States'], + }); + const plan = buildPlan(scanOf([select]), sam); + expect(plan.rows[0]).toMatchObject({ + status: 'will_fill', + write: { ref: select.ref, kind: 'option', index: 1 }, + }); + }); + + it('files are never filled and have no target', () => { + const plan = buildPlan( + scanOf([field({ control: 'file', label: 'Resume' })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'file', + }); + expect(plan.rows[0]!.target).toBeUndefined(); + }); +}); + +describe('buildPlan: answers', () => { + it('fills each answer into its control', () => { + const auth = yesNoSelect(`${AUTH} in the United States?`); + const relocate = field({ + control: 'select', + label: 'Are you willing to relocate?', + options: ['Yes', 'No', 'Depends on location'], + }); + const start = field({ control: 'date', label: 'Earliest start date' }); + const reason = field({ control: 'textarea', label: 'Reason for leaving' }); + const plan = buildPlan(scanOf([auth, relocate, start, reason]), sam); + expect(plan.writes).toEqual([ + { ref: auth.ref, kind: 'option', index: 0 }, + { ref: relocate.ref, kind: 'option', index: 2 }, + { ref: start.ref, kind: 'value', value: '2026-12-01' }, + { ref: reason.ref, kind: 'value', value: 'Looking for a new challenge' }, + ]); + expect(plan.rows[0]!.answerValue).toEqual({ type: 'yes_no', value: true }); + }); + + it('never writes the salary', () => { + const plan = buildPlan(scanOf([field({ label: 'Desired salary' })]), sam); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'never_auto', + ownValue: formatAnswer(SALARY), + }); + expect(plan.rows[0]!.ownValue).not.toBe(''); + expect(plan.writes).toEqual([]); + }); + + it('does not answer a negated question', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you not authorized to work in the United States?'), + ]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'negated', + ownValue: '', + }); + expect(plan.rows[0]!.answerValue).toBeUndefined(); + }); + + it('marks a question that matches two answers ambiguous', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you authorized to work without visa sponsorship?'), + ]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'ambiguous', + ownValue: '', + target: { kind: 'answer', key: 'work_authorization' }, + }); + }); + + it('marks duplicated answers ambiguous', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you authorized to work in the U.S.?'), + yesNoSelect('Is your authorized to work status current?'), + ]), + sam, + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['ambiguous', 'ambiguous']); + expect(plan.rows.map((r) => r.ownValue)).toEqual(['', '']); + expect(plan.writes).toEqual([]); + }); + + it('a question matching two answers counts for neither in the duplicate pass', () => { + const plan = buildPlan( + scanOf([ + yesNoSelect('Are you authorized to work without visa sponsorship?'), + yesNoSelect(`${AUTH}?`), + ]), + sam, + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['ambiguous', undefined]); + expect(plan.rows[1]!.status).toBe('will_fill'); + }); + + it.each([ + ['Canada', sam], + ['Canada', { profile: {}, answers: SAM_ANSWERS }], + ['Canada', withProfile({ country: 'Narnia' })], + ['the EU', sam], + ['Estonia', sam], + ])('treats %s as another country', (place, input) => { + const plan = buildPlan( + scanOf([yesNoSelect(`${AUTH} in ${place}?`)]), + input, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'other_country', + ownValue: '', + }); + expect(plan.rows[0]!.answerValue).toBeUndefined(); + expect(plan.writes).toEqual([]); + }); + + it("fills for the owner's own country, by any spelling", () => { + const plan = buildPlan( + scanOf([yesNoSelect(`${AUTH} in the U.S.?`)]), + withProfile({ country: 'USA' }), + ); + expect(plan.rows[0]!.status).toBe('will_fill'); + }); + + it('fills when no country is named', () => { + const plan = buildPlan(scanOf([yesNoSelect(`${AUTH}?`)]), sam); + expect(plan.rows[0]!.status).toBe('will_fill'); + }); + + it('does not write into a custom control', () => { + const plan = buildPlan( + scanOf([field({ control: 'custom', label: `${AUTH}?` })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'custom_control', + ownValue: 'Yes', + }); + }); + + it('reports an unsupported control', () => { + const plan = buildPlan( + scanOf([field({ control: 'text', label: 'Earliest start date' })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + reason: 'unsupported_control', + ownValue: '2026-12-01', + }); + }); + + it('compares a held answer to the owner', () => { + const same = field({ + control: 'select', + label: `${AUTH}?`, + options: ['Yes', 'No'], + value: 'yes', + }); + const other = field({ + control: 'select', + label: 'Do you need visa sponsorship?', + options: ['Yes', 'No'], + value: 'Yes', + }); + const plan = buildPlan(scanOf([same, other]), sam); + expect(plan.rows.map((r) => r.status)).toEqual(['matches', 'differs']); + expect(plan.writes).toEqual([]); + }); +}); + +describe('buildPlan: unrecognised, frames, tables', () => { + it('flags a required unknown field and counts optional ones', () => { + const plan = buildPlan( + scanOf([ + field({ label: 'Favourite colour', required: true }), + field({ label: 'Pet name' }), + field({ label: 'Shoe size' }), + ]), + sam, + ); + expect(plan.rows).toHaveLength(1); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'not_recognised', + }); + expect(plan.rows[0]!.target).toBeUndefined(); + expect(plan.unrecognisedOptional).toBe(2); + }); + + it('lists a frame and no rows for a scan without fields', () => { + const plan = buildPlan( + scanOf([], ['https://boards.greenhouse.io/embed/job_app?for=example']), + sam, + ); + expect(plan.rows).toEqual([]); + expect(plan.frames).toHaveLength(1); + expect(plan.frames[0]!.site).toBe('greenhouse'); + }); + + it('takes the recognition tables as an argument', () => { + const label = 'Do you hold a valid work permit?'; + const scan = scanOf([yesNoSelect(label)]); + expect(buildPlan(scan, sam).rows).toEqual([]); + const tables: RecognitionTables = { + ...DEFAULT_TABLES, + answerPhrases: new Map([ + ...DEFAULT_TABLES.answerPhrases, + ['work_authorization', ['work permit']], + ]), + }; + const plan = buildPlan(scan, sam, tables); + expect(plan.rows[0]).toMatchObject({ + status: 'will_fill', + target: { kind: 'answer', key: 'work_authorization' }, + }); + }); +}); + +describe('buildPlan: odd answer records', () => { + const auth = () => yesNoSelect(`${AUTH}?`); + + it.each<[string, CanonicalAnswer[]]>([ + [ + 'a record with no key', + [{ id: 'x', createdAt: 'now', value: { type: 'yes_no', value: true } }], + ], + [ + 'the wrong value type', + [answer('work_authorization', { type: 'text', value: 'yes' })], + ], + ['a string for a value', [answer('work_authorization', 'Yes')]], + ['a null value', [answer('work_authorization', null)]], + [ + 'a first record without a value', + [ + answer('work_authorization', undefined), + answer('work_authorization', { type: 'yes_no', value: true }), + ], + ], + [ + 'a non-boolean yes/no', + [answer('work_authorization', { type: 'yes_no', value: 'true' })], + ], + ['a null record', [null as never]], + ])('gives no value for %s', (_name, answers) => { + const plan = buildPlan(scanOf([auth()]), withAnswers(answers)); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'no_value', + ownValue: '', + }); + expect(plan.rows[0]!.answerValue).toBeUndefined(); + expect(plan.writes).toEqual([]); + expectNoBadWrites(plan); + }); + + it('never writes a malformed date or a blank text answer', () => { + const fields = [ + field({ control: 'date', label: 'Earliest start date' }), + field({ control: 'textarea', label: 'Reason for leaving' }), + ]; + const plan = buildPlan( + scanOf(fields), + withAnswers([ + answer('earliest_start_date', { type: 'date', value: '12/01/2026' }), + answer('reason_for_leaving', { type: 'text', value: ' ' }), + ]), + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['no_value', 'no_value']); + expect(plan.writes).toEqual([]); + }); + + it('a missing profile object value is no value, not "undefined"', () => { + const odd = { profile: { email: 5 as never }, answers: [] }; + const plan = buildPlan(scanOf([field({ label: 'Email' })]), odd); + expect(plan.rows[0]!.reason).toBe('no_value'); + expectNoBadWrites(plan); + }); +}); + +describe('buildPlan: rule order and guards', () => { + it.each([ + [ + 'a negated question', + 'Are you not authorized to work in the United States?', + 'negated', + ], + ['a question naming Canada', `${AUTH} in Canada?`, 'other_country'], + ])('rule 6 comes before the custom control rule: %s', (_n, label, reason) => { + const plan = buildPlan(scanOf([field({ control: 'custom', label })]), sam); + expect(plan.rows[0]).toMatchObject({ reason, ownValue: '' }); + expect(plan.rows[0]).not.toHaveProperty('answerValue'); + }); + + it('applies the place check to sponsorship', () => { + const canada = yesNoSelect('Do you need visa sponsorship in Canada?'); + const us = yesNoSelect( + 'Do you need visa sponsorship in the United States?', + ); + const plan = buildPlan(scanOf([canada]), sam); + expect(plan.rows[0]).toMatchObject({ + reason: 'other_country', + ownValue: '', + }); + expect(plan.rows[0]).not.toHaveProperty('answerValue'); + expect(buildPlan(scanOf([us]), sam).rows[0]!.status).toBe('will_fill'); + }); + + it('marks a profile key matched by a custom control and a text field ambiguous', () => { + const plan = buildPlan( + scanOf([ + field({ label: 'Email' }), + field({ control: 'custom', label: 'Email' }), + ]), + sam, + ); + expect(plan.rows.map((r) => r.reason)).toEqual(['ambiguous', 'ambiguous']); + }); + + it('gives a file field labelled Email the file row, with no write', () => { + const plan = buildPlan( + scanOf([field({ control: 'file', label: 'Email' })]), + sam, + ); + expect(plan.rows[0]).toMatchObject({ + status: 'not_filled', + reason: 'file', + }); + expect(plan.rows[0]!.target).toBeUndefined(); + expect(plan.rows[0]!.write).toBeUndefined(); + expect(plan.writes).toEqual([]); + }); + + it('does not count a file field as a duplicate', () => { + const text = field({ label: 'Email' }); + const plan = buildPlan( + scanOf([field({ control: 'file', label: 'Email' }), text]), + sam, + ); + expect(plan.rows[1]!.status).toBe('will_fill'); + expect(plan.writes).toEqual([ + { ref: text.ref, kind: 'value', value: 'sam@example.com' }, + ]); + }); + + it('trims the owner values it offers and writes', () => { + const name = field({ label: 'First name' }); + const reason = field({ control: 'textarea', label: 'Reason for leaving' }); + const input: PlanInput = { + profile: { first_name: ' Sam ' }, + answers: [ + answer('reason_for_leaving', { type: 'text', value: ' Moving on ' }), + ], + }; + const plan = buildPlan(scanOf([name, reason]), input); + expect(plan.rows.map((r) => r.ownValue)).toEqual(['Sam', 'Moving on']); + expect(plan.writes).toEqual([ + { ref: name.ref, kind: 'value', value: 'Sam' }, + { ref: reason.ref, kind: 'value', value: 'Moving on' }, + ]); + }); + + it('joins the checked options of a group in checked order', () => { + const group = field({ + control: 'choice_group', + label: 'Are you not willing to relocate?', + options: ['Red', 'Green', 'Blue'], + checked: [2, 0], + multiple: true, + }); + const plan = buildPlan(scanOf([group]), sam); + expect(plan.rows[0]!.formValue).toBe('Blue, Red'); + }); +}); + +describe('buildPlan: invariants', () => { + it('holds over a large mixed scan', () => { + // Every profile and answer key is used by one field, except the Name pair. + const fields: ScannedField[] = [ + field({ label: 'First name' }), // will_fill (profile) + field({ label: 'Email', value: 'other@example.com' }), // differs + field({ label: 'Phone', value: '555-010-0142' }), // matches + field({ label: 'Name' }), // ambiguous (the deliberate pair) + field({ label: 'Name' }), + field({ control: 'file', label: 'Resume' }), // file + field({ label: 'Favourite colour', required: true }), // not_recognised + field({ label: 'Pet name' }), // optional, counted + field({ control: 'custom', label: 'City' }), // custom_control + field({ label: 'GitHub' }), // no_value (profile lacks it) + field({ + control: 'select', + label: 'Country', + options: ['Canada', 'United States'], + }), // will_fill (profile, option) + field({ label: 'Desired salary' }), // never_auto + yesNoSelect(`${AUTH}?`), // will_fill (answer) + yesNoSelect('Do you need visa sponsorship in Canada?'), // other_country + field({ + control: 'select', + label: 'Are you not willing to relocate?', + options: ['Yes', 'No', 'Depends on location'], + }), // negated + yesNoSelect('Authorized to work, and need visa sponsorship?'), // two answers + field({ label: 'Earliest start date' }), // unsupported_control + field({ control: 'textarea', label: 'Reason for leaving' }), // will_fill (answer) + field({ label: 'LinkedIn', value: 'https://example.com/in/sam' }), // matches + ]; + const noGithub: Partial> = { ...SAM_PROFILE }; + delete noGithub.github; + const plan = buildPlan(scanOf(fields), { + profile: noGithub, + answers: SAM_ANSWERS, + }); + const willFill = plan.rows.filter((r) => r.status === 'will_fill'); + + // The scan must keep covering every outcome. + const seen = new Set( + plan.rows.map((r) => { + const kind = r.target?.kind ?? 'none'; + return r.status === 'not_filled' + ? `not_filled:${r.reason}` + : `${r.status}:${kind}`; + }), + ); + for (const expected of [ + 'will_fill:profile', + 'will_fill:answer', + 'matches:profile', + 'differs:profile', + 'not_filled:negated', + 'not_filled:other_country', + 'not_filled:no_value', + 'not_filled:custom_control', + 'not_filled:unsupported_control', + 'not_filled:ambiguous', + 'not_filled:never_auto', + 'not_filled:file', + 'not_filled:not_recognised', + ]) { + expect(seen).toContain(expected); + } + for (const row of willFill) expect(row.write?.ref).toBe(row.ref); + expect( + plan.rows.filter((r) => r.reason === 'ambiguous').length, + ).toBeGreaterThanOrEqual(3); + + for (const row of plan.rows) { + expect(row.reason !== undefined).toBe(row.status === 'not_filled'); + expect(row.write !== undefined).toBe(row.status === 'will_fill'); + expect(row.answerValue !== undefined).toBe( + row.target?.kind === 'answer' && row.ownValue !== '', + ); + } + for (const row of willFill) expect(row.formValue).toBe(''); + expect(plan.writes).toEqual(willFill.map((r) => r.write)); + expect(new Set(plan.writes.map((w) => w.ref)).size).toBe( + plan.writes.length, + ); + expect(willFill.length).toBeGreaterThan(3); + expect(plan.unrecognisedOptional).toBe(1); + expectNoBadWrites(plan); + }); +}); diff --git a/core/src/fill/plan.ts b/core/src/fill/plan.ts new file mode 100644 index 0000000..e1b24c9 --- /dev/null +++ b/core/src/fill/plan.ts @@ -0,0 +1,355 @@ +import { DEFAULT_ANSWERS, formatAnswer } from '../answers'; +import { isLocalDate } from '../dates'; +import type { ProfileKey } from '../profile'; +import type { AnswerType, AnswerValue } from '../types'; +import { sameProfileValue, sameText } from './compare'; +import { countryOf, placesNamed } from './countries'; +import { fitField, type FitResult, type OwnKind } from './fit'; +import { hasNegation, normalizeLabel } from './normalize'; +import { recogniseAnswers, recogniseProfile } from './recognise'; +import { frameAdvice } from './site'; +import { DEFAULT_TABLES, type RecognitionTables } from './tables'; +import type { + FillPlan, + FillTarget, + FormScan, + NotFilledReason, + PlanInput, + PlanRow, + ScannedField, +} from './types'; + +/** What a field means, found once per field. */ +type Recognised = + | { kind: 'profile'; key: ProfileKey } + | { kind: 'answer'; key: string } + | { kind: 'two_answers'; keys: string[] } + | { kind: 'nothing' }; + +/** A saved answer that is safe to offer: its display text and a clean copy of the value. */ +interface OwnAnswer { + value: AnswerValue; + text: string; +} + +const ANSWER_TYPES = new Map( + DEFAULT_ANSWERS.map((a) => [a.key, a.type]), +); + +// ---- Rule 2: recognise a field ------------------------------------------ + +function recognise(field: ScannedField, tables: RecognitionTables): Recognised { + const profileKey = recogniseProfile(field, tables); + if (profileKey !== undefined) return { kind: 'profile', key: profileKey }; + const keys = recogniseAnswers(field, tables); + const [first] = keys; + if (first === undefined) return { kind: 'nothing' }; + return keys.length === 1 + ? { kind: 'answer', key: first } + : { kind: 'two_answers', keys }; +} + +// ---- Rule 5: first pass, count the keys --------------------------------- + +function duplicateKeys(recognised: readonly Recognised[]): Set { + const counts = new Map(); + for (const r of recognised) { + const id = countKey(r); + if (id !== undefined) counts.set(id, (counts.get(id) ?? 0) + 1); + } + const duplicated = new Set(); + for (const [id, count] of counts) if (count >= 2) duplicated.add(id); + return duplicated; +} + +function countKey(r: Recognised): string | undefined { + if (r.kind === 'profile') return `profile:${r.key}`; + if (r.kind === 'answer') return `answer:${r.key}`; + return undefined; +} + +// ---- Rule 8: the owner's value ------------------------------------------ + +function profileValue(input: PlanInput, key: ProfileKey): string { + const raw: unknown = input.profile[key]; + return typeof raw === 'string' ? raw.trim() : ''; +} + +function nonEmptyString(raw: unknown): string | undefined { + if (typeof raw !== 'string') return undefined; + const trimmed = raw.trim(); + return trimmed === '' ? undefined : trimmed; +} + +/** Checks the stored value against the type the key must have; rebuilds a clean copy. */ +function cleanAnswer(raw: unknown, type: AnswerType): OwnAnswer | undefined { + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) { + return undefined; + } + const stored = raw as { type?: unknown; value?: unknown }; + if (stored.type !== type) return undefined; + switch (type) { + case 'yes_no': { + if (typeof stored.value !== 'boolean') return undefined; + return { + value: { type: 'yes_no', value: stored.value }, + text: stored.value ? 'Yes' : 'No', + }; + } + case 'choice': + case 'text': { + const text = nonEmptyString(stored.value); + if (text === undefined) return undefined; + return { value: { type, value: text }, text }; + } + case 'date': { + const day = stored.value; + if (typeof day !== 'string' || !isLocalDate(day)) return undefined; + return { value: { type: 'date', value: day }, text: day }; + } + case 'money_range': { + const text = formatAnswer(raw as AnswerValue); + return text === '' ? undefined : { value: raw as AnswerValue, text }; + } + default: + return undefined; + } +} + +function ownAnswer(input: PlanInput, key: string): OwnAnswer | undefined { + const type = ANSWER_TYPES.get(key); + if (type === undefined) return undefined; + const record: unknown = input.answers.find( + (a: unknown) => + typeof a === 'object' && + a !== null && + (a as { key?: unknown }).key === key, + ); + if (record === undefined) return undefined; + return cleanAnswer((record as { value?: unknown }).value, type); +} + +function answerKind(own: OwnAnswer): OwnKind | undefined { + switch (own.value.type) { + case 'yes_no': + case 'choice': + case 'date': + case 'text': + return own.value.type; + default: + return undefined; + } +} + +// ---- Rule 6: the place check -------------------------------------------- + +/** True when the question names a place that is not the owner's country. */ +function namesOtherPlace(label: string, input: PlanInput): boolean { + const named = placesNamed(normalizeLabel(label)); + if (named.length === 0) return false; + const country = + typeof input.profile.country === 'string' + ? countryOf(input.profile.country) + : undefined; + return country === undefined || !named.every((place) => place === country); +} + +// ---- Rows --------------------------------------------------------------- + +/** What the form holds now, as text. */ +function formValueOf(field: ScannedField): string { + switch (field.control) { + case 'text': + case 'textarea': + case 'date': + case 'select': + return field.value; + case 'choice_group': + return field.checked + .map((i) => field.options[i]) + .filter((o): o is string => o !== undefined) + .join(', '); + default: + return ''; + } +} + +function baseRow(field: ScannedField, target?: FillTarget): PlanRow { + const row: PlanRow = { + ref: field.ref, + label: field.label, + control: field.control, + required: field.required, + status: 'not_filled', + formValue: formValueOf(field), + ownValue: '', + }; + if (target !== undefined) row.target = target; + return row; +} + +function notFilled( + field: ScannedField, + reason: NotFilledReason, + target?: FillTarget, + own?: OwnAnswer | string, +): PlanRow { + const row = baseRow(field, target); + row.reason = reason; + if (own !== undefined) setOwn(row, own); + return row; +} + +/** Sets ownValue, and answerValue only for an answer target with a value (never for a profile one). */ +function setOwn(row: PlanRow, own: OwnAnswer | string): void { + if (typeof own === 'string') { + row.ownValue = own; + return; + } + row.ownValue = own.text; + if (row.target?.kind === 'answer') row.answerValue = own.value; +} + +/** Rule 9: the row for a fit result. */ +function fitRow( + field: ScannedField, + target: FillTarget, + fit: FitResult, + own: OwnAnswer | string, + same: (formValue: string, ownText: string) => boolean, +): PlanRow { + const ownText = typeof own === 'string' ? own : own.text; + if (fit.fit === 'none') return notFilled(field, fit.reason, target, own); + const row = baseRow(field, target); + setOwn(row, own); + if (fit.fit === 'holds') { + row.formValue = fit.formValue; + row.status = same(fit.formValue, ownText) ? 'matches' : 'differs'; + return row; + } + row.status = 'will_fill'; + row.write = fit.write; + return row; +} + +function profileRow( + field: ScannedField, + key: ProfileKey, + duplicated: boolean, + input: PlanInput, +): PlanRow { + const target: FillTarget = { kind: 'profile', key }; + const own = profileValue(input, key); + // 5. Duplicates keep the owner's value for the copy button. + if (duplicated) return notFilled(field, 'ambiguous', target, own); + // 7. Custom control. + if (field.control === 'custom') { + return notFilled(field, 'custom_control', target, own); + } + // 8. No value. + if (own === '') return notFilled(field, 'no_value', target); + // 9. Fit. + const kind: OwnKind = + key === 'country' || key === 'region' ? 'place' : 'text'; + return fitRow(field, target, fitField(field, kind, own), own, (form, mine) => + sameProfileValue(key, form, mine), + ); +} + +function answerRow( + field: ScannedField, + key: string, + duplicated: boolean, + input: PlanInput, +): PlanRow { + const target: FillTarget = { kind: 'answer', key }; + // 5. Duplicates offer nothing. + if (duplicated) return notFilled(field, 'ambiguous', target); + // 6. Answers only. + if (hasNegation(field.label)) return notFilled(field, 'negated', target); + const own = ownAnswer(input, key); + if (key === 'salary_range') { + return notFilled(field, 'never_auto', target, own); + } + if ( + (key === 'work_authorization' || key === 'sponsorship') && + namesOtherPlace(field.label, input) + ) { + return notFilled(field, 'other_country', target); + } + // 7. Custom control. + if (field.control === 'custom') { + return notFilled(field, 'custom_control', target, own); + } + // 8. No value. + const kind = own === undefined ? undefined : answerKind(own); + if (own === undefined || kind === undefined) { + return notFilled(field, 'no_value', target); + } + // 9. Fit. + return fitRow(field, target, fitField(field, kind, own.text), own, sameText); +} + +/** Rules 1, 3 and 4, then the profile or answer rules. Undefined means no row. */ +function planField( + field: ScannedField, + recognised: Recognised, + duplicates: ReadonlySet, + input: PlanInput, +): PlanRow | undefined { + // 1. Files. + if (field.control === 'file') return notFilled(field, 'file'); + const duplicated = duplicates.has(countKey(recognised) ?? ''); + switch (recognised.kind) { + case 'nothing': + // 3. Optional unknown fields get no row; the caller counts them. + return field.required ? notFilled(field, 'not_recognised') : undefined; + case 'two_answers': + // 4. One question, two answers. + return notFilled(field, 'ambiguous', { + kind: 'answer', + key: recognised.keys[0] ?? '', + }); + case 'profile': + return profileRow(field, recognised.key, duplicated, input); + case 'answer': + return answerRow(field, recognised.key, duplicated, input); + } +} + +/** + * Decides what the extension would write into a form. Pure: it reads the + * scan, the owner's details and answers, and returns one row per recognised + * field plus the writes. It never replaces a value and never writes when in doubt. + */ +export function buildPlan( + scan: FormScan, + input: PlanInput, + tables: RecognitionTables = DEFAULT_TABLES, +): FillPlan { + const recognised = scan.fields.map((f) => + f.control === 'file' + ? ({ kind: 'nothing' } as const) + : recognise(f, tables), + ); + const duplicates = duplicateKeys(recognised); + const plan: FillPlan = { + rows: [], + writes: [], + unrecognisedOptional: 0, + frames: frameAdvice(scan.frames), + }; + scan.fields.forEach((field, i) => { + const r = recognised[i] ?? ({ kind: 'nothing' } as const); + const row = planField(field, r, duplicates, input); + if (row === undefined) { + plan.unrecognisedOptional += 1; + return; + } + plan.rows.push(row); + if (row.status === 'will_fill' && row.write !== undefined) { + plan.writes.push(row.write); + } + }); + return plan; +} diff --git a/core/src/fill/recognise.test.ts b/core/src/fill/recognise.test.ts new file mode 100644 index 0000000..d1b38a5 --- /dev/null +++ b/core/src/fill/recognise.test.ts @@ -0,0 +1,235 @@ +import { describe, expect, it } from 'vitest'; +import { DEFAULT_ANSWERS } from '../answers'; +import { PROFILE_FIELDS, type ProfileKey } from '../profile'; +import { normalizeLabel } from './normalize'; +import { recogniseAnswers, recogniseProfile } from './recognise'; +import { DEFAULT_TABLES } from './tables'; + +const profile = (label: string, autocomplete = '') => + recogniseProfile({ label, autocomplete }, DEFAULT_TABLES); +const answers = (label: string) => recogniseAnswers({ label }, DEFAULT_TABLES); + +describe('DEFAULT_TABLES', () => { + it('has exactly the 14 profile keys', () => { + expect([...DEFAULT_TABLES.profilePhrases.keys()].sort()).toEqual( + PROFILE_FIELDS.map((f) => f.key).sort(), + ); + }); + + it('lists the answer keys in the order of DEFAULT_ANSWERS', () => { + expect([...DEFAULT_TABLES.answerPhrases.keys()]).toEqual( + DEFAULT_ANSWERS.map((a) => a.key), + ); + }); + + it('stores every phrase in normalised form', () => { + const all = [ + ...[...DEFAULT_TABLES.profilePhrases.values()].flat(), + ...[...DEFAULT_TABLES.answerPhrases.values()].flat(), + ]; + expect(all.length).toBeGreaterThan(0); + for (const phrase of all) expect(normalizeLabel(phrase)).toBe(phrase); + }); + + it('has no phrase under two profile keys', () => { + const all = [...DEFAULT_TABLES.profilePhrases.values()].flat(); + expect(new Set(all).size).toBe(all.length); + }); + + it('pins the autocomplete table to the design', () => { + expect(DEFAULT_TABLES.profileAutocomplete.size).toBe(12); + expect([...DEFAULT_TABLES.profileAutocomplete]).toEqual([ + ['name', 'full_name'], + ['given-name', 'first_name'], + ['family-name', 'last_name'], + ['email', 'email'], + ['tel', 'phone'], + ['tel-national', 'phone'], + ['address-line1', 'address_line1'], + ['address-line2', 'address_line2'], + ['address-level2', 'city'], + ['address-level1', 'region'], + ['postal-code', 'postal_code'], + ['country-name', 'country'], + ]); + }); + + it('pins the profile label phrases to the design', () => { + expect([...DEFAULT_TABLES.profilePhrases]).toEqual([ + ['full_name', ['name', 'full name', 'your name', 'legal name']], + ['first_name', ['first name', 'given name']], + ['last_name', ['last name', 'surname', 'family name']], + ['email', ['email', 'email address', 'e mail']], + [ + 'phone', + ['phone', 'phone number', 'mobile', 'mobile number', 'telephone'], + ], + ['address_line1', ['address', 'street address', 'address line 1']], + ['address_line2', ['address line 2']], + ['city', ['city']], + ['region', ['state', 'province', 'region', 'state or province']], + ['postal_code', ['zip', 'zip code', 'postal code', 'postcode']], + ['country', ['country']], + ['linkedin', ['linkedin', 'linkedin url', 'linkedin profile']], + ['github', ['github', 'github url', 'github profile']], + [ + 'website', + [ + 'website', + 'personal website', + 'portfolio', + 'portfolio url', + 'other website', + 'other website url', + ], + ], + ]); + }); + + it('pins the answer phrases to the design', () => { + expect([...DEFAULT_TABLES.answerPhrases]).toEqual([ + [ + 'work_authorization', + [ + 'authorized to work', + 'authorised to work', + 'eligible to work', + 'legally authorized', + 'legally authorised', + 'right to work', + ], + ], + [ + 'sponsorship', + [ + 'require sponsorship', + 'need sponsorship', + 'visa sponsorship', + 'sponsorship for employment', + 'immigration sponsorship', + ], + ], + [ + 'salary_range', + ['salary', 'compensation', 'expected pay', 'desired pay'], + ], + [ + 'earliest_start_date', + [ + 'start date', + 'available to start', + 'when can you start', + 'earliest start', + ], + ], + [ + 'relocation', + [ + 'willing to relocate', + 'open to relocating', + 'open to relocation', + 'able to relocate', + ], + ], + ['reason_for_leaving', ['reason for leaving', 'why are you leaving']], + ]); + }); +}); + +describe('recogniseProfile', () => { + it.each<[ProfileKey, string, string, ProfileKey | undefined]>([ + ['full_name', 'Full name', 'Company name', undefined], + ['first_name', 'First Name *', 'First name of referee', undefined], + ['last_name', 'Surname', 'Maiden surname', undefined], + ['email', 'Email address', 'Reference email', undefined], + ['phone', 'Mobile number', 'Emergency phone', undefined], + ['address_line1', 'Street address', 'Email address', 'email'], + ['address_line2', 'Address line 2', 'Address line 3', undefined], + ['city', 'City', 'City of birth', undefined], + ['region', 'State or province', 'State of mind', undefined], + ['postal_code', 'ZIP code', 'Area code', undefined], + ['country', 'Country', 'Country of birth', undefined], + ['linkedin', 'LinkedIn URL', 'LinkedIn headline', undefined], + ['github', 'GitHub profile', 'GitHub stars', undefined], + ['website', 'Portfolio URL', 'Website feedback', undefined], + ])('%s has a match and a near miss', (key, match, nearMiss, nearResult) => { + expect(profile(match)).toBe(key); + expect(profile(nearMiss)).toBe(nearResult); + }); + + it('lets autocomplete beat the label', () => { + expect(profile('Reference email', 'email')).toBe('email'); + expect(profile('Email', 'family-name')).toBe('last_name'); + expect(profile('Email', 'off')).toBe('email'); + }); + + it('gives undefined for an empty label with no known token', () => { + expect(profile('')).toBeUndefined(); + expect(profile('', 'organization')).toBeUndefined(); + }); + + it.each<[string, ProfileKey]>([ + ['name', 'full_name'], + ['given-name', 'first_name'], + ['family-name', 'last_name'], + ['email', 'email'], + ['tel', 'phone'], + ['tel-national', 'phone'], + ['address-line1', 'address_line1'], + ['address-line2', 'address_line2'], + ['address-level2', 'city'], + ['address-level1', 'region'], + ['postal-code', 'postal_code'], + ['country-name', 'country'], + ])('maps the autocomplete token %s to %s', (token, key) => { + expect(profile('', token)).toBe(key); + }); + + it('does not recognise prototype names', () => { + for (const token of ['constructor', '__proto__', 'toString']) { + expect(profile('', token)).toBeUndefined(); + } + for (const label of ['constructor', 'hasOwnProperty']) { + expect(profile(label)).toBeUndefined(); + expect(answers(label)).toEqual([]); + } + }); +}); + +describe('recogniseAnswers', () => { + it.each<[string, string[]]>([ + [ + 'Are you legally authorized to work in the United States?', + ['work_authorization'], + ], + [ + 'Will you now or in the future require sponsorship for employment visa status?', + ['sponsorship'], + ], + ['Are you willing to relocate?', ['relocation']], + ['When can you start?', ['earliest_start_date']], + ['Reason for leaving your last role', ['reason_for_leaving']], + ['Desired salary', ['salary_range']], + ])('matches %s', (question, expected) => { + expect(answers(question)).toEqual(expected); + }); + + it('returns both answers of a two-answer question, in table order', () => { + expect( + answers('Are you authorized to work without visa sponsorship?'), + ).toEqual(['work_authorization', 'sponsorship']); + expect( + answers('Visa sponsorship: are you authorized to work here?'), + ).toEqual(['work_authorization', 'sponsorship']); + }); + + it('returns each key once when several phrases match', () => { + expect( + answers('Authorized to work? Eligible to work? Right to work?'), + ).toEqual(['work_authorization']); + }); + + it('returns nothing when no phrase matches', () => { + expect(answers('Why do you want to work here?')).toEqual([]); + }); +}); diff --git a/core/src/fill/recognise.ts b/core/src/fill/recognise.ts new file mode 100644 index 0000000..9eafd9f --- /dev/null +++ b/core/src/fill/recognise.ts @@ -0,0 +1,35 @@ +import type { ProfileKey } from '../profile'; +import { containsPhrase, normalizeLabel } from './normalize'; +import type { RecognitionTables } from './tables'; +import type { ScannedField } from './types'; + +/** + * The profile key a field means, or undefined. A known autocomplete token + * decides; an unknown token is ignored and the label must equal a phrase. + */ +export function recogniseProfile( + field: Pick, + tables: RecognitionTables, +): ProfileKey | undefined { + const byToken = tables.profileAutocomplete.get(field.autocomplete); + if (byToken !== undefined) return byToken; + const label = normalizeLabel(field.label); + if (label === '') return undefined; + for (const [key, phrases] of tables.profilePhrases) { + if (phrases.includes(label)) return key; + } + return undefined; +} + +/** Every answer key whose phrase the label contains as whole words, once each, in table order. */ +export function recogniseAnswers( + field: Pick, + tables: RecognitionTables, +): string[] { + const label = normalizeLabel(field.label); + const keys: string[] = []; + for (const [key, phrases] of tables.answerPhrases) { + if (phrases.some((phrase) => containsPhrase(label, phrase))) keys.push(key); + } + return keys; +} diff --git a/core/src/fill/result.test.ts b/core/src/fill/result.test.ts new file mode 100644 index 0000000..07d5975 --- /dev/null +++ b/core/src/fill/result.test.ts @@ -0,0 +1,284 @@ +import { describe, expect, it } from 'vitest'; +import { buildFillResult } from './result'; +import type { FillPlan, PlanRow, WriteReport } from './types'; + +const AT = '2026-11-20T09:00:00.000Z'; + +function plan(rows: PlanRow[]): FillPlan { + return { rows, writes: [], unrecognisedOptional: 0, frames: [] }; +} + +function willFill(ref: number, label = `Field ${ref}`): PlanRow { + return { + ref, + label, + control: 'text', + required: false, + target: { kind: 'profile', key: 'first_name' }, + status: 'will_fill', + formValue: '', + ownValue: 'Alex', + write: { ref, kind: 'value', value: 'Alex' }, + }; +} + +function differs(ref: number, label = `Field ${ref}`): PlanRow { + return { + ref, + label, + control: 'text', + required: false, + target: { kind: 'profile', key: 'email' }, + status: 'differs', + formValue: 'old@example.com', + ownValue: 'new@example.com', + }; +} + +function matches(ref: number, label = `Field ${ref}`): PlanRow { + return { + ref, + label, + control: 'text', + required: false, + target: { kind: 'profile', key: 'city' }, + status: 'matches', + formValue: 'Springfield', + ownValue: 'Springfield', + }; +} + +function notFilled( + ref: number, + reason: PlanRow['reason'], + label = `Field ${ref}`, +): PlanRow { + return { + ref, + label, + control: 'file', + required: false, + status: 'not_filled', + reason, + formValue: '', + ownValue: '', + }; +} + +function answerRow(ref: number): PlanRow { + return { + ref, + label: 'Are you authorised to work in the United States?', + control: 'choice_group', + required: true, + target: { kind: 'answer', key: 'work_auth_us' }, + status: 'will_fill', + formValue: '', + ownValue: 'Yes', + write: { ref, kind: 'option', index: 0 }, + answerValue: { type: 'yes_no', value: true }, + }; +} + +describe('buildFillResult', () => { + it('canonicalises the address', () => { + const tabUrl = 'https://example.com/jobs/1?utm_source=x#apply'; + const empty = plan([]); + + expect( + buildFillResult({ tabUrl, at: AT, plan: empty, outcomes: [] }).url, + ).toBe('https://example.com/jobs/1'); + expect( + buildFillResult({ + tabUrl, + relCanonical: 'https://example.com/jobs/one', + at: AT, + plan: empty, + outcomes: [], + }).url, + ).toBe('https://example.com/jobs/one'); + }); + + it('sets the site type', () => { + const result = buildFillResult({ + tabUrl: 'https://jobs.lever.co/example-co/abc123', + at: AT, + plan: plan([]), + outcomes: [], + }); + + expect(result.siteType).toBe('lever'); + }); + + it('carries outcomes', () => { + const outcomes: WriteReport[] = [ + { ref: 1, outcome: 'written' }, + { ref: 2, outcome: 'gone' }, + ]; + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1), willFill(2), differs(3)]), + outcomes, + }).rows; + + expect(rows[0]).toStrictEqual({ + label: 'Field 1', + target: { kind: 'profile', key: 'first_name' }, + status: 'will_fill', + outcome: 'written', + }); + expect(rows[1]?.outcome).toBe('gone'); + expect(rows[2]).not.toHaveProperty('outcome'); + }); + + it('a will_fill row with no report is failed', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [], + }).rows; + + expect(rows[0]?.outcome).toBe('failed'); + }); + + it('an answer row carries what item 3 needs', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([answerRow(5)]), + outcomes: [{ ref: 5, outcome: 'written' }], + }).rows; + + expect(rows[0]).toStrictEqual({ + label: 'Are you authorised to work in the United States?', + target: { kind: 'answer', key: 'work_auth_us' }, + status: 'will_fill', + answerValue: { type: 'yes_no', value: true }, + outcome: 'written', + }); + }); + + it('the first report for a ref wins', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [ + { ref: 1, outcome: 'written' }, + { ref: 1, outcome: 'failed' }, + ], + }).rows; + + expect(rows[0]?.outcome).toBe('written'); + }); + + it('a report for a ref no row has is ignored', () => { + const withStray = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [{ ref: 99, outcome: 'written' }], + }); + const without = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1)]), + outcomes: [], + }); + + expect(withStray).toStrictEqual(without); + expect(withStray.rows).toHaveLength(1); + }); + + it('a report for a differs row does not give it an outcome', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([differs(2)]), + outcomes: [{ ref: 2, outcome: 'written' }], + }).rows; + + expect(rows[0]).not.toHaveProperty('outcome'); + }); + + it('an empty plan gives no rows but keeps url, siteType and at', () => { + const result = buildFillResult({ + tabUrl: 'https://jobs.lever.co/example-co/abc123?utm_medium=x', + at: AT, + plan: plan([]), + outcomes: [{ ref: 1, outcome: 'written' }], + }); + + expect(result).toStrictEqual({ + url: 'https://jobs.lever.co/example-co/abc123', + siteType: 'lever', + at: AT, + rows: [], + }); + }); + + it('keeps plan row order for mixed statuses', () => { + const planRows = [ + willFill(1, 'First name'), + notFilled(2, 'no_value', 'Middle name'), + differs(3, 'Email'), + matches(4, 'City'), + answerRow(5), + ]; + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan(planRows), + outcomes: [], + }).rows; + + expect(rows.map((row) => row.label)).toStrictEqual( + planRows.map((row) => row.label), + ); + expect(rows.map((row) => row.status)).toStrictEqual([ + 'will_fill', + 'not_filled', + 'differs', + 'matches', + 'will_fill', + ]); + }); + + it('a row without target or reason gets no such keys', () => { + const rows = buildFillResult({ + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([notFilled(7, 'file', 'Resume')]), + outcomes: [], + }).rows; + + expect(rows[0]).toStrictEqual({ + label: 'Resume', + status: 'not_filled', + reason: 'file', + }); + }); + + it('does not change its arguments', () => { + const input = { + tabUrl: 'https://example.com/jobs/1', + at: AT, + plan: plan([willFill(1), answerRow(5), differs(3)]), + outcomes: [ + { ref: 1, outcome: 'written' }, + { ref: 5, outcome: 'gone' }, + ] as WriteReport[], + }; + const snapshot: unknown = JSON.parse( + JSON.stringify({ plan: input.plan, outcomes: input.outcomes }), + ); + + buildFillResult(input); + + expect({ plan: input.plan, outcomes: input.outcomes }).toStrictEqual( + snapshot, + ); + }); +}); diff --git a/core/src/fill/result.ts b/core/src/fill/result.ts new file mode 100644 index 0000000..be3d45a --- /dev/null +++ b/core/src/fill/result.ts @@ -0,0 +1,66 @@ +import type { SiteType } from '../formhand'; +import { canonicalizeUrl } from '../url'; +import type { AnswerValue, IsoInstant } from '../types'; +import { siteTypeForUrl } from './site'; +import type { + FillPlan, + FillTarget, + NotFilledReason, + RowStatus, + WriteOutcome, + WriteReport, +} from './types'; + +export interface FillResultRow { + label: string; + target?: FillTarget; + status: RowStatus; + reason?: NotFilledReason; + outcome?: WriteOutcome; + answerValue?: AnswerValue; +} + +export interface FillResult { + url: string; + siteType: SiteType; + at: IsoInstant; + rows: FillResultRow[]; +} + +/** + * Turns a fill plan and the page's write reports into the record kept for a + * later feature. The first report for a ref wins; reports for unknown refs are + * ignored. Only will_fill rows get an outcome. Never changes its arguments. + */ +export function buildFillResult(args: { + tabUrl: string; + relCanonical?: string; + at: IsoInstant; + plan: FillPlan; + outcomes: readonly WriteReport[]; +}): FillResult { + const reported = new Map(); + for (const report of args.outcomes) { + if (!reported.has(report.ref)) { + reported.set(report.ref, report.outcome); + } + } + + const rows = args.plan.rows.map((row): FillResultRow => { + const result: FillResultRow = { label: row.label, status: row.status }; + if (row.target !== undefined) result.target = row.target; + if (row.reason !== undefined) result.reason = row.reason; + if (row.status === 'will_fill') { + result.outcome = reported.get(row.ref) ?? 'failed'; + } + if (row.answerValue !== undefined) result.answerValue = row.answerValue; + return result; + }); + + return { + url: canonicalizeUrl(args.tabUrl, args.relCanonical), + siteType: siteTypeForUrl(args.tabUrl), + at: args.at, + rows, + }; +} diff --git a/core/src/fill/site.test.ts b/core/src/fill/site.test.ts new file mode 100644 index 0000000..279a95a --- /dev/null +++ b/core/src/fill/site.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from 'vitest'; +import { FRAME_HOSTS, frameAdvice, siteTypeForUrl } from './site'; + +describe('FRAME_HOSTS', () => { + it('maps the Greenhouse and Ashby embed hosts', () => { + expect(FRAME_HOSTS.size).toBe(3); + expect(FRAME_HOSTS.get('job-boards.greenhouse.io')).toBe('greenhouse'); + expect(FRAME_HOSTS.get('boards.greenhouse.io')).toBe('greenhouse'); + expect(FRAME_HOSTS.get('jobs.ashbyhq.com')).toBe('ashby'); + }); +}); + +describe('siteTypeForUrl', () => { + it.each([ + ['https://job-boards.greenhouse.io/exampleco/jobs/1', 'greenhouse'], + ['https://jobs.lever.co/exampleco/abc/apply', 'lever'], + ['https://jobs.ashbyhq.com/exampleco/abc/application', 'ashby'], + ['https://exampleco.wd5.myworkdayjobs.com/x', 'workday'], + ['https://www.linkedin.com/jobs/view/1', 'linkedin'], + ['https://uk.indeed.com/viewjob', 'indeed'], + ['https://example.com/careers', 'other'], + ['https://evil-greenhouse.io/', 'other'], + ['https://greenhouse.io.example.com/', 'other'], + ['not a url', 'other'], + ['', 'other'], + ['about:addons', 'other'], + ['ftp://jobs.lever.co/x', 'other'], + ['HTTPS://JOBS.LEVER.CO/x', 'lever'], + ['https://lever.co/', 'lever'], + ])('siteTypeForUrl(%j) is %s', (url, expected) => { + expect(siteTypeForUrl(url)).toBe(expected); + }); +}); + +describe('frameAdvice', () => { + it('returns one greenhouse entry with the original src', () => { + const src = + 'https://job-boards.greenhouse.io/embed/job_app?for=exampleco&token=1'; + expect(frameAdvice(['https://example.com/video', src])).toEqual([ + { site: 'greenhouse', src }, + ]); + }); + + it('returns an ashby entry for an Ashby frame', () => { + const src = 'https://jobs.ashbyhq.com/exampleco'; + expect(frameAdvice([src])).toEqual([{ site: 'ashby', src }]); + }); + + it('keeps only the first frame for a site', () => { + const first = 'https://boards.greenhouse.io/embed/a'; + const second = 'https://job-boards.greenhouse.io/embed/b'; + expect(frameAdvice([first, second])).toEqual([ + { site: 'greenhouse', src: first }, + ]); + }); + + it('puts greenhouse before ashby whatever the order', () => { + const ashby = 'https://jobs.ashbyhq.com/exampleco'; + const greenhouse = 'https://boards.greenhouse.io/embed/a'; + expect(frameAdvice([ashby, greenhouse])).toEqual([ + { site: 'greenhouse', src: greenhouse }, + { site: 'ashby', src: ashby }, + ]); + }); + + it('ignores frames that do not parse', () => { + expect(frameAdvice(['nonsense'])).toEqual([]); + }); + + it('ignores a look-alike host', () => { + expect(frameAdvice(['https://jobs.ashbyhq.com.example.com/x'])).toEqual([]); + }); + + it('ignores non-https frames', () => { + expect(frameAdvice(['http://jobs.ashbyhq.com/exampleco'])).toEqual([]); + }); + + it('returns an empty list for no frames', () => { + expect(frameAdvice([])).toEqual([]); + }); +}); diff --git a/core/src/fill/site.ts b/core/src/fill/site.ts new file mode 100644 index 0000000..c4fdd6f --- /dev/null +++ b/core/src/fill/site.ts @@ -0,0 +1,76 @@ +import type { SiteType } from '../formhand'; +import type { FrameAdvice } from './types'; + +// core/ declares no URL global (lib ES2023, types []), so declare the subset used here. +interface UrlLike { + protocol: string; + hostname: string; +} +declare const URL: { new (url: string): UrlLike }; + +export const FRAME_HOSTS: ReadonlyMap = new Map< + string, + 'greenhouse' | 'ashby' +>([ + ['job-boards.greenhouse.io', 'greenhouse'], + ['boards.greenhouse.io', 'greenhouse'], + ['jobs.ashbyhq.com', 'ashby'], +]); + +const SITE_SUFFIXES: ReadonlyArray = [ + ['greenhouse.io', 'greenhouse'], + ['lever.co', 'lever'], + ['ashbyhq.com', 'ashby'], + ['myworkdayjobs.com', 'workday'], + ['workday.com', 'workday'], + ['linkedin.com', 'linkedin'], + ['indeed.com', 'indeed'], +]; + +function parseUrl(input: string): UrlLike | undefined { + try { + return new URL(input); + } catch { + return undefined; + } +} + +export function siteTypeForUrl(url: string): SiteType { + const parsed = parseUrl(url); + if ( + !parsed || + (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') + ) { + return 'other'; + } + const host = parsed.hostname.toLowerCase(); + for (const [suffix, site] of SITE_SUFFIXES) { + if (host === suffix || host.endsWith('.' + suffix)) { + return site; + } + } + return 'other'; +} + +export function frameAdvice(frames: readonly string[]): FrameAdvice[] { + const taken = new Map<'greenhouse' | 'ashby', string>(); + for (const src of frames) { + const parsed = parseUrl(src); + if (!parsed || parsed.protocol !== 'https:') { + continue; + } + const site = FRAME_HOSTS.get(parsed.hostname.toLowerCase()); + if (site === undefined || taken.has(site)) { + continue; + } + taken.set(site, src); + } + const advice: FrameAdvice[] = []; + for (const site of ['greenhouse', 'ashby'] as const) { + const src = taken.get(site); + if (src !== undefined) { + advice.push({ site, src }); + } + } + return advice; +} diff --git a/core/src/fill/tables.ts b/core/src/fill/tables.ts new file mode 100644 index 0000000..8912226 --- /dev/null +++ b/core/src/fill/tables.ts @@ -0,0 +1,98 @@ +import type { ProfileKey } from '../profile'; + +export interface RecognitionTables { + profileAutocomplete: ReadonlyMap; + profilePhrases: ReadonlyMap; + /** Answer key to phrases, in the order of DEFAULT_ANSWERS. */ + answerPhrases: ReadonlyMap; +} + +/** Phrases are stored in the form normalizeLabel produces. */ +export const DEFAULT_TABLES: RecognitionTables = { + profileAutocomplete: new Map([ + ['name', 'full_name'], + ['given-name', 'first_name'], + ['family-name', 'last_name'], + ['email', 'email'], + ['tel', 'phone'], + ['tel-national', 'phone'], + ['address-line1', 'address_line1'], + ['address-line2', 'address_line2'], + ['address-level2', 'city'], + ['address-level1', 'region'], + ['postal-code', 'postal_code'], + ['country-name', 'country'], + ]), + profilePhrases: new Map([ + ['full_name', ['name', 'full name', 'your name', 'legal name']], + ['first_name', ['first name', 'given name']], + ['last_name', ['last name', 'surname', 'family name']], + ['email', ['email', 'email address', 'e mail']], + [ + 'phone', + ['phone', 'phone number', 'mobile', 'mobile number', 'telephone'], + ], + ['address_line1', ['address', 'street address', 'address line 1']], + ['address_line2', ['address line 2']], + ['city', ['city']], + ['region', ['state', 'province', 'region', 'state or province']], + ['postal_code', ['zip', 'zip code', 'postal code', 'postcode']], + ['country', ['country']], + ['linkedin', ['linkedin', 'linkedin url', 'linkedin profile']], + ['github', ['github', 'github url', 'github profile']], + [ + 'website', + [ + 'website', + 'personal website', + 'portfolio', + 'portfolio url', + 'other website', + 'other website url', + ], + ], + ]), + answerPhrases: new Map([ + [ + 'work_authorization', + [ + 'authorized to work', + 'authorised to work', + 'eligible to work', + 'legally authorized', + 'legally authorised', + 'right to work', + ], + ], + [ + 'sponsorship', + [ + 'require sponsorship', + 'need sponsorship', + 'visa sponsorship', + 'sponsorship for employment', + 'immigration sponsorship', + ], + ], + ['salary_range', ['salary', 'compensation', 'expected pay', 'desired pay']], + [ + 'earliest_start_date', + [ + 'start date', + 'available to start', + 'when can you start', + 'earliest start', + ], + ], + [ + 'relocation', + [ + 'willing to relocate', + 'open to relocating', + 'open to relocation', + 'able to relocate', + ], + ], + ['reason_for_leaving', ['reason for leaving', 'why are you leaving']], + ]), +}; diff --git a/core/src/fill/types.ts b/core/src/fill/types.ts new file mode 100644 index 0000000..f96fcd7 --- /dev/null +++ b/core/src/fill/types.ts @@ -0,0 +1,124 @@ +import type { ProfileKey } from '../profile'; +import type { AnswerValue, CanonicalAnswer } from '../types'; + +export const MAX_FIELDS = 200; +export const MAX_OPTIONS = 50; +export const MAX_LABEL = 300; +export const MAX_VALUE = 500; +export const MAX_FRAMES = 5; +export const MAX_FRAME_SRC = 2_000; +export const MAX_AUTOCOMPLETE = 40; + +export const CONTROL_KINDS = [ + 'text', + 'textarea', + 'date', + 'select', + 'choice_group', + 'file', + 'custom', +] as const; +export type ControlKind = (typeof CONTROL_KINDS)[number]; + +export interface ScannedField { + /** The field's number in the page script's list for this scan. */ + ref: number; + control: ControlKind; + /** '' when none was found. */ + label: string; + /** Last token, lower case; '' when absent. */ + autocomplete: string; + required: boolean; + /** Text, textarea, date: the value. Select: the chosen option's text, '' on a placeholder. Others: ''. */ + value: string; + /** Select (placeholders left out) and choice_group; [] otherwise. */ + options: string[]; + /** Choice_group: indexes into options; [] otherwise. */ + checked: number[]; + /** A checkbox group or a multi-select. */ + multiple: boolean; + /** The page had more than MAX_OPTIONS options. */ + optionsTruncated: boolean; +} + +export interface FormScan { + fields: ScannedField[]; + frames: string[]; + truncated: boolean; +} + +export type FillWrite = + | { ref: number; kind: 'value'; value: string } + | { ref: number; kind: 'option'; index: number }; + +export const WRITE_OUTCOMES = [ + 'written', + 'gone', + 'not_empty', + 'failed', +] as const; +export type WriteOutcome = (typeof WRITE_OUTCOMES)[number]; + +export interface WriteReport { + ref: number; + outcome: WriteOutcome; +} + +export interface ApplyResult { + outcomes: WriteReport[]; + scan: FormScan; +} + +export type FillTarget = + { kind: 'profile'; key: ProfileKey } | { kind: 'answer'; key: string }; + +export type RowStatus = 'will_fill' | 'matches' | 'differs' | 'not_filled'; + +export type NotFilledReason = + | 'no_value' + | 'custom_control' + | 'unsupported_control' + | 'never_auto' + | 'ambiguous' + | 'negated' + | 'other_country' + | 'file' + | 'not_recognised' + | 'changed'; + +export interface PlanRow { + ref: number; + label: string; + control: ControlKind; + required: boolean; + /** Absent on file and not_recognised rows. */ + target?: FillTarget; + status: RowStatus; + /** Set exactly when status is 'not_filled'. */ + reason?: NotFilledReason; + /** What the form holds now, as text. */ + formValue: string; + /** The owner's value as text; '' when there is none or it must not be offered. */ + ownValue: string; + /** Set exactly when status is 'will_fill'. */ + write?: FillWrite; + /** Answer targets that have a value. */ + answerValue?: AnswerValue; +} + +export interface FrameAdvice { + site: 'greenhouse' | 'ashby'; + src: string; +} + +export interface FillPlan { + rows: PlanRow[]; + writes: FillWrite[]; + unrecognisedOptional: number; + frames: FrameAdvice[]; +} + +export interface PlanInput { + profile: Partial>; + answers: readonly CanonicalAnswer[]; +} diff --git a/core/src/fill/validate.test.ts b/core/src/fill/validate.test.ts new file mode 100644 index 0000000..43964ff --- /dev/null +++ b/core/src/fill/validate.test.ts @@ -0,0 +1,424 @@ +import { describe, expect, it } from 'vitest'; +import type { FormScan, ScannedField } from './types'; +import { toApplyResult, toFormScan } from './validate'; + +function field(over: Record = {}): Record { + return { + ref: 0, + control: 'text', + label: 'First name', + autocomplete: 'given-name', + required: true, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + ...over, + }; +} + +function scanOf( + fields: unknown[], + extra: Record = {}, +): Record { + return { fields, frames: [], truncated: false, ...extra }; +} + +describe('toFormScan', () => { + it('passes a well-formed scan through', () => { + const fields: ScannedField[] = [ + { + ref: 0, + control: 'text', + label: 'Name', + autocomplete: 'name', + required: true, + value: 'Ada Example', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 1, + control: 'textarea', + label: 'Why us', + autocomplete: '', + required: false, + value: 'Because', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 2, + control: 'date', + label: 'Start date', + autocomplete: '', + required: false, + value: '2026-12-01', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 3, + control: 'select', + label: 'Country', + autocomplete: 'country', + required: false, + value: 'Canada', + options: ['Canada', 'Mexico'], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 4, + control: 'choice_group', + label: 'Authorised', + autocomplete: '', + required: true, + value: '', + options: ['Yes', 'No'], + checked: [0], + multiple: false, + optionsTruncated: false, + }, + { + ref: 5, + control: 'file', + label: 'Resume', + autocomplete: '', + required: true, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + { + ref: 6, + control: 'custom', + label: 'Skills', + autocomplete: '', + required: false, + value: '', + options: [], + checked: [], + multiple: false, + optionsTruncated: false, + }, + ]; + const scan: FormScan = { + fields, + frames: ['https://jobs.example.com/a'], + truncated: false, + }; + expect(toFormScan(structuredClone(scan))).toEqual(scan); + }); + + it('rejects non-objects', () => { + expect(toFormScan(undefined)).toBeUndefined(); + expect(toFormScan('x')).toBeUndefined(); + expect(toFormScan([1])).toBeUndefined(); + expect(toFormScan(new Date())).toBeUndefined(); + expect(toFormScan({ fields: 'no' })).toBeUndefined(); + const swapped = Object.create({ x: 1 }) as Record; + swapped.fields = []; + expect(toFormScan(swapped)).toBeUndefined(); + }); + + it('caps a hostile scan', () => { + const many = Array.from({ length: 5000 }, (_, i) => field({ ref: i })); + const big = toFormScan(scanOf(many)); + expect(big?.fields).toHaveLength(200); + expect(big?.truncated).toBe(true); + + const one = toFormScan( + scanOf([ + field({ + label: 'a'.repeat(10_000), + value: 'b'.repeat(600), + }), + ]), + ); + expect(one?.fields[0]?.label).toHaveLength(300); + expect(one?.fields[0]?.value).toHaveLength(500); + + const opts = Array.from({ length: 80 }, (_, i) => `o${String(i)}`); + const sel = toFormScan( + scanOf([field({ control: 'select', options: opts })]), + ); + expect(sel?.fields[0]?.options).toHaveLength(50); + expect(sel?.fields[0]?.optionsTruncated).toBe(true); + }); + + it('caps autocomplete and each option, after trimming', () => { + const scan = toFormScan( + scanOf([ + field({ + control: 'select', + autocomplete: ` ${'X'.repeat(100)} `, + options: [` ${'y'.repeat(400)} `, ' Yes '], + }), + ]), + ); + expect(scan?.fields[0]?.autocomplete).toBe('x'.repeat(40)); + expect(scan?.fields[0]?.options).toEqual(['y'.repeat(300), 'Yes']); + }); + + it('trusts truncation flags only when exactly true', () => { + const scan = toFormScan( + scanOf([field({ control: 'select', optionsTruncated: true })], { + truncated: true, + }), + ); + expect(scan?.truncated).toBe(true); + expect(scan?.fields[0]?.optionsTruncated).toBe(true); + const no = toFormScan( + scanOf([field({ control: 'select', optionsTruncated: 'true' })], { + truncated: 1, + }), + ); + expect(no?.truncated).toBe(false); + expect(no?.fields[0]?.optionsTruncated).toBe(false); + }); + + it('drops bad fields', () => { + const scan = toFormScan( + scanOf([ + field({ ref: -1 }), + field({ ref: 1.5 }), + field({ ref: '2' }), + field({ ref: 3 }), + field({ ref: 3, label: 'dup' }), + field({ ref: 4, control: 'password' }), + null, + field({ ref: 5 }), + ]), + ); + expect(scan?.fields.map((f) => f.ref)).toEqual([3, 5]); + expect(scan?.fields[0]?.label).toBe('First name'); + }); + + it('coerces types', () => { + const scan = toFormScan( + scanOf([ + field({ label: 42, required: 'yes', multiple: 1 }), + field({ + ref: 1, + control: 'choice_group', + options: ['Yes', 7, 'No'], + checked: [0, 9, 'x'], + multiple: true, + }), + field({ ref: 2, control: 'choice_group', options: ['A', 'B'] }), + ]), + ); + expect(scan?.fields[0]?.label).toBe(''); + expect(scan?.fields[0]?.required).toBe(false); + expect(scan?.fields[0]?.multiple).toBe(false); + expect(scan?.fields[1]?.options).toEqual(['Yes', 'No']); + expect(scan?.fields[1]?.checked).toEqual([0]); + expect(scan?.fields[1]?.multiple).toBe(true); + expect(scan?.fields[2]?.checked).toEqual([]); + }); + + it('marks the options untrusted when a non-string option was dropped', () => { + const scan = toFormScan( + scanOf([ + field({ ref: 0, control: 'select', options: ['Yes', 7, 'No'] }), + field({ ref: 1, control: 'select', options: ['Yes', 'No'] }), + field({ ref: 2, control: 'choice_group', options: [null, 'No'] }), + ]), + ); + expect(scan?.fields[0]).toMatchObject({ + options: ['Yes', 'No'], + optionsTruncated: true, + }); + expect(scan?.fields[1]?.optionsTruncated).toBe(false); + expect(scan?.fields[2]).toMatchObject({ + options: ['No'], + optionsTruncated: true, + }); + }); + + it('drops a ref that is not a safe integer', () => { + const scan = toFormScan(scanOf([field({ ref: 1e300 }), field({ ref: 2 })])); + expect(scan?.fields.map((f) => f.ref)).toEqual([2]); + const result = toApplyResult({ + outcomes: [ + { ref: 1e300, outcome: 'written' }, + { ref: 2, outcome: 'written' }, + ], + scan: scanOf([]), + }); + expect(result?.outcomes).toEqual([{ ref: 2, outcome: 'written' }]); + }); + + it('keeps optionsTruncated false on a control without options', () => { + const scan = toFormScan( + scanOf([field({ control: 'text', optionsTruncated: true })]), + ); + expect(scan?.fields[0]?.optionsTruncated).toBe(false); + }); + + it('drops duplicate and out-of-range checked indexes', () => { + const scan = toFormScan( + scanOf([ + field({ + control: 'choice_group', + options: ['A', 'B'], + checked: [1, 1, -1, 0], + }), + ]), + ); + expect(scan?.fields[0]?.checked).toEqual([1, 0]); + }); + + it('treats a missing or non-array frames, options and checked as empty', () => { + const scan = toFormScan({ + fields: [ + field({ control: 'choice_group', options: 'Yes', checked: 'x' }), + ], + frames: 'https://a.example.com', + }); + expect(scan?.frames).toEqual([]); + expect(scan?.fields[0]?.options).toEqual([]); + expect(scan?.fields[0]?.checked).toEqual([]); + }); + + it('empties values a control does not use', () => { + const scan = toFormScan( + scanOf([ + field({ ref: 0, control: 'file', value: 'C:\\x.pdf' }), + field({ ref: 1, control: 'custom', value: 'x', options: ['a'] }), + field({ + ref: 2, + control: 'text', + value: 'kept', + options: ['a'], + checked: [0], + multiple: true, + }), + field({ + ref: 3, + control: 'select', + value: 'a', + options: ['a', 'b'], + checked: [0], + multiple: true, + }), + ]), + ); + expect(scan?.fields[0]?.value).toBe(''); + expect(scan?.fields[1]?.value).toBe(''); + expect(scan?.fields[1]?.options).toEqual([]); + expect(scan?.fields[2]).toMatchObject({ + value: 'kept', + options: [], + checked: [], + multiple: false, + }); + expect(scan?.fields[3]).toMatchObject({ + value: 'a', + options: ['a', 'b'], + checked: [], + multiple: true, + }); + }); + + it('keeps only https frames', () => { + const one = toFormScan( + scanOf([], { + frames: ['https://jobs.ashbyhq.com/a', 'javascript:alert(1)', 7], + }), + ); + expect(one?.frames).toEqual(['https://jobs.ashbyhq.com/a']); + + const six = toFormScan( + scanOf([], { + frames: Array.from( + { length: 6 }, + (_, i) => `https://e.example.com/${String(i)}`, + ), + }), + ); + expect(six?.frames).toHaveLength(5); + + const long = toFormScan( + scanOf([], { frames: [`https://e.example.com/${'a'.repeat(3000)}`] }), + ); + expect(long?.frames[0]).toHaveLength(2000); + }); + + it('ignores unknown keys', () => { + const raw: unknown = JSON.parse( + '{"fields":[],"frames":[],"extra":1,"__proto__":{"x":1}}', + ); + expect(toFormScan(raw)).toEqual({ + fields: [], + frames: [], + truncated: false, + }); + }); +}); + +describe('toApplyResult', () => { + const scan = scanOf([field()]); + + it('passes a good result', () => { + const result = toApplyResult({ + outcomes: [ + { ref: 0, outcome: 'written' }, + { ref: 1, outcome: 'not_empty' }, + ], + scan, + }); + expect(result?.outcomes).toEqual([ + { ref: 0, outcome: 'written' }, + { ref: 1, outcome: 'not_empty' }, + ]); + expect(result?.scan.fields).toHaveLength(1); + }); + + it('turns an unknown outcome into failed', () => { + const result = toApplyResult({ + outcomes: [ + { ref: 0, outcome: 'exploded' }, + { ref: 1, outcome: 7 }, + ], + scan, + }); + expect(result?.outcomes).toEqual([ + { ref: 0, outcome: 'failed' }, + { ref: 1, outcome: 'failed' }, + ]); + }); + + it('rejects a missing scan or bad shape', () => { + expect(toApplyResult({ outcomes: [] })).toBeUndefined(); + expect(toApplyResult({ outcomes: [], scan: 'x' })).toBeUndefined(); + expect(toApplyResult({ outcomes: 'no', scan })).toBeUndefined(); + expect(toApplyResult(null)).toBeUndefined(); + }); + + it('drops entries without an integer ref and caps at 200', () => { + const outcomes: unknown[] = [ + { ref: 'a', outcome: 'written' }, + { ref: 1.5, outcome: 'written' }, + null, + ...Array.from({ length: 300 }, (_, i) => ({ + ref: i, + outcome: 'written', + })), + ]; + const result = toApplyResult({ outcomes, scan }); + expect(result?.outcomes).toHaveLength(200); + expect(result?.outcomes[0]?.ref).toBe(0); + }); +}); diff --git a/core/src/fill/validate.ts b/core/src/fill/validate.ts new file mode 100644 index 0000000..a9096a2 --- /dev/null +++ b/core/src/fill/validate.ts @@ -0,0 +1,158 @@ +import { + CONTROL_KINDS, + MAX_AUTOCOMPLETE, + MAX_FIELDS, + MAX_FRAME_SRC, + MAX_FRAMES, + MAX_LABEL, + MAX_OPTIONS, + MAX_VALUE, + WRITE_OUTCOMES, + type ApplyResult, + type ControlKind, + type FormScan, + type ScannedField, + type WriteOutcome, + type WriteReport, +} from './types'; + +// Everything here arrives from a script that ran inside a web page. It is +// capped or dropped, never thrown on. + +function isPlainObject(value: unknown): value is Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) + return false; + const proto: unknown = Object.getPrototypeOf(value); + return proto === Object.prototype || proto === null; +} + +function text(value: unknown, max: number): string { + return typeof value === 'string' ? value.trim().slice(0, max) : ''; +} + +function controlOf(value: unknown): ControlKind | undefined { + return CONTROL_KINDS.find((kind) => kind === value); +} + +const VALUE_CONTROLS: readonly ControlKind[] = [ + 'text', + 'textarea', + 'date', + 'select', +]; +const OPTION_CONTROLS: readonly ControlKind[] = ['select', 'choice_group']; + +// `cut` is true when the list is not trustworthy as a whole: it was cut at +// the cap, or a non-string entry was dropped (which shifts later indexes). +function toOptions(raw: unknown): { options: string[]; cut: boolean } { + const options: string[] = []; + if (!Array.isArray(raw)) return { options, cut: false }; + let dropped = false; + for (const entry of raw as unknown[]) { + if (typeof entry !== 'string') { + dropped = true; + continue; + } + if (options.length === MAX_OPTIONS) return { options, cut: true }; + options.push(text(entry, MAX_LABEL)); + } + return { options, cut: dropped }; +} + +function toChecked(raw: unknown, optionCount: number): number[] { + if (!Array.isArray(raw)) return []; + const checked: number[] = []; + for (const entry of raw as unknown[]) { + if ( + typeof entry === 'number' && + Number.isInteger(entry) && + entry >= 0 && + entry < optionCount && + !checked.includes(entry) + ) + checked.push(entry); + } + return checked; +} + +function toField(raw: unknown): ScannedField | undefined { + if (!isPlainObject(raw)) return undefined; + const ref = raw.ref; + if (typeof ref !== 'number' || !Number.isSafeInteger(ref) || ref < 0) + return undefined; + const control = controlOf(raw.control); + if (control === undefined) return undefined; + const usesOptions = OPTION_CONTROLS.includes(control); + const { options, cut } = usesOptions + ? toOptions(raw.options) + : { options: [], cut: false }; + return { + ref, + control, + label: text(raw.label, MAX_LABEL), + autocomplete: text(raw.autocomplete, MAX_AUTOCOMPLETE).toLowerCase(), + required: raw.required === true, + value: VALUE_CONTROLS.includes(control) ? text(raw.value, MAX_VALUE) : '', + options, + checked: + control === 'choice_group' ? toChecked(raw.checked, options.length) : [], + multiple: usesOptions && raw.multiple === true, + optionsTruncated: usesOptions && (cut || raw.optionsTruncated === true), + }; +} + +function toFrames(raw: unknown): string[] { + if (!Array.isArray(raw)) return []; + const frames: string[] = []; + for (const entry of raw as unknown[]) { + if (frames.length === MAX_FRAMES) break; + if (typeof entry === 'string' && entry.startsWith('https://')) + frames.push(entry.slice(0, MAX_FRAME_SRC)); + } + return frames; +} + +export function toFormScan(raw: unknown): FormScan | undefined { + if (!isPlainObject(raw) || !Array.isArray(raw.fields)) return undefined; + const fields: ScannedField[] = []; + const seen = new Set(); + let cut = false; + for (const entry of raw.fields as unknown[]) { + const field = toField(entry); + if (field === undefined || seen.has(field.ref)) continue; + if (fields.length === MAX_FIELDS) { + cut = true; + break; + } + seen.add(field.ref); + fields.push(field); + } + return { + fields, + frames: toFrames(raw.frames), + truncated: cut || raw.truncated === true, + }; +} + +function outcomeOf(value: unknown): WriteOutcome { + return WRITE_OUTCOMES.find((outcome) => outcome === value) ?? 'failed'; +} + +export function toApplyResult(raw: unknown): ApplyResult | undefined { + if (!isPlainObject(raw) || !Array.isArray(raw.outcomes)) return undefined; + const scan = toFormScan(raw.scan); + if (scan === undefined) return undefined; + const outcomes: WriteReport[] = []; + for (const entry of raw.outcomes as unknown[]) { + if (outcomes.length === MAX_FIELDS) break; + if ( + !isPlainObject(entry) || + typeof entry.ref !== 'number' || + !Number.isSafeInteger(entry.ref) || + entry.ref < 0 + ) + continue; + outcomes.push({ ref: entry.ref, outcome: outcomeOf(entry.outcome) }); + } + return { outcomes, scan }; +} diff --git a/core/src/profile.test.ts b/core/src/profile.test.ts index 270d467..f75d43b 100644 --- a/core/src/profile.test.ts +++ b/core/src/profile.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { profileValues, setProfileFieldOps } from './profile'; +import { PROFILE_FIELDS, profileValues, setProfileFieldOps } from './profile'; import { emptySnapshot } from './schema'; import type { Deps, ProfileField, Snapshot } from './types'; @@ -219,7 +219,69 @@ describe('setProfileFieldOps', () => { }); }); +describe('PROFILE_FIELDS', () => { + it('has fourteen fields in order', () => { + expect(PROFILE_FIELDS.map((f) => f.key)).toEqual([ + 'full_name', + 'first_name', + 'last_name', + 'email', + 'phone', + 'address_line1', + 'address_line2', + 'city', + 'region', + 'postal_code', + 'country', + 'linkedin', + 'github', + 'website', + ]); + }); + + it('saves last name with its label', () => { + expect( + setProfileFieldOps(emptySnapshot(), 'last_name', 'Example', deps()), + ).toEqual([ + { + kind: 'put', + store: 'profileFields', + record: { + id: 'new1', + createdAt: NOW, + key: 'last_name', + label: 'Last name', + value: 'Example', + }, + }, + ]); + }); +}); + describe('profileValues', () => { + it('reads first and last name', () => { + const data = withFields( + { + id: 'p1', + createdAt: OLD, + key: 'first_name', + label: 'First name', + value: 'Sam', + }, + { + id: 'p2', + createdAt: OLD, + key: 'last_name', + label: 'Last name', + value: 'Example', + }, + ); + expect(profileValues(data)).toEqual({ + first_name: 'Sam', + last_name: 'Example', + }); + }); + it('reads one value per known key', () => { const data = withFields( { diff --git a/core/src/profile.ts b/core/src/profile.ts index f92a3d7..93326e1 100644 --- a/core/src/profile.ts +++ b/core/src/profile.ts @@ -3,6 +3,8 @@ import type { Deps, Id, Snapshot } from './types'; export const PROFILE_FIELDS = [ { key: 'full_name', label: 'Full name' }, + { key: 'first_name', label: 'First name' }, + { key: 'last_name', label: 'Last name' }, { key: 'email', label: 'Email' }, { key: 'phone', label: 'Phone' }, { key: 'address_line1', label: 'Address line 1' }, diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5ad1249..fde58ba 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -5,6 +5,8 @@ Countersign is a Manifest V3 Firefox extension built with WXT and Preact. It sto ## The core and the shell - `core/` holds the rules: types, status logic, dates, application operations, list filtering, answers, documents, export, validation and migrations. It is plain TypeScript. +- `core/src/fill/` holds the matching and planning for the form filler. It has no DOM. +- `shell/fill/` holds the page script (`shell/fill/page/`), the injector (`shell/fill/inject.ts`) and the controller (`shell/fill/controller.ts`). - `shell/` and `entrypoints/` hold everything that touches the browser: IndexedDB, `storage.local`, file saving, the Preact UI and the toolbar button. The split is enforced three ways: @@ -59,11 +61,19 @@ An in-memory repository (`core/src/memory-repository.ts`) is used in tests. The ## The privacy guard -Three parts keep "no network, nothing reads a page until you click" true. The local automatic backup check is the one thing that runs without a click. +Four parts keep "no network, nothing reads or touches a page until you click, never submits" true. The local automatic backup check is the one thing that runs without a click. 1. **Lint rules** (`eslint.config.js`) ban network APIs in source and ban `downloads` outside `shell/files/download.ts`. 2. **Built-output scan** (`guard/scan.ts`, run by `guard/build.test.ts`) looks for network tokens in every built `.js` and `.html` file. A small allowlist (`guard/allowlist.json`) explains known harmless matches, and a test fails if an entry goes stale. 3. **Manifest and CSP checks** (`guard/build.test.ts`) assert that permissions stay within a short allowlist, no host access, no content scripts, no remote resources in built pages, and the exact Content Security Policy from `wxt.config.ts`. +4. **Fill guard** keeps filling click-only and submit-free: + - A lint block in `eslint.config.js` for `shell/fill/page/**` and `entrypoints/fill.ts` bans calls to submit, requestSubmit, click, focus, blur, scrollIntoView and dispatchEvent, constructing events, console, storage, postMessage and cookie access, and the common ways of changing the page, such as creating, removing or moving elements, setting attributes, text, classes, styles or HTML, adding event listeners, resetting a form and `Object.assign`. It is a denylist, so it does not prove that no other change is possible. Only `shell/fill/page/events.ts` may dispatch an event, and only a plain `input` or `change`. + - Outside tests, `eslint.config.js` checks that only `shell/fill/inject.ts` and `entrypoints/fill.ts` write the fill script's name (`fill.js`) or its hook's name (`__countersignFill`) as a literal. This is a check on literal names, not proof that no other file can inject the script. Outside tests, import rules (`no-restricted-imports` plus `import()` selectors, and `@typescript-eslint/no-restricted-imports`) let only `shell/fill/controller.ts` import the injector and only `shell/ui/Popup.tsx` import the controller by value; type imports are free for both. A syntax rule lets only `shell/ui/FillSection.tsx` read the controller's `fill()` (the `core/` folder is exempt because `core/` cannot import the controller). + - The built-output scan (`guard/scan.ts`, run by `guard/build.test.ts`) looks for `submit`, `requestSubmit`, `click`, `KeyboardEvent`, `MouseEvent`, `PointerEvent` and `SubmitEvent` in the built `fill.js`. + - The behaviour test `shell/fill/page-apply.test.ts` fills a fixture form and sees no submit, no new element and no new attribute. + - These lint rules catch ordinary code by name and path. They do not stop code written to get around them, such as a path like `..//inject` or a name built from pieces. Code review is the backstop for that. + - The scan skips text, textarea and select fields it judges hidden (`shell/fill/page/scan.ts`): zero opacity, clipped, unrendered, collapsed or cut off by a clipping parent, or off the page. This check is best-effort. It does not see a field covered by another element, a parent a few pixels wide, or a fixed field below the bottom of the window. The review list is the guard: every field that will be filled is shown before you click Fill. + - The controller test `shell/fill/controller.test.ts` shows that scanning never applies, and `shell/ui/fill-section-source.test.ts` shows that `fill()` is called only from the Fill button's click handler. ## Look and feel diff --git a/entrypoints/fill.ts b/entrypoints/fill.ts new file mode 100644 index 0000000..9ce0db8 --- /dev/null +++ b/entrypoints/fill.ts @@ -0,0 +1,15 @@ +import { defineUnlistedScript } from 'wxt/utils/define-unlisted-script'; +import type { ApplyResult } from '../core/src/fill/types'; +import { createSession } from '../shell/fill/page/session'; + +interface FillHook { + apply: (writes: unknown) => ApplyResult; +} + +export default defineUnlistedScript(() => { + const session = createSession(document); + (globalThis as { __countersignFill?: FillHook }).__countersignFill = { + apply: (writes: unknown) => session.apply(writes), + }; + return session.scan(); +}); diff --git a/eslint.config.js b/eslint.config.js index 94d89fd..ff19500 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -65,14 +65,16 @@ const navigationSyntax = [ `AssignmentExpression[left.property.name='href'][left.object.property.name='location'][left.object.object.name=${GLOBAL_OBJECTS}]`, `AssignmentExpression[left.property.value='href'][left.object.property.name='location'][left.object.object.name=${GLOBAL_OBJECTS}]`, ].map((selector) => ({ selector, message: NAVIGATION_MESSAGE })); -// Reading tabs and injecting scripts are confined to two shell files. -const TABS_MESSAGE = 'Use tabs only in open-dashboard.ts or capture/inject.ts.'; +// Reading tabs and injecting scripts are confined to three shell files. +const TABS_MESSAGE = + 'Use tabs only in open-dashboard.ts, capture/inject.ts or fill/inject.ts.'; const tabsSyntax = [ "MemberExpression[property.name='tabs']", "MemberExpression[property.value='tabs']", "Property[key.name='tabs']", ].map((selector) => ({ selector, message: TABS_MESSAGE })); -const SCRIPTING_MESSAGE = 'Inject only through shell/capture/inject.ts.'; +const SCRIPTING_MESSAGE = + 'Inject only through shell/capture/inject.ts or shell/fill/inject.ts.'; const scriptingSyntax = [ "MemberExpression[property.name='scripting']", "MemberExpression[property.value='scripting']", @@ -84,6 +86,209 @@ const STYLE_MESSAGE = 'No inline styles: the CSP blocks them. Use a class.'; const styleSyntax = [ { selector: "JSXAttribute[name.name='style']", message: STYLE_MESSAGE }, ]; +// no-restricted-imports cannot see import(), so a dynamic import of the fill +// apply call is caught here. It applies to every file, controller.ts included. +const applyImportSyntax = [ + { + selector: + 'ImportExpression[source.value=/(^|\\/)fill\\/inject(\\.[jt]s)?$|^(\\.\\.?\\/)+inject(\\.[jt]s)?$/]', + message: 'Only shell/fill/controller.ts may import the fill apply call.', + }, + { + selector: + 'ImportExpression[source.value=/(^|\\/)fill\\/controller(\\.[jt]s)?$|^(\\.\\.?\\/)+controller(\\.[jt]s)?$/]', + message: 'Only shell/ui/Popup.tsx may import the fill controller.', + }, + // A template literal or variable has no source.value to match, so refuse it. + { + selector: "ImportExpression[source.type!='Literal']", + message: 'import() must use a plain string.', + }, +]; +// The fill page script runs inside the user's page. It reads fields and sets +// their values, nothing else. Each part below is a named list so that +// shell/fill/page/events.ts can drop exactly the dispatch and constructor +// selectors it needs to change. +const FILL_PAGE_MESSAGE = + 'The fill page script only reads fields and sets their values.'; +/** @param {string[]} names */ +const callNames = (names) => `/^(${names.join('|')})$/`; +/** @param {string[]} names */ +const callSelectors = (names) => [ + `CallExpression[callee.property.name=${callNames(names)}]`, + `CallExpression[callee.property.value=${callNames(names)}]`, +]; +/** @param {string[]} names */ +const memberSelectors = (names) => [ + `MemberExpression[property.name=${callNames(names)}]`, + `MemberExpression[property.value=${callNames(names)}]`, +]; +/** @param {string[]} selectors */ +const asFillSyntax = (selectors) => + selectors.map((selector) => ({ selector, message: FILL_PAGE_MESSAGE })); +const fillCallSyntax = asFillSyntax( + callSelectors(['createEvent', 'execCommand']), +); +// Plain member access is banned, not just calls, so el.focus.call(el), +// Reflect.apply(el.focus, ...) and const f = el.scrollIntoView are caught too. +const fillActionSyntax = asFillSyntax( + memberSelectors([ + 'submit', + 'requestSubmit', + 'click', + 'focus', + 'blur', + 'scrollIntoView', + ]), +); +const fillDispatchSyntax = asFillSyntax(memberSelectors(['dispatchEvent'])); +/** @param {string} pattern */ +const eventCtorSelectors = (pattern) => [ + `NewExpression[callee.name=${pattern}]`, + `NewExpression[callee.property.name=${pattern}]`, + `NewExpression[callee.property.value=${pattern}]`, +]; +const fillEventCtorSyntax = asFillSyntax(eventCtorSelectors('/Event$/')); +// events.ts: every name longer than Event stays banned, and a plain Event is +// banned unless its first argument is the literal 'input' or 'change'. +const notInputOrChange = + ":not([arguments.0.type='Literal'][arguments.0.value=/^(input|change)$/])"; +const fillPlainEventCtorSyntax = asFillSyntax([ + ...eventCtorSelectors('/.+Event$/'), + `NewExpression[callee.name='Event']${notInputOrChange}`, + `NewExpression[callee.property.name='Event']${notInputOrChange}`, + `NewExpression[callee.property.value='Event']${notInputOrChange}`, +]); +const fillDomSyntax = asFillSyntax( + memberSelectors([ + 'createElement', + 'setAttribute', + 'removeAttribute', + 'toggleAttribute', + 'dataset', + 'innerHTML', + 'outerHTML', + 'insertAdjacentHTML', + 'append', + 'appendChild', + 'setAttributeNS', + 'removeAttributeNS', + 'setAttributeNode', + 'removeAttributeNode', + 'insertAdjacentElement', + 'insertBefore', + 'removeChild', + 'replaceChild', + 'replaceChildren', + 'replaceWith', + 'prepend', + 'before', + 'after', + 'remove', + 'reset', + 'addEventListener', + 'removeEventListener', + 'attachShadow', + 'insertAdjacentText', + 'setHTMLUnsafe', + 'write', + 'writeln', + 'normalize', + ]), +); +// classList and style are readable, but changing them is not. +/** + * @param {string} object + * @param {string[]} names + */ +const objectCallSelectors = (object, names) => [ + `CallExpression[callee.object.property.name='${object}'][callee.property.name=${callNames(names)}]`, + `CallExpression[callee.object.property.value='${object}'][callee.property.name=${callNames(names)}]`, + `CallExpression[callee.object.property.name='${object}'][callee.property.value=${callNames(names)}]`, + `CallExpression[callee.object.property.value='${object}'][callee.property.value=${callNames(names)}]`, +]; +const ASSIGNED = [ + 'className', + 'id', + 'textContent', + 'innerText', + 'outerText', + 'style', + 'cssText', + 'classList', + 'hidden', + 'title', + 'disabled', + 'slot', + 'nodeValue', + 'data', + 'lang', +]; +// `.add` and `.toggle` are banned on classList only: scan.ts and label.ts call +// Set.add. +const fillMutationSyntax = asFillSyntax([ + "CallExpression[callee.object.name='Object'][callee.property.name='assign']", + "CallExpression[callee.object.name='Object'][callee.property.value='assign']", + ...objectCallSelectors('classList', ['add', 'remove', 'toggle', 'replace']), + ...objectCallSelectors('style', ['setProperty', 'removeProperty']), + `AssignmentExpression[left.type='MemberExpression'][left.property.name=${callNames(ASSIGNED)}]`, + `AssignmentExpression[left.type='MemberExpression'][left.property.value=${callNames(ASSIGNED)}]`, + 'AssignmentExpression[left.object.property.name=/^(style|classList)$/]', + 'AssignmentExpression[left.object.property.value=/^(style|classList)$/]', +]); +// Only the injector and the page script's entry point may name the fill script +// or its hook, so no other file can inject or call it. +const FILL_NAME_MESSAGE = + 'Only shell/fill/inject.ts and entrypoints/fill.ts may name the fill script or its hook.'; +const FILL_NAME = '/fill\\.js|__countersignFill/'; +const fillNameSyntax = [ + `Literal[value=${FILL_NAME}]`, + `TemplateElement[value.cooked=${FILL_NAME}]`, + "Identifier[name='__countersignFill']", +].map((selector) => ({ selector, message: FILL_NAME_MESSAGE })); +// fill() writes into the page, so only the Fill button's click handler in +// FillSection.tsx may reach it. The selectors ban reading `.fill` in any form +// (call, reference, computed key, optional call) and destructuring it. +const FILL_CALL_MESSAGE = + 'Only the Fill button in shell/ui/FillSection.tsx may read fill() from the controller.'; +const fillCallerSyntax = [ + "MemberExpression[property.name='fill']", + "MemberExpression[property.value='fill']", + "ObjectPattern > Property[key.name='fill']", + "ObjectPattern > Property[key.value='fill']", + // A template key with no substitutions: ctrl[`fill`] and { [`fill`]: f }. + "MemberExpression[property.type='TemplateLiteral'][property.quasis.0.value.cooked='fill']", + "ObjectPattern > Property[key.type='TemplateLiteral'][key.quasis.0.value.cooked='fill']", +].map((selector) => ({ selector, message: FILL_CALL_MESSAGE })); +// Module-wide import bans. The apply call is the controller's alone, and the +// controller is Popup.tsx's alone. Type imports stay free. +const injectImport = { + regex: '(^|/)fill/inject(\\.[jt]s)?$', + allowTypeImports: true, + message: 'Only shell/fill/controller.ts may import shell/fill/inject.ts.', +}; +const siblingInjectImport = { + ...injectImport, + regex: '^(\\.\\.?/)+inject(\\.[jt]s)?$', +}; +const controllerImport = { + regex: '(^|/)fill/controller(\\.[jt]s)?$|^\\./controller(\\.[jt]s)?$', + allowTypeImports: true, + message: 'Only shell/ui/Popup.tsx may import the fill controller.', +}; +const siblingControllerImport = { + ...controllerImport, + regex: '^(\\.\\.?/)+controller(\\.[jt]s)?$', +}; +/** @param {object[]} patterns */ +const restrictImports = (...patterns) => ['error', { patterns }]; +const fillLeakSyntax = asFillSyntax([ + `Identifier[name=${callNames(['console', 'localStorage', 'sessionStorage', 'postMessage'])}]`, + // The Identifier selector already catches these by name, so a computed + // string is the only member form left to add. + `MemberExpression[property.value=${callNames(['console', 'localStorage', 'sessionStorage', 'postMessage'])}]`, + ...memberSelectors(['cookie']), +]); export default defineConfig( { @@ -102,13 +307,37 @@ export default defineConfig( rules: { 'no-restricted-globals': ['error', ...networkGlobals], 'no-restricted-properties': ['error', ...networkProperties], + // The apply call writes into the user's page, so only the controller + // (and the injector's own test) may import it. + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + regex: '(^|/)fill/inject(\\.[jt]s)?$|^\\./inject(\\.[jt]s)?$', + importNames: ['applyToPage', 'browserFillApi'], + message: + 'Only shell/fill/controller.ts may import the fill apply call.', + }, + ], + }, + ], + // Value imports of the fill controller are Popup.tsx's alone; its + // default injector writes to the page. Type imports stay free. + '@typescript-eslint/no-restricted-imports': restrictImports( + controllerImport, + injectImport, + ), 'no-restricted-syntax': [ 'error', ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, ...tabsSyntax, ...scriptingSyntax, + ...fillNameSyntax, ], }, }, @@ -122,8 +351,11 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, ...tabsSyntax, ...scriptingSyntax, + ...fillNameSyntax, ...styleSyntax, ], }, @@ -138,8 +370,11 @@ export default defineConfig( 'error', ...networkSyntax, ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, ...tabsSyntax, ...scriptingSyntax, + ...fillNameSyntax, ], }, }, @@ -152,11 +387,15 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, ...scriptingSyntax, + ...fillNameSyntax, ], }, }, - // capture/inject.ts may use both tabs and scripting. + // The two injectors may use both tabs and scripting. Only the fill injector + // may name the fill script and its hook. { files: ['shell/capture/inject.ts'], rules: { @@ -165,6 +404,195 @@ export default defineConfig( ...networkSyntax, ...downloadSyntax, ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, + ...fillNameSyntax, + ], + }, + }, + { + files: ['shell/fill/inject.ts'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, + ], + }, + }, + // Inside shell/fill/, a sibling './inject' is the fill injector too. + { + files: ['shell/fill/**'], + rules: { + '@typescript-eslint/no-restricted-imports': restrictImports( + controllerImport, + injectImport, + siblingInjectImport, + siblingControllerImport, + ), + }, + }, + // The controller and the injector's test may import the injector. + { + files: ['shell/fill/controller.ts', 'shell/fill/inject.test.ts'], + rules: { + 'no-restricted-imports': 'off', + '@typescript-eslint/no-restricted-imports': restrictImports( + controllerImport, + siblingControllerImport, + ), + }, + }, + // Popup.tsx and the controller's own test may import the controller. + { + files: ['shell/ui/Popup.tsx'], + rules: { + '@typescript-eslint/no-restricted-imports': restrictImports(injectImport), + }, + }, + { + files: ['shell/fill/controller.test.ts'], + rules: { + '@typescript-eslint/no-restricted-imports': restrictImports( + injectImport, + siblingInjectImport, + ), + }, + }, + // The fill page script may only read fields and set their values. + { + files: ['shell/fill/page/**'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillNameSyntax, + ...fillCallSyntax, + ...fillActionSyntax, + ...fillDispatchSyntax, + ...fillEventCtorSyntax, + ...fillDomSyntax, + ...fillMutationSyntax, + ...fillLeakSyntax, + ], + }, + }, + // entrypoints/fill.ts is the page script's entry point, so it names the hook. + { + files: ['entrypoints/fill.ts'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillCallSyntax, + ...fillActionSyntax, + ...fillDispatchSyntax, + ...fillEventCtorSyntax, + ...fillDomSyntax, + ...fillMutationSyntax, + ...fillLeakSyntax, + ], + }, + }, + // events.ts alone may dispatch an event, and only a plain Event. + { + files: ['shell/fill/page/events.ts'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...fillCallerSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillCallSyntax, + ...fillActionSyntax, + ...fillNameSyntax, + ...fillPlainEventCtorSyntax, + ...fillDomSyntax, + ...fillMutationSyntax, + ...fillLeakSyntax, + ], + }, + }, + // The guard tests and this file name the fill script to test and ban it. + { + files: ['guard/**', 'eslint.config.js'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ], + }, + }, + // guard/scan.ts is not a test, so it may not name the fill script either. + { + files: ['guard/scan.ts'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillNameSyntax, + ], + }, + }, + // fill() is read only by FillSection.tsx. The controller defines it and its + // test calls it. These blocks keep every other selector for those files. + { + files: ['shell/fill/controller.ts', 'shell/fill/controller.test.ts'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillNameSyntax, + ], + }, + }, + { + files: ['shell/ui/FillSection.tsx'], + rules: { + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillNameSyntax, + ...styleSyntax, ], }, }, @@ -172,6 +600,17 @@ export default defineConfig( { files: ['core/**'], rules: { + // core/ cannot reach the controller, and Array.fill is legitimate here. + 'no-restricted-syntax': [ + 'error', + ...networkSyntax, + ...downloadSyntax, + ...navigationSyntax, + ...applyImportSyntax, + ...tabsSyntax, + ...scriptingSyntax, + ...fillNameSyntax, + ], 'no-restricted-imports': [ 'error', { diff --git a/guard/build.test.ts b/guard/build.test.ts index d418a18..a1401f0 100644 --- a/guard/build.test.ts +++ b/guard/build.test.ts @@ -5,15 +5,18 @@ import allowlist from './allowlist.json'; import { assetExists, cssProblems, + FILL_TOKENS, fontFamiliesIn, parseCsp, scanDirectory, scanDirectoryWithUsage, + scanTextWithUsage, type AllowEntry, } from './scan'; const OUT = resolve(import.meta.dirname, '..', '.output', 'firefox-mv3'); const MANIFEST = join(OUT, 'manifest.json'); +const FILL = join(OUT, 'fill.js'); if (!existsSync(MANIFEST)) { throw new Error( @@ -130,13 +133,35 @@ describe('built extension', () => { it('ships no network calls', () => { expect(scanDirectory(OUT, allowlist as AllowEntry[])).toEqual([]); }); + it('ships the fill script only as a file', () => { + expect(existsSync(FILL)).toBe(true); + expect(manifest.content_scripts).toBeUndefined(); + expect(manifest.web_accessible_resources).toBeUndefined(); + }); + it('the fill script has no submit, click or key words', () => { + const entries = allowlist as AllowEntry[]; + const { hits } = scanTextWithUsage( + FILL, + readFileSync(FILL, 'utf8'), + entries, + FILL_TOKENS, + ); + expect(hits).toEqual([]); + }); it('has no stale allowlist entries', () => { const entries = allowlist as AllowEntry[]; - const { usedEntries } = scanDirectoryWithUsage(OUT, entries); + const network = scanDirectoryWithUsage(OUT, entries); + const fill = scanTextWithUsage( + FILL, + readFileSync(FILL, 'utf8'), + entries, + FILL_TOKENS, + ); entries.forEach((entry, i) => { - expect(usedEntries.has(i), `unused allowlist entry: ${entry.near}`).toBe( - true, - ); + expect( + network.usedEntries.has(i) || fill.usedEntries.has(i), + `unused allowlist entry: ${entry.near}`, + ).toBe(true); }); }); it('ships only local CSS assets', () => { diff --git a/guard/scan.ts b/guard/scan.ts index f80bbcc..f02143e 100644 --- a/guard/scan.ts +++ b/guard/scan.ts @@ -11,6 +11,17 @@ export const NETWORK_TOKENS: readonly string[] = [ 'RTCPeerConnection', ]; +/** Words the built fill script must not contain (it only reads and sets values). */ +export const FILL_TOKENS: readonly string[] = [ + 'submit', + 'requestSubmit', + 'click', + 'KeyboardEvent', + 'MouseEvent', + 'PointerEvent', + 'SubmitEvent', +]; + export interface AllowEntry { token: string; near: string; @@ -41,7 +52,10 @@ export function validateAllowlist(allow: readonly AllowEntry[]): string[] { const problems: string[] = []; allow.forEach((entry, i) => { const label = `allowlist[${i}]`; - if (!NETWORK_TOKENS.includes(entry.token)) { + if ( + !NETWORK_TOKENS.includes(entry.token) && + !FILL_TOKENS.includes(entry.token) + ) { problems.push(`${label}: unknown token "${entry.token}"`); return; } @@ -64,6 +78,7 @@ export function scanTextWithUsage( file: string, text: string, allow: readonly AllowEntry[], + tokens: readonly string[] = NETWORK_TOKENS, ): ScanResult { const problems = validateAllowlist(allow); if (problems.length > 0) { @@ -71,7 +86,7 @@ export function scanTextWithUsage( } const hits: Hit[] = []; const usedEntries = new Set(); - for (const token of NETWORK_TOKENS) { + for (const token of tokens) { for (const match of text.matchAll(tokenPattern(token))) { const start = match.index; const end = start + token.length; diff --git a/guard/source-rules.test.ts b/guard/source-rules.test.ts index 22bb473..cc0b4d7 100644 --- a/guard/source-rules.test.ts +++ b/guard/source-rules.test.ts @@ -5,10 +5,12 @@ import { describe, expect, it } from 'vitest'; import { assetExists, cssProblems, + FILL_TOKENS, fontFamiliesIn, NETWORK_TOKENS, parseCsp, scanText, + scanTextWithUsage, validateAllowlist, } from './scan'; @@ -57,6 +59,63 @@ describe('scanText', () => { scanText('a.js', 'x', [{ token: 'fetch', near: '', reason: 'r' }]), ).toThrow(/allowlist/i); }); + it('finds each fill token as a whole word', () => { + for (const token of FILL_TOKENS) { + expect( + scanTextWithUsage('fill.js', `x.${token}()`, [], FILL_TOKENS).hits, + ).toHaveLength(1); + } + }); + it('ignores longer words', () => { + expect( + scanTextWithUsage( + 'fill.js', + 'submitted=1;onclick;clicked()', + [], + FILL_TOKENS, + ).hits, + ).toEqual([]); + }); + it('the network scan ignores fill words', () => { + expect(scanText('a.js', 'form.submit()', [])).toEqual([]); + }); + it('an allowlist entry may name a fill token', () => { + const allow = [ + { token: 'click', near: 'label:"click to expand"', reason: 'test' }, + ]; + expect(validateAllowlist(allow)).toEqual([]); + const text = 'x={label:"click to expand"};y.click()'; + const result = scanTextWithUsage('fill.js', text, allow, FILL_TOKENS); + expect(result.hits).toHaveLength(1); + expect(result.hits[0]?.context).toContain('y.click()'); + expect( + scanTextWithUsage( + 'fill.js', + 'label:"click to expand";fetch(1)', + allow, + FILL_TOKENS, + ).hits, + ).toEqual([]); + }); + it('a fill entry never hides a network hit, nor a network entry a fill hit', () => { + const fillEntry = [ + { token: 'click', near: 'label:"click to expand"', reason: 'test' }, + ]; + expect( + scanText('a.js', 'label:"click to expand";fetch(1)', fillEntry), + ).toHaveLength(1); + const netEntry = [ + { token: 'fetch', near: 'errorMessage="fetch failed"', reason: 'test' }, + ]; + expect( + scanTextWithUsage( + 'fill.js', + 'errorMessage="fetch failed";x.click()', + netEntry, + FILL_TOKENS, + ).hits, + ).toHaveLength(1); + }); }); describe('validateAllowlist', () => { @@ -254,10 +313,12 @@ describe('download guard', { timeout: 60_000 }, () => { describe('navigation and injection guard', { timeout: 60_000 }, () => { const navMessage = 'Countersign never navigates away or opens windows.'; const tabsMessage = - 'Use tabs only in open-dashboard.ts or capture/inject.ts.'; - const scriptingMessage = 'Inject only through shell/capture/inject.ts.'; + 'Use tabs only in open-dashboard.ts, capture/inject.ts or fill/inject.ts.'; + const scriptingMessage = + 'Inject only through shell/capture/inject.ts or shell/fill/inject.ts.'; const dashboard = 'shell/open-dashboard.ts'; const inject = 'shell/capture/inject.ts'; + const fillInject = 'shell/fill/inject.ts'; const save = "browser.downloads.download({ url: 'blob:x' });"; // Probe paths such as shell/ui/x.tsx and shell/capture/inject.ts do not exist // on disk, so type-aware parsing would fail. Switch type information off; @@ -321,27 +382,38 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { const found = await syntaxMessages(code, 'shell/ui/x.tsx'); expect(found.some((m) => m.message === tabsMessage)).toBe(true); }); - it.each([dashboard, inject])('allows tabs access in %s', async (file) => { - const found = await syntaxMessages('browser.tabs.query({});', file); - expect(found.some((m) => m.message === tabsMessage)).toBe(false); - }); + it.each([dashboard, inject, fillInject])( + 'allows tabs access in %s', + async (file) => { + const found = await syntaxMessages('browser.tabs.query({});', file); + expect(found.some((m) => m.message === tabsMessage)).toBe(false); + }, + ); it.each([ 'browser.scripting.executeScript({});', "browser['scripting'].executeScript({});", 'const { scripting } = browser;', ])('rejects scripting access %s outside inject.ts', async (code) => { - for (const file of ['shell/ui/x.tsx', dashboard]) { + for (const file of [ + 'shell/ui/x.tsx', + dashboard, + 'shell/fill/controller.ts', + 'shell/fill/page/scan.ts', + ]) { const found = await syntaxMessages(code, file); expect(found.some((m) => m.message === scriptingMessage)).toBe(true); } }); - it('allows scripting access in inject.ts', async () => { - const found = await syntaxMessages( - 'browser.scripting.executeScript({});', - inject, - ); - expect(found.some((m) => m.message === scriptingMessage)).toBe(false); - }); + it.each([inject, fillInject])( + 'allows scripting access in %s', + async (file) => { + const found = await syntaxMessages( + 'browser.scripting.executeScript({});', + file, + ); + expect(found.some((m) => m.message === scriptingMessage)).toBe(false); + }, + ); it('rejects tabs access in the download wrapper', async () => { const found = await syntaxMessages( 'browser.tabs.query({});', @@ -349,7 +421,7 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { ); expect(found.some((m) => m.message === tabsMessage)).toBe(true); }); - it.each([dashboard, inject])( + it.each([dashboard, inject, fillInject])( 'keeps the download, network and navigation rules in %s', async (file) => { for (const [code, message] of [ @@ -372,6 +444,258 @@ describe('navigation and injection guard', { timeout: 60_000 }, () => { ); expect(found.some((m) => m.message === navMessage)).toBe(true); }); + it.each([ + [ + "import { applyToPage } from '../fill/inject';", + 'shell/ui/FillSection.tsx', + ], + ["import { applyToPage } from './inject';", 'shell/fill/other.ts'], + ["import { browserFillApi } from '../fill/inject';", 'shell/ui/Popup.tsx'], + ["import * as inject from '../fill/inject';", 'shell/ui/x.tsx'], + ["export { applyToPage } from './inject';", 'shell/fill/index.ts'], + ["export * from './inject';", 'shell/fill/index.ts'], + ["import { applyToPage } from '../fill/inject.js';", 'shell/ui/x.tsx'], + ])('rejects the apply import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === 'no-restricted-imports')).toBe(true); + }); + it.each([ + ["const m = await import('./inject');", 'shell/fill/other.ts'], + ["const m = await import('./inject');", 'shell/fill/controller.ts'], + ["const m = await import('../fill/inject');", 'shell/ui/x.tsx'], + ])('rejects the dynamic import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect( + found.some( + (m) => + m.message === + 'Only shell/fill/controller.ts may import the fill apply call.', + ), + ).toBe(true); + }); + it.each([ + ["import { applyToPage } from './inject';", 'shell/fill/controller.ts'], + ["import { applyToPage } from './inject';", 'shell/fill/inject.test.ts'], + ["import type { ScanOutcome } from '../fill/inject';", 'shell/ui/x.tsx'], + ["import type { ScanOutcome } from './inject';", 'shell/fill/other.ts'], + ])('allows the import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === 'no-restricted-imports')).toBe(false); + }); + it('still rejects shell imports in core/', async () => { + const found = await syntaxMessages( + "import { x } from '../../shell/fill/inject';", + 'core/src/status.ts', + ); + expect(found.some((m) => m.ruleId === 'no-restricted-imports')).toBe(true); + }); + const controllerRule = '@typescript-eslint/no-restricted-imports'; + it.each([ + [ + "import { createFillController } from '../fill/controller';", + 'shell/ui/FillSection.tsx', + ], + [ + "import { createFillController } from '../../shell/fill/controller';", + 'entrypoints/background.ts', + ], + [ + "import { createFillController } from './controller.js';", + 'shell/fill/other.ts', + ], + ["export * from './controller';", 'shell/fill/index.ts'], + ])('rejects the controller import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === controllerRule)).toBe(true); + }); + it('rejects a dynamic import of the controller', async () => { + const found = await syntaxMessages( + "const m = await import('../fill/controller');", + 'entrypoints/background.ts', + ); + expect( + found.some( + (m) => + m.message === + 'Only shell/ui/Popup.tsx may import the fill controller.', + ), + ).toBe(true); + }); + it.each([ + [ + "import type { FillController } from '../fill/controller';", + 'shell/ui/FillSection.tsx', + ], + [ + "import { type FillState } from '../fill/controller';", + 'shell/ui/fill-view.ts', + ], + [ + "import { createFillController } from '../fill/controller';", + 'shell/ui/Popup.tsx', + ], + [ + "import { createFillController } from './controller';", + 'shell/fill/controller.test.ts', + ], + ])('allows the controller import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === controllerRule)).toBe(false); + }); + it.each([ + [ + "import { scanPage } from '../shell/fill/inject';", + 'entrypoints/background.ts', + ], + ["import { scanPage } from '../fill/inject';", 'shell/capture/inject.ts'], + ["import { scanPage } from './inject';", 'shell/fill/other.ts'], + ["import { FILL_TIMEOUT_MS } from '../fill/inject';", 'shell/ui/Popup.tsx'], + ["import { scanPage } from './inject';", 'shell/fill/controller.test.ts'], + ["import { scanPage } from '../inject';", 'shell/fill/page/x.ts'], + ["import { scanPage } from '../../inject.js';", 'shell/fill/page/y/x.ts'], + ["import { scanPage } from '../../fill/inject';", 'shell/ui/x.ts'], + ["import { scanPage } from '../shell/fill/inject';", 'entrypoints/x.ts'], + ])('rejects the injector import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === controllerRule)).toBe(true); + }); + it.each([ + ["import { scanPage } from './inject';", 'shell/fill/controller.ts'], + ["import { scanPage } from './inject';", 'shell/fill/inject.test.ts'], + [ + "import type { ScanOutcome } from '../fill/inject';", + 'shell/ui/Popup.tsx', + ], + [ + "import type { ScanOutcome } from '../fill/inject';", + 'entrypoints/background.ts', + ], + ["import { openTab } from './inject';", 'shell/capture/other.ts'], + ["import type { ScanOutcome } from '../inject';", 'shell/fill/page/x.ts'], + ])('allows the injector import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === controllerRule)).toBe(false); + }); + it.each([ + [ + "import { createFillController } from '../controller';", + 'shell/fill/page/x.ts', + ], + ["export * from '../../controller.js';", 'shell/fill/page/y/x.ts'], + [ + "import { createFillController } from '../controller';", + 'shell/fill/inject.test.ts', + ], + ])('rejects the parent controller import %s in %s', async (code, file) => { + const found = await syntaxMessages(code, file); + expect(found.some((m) => m.ruleId === controllerRule)).toBe(true); + }); + it('allows a type import of the controller from a fill subfolder', async () => { + const found = await syntaxMessages( + "import type { FillState } from '../controller';", + 'shell/fill/page/x.ts', + ); + expect(found.some((m) => m.ruleId === controllerRule)).toBe(false); + }); + it.each([ + ["const m = await import('../inject');", 'shell/fill/page/x.ts'], + ["const m = await import('../../inject.js');", 'shell/fill/page/y/x.ts'], + ['const m = await import(`../fill/inject`);', 'shell/ui/x.ts'], + ['const m = await import(`../fill/controller`);', 'shell/ui/x.ts'], + ['const m = await import(x);', 'shell/ui/x.ts'], + ])('rejects the dynamic import %s in %s (new forms)', async (code, file) => { + const found = await syntaxMessages(code, file); + expect( + found.some( + (m) => + m.message === + 'Only shell/fill/controller.ts may import the fill apply call.' || + m.message === + 'Only shell/ui/Popup.tsx may import the fill controller.' || + m.message === 'import() must use a plain string.', + ), + ).toBe(true); + }); + it('rejects a dynamic parent controller import', async () => { + const found = await syntaxMessages( + "const m = await import('../controller');", + 'shell/fill/page/x.ts', + ); + expect( + found.some( + (m) => + m.message === + 'Only shell/ui/Popup.tsx may import the fill controller.', + ), + ).toBe(true); + }); + it.each([ + [ + 'const m = await import(`../fill/inject`);', + 'import() must use a plain string.', + ], + ['const m = await import(x);', 'import() must use a plain string.'], + ])('flags %s as a non-literal import', async (code, message) => { + const found = await syntaxMessages(code, 'shell/ui/x.ts'); + expect(found.some((m) => m.message === message)).toBe(true); + }); + const fillCallMessage = + 'Only the Fill button in shell/ui/FillSection.tsx may read fill() from the controller.'; + it.each([ + ['shell/ui/Popup.tsx', 'void ctrl.fill();'], + ['shell/ui/NewButton.tsx', 'void controller.fill();'], + ['shell/ui/Popup.tsx', "void ctrl['fill']();"], + ['shell/ui/Popup.tsx', 'const { fill } = ctrl;'], + ['shell/ui/Popup.tsx', 'const { fill: go } = ctrl;'], + ['shell/ui/Popup.tsx', 'const x = + + + diff --git a/shell/fill/fixtures/embed-ashby.html b/shell/fill/fixtures/embed-ashby.html new file mode 100644 index 0000000..bb71a67 --- /dev/null +++ b/shell/fill/fixtures/embed-ashby.html @@ -0,0 +1,14 @@ + + + + + Careers at Example Robotics + + +

Careers at Example Robotics

+ + + diff --git a/shell/fill/fixtures/embed-greenhouse.html b/shell/fill/fixtures/embed-greenhouse.html new file mode 100644 index 0000000..06203f2 --- /dev/null +++ b/shell/fill/fixtures/embed-greenhouse.html @@ -0,0 +1,15 @@ + + + + + Careers at Example Robotics + + +

Careers at Example Robotics

+ + + + diff --git a/shell/fill/fixtures/greenhouse-like.html b/shell/fill/fixtures/greenhouse-like.html new file mode 100644 index 0000000..5912176 --- /dev/null +++ b/shell/fill/fixtures/greenhouse-like.html @@ -0,0 +1,75 @@ + + + + + Example Robotics - Careers + + + +

Robotics Engineer, Example Robotics

+
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + + +
+
+ + + +
+ +
+ + diff --git a/shell/fill/fixtures/lever-like.html b/shell/fill/fixtures/lever-like.html new file mode 100644 index 0000000..25ac6ce --- /dev/null +++ b/shell/fill/fixtures/lever-like.html @@ -0,0 +1,77 @@ + + + + + Example Robotics - Apply for Robotics Engineer + + +

Apply for Robotics Engineer at Example Robotics

+
+ +
    +
  • + +
  • +
  • + +
  • +
  • +
    Phone
    + +
  • +
  • +
    Current location
    + +
  • +
  • +
    LinkedIn URL
    + +
  • +
  • +
    Resume/CV
    + +
  • +
  • +
    + Are you legally authorized to work in the United States? +
    + +
  • +
  • +
    + Will you now or in the future require visa sponsorship? +
    +
      +
    • + +
    • +
    • + +
    • +
    +
  • +
  • +
    Additional information
    + +
  • +
+ +
+ + diff --git a/shell/fill/fixtures/no-form.html b/shell/fill/fixtures/no-form.html new file mode 100644 index 0000000..4f01c4f --- /dev/null +++ b/shell/fill/fixtures/no-form.html @@ -0,0 +1,19 @@ + + + + + Engineer at Example Robotics + + +
+ +
+
+

Engineer at Example Robotics

+

About the role

+

Build and test robot control software with a small team.

+

Requirements

+

Three years of experience with embedded systems.

+
+ + diff --git a/shell/fill/fixtures/prefilled.html b/shell/fill/fixtures/prefilled.html new file mode 100644 index 0000000..3e0457d --- /dev/null +++ b/shell/fill/fixtures/prefilled.html @@ -0,0 +1,42 @@ + + + + + Example Robotics - Update your application + + +
+ +
+ + +
+
+ + +
+
+ + +
+
+ Are you over 18? + + +
+
+ + +
+
+ + +
+ +
+ + diff --git a/shell/fill/fixtures/referee-block.html b/shell/fill/fixtures/referee-block.html new file mode 100644 index 0000000..10a3720 --- /dev/null +++ b/shell/fill/fixtures/referee-block.html @@ -0,0 +1,22 @@ + + + + + Apply to Example Robotics + + +
+ + + + +
+ Reference + + + + +
+
+ + diff --git a/shell/fill/fixtures/two-forms.html b/shell/fill/fixtures/two-forms.html new file mode 100644 index 0000000..5460100 --- /dev/null +++ b/shell/fill/fixtures/two-forms.html @@ -0,0 +1,28 @@ + + + + + Engineer at Example Robotics + + +
+

Engineer at Example Robotics

+
+ + + + + + + + +
+
+
+
+ + +
+
+ + diff --git a/shell/fill/inject.test.ts b/shell/fill/inject.test.ts new file mode 100644 index 0000000..62d87e6 --- /dev/null +++ b/shell/fill/inject.test.ts @@ -0,0 +1,177 @@ +import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'; +import type { FillWrite } from '../../core/src/fill/types'; +import { FILL_TIMEOUT_MS, applyToPage, scanPage, type FillApi } from './inject'; + +const SCAN = { fields: [], frames: [], truncated: false }; +const RESULT = { outcomes: [{ ref: 1, outcome: 'written' }], scan: SCAN }; +const WRITES: FillWrite[] = [ + { ref: 1, kind: 'value', value: 'Ada Example' }, + { ref: 2, kind: 'option', index: 0 }, +]; + +function fakeApi( + tab: { id?: number; url?: string } | undefined, + scan: () => Promise = () => Promise.resolve(SCAN), + apply: () => Promise = () => Promise.resolve(RESULT), +): Pick & { + scan: Mock<(tabId: number) => Promise>; + apply: Mock< + (tabId: number, writes: readonly FillWrite[]) => Promise + >; +} { + return { + activeTab: () => Promise.resolve(tab), + scan: vi.fn<(tabId: number) => Promise>(scan), + apply: + vi.fn<(tabId: number, writes: readonly FillWrite[]) => Promise>( + apply, + ), + }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('scanPage', () => { + it('returns the validated scan with the tab id and address', async () => { + const api = fakeApi({ id: 7, url: ' https://example.com/apply ' }); + expect(await scanPage(api)).toEqual({ + ok: true, + tabId: 7, + url: 'https://example.com/apply', + scan: SCAN, + }); + expect(api.scan).toHaveBeenCalledWith(7); + }); + + it('reports no_tab', async () => { + expect(await scanPage(fakeApi(undefined))).toEqual({ + ok: false, + reason: 'no_tab', + }); + expect(await scanPage(fakeApi({ url: 'https://example.com/' }))).toEqual({ + ok: false, + reason: 'no_tab', + }); + const api: FillApi = { + activeTab: () => Promise.reject(new Error('no window')), + scan: vi.fn(), + apply: vi.fn(), + }; + expect(await scanPage(api)).toEqual({ ok: false, reason: 'no_tab' }); + }); + + it.each([ + 'about:addons', + 'moz-extension://x/popup.html', + 'file:///c:/x.html', + undefined, + ' ', + ])('does not inject on a non-http page (%s)', async (url) => { + const api = fakeApi({ id: 1, url }); + expect(await scanPage(api)).toEqual({ ok: false, reason: 'not_http' }); + expect(api.scan).not.toHaveBeenCalled(); + }); + + it('refuses when the scan rejects', async () => { + const api = fakeApi({ id: 1, url: 'https://example.com/' }, () => + Promise.reject(new Error('blocked')), + ); + expect(await scanPage(api)).toEqual({ ok: false, reason: 'refused' }); + }); + + it.each([undefined, 'x', { fields: 1 }])( + 'refuses a result that is not a scan (%j)', + async (raw) => { + const api = fakeApi({ id: 1, url: 'https://example.com/' }, () => + Promise.resolve(raw), + ); + expect(await scanPage(api)).toEqual({ ok: false, reason: 'refused' }); + }, + ); + + it('times out after 5 s and clears the timer', async () => { + vi.useFakeTimers(); + const api = fakeApi({ id: 1, url: 'https://example.com/' }, () => { + return new Promise(() => undefined); + }); + const pending = scanPage(api); + await vi.advanceTimersByTimeAsync(FILL_TIMEOUT_MS); + expect(await pending).toEqual({ ok: false, reason: 'refused' }); + expect(vi.getTimerCount()).toBe(0); + }); + + it('clears the timer when the scan settles', async () => { + vi.useFakeTimers(); + const api = fakeApi({ id: 1, url: 'https://example.com/' }); + await scanPage(api); + expect(vi.getTimerCount()).toBe(0); + }); + + it('never calls apply', async () => { + const api = fakeApi({ id: 1, url: 'https://example.com/' }); + await scanPage(api); + expect(api.apply).not.toHaveBeenCalled(); + }); +}); + +describe('applyToPage', () => { + it('passes the tab id and the writes through unchanged', async () => { + const api = fakeApi(undefined); + await applyToPage(7, WRITES, api); + expect(api.apply).toHaveBeenCalledTimes(1); + const args = api.apply.mock.calls[0] as unknown[]; + expect(args[0]).toBe(7); + expect(args[1]).toBe(WRITES); + }); + + it('returns the validated result', async () => { + expect(await applyToPage(1, WRITES, fakeApi(undefined))).toEqual({ + ok: true, + result: RESULT, + }); + }); + + it('fails when the script is not registered', async () => { + const api = fakeApi(undefined, undefined, () => Promise.resolve(undefined)); + expect(await applyToPage(1, WRITES, api)).toEqual({ ok: false }); + }); + + it('fails on a rejection', async () => { + const api = fakeApi(undefined, undefined, () => + Promise.reject(new Error('gone')), + ); + expect(await applyToPage(1, WRITES, api)).toEqual({ ok: false }); + }); + + it('fails on a result that is not an apply result', async () => { + const api = fakeApi(undefined, undefined, () => + Promise.resolve({ outcomes: 1 }), + ); + expect(await applyToPage(1, WRITES, api)).toEqual({ ok: false }); + }); + + it('times out after 5 s and clears the timer', async () => { + vi.useFakeTimers(); + const api = fakeApi(undefined, undefined, () => { + return new Promise(() => undefined); + }); + const pending = applyToPage(1, WRITES, api); + await vi.advanceTimersByTimeAsync(FILL_TIMEOUT_MS); + expect(await pending).toEqual({ ok: false }); + expect(vi.getTimerCount()).toBe(0); + }); + + it('clears the timer when the apply settles', async () => { + vi.useFakeTimers(); + await applyToPage(1, WRITES, fakeApi(undefined)); + expect(vi.getTimerCount()).toBe(0); + }); + + it('never calls scan', async () => { + const api = fakeApi(undefined); + await applyToPage(1, WRITES, api); + expect(api.scan).not.toHaveBeenCalled(); + }); +}); diff --git a/shell/fill/inject.ts b/shell/fill/inject.ts new file mode 100644 index 0000000..cc37144 --- /dev/null +++ b/shell/fill/inject.ts @@ -0,0 +1,100 @@ +import { browser } from 'wxt/browser'; +import type { + ApplyResult, + FillWrite, + FormScan, +} from '../../core/src/fill/types'; +import { toApplyResult, toFormScan } from '../../core/src/fill/validate'; + +export const FILL_TIMEOUT_MS = 5_000; + +export interface FillApi { + activeTab(): Promise<{ id?: number; url?: string } | undefined>; + scan(tabId: number): Promise; + apply(tabId: number, writes: readonly FillWrite[]): Promise; +} + +export const browserFillApi: FillApi = { + async activeTab() { + const tabs = await browser.tabs.query({ + active: true, + currentWindow: true, + }); + return tabs[0]; + }, + async scan(tabId) { + const results = await browser.scripting.executeScript({ + target: { tabId }, + files: ['/fill.js'], + }); + return results[0]?.result; + }, + async apply(tabId, writes) { + const results = await browser.scripting.executeScript({ + target: { tabId }, + // Serialised into the page: it must reference nothing outside itself. + func: (w: unknown) => + ( + globalThis as { + __countersignFill?: { apply(w: unknown): unknown }; + } + ).__countersignFill?.apply(w), + args: [writes], + }); + return results[0]?.result; + }, +}; + +export type ScanOutcome = + | { ok: true; tabId: number; url: string; scan: FormScan } + | { ok: false; reason: 'no_tab' | 'not_http' | 'refused' }; + +export type ApplyOutcome = { ok: true; result: ApplyResult } | { ok: false }; + +const TIMED_OUT = Symbol('timed out'); + +/** Resolves with the call's value, or undefined on rejection or timeout. */ +async function raced(call: () => Promise): Promise { + let timer: ReturnType | undefined; + try { + const timeout = new Promise((resolve) => { + timer = setTimeout(() => { + resolve(TIMED_OUT); + }, FILL_TIMEOUT_MS); + }); + const result = await Promise.race([call(), timeout]); + return result === TIMED_OUT ? undefined : result; + } catch { + return undefined; + } finally { + clearTimeout(timer); + } +} + +export async function scanPage( + api: FillApi = browserFillApi, +): Promise { + let tab: { id?: number; url?: string } | undefined; + try { + tab = await api.activeTab(); + } catch { + return { ok: false, reason: 'no_tab' }; + } + if (typeof tab?.id !== 'number') return { ok: false, reason: 'no_tab' }; + const url = typeof tab.url === 'string' ? tab.url.trim() : ''; + if (!/^https?:\/\//i.test(url)) return { ok: false, reason: 'not_http' }; + const tabId = tab.id; + const scan = toFormScan(await raced(() => api.scan(tabId))); + return scan + ? { ok: true, tabId, url, scan } + : { ok: false, reason: 'refused' }; +} + +export async function applyToPage( + tabId: number, + writes: readonly FillWrite[], + api: FillApi = browserFillApi, +): Promise { + const result = toApplyResult(await raced(() => api.apply(tabId, writes))); + return result ? { ok: true, result } : { ok: false }; +} diff --git a/shell/fill/page-apply.test.ts b/shell/fill/page-apply.test.ts new file mode 100644 index 0000000..c8bad91 --- /dev/null +++ b/shell/fill/page-apply.test.ts @@ -0,0 +1,658 @@ +// @vitest-environment happy-dom +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Window } from 'happy-dom'; +import { describe, expect, it, vi } from 'vitest'; +import { applyWrites } from './page/apply'; +import { scanForm, type PageScan } from './page/scan'; + +interface Loaded { + window: Window; + doc: Document; + page: PageScan; +} + +function parse(html: string): Loaded { + const window = new Window({ url: 'https://example.com/jobs/1' }); + window.document.write(html); + const doc = window.document as unknown as Document; + return { window, doc, page: scanForm(doc) }; +} + +function load(name: string): Loaded { + return parse( + readFileSync(join(import.meta.dirname, 'fixtures', name), 'utf8'), + ); +} + +function refOf(page: PageScan, label: RegExp): number { + const field = page.scan.fields.find((f) => label.test(f.label)); + if (!field) throw new Error(`no field matches ${String(label)}`); + return field.ref; +} + +const WATCHED = [ + 'input', + 'change', + 'keydown', + 'keyup', + 'click', + 'focus', + 'blur', + 'submit', +]; + +function record(doc: Document): Event[] { + const events: Event[] = []; + for (const type of WATCHED) { + doc.addEventListener(type, (event) => events.push(event), { + capture: true, + }); + } + return events; +} + +function attributeMap(doc: Document): string[] { + return Array.from(doc.querySelectorAll('*')).map( + (el) => + `${el.localName}|` + + Array.from(el.attributes) + .map((a) => `${a.name}=${a.value}`) + .join(','), + ); +} + +describe('applyWrites', () => { + it('writes text, a select option and a checkbox', () => { + const { doc, page } = load('lever-like.html'); + const name = refOf(page, /Full name/); + const auth = refOf(page, /authorized/); + const sponsor = refOf(page, /sponsorship/); + const reports = applyWrites(page.elements, [ + { ref: name, kind: 'value', value: 'Sam Example' }, + { ref: auth, kind: 'option', index: 0 }, + { ref: sponsor, kind: 'option', index: 1 }, + ]); + expect(reports).toEqual([ + { ref: name, outcome: 'written' }, + { ref: auth, outcome: 'written' }, + { ref: sponsor, outcome: 'written' }, + ]); + expect((doc.querySelector('[name="name"]') as HTMLInputElement).value).toBe( + 'Sam Example', + ); + const select = doc.querySelector('select') as HTMLSelectElement; + expect(select.options[select.selectedIndex]?.text).toBe('Yes'); + const boxes = doc.querySelectorAll('[name="sponsorship"]'); + expect((boxes[0] as HTMLInputElement).checked).toBe(false); + expect((boxes[1] as HTMLInputElement).checked).toBe(true); + }); + + it('fires input then change once per field', () => { + const { doc, page } = load('lever-like.html'); + const events = record(doc); + applyWrites(page.elements, [ + { ref: refOf(page, /Full name/), kind: 'value', value: 'Sam Example' }, + { ref: refOf(page, /authorized/), kind: 'option', index: 0 }, + { ref: refOf(page, /sponsorship/), kind: 'option', index: 1 }, + ]); + expect(events.map((e) => e.type)).toEqual([ + 'input', + 'change', + 'input', + 'change', + 'input', + 'change', + ]); + const targets = events.map((e) => e.target); + expect(targets[0]).toBe(targets[1]); + expect(targets[2]).toBe(targets[3]); + expect(targets[4]).toBe(targets[5]); + expect(targets[4]).toBe(doc.querySelectorAll('[name="sponsorship"]')[1]); + }); + + it('leaves a non-empty field alone', () => { + const { doc, page } = load('prefilled.html'); + const events = record(doc); + const email = refOf(page, /Email/); + const select = refOf(page, /relocate/); + const group = refOf(page, /over 18/); + const reports = applyWrites(page.elements, [ + { ref: email, kind: 'value', value: 'other@example.com' }, + { ref: select, kind: 'option', index: 1 }, + { ref: group, kind: 'option', index: 0 }, + ]); + expect(reports.map((r) => r.outcome)).toEqual([ + 'not_empty', + 'not_empty', + 'not_empty', + ]); + expect((doc.querySelector('#email') as HTMLInputElement).value).toBe( + 'someone@example.com', + ); + expect((doc.querySelector('#relocate') as HTMLSelectElement).value).toBe( + 'yes', + ); + const radios = doc.querySelectorAll('[name="adult"]'); + expect((radios[0] as HTMLInputElement).checked).toBe(false); + expect((radios[1] as HTMLInputElement).checked).toBe(true); + expect(events).toEqual([]); + }); + + it('treats a field holding only spaces as not empty', () => { + const { doc, page } = load('lever-like.html'); + const name = refOf(page, /Full name/); + (doc.querySelector('[name="name"]') as HTMLInputElement).value = ' '; + const reports = applyWrites(page.elements, [ + { ref: name, kind: 'value', value: 'Sam Example' }, + ]); + expect(reports).toEqual([{ ref: name, outcome: 'not_empty' }]); + }); + + it('a detached element is gone', () => { + const { doc, page } = load('lever-like.html'); + const name = refOf(page, /Full name/); + doc.querySelector('[name="name"]')?.remove(); + const reports = applyWrites(page.elements, [ + { ref: name, kind: 'value', value: 'Sam Example' }, + { ref: 999, kind: 'value', value: 'x' }, + ]); + expect(reports).toEqual([ + { ref: name, outcome: 'gone' }, + { ref: 999, outcome: 'gone' }, + ]); + }); + + it('the page changed after the scan', () => { + const { doc, page } = load('lever-like.html'); + const name = refOf(page, /Full name/); + const input = doc.querySelector('[name="name"]') as HTMLInputElement; + input.value = 'Typed by the visitor'; + const reports = applyWrites(page.elements, [ + { ref: name, kind: 'value', value: 'Sam Example' }, + ]); + expect(reports).toEqual([{ ref: name, outcome: 'not_empty' }]); + expect(input.value).toBe('Typed by the visitor'); + }); + + it('wrong shapes fail', () => { + const { doc, page } = load('lever-like.html'); + const events = record(doc); + const before = attributeMap(doc); + const name = refOf(page, /Full name/); + const auth = refOf(page, /authorized/); + const file = page.scan.fields.find((f) => f.control === 'file'); + const custom = page.scan.fields.find((f) => f.control === 'custom'); + expect(file).toBeDefined(); + expect(custom).toBeDefined(); + const writes = [ + { ref: name, kind: 'option', index: 0 }, + { ref: auth, kind: 'value', value: 'Yes' }, + { ref: auth, kind: 'option', index: 9 }, + { ref: name, kind: 'value', value: 'x'.repeat(501) }, + { ref: name, kind: 'value' }, + { ref: auth, kind: 'option', index: -1 }, + { ref: auth, kind: 'option', index: 1.5 }, + { ref: file?.ref ?? -1, kind: 'value', value: 'a' }, + { ref: custom?.ref ?? -1, kind: 'value', value: 'a' }, + { ref: name, kind: 'other' }, + ]; + const reports = applyWrites(page.elements, writes); + expect(reports).toHaveLength(writes.length); + expect(reports.every((r) => r.outcome === 'failed')).toBe(true); + expect((doc.querySelector('[name="name"]') as HTMLInputElement).value).toBe( + '', + ); + expect((doc.querySelector('select') as HTMLSelectElement).value).toBe(''); + expect(events).toEqual([]); + expect(attributeMap(doc)).toEqual(before); + }); + + it('fails a date that is not YYYY-MM-DD and writes one that is', () => { + const { doc, page } = parse( + '
', + ); + const ref = refOf(page, /Start date/); + expect(page.scan.fields[0]?.control).toBe('date'); + expect( + applyWrites(page.elements, [{ ref, kind: 'value', value: '12/01/2026' }]), + ).toEqual([{ ref, outcome: 'failed' }]); + expect( + applyWrites(page.elements, [{ ref, kind: 'value', value: '2026-12-01' }]), + ).toEqual([{ ref, outcome: 'written' }]); + expect((doc.querySelector('#d') as HTMLInputElement).value).toBe( + '2026-12-01', + ); + }); + + it('fails a field that became disabled or read-only after the scan', () => { + const { doc, page } = parse( + '
' + + '' + + '' + + '
' + + '
' + + '' + + '
Gamma' + + '' + + '' + + '
', + ); + const writes = [ + { ref: refOf(page, /Alpha/), kind: 'value', value: 'x' }, + { ref: refOf(page, /Bravo/), kind: 'value', value: 'x' }, + { ref: refOf(page, /Charlie/), kind: 'value', value: 'x' }, + { ref: refOf(page, /Sierra/), kind: 'option', index: 0 }, + { ref: refOf(page, /Gamma/), kind: 'option', index: 1 }, + ]; + doc.querySelector('#a')?.setAttribute('disabled', ''); + doc.querySelector('#b')?.setAttribute('readonly', ''); + doc.querySelector('#fs')?.setAttribute('disabled', ''); + doc.querySelector('#s')?.setAttribute('disabled', ''); + doc.querySelectorAll('[name="g"]')[1]?.setAttribute('disabled', ''); + const reports = applyWrites(page.elements, writes); + expect(reports.map((r) => r.outcome)).toEqual([ + 'failed', + 'failed', + 'failed', + 'failed', + 'failed', + ]); + for (const id of ['a', 'b', 'c']) { + expect((doc.querySelector('#' + id) as HTMLInputElement).value).toBe(''); + } + expect((doc.querySelector('#s') as HTMLSelectElement).value).toBe(''); + expect( + (doc.querySelectorAll('[name="g"]')[1] as HTMLInputElement).checked, + ).toBe(false); + }); + + it('fails a field disabled after the scan', () => { + const { doc, page } = load('lever-like.html'); + const name = refOf(page, /Full name/); + doc.querySelector('[name="name"]')?.setAttribute('disabled', ''); + expect( + applyWrites(page.elements, [{ ref: name, kind: 'value', value: 'x' }]), + ).toEqual([{ ref: name, outcome: 'failed' }]); + }); + + it('hostile writes', () => { + const { page } = load('lever-like.html'); + expect(applyWrites(page.elements, 'x')).toEqual([]); + expect(applyWrites(page.elements, { length: 3 })).toEqual([]); + expect(applyWrites(page.elements, null)).toEqual([]); + const name = refOf(page, /Full name/); + const many = Array.from({ length: 5000 }, () => ({ + ref: name, + kind: 'value', + value: 'x', + })); + expect(applyWrites(page.elements, many).length).toBeLessThanOrEqual(200); + expect( + applyWrites(page.elements, [null, 'x', [], { kind: 'value' }]), + ).toEqual([]); + expect( + applyWrites(page.elements, [{ ref: 'a', kind: 'value', value: 'x' }]), + ).toEqual([]); + }); + + it('reads at most 200 entries, counting skipped ones', () => { + const { page } = load('lever-like.html'); + const name = refOf(page, /Full name/); + const writes: unknown[] = Array.from({ length: 200 }, () => null); + writes.push({ ref: name, kind: 'value', value: 'Sam Example' }); + expect(applyWrites(page.elements, writes)).toEqual([]); + }); + + it('goes through the prototype setter', () => { + const { doc, window, page } = load('lever-like.html'); + const name = refOf(page, /Full name/); + const input = doc.querySelector('[name="name"]') as HTMLInputElement; + const calls: string[] = []; + Object.defineProperty(input, 'value', { + configurable: true, + get() { + return ''; + }, + set(v: string) { + calls.push(v); + }, + }); + const reports = applyWrites(page.elements, [ + { ref: name, kind: 'value', value: 'Sam Example' }, + ]); + expect(reports).toEqual([{ ref: name, outcome: 'written' }]); + expect(calls).toEqual([]); + // The getter is always called with .call on the element. + // eslint-disable-next-line @typescript-eslint/unbound-method + const get = Object.getOwnPropertyDescriptor( + window.HTMLInputElement.prototype, + 'value', + )?.get; + expect(get?.call(input)).toBe('Sam Example'); + }); + + it('behaviour guard: a full fill only sets values', () => { + const { doc, window, page } = load('lever-like.html'); + const events = record(doc); + const submit = vi.spyOn(window.HTMLFormElement.prototype, 'submit'); + const requestSubmit = vi.spyOn( + window.HTMLFormElement.prototype, + 'requestSubmit', + ); + const countBefore = doc.querySelectorAll('*').length; + const attributesBefore = attributeMap(doc); + const activeBefore = doc.activeElement; + + const reports = applyWrites(page.elements, [ + { ref: refOf(page, /Full name/), kind: 'value', value: 'Sam Example' }, + { ref: refOf(page, /Email/), kind: 'value', value: 'sam@example.com' }, + { ref: refOf(page, /Phone/), kind: 'value', value: '555-0100' }, + { ref: refOf(page, /authorized/), kind: 'option', index: 0 }, + { ref: refOf(page, /sponsorship/), kind: 'option', index: 1 }, + { ref: refOf(page, /Additional/), kind: 'value', value: 'Hello' }, + ]); + + expect(reports.every((r) => r.outcome === 'written')).toBe(true); + expect(events.map((e) => e.type)).not.toContain('submit'); + for (const type of ['keydown', 'keyup', 'click', 'focus', 'blur']) { + expect(events.map((e) => e.type)).not.toContain(type); + } + expect(submit).not.toHaveBeenCalled(); + expect(requestSubmit).not.toHaveBeenCalled(); + expect(doc.querySelectorAll('*').length).toBe(countBefore); + expect(attributeMap(doc)).toEqual(attributesBefore); + expect(doc.activeElement).toBe(activeBefore); + }); + + it('reports gone when the select options were replaced after the scan', () => { + const { doc, page } = load('lever-like.html'); + const events = record(doc); + const auth = refOf(page, /authorized/); + const select = doc.querySelector('select') as HTMLSelectElement; + select.innerHTML = + ''; + expect( + applyWrites(page.elements, [{ ref: auth, kind: 'option', index: 1 }]), + ).toEqual([{ ref: auth, outcome: 'gone' }]); + expect(select.selectedIndex).toBe(0); + expect(events).toEqual([]); + }); + + it('reports failed and fires nothing when the value did not take', () => { + const { doc, window, page } = parse( + '
', + ); + const events = record(doc); + const ref = refOf(page, /Start date/); + // happy-dom does not sanitise dates, so make the getter report what a browser would. + const proto = window.HTMLInputElement.prototype; + const original = Object.getOwnPropertyDescriptor(proto, 'value'); + Object.defineProperty(proto, 'value', { + configurable: true, + get: () => '', + // eslint-disable-next-line @typescript-eslint/unbound-method + set: original?.set, + }); + expect( + applyWrites(page.elements, [{ ref, kind: 'value', value: '2026-13-45' }]), + ).toEqual([{ ref, outcome: 'failed' }]); + if (original) Object.defineProperty(proto, 'value', original); + expect(events).toEqual([]); + }); + + it('reports written for a textarea value with CRLF line breaks', () => { + const { doc, page } = load('lever-like.html'); + const ref = refOf(page, /Additional/); + expect( + applyWrites(page.elements, [ + { ref, kind: 'value', value: 'one\r\ntwo\rthree' }, + ]), + ).toEqual([{ ref, outcome: 'written' }]); + const stored = (doc.querySelector('textarea') as HTMLTextAreaElement).value; + expect(stored.replace(/\r\n?/g, '\n')).toBe('one\ntwo\nthree'); + }); + + it('fails an option disabled after the scan', () => { + const { doc, page } = load('lever-like.html'); + const events = record(doc); + const auth = refOf(page, /authorized/); + doc.querySelectorAll('option')[1]?.setAttribute('disabled', ''); + expect( + applyWrites(page.elements, [{ ref: auth, kind: 'option', index: 0 }]), + ).toEqual([{ ref: auth, outcome: 'failed' }]); + expect((doc.querySelector('select') as HTMLSelectElement).value).toBe(''); + expect(events).toEqual([]); + }); + + it('writes a select with nothing chosen', () => { + const { doc, page } = load('lever-like.html'); + const auth = refOf(page, /authorized/); + const select = doc.querySelector('select') as HTMLSelectElement; + select.selectedIndex = -1; + expect(select.selectedIndex).toBe(-1); + expect( + applyWrites(page.elements, [{ ref: auth, kind: 'option', index: 1 }]), + ).toEqual([{ ref: auth, outcome: 'written' }]); + expect(select.options[select.selectedIndex]?.text).toBe('No'); + }); + + describe('recheck at write time', () => { + const ONE = + '
'; + + function expectUntouched( + change: (doc: Document) => void, + html = ONE, + ): void { + const { doc, page } = parse(html); + const events = record(doc); + const ref = refOf(page, /Alpha/); + change(doc); + expect( + applyWrites(page.elements, [{ ref, kind: 'value', value: 'x' }]), + ).toEqual([{ ref, outcome: 'gone' }]); + expect(doc.querySelector('#a')?.getAttribute('value')).toBeNull(); + expect((doc.querySelector('#a') as HTMLInputElement).value).not.toBe('x'); + expect(events).toEqual([]); + } + + it('does not write a field hidden with display:none', () => { + expectUntouched((doc) => + (doc.querySelector('#a') as HTMLElement).style.setProperty( + 'display', + 'none', + ), + ); + }); + + it('does not write a text input made transparent', () => { + expectUntouched((doc) => + (doc.querySelector('#a') as HTMLElement).style.setProperty( + 'opacity', + '0', + ), + ); + }); + + it('does not write a field switched to a password', () => { + expectUntouched((doc) => + doc.querySelector('#a')?.setAttribute('type', 'password'), + ); + }); + + it('does not write a field given a card autocomplete', () => { + expectUntouched((doc) => + doc.querySelector('#a')?.setAttribute('autocomplete', 'cc-number'), + ); + }); + + it('does not write a field whose control kind changed', () => { + expectUntouched((doc) => + doc.querySelector('#a')?.setAttribute('type', 'checkbox'), + ); + }); + + it('does not write a radio group that gained a checked disabled peer', () => { + const { doc, page } = parse( + '
Gamma' + + '' + + '' + + '' + + '
', + ); + const events = record(doc); + const ref = refOf(page, /Gamma/); + const radios = doc.querySelectorAll('[name="g"]'); + (radios[2] as HTMLInputElement).checked = true; + expect( + applyWrites(page.elements, [{ ref, kind: 'option', index: 0 }]), + ).toEqual([{ ref, outcome: 'gone' }]); + expect((radios[0] as HTMLInputElement).checked).toBe(false); + expect(events).toEqual([]); + }); + + it('puts a text field back to empty when the value did not take', () => { + const { doc, window, page } = parse( + '
', + ); + const events = record(doc); + const ref = refOf(page, /Start date/); + const proto = window.HTMLInputElement.prototype; + const original = Object.getOwnPropertyDescriptor(proto, 'value'); + let stored = ''; + Object.defineProperty(proto, 'value', { + configurable: true, + // A browser keeps a sanitised value, here a different one. + get: () => stored, + set: (v: string) => { + stored = v === '' ? '' : 'sanitised'; + }, + }); + try { + expect( + applyWrites(page.elements, [ + { ref, kind: 'value', value: '2026-13-45' }, + ]), + ).toEqual([{ ref, outcome: 'failed' }]); + expect(stored).toBe(''); + } finally { + if (original) Object.defineProperty(proto, 'value', original); + } + expect(events).toEqual([]); + }); + + it('restores the previous option when the select did not take', () => { + const { doc, window, page } = parse( + '
', + ); + const events = record(doc); + const ref = refOf(page, /Sierra/); + const select = doc.querySelector('#s') as HTMLSelectElement; + const proto = window.HTMLSelectElement.prototype; + const original = Object.getOwnPropertyDescriptor(proto, 'selectedIndex'); + const calls: number[] = []; + Object.defineProperty(proto, 'selectedIndex', { + configurable: true, + // The first read after a write reports a different index, as a browser that refused it. + get(this: HTMLSelectElement) { + return calls.length === 1 + ? -1 + : (original?.get?.call(this) as number); + }, + set(this: HTMLSelectElement, v: number) { + calls.push(v); + original?.set?.call(this, v); + }, + }); + try { + expect( + applyWrites(page.elements, [{ ref, kind: 'option', index: 0 }]), + ).toEqual([{ ref, outcome: 'failed' }]); + expect(calls).toEqual([1, 0]); + } finally { + if (original) Object.defineProperty(proto, 'selectedIndex', original); + } + expect(select.selectedIndex).toBe(0); + expect(events).toEqual([]); + }); + + it('unchecks the member when the checked state did not take', () => { + const { doc, window, page } = parse( + '
Gamma' + + '' + + '' + + '
', + ); + const events = record(doc); + const ref = refOf(page, /Gamma/); + const radios = doc.querySelectorAll('[name="g"]'); + const proto = window.HTMLInputElement.prototype; + const original = Object.getOwnPropertyDescriptor(proto, 'checked'); + Object.defineProperty(proto, 'checked', { + configurable: true, + get: () => false, + // eslint-disable-next-line @typescript-eslint/unbound-method + set: original?.set, + }); + try { + expect( + applyWrites(page.elements, [{ ref, kind: 'option', index: 0 }]), + ).toEqual([{ ref, outcome: 'failed' }]); + } finally { + if (original) Object.defineProperty(proto, 'checked', original); + } + expect((radios[0] as HTMLInputElement).checked).toBe(false); + expect((radios[1] as HTMLInputElement).checked).toBe(false); + expect(events).toEqual([]); + }); + + describe('a hidden group member', () => { + const GROUP = + '
Gamma' + + '' + + '' + + '' + + '
'; + + function hideThenWrite(hide: number, target: number): void { + const { doc, page } = parse(GROUP); + const events = record(doc); + const ref = refOf(page, /Gamma/); + const radios = Array.from( + doc.querySelectorAll('[name="g"]'), + ); + radios[hide]?.style.setProperty('display', 'none'); + expect( + applyWrites(page.elements, [{ ref, kind: 'option', index: target }]), + ).toEqual([{ ref, outcome: 'gone' }]); + expect(radios.some((r) => r.checked)).toBe(false); + expect(events).toEqual([]); + } + + it('is not written when it is a later member', () => { + hideThenWrite(1, 1); + }); + + it('fails closed when the first member is hidden and a later one is targeted', () => { + hideThenWrite(0, 1); + }); + }); + }); + + it('leaves a checkbox group with one member checked alone', () => { + const { doc, page } = load('lever-like.html'); + const events = record(doc); + const sponsor = refOf(page, /sponsorship/); + const boxes = doc.querySelectorAll('[name="sponsorship"]'); + (boxes[0] as HTMLInputElement).checked = true; + expect( + applyWrites(page.elements, [{ ref: sponsor, kind: 'option', index: 1 }]), + ).toEqual([{ ref: sponsor, outcome: 'not_empty' }]); + expect((boxes[1] as HTMLInputElement).checked).toBe(false); + expect(events).toEqual([]); + }); +}); diff --git a/shell/fill/page-events.test.ts b/shell/fill/page-events.test.ts new file mode 100644 index 0000000..632c688 --- /dev/null +++ b/shell/fill/page-events.test.ts @@ -0,0 +1,45 @@ +// @vitest-environment happy-dom +import { Window } from 'happy-dom'; +import { describe, expect, it } from 'vitest'; +import { notifyChanged } from './page/events'; + +const WATCHED = [ + 'input', + 'change', + 'keydown', + 'keyup', + 'click', + 'focus', + 'blur', + 'submit', +]; + +function build(): { document: Document; input: Element } { + const window = new Window({ url: 'https://example.com/apply' }); + window.document.write('
'); + const document = window.document as unknown as Document; + const input = document.querySelector('input'); + if (!input) throw new Error('fixture has no input'); + return { document, input }; +} + +describe('notifyChanged', () => { + it('dispatches exactly input then change', () => { + const { document, input } = build(); + const events: Event[] = []; + // Capture listeners see focus and blur, which do not bubble. + for (const type of WATCHED) { + document.addEventListener(type, (event) => events.push(event), { + capture: true, + }); + } + + notifyChanged(input); + + expect(events.map((event) => event.type)).toEqual(['input', 'change']); + for (const event of events) { + expect(event.bubbles).toBe(true); + expect(event.target).toBe(input); + } + }); +}); diff --git a/shell/fill/page-label.test.ts b/shell/fill/page-label.test.ts new file mode 100644 index 0000000..c96da8b --- /dev/null +++ b/shell/fill/page-label.test.ts @@ -0,0 +1,258 @@ +// @vitest-environment happy-dom +import { Window } from 'happy-dom'; +import { describe, expect, it } from 'vitest'; +import { fieldLabel, groupLabel } from './page/label'; + +function load(body: string): Document { + const window = new Window({ url: 'https://example.com/apply' }); + window.document.write(`${body}`); + return window.document as unknown as Document; +} + +const isField = (): boolean => true; + +describe('fieldLabel', () => { + it('aria-labelledby wins over a label for', () => { + const doc = load( + 'Full name', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Full name'); + }); + + it('joins two labelledby ids with a space', () => { + const doc = load( + 'Example RoboticsPhone', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe( + 'Example Robotics Phone', + ); + }); + + it('label for', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Full name'); + }); + + it('wrapping label', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Full name'); + }); + + it("a wrapping label leaves out a nested select's options", () => { + const doc = load( + '', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Country'); + }); + + it('aria-label when there is no label element', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Phone'); + }); + + it('nearest container, Lever shape', () => { + const doc = load( + '
  • Phone
  • ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Phone'); + }); + + it('does not climb past a container with another field', () => { + const doc = load( + '

    Contact

      ' + + '
    • Phone
    • ' + + '
    • Email
    • ' + + '
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Phone'); + expect(fieldLabel(doc.getElementById('b')!, isField)).toBe('Email'); + }); + + it('a placeholder is not a label', () => { + const doc = load( + '
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe(''); + }); + + it('caps at 300 characters', () => { + const doc = load(``); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('a'.repeat(300)); + }); + + it('trims again when the cut ends on a space', () => { + const doc = load(``); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('a'.repeat(299)); + }); + + it('collapses whitespace and newlines', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe( + 'Full name here', + ); + }); + + it('does not use a label for an element without an id', () => { + const doc = load('
    '); + expect(fieldLabel(doc.querySelector('input')!, isField)).toBe(''); + }); + + it('respects isCandidate when deciding what a container holds', () => { + const doc = load( + '
    Phone
    ', + ); + const notHidden = (o: Element): boolean => + o.getAttribute('type') !== 'hidden'; + expect(fieldLabel(doc.getElementById('a')!, notHidden)).toBe('Phone'); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe(''); + }); + + it('passes an empty li but never reaches a heading above another field', () => { + const doc = load( + '

    Contact

      ' + + '
    • ' + + '
    • ' + + '
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe(''); + expect(fieldLabel(doc.getElementById('b')!, isField)).toBe(''); + }); + + it('uses the nearest ancestor with text, not a larger one', () => { + const doc = load( + '
    Outer words
    Inner
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Inner'); + }); + + it('passes an empty container to reach a qualifying one with text', () => { + const doc = load( + '
    Outer words
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Outer words'); + }); + + it('never uses a form as a container', () => { + const doc = load('
    Heading
    '); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe(''); + }); + + it('never uses the body as a container', () => { + const doc = load('Heading
    '); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe(''); + }); + + it('label for beats a wrapping label', () => { + const doc = load( + '', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Outside'); + }); + + it('a wrapping label beats aria-label', () => { + const doc = load(''); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Inside'); + }); + + it('an empty labelledby target falls through to the label for', () => { + const doc = load( + '', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Outside'); + }); + + it('an empty label falls through to aria-label', () => { + const doc = load( + '', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Aria'); + }); + + it('leaves out button, textarea, script and style text in a wrapping label', () => { + const doc = load( + '', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Name'); + }); + + it('leaves out button, textarea, script and style text in a container', () => { + const doc = load( + '
    Name
    ', + ); + expect(fieldLabel(doc.getElementById('a')!, isField)).toBe('Name'); + }); +}); + +describe('groupLabel', () => { + it('leaves out a member label that sits inside a nested element', () => { + const doc = load( + '

    Pick one

    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Pick one'); + }); + + it('leaves out a label for that wraps a member', () => { + const doc = load( + '

    Pick one

    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Pick one'); + }); + + it('uses only the legend, not the other text of the fieldset', () => { + const doc = load( + '
    Preference

    Extra note

    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Preference'); + }); + + it('keeps climbing group ancestors until one has a label', () => { + const doc = load( + '
    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Contact preference'); + }); + + it('uses the legend of a fieldset', () => { + const doc = load( + '
    Work authorisation
    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Work authorisation'); + }); + + it('uses aria-labelledby on a radiogroup', () => { + const doc = load( + 'Do you need sponsorship?
    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Do you need sponsorship?'); + }); + + it('uses the question text of a container without the members labels', () => { + const doc = load( + '

    Do you need sponsorship?

    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Do you need sponsorship?'); + }); + + it('leaves out labels that point at a member by id', () => { + const doc = load( + '

    Pick one

    ', + ); + const members = [...doc.querySelectorAll('input')]; + expect(groupLabel(members, isField)).toBe('Pick one'); + }); + + it('does not use a fieldset that holds another field', () => { + const doc = load( + '
    Everything

    Pick one

    ', + ); + const members = [doc.querySelector('input[type=checkbox]')!]; + expect(groupLabel(members, isField)).toBe('Pick one'); + }); +}); diff --git a/shell/fill/page-scan.test.ts b/shell/fill/page-scan.test.ts new file mode 100644 index 0000000..28ef987 --- /dev/null +++ b/shell/fill/page-scan.test.ts @@ -0,0 +1,1533 @@ +// @vitest-environment happy-dom +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Window } from 'happy-dom'; +import { describe, expect, it } from 'vitest'; +import { buildPlan } from '../../core/src/fill/plan'; +import { FRAME_HOSTS } from '../../core/src/fill/site'; +import type { PlanInput } from '../../core/src/fill/types'; +import { toFormScan } from '../../core/src/fill/validate'; +import { scanForm } from './page/scan'; + +function parse(html: string): Document { + const window = new Window({ url: 'https://example.com/jobs/1' }); + window.document.write(html); + return window.document as unknown as Document; +} + +function load(name: string): Document { + return parse( + readFileSync(join(import.meta.dirname, 'fixtures', name), 'utf8'), + ); +} + +const FIXTURES = [ + 'lever-like.html', + 'greenhouse-like.html', + 'autocomplete-only.html', + 'prefilled.html', + 'two-forms.html', + 'referee-block.html', + 'no-form.html', + 'embed-greenhouse.html', + 'embed-ashby.html', +]; + +describe('scanForm: lever-like', () => { + const { scan } = scanForm(load('lever-like.html')); + + it('finds nine fields with the right controls', () => { + expect(scan.fields.map((f) => f.control)).toEqual([ + 'text', + 'text', + 'text', + 'custom', + 'text', + 'file', + 'select', + 'choice_group', + 'textarea', + ]); + expect(scan.frames).toEqual([]); + expect(scan.truncated).toBe(false); + }); + + it('reads the labels', () => { + expect(scan.fields.map((f) => f.label)).toEqual([ + 'Full name', + 'Email', + 'Phone', + 'Current location', + 'LinkedIn URL', + 'Resume/CV', + 'Are you legally authorized to work in the United States?', + 'Will you now or in the future require visa sponsorship?', + 'Additional information', + ]); + }); + + it('marks Full name required and nothing else', () => { + expect(scan.fields.map((f) => f.required)).toEqual([ + true, + false, + false, + false, + false, + false, + false, + false, + false, + ]); + }); + + it('reports the select without its placeholder', () => { + const select = scan.fields[6]; + expect(select?.options).toEqual(['Yes', 'No']); + expect(select?.value).toBe(''); + expect(select?.multiple).toBe(false); + }); + + it('reports the checkbox group', () => { + const group = scan.fields[7]; + expect(group?.options).toEqual(['Yes', 'No']); + expect(group?.checked).toEqual([]); + expect(group?.multiple).toBe(true); + }); + + it('never reads the hidden input', () => { + expect(JSON.stringify(scan)).not.toContain('hidden-token-7731'); + }); +}); + +describe('scanForm: greenhouse-like', () => { + const { scan } = scanForm(load('greenhouse-like.html')); + + it('finds nine fields', () => { + expect(scan.fields).toHaveLength(9); + expect(scan.fields.slice(0, 3).map((f) => f.autocomplete)).toEqual([ + 'given-name', + 'family-name', + 'email', + ]); + }); + + it('reads First Name as required', () => { + const first = scan.fields[0]; + expect(['First Name *', 'First Name']).toContain(first?.label); + expect(first?.required).toBe(true); + }); + + it('reports the comboboxes as custom with no value', () => { + const custom = scan.fields.filter((f) => f.control === 'custom'); + expect(custom).toHaveLength(2); + expect(custom.every((f) => f.value === '')).toBe(true); + expect(scan.fields[7]?.control).toBe('custom'); + expect(scan.fields[8]?.control).toBe('custom'); + }); + + it('skips the aria-hidden helpers and keeps the clipped file input', () => { + expect(scan.fields.filter((f) => f.control === 'file')).toHaveLength(1); + expect(scan.fields[4]?.control).toBe('file'); + expect(scan.fields).toHaveLength(9); + }); +}); + +describe('scanForm: autocomplete-only', () => { + const { scan } = scanForm(load('autocomplete-only.html')); + + it('finds nine unlabelled fields', () => { + expect(scan.fields).toHaveLength(9); + expect(scan.fields.every((f) => f.label === '')).toBe(true); + expect(scan.fields.map((f) => f.autocomplete)).toEqual([ + 'name', + 'email', + 'tel', + 'address-line1', + 'address-level2', + 'address-level1', + 'postal-code', + 'country-name', + 'given-name', + ]); + }); + + it('skips card, one-time code and password inputs', () => { + const tokens = scan.fields.map((f) => f.autocomplete); + expect(tokens).not.toContain('cc-number'); + expect(tokens).not.toContain('one-time-code'); + expect(tokens).not.toContain('current-password'); + }); +}); + +describe('scanForm: prefilled', () => { + const { scan } = scanForm(load('prefilled.html')); + + it('reads the values', () => { + expect(scan.fields).toHaveLength(4); + expect(scan.fields[0]?.value).toBe('someone@example.com'); + expect(scan.fields[1]?.value).toBe('555-0100'); + expect(scan.fields[2]?.control).toBe('select'); + expect(scan.fields[2]?.value).toBe('Yes'); + }); + + it('reads the radio group', () => { + const group = scan.fields[3]; + expect(group?.control).toBe('choice_group'); + expect(group?.options).toEqual(['Yes', 'No']); + expect(group?.checked).toEqual([1]); + expect(group?.multiple).toBe(false); + }); + + it('leaves out the read-only and disabled inputs', () => { + const text = JSON.stringify(scan); + expect(text).not.toContain('REF-1'); + expect(text).not.toContain('locked'); + }); +}); + +describe('scanForm: elements line up', () => { + it.each(FIXTURES)('%s', (name) => { + const { scan, elements } = scanForm(load(name)); + expect(elements).toHaveLength(scan.fields.length); + scan.fields.forEach((field, i) => { + expect(field.ref).toBe(i); + expect(elements[i]?.control).toBe(field.control); + if (field.control === 'select' || field.control === 'choice_group') { + expect(elements[i]?.options).toHaveLength(field.options.length); + } + }); + }); + + it('keeps a select placeholder out of both lists', () => { + const { scan, elements } = scanForm(load('lever-like.html')); + expect(scan.fields[6]?.options).toEqual(['Yes', 'No']); + expect( + elements[6]?.options.map((o) => (o as HTMLOptionElement).text), + ).toEqual(['Yes', 'No']); + }); + + it('puts the first group member in el', () => { + const { elements } = scanForm(load('prefilled.html')); + expect((elements[3]?.el as HTMLInputElement).value).toBe('yes'); + }); +}); + +describe('scanForm: hidden fields', () => { + it('skips fields hidden by an ancestor', () => { + const doc = parse(`
    + + +
    +
    +
    + +
    `); + expect(scanForm(doc).scan.fields.map((f) => f.label)).toEqual(['Six']); + }); + + it('keeps a file input that is hidden by display', () => { + const doc = parse( + '
    ', + ); + const { scan } = scanForm(doc); + expect(scan.fields).toHaveLength(1); + expect(scan.fields[0]?.control).toBe('file'); + }); +}); + +describe('scanForm: candidates and control', () => { + it('uses an allow list of input types', () => { + const doc = parse(`
    + + + + + + + + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields.map((f) => f.label)).toEqual([ + 'a', + 'b', + 'c', + 'd', + 'e', + 'f', + ]); + expect(scan.fields[3]?.control).toBe('date'); + }); + + it('treats aria-haspopup, aria-autocomplete and role as custom', () => { + const doc = parse(`
    + + + + + +
    `); + expect(scanForm(doc).scan.fields.map((f) => f.control)).toEqual([ + 'custom', + 'text', + 'text', + 'custom', + 'custom', + ]); + }); + + it('skips a field in a disabled fieldset', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields.map((f) => f.label)).toEqual(['b']); + }); + + it('skips new-password and cc- autocomplete, keeps the rest', () => { + const doc = parse(`
    + + + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields.map((f) => f.label)).toEqual(['d']); + expect(scan.fields[0]?.autocomplete).toBe('off'); + }); + + it('reads aria-required and trims values', () => { + const doc = parse( + '
    ', + ); + const { scan } = scanForm(doc); + expect(scan.fields[0]?.required).toBe(true); + expect(scan.fields[0]?.value).toBe('hi'); + expect(scan.fields[1]?.value).toBe(''); + }); + + it('reads a multi-select and a checked group of one', () => { + const doc = parse(`
    + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields[0]?.multiple).toBe(true); + expect(scan.fields[1]?.control).toBe('choice_group'); + expect(scan.fields[1]?.options).toEqual(['Agree']); + expect(scan.fields[1]?.checked).toEqual([0]); + }); + + it('falls back to the value attribute for an option label', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields[0]?.options).toEqual(['alpha', 'beta']); + }); + + it('gives a select with only a placeholder chosen an empty value', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields[0]?.value).toBe(''); + }); +}); + +describe('scanForm: caps', () => { + it('stops at 200 fields', () => { + const inputs = Array.from( + { length: 250 }, + (_, i) => ``, + ).join(''); + const { scan, elements } = scanForm(parse(`
    ${inputs}
    `)); + expect(scan.fields).toHaveLength(200); + expect(elements).toHaveLength(200); + expect(scan.truncated).toBe(true); + }); + + it('is not truncated at exactly 200 fields', () => { + const inputs = Array.from( + { length: 200 }, + (_, i) => ``, + ).join(''); + expect(scanForm(parse(`
    ${inputs}
    `)).scan.truncated).toBe( + false, + ); + }); + + it('cuts a select at 50 options in both lists', () => { + const options = Array.from( + { length: 80 }, + (_, i) => ``, + ).join(''); + const { scan, elements } = scanForm( + parse(`
    `), + ); + expect(scan.fields[0]?.options).toHaveLength(50); + expect(elements[0]?.options).toHaveLength(50); + expect(scan.fields[0]?.optionsTruncated).toBe(true); + }); + + it('cuts long values at 500 characters', () => { + const doc = parse( + `
    `, + ); + expect(scanForm(doc).scan.fields[0]?.value).toHaveLength(500); + }); +}); + +const GREENHOUSE_SRC = + 'https://job-boards.greenhouse.io/embed/job_app?for=exampleco&token=1234567&validityToken=abc'; + +describe('scanForm: the form choice', () => { + it('scans the application form and ignores the newsletter box', () => { + const { scan, elements } = scanForm(load('two-forms.html')); + expect(scan.fields).toHaveLength(4); + expect(elements).toHaveLength(4); + expect(scan.fields.filter((f) => f.label === 'Email')).toHaveLength(1); + }); + + it('picks the first form on a tie', () => { + const doc = parse(`
    + +
    + +
    `); + expect(scanForm(doc).scan.fields.map((f) => f.label)).toEqual(['A1', 'A2']); + }); + + it('scans the whole document when there is no form', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields.map((f) => f.label)).toEqual(['A', 'B']); + }); + + it('finds nothing on a posting page with only a search box', () => { + const { scan } = scanForm(load('no-form.html')); + expect(scan.fields).toEqual([]); + expect(scan.frames).toEqual([]); + }); + + it('forms a group only from members inside the chosen form', () => { + const doc = parse(`
    + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields).toHaveLength(3); + expect(scan.fields[2]?.options).toEqual(['x', 'y']); + }); + + it('plans the referee block as four ambiguous rows', () => { + const sam: PlanInput = { + profile: { full_name: 'Sam Example', email: 'sam@example.com' }, + answers: [], + }; + const { scan } = scanForm(load('referee-block.html')); + expect(scan.fields.map((f) => f.label)).toEqual([ + 'Name', + 'Email', + 'Name', + 'Email', + ]); + const plan = buildPlan(scan, sam); + expect(plan.rows).toHaveLength(4); + for (const row of plan.rows) { + expect(row.status).toBe('not_filled'); + expect(row.reason).toBe('ambiguous'); + } + expect(plan.writes).toEqual([]); + }); +}); + +describe('scanForm: frames', () => { + it('reports the Greenhouse embed and no fields', () => { + const { scan } = scanForm(load('embed-greenhouse.html')); + expect(scan.frames).toEqual([GREENHOUSE_SRC]); + expect(scan.fields).toEqual([]); + }); + + it('reports the Ashby embed', () => { + const { scan } = scanForm(load('embed-ashby.html')); + expect(scan.frames).toEqual([ + 'https://jobs.ashbyhq.com/exampleco/0000?embed=js', + ]); + }); + + it('reports every known frame host', () => { + const frames = Array.from(FRAME_HOSTS.keys()).map( + (host) => ``, + ); + const { scan } = scanForm(parse(frames.join(''))); + expect(scan.frames).toHaveLength(FRAME_HOSTS.size); + }); + + it('stops at five frames', () => { + const frames = Array.from( + { length: 6 }, + (_, i) => ``, + ).join(''); + expect(scanForm(parse(frames)).scan.frames).toHaveLength(5); + }); + + it('resolves a relative src and skips other protocols and no src', () => { + const doc = parse(` + + + + `); + expect(scanForm(doc).scan.frames).toEqual([ + 'https://boards.greenhouse.io/embed/job_app?for=a', + ]); + }); + + it('cuts a long src at 2,000 characters', () => { + const doc = parse( + ``, + ); + expect(scanForm(doc).scan.frames[0]).toHaveLength(2000); + }); + + it('finds frames outside the chosen form', () => { + const doc = parse( + `
    `, + ); + expect(scanForm(doc).scan.frames).toEqual([GREENHOUSE_SRC]); + }); +}); + +function labels(html: string): string[] { + return scanForm(parse(`
    ${html}
    `)).scan.fields.map( + (f) => f.label, + ); +} + +describe('scanForm: fix round 1, skips', () => { + it('skips when any autocomplete token is blocked', () => { + expect( + labels(` + + + + + `), + ).toEqual(['e']); + }); + + it('still reports the last token as autocomplete', () => { + const doc = parse( + '
    ', + ); + expect(scanForm(doc).scan.fields[0]?.autocomplete).toBe('given-name'); + }); + + it('skips aria-hidden in any case or padding', () => { + expect( + labels(` + + + `), + ).toEqual(['c']); + }); + + it('reads role tokens for combobox', () => { + const doc = parse(`
    + + + +
    `); + expect(scanForm(doc).scan.fields.map((f) => f.control)).toEqual([ + 'custom', + 'custom', + 'text', + ]); + }); + + it('leaves out inputs of types the allow list lacks', () => { + expect( + labels(` + + + + + + + `), + ).toEqual(['g']); + }); + + it('does not trim the type attribute', () => { + expect( + labels(` + + + `), + ).toEqual(['c']); + }); + + it('keeps a file input under a display:none ancestor', () => { + const { scan } = scanForm( + parse( + '
    ', + ), + ); + expect(scan.fields.map((f) => f.control)).toEqual(['file']); + }); +}); + +describe('scanForm: fix round 1, defaults', () => { + it('pins values for custom, file and date', () => { + const { scan } = scanForm( + parse(`
    + + + +
    `), + ); + expect(scan.fields.map((f) => [f.control, f.value])).toEqual([ + ['custom', ''], + ['file', ''], + ['date', '2026-12-01'], + ]); + expect(toFormScan(scan)).toEqual(scan); + }); + + it('trims again after cutting a value', () => { + const value = `${'x'.repeat(499)} y`; + const { scan } = scanForm( + parse(`
    `), + ); + expect(scan.fields[0]?.value).toBe('x'.repeat(499)); + expect(toFormScan(scan)).toEqual(scan); + }); +}); + +describe('scanForm: fix round 1, groups and options', () => { + it('cuts a 60 member checkbox group at 50', () => { + const members = Array.from( + { length: 60 }, + (_, i) => ``, + ).join(''); + const { scan, elements } = scanForm(parse(`
    ${members}
    `)); + expect(scan.fields).toHaveLength(1); + expect(scan.fields[0]?.options).toHaveLength(50); + expect(scan.fields[0]?.optionsTruncated).toBe(true); + expect(elements[0]?.options).toHaveLength(50); + expect(toFormScan(scan)).toEqual(scan); + }); + + it('lists every checked radio', () => { + const { scan } = scanForm( + parse(`
    + + + +
    `), + ); + expect(scan.fields[0]?.checked).toEqual([0, 2]); + }); + + it('makes two groups of a radio and a checkbox sharing a name', () => { + const { scan } = scanForm( + parse(`
    + + + +
    `), + ); + expect(scan.fields).toHaveLength(2); + expect(scan.fields.map((f) => f.options)).toEqual([['a', 'c'], ['b']]); + expect(scan.fields.map((f) => f.multiple)).toEqual([false, true]); + }); + + it('leaves a disabled member out of the options', () => { + const { scan, elements } = scanForm( + parse(`
    + + + +
    `), + ); + expect(scan.fields[0]?.options).toEqual(['a', 'c']); + expect(elements[0]?.options).toHaveLength(2); + }); + + it('requires the group when any member is required', () => { + const { scan } = scanForm( + parse(`
    + + +
    `), + ); + expect(scan.fields[0]?.required).toBe(true); + }); + + it('cuts a select with a placeholder and 60 options at 50', () => { + const options = Array.from( + { length: 60 }, + (_, i) => ``, + ).join(''); + const { scan, elements } = scanForm( + parse( + `
    `, + ), + ); + const field = scan.fields[0]; + expect(field?.options).toHaveLength(50); + expect(field?.options[0]).toBe('Option 0'); + expect(field?.optionsTruncated).toBe(true); + expect(elements[0]?.options).toHaveLength(50); + }); + + it('leaves disabled options and disabled optgroups out of both lists', () => { + const { scan, elements } = scanForm( + parse(`
    `), + ); + expect(scan.fields[0]?.options).toEqual(['Alpha', 'Delta']); + expect( + elements[0]?.options.map((o) => (o as HTMLOptionElement).text), + ).toEqual(['Alpha', 'Delta']); + }); +}); + +describe('scanForm: validation', () => { + it.each(FIXTURES)('%s passes toFormScan unchanged', (name) => { + const { scan } = scanForm(load(name)); + expect(toFormScan(scan)).toEqual(scan); + }); +}); + +describe('scanForm: visually hidden fields', () => { + function count(html: string): number { + return scanForm(parse(`
    ${html}
    `)).scan.fields.length; + } + + function stubBox( + doc: Document, + selector: string, + box: Partial, + ): void { + const el = doc.querySelector(selector) as Element; + const full = { + left: 0, + top: 0, + right: 0, + bottom: 0, + width: 0, + height: 0, + ...box, + }; + el.getBoundingClientRect = () => full as DOMRect; + } + + it('keeps an ordinary field', () => { + expect(count('')).toBe(1); + }); + + it('skips opacity:0 on the field', () => { + expect(count('')).toBe(0); + }); + + it('skips opacity:0 on an ancestor', () => { + expect(count('
    ')).toBe(0); + }); + + it.each([ + 'clip: rect(0px, 0px, 0px, 0px)', + 'clip: rect(1px, 1px, 1px, 1px)', + 'clip-path: inset(50%)', + 'clip-path: inset(100%)', + ])('skips %s', (style) => { + expect(count(``)).toBe(0); + }); + + it('skips a field with a 1px computed size', () => { + expect(count('')).toBe(0); + }); + + it('skips a select that is opacity:0', () => { + expect(count('')).toBe( + 0, + ); + }); + + it('skips a tiny laid-out box', () => { + const doc = parse('
    '); + stubBox(doc, '#t', { + left: 10, + top: 10, + right: 11, + bottom: 30, + width: 1, + height: 20, + }); + expect(scanForm(doc).scan.fields).toHaveLength(0); + }); + + it('skips a box left of the page', () => { + const doc = parse('
    '); + stubBox(doc, '#t', { + left: -10200, + top: 10, + right: -10000, + bottom: 30, + width: 200, + height: 20, + }); + expect(scanForm(doc).scan.fields).toHaveLength(0); + }); + + it('skips a box above the page', () => { + const doc = parse('
    '); + stubBox(doc, '#t', { + left: 10, + top: -5000, + right: 210, + bottom: -4980, + width: 200, + height: 20, + }); + expect(scanForm(doc).scan.fields).toHaveLength(0); + }); + + it('keeps a normal laid-out box', () => { + const doc = parse('
    '); + stubBox(doc, '#t', { + left: 10, + top: 10, + right: 210, + bottom: 30, + width: 200, + height: 20, + }); + expect(scanForm(doc).scan.fields).toHaveLength(1); + }); + + it('still scans a radio group with opacity:0 members', () => { + const { scan } = scanForm( + parse(`
    + + +
    `), + ); + expect(scan.fields).toHaveLength(1); + expect(scan.fields[0]?.options).toEqual(['a', 'b']); + }); +}); + +describe('scanForm: a checked radio that is not a candidate', () => { + function outcome(hiddenMember: string): number { + const { scan, elements } = scanForm( + parse(`
    + + + ${hiddenMember} +
    `), + ); + expect(elements).toHaveLength(scan.fields.length); + return scan.fields.length; + } + + it('leaves the group out when a disabled member is checked', () => { + expect( + outcome(''), + ).toBe(0); + }); + + it('leaves the group out when a display:none member is checked', () => { + expect( + outcome( + '', + ), + ).toBe(0); + }); + + it('leaves the group out when a readonly member is checked', () => { + expect( + outcome(''), + ).toBe(0); + }); + + it('keeps the group when the non-candidate member is unchecked', () => { + expect(outcome('')).toBe( + 1, + ); + }); + + it('ignores a checked radio of the same name in another form', () => { + const { scan } = scanForm( + parse(`
    + + +
    `), + ); + expect(scan.fields).toHaveLength(1); + }); + + it('produces no write in the plan', () => { + const { scan } = scanForm( + parse(`
    + + + +
    `), + ); + expect(scan.fields.some((f) => f.control === 'choice_group')).toBe(false); + }); +}); + +describe('scanForm: fix round 1, parents, unrendered fields, form owners', () => { + type Box = Partial; + const rectOf = (box: Box): DOMRect => + ({ + left: 0, + top: 0, + right: 0, + bottom: 0, + width: 0, + height: 0, + ...box, + }) as DOMRect; + + function stubBox(doc: Document, selector: string, box: Box): void { + const el = doc.querySelector(selector) as Element; + el.getBoundingClientRect = () => rectOf(box); + } + + function fieldCount(doc: Document): number { + return scanForm(doc).scan.fields.length; + } + + it('skips a field in an sr-only wrapper', () => { + const doc = parse( + `
    `, + ); + expect(fieldCount(doc)).toBe(0); + }); + + it('skips a field in a collapsed accordion', () => { + const doc = parse( + `
    `, + ); + expect(fieldCount(doc)).toBe(0); + }); + + it('skips a field in a laid-out wrapper of 1px that clips', () => { + const doc = parse( + `
    `, + ); + stubBox(doc, '#w', { + left: 5, + top: 5, + right: 205, + bottom: 5, + width: 200, + height: 0, + }); + stubBox(doc, '#t', { + left: 5, + top: 5, + right: 205, + bottom: 25, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }); + + it('keeps a field in a small wrapper that does not clip', () => { + const doc = parse( + `
    `, + ); + expect(fieldCount(doc)).toBe(1); + }); + + it('skips a field when checkVisibility says it is not visible', () => { + const doc = parse('
    '); + ( + doc.querySelector('#t') as unknown as { checkVisibility: () => boolean } + ).checkVisibility = () => false; + expect(fieldCount(doc)).toBe(0); + }); + + it('skips a field with no client rects when checkVisibility exists', () => { + const doc = parse('
    '); + const el = doc.querySelector('#t') as unknown as { + checkVisibility: () => boolean; + getClientRects: () => unknown[]; + }; + el.checkVisibility = () => true; + el.getClientRects = () => []; + expect(fieldCount(doc)).toBe(0); + }); + + it('skips a text field inside a closed details when it is unrendered', () => { + const doc = parse( + '
    s
    ', + ); + const el = doc.querySelector('#t') as unknown as { + checkVisibility: () => boolean; + }; + el.checkVisibility = () => false; + expect(fieldCount(doc)).toBe(0); + }); + + it('asks checkVisibility without opacityProperty for a radio, and skips it when unrendered', () => { + const doc = parse( + '
    ', + ); + const el = doc.querySelector('#t') as unknown as { + checkVisibility: (o: Record) => boolean; + }; + let seen: Record = {}; + el.checkVisibility = (o) => { + seen = o; + return false; + }; + expect(fieldCount(doc)).toBe(0); + expect(seen.opacityProperty).toBeUndefined(); + expect(seen).not.toHaveProperty('contentVisibilityAuto'); + }); + + it('does not pass contentVisibilityAuto to checkVisibility for a text field', () => { + const doc = parse('
    '); + const el = doc.querySelector('#t') as unknown as { + checkVisibility: (o: Record) => boolean; + }; + let seen: Record | undefined; + el.checkVisibility = (o) => { + seen = o; + return true; + }; + expect(fieldCount(doc)).toBe(1); + expect(seen).toBeDefined(); + expect(seen).not.toHaveProperty('contentVisibilityAuto'); + }); + + it('keeps a field when body clips overflow and has a zero-height rect', () => { + const doc = parse('
    '); + doc.body.style.overflowX = 'hidden'; + stubBox(doc, 'body', { + left: 0, + top: 0, + right: 800, + bottom: 0, + width: 800, + height: 0, + }); + stubBox(doc, '#t', { + left: 10, + top: 10, + right: 210, + bottom: 30, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('keeps a field inside an inline span with overflow hidden', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 10, + top: 10, + right: 10, + bottom: 10, + width: 0, + height: 0, + }); + stubBox(doc, '#t', { + left: 10, + top: 10, + right: 210, + bottom: 30, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('skips a laid-out field in a 0x0 clipping wrapper at the page origin', () => { + // A real 0x0 box at the origin reads all zero, like happy-dom's no-layout box. + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 0, + right: 0, + bottom: 0, + width: 0, + height: 0, + }); + stubBox(doc, '#t', { + left: 0, + top: 0, + right: 200, + bottom: 20, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }); + + it('keeps a field scrolled out of view inside a scrolling box', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 400, + bottom: 500, + width: 400, + height: 400, + }); + stubBox(doc, '#t', { + left: 10, + top: 700, + right: 210, + bottom: 720, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('keeps a positioned field that sits outside a large clipping wrapper', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 400, + bottom: 300, + width: 400, + height: 200, + }); + stubBox(doc, '#t', { + left: 10, + top: 400, + right: 210, + bottom: 420, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('skips a field pushed outside a large overflow:hidden wrapper', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 300, + bottom: 130, + width: 300, + height: 30, + }); + stubBox(doc, '#t', { + left: 0, + top: 300, + right: 200, + bottom: 320, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }); + + it('skips an absolute field pushed outside its positioned clipping wrapper', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 300, + bottom: 130, + width: 300, + height: 30, + }); + stubBox(doc, '#t', { + left: 0, + top: 300, + right: 200, + bottom: 320, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }); + + it('skips an absolute field clipped by a positioned grandparent it escapes to', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#g', { + left: 0, + top: 100, + right: 300, + bottom: 130, + width: 300, + height: 30, + }); + stubBox(doc, '#t', { + left: 0, + top: 300, + right: 200, + bottom: 320, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }); + + it.each([ + ['fixed', 'transform:translateZ(0)'], + ['fixed', 'filter:blur(0px)'], + ['fixed', 'will-change:transform'], + ['absolute', 'transform:translateZ(0)'], + ['absolute', 'contain:layout'], + ])( + 'skips a %s field clipped by a wrapper that %s makes its containing block', + (position, rule) => { + const doc = parse( + `
    `, + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 300, + bottom: 130, + width: 300, + height: 30, + }); + stubBox(doc, '#t', { + left: 0, + top: 300, + right: 200, + bottom: 320, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }, + ); + + it('skips a field pushed out of a contain:paint wrapper', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 300, + bottom: 130, + width: 300, + height: 30, + }); + stubBox(doc, '#t', { + left: 0, + top: 300, + right: 200, + bottom: 320, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }); + + it('keeps a fixed field outside a plain clipping wrapper', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 300, + bottom: 130, + width: 300, + height: 30, + }); + stubBox(doc, '#t', { + left: 0, + top: 300, + right: 200, + bottom: 320, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('keeps an absolute field that escapes a tiny wrapper which is not its containing block', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 100, + right: 300, + bottom: 100, + width: 300, + height: 0, + }); + stubBox(doc, '#t', { + left: 0, + top: 100, + right: 200, + bottom: 120, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('skips a field in a laid-out 1px clipping wrapper away from it', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 0, + top: 0, + right: 1, + bottom: 1, + width: 1, + height: 1, + }); + stubBox(doc, '#t', { + left: 50, + top: 50, + right: 250, + bottom: 70, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(0); + }); + + it('keeps a field when a laid-out clipping wrapper intersects it', () => { + const doc = parse( + '
    ', + ); + stubBox(doc, '#w', { + left: 40, + top: 40, + right: 300, + bottom: 100, + width: 260, + height: 60, + }); + stubBox(doc, '#t', { + left: 50, + top: 50, + right: 250, + bottom: 70, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('judges the horizontal edge on a right-to-left page', () => { + const make = (left: number) => { + const doc = parse('
    '); + doc.documentElement.style.direction = 'rtl'; + Object.defineProperty(doc.documentElement, 'clientWidth', { + value: 1000, + configurable: true, + }); + Object.defineProperty(doc.defaultView, 'scrollX', { + value: -200, + configurable: true, + }); + stubBox(doc, '#t', { + left, + top: 10, + right: left + 200, + bottom: 30, + width: 200, + height: 20, + }); + return doc; + }; + // Page x = left + scrollX; the document's right edge is at clientWidth. + expect(fieldCount(make(900))).toBe(1); + expect(fieldCount(make(1300))).toBe(0); + }); + + it('keeps two same-name radios apart when one belongs to another form by attribute', () => { + const doc = parse( + `
    + + +
    `, + ); + expect(fieldCount(doc)).toBe(2); + }); + + it('is not blocked by a checked disabled peer when form points at no form', () => { + const doc = parse( + `
    + + + +
    `, + ); + expect(fieldCount(doc)).toBe(1); + }); + + it.each([ + 'inset(0px 50%)', + 'inset(0px 0px 100% 0px)', + 'inset(50% 0px 50% 0px)', + ])('skips clip-path %s', (path) => { + const doc = parse( + `
    `, + ); + expect(fieldCount(doc)).toBe(0); + }); + + it('keeps a small clip-path inset', () => { + const doc = parse( + '
    ', + ); + expect(fieldCount(doc)).toBe(1); + }); + + it('keeps a box left of the page on a right-to-left page', () => { + const doc = parse('
    '); + doc.documentElement.style.direction = 'rtl'; + stubBox(doc, '#t', { + left: -300, + top: 10, + right: -100, + bottom: 30, + width: 200, + height: 20, + }); + expect(fieldCount(doc)).toBe(1); + }); + + it('adds scrollY before judging a box above the page', () => { + const kept = parse('
    '); + Object.defineProperty(kept.defaultView, 'scrollY', { + value: 300, + configurable: true, + }); + stubBox(kept, '#t', { + left: 10, + top: -200, + right: 210, + bottom: -180, + width: 200, + height: 20, + }); + expect(fieldCount(kept)).toBe(1); + const near = parse('
    '); + Object.defineProperty(near.defaultView, 'scrollY', { + value: 300, + configurable: true, + }); + stubBox(near, '#t', { + left: 10, + top: -350, + right: 210, + bottom: -320, + width: 200, + height: 30, + }); + expect(fieldCount(near)).toBe(0); + const skipped = parse('
    '); + Object.defineProperty(skipped.defaultView, 'scrollY', { + value: 300, + configurable: true, + }); + stubBox(skipped, '#t', { + left: 10, + top: -420, + right: 210, + bottom: -400, + width: 200, + height: 20, + }); + expect(fieldCount(skipped)).toBe(0); + }); + + it('adds scrollX before judging a box left of the page', () => { + const kept = parse('
    '); + Object.defineProperty(kept.defaultView, 'scrollX', { + value: 300, + configurable: true, + }); + stubBox(kept, '#t', { + left: -400, + top: 10, + right: -200, + bottom: 30, + width: 200, + height: 20, + }); + expect(fieldCount(kept)).toBe(1); + const skipped = parse('
    '); + Object.defineProperty(skipped.defaultView, 'scrollX', { + value: 300, + configurable: true, + }); + stubBox(skipped, '#t', { + left: -600, + top: 10, + right: -400, + bottom: 30, + width: 200, + height: 20, + }); + expect(fieldCount(skipped)).toBe(0); + }); + + it('blocks a group for a checked disabled radio outside the form that belongs to it', () => { + const doc = parse(`
    + + +
    + `); + expect(fieldCount(doc)).toBe(0); + }); + + it('treats a radio inside one form with form="other" as another group', () => { + const doc = parse(`
    + + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields).toHaveLength(1); + expect(scan.fields[0]?.options).toEqual(['a', 'b']); + }); + + it('does not let a checked peer in another form block this form', () => { + const doc = parse(`
    + + +
    +
    + + +
    `); + const { scan } = scanForm(doc); + expect(scan.fields.map((f) => f.options)).toEqual([['a', 'b']]); + }); +}); diff --git a/shell/fill/page-session.test.ts b/shell/fill/page-session.test.ts new file mode 100644 index 0000000..1cf9f94 --- /dev/null +++ b/shell/fill/page-session.test.ts @@ -0,0 +1,59 @@ +// @vitest-environment happy-dom +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { Window } from 'happy-dom'; +import { describe, expect, it } from 'vitest'; +import { toApplyResult } from '../../core/src/fill/validate'; +import { createSession } from './page/session'; + +function load(name: string): Document { + const window = new Window({ url: 'https://example.com/jobs/1' }); + window.document.write( + readFileSync(join(import.meta.dirname, 'fixtures', name), 'utf8'), + ); + return window.document as unknown as Document; +} + +const WRITE = [{ ref: 0, kind: 'value', value: 'Sam Example' }]; + +describe('createSession', () => { + it('scan then apply writes the field and rescans', () => { + const session = createSession(load('lever-like.html')); + session.scan(); + const result = session.apply(WRITE); + expect(result.outcomes).toEqual([{ ref: 0, outcome: 'written' }]); + expect(result.scan.fields[0]?.value).toBe('Sam Example'); + }); + + it('reports every write as gone when apply runs before scan', () => { + const session = createSession(load('lever-like.html')); + const result = session.apply(WRITE); + expect(result.outcomes).toEqual([{ ref: 0, outcome: 'gone' }]); + expect(result.scan.fields.length).toBeGreaterThan(0); + }); + + it('a second scan replaces the elements', () => { + const doc = load('lever-like.html'); + const session = createSession(doc); + const first = session.scan(); + const firstId = first.fields[0]?.label; + const el = doc.querySelector('input[name="name"]'); + el?.remove(); + const second = session.scan(); + expect(second.fields.length).toBe(first.fields.length - 1); + const result = session.apply(WRITE); + expect(result.outcomes).toEqual([{ ref: 0, outcome: 'written' }]); + expect(result.scan.fields[0]?.value).toBe('Sam Example'); + expect(result.scan.fields[0]?.label).toBe(second.fields[0]?.label); + expect(result.scan.fields[0]?.label).not.toBe(firstId); + }); + + it('returns plain data that passes validation', () => { + const session = createSession(load('lever-like.html')); + session.scan(); + const result = session.apply(WRITE); + expect(toApplyResult(result)).toEqual(result); + expect(Object.keys(result).sort()).toEqual(['outcomes', 'scan']); + expect(Object.keys(session.scan())).not.toContain('elements'); + }); +}); diff --git a/shell/fill/page/apply.ts b/shell/fill/page/apply.ts new file mode 100644 index 0000000..585e6fe --- /dev/null +++ b/shell/fill/page/apply.ts @@ -0,0 +1,228 @@ +import { isPlaceholderOption } from '../../../core/src/fill/normalize'; +import { + MAX_FIELDS, + MAX_VALUE, + type WriteReport, +} from '../../../core/src/fill/types'; +import { notifyChanged } from './events'; +import { + controlOf, + hasCheckedPeer, + isCandidate, + type FieldElements, +} from './scan'; + +type Write = + | { ref: number; kind: 'value'; value: string } + | { ref: number; kind: 'option'; index: number }; + +const DATE_VALUE = /^\d{4}-\d{2}-\d{2}$/; + +function isRecord(entry: unknown): entry is Record { + return typeof entry === 'object' && entry !== null && !Array.isArray(entry); +} + +/** The write when its shape is right, otherwise null. The ref is checked by the caller. */ +function readWrite(entry: Record, ref: number): Write | null { + const kind = entry.kind; + if (kind === 'value') { + const value = entry.value; + if (typeof value !== 'string' || value.length > MAX_VALUE) return null; + return { ref, kind, value }; + } + if (kind === 'option') { + const index = entry.index; + if (typeof index !== 'number' || !Number.isInteger(index) || index < 0) { + return null; + } + return { ref, kind, index }; + } + return null; +} + +function isDisabled(el: Element): boolean { + return ( + el.hasAttribute('disabled') || el.closest('fieldset[disabled]') !== null + ); +} + +function isOptionDisabled(option: Element): boolean { + return ( + option.hasAttribute('disabled') || + option.closest('optgroup[disabled]') !== null + ); +} + +type Setter = (this: Element, value: never) => void; + +/** A property setter from the element's own window, or undefined. */ +function protoSetter( + el: Element, + ctor: 'HTMLInputElement' | 'HTMLTextAreaElement' | 'HTMLSelectElement', + property: 'value' | 'selectedIndex' | 'checked', +): Setter | undefined { + const view = el.ownerDocument.defaultView; + const proto = view?.[ctor]?.prototype; + if (!proto) return undefined; + // The setter is always called with .call on the element. + // eslint-disable-next-line @typescript-eslint/unbound-method + return Object.getOwnPropertyDescriptor(proto, property)?.set as + Setter | undefined; +} + +type Getter = (this: Element) => unknown; + +/** A property getter from the element's own window, or undefined. */ +function protoGetter( + el: Element, + ctor: 'HTMLInputElement' | 'HTMLTextAreaElement' | 'HTMLSelectElement', + property: 'value' | 'selectedIndex' | 'checked', +): Getter | undefined { + const view = el.ownerDocument.defaultView; + const proto = view?.[ctor]?.prototype; + if (!proto) return undefined; + // The getter is always called with .call on the element. + // eslint-disable-next-line @typescript-eslint/unbound-method + return Object.getOwnPropertyDescriptor(proto, property)?.get as + Getter | undefined; +} + +/** The scan's own test, run again: still a candidate and still the same kind of control. */ +function stillFillable(el: Element, control: string): boolean { + return isCandidate(el) && controlOf(el) === control; +} + +function applyOne( + fe: FieldElements | undefined, + write: Write, +): WriteReport['outcome'] { + if (!fe || !fe.el.isConnected) return 'gone'; + const { control, el } = fe; + + if (control === 'text' || control === 'textarea' || control === 'date') { + if (write.kind !== 'value') return 'failed'; + if (isDisabled(el) || el.hasAttribute('readonly')) return 'failed'; + if (control === 'date' && !DATE_VALUE.test(write.value)) return 'failed'; + if (!stillFillable(el, control)) return 'gone'; + const setter = protoSetter( + el, + el.localName === 'textarea' ? 'HTMLTextAreaElement' : 'HTMLInputElement', + 'value', + ); + if (!setter) return 'failed'; + if ((el as HTMLInputElement).value !== '') return 'not_empty'; + const ctor = + el.localName === 'textarea' ? 'HTMLTextAreaElement' : 'HTMLInputElement'; + const getter = protoGetter(el, ctor, 'value'); + if (!getter) return 'failed'; + setter.call(el, write.value as never); + // A browser may sanitise the value, and a text area stores line breaks as LF. + const stored = getter.call(el); + const expected = + control === 'textarea' + ? write.value.replace(/\r\n?/g, '\n') + : write.value; + if (stored !== write.value && stored !== expected) { + // The field was empty before, so put it back. No events. + setter.call(el, '' as never); + return 'failed'; + } + notifyChanged(el); + return 'written'; + } + + if (control === 'select') { + if (write.kind !== 'option') return 'failed'; + if (el.localName !== 'select') return 'failed'; + if (isDisabled(el) || el.hasAttribute('readonly')) return 'failed'; + const option = fe.options[write.index]; + if (!option || option.localName !== 'option') return 'failed'; + if (isOptionDisabled(option)) return 'failed'; + const select = el as HTMLSelectElement; + const optionIndex = (option as HTMLOptionElement).index; + if (select.options[optionIndex] !== option) return 'gone'; + if (!stillFillable(el, control)) return 'gone'; + const setter = protoSetter(el, 'HTMLSelectElement', 'selectedIndex'); + const getter = protoGetter(el, 'HTMLSelectElement', 'selectedIndex'); + if (!setter || !getter) return 'failed'; + const chosen = select.options[select.selectedIndex]; + if ( + chosen && + !isPlaceholderOption(chosen.text, chosen.value, chosen.index) + ) { + return 'not_empty'; + } + const previous = getter.call(el) as number; + setter.call(el, optionIndex as never); + if (getter.call(el) !== optionIndex) { + setter.call(el, previous as never); + return 'failed'; + } + notifyChanged(el); + return 'written'; + } + + if (control === 'choice_group') { + if (write.kind !== 'option') return 'failed'; + if (isDisabled(el) || el.hasAttribute('readonly')) return 'failed'; + const member = fe.options[write.index]; + if (!member || member.localName !== 'input') return 'failed'; + if (isDisabled(member)) return 'failed'; + if (!member.isConnected) return 'gone'; + if (!stillFillable(el, control) || !isCandidate(member)) return 'gone'; + const name = member.getAttribute('name') ?? ''; + if ( + name !== '' && + (member as HTMLInputElement).type === 'radio' && + hasCheckedPeer(member as HTMLInputElement, name) + ) { + return 'gone'; + } + const setter = protoSetter(member, 'HTMLInputElement', 'checked'); + const getter = protoGetter(member, 'HTMLInputElement', 'checked'); + if (!setter || !getter) return 'failed'; + const anyChecked = fe.options.some( + (m) => (m as HTMLInputElement).checked === true, + ); + if (anyChecked) return 'not_empty'; + setter.call(member, true as never); + if (getter.call(member) !== true) { + setter.call(member, false as never); + return 'failed'; + } + notifyChanged(member); + return 'written'; + } + + return 'failed'; +} + +/** Sets the given values into empty fields. Never replaces a value. */ +export function applyWrites( + elements: readonly FieldElements[], + writes: unknown, +): WriteReport[] { + if (!Array.isArray(writes)) return []; + const reports: WriteReport[] = []; + const count = Math.min(writes.length, MAX_FIELDS); + for (let i = 0; i < count; i++) { + let ref: number | undefined; + try { + const entry: unknown = writes[i]; + if (!isRecord(entry)) continue; + const rawRef = entry.ref; + if (typeof rawRef !== 'number' || !Number.isInteger(rawRef)) continue; + ref = rawRef; + const write = readWrite(entry, ref); + if (!write) { + reports.push({ ref, outcome: 'failed' }); + continue; + } + const fe = ref >= 0 ? elements[ref] : undefined; + reports.push({ ref, outcome: applyOne(fe, write) }); + } catch { + if (ref !== undefined) reports.push({ ref, outcome: 'failed' }); + } + } + return reports; +} diff --git a/shell/fill/page/events.ts b/shell/fill/page/events.ts new file mode 100644 index 0000000..33b70d2 --- /dev/null +++ b/shell/fill/page/events.ts @@ -0,0 +1,5 @@ +// Tells the page that a field's value was set by the extension. +export function notifyChanged(el: Element): void { + el.dispatchEvent(new Event('input', { bubbles: true })); + el.dispatchEvent(new Event('change', { bubbles: true })); +} diff --git a/shell/fill/page/label.ts b/shell/fill/page/label.ts new file mode 100644 index 0000000..163a202 --- /dev/null +++ b/shell/fill/page/label.ts @@ -0,0 +1,159 @@ +import { MAX_LABEL } from '../../../core/src/fill/types'; + +// Finds the question text for a field or a group of fields. Reads the DOM only. + +const SKIPPED = new Set([ + 'input', + 'select', + 'textarea', + 'button', + 'option', + 'script', + 'style', +]); +const FIELDS = 'input, select, textarea'; +const GROUP_ANCESTOR = 'fieldset, [role="group"], [role="radiogroup"]'; + +function tidy(raw: string): string { + return raw.replace(/\s+/g, ' ').trim().slice(0, MAX_LABEL).trim(); +} + +function collect( + node: Node, + left: ReadonlySet, + parts: string[], +): void { + for (const child of Array.from(node.childNodes)) { + if (child.nodeType === 3) { + parts.push(child.textContent ?? ''); + } else if (child.nodeType === 1) { + const el = child as Element; + if (!SKIPPED.has(el.localName) && !left.has(el)) { + collect(el, left, parts); + } + } + } +} + +function textOf(node: Node, left: ReadonlySet = new Set()): string { + const parts: string[] = []; + collect(node, left, parts); + return tidy(parts.join(' ')); +} + +function labelledBy(el: Element): string { + const ids = (el.getAttribute('aria-labelledby') ?? '') + .split(/\s+/) + .filter((id) => id !== ''); + const texts: string[] = []; + for (const id of ids) { + const target = el.ownerDocument.getElementById(id); + if (target) texts.push(textOf(target)); + } + return tidy(texts.filter((t) => t !== '').join(' ')); +} + +function labelsFor(el: Element): Element[] { + const id = el.getAttribute('id') ?? ''; + if (id === '') return []; + return Array.from(el.ownerDocument.querySelectorAll('label')).filter( + (label) => label.getAttribute('for') === id, + ); +} + +function isRoot(el: Element): boolean { + return el.localName === 'form' || el.localName === 'body'; +} + +function holdsOther( + container: Element, + allowed: readonly Element[], + isCandidate: (other: Element) => boolean, +): boolean { + return Array.from(container.querySelectorAll(FIELDS)).some( + (other) => !allowed.includes(other) && isCandidate(other), + ); +} + +// Climbs from the field's parent. Only empty containers are passed over; the +// first one with text wins; one that holds another candidate ends the search. +function containerText( + start: Element | null, + members: readonly Element[], + isCandidate: (other: Element) => boolean, + left: ReadonlySet, +): string { + for (let cur = start; cur && !isRoot(cur); cur = cur.parentElement) { + if (holdsOther(cur, members, isCandidate)) return ''; + if ( + Array.from(left).some((label) => label.contains(cur)) || + !members.every((m) => cur.contains(m)) + ) { + continue; + } + const text = textOf(cur, left); + if (text !== '') return text; + } + return ''; +} + +export function fieldLabel( + el: Element, + isCandidate: (other: Element) => boolean, +): string { + const named = labelledBy(el); + if (named !== '') return named; + + for (const label of labelsFor(el)) { + const text = textOf(label); + if (text !== '') return text; + } + + const wrapping = el.closest('label'); + if (wrapping) { + const text = textOf(wrapping); + if (text !== '') return text; + } + + const aria = tidy(el.getAttribute('aria-label') ?? ''); + if (aria !== '') return aria; + + return containerText(el.parentElement, [el], isCandidate, new Set()); +} + +export function groupLabel( + members: readonly Element[], + isCandidate: (other: Element) => boolean, +): string { + const first = members[0]; + if (!first) return ''; + + for ( + let cur = first.parentElement; + cur && !isRoot(cur); + cur = cur.parentElement + ) { + if (!cur.matches(GROUP_ANCESTOR)) continue; + if (!members.every((m) => cur.contains(m))) continue; + if (holdsOther(cur, members, isCandidate)) continue; + const named = labelledBy(cur); + if (named !== '') return named; + const aria = tidy(cur.getAttribute('aria-label') ?? ''); + if (aria !== '') return aria; + if (cur.localName === 'fieldset') { + const legend = Array.from(cur.children).find( + (child) => child.localName === 'legend', + ); + const text = legend ? textOf(legend) : ''; + if (text !== '') return text; + } + } + + const left = new Set(); + for (const member of members) { + const wrapping = member.closest('label'); + if (wrapping) left.add(wrapping); + for (const label of labelsFor(member)) left.add(label); + } + return containerText(first.parentElement, members, isCandidate, left); +} diff --git a/shell/fill/page/scan.ts b/shell/fill/page/scan.ts new file mode 100644 index 0000000..b7ec5b2 --- /dev/null +++ b/shell/fill/page/scan.ts @@ -0,0 +1,663 @@ +import { isPlaceholderOption } from '../../../core/src/fill/normalize'; +import { FRAME_HOSTS } from '../../../core/src/fill/site'; +import { + MAX_AUTOCOMPLETE, + MAX_FIELDS, + MAX_FRAMES, + MAX_FRAME_SRC, + MAX_LABEL, + MAX_OPTIONS, + MAX_VALUE, + type ControlKind, + type FormScan, + type ScannedField, +} from '../../../core/src/fill/types'; +import { fieldLabel, groupLabel } from './label'; + +export interface FieldElements { + control: ControlKind; + /** The element, or the first member of a group. */ + el: Element; + /** The