wetaca-cli 0.2.4 → 0.2.6

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/AGENTS.md ADDED
@@ -0,0 +1,31 @@
1
+ # AGENTS.md
2
+
3
+ Guidance for AI coding agents (Claude Code, Codex, Cursor, Hermes, OpenCode, Jules, ...) working in this repository — and a pointer for agents that help the *user* manage their Wetaca account with the installed CLI.
4
+
5
+ ## Managing a Wetaca account with wetaca-cli
6
+
7
+ If your goal is to operate the user's Wetaca account (menu, subscription, deliveries, orders, vouchers), **do not read this repo's source first**. Run the embedded agent guide:
8
+
9
+ ```
10
+ wetaca skills get wetaca-usage
11
+ ```
12
+
13
+ That output is the canonical, version-matched contract: output formats, exit codes, command list, confirmation rules and typical flows. If `wetaca` is not installed: `npm install -g wetaca-cli`.
14
+
15
+ Non-negotiable rules when acting on a real account:
16
+
17
+ 1. Reads (`suggestion show`, `orders list`, ...) are safe; run them freely.
18
+ 2. Mutations require an explicit summary → confirmation. In non-interactive runs pass `--yes` ONLY when the user asked for that exact operation.
19
+ 3. Prefer `--dry-run` before any mutation that supports it.
20
+ 4. Never touch payments (the CLI cannot either).
21
+
22
+ ## Working on this codebase
23
+
24
+ - Zero-dependency Node ESM (>=18). Do not add npm dependencies.
25
+ - Layout: `bin/wetaca.js` (arg parsing, dispatch, help), `src/lib.js` (config, GraphQL client, errors, output), `src/commands.js` (command implementations), `src/queries.js` (GraphQL operations), `src/guide.js` (embedded agent guide — single source for `docs/agent-guide.md`, regenerate with `node bin/wetaca.js skills get wetaca-usage > docs/agent-guide.md`).
26
+ - GraphQL reference operations live in `docs/api-operations/` (extracted from wetaca.com's production bundle; `extract-gql.mjs` re-extracts them).
27
+ - Contract: every command returns JSON on stdout (pretty/jsonl optional), errors as JSON on stderr with `--error-format json`, stable exit codes (0 ok, 1 unexpected, 2 usage, 3 auth, 4 network, 5 not found, 6 API, 7 contract drift). See `docs/cli-spec.md`.
28
+ - Mutations must follow the existing pattern: build payload → honor `--dry-run` → `confirm(flags, summary)` unless `--yes` → call `gql()`.
29
+ - After changing `src/guide.js`, regenerate `docs/agent-guide.md` (they must stay identical).
30
+ - Check syntax before committing: `node --check` on every touched file. CI runs the same checks plus smoke tests and cookie-parser tests.
31
+ - Releases: `npm version patch && git push --follow-tags`. The GitHub Actions `Publish to npm` workflow stages the package (`npm stage publish`, OIDC trusted publishing, no token); a maintainer approves it with `npm stage approve <id> --otp <code>`.
package/README.md CHANGED
@@ -26,13 +26,23 @@ npm install -g wetaca-cli # from npm
26
26
  wetaca doctor
27
27
  ```
28
28
 
29
- Or from the repo: `npm install -g .`
29
+ Or from this repo: `npm install -g .`
30
+
31
+ ## For AI agents
32
+
33
+ Point your agent at this repo and it will find `AGENTS.md` (Claude Code, Codex, Cursor, OpenCode, Jules, Hermes all read it automatically). The canonical contract for agents is embedded in the binary:
34
+
35
+ ```
36
+ wetaca skills get wetaca-usage
37
+ ```
38
+
39
+ A portable skill file is also available at [`skill/SKILL.md`](skill/SKILL.md) for platforms with skill directories (Hermes: `hermes skills install https://raw.githubusercontent.com/gorgueugr/wetaca-cli/master/skill/SKILL.md`).
30
40
 
31
41
  ## Get started
32
42
 
33
43
  ```
34
- wetaca auth login --refresh-token <COOKIE> # refresh-token cookie from wetaca.com (lasts ~120 days)
35
- wetaca auth login # prompts for the refresh-token (hidden); also accepts a session JWT
44
+ wetaca auth login --token <TOKEN> # session token from DevTools (F12 -> Network -> api.wetaca.com -> "authorization: Bearer ..."); the CLI mints the session cookies and the session auto-renews (~120 days)
45
+ wetaca auth login # opens the browser and prompts for the token (hidden)
36
46
  wetaca me --format pretty
37
47
  ```
38
48
 
@@ -71,6 +81,7 @@ wetaca skills get wetaca-usage
71
81
  | [Specification](docs/cli-spec.md) | every command, flag, exit code and GraphQL operation |
72
82
  | [Extracted operations](docs/api-operations/) | the ~190 GraphQL documents from Wetaca's website |
73
83
  | [Agent guide](docs/agent-guide.md) | `wetaca skills get wetaca-usage` |
84
+ | [Agent skill](skill/SKILL.md) | portable SKILL.md for skill hubs (Hermes, Claude Code, OpenCode...) |
74
85
 
75
86
  ## Good to know
76
87
 
package/bin/wetaca.js CHANGED
@@ -10,14 +10,17 @@ USAGE
10
10
  wetaca [global flags] <noun> <verb> [args] [flags]
11
11
 
12
12
  COMMANDS
13
- auth login [--refresh-token COOKIE | --cookies FILE | --cookies-stdin | --token T [--clipboard]] | status | logout
14
- auth login imports the refresh-token cookie from wetaca.com (F12 -> Application -> Cookies;
15
- lasts ~120 days) and RENEWS the session token automatically when it expires.
16
- The password is never asked for or stored.
17
- --cookies FILE accepts browser exports: Netscape cookies.txt, Cookie-Editor/
18
- EditThisCookie JSON, a Cookie: header, or the bare value; only cookies from
19
- wetaca.com are read.
20
- login --token: paste the session token straight from wetaca.com (expires ~1h)
13
+ auth login [--token T [--clipboard] | --refresh-token COOKIE | --cookies FILE | --cookies-stdin] | status | logout
14
+ auth login opens https://wetaca.com in your browser: in DevTools (F12 -> Network ->
15
+ any request to api.wetaca.com) copy what comes after "authorization: Bearer "
16
+ (the session token) -> paste it at the prompt or pass --token T. The CLI
17
+ validates it and mints the session cookies via POST /session/start
18
+ (auth-token + refresh-token pair), so the session auto-renews itself
19
+ (~120 days). The password is never asked for.
20
+ Also accepted: --refresh-token COOKIE, a whole "Cookie:" header line, or a
21
+ cookie export (--cookies FILE / --cookies-stdin: Netscape, Cookie-Editor JSON).
22
+ Note: the server validates the auth-token + refresh-token PAIR; a bare
23
+ refresh-token always fails with 401.
21
24
  me show account summary
22
25
  subscription show | pause [--weeks N] | resume
23
26
  suggestion show | pause | resume | edit --profile-suggestion ID --set "id:qty,..."
package/docs/GUIA.md CHANGED
@@ -113,6 +113,6 @@ Automation ideas (cron):
113
113
 
114
114
  ## 4. Session
115
115
 
116
- - Status: `wetaca auth status` · Refresh: `wetaca auth login --cookies cookies.txt` (export with Cookie-Editor) or `--refresh-token <COOKIE>` (F12 → Application → Cookies → `refresh-token`; lasts ~120 days and the CLI renews the token itself). Alternative: `wetaca auth login --token <TOKEN> --clipboard` (expires in ~1h).
116
+ - Status: `wetaca auth status` · Login: `wetaca auth login --token <TOKEN>` (or `--token --clipboard`): copy the `authorization: Bearer ***` header of any request to api.wetaca.com in DevTools (F12 -> Network). The CLI validates it and mints the session cookies via POST /session/start (auth-token + refresh-token pair), so the session auto-renews itself for ~120 days. VERIFIED end-to-end. Note: the server validates the cookie PAIR — a bare refresh-token always 401s.
117
117
  - The token lives in `~/.config/wetaca-cli/credentials.json` (0600) and the rest of the settings in `config.json`; `WETACA_TOKEN` overrides it (CI).
118
118
  - If the API rejects it (exit 3), redo the extraction with DevTools (docs/cli-spec.md §6).
@@ -1,71 +1,80 @@
1
- # wetaca-cli — guía para agentes IA
1
+ # wetaca-cli — guide for AI agents
2
2
 
3
- Gestiona la cuenta de Wetaca (suscripción de comida semanal) del usuario desde el terminal.
4
- Todo comando devuelve JSON en stdout por defecto; los errores van a stderr.
3
+ Manage the user's Wetaca account (weekly meal subscription) from the terminal.
4
+ Every command returns JSON on stdout by default; errors go to stderr.
5
5
 
6
- ## Antes de empezar
6
+ ## Before you start
7
7
 
8
- 1. Ejecuta `wetaca doctor` para verificar node, conectividad y sesión.
9
- 2. `wetaca auth status` dice si hay sesión válida. Si no la hay:
10
- - `wetaca auth login --cookies cookies.txt` (export con la extensión Cookie-Editor sobre wetaca.com logueado) o `--refresh-token COOKIE` (cookie de wetaca.com, dura ~120 días; el CLI renueva el token solo). Sin contraseña.
11
- - `wetaca auth login --token T` o `--token --clipboard`: token copiado de la cabecera
12
- `authorization: Bearer …` de cualquier petición a api.wetaca.com en las DevTools del
13
- usuario (F12 → Network). Es la vía si su cuenta entra con Google.
14
- No pidas al usuario la contraseña de Google ni automatices su navegador para el login.
8
+ 1. Run `wetaca doctor` to check node, connectivity and session.
9
+ 2. `wetaca auth status` tells you whether there is a valid session. If there isn't:
10
+ - `wetaca auth login --token T` (or `--token --clipboard`, or paste it when prompted): copy the
11
+ `authorization: Bearer *** header of any request to api.wetaca.com in the user's DevTools
12
+ (F12 → Network). The CLI validates it and then mints the session cookies exactly like the
13
+ website does after a login (POST /session/start issues the auth-token + refresh-token pair),
14
+ so the session auto-renews for ~120 days. This is the way to go if their account logs in
15
+ with Google. No password involved.
16
+ Never ask the user for their Google password and never automate their browser for the login.
15
17
 
16
- ## Contrato de salida
18
+ ## Output contract
17
19
 
18
- - stdout: JSON (`--format pretty` para humanos, `jsonl` para listas línea a línea).
19
- - `--error-format json`: envoltorio de error { error: { code, category, reason, retryable, message, suggested_commands } }.
20
- - Exit codes estables: 0 ok · 1 inesperado · 2 uso/validación/confirmación denegada · 3 auth ·
21
- 4 red · 5 no encontrado · 6 la API rechazó la operación · 7 deriva de contrato (schema cambiado).
22
- - `reason: "auth_required"` → nada que reintentar; el usuario debe hacer login.
23
- - `reason: "contract_drift"` → no reinventes la query; abre issue en el repo.
20
+ - stdout: JSON (`--format pretty` for humans, `jsonl` for lists, one line each).
21
+ - `--error-format json`: error wrapper { error: { code, category, reason, retryable, message, suggested_commands } }.
22
+ - Stable exit codes: 0 ok · 1 unexpected · 2 usage/validation/confirmation denied · 3 auth ·
23
+ 4 network · 5 not found · 6 the API rejected the operation · 7 contract drift (schema changed).
24
+ - `reason: "auth_required"` → nothing to retry; the user must log in.
25
+ - `reason: "contract_drift"` → don't reinvent the query; open an issue on the repo.
24
26
 
25
- ## Reglas para operaciones con efectos reales
27
+ ## Rules for operations with real effects
26
28
 
27
- 1. Nada cambia la cuenta sin confirmación: sin terminal, exige `--yes`. Pasa `--yes` SOLO cuando
28
- el usuario pidió exactamente esa operación y vio el resumen.
29
- 2. Usa `--dry-run` en `suggestion edit` y `orders cancel` para mostrar qué se enviaría, antes de pedir confirmación.
30
- 3. `suggestion pause` salta la entrega de la semana próxima (la semana ya cobrada NO se toca).
31
- `subscription pause --weeks N` pausa la suscripción N semanas (cancelación temporal);
32
- `subscription resume` la reactiva.
33
- 4. `orders cancel <id>` cancela un pedido confirmado y devuelve el importe. Ids: `deliveries next`
34
- (pedidos pendientes) y `orders list` (histórico).
35
- 5. Nunca gestiones pagos: wetaca-cli no toca tarjetas ni pagos pendientes de Redsys/PayPal.
36
- Si `nextPaymentPendingOrder` no es null, dilo al usuario y que lo pague en wetaca.com.
29
+ 1. Nothing changes the account without confirmation: without a terminal, `--yes` is required. Pass `--yes` ONLY when
30
+ the user asked for exactly that operation and saw the summary.
31
+ 2. Use `--dry-run` on `suggestion edit` and `orders cancel` to show what would be sent, before asking for confirmation.
32
+ 3. `suggestion pause` skips next week's delivery (the already-billed week is NOT touched).
33
+ `subscription pause --weeks N` pauses the subscription for N weeks (temporary cancellation);
34
+ `subscription resume` reactivates it.
35
+ 4. `orders cancel <id>` cancels a confirmed order and refunds the amount. Ids: `deliveries next`
36
+ (pending orders) and `orders list` (history).
37
+ 5. Never manage payments: wetaca-cli does not touch cards or pending Redsys/PayPal payments.
38
+ If `nextPaymentPendingOrder` is not null, tell the user and have them pay on wetaca.com.
37
39
 
38
- ## Comandos
40
+ ## Commands
39
41
 
40
42
  wetaca auth login [--refresh-token COOKIE | --token T] | status | logout
41
- wetaca me resumen: cliente + suscripción + cartera
43
+ wetaca me summary: customer + subscription + wallet
42
44
  wetaca subscription show | pause [--weeks N] [--feedback S] | resume
43
- wetaca suggestion show menú de la semana próxima por perfil, precios, ventana de entrega
44
- wetaca suggestion pause | resume saltar / reactivar la semana próxima
45
- wetaca suggestion edit --profile-suggestion ID --set "productId:cant,..." [--dry-run]
46
- wetaca deliveries next sugerencias y pedidos pendientes (ids para orders/cancel)
45
+ wetaca suggestion show next week's menu per profile, prices, delivery window
46
+ wetaca suggestion pause | resume skip / reactivate next week
47
+ wetaca suggestion edit --profile-suggestion ID --set "productId:qty,..." [--dry-run]
48
+ wetaca deliveries next suggestions and pending orders (ids for orders/cancel)
47
49
  wetaca orders list [--limit N] | show <id> | cancel <id> [--dry-run]
48
- wetaca menu list platos de la semana (ids para suggestion edit)
49
- wetaca dish show <slug> detalle/ingredientes de un plato
50
- wetaca deliveries options franjas de entrega disponibles para tu CP
51
- wetaca deliveries set-option <id> --dry-run cambia la franja (revisa y repite con --yes)
52
- wetaca profiles list tus perfiles y su menú
53
- wetaca profiles pause <id|nombre> pausa un perfil (dry-run antes)
50
+ wetaca menu list dishes of the week (ids for suggestion edit)
51
+ wetaca dish show <slug> details/ingredients of a dish
52
+ wetaca deliveries options delivery slots available for your zip code
53
+ wetaca deliveries set-option <id> --dry-run changes the slot (review and repeat with --yes)
54
+ wetaca profiles list your profiles and their menu
55
+ wetaca profiles pause <id|name> pauses a profile (dry-run first)
54
56
  wetaca addresses list
55
- wetaca addresses save --street C --number N [--floor F] --zipcode CP --city CIUDAD --dry-run
56
- (revisa el plan; repite con --yes; opcional --notes --firstname --lastname --phone)
57
- wetaca addresses remove <id> borra una dirección no en uso
57
+ wetaca addresses save --street C --number N [--floor F] --zipcode ZIP --city CITY --dry-run
58
+ (review the plan; repeat with --yes; optional --notes --firstname --lastname --phone)
59
+ wetaca addresses remove <id> deletes an address not in use
58
60
  wetaca vouchers list
61
+ wetaca vouchers current voucher applied to next week (if any)
62
+ wetaca vouchers apply <CODE> apply a voucher to next week (--dry-run first, then --yes)
63
+ wetaca vouchers skip explicitly use no voucher next week (WARNING: the API
64
+ implements this as skipVoucher=true, which ALSO pauses
65
+ next week's delivery — same effect as suggestion pause.
66
+ Revert with: wetaca suggestion resume)
67
+ wetaca giftcards show | redeem <CODE> gift card limits / redeem into wallet
59
68
  wetaca wallet
60
69
  wetaca config path | list | get <k> | set <k> <v>
61
70
  wetaca doctor
62
- wetaca skills get wetaca-usage esta guía
71
+ wetaca skills get wetaca-usage this guide
63
72
 
64
- ## Flujos típicos
73
+ ## Typical flows
65
74
 
66
- - "¿Qué toca esta semana?": `wetaca suggestion show --format pretty`
67
- - "Esta semana no quiero arroz": `suggestion show` → localiza el plato y su `productSuggestionId`
68
- (`profileSuggestionId`) y `productId` → `suggestion edit --profile-suggestion ID --set "..." --dry-run`
69
- → muestra el plan → confirma → ejecuta con `--yes`.
70
- - "Vacaciones dos semanas": `subscription pause --weeks 2` (resumen → --yes) y luego `subscription resume`.
71
- - "Cancela el pedido de mañana": `deliveries next` → `orders cancel <id>`.
75
+ - "What's on this week?": `wetaca suggestion show --format pretty`
76
+ - "I don't want rice this week": `suggestion show` → locate the dish and its `productSuggestionId`
77
+ (`profileSuggestionId`) and `productId` → `suggestion edit --profile-suggestion ID --set "..." --dry-run`
78
+ → show the plan → confirm → run with `--yes`.
79
+ - "Vacation for two weeks": `subscription pause --weeks 2` (summary → --yes) and then `subscription resume`.
80
+ - "Cancel tomorrow's order": `deliveries next` → `orders cancel <id>`.
package/docs/cli-spec.md CHANGED
@@ -64,12 +64,12 @@ completion bash | zsh | fish
64
64
 
65
65
  ## 6. Session
66
66
 
67
- - **Recommended path - `refresh-token` cookie**: log in to wetaca.com, F12 -> Application -> Cookies -> `https://wetaca.com` -> copy the value of **`refresh-token`** (lasts ~120 days) and run `wetaca auth login --refresh-token <VALUE>` (or paste it when the CLI prompts for it, hidden). The CLI stores it in `credentials.json` (0600) and **renews only the session token** via `POST /session/refresh` (header `x-wetaca-session: 1`, cookie `refresh-token`), exactly like the website does. If the API rotates the refresh-token in the response, the CLI stores the new one.
68
- - **Import from a cookie export**: `wetaca auth login --cookies cookies.txt` or `--cookies-stdin`. Formats: Netscape cookies.txt (includes `#HttpOnly_` lines), Cookie-Editor/EditThisCookie JSON (array or `{url, cookies}`), `Cookie:` header, or the bare value. Only wetaca.com cookies are read; if there is no `refresh-token` in the export, a clear error is shown.
69
- - Direct session token import (alternative, expires in ~1h): F12 -> Network -> filter `api.wetaca.com` -> any request -> header `authorization: Bearer ***` -> `wetaca auth login --token <TOKEN>` (or `--clipboard`). Any format is accepted and validated by running the `customer` query.
67
+ - **Recommended path - session token + auto-start**: copy the `authorization: Bearer ***` header of any request to api.wetaca.com in DevTools (F12 -> Network) and run `wetaca auth login --token <TOKEN>` (or `--token --clipboard`, or paste it when the CLI prompts for it, hidden). The CLI validates it with the `customer` query and then mints the session cookies exactly like the website does after a login: `POST https://wetaca.com/session/start` body `{token}` (header `x-wetaca-session: 1`, browser UA) -> Set-Cookie with the **pair** `auth-token` (path=/) + `refresh-token` (path=/session/refresh), both httpOnly. The pair is stored in `credentials.json` (0600) as `sessionAuthToken` + `refreshToken`. VERIFIED end-to-end against a real account.
68
+ - **Auto-renewal**: when the session token expires (~1h), the CLI transparently calls `POST https://wetaca.com/session/refresh` (header `x-wetaca-session: 1`, browser UA) with the cookie **pair** `Cookie: auth-token=X; refresh-token=Y` and retries the request. The server validates the pair: sending only the refresh-token ALWAYS returns 401 (this is why a bare `--refresh-token VALUE` copied from the browser does not work). Each response issues a new `auth-token`, which the CLI stores; the refresh cookie lasts ~120 days.
69
+ - **Import from a cookie export**: `wetaca auth login --cookies cookies.txt` or `--cookies-stdin`. Formats: Netscape cookies.txt (includes `#HttpOnly_` lines), Cookie-Editor/EditThisCookie JSON (array or `{url, cookies}`), `Cookie:` header, or the bare value. Only wetaca.com cookies are read; the import must include BOTH `auth-token` and `refresh-token` or the refresh will 401.
70
70
  - **The password is never requested or stored** (user's decision). The `sessionTokenByPassword` endpoints exist in the API but the CLI does not use them.
71
71
  - Validation: the test that matters is that the `customer` query responds with the token (`tokenIsValid` is diagnostic only: it returned false with valid tokens).
72
- - Storage: secrets (token, refreshToken) in `credentials.json` with restrictive permissions (0600 / user-only ACL); everything else in `config.json`. Env: `WETACA_TOKEN` (CI, highest priority), `WETACA_REFRESH_TOKEN` (CI, auto-refresh without disk). Profiles: `--profile` / `WETACA_PROFILE` / `defaultProfile`.
72
+ - Storage: secrets (token, sessionAuthToken, refreshToken) in `credentials.json` with restrictive permissions (0600 / user-only ACL); everything else in `config.json`. Env: `WETACA_TOKEN` (CI, highest priority), `WETACA_REFRESH_TOKEN` (CI, auto-refresh without disk). Profiles: `--profile` / `WETACA_PROFILE` / `defaultProfile`.
73
73
  - Header: `authorization: Bearer ***` on every request.
74
74
 
75
75
  ## 7. API
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wetaca-cli",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Manage your Wetaca from the terminal: subscription, weekly menu, deliveries and orders. Built for people and AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,8 @@
10
10
  "bin",
11
11
  "src",
12
12
  "docs",
13
+ "skill",
14
+ "AGENTS.md",
13
15
  "README.md",
14
16
  "LICENSE"
15
17
  ],
package/skill/SKILL.md ADDED
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: wetaca-usage
3
+ description: Use when the user asks about Wetaca meals or deliveries.
4
+ version: 0.2.4
5
+ author: Jorge Soler Padial (https://github.com/gorgueugr)
6
+ license: MIT
7
+ metadata:
8
+ hermes:
9
+ tags: [wetaca, cli, account-management]
10
+ ---
11
+
12
+ # wetaca-cli — agent guide
13
+
14
+ Run the embedded, version-matched guide (source of truth, kept in sync with the installed binary):
15
+
16
+ ```
17
+ wetaca skills get wetaca-usage
18
+ ```
19
+
20
+ If `wetaca` is not installed: `npm install -g wetaca-cli` (requires Node >= 18).
21
+
22
+ ## When to Use
23
+
24
+ - The user asks about their Wetaca account: weekly menu, subscription, deliveries, orders, vouchers, gift cards, wallet or addresses.
25
+ - The user wants to change next week's menu, skip a week, pause the subscription, cancel an order or apply a voucher.
26
+
27
+ ## Contract
28
+
29
+ Every command returns JSON on stdout by default (`--format pretty` for humans); errors go to stderr as JSON with `--error-format json`; stable exit codes (0 ok · 1 unexpected · 2 usage/confirmation · 3 auth · 4 network · 5 not found · 6 API rejected · 7 contract drift).
30
+
31
+ ## Golden rules
32
+
33
+ 1. Reads are safe. Run them freely.
34
+ 2. Mutations need a summary shown to the user; pass `--yes` only for an explicitly requested operation.
35
+ 3. Use `--dry-run` on `suggestion edit`, `addresses save`, `deliveries set-option`, `orders cancel` before any real run.
36
+ 4. Never touch payments — the CLI does not either.
37
+ 5. `reason: "auth_required"` → the user must run `wetaca auth login` (cookie-based; no password involved).
38
+
39
+ Project source: https://github.com/gorgueugr/wetaca-cli
package/src/commands.js CHANGED
@@ -3,9 +3,9 @@ import readline from 'node:readline/promises';
3
3
  import child_process from 'node:child_process';
4
4
  import fs from 'node:fs';
5
5
  import {
6
- CliError, usageError, EXIT, gql, cents, fmtDate, emit,
6
+ CliError, usageError, EXIT, gql, cents, fmtDate, fmtWindow, emit,
7
7
  getToken, loadConfig, saveConfig, saveProfile, configPath, configDir,
8
- loadCreds, saveCreds, credentialsPath, sessionRefresh,
8
+ loadCreds, saveCreds, credentialsPath, sessionRefresh, sessionStart,
9
9
  } from './lib.js';
10
10
  import * as Q from './queries.js';
11
11
 
@@ -129,9 +129,41 @@ function ask(question, { hidden = false } = {}) {
129
129
  });
130
130
  }
131
131
 
132
+ // Explains the session flow in a few lines and opens the browser so the user can grab
133
+ // the refresh-token from localStorage (no path restriction there). All to STDERR (stdout = JSON).
134
+
135
+ function openBrowser(url) {
136
+ try {
137
+ const { execSync } = child_process;
138
+ if (process.platform === 'win32') {
139
+ // rundll32 keeps the URL intact as argv (cmd /c start cuts at &, explorer.exe may open Explorer)
140
+ execSync(`rundll32 url.dll,FileProtocolHandler ${url}`, { stdio: 'ignore' });
141
+ } else if (process.platform === 'darwin') {
142
+ execSync(`open ${JSON.stringify(url)}`, { stdio: 'ignore' });
143
+ } else {
144
+ execSync(`xdg-open ${JSON.stringify(url)}`, { stdio: 'ignore' });
145
+ }
146
+ return true;
147
+ } catch { return false; }
148
+ }
149
+
150
+ function printLoginGuide() {
151
+ openBrowser('https://wetaca.com/');
152
+ const lines = [
153
+ '',
154
+ 'Opening https://wetaca.com in your browser (make sure you are logged in).',
155
+ 'In DevTools (F12 -> Network -> any request to api.wetaca.com) copy what comes after',
156
+ '"authorization: Bearer " (the session token). Paste it here and press Enter:',
157
+ 'The CLI will start a full session (POST /session/start) and keep it auto-renewed.',
158
+ '',
159
+ ];
160
+ process.stderr.write(lines.join('\n'));
161
+ }
162
+
132
163
  export async function authLogin(args, flags, ctx) {
133
164
  let token = flags.token;
134
165
  let viaRefresh = false;
166
+ let clipboardRefresh = null;
135
167
 
136
168
  if (flags.clipboard) {
137
169
  // read the token from the clipboard (e.g. extracted from the wetaca.com DevTools console)
@@ -142,11 +174,18 @@ export async function authLogin(args, flags, ctx) {
142
174
  : process.platform === 'darwin' ? execSync('pbpaste', { encoding: 'utf8' })
143
175
  : execSync('xclip -selection clipboard -o', { encoding: 'utf8' });
144
176
  const m = String(out).match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
145
- token = m ? m[0] : String(out).trim();
177
+ const rt = extractRefreshToken(m ? m[0] : String(out));
178
+ if (m) {
179
+ token = m[0]; // session JWT
180
+ } else if (rt) {
181
+ clipboardRefresh = rt; // refresh-token (e.g. copied with the console snippet)
182
+ } else {
183
+ token = String(out).trim();
184
+ }
146
185
  } catch (e) {
147
186
  throw usageError('Could not read the clipboard: ' + e.message);
148
187
  }
149
- if (!token) throw usageError('The clipboard is empty.');
188
+ if (!token && !clipboardRefresh) throw usageError('The clipboard is empty.');
150
189
  }
151
190
 
152
191
  let customer = null;
@@ -165,19 +204,24 @@ export async function authLogin(args, flags, ctx) {
165
204
  throw usageError('Could not read the cookies file: ' + e.message);
166
205
  }
167
206
  }
168
- if (cookieFileInput != null || flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN) {
207
+ if (cookieFileInput != null || flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN || clipboardRefresh) {
169
208
  // Import the refresh-token from the web (120-day cookie)
170
209
  // and let /session/refresh mint the session tokens. No password is ever requested.
171
210
  let rt;
172
211
  if (cookieFileInput != null) {
173
212
  rt = extractRefreshToken(cookieFileInput);
174
213
  } else {
175
- rt = String(flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN).trim();
214
+ rt = String(flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN || clipboardRefresh || '').trim();
176
215
  }
177
216
  if (!rt) {
178
217
  throw new CliError(EXIT.AUTH,
179
- 'The cookie export contains no "refresh-token" cookie from wetaca.com. ' +
180
- 'Make sure to export the cookies while logged in to wetaca.com (the cookie is created on login).',
218
+ 'The cookie export contains no "refresh-token" cookie from wetaca.com. That cookie is ' +
219
+ 'written with path=/session/refresh, so it does NOT appear in Cookie-Editor or ' +
220
+ 'Application -> Cookies on normal pages. Get it while logged in: either open ' +
221
+ 'https://wetaca.com/session/refresh (a bare "Unauthorized" page is expected) and the ' +
222
+ 'cookie becomes visible there, or F12 -> Network -> filter "refresh" -> POST ' +
223
+ '/session/refresh -> Request Headers -> copy the whole "Cookie:" line (the CLI ' +
224
+ 'extracts the refresh-token from it).',
181
225
  { reason: 'refresh_token_missing', suggested_commands: ['wetaca auth login --refresh-token VALOR'] });
182
226
  }
183
227
  saveProfile(ctx.profile, { refreshToken: rt });
@@ -187,7 +231,8 @@ export async function authLogin(args, flags, ctx) {
187
231
  } catch (e) {
188
232
  throw new CliError(e.exitCode || EXIT.AUTH,
189
233
  'Could not refresh the session with that refresh-token. ' + e.message,
190
- { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'] });
234
+ { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'],
235
+ details: e.extra?.details });
191
236
  }
192
237
  const c = await gql(Q.CUSTOMER, {}, { token, debug: ctx.debug });
193
238
  customer = c.customer;
@@ -211,26 +256,45 @@ export async function authLogin(args, flags, ctx) {
211
256
  '(without the word Bearer, without quotes). Original error: ' + e.message,
212
257
  { reason: 'invalid_token' });
213
258
  }
259
+ // Mint a refresh-token from the session token (the web's POST /session/start step).
260
+ // If Wetaca issues one, the session becomes auto-renewable; if it declines, we keep
261
+ // the short-lived session (not fatal).
262
+ try {
263
+ const out = await sessionStart(token, ctx.profile, ctx.debug);
264
+ if (out) {
265
+ saveProfile(ctx.profile, { refreshToken: out.refreshToken, sessionAuthToken: out.authToken });
266
+ viaRefresh = true;
267
+ if (ctx.debug) console.error('wetaca: /session/start issued the session cookies (session is now auto-renewable)');
268
+ } else if (ctx.debug) {
269
+ console.error('wetaca: /session/start did not issue a refresh-token');
270
+ }
271
+ } catch (e) {
272
+ if (ctx.debug) console.error('wetaca: /session/start attempt failed: ' + e.message);
273
+ }
214
274
  } else {
215
275
  // Without --refresh-token or --token: prompt for it on the terminal (hidden). Accepts the
216
276
  // refresh-token cookie (preferred, lasts 120 days) or a direct session JWT.
217
277
  if (ctx.noInput || !process.stdin.isTTY) {
218
- throw usageError('Without a terminal you need --refresh-token VALUE (a wetaca.com cookie, F12 → Application → Cookies), or --token VALUE / --token --clipboard.');
278
+ throw usageError('Without a terminal you need --refresh-token VALUE (from wetaca.com while logged in: F12 -> Network -> filter "refresh" -> POST /session/refresh -> Request Headers -> Cookie -> refresh-token; the cookie is path-restricted so it does NOT appear in Application -> Cookies), or --token VALUE / --token --clipboard.');
219
279
  }
220
- const pasted = await ask('Paste the refresh-token (or the session token) and press Enter: ', { hidden: true });
280
+ printLoginGuide();
281
+ const pasted = await ask('Refresh-token / session token (hidden): ', { hidden: true });
221
282
  const v = (pasted || '').trim().replace(/^["']|["']$/g, '');
222
283
  if (!v) throw usageError('No token was pasted.');
223
284
  if (v.startsWith('eyJ')) {
224
285
  token = v; // direct session JWT
225
286
  } else {
226
- saveProfile(ctx.profile, { refreshToken: v });
287
+ // Accepts the bare value, a whole "Cookie: ..." line, or a cookie export.
288
+ const rt = extractRefreshToken(v) || v;
289
+ saveProfile(ctx.profile, { refreshToken: rt });
227
290
  try {
228
- token = await sessionRefresh(v, ctx.profile, ctx.debug);
291
+ token = await sessionRefresh(rt, ctx.profile, ctx.debug);
229
292
  viaRefresh = true;
230
293
  } catch (e) {
231
294
  throw new CliError(e.exitCode || EXIT.AUTH,
232
295
  'Could not refresh the session with that refresh-token. ' + e.message,
233
- { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'] });
296
+ { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'],
297
+ details: e.extra?.details });
234
298
  }
235
299
  }
236
300
  try {
@@ -240,6 +304,19 @@ export async function authLogin(args, flags, ctx) {
240
304
  throw new CliError(EXIT.AUTH, 'The API rejected the token. Original error: ' + e.message,
241
305
  { reason: 'invalid_token' });
242
306
  }
307
+ // Same as --token: try to mint the session cookie pair so the session auto-renews.
308
+ if (token.startsWith('eyJ')) {
309
+ try {
310
+ const out = await sessionStart(token, ctx.profile, ctx.debug);
311
+ if (out) {
312
+ saveProfile(ctx.profile, { refreshToken: out.refreshToken, sessionAuthToken: out.authToken });
313
+ viaRefresh = true;
314
+ if (ctx.debug) console.error('wetaca: /session/start issued the session cookies (session is now auto-renewable)');
315
+ }
316
+ } catch (e) {
317
+ if (ctx.debug) console.error('wetaca: /session/start attempt failed: ' + e.message);
318
+ }
319
+ }
243
320
  }
244
321
 
245
322
  // The session token and (if imported) the refresh-token are saved. NEVER the password.
@@ -401,7 +478,9 @@ export async function sugEdit(args, flags, ctx) {
401
478
  if (!id || !qty) throw usageError(`Invalid pair in --set: '${pair}' (id:qty format).`);
402
479
  const n = parseInt(qty, 10);
403
480
  if (!Number.isInteger(n) || n < 0) throw usageError(`Invalid quantity in '${pair}'.`);
404
- return { id, quantity: n };
481
+ const pid = parseInt(id, 10); // the API declares productsInput[].id as Int (ModelId)
482
+ if (!Number.isInteger(pid) || pid <= 0) throw usageError(`Invalid product id in '${pair}' (must be numeric, from \`wetaca suggestion show\`).`);
483
+ return { id: pid, quantity: n };
405
484
  });
406
485
  const payload = { profileSuggestionId: psid, productsInput, resumeAccountSuggestion: flags.resume === undefined ? undefined : flags.resume === 'true' || flags.resume === true };
407
486
  if (ctx.dryRun) return { dryRun: true, wouldSend: { query: 'editProfileSuggestionMenu', variables: payload } };
@@ -640,7 +719,10 @@ export async function walletShow(args, flags, ctx) {
640
719
  // ---------- vouchers apply / gift cards ----------
641
720
 
642
721
  // `vouchers apply CODE` / `vouchers skip` — applies (or explicitly skips) a voucher
643
- // on next week's suggestion.
722
+ // on next week's suggestion. NOTE: the API implements `skip` as skipVoucher=true,
723
+ // which ALSO sets suggestion.skip=true (pauses next week's delivery). Verified live
724
+ // 2026-10-29 — `vouchers skip` == `suggestion pause` + explicit no-voucher.
725
+ // Revert with `suggestion resume`.
644
726
  export async function vouchersApply(args, flags, ctx) {
645
727
  const skip = args[0] === 'skip' || flags.skip === true;
646
728
  const code = skip ? undefined : args[0];
@@ -648,7 +730,9 @@ export async function vouchersApply(args, flags, ctx) {
648
730
  const sid = flags.suggestion || await nextSuggestionId(ctx.profile, ctx.debug);
649
731
  const payload = { voucherCode: skip ? undefined : code, skipVoucher: skip, suggestionId: sid };
650
732
  if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'assignNextSuggestionVoucher', variables: payload } };
651
- await confirm(flags, skip ? `Skip voucher on next week's delivery (suggestion ${sid}).` : `Apply voucher ${code} to next week's delivery (suggestion ${sid}).`);
733
+ await confirm(flags, skip
734
+ ? `Skip voucher on next week's delivery (suggestion ${sid}). WARNING: the API also pauses next week's delivery (skipVoucher=true sets suggestion.skip). Revert with: wetaca suggestion resume.`
735
+ : `Apply voucher ${code} to next week's delivery (suggestion ${sid}).`);
652
736
  const d = await gql(Q.ASSIGN_NEXT_SUGGESTION_VOUCHER, payload, { profile: ctx.profile, debug: ctx.debug });
653
737
  const r = d.assignNextSuggestionVoucher || {};
654
738
  return {
package/src/guide.js CHANGED
@@ -8,10 +8,12 @@ Every command returns JSON on stdout by default; errors go to stderr.
8
8
 
9
9
  1. Run \`wetaca doctor\` to check node, connectivity and session.
10
10
  2. \`wetaca auth status\` tells you whether there is a valid session. If there isn't:
11
- - \`wetaca auth login --cookies cookies.txt\` (export with the Cookie-Editor extension on wetaca.com while logged in) or \`--refresh-token COOKIE\` (a wetaca.com cookie, lasts ~120 days; the CLI renews the token on its own). No password involved.
12
- - \`wetaca auth login --token T\` or \`--token --clipboard\`: token copied from the
13
- \`authorization: Bearer *** header of any request to api.wetaca.com in the
14
- user's DevTools (F12 → Network). This is the way to go if their account logs in with Google.
11
+ - \`wetaca auth login --token T\` (or \`--token --clipboard\`, or paste it when prompted): copy the
12
+ \`authorization: Bearer *** header of any request to api.wetaca.com in the user's DevTools
13
+ (F12 → Network). The CLI validates it and then mints the session cookies exactly like the
14
+ website does after a login (POST /session/start issues the auth-token + refresh-token pair),
15
+ so the session auto-renews for ~120 days. This is the way to go if their account logs in
16
+ with Google. No password involved.
15
17
  Never ask the user for their Google password and never automate their browser for the login.
16
18
 
17
19
  ## Output contract
@@ -59,7 +61,10 @@ Every command returns JSON on stdout by default; errors go to stderr.
59
61
  wetaca vouchers list
60
62
  wetaca vouchers current voucher applied to next week (if any)
61
63
  wetaca vouchers apply <CODE> apply a voucher to next week (--dry-run first, then --yes)
62
- wetaca vouchers skip explicitly use no voucher next week
64
+ wetaca vouchers skip explicitly use no voucher next week (WARNING: the API
65
+ implements this as skipVoucher=true, which ALSO pauses
66
+ next week's delivery — same effect as suggestion pause.
67
+ Revert with: wetaca suggestion resume)
63
68
  wetaca giftcards show | redeem <CODE> gift card limits / redeem into wallet
64
69
  wetaca wallet
65
70
  wetaca config path | list | get <k> | set <k> <v>
package/src/lib.js CHANGED
@@ -45,7 +45,7 @@ export function configPath() { return path.join(configDir(), 'config.json'); }
45
45
  // El config.json nunca lleva secretos.
46
46
  export function credentialsPath() { return path.join(configDir(), 'credentials.json'); }
47
47
 
48
- const SECRET_KEYS = ['token', 'login', 'password', 'refreshToken'];
48
+ const SECRET_KEYS = ['token', 'login', 'password', 'refreshToken', 'sessionAuthToken'];
49
49
 
50
50
  // Permisos restrictivos: 0600 en POSIX; en Windows, ACL solo para el usuario actual.
51
51
  function restrictPerms(p) {
@@ -144,6 +144,16 @@ export function getToken(profileName) {
144
144
 
145
145
  // ---------- GraphQL client ----------
146
146
  const API_URL = process.env.WETACA_API_URL || 'https://api.wetaca.com/graphql';
147
+ // Session endpoints live on the main site origin, NOT on api.wetaca.com
148
+ // (POST https://api.wetaca.com/session/refresh -> 404 "Cannot POST";
149
+ // POST https://wetaca.com/session/refresh -> real route, 401 without a cookie).
150
+ const SESSION_REFRESH_URL = process.env.WETACA_SESSION_REFRESH_URL || 'https://wetaca.com/session/refresh';
151
+ // The web calls POST /session/start {token} right after validating credentials; its
152
+ // Set-Cookie response is what issues the auth-token + refresh-token cookies.
153
+ const SESSION_START_URL = process.env.WETACA_SESSION_START_URL || 'https://wetaca.com/session/start';
154
+ // wetaca.com's WAF (Cloudflare) 403s non-browser User-Agents on /session/refresh,
155
+ // while api.wetaca.com/graphql accepts the CLI UA. Use a browser UA for session endpoints only.
156
+ const BROWSER_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36';
147
157
  const UA = `wetaca-cli/${VERSION} (+https://github.com/gorgueugr/wetaca-cli)`;
148
158
 
149
159
  async function rawRequest(query, variables, tok, debug) {
@@ -173,13 +183,20 @@ async function rawRequest(query, variables, tok, debug) {
173
183
  throw e;
174
184
  }
175
185
  throw new CliError(EXIT.API, `The API responded with HTTP ${res.status}`,
176
- { reason: 'http_' + res.status, retryable: res.status >= 500 || res.status === 429 });
186
+ { reason: 'http_' + res.status, retryable: res.status >= 500 || res.status === 429, httpStatus: res.status });
177
187
  }
178
188
  let body;
179
189
  try { body = await res.json(); } catch {
180
190
  throw new CliError(EXIT.DRIFT, 'The API returned a non-JSON response (possible contract change).',
181
191
  { reason: 'contract_drift', retryable: false });
182
192
  }
193
+ // GraphQL validation errors can hide behind HTTP 500: surface them as an API error
194
+ // with the real message instead of an opaque retryable 500.
195
+ if (!res.ok && body?.errors?.length) {
196
+ const msg = body.errors.map((e) => e.message).join('; ');
197
+ throw new CliError(EXIT.API, `The API rejected the request (HTTP ${res.status}): ${msg}`,
198
+ { reason: 'graphql_error', retryable: false, details: body.errors });
199
+ }
183
200
  return body;
184
201
  }
185
202
 
@@ -193,28 +210,60 @@ function storedRefreshToken(profile) {
193
210
  return c?.refreshToken || null;
194
211
  }
195
212
 
213
+ // The auth-token cookie issued by /session/start (path=/). /session/refresh validates
214
+ // the auth-token + refresh-token PAIR, so both must travel in the Cookie header.
215
+ function storedSessionAuthToken(profile) {
216
+ const cfg = loadConfig();
217
+ const name = profile || cfg.defaultProfile || 'default';
218
+ return loadCreds().profiles?.[name]?.sessionAuthToken || null;
219
+ }
220
+
196
221
  // Renews the token with the refresh-token cookie (120 days) via POST /session/refresh,
197
222
  // just like the web does (bundles: auth-token + refresh-token cookies, x-wetaca-session).
198
223
  // Also exported for `auth login --refresh-token`.
224
+ // Chrome's cookie UI shows the DECODED value while the cookie travels percent-encoded,
225
+ // so we try the pasted value plus its encoded/decoded variants before giving up.
199
226
  export async function sessionRefresh(rt, profile, debug) {
200
- let res;
227
+ const candidates = [rt];
201
228
  try {
202
- res = await fetch(`${API_URL}/session/refresh`, {
203
- method: 'POST',
204
- headers: {
205
- 'Content-Type': 'application/json',
206
- Cookie: `refresh-token=${rt}`,
207
- 'x-wetaca-session': '1',
208
- 'User-Agent': UA,
209
- },
210
- });
211
- } catch (e) {
212
- throw new CliError(EXIT.NETWORK, `Could not connect to the Wetaca API: ${e.cause?.code || e.message}`,
213
- { reason: 'network', retryable: true });
229
+ const enc = encodeURIComponent(rt);
230
+ if (enc !== rt && !candidates.includes(enc)) candidates.push(enc);
231
+ const dec = decodeURIComponent(rt);
232
+ if (dec !== rt && !candidates.includes(dec)) candidates.push(dec);
233
+ } catch { /* malformed percent-encoding: keep the raw value */ }
234
+ const attempt = async (value) => {
235
+ const sessionAuth = storedSessionAuthToken(profile);
236
+ const cookie = sessionAuth
237
+ ? `auth-token=${sessionAuth}; refresh-token=${value}`
238
+ : `refresh-token=${value}`;
239
+ try {
240
+ return await fetch(SESSION_REFRESH_URL, {
241
+ method: 'POST',
242
+ headers: {
243
+ 'Content-Type': 'application/json',
244
+ Cookie: cookie,
245
+ 'x-wetaca-session': '1',
246
+ 'User-Agent': BROWSER_UA,
247
+ },
248
+ });
249
+ } catch (e) {
250
+ throw new CliError(EXIT.NETWORK, `Could not connect to the Wetaca API: ${e.cause?.code || e.message}`,
251
+ { reason: 'network', retryable: true });
252
+ }
253
+ };
254
+ let res = await attempt(candidates[0]);
255
+ for (let i = 1; i < candidates.length && (res.status === 400 || res.status === 401); i++) {
256
+ if (debug) console.error(`wetaca: refresh rejected with HTTP ${res.status}, retrying with re-encoded value (${i}/${candidates.length - 1})`);
257
+ res = await attempt(candidates[i]);
214
258
  }
259
+ if (debug) console.error(`wetaca: POST ${SESSION_REFRESH_URL} -> ${res.status}`);
215
260
  if (res.status === 400 || res.status === 401) {
216
- throw new CliError(EXIT.AUTH, 'The refresh-token is invalid (copied incorrectly, expired, or revoked). Copy it from wetaca.com while logged in: F12 → Application → Cookies → wetaca.com → refresh-token (full value).',
217
- { reason: 'refresh_token_invalid', retryable: false, suggested_commands: ['wetaca auth login --token T'] });
261
+ const body = (await res.text().catch(() => '')).slice(0, 200);
262
+ throw new CliError(EXIT.AUTH, 'The refresh-token is invalid (copied incorrectly, expired, or revoked). ' +
263
+ 'Copy it from wetaca.com while logged in: open https://wetaca.com/session/refresh (an "Unauthorized" page is expected), ' +
264
+ 'F12 -> Network -> click that request -> Cookies tab (Request Cookies) -> copy the full refresh-token value.',
265
+ { reason: 'refresh_token_invalid', retryable: false, suggested_commands: ['wetaca auth login --token T'],
266
+ details: { httpStatus: res.status, body } });
218
267
  }
219
268
  if (!res.ok) {
220
269
  throw new CliError(EXIT.API, `The API responded with HTTP ${res.status} while refreshing the session`,
@@ -238,6 +287,43 @@ export async function sessionRefresh(rt, profile, debug) {
238
287
  return j.token;
239
288
  }
240
289
 
290
+ // Starts a browser-style session from a session token (the web's step right after
291
+ // validating credentials): POST /session/start {token}. Wetaca responds with the session
292
+ // cookies (auth-token with path=/ and refresh-token with path=/session/refresh, httpOnly).
293
+ // /session/refresh validates the PAIR, so we capture both. Returns {refreshToken,
294
+ // authToken} or null if the endpoint declined (not fatal).
295
+ export async function sessionStart(token, profile, debug) {
296
+ let res;
297
+ try {
298
+ res = await fetch(SESSION_START_URL, {
299
+ method: 'POST',
300
+ headers: {
301
+ 'Content-Type': 'application/json',
302
+ 'x-wetaca-session': '1',
303
+ 'User-Agent': BROWSER_UA,
304
+ },
305
+ body: JSON.stringify({ token }),
306
+ });
307
+ } catch (e) {
308
+ throw new CliError(EXIT.NETWORK, `Could not connect to the Wetaca API: ${e.cause?.code || e.message}`,
309
+ { reason: 'network', retryable: true });
310
+ }
311
+ if (debug) console.error(`wetaca: POST ${SESSION_START_URL} -> ${res.status}`);
312
+ if (!res.ok) return null;
313
+ const setCookies = typeof res.headers.getSetCookie === 'function'
314
+ ? res.headers.getSetCookie()
315
+ : [res.headers.get('set-cookie')].filter(Boolean);
316
+ const out = { refreshToken: null, authToken: null };
317
+ for (const c of setCookies) {
318
+ const s = String(c);
319
+ let m = s.match(/(?:^|[,\s])refresh-token=([^;\s]+)/);
320
+ if (m && m[1]) out.refreshToken = m[1];
321
+ m = s.match(/(?:^|[,\s])auth-token=([^;\s]+)/);
322
+ if (m && m[1]) out.authToken = m[1];
323
+ }
324
+ return out.refreshToken ? out : null;
325
+ }
326
+
241
327
  export async function gql(query, variables, { token, profile, debug, anon = false } = {}) {
242
328
  const tok0 = token ?? getToken(profile);
243
329
  if (!tok0 && !anon) {