wetaca-cli 0.2.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -18,6 +18,7 @@ Non-negotiable rules when acting on a real account:
18
18
  2. Mutations require an explicit summary → confirmation. In non-interactive runs pass `--yes` ONLY when the user asked for that exact operation.
19
19
  3. Prefer `--dry-run` before any mutation that supports it.
20
20
  4. Never touch payments (the CLI cannot either).
21
+ 5. When a command fails with exit 1/6/7, `wetaca report show` (redacted report) and, if the user agrees, `wetaca report create --yes` to file the issue. `report` needs no Wetaca session.
21
22
 
22
23
  ## Working on this codebase
23
24
 
@@ -27,5 +28,11 @@ Non-negotiable rules when acting on a real account:
27
28
  - 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
29
  - Mutations must follow the existing pattern: build payload → honor `--dry-run` → `confirm(flags, summary)` unless `--yes` → call `gql()`.
29
30
  - 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
+ - Check syntax before committing: `node --check` on every touched file. CI runs the same checks plus
32
+ `npm test` (`node --test test/*.test.mjs`: redaction, argv scrubbing, fingerprints, the report body,
33
+ the error cache and the full `report create` flow against a local GitHub API stub).
34
+ - `report` conventions: keep it dependency-free and offline-safe; every new field that can carry user
35
+ data must pass through `redact()`; never add a code path that posts to GitHub without the
36
+ confirmation step unless `--yes` was passed explicitly; new secrets/PII shapes belong in
37
+ `REDACTIONS` **and** in a test.
31
38
  - 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
@@ -38,11 +38,33 @@ wetaca skills get wetaca-usage
38
38
 
39
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`).
40
40
 
41
+ ## Report a bug (agents included)
42
+
43
+ Every real failure is cached locally with secrets and personal data stripped, so an agent can turn
44
+ "it broke" into a usable issue without ever seeing the user's credentials:
45
+
46
+ ```
47
+ wetaca report show # title + body + pre-filled GitHub URL (no credentials needed)
48
+ wetaca report last # the stored failure, raw
49
+ wetaca report create --yes # files the issue via `gh auth token` / GITHUB_TOKEN
50
+ ```
51
+
52
+ - Redaction happens before anything is written: session JWTs, cookies, `authorization` headers,
53
+ GitHub/npm tokens, e-mail addresses, phone numbers, street addresses, and the values of
54
+ `--token --refresh-token --street --city --zipcode --code` never reach the report.
55
+ - **Deduped by fingerprint**: the same failure always hashes to the same `wf-…` id, so a second run
56
+ returns the open issue (`mode: "existing"`) instead of a duplicate. `--force` files anyway.
57
+ - No GitHub credential? `wetaca report show --open` opens the pre-filled form, and `report_path`
58
+ in the JSON holds the full markdown.
59
+ - `--doctor` attaches `wetaca doctor`, `--notes "…"` adds context, `--error-file F` reports an error
60
+ captured elsewhere (`wetaca … --error-format json 2> err.json`).
61
+ - `report` needs no Wetaca session.
62
+
41
63
  ## Get started
42
64
 
43
65
  ```
44
- wetaca auth login --refresh-token <COOKIE> # refresh-token cookie from wetaca.com (lasts ~120 days)
45
- wetaca auth login # prompts for the refresh-token (hidden); also accepts a session JWT
66
+ 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)
67
+ wetaca auth login # opens the browser and prompts for the token (hidden)
46
68
  wetaca me --format pretty
47
69
  ```
48
70
 
@@ -82,6 +104,7 @@ wetaca skills get wetaca-usage
82
104
  | [Extracted operations](docs/api-operations/) | the ~190 GraphQL documents from Wetaca's website |
83
105
  | [Agent guide](docs/agent-guide.md) | `wetaca skills get wetaca-usage` |
84
106
  | [Agent skill](skill/SKILL.md) | portable SKILL.md for skill hubs (Hermes, Claude Code, OpenCode...) |
107
+ | [Spanish guide](docs/GUIA.md) | day-to-day recipes in Spanish |
85
108
 
86
109
  ## Good to know
87
110
 
package/bin/wetaca.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // wetaca-cli — entry point: arg parsing, dispatch, help, error handling.
3
3
  import { CliError, EXIT, printError, loadConfig, configPath, VERSION } from '../src/lib.js';
4
4
  import * as C from '../src/commands.js';
5
+ import { reportCmd, recordLastError } from '../src/report.js';
5
6
  import { GUIDE } from '../src/guide.js';
6
7
 
7
8
  const HELP = `wetaca-cli ${VERSION} — your Wetaca from the terminal.
@@ -10,14 +11,17 @@ USAGE
10
11
  wetaca [global flags] <noun> <verb> [args] [flags]
11
12
 
12
13
  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)
14
+ auth login [--token T [--clipboard] | --refresh-token COOKIE | --cookies FILE | --cookies-stdin] | status | logout
15
+ auth login opens https://wetaca.com in your browser: in DevTools (F12 -> Network ->
16
+ any request to api.wetaca.com) copy what comes after "authorization: Bearer "
17
+ (the session token) -> paste it at the prompt or pass --token T. The CLI
18
+ validates it and mints the session cookies via POST /session/start
19
+ (auth-token + refresh-token pair), so the session auto-renews itself
20
+ (~120 days). The password is never asked for.
21
+ Also accepted: --refresh-token COOKIE, a whole "Cookie:" header line, or a
22
+ cookie export (--cookies FILE / --cookies-stdin: Netscape, Cookie-Editor JSON).
23
+ Note: the server validates the auth-token + refresh-token PAIR; a bare
24
+ refresh-token always fails with 401.
21
25
  me show account summary
22
26
  subscription show | pause [--weeks N] | resume
23
27
  suggestion show | pause | resume | edit --profile-suggestion ID --set "id:qty,..."
@@ -36,6 +40,12 @@ COMMANDS
36
40
  wallet show
37
41
  config path | list | get <k> | set <k> <v>
38
42
  doctor diagnostics (node, network, session)
43
+ report show | last | create turn the last failure into a GitHub issue
44
+ show: redacted report + a pre-filled issue URL (no credentials needed)
45
+ last: the stored failure (raw, still redacted)
46
+ create [--yes]: files the issue with gh/GITHUB_TOKEN, deduped by fingerprint
47
+ flags: --title T --notes "..." --expected "..." --repo O/R --error-file F
48
+ --doctor (attach doctor output) --open (open the issue/URL) --force
39
49
  skills get wetaca-usage AI-agent guide (embedded)
40
50
  completion bash | zsh | fish autocompletion script
41
51
 
@@ -55,7 +65,7 @@ GLOBAL FLAGS
55
65
 
56
66
  const COMPLETION = {
57
67
  bash: `_wetaca() {
58
- local cur prev nouns="auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor skills completion"
68
+ local cur prev nouns="auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor report skills completion"
59
69
  COMPREPLY=()
60
70
  cur="\${COMP_WORDS[COMP_CWORD]}"
61
71
  if [ "$COMP_CWORD" -eq 1 ]; then COMPREPLY=( $(compgen -W "$nouns" -- "$cur") ); fi
@@ -63,16 +73,18 @@ const COMPLETION = {
63
73
  }
64
74
  complete -F _wetaca wetaca`,
65
75
  zsh: `#compdef wetaca
66
- _wetaca() { _alternative 'args:command:(auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor skills completion)' }
76
+ _wetaca() { _alternative 'args:command:(auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor report skills completion)' }
67
77
  _wetaca "$@"`,
68
- fish: `complete -c wetaca -n '__fish_use_subcommand' -a 'auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor skills completion'`,
78
+ fish: `complete -c wetaca -n '__fish_use_subcommand' -a 'auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor report skills completion'`,
69
79
  };
70
80
 
71
81
  // ---------- flag parsing ----------
72
- const BOOL_FLAGS = new Set(['yes', 'no-input', 'dry-run', 'debug', 'no-color', 'help', 'version', 'clipboard', 'cookies-stdin']);
82
+ const BOOL_FLAGS = new Set(['yes', 'no-input', 'dry-run', 'debug', 'no-color', 'help', 'version', 'clipboard', 'cookies-stdin',
83
+ 'open', 'force', 'doctor']);
73
84
  const VALUE_FLAGS = new Set(['format', 'error-format', 'profile', 'token', 'refresh-token', 'cookies',
74
85
  'weeks', 'feedback', 'set', 'limit', 'offset', 'suggestion', 'profile-suggestion', 'resume', 'code', 'state',
75
- 'street', 'number', 'floor', 'zipcode', 'city', 'notes', 'firstname', 'lastname', 'phone']);
86
+ 'street', 'number', 'floor', 'zipcode', 'city', 'notes', 'firstname', 'lastname', 'phone',
87
+ 'title', 'expected', 'repo', 'error-file', 'command']);
76
88
 
77
89
  function parseArgs(argv) {
78
90
  const flags = {}, positional = [];
@@ -216,6 +228,9 @@ async function main() {
216
228
  case 'doctor':
217
229
  result = await C.doctor(args, flags, ctx);
218
230
  break;
231
+ case 'report':
232
+ result = await reportCmd(verb, args, flags, ctx, { doctor: C.doctor, confirm: C.confirm });
233
+ break;
219
234
  case 'skills':
220
235
  if (verb === 'get' && args[0] === 'wetaca-usage') { process.stdout.write(GUIDE); return 0; }
221
236
  if (verb === 'list') { result = { skills: [{ id: 'wetaca-usage', description: 'AI-agent usage guide' }] }; break; }
@@ -247,6 +262,9 @@ main()
247
262
  const { flags } = parseArgs(process.argv.slice(2));
248
263
  const errorFormat = flags['error-format'] === 'json' ? 'json' : 'text';
249
264
  const debug = flags.debug === true;
265
+ // Keep the last failure on disk so `wetaca report` can turn it into an issue
266
+ // (secrets and personal data are redacted before it is written).
267
+ recordLastError(err);
250
268
  if (err instanceof CliError) {
251
269
  printError(err, errorFormat, debug);
252
270
  process.exitCode = err.exitCode;
package/docs/GUIA.md CHANGED
@@ -106,6 +106,24 @@ JSON on stdout, JSON errors with `--error-format json`, stable exit codes
106
106
 
107
107
  Golden rule for agents: read a lot, write little, and show a summary before `--yes`.
108
108
 
109
+ ### Reportar un fallo (para agentes y humanos)
110
+
111
+ El CLI guarda el último fallo real en `~/.config/wetaca-cli/last-error.json`, ya redactado:
112
+
113
+ ```bash
114
+ wetaca report show # título + cuerpo + URL de issue prerellenada (sin credenciales)
115
+ wetaca report show --open # abre el formulario de GitHub en el navegador
116
+ wetaca report create --yes # crea el issue con `gh auth token` o GITHUB_TOKEN
117
+ ```
118
+
119
+ - Se redactan antes de escribir nada: JWT de sesión, cookies, cabeceras `authorization`, tokens de
120
+ GitHub/npm, correos, teléfonos, direcciones y los valores de `--token --street --city --zipcode --code`.
121
+ - Mismo fallo → mismo fingerprint `wf-…` → reutiliza el issue abierto (`mode: "existing"`) en vez de duplicarlo.
122
+ - `--doctor` adjunta la salida de `wetaca doctor`; `--notes "…"` añade contexto (no metas datos de la cuenta).
123
+ - `report` no necesita sesión de Wetaca. Sin credencial de GitHub: `report show --open` y pega el
124
+ contenido de `report_path`.
125
+
126
+
109
127
  Automation ideas (cron):
110
128
  - Every Thursday: `suggestion show` → summary via Telegram → you reply with changes → agent applies them with `--yes`.
111
129
  - Every Wednesday: if `suggestion show | jq -r .validUntil` is close and `skip=false`, send a reminder to decide on pausing.
@@ -113,6 +131,6 @@ Automation ideas (cron):
113
131
 
114
132
  ## 4. Session
115
133
 
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).
134
+ - 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
135
  - 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
136
  - If the API rejects it (exit 3), redo the extraction with DevTools (docs/cli-spec.md §6).
@@ -7,10 +7,12 @@ Every command returns JSON on stdout by default; errors go to stderr.
7
7
 
8
8
  1. Run `wetaca doctor` to check node, connectivity and session.
9
9
  2. `wetaca auth status` tells you whether there is a valid session. If there isn't:
10
- - `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.
11
- - `wetaca auth login --token T` or `--token --clipboard`: token copied from the
12
- `authorization: Bearer *** header of any request to api.wetaca.com in the
13
- user's DevTools (F12 → Network). This is the way to go if their account logs in with Google.
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.
14
16
  Never ask the user for their Google password and never automate their browser for the login.
15
17
 
16
18
  ## Output contract
@@ -20,7 +22,24 @@ Every command returns JSON on stdout by default; errors go to stderr.
20
22
  - Stable exit codes: 0 ok · 1 unexpected · 2 usage/validation/confirmation denied · 3 auth ·
21
23
  4 network · 5 not found · 6 the API rejected the operation · 7 contract drift (schema changed).
22
24
  - `reason: "auth_required"` → nothing to retry; the user must log in.
23
- - `reason: "contract_drift"` → don't reinvent the query; open an issue on the repo.
25
+ - `reason: "contract_drift"` → don't reinvent the query; file a report: `wetaca report show` → `wetaca report create --yes`.
26
+
27
+ ## Reporting a bug (exit 1/6/7)
28
+
29
+ The CLI keeps the last real failure (redacted) on disk. `wetaca report show` turns it into a
30
+ GitHub issue: title, repro command, environment, error JSON and the failing project frames.
31
+ No Wetaca session is needed for this.
32
+
33
+ 1. `wetaca report show` — inspect the body. It is already redacted: tokens, cookies, e-mail,
34
+ phone numbers, street addresses and the values of `--token/--street/--city/--zipcode/--code`
35
+ never reach the report.
36
+ 2. `wetaca report create --yes` — opens the issue on github.com/gorgueugr/wetaca-cli using
37
+ `gh auth token` or `GITHUB_TOKEN`. Identical failures are deduped by fingerprint
38
+ (`mode: "existing"` + the open issue instead of a duplicate).
39
+ 3. Without a credential: `wetaca report show --open` opens the pre-filled GitHub form;
40
+ `report_path` in the JSON is the full markdown to paste.
41
+
42
+ Ask the user before filing an issue on their behalf. Never paste account data into `--notes`.
24
43
 
25
44
  ## Rules for operations with real effects
26
45
 
@@ -66,6 +85,7 @@ Every command returns JSON on stdout by default; errors go to stderr.
66
85
  wetaca wallet
67
86
  wetaca config path | list | get <k> | set <k> <v>
68
87
  wetaca doctor
88
+ wetaca report show | last | create [--yes] last failure -> GitHub issue (redacted)
69
89
  wetaca skills get wetaca-usage this guide
70
90
 
71
91
  ## Typical flows
package/docs/cli-spec.md CHANGED
@@ -44,6 +44,9 @@ vouchers list
44
44
  wallet show
45
45
  config path | list | get <k> | set <k> <v>
46
46
  doctor
47
+ report show | last | create [--yes] [--title T] [--notes S] [--expected S]
48
+ [--repo OWNER/REPO] [--error-file F] [--command "noun verb"]
49
+ [--doctor] [--open] [--force] [--dry-run]
47
50
  skills list | get wetaca-usage
48
51
  completion bash | zsh | fish
49
52
  ```
@@ -64,12 +67,12 @@ completion bash | zsh | fish
64
67
 
65
68
  ## 6. Session
66
69
 
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.
70
+ - **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.
71
+ - **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.
72
+ - **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
73
  - **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
74
  - 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`.
75
+ - 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
76
  - Header: `authorization: Bearer ***` on every request.
74
77
 
75
78
  ## 7. API
@@ -111,3 +114,47 @@ is unvalidated), new account sign-up with SMS, Google OAuth, weekly survey, acti
111
114
  - The `productId`/`profileSuggestionId` ids are internal; they are obtained from `suggestion show`/`deliveries next`.
112
115
  - The price is returned in cents (the `*Eur` field is already formatted in some responses).
113
116
  - `subscription pause` uses `cancelSubscriptionAccount` with `pausedWeeks`; the API treats it as a temporary pause. Without `--weeks` it is an indefinite pause; reactivate with `subscription resume`.
117
+
118
+ ## 11. Report (`wetaca report`)
119
+
120
+ Turns the last real failure into a GitHub issue, for people and for agents. Needs **no Wetaca session**.
121
+
122
+ **Cache.** Every command that fails with a non-usage error writes `<config>/last-error.json` (0600):
123
+ `{ at, command, argv, cli_version, node, platform, error: { code, category, reason, retryable, message,
124
+ suggested_commands, details?, stack_frames[] } }`. Usage errors, declined confirmations and
125
+ `wetaca report` itself never overwrite it. `WETACA_REPORT_CACHE=0` disables the cache.
126
+ `stack_frames` keeps only frames inside `src/` or `bin/` (`file.js:line`), so it never carries the
127
+ user's paths.
128
+
129
+ **Redaction** runs before anything is written, in the cache and in the report: session JWTs,
130
+ `authorization` headers, `Bearer`/`GitHub`/`npm` tokens, cookie pairs (`refresh-token=…`),
131
+ e-mail addresses, phone numbers (with or without separators), Spanish street lines, postal
132
+ code + city, `$HOME`/`C:\Users\…` paths, and the values of
133
+ `--token --refresh-token --cookies --password --code --street --number --floor --zipcode --city
134
+ --notes --firstname --lastname --phone --email`. Positional names in `profiles pause|resume`,
135
+ `vouchers apply` and `giftcards redeem` are replaced by `«redacted»`; numeric ids are kept.
136
+ `--notes` / `--expected` are user text and are appended **without** redaction: never put account
137
+ data there.
138
+
139
+ **Fingerprint**: `wf-` + the first 10 hex of sha256 over `command | reason | message` after
140
+ lower-casing, replacing ids/digit runs with `#` and truncating to 160 chars. Version-independent, so
141
+ the same failure across releases dedupes to one issue.
142
+
143
+ **Verbs and output.**
144
+ - `show` (default): writes `<config>/reports/report-<fingerprint>.md` and returns
145
+ `{ ok, mode: "manual", fingerprint, title, body, redactions, report_path, repo, issue_url, opened, next }`.
146
+ `issue_url` is the pre-filled `https://github.com/<repo>/issues/new?title=…&body=…&labels=bug`
147
+ (body capped at 6000 chars in the URL; the file always has the whole report).
148
+ - `last`: `{ ok, hasError, path, ...storedRecord }`.
149
+ - `create`: needs a GitHub credential — `GITHUB_TOKEN`/`GH_TOKEN`/`WETACA_REPORT_TOKEN`, else
150
+ `gh auth token`. No credential → exit 3 (`github_auth_required`) with `suggested_commands`.
151
+ Searches `repo:<repo> is:issue in:body "wetaca-report-fingerprint: <fp>"` first and returns
152
+ `mode: "existing"` when the fingerprint is already open (`--force` bypasses). Confirmation shows
153
+ the exact public body unless `--yes`. Returns `{ ok, mode: "created", issue: { number, url, state, labels } }`.
154
+ - `--dry-run` on `create` returns `wouldSend: { repo, title, body, labels }` and performs no network call.
155
+ - Flags: `--title`, `--notes`, `--expected`, `--repo OWNER/REPO` (default: the package's own repo;
156
+ env `WETACA_REPORT_REPO`), `--error-file FILE` (JSON error wrapper from
157
+ `--error-format json`), `--command "noun verb"`, `--doctor`, `--open`, `--force`.
158
+ - `WETACA_GITHUB_API` (or `GITHUB_API_URL`) overrides `https://api.github.com` — GHES and tests.
159
+ - GitHub errors: 401/403 → exit 3 (`github_auth`), 404 → exit 5, other → exit 6
160
+ (`github_http_<status>`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wetaca-cli",
3
- "version": "0.2.5",
3
+ "version": "0.3.0",
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": {
@@ -42,5 +42,8 @@
42
42
  "engines": {
43
43
  "node": ">=18"
44
44
  },
45
+ "scripts": {
46
+ "test": "node --test test/*.test.mjs"
47
+ },
45
48
  "license": "MIT"
46
49
  }
package/skill/SKILL.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: wetaca-usage
3
3
  description: Use when the user asks about Wetaca meals or deliveries.
4
- version: 0.2.4
4
+ version: 0.3.0
5
5
  author: Jorge Soler Padial (https://github.com/gorgueugr)
6
6
  license: MIT
7
7
  metadata:
@@ -35,5 +35,17 @@ Every command returns JSON on stdout by default (`--format pretty` for humans);
35
35
  3. Use `--dry-run` on `suggestion edit`, `addresses save`, `deliveries set-option`, `orders cancel` before any real run.
36
36
  4. Never touch payments — the CLI does not either.
37
37
  5. `reason: "auth_required"` → the user must run `wetaca auth login` (cookie-based; no password involved).
38
+ 6. If a command fails with exit 1/6/7, `wetaca report show` renders a redacted bug report (no session needed) and `wetaca report create --yes` files it on GitHub, deduped by fingerprint. Ask the user first; never paste account data into `--notes`.
39
+
40
+ ## Report a bug
41
+
42
+ Every real failure is cached on disk already redacted (tokens, cookies, e-mails, phones, addresses
43
+ and the values of `--token/--street/--city/--zipcode/--code` are removed). `wetaca report` turns it
44
+ into an issue: title, repro command, environment, error JSON and the failing project frames.
45
+
46
+ - `wetaca report show` → body + pre-filled GitHub URL, no credentials needed.
47
+ - `wetaca report create --yes` → files it via `gh auth token`/`GITHUB_TOKEN`; returns
48
+ `mode: "created"` with the issue, or `mode: "existing"` when the same fingerprint is already open.
49
+ - No GitHub credential → exit 3 with `suggested_commands` (`gh auth login`, `report show --open`).
38
50
 
39
51
  Project source: https://github.com/gorgueugr/wetaca-cli
package/src/commands.js CHANGED
@@ -5,7 +5,7 @@ import fs from 'node:fs';
5
5
  import {
6
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
 
@@ -57,7 +57,7 @@ export function extractRefreshToken(text) {
57
57
  return null;
58
58
  }
59
59
 
60
- async function confirm(flags, summary) {
60
+ export async function confirm(flags, summary) {
61
61
  if (flags.yes) return;
62
62
  if (flags.noInput || !process.stdin.isTTY) {
63
63
  throw usageError(
@@ -74,7 +74,7 @@ async function confirm(flags, summary) {
74
74
  }
75
75
 
76
76
  function requireId(v, what) {
77
- if (!v) throw usageError(`Missing <${what}>.`);
77
+ if (!v) throw usageError(`Missing <${String(what).replace(/[<>]/g, '')}>.`);
78
78
  return v;
79
79
  }
80
80
 
@@ -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.
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
@@ -21,7 +23,24 @@ Every command returns JSON on stdout by default; errors go to stderr.
21
23
  - Stable exit codes: 0 ok · 1 unexpected · 2 usage/validation/confirmation denied · 3 auth ·
22
24
  4 network · 5 not found · 6 the API rejected the operation · 7 contract drift (schema changed).
23
25
  - \`reason: "auth_required"\` → nothing to retry; the user must log in.
24
- - \`reason: "contract_drift"\` → don't reinvent the query; open an issue on the repo.
26
+ - \`reason: "contract_drift"\` → don't reinvent the query; file a report: \`wetaca report show\` → \`wetaca report create --yes\`.
27
+
28
+ ## Reporting a bug (exit 1/6/7)
29
+
30
+ The CLI keeps the last real failure (redacted) on disk. \`wetaca report show\` turns it into a
31
+ GitHub issue: title, repro command, environment, error JSON and the failing project frames.
32
+ No Wetaca session is needed for this.
33
+
34
+ 1. \`wetaca report show\` — inspect the body. It is already redacted: tokens, cookies, e-mail,
35
+ phone numbers, street addresses and the values of \`--token/--street/--city/--zipcode/--code\`
36
+ never reach the report.
37
+ 2. \`wetaca report create --yes\` — opens the issue on github.com/gorgueugr/wetaca-cli using
38
+ \`gh auth token\` or \`GITHUB_TOKEN\`. Identical failures are deduped by fingerprint
39
+ (\`mode: "existing"\` + the open issue instead of a duplicate).
40
+ 3. Without a credential: \`wetaca report show --open\` opens the pre-filled GitHub form;
41
+ \`report_path\` in the JSON is the full markdown to paste.
42
+
43
+ Ask the user before filing an issue on their behalf. Never paste account data into \`--notes\`.
25
44
 
26
45
  ## Rules for operations with real effects
27
46
 
@@ -67,6 +86,7 @@ Every command returns JSON on stdout by default; errors go to stderr.
67
86
  wetaca wallet
68
87
  wetaca config path | list | get <k> | set <k> <v>
69
88
  wetaca doctor
89
+ wetaca report show | last | create [--yes] last failure -> GitHub issue (redacted)
70
90
  wetaca skills get wetaca-usage this guide
71
91
 
72
92
  ## Typical flows