wetaca-cli 0.2.0 → 0.2.2
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/docs/GUIA.md +118 -118
- package/package.json +7 -3
- package/src/commands.js +700 -700
- package/src/lib.js +371 -371
package/src/lib.js
CHANGED
|
@@ -1,371 +1,371 @@
|
|
|
1
|
-
// wetaca-cli — core library: config, errors, GraphQL client, output.
|
|
2
|
-
// Zero dependencies. Node >= 18.
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import os from 'node:os';
|
|
6
|
-
import child_process from 'node:child_process';
|
|
7
|
-
import { createRequire } from 'node:module';
|
|
8
|
-
|
|
9
|
-
const require = createRequire(import.meta.url);
|
|
10
|
-
export const VERSION = require('../package.json').version;
|
|
11
|
-
|
|
12
|
-
// ---------- exit codes (stable contract) ----------
|
|
13
|
-
export const EXIT = {
|
|
14
|
-
OK: 0,
|
|
15
|
-
UNEXPECTED: 1, // bug or unknown failure
|
|
16
|
-
USAGE: 2, // bad flags/args, validation refused, declined confirmation
|
|
17
|
-
AUTH: 3, // no/invalid token -> run `wetaca auth login`
|
|
18
|
-
NETWORK: 4, // cannot reach api.wetaca.com
|
|
19
|
-
NOT_FOUND: 5, // unknown id / no resource
|
|
20
|
-
API: 6, // Wetaca API refused the operation (see details)
|
|
21
|
-
DRIFT: 7, // API contract drift: expected field missing / shape changed
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
export class CliError extends Error {
|
|
25
|
-
constructor(exitCode, message, extra = {}) {
|
|
26
|
-
super(message);
|
|
27
|
-
this.exitCode = exitCode;
|
|
28
|
-
this.extra = extra; // { reason, retryable, suggested_commands, details }
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function usageError(message, extra = {}) {
|
|
33
|
-
return new CliError(EXIT.USAGE, message, { reason: 'usage', retryable: false, ...extra });
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// ---------- config ----------
|
|
37
|
-
export function configDir() {
|
|
38
|
-
if (process.env.WETACA_CONFIG_DIR) return process.env.WETACA_CONFIG_DIR;
|
|
39
|
-
const xdg = process.env.XDG_CONFIG_HOME;
|
|
40
|
-
return path.join(xdg || path.join(os.homedir(), '.config'), 'wetaca-cli');
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function configPath() { return path.join(configDir(), 'config.json'); }
|
|
44
|
-
// Secretos (token/refreshToken) en fichero aparte con permisos restrictivos.
|
|
45
|
-
// El config.json nunca lleva secretos.
|
|
46
|
-
export function credentialsPath() { return path.join(configDir(), 'credentials.json'); }
|
|
47
|
-
|
|
48
|
-
const SECRET_KEYS = ['token', 'login', 'password', 'refreshToken'];
|
|
49
|
-
|
|
50
|
-
// Permisos restrictivos: 0600 en POSIX; en Windows, ACL solo para el usuario actual.
|
|
51
|
-
function restrictPerms(p) {
|
|
52
|
-
try {
|
|
53
|
-
if (process.platform === 'win32') {
|
|
54
|
-
const { execFileSync } = child_process;
|
|
55
|
-
execFileSync('icacls', [p, '/inheritance:r', '/grant:r', `${os.userInfo().username}:F`], { stdio: 'ignore', windowsHide: true });
|
|
56
|
-
} else {
|
|
57
|
-
fs.chmodSync(p, 0o600);
|
|
58
|
-
}
|
|
59
|
-
} catch { /* best effort: si falla, el fichero queda con permisos por defecto */ }
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function saveCreds(creds) {
|
|
63
|
-
fs.mkdirSync(configDir(), { recursive: true });
|
|
64
|
-
const tmp = credentialsPath() + '.tmp';
|
|
65
|
-
fs.writeFileSync(tmp, JSON.stringify(creds, null, 2) + '\n', { mode: 0o600 });
|
|
66
|
-
fs.renameSync(tmp, credentialsPath());
|
|
67
|
-
restrictPerms(credentialsPath());
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function loadCreds() {
|
|
71
|
-
try { return JSON.parse(fs.readFileSync(credentialsPath(), 'utf8')); } catch { return { profiles: {} }; }
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export function loadConfig() {
|
|
75
|
-
try {
|
|
76
|
-
return JSON.parse(fs.readFileSync(configPath(), 'utf8'));
|
|
77
|
-
} catch {
|
|
78
|
-
return { defaultProfile: 'default', profiles: {} };
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function saveConfig(cfg) {
|
|
83
|
-
fs.mkdirSync(configDir(), { recursive: true });
|
|
84
|
-
const tmp = configPath() + '.tmp';
|
|
85
|
-
fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2) + '\n');
|
|
86
|
-
fs.renameSync(tmp, configPath());
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export function getProfile(name, { create = false } = {}) {
|
|
90
|
-
const cfg = loadConfig();
|
|
91
|
-
name = name || cfg.defaultProfile || 'default';
|
|
92
|
-
// combined view: config.json (public) + credentials.json (secrets); the legacy
|
|
93
|
-
// one with secrets inside config.json keeps being read until migrated
|
|
94
|
-
const creds = loadCreds().profiles?.[name] || {};
|
|
95
|
-
const legacy = cfg.profiles?.[name] || {};
|
|
96
|
-
const p = { ...legacy, ...creds };
|
|
97
|
-
if (!legacy.token && !legacy.email && !legacy.login && !legacy.password && !Object.keys(creds).length) {
|
|
98
|
-
if (!create) return { name, token: null, email: null };
|
|
99
|
-
cfg.profiles = { ...(cfg.profiles || {}), [name]: { token: null, email: null } };
|
|
100
|
-
saveConfig(cfg);
|
|
101
|
-
return { name, token: null, email: null };
|
|
102
|
-
}
|
|
103
|
-
return { name, ...p };
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
export function saveProfile(name, data) {
|
|
107
|
-
const cfg = loadConfig();
|
|
108
|
-
name = name || cfg.defaultProfile || 'default';
|
|
109
|
-
const creds = loadCreds();
|
|
110
|
-
let credsDirty = false;
|
|
111
|
-
// secretos → credentials.json; resto → config.json
|
|
112
|
-
const sec = {}, pub = {};
|
|
113
|
-
for (const [k, v] of Object.entries(data)) (SECRET_KEYS.includes(k) ? sec : pub)[k] = v;
|
|
114
|
-
if (Object.keys(sec).length) {
|
|
115
|
-
creds.profiles = { ...(creds.profiles || {}), [name]: { ...(creds.profiles?.[name] || {}), ...sec } };
|
|
116
|
-
credsDirty = true;
|
|
117
|
-
}
|
|
118
|
-
// migration of legacy config.json: token/refreshToken move to credentials.json;
|
|
119
|
-
// login/password are DELETED (the CLI no longer stores passwords, user's decision)
|
|
120
|
-
for (const [pname, p] of Object.entries(cfg.profiles || {})) {
|
|
121
|
-
const legacy = SECRET_KEYS.filter((k) => p[k] != null);
|
|
122
|
-
if (!legacy.length) continue;
|
|
123
|
-
for (const k of legacy) {
|
|
124
|
-
if (k === 'login' || k === 'password') { delete p[k]; continue; }
|
|
125
|
-
creds.profiles = { ...(creds.profiles || {}) };
|
|
126
|
-
creds.profiles[pname] = { ...(creds.profiles?.[pname] || {}) };
|
|
127
|
-
creds.profiles[pname][k] ??= p[k];
|
|
128
|
-
delete p[k];
|
|
129
|
-
}
|
|
130
|
-
credsDirty = true;
|
|
131
|
-
}
|
|
132
|
-
if (credsDirty) saveCreds(creds);
|
|
133
|
-
if (Object.keys(pub).length) {
|
|
134
|
-
cfg.profiles = { ...(cfg.profiles || {}), [name]: { ...(cfg.profiles?.[name] || {}), ...pub } };
|
|
135
|
-
}
|
|
136
|
-
if (!cfg.defaultProfile) cfg.defaultProfile = name;
|
|
137
|
-
saveConfig(cfg);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
export function getToken(profileName) {
|
|
141
|
-
if (process.env.WETACA_TOKEN) return process.env.WETACA_TOKEN;
|
|
142
|
-
return getProfile(profileName).token || null;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// ---------- GraphQL client ----------
|
|
146
|
-
const API_URL = process.env.WETACA_API_URL || 'https://api.wetaca.com/graphql';
|
|
147
|
-
const UA = `wetaca-cli/${VERSION} (+https://github.com/gorgueugr/wetaca-cli)`;
|
|
148
|
-
|
|
149
|
-
async function rawRequest(query, variables, tok, debug) {
|
|
150
|
-
const headers = {
|
|
151
|
-
'Content-Type': 'application/json',
|
|
152
|
-
'User-Agent': UA,
|
|
153
|
-
};
|
|
154
|
-
if (tok) headers.authorization = `Bearer ${tok}`;
|
|
155
|
-
let res;
|
|
156
|
-
const started = Date.now();
|
|
157
|
-
try {
|
|
158
|
-
res = await fetch(API_URL, {
|
|
159
|
-
method: 'POST',
|
|
160
|
-
headers,
|
|
161
|
-
body: JSON.stringify({ query, variables: variables || {} }),
|
|
162
|
-
});
|
|
163
|
-
} catch (e) {
|
|
164
|
-
throw new CliError(EXIT.NETWORK, `Could not connect to the Wetaca API: ${e.cause?.code || e.message}`,
|
|
165
|
-
{ reason: 'network', retryable: true });
|
|
166
|
-
}
|
|
167
|
-
if (debug) console.error(`wetaca: POST ${API_URL} -> ${res.status} (${Date.now() - started} ms)`);
|
|
168
|
-
if (!res.ok) {
|
|
169
|
-
if (res.status === 401 || res.status === 403) {
|
|
170
|
-
const e = new CliError(EXIT.AUTH, 'The API rejected the session (401/403). The token may have expired.',
|
|
171
|
-
{ reason: 'auth_rejected', retryable: false, suggested_commands: ['wetaca auth login'] });
|
|
172
|
-
e.auth = true;
|
|
173
|
-
throw e;
|
|
174
|
-
}
|
|
175
|
-
throw new CliError(EXIT.API, `The API responded with HTTP ${res.status}`,
|
|
176
|
-
{ reason: 'http_' + res.status, retryable: res.status >= 500 || res.status === 429 });
|
|
177
|
-
}
|
|
178
|
-
let body;
|
|
179
|
-
try { body = await res.json(); } catch {
|
|
180
|
-
throw new CliError(EXIT.DRIFT, 'The API returned a non-JSON response (possible contract change).',
|
|
181
|
-
{ reason: 'contract_drift', retryable: false });
|
|
182
|
-
}
|
|
183
|
-
return body;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Stored credential for auto-refresh: ONLY the refresh-token (120-day cookie).
|
|
187
|
-
// The password is never requested nor stored (user's decision).
|
|
188
|
-
function storedRefreshToken(profile) {
|
|
189
|
-
if (process.env.WETACA_REFRESH_TOKEN) return process.env.WETACA_REFRESH_TOKEN;
|
|
190
|
-
const cfg = loadConfig();
|
|
191
|
-
const name = profile || cfg.defaultProfile || 'default';
|
|
192
|
-
const c = loadCreds().profiles?.[name];
|
|
193
|
-
return c?.refreshToken || null;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// Renews the token with the refresh-token cookie (120 days) via POST /session/refresh,
|
|
197
|
-
// just like the web does (bundles: auth-token + refresh-token cookies, x-wetaca-session).
|
|
198
|
-
// Also exported for `auth login --refresh-token`.
|
|
199
|
-
export async function sessionRefresh(rt, profile, debug) {
|
|
200
|
-
let res;
|
|
201
|
-
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 });
|
|
214
|
-
}
|
|
215
|
-
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'] });
|
|
218
|
-
}
|
|
219
|
-
if (!res.ok) {
|
|
220
|
-
throw new CliError(EXIT.API, `The API responded with HTTP ${res.status} while refreshing the session`,
|
|
221
|
-
{ reason: 'http_' + res.status, retryable: res.status >= 500 });
|
|
222
|
-
}
|
|
223
|
-
let j;
|
|
224
|
-
try { j = await res.json(); } catch {
|
|
225
|
-
throw new CliError(EXIT.DRIFT, 'The API returned a non-JSON response while refreshing the session.',
|
|
226
|
-
{ reason: 'contract_drift', retryable: false });
|
|
227
|
-
}
|
|
228
|
-
if (!j?.token) {
|
|
229
|
-
throw new CliError(EXIT.DRIFT, 'The refresh did not return a token (possible contract change).',
|
|
230
|
-
{ reason: 'contract_drift', retryable: false });
|
|
231
|
-
}
|
|
232
|
-
saveProfile(profile, { token: j.token });
|
|
233
|
-
// rotation: if the API issues a new refresh-token in Set-Cookie, we save it
|
|
234
|
-
const sc = res.headers.get('set-cookie');
|
|
235
|
-
const m = sc && sc.match(/(?:^|,\s*)refresh-token=([^;\s]+)/);
|
|
236
|
-
if (m && m[1] && m[1] !== rt) saveProfile(profile, { refreshToken: m[1] });
|
|
237
|
-
if (debug) console.error('wetaca: token automatically renewed (refresh-token)');
|
|
238
|
-
return j.token;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
export async function gql(query, variables, { token, profile, debug, anon = false } = {}) {
|
|
242
|
-
const tok0 = token ?? getToken(profile);
|
|
243
|
-
if (!tok0 && !anon) {
|
|
244
|
-
throw new CliError(EXIT.AUTH, 'No session. Run `wetaca auth login` (or set WETACA_TOKEN).',
|
|
245
|
-
{ reason: 'auth_required', retryable: false, suggested_commands: ['wetaca auth login'] });
|
|
246
|
-
}
|
|
247
|
-
// Auto-refresh: if the request fails due to an expired session and a refresh-token is stored,
|
|
248
|
-
// renew via /session/refresh and retry ONCE (only with the stored token).
|
|
249
|
-
const canRefresh = !anon && !token && !!storedRefreshToken(profile);
|
|
250
|
-
const call = async (tok) => {
|
|
251
|
-
const body = await rawRequest(query, variables, tok, debug);
|
|
252
|
-
if (body.errors?.length) {
|
|
253
|
-
const codes = body.errors.map((e) => e.extensions?.code).filter(Boolean);
|
|
254
|
-
if (codes.includes('UNAUTHENTICATED')) {
|
|
255
|
-
const e = new CliError(EXIT.AUTH, 'The session is not valid for this operation.',
|
|
256
|
-
{ reason: 'auth_required', retryable: false, suggested_commands: ['wetaca auth login'] });
|
|
257
|
-
e.auth = true;
|
|
258
|
-
throw e;
|
|
259
|
-
}
|
|
260
|
-
throw new CliError(EXIT.API, body.errors.map((e) => e.message).join('; '),
|
|
261
|
-
{ reason: 'graphql_error', retryable: false, details: body.errors });
|
|
262
|
-
}
|
|
263
|
-
// OJO: los campos top-level null son NORMALES en esta API (p. ej. nextPaymentPendingOrder
|
|
264
|
-
// null = "no hay pagos pendientes"); no implican deriva de contrato. Cada comando decide.
|
|
265
|
-
return body.data;
|
|
266
|
-
};
|
|
267
|
-
try {
|
|
268
|
-
return await call(tok0);
|
|
269
|
-
} catch (e) {
|
|
270
|
-
if (!canRefresh || !e.auth) throw e;
|
|
271
|
-
const rt = storedRefreshToken(profile);
|
|
272
|
-
if (!rt) throw e;
|
|
273
|
-
return call(await sessionRefresh(rt, profile, debug));
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// ---------- money / dates helpers ----------
|
|
278
|
-
export function cents(v) {
|
|
279
|
-
if (v == null) return null;
|
|
280
|
-
return (v / 100).toFixed(2).replace('.', ',') + ' €';
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
export function fmtWindow(option) {
|
|
284
|
-
if (!option) return null;
|
|
285
|
-
return fmtDate(option.start) + ' → ' + fmtDate(option.end);
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
export function fmtDate(iso) {
|
|
289
|
-
if (!iso) return null;
|
|
290
|
-
const d = new Date(iso);
|
|
291
|
-
if (isNaN(d)) return iso;
|
|
292
|
-
const wd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
|
|
293
|
-
const p = (n) => String(n).padStart(2, '0');
|
|
294
|
-
return `${wd} ${p(d.getDate())} ${['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()]} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// ---------- output ----------
|
|
298
|
-
export function isJsonFormat(fmt) { return fmt === 'json' || fmt === 'jsonl'; }
|
|
299
|
-
|
|
300
|
-
export function emit(data, { format, jsonl }) {
|
|
301
|
-
if (format === 'pretty') { printPretty(data); return; }
|
|
302
|
-
if (jsonl) {
|
|
303
|
-
const arr = Array.isArray(data) ? data : data.items;
|
|
304
|
-
if (Array.isArray(arr)) { for (const x of arr) console.log(JSON.stringify(x)); return; }
|
|
305
|
-
}
|
|
306
|
-
console.log(JSON.stringify(data, null, 2));
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
function printPretty(data, indent = '') {
|
|
310
|
-
if (Array.isArray(data)) {
|
|
311
|
-
if (data.length && typeof data[0] === 'object') printTable(data); else data.forEach((x) => console.log(indent + '- ' + x));
|
|
312
|
-
return;
|
|
313
|
-
}
|
|
314
|
-
if (typeof data !== 'object' || data === null) { console.log(indent + String(data)); return; }
|
|
315
|
-
for (const [k, v] of Object.entries(data)) {
|
|
316
|
-
if (v == null) continue;
|
|
317
|
-
if (typeof v === 'object' && !Array.isArray(v)) {
|
|
318
|
-
console.log(indent + k + ':');
|
|
319
|
-
printPretty(v, indent + ' ');
|
|
320
|
-
} else if (Array.isArray(v)) {
|
|
321
|
-
console.log(indent + k + ':');
|
|
322
|
-
printPretty(v, indent + ' ');
|
|
323
|
-
} else {
|
|
324
|
-
// prices in cents → euros in pretty mode
|
|
325
|
-
const isCents = /price|toPay|balance/i.test(k) && typeof v === 'number' && v > 100;
|
|
326
|
-
console.log(indent + `${k}: ${isCents ? cents(v) : v}`);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
function printTable(rows) {
|
|
332
|
-
const cols = Object.keys(rows[0]);
|
|
333
|
-
const cell = (v, k) => {
|
|
334
|
-
if (v == null) return '';
|
|
335
|
-
if (Array.isArray(v)) return v.map((x) => cell(x)).join(', ');
|
|
336
|
-
if (typeof v === 'object') {
|
|
337
|
-
if (typeof v.name === 'string') return v.name;
|
|
338
|
-
return Object.entries(v).filter(([, x]) => x != null && typeof x !== 'object')
|
|
339
|
-
.map(([kk, x]) => `${kk}=${x}`).join(' ');
|
|
340
|
-
}
|
|
341
|
-
if (typeof v === 'number' && /price|toPay/i.test(k || '') && v > 100) return cents(v);
|
|
342
|
-
return String(v);
|
|
343
|
-
};
|
|
344
|
-
const w = {};
|
|
345
|
-
for (const c of cols) w[c] = Math.min(Math.max(c.length, ...rows.map((r) => cell(r[c], c).length)), 40);
|
|
346
|
-
const line = (l, m, r) => l + cols.map((c) => '─'.repeat(w[c])).join(m) + r;
|
|
347
|
-
console.log(line('┌', '┬', '┐'));
|
|
348
|
-
console.log('│' + cols.map((c) => c.padEnd(w[c])).join('│') + '│');
|
|
349
|
-
console.log(line('├', '┼', '┤'));
|
|
350
|
-
for (const r of rows) console.log('│' + cols.map((c) => cell(r[c], c).slice(0, w[c]).padEnd(w[c])).join('│') + '│');
|
|
351
|
-
console.log(line('└', '┴', '┘'));
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
export function printError(err, errorFormat, debug = false) {
|
|
355
|
-
if (errorFormat === 'json') {
|
|
356
|
-
console.error(JSON.stringify({
|
|
357
|
-
error: {
|
|
358
|
-
code: err.exitCode,
|
|
359
|
-
category: Object.entries(EXIT).find(([, v]) => v === err.exitCode)?.[0]?.toLowerCase() || 'unexpected',
|
|
360
|
-
reason: err.extra?.reason || 'unexpected',
|
|
361
|
-
retryable: !!err.extra?.retryable,
|
|
362
|
-
message: err.message,
|
|
363
|
-
suggested_commands: err.extra?.suggested_commands || [],
|
|
364
|
-
...(debug && err.extra?.details ? { details: err.extra.details } : {}),
|
|
365
|
-
},
|
|
366
|
-
}, null, 2));
|
|
367
|
-
} else {
|
|
368
|
-
console.error('wetaca: ' + err.message);
|
|
369
|
-
if (err.extra?.suggested_commands?.length) console.error(' → ' + err.extra.suggested_commands.join(' ; '));
|
|
370
|
-
}
|
|
371
|
-
}
|
|
1
|
+
// wetaca-cli — core library: config, errors, GraphQL client, output.
|
|
2
|
+
// Zero dependencies. Node >= 18.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import child_process from 'node:child_process';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
|
|
9
|
+
const require = createRequire(import.meta.url);
|
|
10
|
+
export const VERSION = require('../package.json').version;
|
|
11
|
+
|
|
12
|
+
// ---------- exit codes (stable contract) ----------
|
|
13
|
+
export const EXIT = {
|
|
14
|
+
OK: 0,
|
|
15
|
+
UNEXPECTED: 1, // bug or unknown failure
|
|
16
|
+
USAGE: 2, // bad flags/args, validation refused, declined confirmation
|
|
17
|
+
AUTH: 3, // no/invalid token -> run `wetaca auth login`
|
|
18
|
+
NETWORK: 4, // cannot reach api.wetaca.com
|
|
19
|
+
NOT_FOUND: 5, // unknown id / no resource
|
|
20
|
+
API: 6, // Wetaca API refused the operation (see details)
|
|
21
|
+
DRIFT: 7, // API contract drift: expected field missing / shape changed
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export class CliError extends Error {
|
|
25
|
+
constructor(exitCode, message, extra = {}) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.exitCode = exitCode;
|
|
28
|
+
this.extra = extra; // { reason, retryable, suggested_commands, details }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function usageError(message, extra = {}) {
|
|
33
|
+
return new CliError(EXIT.USAGE, message, { reason: 'usage', retryable: false, ...extra });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ---------- config ----------
|
|
37
|
+
export function configDir() {
|
|
38
|
+
if (process.env.WETACA_CONFIG_DIR) return process.env.WETACA_CONFIG_DIR;
|
|
39
|
+
const xdg = process.env.XDG_CONFIG_HOME;
|
|
40
|
+
return path.join(xdg || path.join(os.homedir(), '.config'), 'wetaca-cli');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function configPath() { return path.join(configDir(), 'config.json'); }
|
|
44
|
+
// Secretos (token/refreshToken) en fichero aparte con permisos restrictivos.
|
|
45
|
+
// El config.json nunca lleva secretos.
|
|
46
|
+
export function credentialsPath() { return path.join(configDir(), 'credentials.json'); }
|
|
47
|
+
|
|
48
|
+
const SECRET_KEYS = ['token', 'login', 'password', 'refreshToken'];
|
|
49
|
+
|
|
50
|
+
// Permisos restrictivos: 0600 en POSIX; en Windows, ACL solo para el usuario actual.
|
|
51
|
+
function restrictPerms(p) {
|
|
52
|
+
try {
|
|
53
|
+
if (process.platform === 'win32') {
|
|
54
|
+
const { execFileSync } = child_process;
|
|
55
|
+
execFileSync('icacls', [p, '/inheritance:r', '/grant:r', `${os.userInfo().username}:F`], { stdio: 'ignore', windowsHide: true });
|
|
56
|
+
} else {
|
|
57
|
+
fs.chmodSync(p, 0o600);
|
|
58
|
+
}
|
|
59
|
+
} catch { /* best effort: si falla, el fichero queda con permisos por defecto */ }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function saveCreds(creds) {
|
|
63
|
+
fs.mkdirSync(configDir(), { recursive: true });
|
|
64
|
+
const tmp = credentialsPath() + '.tmp';
|
|
65
|
+
fs.writeFileSync(tmp, JSON.stringify(creds, null, 2) + '\n', { mode: 0o600 });
|
|
66
|
+
fs.renameSync(tmp, credentialsPath());
|
|
67
|
+
restrictPerms(credentialsPath());
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function loadCreds() {
|
|
71
|
+
try { return JSON.parse(fs.readFileSync(credentialsPath(), 'utf8')); } catch { return { profiles: {} }; }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function loadConfig() {
|
|
75
|
+
try {
|
|
76
|
+
return JSON.parse(fs.readFileSync(configPath(), 'utf8'));
|
|
77
|
+
} catch {
|
|
78
|
+
return { defaultProfile: 'default', profiles: {} };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function saveConfig(cfg) {
|
|
83
|
+
fs.mkdirSync(configDir(), { recursive: true });
|
|
84
|
+
const tmp = configPath() + '.tmp';
|
|
85
|
+
fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2) + '\n');
|
|
86
|
+
fs.renameSync(tmp, configPath());
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function getProfile(name, { create = false } = {}) {
|
|
90
|
+
const cfg = loadConfig();
|
|
91
|
+
name = name || cfg.defaultProfile || 'default';
|
|
92
|
+
// combined view: config.json (public) + credentials.json (secrets); the legacy
|
|
93
|
+
// one with secrets inside config.json keeps being read until migrated
|
|
94
|
+
const creds = loadCreds().profiles?.[name] || {};
|
|
95
|
+
const legacy = cfg.profiles?.[name] || {};
|
|
96
|
+
const p = { ...legacy, ...creds };
|
|
97
|
+
if (!legacy.token && !legacy.email && !legacy.login && !legacy.password && !Object.keys(creds).length) {
|
|
98
|
+
if (!create) return { name, token: null, email: null };
|
|
99
|
+
cfg.profiles = { ...(cfg.profiles || {}), [name]: { token: null, email: null } };
|
|
100
|
+
saveConfig(cfg);
|
|
101
|
+
return { name, token: null, email: null };
|
|
102
|
+
}
|
|
103
|
+
return { name, ...p };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function saveProfile(name, data) {
|
|
107
|
+
const cfg = loadConfig();
|
|
108
|
+
name = name || cfg.defaultProfile || 'default';
|
|
109
|
+
const creds = loadCreds();
|
|
110
|
+
let credsDirty = false;
|
|
111
|
+
// secretos → credentials.json; resto → config.json
|
|
112
|
+
const sec = {}, pub = {};
|
|
113
|
+
for (const [k, v] of Object.entries(data)) (SECRET_KEYS.includes(k) ? sec : pub)[k] = v;
|
|
114
|
+
if (Object.keys(sec).length) {
|
|
115
|
+
creds.profiles = { ...(creds.profiles || {}), [name]: { ...(creds.profiles?.[name] || {}), ...sec } };
|
|
116
|
+
credsDirty = true;
|
|
117
|
+
}
|
|
118
|
+
// migration of legacy config.json: token/refreshToken move to credentials.json;
|
|
119
|
+
// login/password are DELETED (the CLI no longer stores passwords, user's decision)
|
|
120
|
+
for (const [pname, p] of Object.entries(cfg.profiles || {})) {
|
|
121
|
+
const legacy = SECRET_KEYS.filter((k) => p[k] != null);
|
|
122
|
+
if (!legacy.length) continue;
|
|
123
|
+
for (const k of legacy) {
|
|
124
|
+
if (k === 'login' || k === 'password') { delete p[k]; continue; }
|
|
125
|
+
creds.profiles = { ...(creds.profiles || {}) };
|
|
126
|
+
creds.profiles[pname] = { ...(creds.profiles?.[pname] || {}) };
|
|
127
|
+
creds.profiles[pname][k] ??= p[k];
|
|
128
|
+
delete p[k];
|
|
129
|
+
}
|
|
130
|
+
credsDirty = true;
|
|
131
|
+
}
|
|
132
|
+
if (credsDirty) saveCreds(creds);
|
|
133
|
+
if (Object.keys(pub).length) {
|
|
134
|
+
cfg.profiles = { ...(cfg.profiles || {}), [name]: { ...(cfg.profiles?.[name] || {}), ...pub } };
|
|
135
|
+
}
|
|
136
|
+
if (!cfg.defaultProfile) cfg.defaultProfile = name;
|
|
137
|
+
saveConfig(cfg);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function getToken(profileName) {
|
|
141
|
+
if (process.env.WETACA_TOKEN) return process.env.WETACA_TOKEN;
|
|
142
|
+
return getProfile(profileName).token || null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------- GraphQL client ----------
|
|
146
|
+
const API_URL = process.env.WETACA_API_URL || 'https://api.wetaca.com/graphql';
|
|
147
|
+
const UA = `wetaca-cli/${VERSION} (+https://github.com/gorgueugr/wetaca-cli)`;
|
|
148
|
+
|
|
149
|
+
async function rawRequest(query, variables, tok, debug) {
|
|
150
|
+
const headers = {
|
|
151
|
+
'Content-Type': 'application/json',
|
|
152
|
+
'User-Agent': UA,
|
|
153
|
+
};
|
|
154
|
+
if (tok) headers.authorization = `Bearer ${tok}`;
|
|
155
|
+
let res;
|
|
156
|
+
const started = Date.now();
|
|
157
|
+
try {
|
|
158
|
+
res = await fetch(API_URL, {
|
|
159
|
+
method: 'POST',
|
|
160
|
+
headers,
|
|
161
|
+
body: JSON.stringify({ query, variables: variables || {} }),
|
|
162
|
+
});
|
|
163
|
+
} catch (e) {
|
|
164
|
+
throw new CliError(EXIT.NETWORK, `Could not connect to the Wetaca API: ${e.cause?.code || e.message}`,
|
|
165
|
+
{ reason: 'network', retryable: true });
|
|
166
|
+
}
|
|
167
|
+
if (debug) console.error(`wetaca: POST ${API_URL} -> ${res.status} (${Date.now() - started} ms)`);
|
|
168
|
+
if (!res.ok) {
|
|
169
|
+
if (res.status === 401 || res.status === 403) {
|
|
170
|
+
const e = new CliError(EXIT.AUTH, 'The API rejected the session (401/403). The token may have expired.',
|
|
171
|
+
{ reason: 'auth_rejected', retryable: false, suggested_commands: ['wetaca auth login'] });
|
|
172
|
+
e.auth = true;
|
|
173
|
+
throw e;
|
|
174
|
+
}
|
|
175
|
+
throw new CliError(EXIT.API, `The API responded with HTTP ${res.status}`,
|
|
176
|
+
{ reason: 'http_' + res.status, retryable: res.status >= 500 || res.status === 429 });
|
|
177
|
+
}
|
|
178
|
+
let body;
|
|
179
|
+
try { body = await res.json(); } catch {
|
|
180
|
+
throw new CliError(EXIT.DRIFT, 'The API returned a non-JSON response (possible contract change).',
|
|
181
|
+
{ reason: 'contract_drift', retryable: false });
|
|
182
|
+
}
|
|
183
|
+
return body;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Stored credential for auto-refresh: ONLY the refresh-token (120-day cookie).
|
|
187
|
+
// The password is never requested nor stored (user's decision).
|
|
188
|
+
function storedRefreshToken(profile) {
|
|
189
|
+
if (process.env.WETACA_REFRESH_TOKEN) return process.env.WETACA_REFRESH_TOKEN;
|
|
190
|
+
const cfg = loadConfig();
|
|
191
|
+
const name = profile || cfg.defaultProfile || 'default';
|
|
192
|
+
const c = loadCreds().profiles?.[name];
|
|
193
|
+
return c?.refreshToken || null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Renews the token with the refresh-token cookie (120 days) via POST /session/refresh,
|
|
197
|
+
// just like the web does (bundles: auth-token + refresh-token cookies, x-wetaca-session).
|
|
198
|
+
// Also exported for `auth login --refresh-token`.
|
|
199
|
+
export async function sessionRefresh(rt, profile, debug) {
|
|
200
|
+
let res;
|
|
201
|
+
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 });
|
|
214
|
+
}
|
|
215
|
+
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'] });
|
|
218
|
+
}
|
|
219
|
+
if (!res.ok) {
|
|
220
|
+
throw new CliError(EXIT.API, `The API responded with HTTP ${res.status} while refreshing the session`,
|
|
221
|
+
{ reason: 'http_' + res.status, retryable: res.status >= 500 });
|
|
222
|
+
}
|
|
223
|
+
let j;
|
|
224
|
+
try { j = await res.json(); } catch {
|
|
225
|
+
throw new CliError(EXIT.DRIFT, 'The API returned a non-JSON response while refreshing the session.',
|
|
226
|
+
{ reason: 'contract_drift', retryable: false });
|
|
227
|
+
}
|
|
228
|
+
if (!j?.token) {
|
|
229
|
+
throw new CliError(EXIT.DRIFT, 'The refresh did not return a token (possible contract change).',
|
|
230
|
+
{ reason: 'contract_drift', retryable: false });
|
|
231
|
+
}
|
|
232
|
+
saveProfile(profile, { token: j.token });
|
|
233
|
+
// rotation: if the API issues a new refresh-token in Set-Cookie, we save it
|
|
234
|
+
const sc = res.headers.get('set-cookie');
|
|
235
|
+
const m = sc && sc.match(/(?:^|,\s*)refresh-token=([^;\s]+)/);
|
|
236
|
+
if (m && m[1] && m[1] !== rt) saveProfile(profile, { refreshToken: m[1] });
|
|
237
|
+
if (debug) console.error('wetaca: token automatically renewed (refresh-token)');
|
|
238
|
+
return j.token;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export async function gql(query, variables, { token, profile, debug, anon = false } = {}) {
|
|
242
|
+
const tok0 = token ?? getToken(profile);
|
|
243
|
+
if (!tok0 && !anon) {
|
|
244
|
+
throw new CliError(EXIT.AUTH, 'No session. Run `wetaca auth login` (or set WETACA_TOKEN).',
|
|
245
|
+
{ reason: 'auth_required', retryable: false, suggested_commands: ['wetaca auth login'] });
|
|
246
|
+
}
|
|
247
|
+
// Auto-refresh: if the request fails due to an expired session and a refresh-token is stored,
|
|
248
|
+
// renew via /session/refresh and retry ONCE (only with the stored token).
|
|
249
|
+
const canRefresh = !anon && !token && !!storedRefreshToken(profile);
|
|
250
|
+
const call = async (tok) => {
|
|
251
|
+
const body = await rawRequest(query, variables, tok, debug);
|
|
252
|
+
if (body.errors?.length) {
|
|
253
|
+
const codes = body.errors.map((e) => e.extensions?.code).filter(Boolean);
|
|
254
|
+
if (codes.includes('UNAUTHENTICATED')) {
|
|
255
|
+
const e = new CliError(EXIT.AUTH, 'The session is not valid for this operation.',
|
|
256
|
+
{ reason: 'auth_required', retryable: false, suggested_commands: ['wetaca auth login'] });
|
|
257
|
+
e.auth = true;
|
|
258
|
+
throw e;
|
|
259
|
+
}
|
|
260
|
+
throw new CliError(EXIT.API, body.errors.map((e) => e.message).join('; '),
|
|
261
|
+
{ reason: 'graphql_error', retryable: false, details: body.errors });
|
|
262
|
+
}
|
|
263
|
+
// OJO: los campos top-level null son NORMALES en esta API (p. ej. nextPaymentPendingOrder
|
|
264
|
+
// null = "no hay pagos pendientes"); no implican deriva de contrato. Cada comando decide.
|
|
265
|
+
return body.data;
|
|
266
|
+
};
|
|
267
|
+
try {
|
|
268
|
+
return await call(tok0);
|
|
269
|
+
} catch (e) {
|
|
270
|
+
if (!canRefresh || !e.auth) throw e;
|
|
271
|
+
const rt = storedRefreshToken(profile);
|
|
272
|
+
if (!rt) throw e;
|
|
273
|
+
return call(await sessionRefresh(rt, profile, debug));
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ---------- money / dates helpers ----------
|
|
278
|
+
export function cents(v) {
|
|
279
|
+
if (v == null) return null;
|
|
280
|
+
return (v / 100).toFixed(2).replace('.', ',') + ' €';
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export function fmtWindow(option) {
|
|
284
|
+
if (!option) return null;
|
|
285
|
+
return fmtDate(option.start) + ' → ' + fmtDate(option.end);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function fmtDate(iso) {
|
|
289
|
+
if (!iso) return null;
|
|
290
|
+
const d = new Date(iso);
|
|
291
|
+
if (isNaN(d)) return iso;
|
|
292
|
+
const wd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
|
|
293
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
294
|
+
return `${wd} ${p(d.getDate())} ${['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()]} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// ---------- output ----------
|
|
298
|
+
export function isJsonFormat(fmt) { return fmt === 'json' || fmt === 'jsonl'; }
|
|
299
|
+
|
|
300
|
+
export function emit(data, { format, jsonl }) {
|
|
301
|
+
if (format === 'pretty') { printPretty(data); return; }
|
|
302
|
+
if (jsonl) {
|
|
303
|
+
const arr = Array.isArray(data) ? data : data.items;
|
|
304
|
+
if (Array.isArray(arr)) { for (const x of arr) console.log(JSON.stringify(x)); return; }
|
|
305
|
+
}
|
|
306
|
+
console.log(JSON.stringify(data, null, 2));
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function printPretty(data, indent = '') {
|
|
310
|
+
if (Array.isArray(data)) {
|
|
311
|
+
if (data.length && typeof data[0] === 'object') printTable(data); else data.forEach((x) => console.log(indent + '- ' + x));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (typeof data !== 'object' || data === null) { console.log(indent + String(data)); return; }
|
|
315
|
+
for (const [k, v] of Object.entries(data)) {
|
|
316
|
+
if (v == null) continue;
|
|
317
|
+
if (typeof v === 'object' && !Array.isArray(v)) {
|
|
318
|
+
console.log(indent + k + ':');
|
|
319
|
+
printPretty(v, indent + ' ');
|
|
320
|
+
} else if (Array.isArray(v)) {
|
|
321
|
+
console.log(indent + k + ':');
|
|
322
|
+
printPretty(v, indent + ' ');
|
|
323
|
+
} else {
|
|
324
|
+
// prices in cents → euros in pretty mode
|
|
325
|
+
const isCents = /price|toPay|balance/i.test(k) && typeof v === 'number' && v > 100;
|
|
326
|
+
console.log(indent + `${k}: ${isCents ? cents(v) : v}`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function printTable(rows) {
|
|
332
|
+
const cols = Object.keys(rows[0]);
|
|
333
|
+
const cell = (v, k) => {
|
|
334
|
+
if (v == null) return '';
|
|
335
|
+
if (Array.isArray(v)) return v.map((x) => cell(x)).join(', ');
|
|
336
|
+
if (typeof v === 'object') {
|
|
337
|
+
if (typeof v.name === 'string') return v.name;
|
|
338
|
+
return Object.entries(v).filter(([, x]) => x != null && typeof x !== 'object')
|
|
339
|
+
.map(([kk, x]) => `${kk}=${x}`).join(' ');
|
|
340
|
+
}
|
|
341
|
+
if (typeof v === 'number' && /price|toPay/i.test(k || '') && v > 100) return cents(v);
|
|
342
|
+
return String(v);
|
|
343
|
+
};
|
|
344
|
+
const w = {};
|
|
345
|
+
for (const c of cols) w[c] = Math.min(Math.max(c.length, ...rows.map((r) => cell(r[c], c).length)), 40);
|
|
346
|
+
const line = (l, m, r) => l + cols.map((c) => '─'.repeat(w[c])).join(m) + r;
|
|
347
|
+
console.log(line('┌', '┬', '┐'));
|
|
348
|
+
console.log('│' + cols.map((c) => c.padEnd(w[c])).join('│') + '│');
|
|
349
|
+
console.log(line('├', '┼', '┤'));
|
|
350
|
+
for (const r of rows) console.log('│' + cols.map((c) => cell(r[c], c).slice(0, w[c]).padEnd(w[c])).join('│') + '│');
|
|
351
|
+
console.log(line('└', '┴', '┘'));
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export function printError(err, errorFormat, debug = false) {
|
|
355
|
+
if (errorFormat === 'json') {
|
|
356
|
+
console.error(JSON.stringify({
|
|
357
|
+
error: {
|
|
358
|
+
code: err.exitCode,
|
|
359
|
+
category: Object.entries(EXIT).find(([, v]) => v === err.exitCode)?.[0]?.toLowerCase() || 'unexpected',
|
|
360
|
+
reason: err.extra?.reason || 'unexpected',
|
|
361
|
+
retryable: !!err.extra?.retryable,
|
|
362
|
+
message: err.message,
|
|
363
|
+
suggested_commands: err.extra?.suggested_commands || [],
|
|
364
|
+
...(debug && err.extra?.details ? { details: err.extra.details } : {}),
|
|
365
|
+
},
|
|
366
|
+
}, null, 2));
|
|
367
|
+
} else {
|
|
368
|
+
console.error('wetaca: ' + err.message);
|
|
369
|
+
if (err.extra?.suggested_commands?.length) console.error(' → ' + err.extra.suggested_commands.join(' ; '));
|
|
370
|
+
}
|
|
371
|
+
}
|