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/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) {