From 86334b4848597cb26a13b18b457e779c78625afb Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Thu, 30 Jul 2026 22:00:43 -0600 Subject: [PATCH] =?UTF-8?q?ADFA-4949=20fix(dashboard):=20close=20out=20the?= =?UTF-8?q?=20Kolibri=20pass=20=E2=80=94=20review=20nits,=20credential=20t?= =?UTF-8?q?ests,=20books=20on=20the=20shared=20store?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second review follow-up. Finishes the dashboard side so the remaining work (Android wishlist/service, Courses screen, catalog asset) does not have to come back here. login() no longer reports HTTP 400 as bad credentials. 400 is the serializer rejecting the request — a missing field, an unknown facility — and calling that "wrong password" sends the operator to change a password that was fine. It is now 'protocol' and carries the response body. readStore() logs when it degrades. A corrupt or unreadable credentials.json silently fell back to Admin/changeme, so the symptom surfaced later as an auth failure with no stated cause. ENOENT stays quiet: no override yet is the normal case. deleteChannel()'s job id is now usable. It returns a Kolibri task id, and nothing in our API could poll it. Added getKolibriTask() and GET /kolibri/task/:id, and the delete response carries statusUrl. authStatus() distinguishes upstream from ours. A fetch timeout or connection failure means Kolibri is not ready (503), not that we broke (500); a KolibriApiError propagates 401/403 and otherwise reports 502. credentials.ts has tests: 16 covering the env -> override -> factory precedence, that half a credential in the environment does not apply, 0600 permissions, no leftover .tmp files from the atomic write, degradation on corrupt and wrong-shaped JSON, input validation, that the username is trimmed and the password is not, that describeCredential never returns the password, and that isDefault still flags a hand-written Admin/changeme. books moved onto the shared store. books.exec.ts and books.query.ts had the credentials inline with a comment saying an override could be added later; this is that override. Behaviour on an untouched device is identical — verified that getCredential('calibre') resolves to Admin/changeme with no override present — but a device whose Calibre-Web password changed now keeps working without a rebuild. No inline credentials remain in the dashboard. Verified: tsc --noEmit clean, build OK, npm test 64/64 (48 + 16 new). Runner re-exercised against the mock across the happy, failed, empty-COMPLETED and session-expiry scenarios; no change in behaviour. --- static/dashboard/package.json | 2 +- static/dashboard/routes.ts | 29 ++- static/dashboard/sockets/books.exec.ts | 13 +- static/dashboard/sockets/books.query.ts | 9 +- static/dashboard/sockets/credentials.test.ts | 244 +++++++++++++++++++ static/dashboard/sockets/credentials.ts | 23 +- static/dashboard/sockets/kolibri.query.ts | 39 ++- static/dashboard/sockets/kolibri.session.ts | 13 +- 8 files changed, 352 insertions(+), 20 deletions(-) create mode 100644 static/dashboard/sockets/credentials.test.ts diff --git a/static/dashboard/package.json b/static/dashboard/package.json index c37e773bc..28f7fce3f 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -4,7 +4,7 @@ "description": "", "main": "index.js", "scripts": { - "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts", + "test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts", "typecheck": "tsc --noEmit", "build": "tsc", "start": "node dist/server.js" diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts index f35868e77..9177a8aca 100644 --- a/static/dashboard/routes.ts +++ b/static/dashboard/routes.ts @@ -11,9 +11,9 @@ import { searchCatalog, listLibrary, removeBook, listLanguages } from './sockets import { parseBox, parseEstimate } from './sockets/maps.socket'; import { preflight, listInstalledChannels, browseRemoteChannels, resolveIdentifier, - browseChannelTree, estimateSelection, deleteChannel, verifyCredentials, + browseChannelTree, estimateSelection, deleteChannel, getKolibriTask, verifyCredentials, } from './sockets/kolibri.query'; -import { checkReadiness, KolibriAuthError } from './sockets/kolibri.session'; +import { checkReadiness, KolibriAuthError, KolibriApiError } from './sockets/kolibri.session'; import { describeCredential, setCredential, clearCredential, isServiceName, } from './sockets/credentials'; @@ -179,6 +179,17 @@ function authStatus(e: unknown): number { default: return 502; } } + // Kolibri respondió, pero con error: propagamos su semántica en lugar de un 500. + if (e instanceof KolibriApiError) { + if (e.status === 401 || e.status === 403) return e.status; + return e.status >= 500 ? 502 : 502; // upstream en mal estado + } + // fetch aborta por timeout (AbortError) o no conecta (TypeError). Eso es + // "Kolibri no está listo", no "nuestro servidor se rompió": 503, no 500. + if (e instanceof Error && (e.name === 'AbortError' || e.name === 'TimeoutError' + || e instanceof TypeError)) { + return 503; + } return 500; } @@ -276,12 +287,24 @@ apiRouter.post('/kolibri/delete', async (req: Request, res: Response): Promise => { + try { + res.json(await getKolibriTask(String(req.params.id))); + } catch (e: any) { + const status = e instanceof KolibriApiError && e.status === 404 ? 404 : authStatus(e); + res.status(status).json({ error: e?.message || 'task lookup failed' }); + } +}); + // --- Credenciales de servicios (ADFA-4949) --------------------------------------- // Permite al webview actualizar usuario/contraseña sin recompilar. La contraseña // NUNCA se devuelve: el GET solo dice qué usuario hay y de dónde sale. diff --git a/static/dashboard/sockets/books.exec.ts b/static/dashboard/sockets/books.exec.ts index f94311ff9..1c9623197 100644 --- a/static/dashboard/sockets/books.exec.ts +++ b/static/dashboard/sockets/books.exec.ts @@ -5,15 +5,17 @@ // download_books_batch handler (auth/CSRF + fetch + upload), made durable and reporting // structured per-book progress. A job item is { id, title, url }. import { jobs, RunnerContext } from './jobs'; +import { getCredential } from './credentials'; import fs from 'fs'; import path from 'path'; const CALIBRE_WEB_LOCAL_URL = 'http://127.0.0.1:8083'; const TMP_DIR = '/tmp/books_downloader/'; const SYSTEM_USER_AGENT = 'K2Go Dashboard/1.0 (https://github.com/appdevforall/KnowledgeToGo)'; -// Defaults match the Phase 1 handler; a credential override can be added later if needed. -const CALIBRE_WEB_USER = 'Admin'; -const CALIBRE_WEB_PASS = 'changeme'; +// ADFA-4949: the credential override the original comment anticipated. Values now +// come from the shared store (env -> persisted override -> the same Admin/changeme +// factory default), so a device whose Calibre-Web password changed keeps working +// without a rebuild. Behaviour on an untouched device is identical. interface BookItem { id?: string; title?: string; url?: string; } @@ -29,8 +31,9 @@ async function getCalibreSession(): Promise<{ cookie: string; csrfToken: string const loginData = new URLSearchParams(); loginData.append('csrf_token', csrfToken); - loginData.append('username', CALIBRE_WEB_USER); - loginData.append('password', CALIBRE_WEB_PASS); + const cred = getCredential('calibre'); + loginData.append('username', cred.username); + loginData.append('password', cred.password); const authRes = await fetch(`${CALIBRE_WEB_LOCAL_URL}/login`, { method: 'POST', diff --git a/static/dashboard/sockets/books.query.ts b/static/dashboard/sockets/books.query.ts index e1166c992..676652218 100644 --- a/static/dashboard/sockets/books.query.ts +++ b/static/dashboard/sockets/books.query.ts @@ -9,6 +9,7 @@ // The cover URL is DERIVED from the Gutenberg id (standard Gutenberg cover path) so we never // bloat the catalog with image blobs; the client loads it online with an offline fallback. import Database from 'better-sqlite3'; +import { getCredential } from './credentials'; import fs from 'fs'; import path from 'path'; @@ -18,8 +19,7 @@ const BOOKS_DIR = '/library/dashboard/books/'; const CATALOG_DB_PATH = path.join(BOOKS_DIR, 'catalog.db'); const CALIBRE_WEB_LOCAL_URL = 'http://127.0.0.1:8083'; -const CALIBRE_WEB_USER = 'Admin'; -const CALIBRE_WEB_PASS = 'changeme'; +// ADFA-4949: credentials come from the shared store (see sockets/credentials.ts). export interface CatalogBook { gutenberg_id: number | string; @@ -117,8 +117,9 @@ async function getCalibreSession(): Promise<{ cookie: string; csrfToken: string const loginData = new URLSearchParams(); loginData.append('csrf_token', csrfToken); - loginData.append('username', CALIBRE_WEB_USER); - loginData.append('password', CALIBRE_WEB_PASS); + const cred = getCredential('calibre'); + loginData.append('username', cred.username); + loginData.append('password', cred.password); const authRes = await fetch(`${CALIBRE_WEB_LOCAL_URL}/login`, { method: 'POST', diff --git a/static/dashboard/sockets/credentials.test.ts b/static/dashboard/sockets/credentials.test.ts new file mode 100644 index 000000000..c861e6ea5 --- /dev/null +++ b/static/dashboard/sockets/credentials.test.ts @@ -0,0 +1,244 @@ +/// +// +// sockets/credentials.test.ts — ADFA-4949 +// +// El almacén de credenciales es el único módulo nuevo que maneja un secreto, así +// que merece cobertura propia. Solo toca fs, sin dependencias nativas, de modo que +// corre bajo `npm ci --ignore-scripts` igual que el resto de la suite. +// +// El módulo lee la ruta del store en tiempo de importación (K2GO_CREDENTIALS_FILE), +// así que cada caso usa un fichero temporal fijado ANTES del require, y el módulo se +// recarga limpiando la caché de require. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const MODULE = './credentials'; + +interface CredentialsModule { + getCredential(s: 'kolibri' | 'calibre'): { username: string; password: string; origin: string }; + setCredential(s: 'kolibri' | 'calibre', c: { username: string; password: string }): void; + clearCredential(s: 'kolibri' | 'calibre'): void; + describeCredential(s: 'kolibri' | 'calibre'): { + service: string; username: string; origin: string; isDefault: boolean; + }; + isServiceName(s: string): boolean; + CREDENTIALS_STORE_PATH: string; +} + +/** Carga el módulo con un store temporal y el entorno indicado. */ +function load(env: Record = {}): { + mod: CredentialsModule; storePath: string; cleanup: () => void; +} { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'k2go-cred-')); + const storePath = path.join(dir, 'credentials.json'); + + const saved: Record = {}; + const apply = (k: string, v: string | undefined) => { + saved[k] = process.env[k]; + if (v === undefined) delete process.env[k]; else process.env[k] = v; + }; + apply('K2GO_CREDENTIALS_FILE', storePath); + for (const k of ['K2GO_KOLIBRI_USER', 'K2GO_KOLIBRI_PASS', + 'K2GO_CALIBRE_USER', 'K2GO_CALIBRE_PASS']) { + apply(k, env[k]); + } + + delete require.cache[require.resolve(MODULE)]; + const mod = require(MODULE) as CredentialsModule; + + return { + mod, + storePath, + cleanup: () => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; else process.env[k] = v; + } + delete require.cache[require.resolve(MODULE)]; + try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ } + }, + }; +} + +// ─── Precedencia ───────────────────────────────────────────────────────────── + +test('sin override ni env, devuelve el default de fábrica de IIAB', () => { + const { mod, cleanup } = load(); + try { + const c = mod.getCredential('kolibri'); + assert.equal(c.username, 'Admin'); + assert.equal(c.password, 'changeme'); + assert.equal(c.origin, 'default'); + } finally { cleanup(); } +}); + +test('el override persistido gana sobre el default', () => { + const { mod, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: 'operador', password: 's3cr3t' }); + const c = mod.getCredential('kolibri'); + assert.equal(c.username, 'operador'); + assert.equal(c.password, 's3cr3t'); + assert.equal(c.origin, 'override'); + } finally { cleanup(); } +}); + +test('el entorno gana sobre el override persistido', () => { + // Precedencia declarada: env > override > default. Es lo que permite fijar la + // credencial desde el servicio PDSM sin tocar el fichero. + const { mod, cleanup } = load({ + K2GO_KOLIBRI_USER: 'desde-env', K2GO_KOLIBRI_PASS: 'env-pass', + }); + try { + mod.setCredential('kolibri', { username: 'operador', password: 's3cr3t' }); + const c = mod.getCredential('kolibri'); + assert.equal(c.username, 'desde-env'); + assert.equal(c.origin, 'env'); + } finally { cleanup(); } +}); + +test('el entorno solo aplica si están usuario Y contraseña', () => { + // Media credencial no es una credencial: con solo el usuario hay que caer al + // siguiente nivel, no intentar autenticar sin contraseña. + const { mod, cleanup } = load({ K2GO_KOLIBRI_USER: 'solo-usuario' }); + try { + assert.equal(mod.getCredential('kolibri').origin, 'default'); + } finally { cleanup(); } +}); + +test('los servicios no se pisan entre sí', () => { + const { mod, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: 'k', password: 'kp' }); + assert.equal(mod.getCredential('calibre').origin, 'default'); + assert.equal(mod.getCredential('kolibri').username, 'k'); + } finally { cleanup(); } +}); + +test('clearCredential vuelve al default', () => { + const { mod, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: 'operador', password: 's3cr3t' }); + mod.clearCredential('kolibri'); + assert.equal(mod.getCredential('kolibri').origin, 'default'); + assert.equal(mod.getCredential('kolibri').username, 'Admin'); + } finally { cleanup(); } +}); + +// ─── Persistencia ──────────────────────────────────────────────────────────── + +test('el fichero se escribe con permisos 0600', () => { + const { mod, storePath, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: 'operador', password: 's3cr3t' }); + assert.ok(fs.existsSync(storePath)); + if (process.platform !== 'win32') { + assert.equal(fs.statSync(storePath).mode & 0o777, 0o600); + } + } finally { cleanup(); } +}); + +test('no quedan ficheros temporales tras escribir', () => { + // La escritura es write+rename para que un corte no deje un JSON truncado. + const { mod, storePath, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: 'a', password: 'b' }); + mod.setCredential('calibre', { username: 'c', password: 'd' }); + const leftovers = fs.readdirSync(path.dirname(storePath)) + .filter((f) => f.includes('.tmp-')); + assert.deepEqual(leftovers, []); + } finally { cleanup(); } +}); + +test('un JSON corrupto degrada al default en vez de romper', () => { + const { mod, storePath, cleanup } = load(); + try { + fs.writeFileSync(storePath, '{ esto no es json', { mode: 0o600 }); + const c = mod.getCredential('kolibri'); + assert.equal(c.origin, 'default'); + assert.equal(c.username, 'Admin'); + } finally { cleanup(); } +}); + +test('un JSON válido pero con forma inesperada se ignora', () => { + const { mod, storePath, cleanup } = load(); + try { + // Entradas sin password, o de tipo equivocado, no deben adoptarse a medias. + fs.writeFileSync(storePath, JSON.stringify({ + kolibri: { username: 'x' }, + calibre: 'no-soy-un-objeto', + }), { mode: 0o600 }); + assert.equal(mod.getCredential('kolibri').origin, 'default'); + assert.equal(mod.getCredential('calibre').origin, 'default'); + } finally { cleanup(); } +}); + +// ─── Validación de entrada ─────────────────────────────────────────────────── + +test('setCredential rechaza usuario o contraseña vacíos', () => { + const { mod, cleanup } = load(); + try { + assert.throws(() => mod.setCredential('kolibri', { username: '', password: 'x' })); + assert.throws(() => mod.setCredential('kolibri', { username: ' ', password: 'x' })); + assert.throws(() => mod.setCredential('kolibri', { username: 'u', password: '' })); + } finally { cleanup(); } +}); + +test('setCredential recorta espacios del usuario, no de la contraseña', () => { + // La contraseña se guarda literal: recortarla rompería una que empiece o acabe + // en espacio, y el usuario nunca sabría por qué falla el login. + const { mod, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: ' operador ', password: ' con espacios ' }); + const c = mod.getCredential('kolibri'); + assert.equal(c.username, 'operador'); + assert.equal(c.password, ' con espacios '); + } finally { cleanup(); } +}); + +// ─── describeCredential: lo que ve el webview ──────────────────────────────── + +test('describeCredential nunca expone la contraseña', () => { + const { mod, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: 'operador', password: 'no-debe-salir' }); + const d = mod.describeCredential('kolibri') as Record; + assert.equal(JSON.stringify(d).includes('no-debe-salir'), false); + assert.equal('password' in d, false); + assert.equal(d.username, 'operador'); + } finally { cleanup(); } +}); + +test('isDefault avisa de que sigue la credencial de fábrica', () => { + const { mod, cleanup } = load(); + try { + assert.equal(mod.describeCredential('kolibri').isDefault, true); + mod.setCredential('kolibri', { username: 'operador', password: 's3cr3t' }); + assert.equal(mod.describeCredential('kolibri').isDefault, false); + } finally { cleanup(); } +}); + +test('isDefault sigue siendo true si se reescribe la credencial de fábrica', () => { + // Guardar Admin/changeme a mano no deja de ser la credencial de fábrica: el + // aviso de la UI tiene que seguir apareciendo. + const { mod, cleanup } = load(); + try { + mod.setCredential('kolibri', { username: 'Admin', password: 'changeme' }); + assert.equal(mod.describeCredential('kolibri').isDefault, true); + } finally { cleanup(); } +}); + +// ─── isServiceName ─────────────────────────────────────────────────────────── + +test('isServiceName acota los servicios conocidos', () => { + const { mod, cleanup } = load(); + try { + assert.equal(mod.isServiceName('kolibri'), true); + assert.equal(mod.isServiceName('calibre'), true); + assert.equal(mod.isServiceName('kiwix'), false); + assert.equal(mod.isServiceName('__proto__'), false); + assert.equal(mod.isServiceName(''), false); + } finally { cleanup(); } +}); diff --git a/static/dashboard/sockets/credentials.ts b/static/dashboard/sockets/credentials.ts index 4d4e1f4bd..429f5014a 100644 --- a/static/dashboard/sockets/credentials.ts +++ b/static/dashboard/sockets/credentials.ts @@ -57,12 +57,21 @@ export function isServiceName(s: string): s is ServiceName { type Store = Partial>; /** Lectura tolerante: un fichero ausente o corrupto degrada a los defaults, no - * rompe el arranque del dashboard. */ + * rompe el arranque del dashboard. + * + * Pero la degradación se REGISTRA. Silenciarla convierte "el fichero se corrompió" + * en "las credenciales dejaron de funcionar sin motivo", que es media hora de + * diagnóstico por un mensaje que costaba una línea. Un fichero ausente es normal + * (nadie ha puesto override todavía) y no se registra. */ function readStore(): Store { try { const raw = fs.readFileSync(STORE_PATH, 'utf8'); const parsed = JSON.parse(raw) as unknown; - if (!parsed || typeof parsed !== 'object') return {}; + if (!parsed || typeof parsed !== 'object') { + console.warn(`[credentials] ${STORE_PATH} no contiene un objeto JSON; ` + + 'se usan los valores de fábrica'); + return {}; + } const out: Store = {}; for (const svc of SERVICES) { const entry = (parsed as Record)[svc]; @@ -74,7 +83,15 @@ function readStore(): Store { } } return out; - } catch { + } catch (e) { + // ENOENT es el caso normal: aún no hay override. Cualquier otra cosa + // (JSON roto, permisos) sí merece un aviso. + const code = (e as NodeJS.ErrnoException)?.code; + if (code !== 'ENOENT') { + console.warn(`[credentials] no se pudo leer ${STORE_PATH} ` + + `(${e instanceof Error ? e.message : String(e)}); ` + + 'se usan los valores de fábrica'); + } return {}; } } diff --git a/static/dashboard/sockets/kolibri.query.ts b/static/dashboard/sockets/kolibri.query.ts index 0a2d8e29b..ebd282949 100644 --- a/static/dashboard/sockets/kolibri.query.ts +++ b/static/dashboard/sockets/kolibri.query.ts @@ -23,6 +23,7 @@ import { loginForContent, login, apiJson, apiFetch, checkReadiness, KolibriSession, STUDIO_URL, } from './kolibri.session'; +import { TASK_DELETE_CHANNEL, TERMINAL_STATES, mapPercent } from './kolibri.map'; const KOLIBRI_HOME = process.env.KOLIBRI_HOME || '/library/kolibri'; const MAIN_DB = path.join(KOLIBRI_HOME, 'db.sqlite3'); @@ -281,13 +282,18 @@ export async function estimateSelection( }; } -/** Borra un canal completo (metadatos + archivos) vía la tarea de Kolibri. */ +/** + * Borra un canal completo (metadatos + archivos) vía la tarea de Kolibri. + * + * Devuelve el id del job DE KOLIBRI, no del motor local: es una operación corta y + * no merece un job durable. Se consulta con getKolibriTask() / GET /kolibri/task/:id. + */ export async function deleteChannel(channelId: string, channelName?: string): Promise { const session = await loginForContent(); const job = await apiJson<{ id?: string }>(session, '/api/tasks/tasks/', { method: 'POST', body: JSON.stringify({ - type: 'kolibri.core.content.tasks.deletechannel', + type: TASK_DELETE_CHANNEL, channel_id: channelId, channel_name: channelName || channelId, }), @@ -296,6 +302,35 @@ export async function deleteChannel(channelId: string, channelName?: string): Pr return job.id; } +export interface KolibriTaskStatus { + id: string; + status: string; + /** 0-100 entero, o -1 si Kolibri no reporta progreso para esta tarea. */ + percent: number; + exception: string | null; + done: boolean; +} + +/** + * Estado de una tarea de Kolibri lanzada fuera del motor de jobs (hoy, el borrado). + * + * Sin esto, deleteChannel() devolvía un id que ningún endpoint nuestro sabía + * consultar: el cliente recibía un identificador inútil. + */ +export async function getKolibriTask(taskId: string): Promise { + const session = await loginForContent(); + const job = await apiJson<{ + id: string; status: string; percentage: number | null; exception: string | null; + }>(session, `/api/tasks/tasks/${encodeURIComponent(taskId)}/`); + return { + id: job.id, + status: job.status, + percent: mapPercent(job.percentage), + exception: job.exception ?? null, + done: TERMINAL_STATES.has(job.status), + }; +} + /** Diagnóstico ampliado: readiness + estado local. Lo consume /kolibri/preflight. * checkReadiness() no lanza: siempre devuelve un diagnóstico, así que un Kolibri * caído se refleja en los campos en lugar de romper la respuesta. diff --git a/static/dashboard/sockets/kolibri.session.ts b/static/dashboard/sockets/kolibri.session.ts index f84510a82..04e5fd17d 100644 --- a/static/dashboard/sockets/kolibri.session.ts +++ b/static/dashboard/sockets/kolibri.session.ts @@ -147,14 +147,23 @@ export async function login( `Kolibri cortó la conexión durante el login: ${e instanceof Error ? e.message : String(e)}`); } - if (res.status === 401 || res.status === 400) { + if (res.status === 401) { // 401 también aparece en "app mode" si allow_other_browsers_to_connect=False // y no hay cookie de app-key. En un box servido por nginx no aplica, pero el // mensaje lo menciona para que el diagnóstico no lleve horas. throw new KolibriAuthError('credentials', - `Kolibri rechazó las credenciales de '${cred.username}' (HTTP ${res.status}). ` + `Kolibri rechazó las credenciales de '${cred.username}'. ` + 'Si el dispositivo está en modo aplicación, revisa allow_other_browsers_to_connect.'); } + if (res.status === 400) { + // 400 es el serializer rechazando la petición (campo ausente, facility + // desconocida...), no una contraseña incorrecta. Reportarlo como credencial + // inválida manda al operador a cambiar una contraseña que estaba bien. + const detail = await res.text().catch(() => ''); + throw new KolibriAuthError('protocol', + `Kolibri rechazó la petición de login (HTTP 400), no las credenciales: ` + + (detail.slice(0, 200) || 'sin detalle')); + } if (!res.ok) { throw new KolibriAuthError('protocol', `Login devolvió HTTP ${res.status}`); }