@trawlme/skills 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,7 +48,9 @@ npm install -g @trawlme/cli
48
48
  trawl skills install
49
49
  ```
50
50
 
51
- The CLI bundles the skills and keeps them in sync with the CLI version.
51
+ The CLI bundles the skills and keeps them in sync with the CLI version — every `trawl` command re-syncs a skill whose installed version drifts from the CLI's.
52
+
53
+ Since `@trawlme/cli` 3.10, `trawl login` also installs any bundled skill you don't already have when run interactively — no separate `trawl skills install` needed. It prints exactly what it installed, plus the one thing you have to do yourself: **restart Claude Code**, since skills are only picked up at session start.
52
54
 
53
55
  ## Migrating from v0.1.x
54
56
 
@@ -66,6 +68,14 @@ Example prompts:
66
68
  - "scrape a site behind login without giving Trawl my credentials" (`trawl-scrap-account`)
67
69
  - "test my scrap locally before pushing" (`trawl-scrap-local-test`)
68
70
 
71
+ ### Authenticated scraps: session capture
72
+
73
+ With `@trawlme/cli` 3.12 or later, `trawl-scrap-account` walks Claude through `trawl scraps account session capture <id>` for a site that needs a login — it opens a real, visible Chrome window at the scrap's target URL, you log in there exactly as you normally would (2FA included), and the CLI reads the resulting session over the Chrome DevTools Protocol (cookies and per-origin localStorage) and uploads it. No manual cookie export.
74
+
75
+ > You stay authenticated as yourself throughout — Trawl never sees your credentials, only the resulting session. Responsibility for lawful use of that session stays with you; this isn't legal advice.
76
+
77
+ This needs a local interactive terminal with a real display — it doesn't work headless, in CI, or over a plain SSH session. `session set -c <file>` (manual cookie upload) remains the fallback when capture can't run.
78
+
69
79
  ## Commands
70
80
 
71
81
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trawlme/skills",
3
- "version": "1.4.2",
3
+ "version": "1.4.4",
4
4
  "description": "Claude Code skills for the Trawl CLI — teaches Claude how to manage scraps via @trawlme/cli",
5
5
  "type": "module",
6
6
  "bin": {
@@ -199,7 +199,7 @@ trawl scraps rm <id> # `rm` is an alias for `delete`, same
199
199
 
200
200
  ## Scrap accounts
201
201
 
202
- For per-scrap authentication, see the `trawl-scrap-account` skill. CLI commands: `trawl scraps account set/status/clear-session/delete`, plus `trawl scraps account session set <id>` (upload BYO-cookies).
202
+ For per-scrap authentication, see the `trawl-scrap-account` skill. CLI commands: `trawl scraps account set/status/clear-session/delete`, plus `trawl scraps account session capture <id>` (one-command login capture — the primary path) and `trawl scraps account session set <id> -c <file>` (manual upload — the fallback).
203
203
 
204
204
  ## MCP bridge
205
205
 
@@ -212,7 +212,7 @@ TOKEN=$(trawl token)
212
212
 
213
213
  # MCP endpoint — accepts the session JWT as a Bearer token. This is a real,
214
214
  # runnable JSON-RPC 2.0 call (tools/list) against the Streamable HTTP
215
- # transport — verified against trawl_node's mcp.controller.js:
215
+ # transport — verified end-to-end against a live server:
216
216
  curl --fail-with-body -X POST https://api.trawl.me/api/mcp \
217
217
  -H "Authorization: Bearer $TOKEN" \
218
218
  -H "Content-Type: application/json" \
@@ -256,6 +256,12 @@ Note: the CLI surfaces the abstract proxy Tier (0–4) + diagnostics + autofix,
256
256
 
257
257
  **`snapshot -o <file>` on a never-run scrap (since CLI 1.18.4):** without `--json`, this now exits `4` (`not_found`) instead of silently exiting `0` with nothing written — before 1.18.4 a script checking only the exit code couldn't tell "no file was produced" from success. `--json` takes priority when both flags are passed together.
258
258
 
259
+ **`failureKind: 'auth'` — the target site wants a login, not you.** `doctor`/`run-info`/`history` can show this on a run: the worker landed on a known login route and the run came back empty — the SITE is asking for a session, not blocking the request outright. Node ranks a worker-flagged block ABOVE this (precedence is block > auth > selector > nav > empty): `auth` only fires on an empty run that is NOT also block-flagged. Once it does fire, it skips auto-fix (a selector rewrite can never clear a login wall). Treat it as a distinct case from a blocked/wall run, not a subtype of one:
260
+ - **Send the user to the `trawl-scrap-account` skill**, not to a "no reliable bypass" explanation. The fix is that skill's `session capture` command, not a selector rewrite or a proxy-tier bump.
261
+ - A run can carry BOTH `failureKind: 'auth'` and a matched vendor wall when the vendor is one the server's block classifier doesn't yet recognize by name — e.g. `block.kind` naming Kasada. The server's block classifier and the CLI's own vendor list (`WALL_VENDOR_PATTERNS` in `doctor.ts`) are maintained separately: the CLI's list matches Kasada and reports a wall, but the server's classifier doesn't recognize it, so the block flag never gets set and `auth` still fires on the same run instead of `block` pre-empting it. For every vendor the server's classifier DOES match (Akamai, Cloudflare, DataDome, PerimeterX), `block` always wins first and the two never coexist. Don't collapse the Kasada case into one story — state both readings rather than choosing, the same way `doctor` hedges instead of asserting one.
262
+
263
+ **Don't confuse this with the CLI's own `kind: 'auth'`** (Errors to recognize / Exit codes below). The `--json` error envelope's `kind` field means **your Trawl session** is the problem — an expired or missing JWT, exit `3` — and the fix is `trawl login`. `failureKind: 'auth'` on a *run* means the **scraped site** wants credentials — the fix is `trawl scraps account session capture <id>` (see `trawl-scrap-account`). Same string, two unrelated axes (this CLI's own auth vs. the target site's auth) on two different objects (a thrown CLI error vs. a persisted run) — sending someone to `trawl login` for a `failureKind:'auth'` run fixes nothing.
264
+
259
265
  **"Create a job that runs every morning"**
260
266
  ```bash
261
267
  trawl scraps create -t "Morning crawl" -u "https://..." -d "Daily crawl at 8am" -r '...'
@@ -19,7 +19,7 @@ Injecting cookies does not change the worker's fingerprint policy.
19
19
 
20
20
  2. **One-shot test or short-lived experiment, or you want to verify your cookies work before setting up persistence** → use **Flavour A — Embedded BYO-cookies**. Hard-code the cookie array directly in the script body. Accepts the trade-off that cookies are in plain text in the script source.
21
21
 
22
- 3. **MFA, SSO, OAuth, or you don't want to hand credentials to Trawl** → use **Flavour B — Persisted BYO-cookies**. Export cookies from a logged-in browser session, push them into `TRAWL.account.session.cookies` via UI, CLI, or API, and the script reads them back before navigation. Cookies are encrypted at rest.
22
+ 3. **MFA, SSO, OAuth, or you don't want to hand credentials to Trawl** → use **Flavour B — Persisted BYO-cookies**. Run `trawl scraps account session capture <scrap-id>` locally: it opens a real Chrome, you log in exactly as you normally would (2FA included), and the CLI reads the resulting session over CDP and uploads it — no manual export. Manual upload (`session set -c <file>`) still exists as a fallback. Cookies (and localStorage) are encrypted at rest.
23
23
 
24
24
  ## Trawl-managed credentials (server-stored, still supported)
25
25
 
@@ -28,19 +28,22 @@ The worker injects the account credentials under `TRAWL.account`:
28
28
  - `TRAWL.account.username` — the username stored for this scrap account (alias: `account.username`).
29
29
  - `TRAWL.account.password` — the password stored for this scrap account (alias: `account.password`).
30
30
 
31
- After a successful login, call `saveSession(await page.cookies())` immediately. The worker persists the cookie array encrypted at rest and exposes it as `TRAWL.account.session.cookies` on the next run.
31
+ The worker replays a stored session automatically, before your script's first navigation — your script never restores cookies itself (don't call `page.setCookie(...TRAWL.account.session.cookies)`; the worker already applied them via `browserContext.setCookie()`, and per-page `setCookie` is deprecated Puppeteer surface besides). Its job is to **detect whether the page is already logged in**, and only run the credential login flow when it isn't. After a successful login, call `saveSession(await page.cookies())` — the worker persists the cookie array encrypted at rest and replays it on the next run. This is a **cookies-only** refresh: it never touches or clears an `origins` (localStorage) block already saved via `session capture` or the web UI.
32
32
 
33
33
  > Legacy bare `account.*` (e.g. `account.username`) still works as an alias.
34
34
 
35
35
  ```js
36
36
  const page = await browser.newPage();
37
37
 
38
- if (TRAWL.account?.session?.cookies) {
39
- // Saved session exists — restore cookies and skip the login flow.
40
- await page.setCookie(...TRAWL.account.session.cookies);
41
- await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
42
- } else {
43
- // First run (or cleared session) — perform full login.
38
+ // The worker has already replayed any stored session onto this page.
39
+ // Check for a marker that only appears when logged in, rather than
40
+ // assuming a saved session means you're logged in.
41
+ // `domcontentloaded` fires before an SPA hydrates, so an immediate DOM query
42
+ // can read "not logged in" on a perfectly valid session — wait for the marker instead.
43
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
44
+ const loggedIn = await page.waitForSelector('.account-menu', { timeout: 10_000 }).then(() => true, () => false);
45
+
46
+ if (!loggedIn) {
44
47
  await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
45
48
  await page.type('#username', TRAWL.account.username);
46
49
  await page.type('#password', TRAWL.account.password);
@@ -80,25 +83,70 @@ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded'
80
83
 
81
84
  ## Flavour B — Persisted BYO-cookies
82
85
 
83
- Export cookies from a logged-in browser session. Three write paths exist for `TRAWL.account.session.cookies` (any one is fine; the scrap source reads them back identically):
86
+ ### The command: `session capture` (primary path)
84
87
 
85
- - **UI** (one-off / interactive): scrap settings drawer → Account section → **Upload session cookies** → paste a Puppeteer cookie JSON array → Save.
86
- - **CLI** (scripted / batch): `trawl scraps account session set <scrap-id> --cookies <file>` (npm `@trawlme/cli` ≥ 1.14.0).
87
- - **API** (custom tooling): `PUT /api/scraps/:scrapId/account/session` with body `{ cookies: [...] }`.
88
+ ```bash
89
+ trawl scraps account session capture <scrap-id>
90
+ ```
88
91
 
89
- The worker encrypts them at rest; the script reads the same global as the managed flow:
92
+ Opens a real, headed Chrome at the scrap's target URL. The user logs in there exactly as they normally would — password, MFA, SSO, whatever the site needs. **Enter back in the terminal is the reliable way to complete capture.** Closing the Chrome window also works, but only if Chrome's process survives that close (it captures cookies only then — never localStorage); if that window was the only one open and closing it quits Chrome entirely — the common case, especially on Linux — nothing is captured or uploaded at all. Tell the user to press Enter, not to close the window, when they actually want the localStorage half. The CLI then reads the session over CDP (cookies **and** per-origin localStorage) and uploads it via the same endpoint Flavour B always used (`PUT /api/scraps/:scrapId/account/session`). `--json` prints counts only, nested under `capture` (`capture.cookiesCaptured`, `capture.originsCaptured`), next to `account` and `targetDomain` — the session itself is never printed, in any mode.
90
93
 
91
- ```js
92
- if (!TRAWL.account?.session?.cookies) {
93
- throw new Error('Flavour B requires TRAWL.account.session.cookies — push them via UI / CLI / API first.');
94
- }
94
+ > You stay authenticated as yourself throughout — Trawl never sees your credentials, only the resulting session. Responsibility for lawful use of that session stays with you; this isn't legal advice.
95
+
96
+ Flags:
97
+ - `--chrome <path>` — a specific Chrome/Chromium executable. Auto-detected otherwise; `TRAWL_CHROME_PATH` (or `PUPPETEER_EXECUTABLE_PATH`/`CHROME_PATH`) names one explicitly, checked before the well-known per-OS install paths.
98
+ - `--json` — machine-readable summary, never the secret.
99
+
100
+ The scrap needs a target URL configured first (`trawl scraps update <id> -u <url>` if it doesn't have one — there's nothing to open a browser to otherwise). If login didn't actually complete on that domain before Enter/close, nothing uploads — the CLI says plainly that 0 cookies were in scope, rather than silently saving an unauthenticated session.
101
+
102
+ **🔴 Your role here is detect, orient, explain — never extract.** Tell the user this command exists and what it does; do not open a browser yourself and copy cookies out of it. Browser JavaScript cannot see an HttpOnly cookie — which is why Claude's own browser tooling (`document.cookie`, `page.evaluate`) can't capture it, and Instagram, X, and Reddit all mark their session cookie HttpOnly. The CLI uses CDP for automated capture; the DevTools export documented in `references/cookie-injection.md` remains the manual fallback. A skill that tells you to read cookies yourself produces a silent, confident-looking failure on the one cookie the site actually checks.
103
+
104
+ ### Prerequisites — this needs a human, on their own machine, right now
105
+
106
+ `session capture` requires a **local, interactive terminal with a display**, because a human has to actually see the Chrome window and log in. It does **not** work headless, in CI, over a plain SSH session (no display on Linux), or from an agent driving a remote/cloud browser. If that's the actual environment, say so plainly and point at the fallback below — don't imply a session is always recoverable from wherever you happen to be running.
107
+
108
+ ### Fallback — manual upload (`session set`)
109
+
110
+ ```bash
111
+ trawl scraps account session set <scrap-id> -c <file>
112
+ ```
95
113
 
114
+ Accepts either a bare Puppeteer cookie JSON array, or a `{ cookies, origins }` storageState-shaped file — the same shape `session capture` uploads, so a file saved from one capture can be replayed with `set` later, or handed to someone else. Reach for this only when capture genuinely can't run in the current environment. UI (scrap settings → Account → Upload session cookies) and API (`PUT /api/scraps/:scrapId/account/session`) reach the same endpoint.
115
+
116
+ The worker encrypts the stored session at rest and replays it automatically before your script's first navigation — Flavour B has no credentials to fall back on, so the script's only job is to confirm the replayed session is actually logged in, and throw (pointing back at capture) if it isn't:
117
+
118
+ ```js
96
119
  const page = await browser.newPage();
97
- await page.setCookie(...TRAWL.account.session.cookies);
120
+
121
+ // The worker has already replayed the stored session onto this page.
122
+ // `domcontentloaded` fires before an SPA hydrates, so an immediate DOM query
123
+ // can read "not logged in" on a perfectly valid session — wait for the marker instead.
98
124
  await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
125
+ const loggedIn = await page.waitForSelector('.account-menu', { timeout: 10_000 }).then(() => true, () => false);
126
+
127
+ if (!loggedIn) {
128
+ throw new Error('Session missing or expired — re-run `session capture` (or `session set`) to refresh it.');
129
+ }
99
130
  ```
100
131
 
101
- See `references/cookie-injection.md` for domain matching, HttpOnly export, localStorage, and expiry handling.
132
+ See `references/cookie-injection.md` for the session/cookie shape the server accepts, domain matching, and localStorage replay (including the manual fallback walkthrough for when capture can't run).
133
+
134
+ ### Necessary, not sufficient — cookies alone don't clear every wall
135
+
136
+ A valid, freshly-captured session is the right first move, but not a guaranteed fix:
137
+
138
+ - **Reddit**: a run with valid, unexpired cookies still came back empty — the app hydrates its authenticated view client-side and the worker's snapshot landed without that hydration completing. X and Instagram are the same class of SPA; expect the same failure mode.
139
+ - **Amazon** (`/product-reviews/…`): a 403 there is an **IP-level** block, not a login wall — no cookie touches it.
140
+ - **Tier-1 social in general**: without a **geo-matched residential proxy**, session injection is close to dead — a valid cookie replayed from a datacenter ASN is itself a signal these sites flag, independent of whether the cookie is genuinely good.
141
+
142
+ Say this plainly when recommending capture: it's the right lever to pull, not a promised fix.
143
+
144
+ ### Secret hygiene — a session is a bearer secret
145
+
146
+ - `session capture` scopes what it uploads to the scrap's target domain — cookies and localStorage entries outside that domain are dropped, not uploaded. Never widen this: don't tell a user to export their *whole* cookie jar when only one site's session is needed.
147
+ - The temporary Chrome profile `capture` launches into is deleted after the run, success or failure.
148
+ - If a manual `cookies.json` (or storageState file) is ever created for the fallback path, delete it after `session set` uploads it — it's a live bearer credential sitting on disk otherwise.
149
+ - `--json` never prints the session, and neither should you — only counts and the target domain are safe to relay back to the user.
102
150
 
103
151
  ## Anti-patterns to avoid
104
152
 
@@ -107,9 +155,11 @@ Authentication does not change the worker boundary rules (see `trawl-scrap-desig
107
155
  - No stealth plugins even when cookies are set.
108
156
  - No `waitForTimeout` — use state-based waits.
109
157
  - No deep CSS chains for post-login selectors.
158
+ - Never read cookies via your own browser tooling and hand them to the user (or paste them into a scrap) — `document.cookie` silently drops HttpOnly cookies, the ones that matter. Detect the wall, name `session capture`, stop there.
110
159
 
111
160
  ## What this skill does NOT cover
112
161
 
113
162
  - Scraping logic → `trawl-scrap-design`
114
163
  - CLI account management → `trawl-cli` (`trawl scraps account set/status/clear-session/delete`)
115
164
  - Local debugging runs → `trawl-scrap-local-test`
165
+ - The CLI's own auth errors (your Trawl login expired) → `trawl-cli` skill, `trawl login` — that `kind:'auth'` is unrelated to a scrap run's `failureKind:'auth'` covered here (which means the *target site* wants a session, not that your Trawl login is stale)
@@ -2,6 +2,8 @@
2
2
  title: Cookie Injection
3
3
  ---
4
4
 
5
+ > **Fallback reference.** `trawl scraps account session capture <id>` (see `SKILL.md`) is the primary way to get a session now — it drives a real Chrome over CDP, sees HttpOnly cookies, and captures localStorage automatically, no manual steps. Everything below is for when capture can't run, or for understanding the shape the server stores. Manual steps here are things to tell the **user** to do in their own browser — never actions for your own browser tool to perform.
6
+
5
7
  ### setCookie before goto
6
8
 
7
9
  Call `page.setCookie(...cookies)` before `page.goto`. Cookies set after `goto` are ignored — request headers are already sent.
@@ -12,13 +14,16 @@ await page.setCookie(...cookies); // must come before goto
12
14
  await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
13
15
  ```
14
16
 
15
- ### HttpOnly cookies are invisible from JS
17
+ ### HttpOnly cookies are invisible from JS — and from your own browser tooling
18
+
19
+ `document.cookie` and `page.evaluate(() => document.cookie)` silently skip HttpOnly cookies — the partial set won't authenticate the session. This is the most common silent failure in a hand-written script, and it's structural: no browser-JS API returns an HttpOnly cookie, by design.
20
+
21
+ **The same restriction applies to Claude's own browser tooling** — it evaluates JS in page context, the same `document.cookie` ceiling. Instagram, X, and Reddit all mark their session cookie HttpOnly, so an agent trying to read the cookie itself via its own browser tool produces a confident-looking but silently wrong result on exactly the cookie that matters. **Never do this — detect the wall, then tell the user to run `session capture` (see `SKILL.md`), which reads the full jar over CDP instead of JS.**
16
22
 
17
- `document.cookie` and `page.evaluate(() => document.cookie)` silently skip HttpOnly cookies — the partial set won't authenticate the session. This is the most common silent failure.
23
+ A human, using the browser's own DevTools UI (not JS), can still see and copy an HttpOnly cookie's value manually — that's the fallback below, unaffected by the JS restriction above. It's just slower and more error-prone than one CLI command, and it's a step for the user to take in their own browser, never you.
18
24
 
19
- Capture the full cookie set via:
25
+ Manual capture, when still needed:
20
26
  - **DevTools** → Application → Cookies → select the domain → copy to JSON manually.
21
- - **A WebExtensions-based Chrome extension** from https://chromewebstore.google.com/search/cookie%20exporter
22
27
 
23
28
  ### Domain matching gotchas
24
29
 
@@ -43,11 +48,25 @@ When cookies don't apply, check `domain` first. Export the exact value from DevT
43
48
  ]
44
49
  ```
45
50
 
51
+ ### Session shape the server accepts
52
+
53
+ `PUT /api/scraps/:scrapId/account/session` — what `session set` and `session capture` both call — validates and normalizes what's uploaded, whether that's a bare cookie array or `{ cookies, origins? }`:
54
+
55
+ **Cookie** — `{ name, value, domain, path?, httpOnly?, secure?, expires?, sameSite? }`:
56
+ - `name` / `value` — required strings.
57
+ - `domain` — **required**. A domain-less cookie used to silently no-op at replay time; the server now rejects it outright instead of letting a run fail silently later.
58
+ - `expires` — unix **seconds** (not milliseconds) — same unit as Puppeteer's `CookieData.expires` / DevTools' `expirationDate`. `-1` (some export tools' "session cookie" marker) is accepted but dropped, not stored literally.
59
+ - `sameSite` — `Strict` | `Lax` | `None` (`chrome.cookies.Cookie`'s lowercase `strict`/`lax`/`no_restriction` are recased automatically; `unspecified` is dropped). **`sameSite: 'None'` requires `secure: true`** — the browser silently drops a `None` cookie missing `secure` at the CDP layer, so the server rejects that combination up front rather than letting the cookie vanish invisibly at replay time.
60
+
61
+ **`origins[]`** (optional, storageState-shaped — what `session capture` uploads for localStorage): `[{ origin: "https://example.com", localStorage: [{ name, value }] }]`. `origin` must be a bare `scheme://host[:port]` — no path or query.
62
+
63
+ **`session set -c <file>` only checks that each cookie has a string `name`/`value` before sending it** — everything else above (domain, sameSite legality, the `None`+`secure` pairing) is enforced server-side, at upload time, as a `422` naming the bad field. A hand-edited or hand-copied DevTools export that skips `domain`, or carries a `sameSite` the server doesn't recognize, fails loudly right there on `session set` — not silently, deep inside a later scheduled run.
64
+
46
65
  ### localStorage / sessionStorage parallel save
47
66
 
48
- Some sites store JWTs in `localStorage`, not cookies. Detection signal: navigation succeeds but immediately redirects to `/login` despite valid cookies.
67
+ Some sites store JWTs in `localStorage`, not cookies. Detection signal: navigation succeeds but immediately redirects to a login route despite valid cookies (see `references/session-flow.md` for the exact-route matcher — never a `.includes('/login')` substring check). `session capture` reads this automatically, scoped per-origin to the target domain, and uploads it as `origins[]` alongside the cookies — no separate step needed.
49
68
 
50
- Capture localStorage from a logged-in session:
69
+ Manual fallback, when capture can't run — tell the user to do this in their own browser, never something to run via your own browser tool:
51
70
 
52
71
  ```js
53
72
  // In DevTools console on the logged-in page:
@@ -73,23 +92,22 @@ The worker starts a fresh browser context on each run. Persistence requires:
73
92
 
74
93
  Flavour A re-injects cookies from the script source on every run.
75
94
 
76
- ### Exporting cookies from Chrome — walkthrough
95
+ ### Exporting cookies from Chrome — manual fallback walkthrough
96
+
97
+ **Prefer `trawl scraps account session capture <id>` (see `SKILL.md`)** — it does this over CDP in one step: cookies, HttpOnly included, plus localStorage, no manual copying. Use the walkthrough below only when capture genuinely can't run in the environment (no local interactive terminal/display). These are steps for the user to run themselves in their own Chrome — never something to execute via your own browser tooling.
77
98
 
78
99
  1. Log in to the target site in Chrome.
79
100
  2. Open DevTools → Application → Storage → Cookies → select the domain.
80
- 3. Copy values to a JSON array matching `CookieParam` shape (`name`, `value`, `domain`, `path`, `httpOnly`, `secure`).
81
-
82
- Or use a cookie-export extension: https://chromewebstore.google.com/search/cookie%20exporter
101
+ 3. Copy values to a JSON array matching `CookieParam` shape (`name`, `value`, `domain`, `path`, `httpOnly`, `secure`) — see "Session shape the server accepts" above for the full field list the server validates.
83
102
 
84
103
  ### Storage state expiry
85
104
 
86
105
  Signs of expired cookies:
87
- - Navigation lands on `/login` or identity-provider redirect.
106
+ - Navigation lands on a login route (see `references/session-flow.md`) or an identity-provider redirect.
88
107
  - First protected request returns 401 or 403.
89
108
  - Page loads but user-specific data is absent (silent guest view).
90
109
 
91
110
  Refresh:
92
- 1. Log in locally in a fresh Chrome session.
93
- 2. Export new cookies (walkthrough above).
94
- 3. Re-upload via flavour B, or update the embedded array (flavour A).
95
- 4. Trawl-managed flow: `trawl scraps account clear-session <id>` to force re-login on next run.
111
+ 1. `trawl scraps account session capture <id>` — fastest path, re-does the login and re-uploads in one step (see `SKILL.md`). Remember cookies alone aren't always sufficient — see the "Necessary, not sufficient" caveats there.
112
+ 2. Manual fallback: log in locally in a fresh Chrome session, export new cookies (walkthrough above), re-upload via `session set -c <file>` (flavour B) or update the embedded array (flavour A).
113
+ 3. Trawl-managed flow: `trawl scraps account clear-session <id>` to force re-login on next run.
@@ -10,19 +10,22 @@ Async helper injected by the worker. Call after confirming login succeeded — n
10
10
  await saveSession(await page.cookies());
11
11
  ```
12
12
 
13
- The worker persists the cookie array encrypted. On the next run, `TRAWL.account.session.cookies` is populated and the login flow is skipped. Call once per run only.
13
+ The worker persists the cookie array encrypted and replays it automatically on the next run, before your script's first navigation. This is a **cookies-only** refresh — it never touches or clears any `origins` (localStorage) block already on the account, whether that came from `session capture` or the web UI. Call once per run only.
14
14
 
15
15
  ### Reuse pattern (full code)
16
16
 
17
17
  ```js
18
18
  const page = await browser.newPage();
19
19
 
20
- if (TRAWL.account?.session?.cookies) {
21
- // Saved session exists — restore cookies and skip the login flow.
22
- await page.setCookie(...TRAWL.account.session.cookies);
23
- await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
24
- } else {
25
- // First run (or cleared session) — perform full login.
20
+ // The worker has already replayed any stored session onto this page.
21
+ // Check for a marker that only appears when logged in, rather than
22
+ // assuming a saved session means you're logged in.
23
+ // `domcontentloaded` fires before an SPA hydrates, so wait for the marker
24
+ // with a bounded timeout instead of querying for it immediately.
25
+ await page.goto('https://example.com/dashboard', { waitUntil: 'domcontentloaded' });
26
+ const loggedIn = await page.waitForSelector('.account-menu', { timeout: 10_000 }).then(() => true, () => false);
27
+
28
+ if (!loggedIn) {
26
29
  await page.goto('https://example.com/login', { waitUntil: 'domcontentloaded' });
27
30
  await page.type('#username', TRAWL.account.username);
28
31
  await page.type('#password', TRAWL.account.password);
@@ -35,7 +38,7 @@ if (TRAWL.account?.session?.cookies) {
35
38
  }
36
39
  ```
37
40
 
38
- `TRAWL.account.session` is `undefined` on the first run — hence the optional chain. Both branches must reach the same post-login URL before scraping starts.
41
+ `TRAWL.account.session` is always an object once an account is configured — `cookies` and `origins` default to `[]` rather than the field itself being absent or `undefined`, so `if (TRAWL.account?.session?.cookies)` is *always* truthy (an empty array is truthy in JS) and can't tell you whether a session was actually captured. The marker check above is what actually distinguishes the two cases. Both branches must reach the same post-login URL before scraping starts.
39
42
 
40
43
  ### Forced re-login
41
44
 
@@ -43,7 +46,7 @@ if (TRAWL.account?.session?.cookies) {
43
46
  trawl scraps account clear-session <scrap-id>
44
47
  ```
45
48
 
46
- The next run finds `TRAWL.account.session` undefined, falls into the login branch, and re-runs `saveSession` on success.
49
+ The next run replays `cookies: []` / `origins: []` (nothing to restore), the marker check fails, the script falls into the login branch, and `saveSession` re-runs on success.
47
50
 
48
51
  ### When the login flow itself breaks
49
52
 
@@ -51,7 +54,25 @@ Two failure modes:
51
54
 
52
55
  **Navigation failed** — `page.waitForNavigation` throws (network error or timeout). The `try/catch` catches this only; it does NOT detect wrong credentials.
53
56
 
54
- **Wrong credentials** — site redirects back to `/login` (navigational success, so `try/catch` never fires). Detect by checking `page.url()` after navigation resolves.
57
+ **Wrong credentials** — site redirects back to a login route (navigational success, so `try/catch` never fires). Detect by checking `page.url()` after navigation resolves — but match the **exact pathname**, never a substring like `.includes('/login')`. A substring match false-positives on any URL that merely contains the word — `github.com/{org}/login`, `reddit.com/r/login`, a docs page at `/docs/login` — and would misclassify a page that loaded fine as a rejected login. Match against the same login-route vocabulary Trawl's own server-side login-wall detector uses, exact-whole-pathname (trailing-slash-insensitive):
58
+
59
+ ```js
60
+ const LOGIN_ROUTES = new Set([
61
+ '/login', '/signin', '/accounts/login', '/ap/signin',
62
+ '/i/flow/login', '/users/sign_in', '/auth/login',
63
+ ]);
64
+
65
+ function isLoginRoute(url) {
66
+ let pathname;
67
+ try {
68
+ pathname = new URL(url).pathname;
69
+ } catch {
70
+ return false;
71
+ }
72
+ const normalized = pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname;
73
+ return LOGIN_ROUTES.has(normalized);
74
+ }
75
+ ```
55
76
 
56
77
  ```js
57
78
  const page = await browser.newPage();
@@ -69,8 +90,8 @@ try {
69
90
  throw new Error(`Login navigation failed: ${err.message}`);
70
91
  }
71
92
 
72
- if (page.url().includes('/login')) {
73
- // Form rejected our credentials and we're still on the login page.
93
+ if (isLoginRoute(page.url())) {
94
+ // Exact route match, not a substring — form rejected our credentials and we're still on a login page.
74
95
  throw new Error('Login failed: wrong credentials');
75
96
  }
76
97
 
@@ -35,7 +35,7 @@ export function buildContext(flags, readFile = (p) => readFileSync(resolve(p), '
35
35
  account.session = { cookies: JSON.parse(readFile(cookiesPath)) };
36
36
  }
37
37
 
38
- // Parity with the worker (trawl_node#786): also expose creds under TRAWL.account.*.
38
+ // Parity with the production worker: also expose creds under TRAWL.account.*.
39
39
  // null when nothing was provided, mirroring buildTrawlAccount's null-when-empty contract.
40
40
  const hasAccount = !!(account.username || account.password || account.session);
41
41
  TRAWL.account = hasAccount ? account : null;