wetaca-cli 0.2.5 → 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/README.md CHANGED
@@ -41,8 +41,8 @@ A portable skill file is also available at [`skill/SKILL.md`](skill/SKILL.md) fo
41
41
  ## Get started
42
42
 
43
43
  ```
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
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)
46
46
  wetaca me --format pretty
47
47
  ```
48
48
 
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).
@@ -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
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.5",
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": {
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
 
@@ -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
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) {
@@ -200,28 +210,60 @@ function storedRefreshToken(profile) {
200
210
  return c?.refreshToken || null;
201
211
  }
202
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
+
203
221
  // Renews the token with the refresh-token cookie (120 days) via POST /session/refresh,
204
222
  // just like the web does (bundles: auth-token + refresh-token cookies, x-wetaca-session).
205
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.
206
226
  export async function sessionRefresh(rt, profile, debug) {
207
- let res;
227
+ const candidates = [rt];
208
228
  try {
209
- res = await fetch(`${API_URL}/session/refresh`, {
210
- method: 'POST',
211
- headers: {
212
- 'Content-Type': 'application/json',
213
- Cookie: `refresh-token=${rt}`,
214
- 'x-wetaca-session': '1',
215
- 'User-Agent': UA,
216
- },
217
- });
218
- } catch (e) {
219
- throw new CliError(EXIT.NETWORK, `Could not connect to the Wetaca API: ${e.cause?.code || e.message}`,
220
- { 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]);
221
258
  }
259
+ if (debug) console.error(`wetaca: POST ${SESSION_REFRESH_URL} -> ${res.status}`);
222
260
  if (res.status === 400 || res.status === 401) {
223
- 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).',
224
- { 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 } });
225
267
  }
226
268
  if (!res.ok) {
227
269
  throw new CliError(EXIT.API, `The API responded with HTTP ${res.status} while refreshing the session`,
@@ -245,6 +287,43 @@ export async function sessionRefresh(rt, profile, debug) {
245
287
  return j.token;
246
288
  }
247
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
+
248
327
  export async function gql(query, variables, { token, profile, debug, anon = false } = {}) {
249
328
  const tok0 = token ?? getToken(profile);
250
329
  if (!tok0 && !anon) {