From 2dd77538eca894500813eb17e324de56887a7e4d Mon Sep 17 00:00:00 2001 From: Marc Pomar Date: Tue, 3 Nov 2026 13:31:56 +0100 Subject: [PATCH] =?UTF-8?q?feat(auth):=20admin=20the=20login=20a=20user=20?= =?UTF-8?q?actually=20has=20=E2=80=94=20set-password,=20update=20email+ide?= =?UTF-8?q?ntifier,=20diagnose,=20recovery=20links,=20and=20show=20the=20t?= =?UTF-8?q?yped=20identifier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A user could not log in because the email they were given was not the one their account signs in with, and the CLI/MCP could neither see that nor fix it — the whole flow needed the dashboard. Now it does not. Reads - auth users get / get_auth_user: show `credentials` — the email/username the user actually TYPES at the database login, which can differ from the profile email (and when it does, that mismatch is the bug). - auth users diagnose / diagnose_auth_login: given what a person typed, say in one call whether it signs anyone in; if not, whether it is a user's profile email while they log in with another identifier, and what that identifier is. Near-match suggestions otherwise. - auth logs list / list_auth_logs: a failed login resolves no user, so the row now shows the identifier that was typed (already stored in the audit data, just never surfaced) — "USER (tried)" / `attempted_identifier`. Writes (--writes) - auth users update / update_auth_user: change email, name, email_verified; --email also moves the database credential identifier so login keeps working (--profile-only to opt out). - auth users set-password / set_auth_user_password: set the password directly (--generate, or stdin — never argv; the MCP tool pipes it on stdin). - auth users password-setup --print / get_auth_recovery_link, and auth users tickets list|revoke: mint and read back a reset link to hand over by another channel when the account's email cannot receive it. All wrap existing auth-sdk methods (userUpdate, credentials*, user tickets) — no management-API change. Unit tests for the new MCP tool shapes/flags/stdin and the credential resolver. --- src/commands/auth/logs/list.ts | 20 ++- src/commands/auth/users/diagnose.ts | 130 ++++++++++++++++++++ src/commands/auth/users/get.ts | 58 ++++++++- src/commands/auth/users/index.ts | 10 +- src/commands/auth/users/password_setup.ts | 40 +++++- src/commands/auth/users/resolve.test.ts | 57 +++++++++ src/commands/auth/users/resolve.ts | 53 ++++++++ src/commands/auth/users/set_password.ts | 110 +++++++++++++++++ src/commands/auth/users/tickets.ts | 115 ++++++++++++++++++ src/commands/auth/users/update.ts | 110 +++++++++++++++++ src/mcp/tools.auth_users.test.ts | 105 ++++++++++++++++ src/mcp/tools.ts | 142 ++++++++++++++++++++-- 12 files changed, 927 insertions(+), 23 deletions(-) create mode 100644 src/commands/auth/users/diagnose.ts create mode 100644 src/commands/auth/users/resolve.test.ts create mode 100644 src/commands/auth/users/set_password.ts create mode 100644 src/commands/auth/users/tickets.ts create mode 100644 src/commands/auth/users/update.ts create mode 100644 src/mcp/tools.auth_users.test.ts diff --git a/src/commands/auth/logs/list.ts b/src/commands/auth/logs/list.ts index fe4a304..cfe3c7a 100644 --- a/src/commands/auth/logs/list.ts +++ b/src/commands/auth/logs/list.ts @@ -119,15 +119,25 @@ export const logs_list: CommandModule = { return } log.info(`📜 ${page.data.length} entr${page.data.length === 1 ? 'y' : 'ies'}:`) + // The USER column: the resolved user when there is one; otherwise the + // identifier the person actually TYPED (`data.email`), marked `(tried)`. + // A failed login never resolves a user — that typed value is the whole + // point of the row (who was trying, with what address). + const user_cell = (entry: (typeof page.data)[number]): string => { + const resolved = + typeof entry.user === 'string' + ? entry.user + : ((entry.user as { email?: string; id?: string } | undefined)?.email ?? + (entry.user as { id?: string } | undefined)?.id) + if (resolved) return resolved + const tried = (entry.data as { email?: string } | undefined)?.email + return tried ? `${tried} (tried)` : '-' + } const rows = page.data.map(entry => [ entry.createdAt ?? '-', entry.type ?? '-', log_status_badge(entry.status), - typeof entry.user === 'string' - ? entry.user - : ((entry.user as { email?: string; id?: string } | undefined)?.email ?? - (entry.user as { id?: string } | undefined)?.id ?? - '-'), + user_cell(entry), truncate(entry.message, 48), entry.id ?? '-' ]) diff --git a/src/commands/auth/users/diagnose.ts b/src/commands/auth/users/diagnose.ts new file mode 100644 index 0000000..6b29bf8 --- /dev/null +++ b/src/commands/auth/users/diagnose.ts @@ -0,0 +1,130 @@ +import { CommandModule } from 'yargs' +import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin' +import { fetch_page, from_paginator } from '../../../lib/listing' +import { log } from '../../../log' +import { TenantArgs, json_option, tenant_options } from '../options' +import { print_json } from '../render' + +interface DiagnoseArgs extends TenantArgs { + identifier: string +} + +type Cred = { + id: string + connection?: string + email?: string + username?: string + user?: string | { id?: string; email?: string } +} + +const user_of = (c: Cred): { id?: string; email?: string } => + typeof c.user === 'string' ? { id: c.user } : (c.user ?? {}) + +// Answers "why can't X log in?" from the identifier the person typed. The +// password login matches a CREDENTIAL identifier, not the profile email, so a +// login can fail for a reason get_auth_user alone does not show: the address +// they were given is simply not one any account logs in with. This resolves +// that in one call. +export const users_diagnose: CommandModule = { + command: 'diagnose ', + describe: 'Explain why an email/username someone typed does (or does not) log in', + builder: yargs => + json_option(tenant_options(yargs)) + .positional('identifier', { + type: 'string', + demandOption: true, + description: 'The email or username the person is trying to log in with' + }) + .example( + '$0 auth users diagnose jtamargo@med.ucm.es', + 'Check whether that identifier logs in, and if not, what the account actually uses' + ) + .showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + const api = await requireAuthAdmin(args) + const id = args.identifier.trim() + const as_email = id.includes('@') + const needle = as_email ? id.toLowerCase() : id + + const first = async (params: Record): Promise => + fetch_page(from_paginator(api.credentialsList(params as never)), { limit: 20 }) + .then(r => r.data as Cred[]) + .catch(() => []) + + // 1. Exact: does any database credential log in with this identifier? + const matches = await first({ + ...(as_email ? { email: needle } : { username: needle }), + expand: ['user'] + }) + + // 2. If not, is it a user's PROFILE email while they log in with another + // identifier? (the trap: a right-looking email that is not the login.) + const profile_users = matches.length === 0 && as_email + ? await fetch_page(from_paginator(api.userList({ email: needle } as never)), { + limit: 5 + }) + .then(r => r.data as Array<{ id: string; email?: string }>) + .catch(() => []) + : [] + const alt_creds: Record = {} + for (const u of profile_users) { + alt_creds[u.id] = await first({ user: u.id }) + } + + // 3. Fuzzy suggestions when nothing matched at all. + const suggestions = + matches.length === 0 && profile_users.length === 0 + ? await first({ q: as_email ? id.split('@')[0] : id }) + : [] + + if (args.json) { + return print_json({ + identifier: id, + logs_in: matches.length > 0, + matches: matches.map(c => ({ + credential: c.id, + connection: c.connection, + identifier: c.email ?? c.username, + user: user_of(c) + })), + profile_email_only: profile_users.map(u => ({ + user: u.id, + email: u.email, + login_identifiers: (alt_creds[u.id] ?? []).map(c => c.email ?? c.username) + })), + suggestions: suggestions.map(c => c.email ?? c.username).filter(Boolean) + }) + } + + log.info(`🔎 Diagnosing login for: ${id}`) + if (matches.length > 0) { + log.info('✅ This IS a login identifier. It signs in as:') + for (const c of matches) { + const u = user_of(c) + log.info(` ${u.email ?? u.id ?? '-'} (${u.id ?? '-'}) · connection ${c.connection ?? '-'}`) + } + log.info(' If login still fails, it is the password or a suspension — not the identifier.') + log.info(' Set a password: faable auth users set-password --generate') + return + } + + log.info(`❌ No account logs in with ${id}.`) + if (profile_users.length > 0) { + log.info('⚠️ But a user has it as their PROFILE email — they must log in with their identifier:') + for (const u of profile_users) { + const ids = (alt_creds[u.id] ?? []).map(c => c.email ?? c.username).filter(Boolean) + log.info(` ${u.email} → logs in with: ${ids.length ? ids.join(', ') : '(no database credential)'}`) + } + log.info(' Fix: tell them that identifier, or move it with: faable auth users update --email ' + id) + return + } + if (suggestions.length > 0) { + log.info(' Did you mean one of these login identifiers?') + for (const c of suggestions.slice(0, 5)) { + log.info(` - ${c.email ?? c.username} (${user_of(c).email ?? user_of(c).id ?? '-'})`) + } + } else { + log.info(' No similar identifier found in this tenant.') + } + }) +} diff --git a/src/commands/auth/users/get.ts b/src/commands/auth/users/get.ts index 599559d..9fcd9b4 100644 --- a/src/commands/auth/users/get.ts +++ b/src/commands/auth/users/get.ts @@ -33,7 +33,8 @@ type ProfileData = { export const users_get: CommandModule = { command: 'get ', - describe: 'Show a user (by id or email), including their federated identities', + describe: + 'Show a user (by id or email), their federated identities and their database login identifiers', builder: yargs => json_option(tenant_options(yargs)) .positional('user_id', { @@ -59,10 +60,40 @@ export const users_get: CommandModule = { .then(r => r.data.map(i => sanitize_identity(i as never))) .catch(() => [] as Record[]) - // Resolve connection ids to names ("github") once per distinct id. + // Database-connection credentials: the email/username the user actually + // TYPES to log in. Distinct from `user.email` (the profile email), which + // is NOT what the password login matches — the gap that otherwise sends + // you to the dashboard to find out why a login keeps failing. Best-effort. + const credentials = await fetch_page( + from_paginator(api.credentialsList({ user: user_id })), + { limit: 200, all: true } + ) + .then(r => + r.data.map(c => ({ + id: String((c as { id?: unknown }).id ?? ''), + connection: String((c as { connection?: unknown }).connection ?? ''), + email: (c as { email?: string }).email, + username: (c as { username?: string }).username + })) + ) + .catch( + () => + [] as { + id: string + connection: string + email?: string + username?: string + }[] + ) + + // Resolve connection ids to names ("github", "default") once per distinct + // id — identities and credentials alike. const connection_names = new Map() for (const id of new Set( - identities.map(i => String(i.connection ?? '')).filter(Boolean) + [ + ...identities.map(i => String(i.connection ?? '')), + ...credentials.map(c => c.connection) + ].filter(Boolean) )) { const conn = (await api.connectionGet(id).catch(() => null)) as { connection_name?: string @@ -74,11 +105,30 @@ export const users_get: CommandModule = { ) } - if (args.json) return print_json({ ...user, identities }) + if (args.json) + return print_json({ + ...user, + identities, + credentials: credentials.map(c => ({ + ...c, + connection_name: connection_names.get(c.connection) ?? c.connection + })) + }) log.info(`👤 ${user.id}`) log.info(` Email: ${user.email ?? '-'} (verified: ${yes_no(user.email_verified)})`) log.info(` Name: ${user.name ?? '-'}`) + if (credentials.length > 0) { + // What the user types at the password login — may differ from the + // profile email above, in which case that mismatch is the bug. + const ids = credentials + .map(c => { + const conn = connection_names.get(c.connection) ?? (c.connection || 'default') + return `${c.email ?? c.username ?? '-'} (${conn})` + }) + .join(', ') + log.info(` Login IDs: ${ids}`) + } if (user.phone) log.info(` Phone: ${user.phone}`) if (user.country_iso) log.info(` Country: ${user.country_iso}`) log.info(` Created: ${user.createdAt ?? '-'}`) diff --git a/src/commands/auth/users/index.ts b/src/commands/auth/users/index.ts index 74bde39..ff71a90 100644 --- a/src/commands/auth/users/index.ts +++ b/src/commands/auth/users/index.ts @@ -1,4 +1,5 @@ import { CommandModule } from 'yargs' +import { users_diagnose } from './diagnose' import { users_export } from './export' import { users_get } from './get' import { users_import } from './import' @@ -7,19 +8,26 @@ import { users_password_setup } from './password_setup' import { users_permissions } from './permissions' import { users_reinstate } from './reinstate' import { users_roles } from './roles' +import { users_set_password } from './set_password' import { users_suspend } from './suspend' +import { users_tickets } from './tickets' +import { users_update } from './update' export const users: CommandModule = { command: 'users', describe: - 'List, count, inspect, suspend, reinstate, import and export users, and manage their roles', + 'List, count, inspect, update, suspend, reinstate, set passwords for, import and export users, and manage their roles', builder: yargs => yargs .command(users_list) .command(users_get) + .command(users_diagnose) + .command(users_update) .command(users_suspend) .command(users_reinstate) + .command(users_set_password) .command(users_password_setup) + .command(users_tickets) .command(users_roles) .command(users_permissions) .command(users_import) diff --git a/src/commands/auth/users/password_setup.ts b/src/commands/auth/users/password_setup.ts index 9fcd7a9..b88201b 100644 --- a/src/commands/auth/users/password_setup.ts +++ b/src/commands/auth/users/password_setup.ts @@ -9,6 +9,7 @@ import { resolve_user_ref } from './resolve' interface PasswordSetupArgs extends TenantArgs { user: string channel?: 'email' | 'sms' | 'whatsapp' + print?: boolean yes?: boolean } @@ -29,12 +30,22 @@ export const users_password_setup: CommandModule = { choices: ['email', 'sms', 'whatsapp'], description: "How to deliver it (default: the tenant's)" }) + .option('print', { + type: 'boolean', + default: false, + description: + 'Also print the recovery link, to hand it over by another channel when the email will not reach the person (email channel only)' + }) .option('yes', { alias: 'y', type: 'boolean', default: false, description: 'Skip the confirmation prompt' }) + .example( + '$0 auth users password-setup ana@example.com --print', + 'Mint a reset link and print it (also sends the email)' + ) .showHelpOnFail(false) as any, handler: withAuthHints(async args => { // An email is resolved first (a read), so the prompt names one user; an @@ -50,10 +61,33 @@ export const users_password_setup: CommandModule = { return } const api = early ?? (await requireAuthAdmin(args)) - const res = await api.userPasswordSetup(await resolve_user_ref(api, user_id), { + const id = await resolve_user_ref(api, user_id) + const res = await api.userPasswordSetup(id, { ...(args.channel ? { channel: args.channel } : {}) }) - if (args.json) return print_json({ user_id, ...res }) - log.info(`📨 Sent to ${args.user} (${(res as { channel?: string }).channel ?? 'email'}).`) + const channel = (res as { channel?: string }).channel ?? 'email' + + // The setup response carries only the ticket id; the usable link lives on + // the ticket. Read it back when asked — the way to deliver a reset to + // someone whose mailbox does not receive (a login identifier that is not a + // real inbox). A link exists only for the email channel. + let link: string | undefined + if (args.print && channel === 'email') { + const ticket_id = (res as { ticket_id?: string }).ticket_id + const tickets = await api + .userListTickets(id) + .then(r => (r as { results?: Array<{ id: string; link?: string }> }).results ?? []) + .catch(() => []) + link = tickets.find(t => t.id === ticket_id)?.link ?? tickets.find(t => t.link)?.link + } + + if (args.json) return print_json({ user_id: id, ...res, ...(link ? { link } : {}) }) + log.info(`📨 Sent to ${args.user} (${channel}).`) + if (args.print) { + if (link) log.info(`🔗 ${link}`) + else if (channel === 'email') + log.info(' (link not available — it may already be consumed or expired)') + else log.info(` (no link: the ${channel} channel delivers a code, not a link)`) + } }) } diff --git a/src/commands/auth/users/resolve.test.ts b/src/commands/auth/users/resolve.test.ts new file mode 100644 index 0000000..758ce23 --- /dev/null +++ b/src/commands/auth/users/resolve.test.ts @@ -0,0 +1,57 @@ +import test from 'ava' +import { resolve_user_credential } from './resolve' + +// A fake SDK `credentialsList(params)`: returns a paginator (`.pass()`) over a +// fixed set, filtered by the `user`/`connection` query the resolver sends. +const fake_api = (creds: Array>) => ({ + credentialsList(params?: { user?: string; connection?: string }) { + return { + async pass() { + let results = creds + if (params?.connection) { + results = results.filter(c => c.connection === params.connection) + } + return { results, next: null } + } + } + } +}) + +const CRED = (id: string, connection: string, email: string) => ({ + id, + connection, + email +}) + +test('returns the single database credential of a one-connection tenant', async t => { + const api = fake_api([CRED('credentials_1', 'connection_db', 'ana@login.com')]) + const cred = await resolve_user_credential(api as never, 'user_1') + t.is(cred.id, 'credentials_1') + t.is(cred.email, 'ana@login.com') +}) + +test('throws when the user has no database credential', async t => { + const api = fake_api([]) + await t.throwsAsync(() => resolve_user_credential(api as never, 'user_1'), { + message: /no database credential/ + }) +}) + +test('with several credentials, demands --connection', async t => { + const api = fake_api([ + CRED('credentials_1', 'connection_a', 'ana@a.com'), + CRED('credentials_2', 'connection_b', 'ana@b.com') + ]) + await t.throwsAsync(() => resolve_user_credential(api as never, 'user_1'), { + message: /pass --connection/ + }) +}) + +test('with several credentials, --connection picks the one', async t => { + const api = fake_api([ + CRED('credentials_1', 'connection_a', 'ana@a.com'), + CRED('credentials_2', 'connection_b', 'ana@b.com') + ]) + const cred = await resolve_user_credential(api as never, 'user_1', 'connection_b') + t.is(cred.id, 'credentials_2') +}) diff --git a/src/commands/auth/users/resolve.ts b/src/commands/auth/users/resolve.ts index 7753c8d..4e49d22 100644 --- a/src/commands/auth/users/resolve.ts +++ b/src/commands/auth/users/resolve.ts @@ -1,5 +1,58 @@ import type { FaableAuthApi } from '@faable/auth-sdk' import { CliError } from '../../../lib/errors' +import { fetch_page, from_paginator } from '../../../lib/listing' + +export interface UserCredential { + id: string + connection: string + email?: string + username?: string +} + +// The database credential a password login matches — the email/username the +// user actually types, which can differ from their profile email. One per +// database connection: a single-connection tenant has exactly one. With more, +// `connection` (id or the name it was created with) disambiguates. Throws when +// the user has none (they sign in only through social/passwordless). +export const resolve_user_credential = async ( + api: Pick, + user_id: string, + connection?: string +): Promise => { + const { data } = await fetch_page( + from_paginator(api.credentialsList({ user: user_id } as never)), + { limit: 200, all: true } + ) + const creds: UserCredential[] = (data as Record[]).map(c => ({ + id: String(c.id ?? ''), + connection: String(c.connection ?? ''), + email: c.email as string | undefined, + username: c.username as string | undefined + })) + if (creds.length === 0) { + throw new CliError( + 'not_found', + `User ${user_id} has no database credential — they sign in only through a social or passwordless connection.` + ) + } + if (connection) { + const match = creds.filter(c => c.connection === connection) + if (match.length === 1) return match[0] + throw new CliError( + 'usage', + `User ${user_id} has no single credential on connection ${connection} (${match.length} matched).` + ) + } + if (creds.length > 1) { + throw new CliError( + 'usage', + `User ${user_id} has ${creds.length} database credentials (${creds + .map(c => c.connection) + .join(', ')}): pass --connection.` + ) + } + return creds[0] +} // A user given as an id (`user_…`) or as an email. An email is looked up with // an exact `?email=` (stored lowercase) and must match ONE user: a write by diff --git a/src/commands/auth/users/set_password.ts b/src/commands/auth/users/set_password.ts new file mode 100644 index 0000000..f4de80f --- /dev/null +++ b/src/commands/auth/users/set_password.ts @@ -0,0 +1,110 @@ +import crypto from 'crypto' +import { CommandModule } from 'yargs' +import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin' +import { confirm } from '../../../lib/interactive' +import { read_stdin } from '../../../lib/stdin' +import { log } from '../../../log' +import { TenantArgs, json_option, tenant_options } from '../options' +import { print_json } from '../render' +import { resolve_user_credential, resolve_user_ref } from './resolve' + +interface SetPasswordArgs extends TenantArgs { + user: string + password?: string + generate?: boolean + connection?: string + yes?: boolean +} + +// 24 url-safe characters from 18 random bytes — ample entropy and nothing a +// shell will mangle when the admin pastes it on. +const generate_password = (): string => crypto.randomBytes(18).toString('base64url') + +// Sets a user's database password directly, to the given value. The link flow +// (`password-setup`) is the right tool when the person can receive the email; +// this is for when they cannot and an admin must hand them a working password. +// The value never travels in argv: it is read from stdin (or generated). +export const users_set_password: CommandModule = { + command: 'set-password ', + describe: "Set a user's database password directly (overwrites the current one)", + builder: yargs => + json_option(tenant_options(yargs)) + .positional('user', { + type: 'string', + demandOption: true, + description: 'User id (user_…) or email' + }) + .option('password', { + type: 'string', + description: + 'The new password. Prefer stdin (keeps it out of shell history) or --generate.' + }) + .option('generate', { + type: 'boolean', + default: false, + description: 'Generate a strong password and print it once' + }) + .option('connection', { + type: 'string', + description: + "Database connection id or name, when the user has more than one credential" + }) + .option('yes', { + alias: 'y', + type: 'boolean', + default: false, + description: 'Skip the confirmation prompt' + }) + .example( + '$0 auth users set-password ana@example.com --generate', + 'Set a random password and print it once' + ) + .example( + 'printf %s "s3cr3t" | $0 auth users set-password ana@example.com -y', + 'Set a password read from stdin (never in shell history)' + ) + .showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + if (args.password && args.generate) { + throw new Error('Pass either a password (stdin/--password) or --generate, not both.') + } + // Resolve the password before any request, so a piped value is consumed + // deterministically and nothing runs when there is none. + let password = args.password + if (args.generate) password = generate_password() + if (!password && !process.stdin.isTTY) password = (await read_stdin()).trim() + if (!password) { + throw new Error( + 'No password given. Use --generate, or pipe the password on stdin.' + ) + } + + const api = await requireAuthAdmin(args) + const user_id = await resolve_user_ref(api, args.user) + const cred = await resolve_user_credential(api, user_id, args.connection) + const login = cred.email ?? cred.username ?? cred.id + + const go = await confirm({ + message: `Set a new password for ${args.user} (login ${login})?`, + yes: args.yes + }) + if (!go) { + log.info('Cancelled.') + return + } + + await api.credentialsSetPassword(cred.id, { password }) + + if (args.json) { + return print_json({ + user_id, + credential: cred.id, + login, + ...(args.generate ? { password } : {}) + }) + } + log.info(`✅ Password set for ${args.user} (login ${login}).`) + if (args.generate) log.info(` Password (shown once): ${password}`) + log.info(' They can change it from their profile once signed in.') + }) +} diff --git a/src/commands/auth/users/tickets.ts b/src/commands/auth/users/tickets.ts new file mode 100644 index 0000000..55b8d3b --- /dev/null +++ b/src/commands/auth/users/tickets.ts @@ -0,0 +1,115 @@ +import { CommandModule } from 'yargs' +import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin' +import { confirm } from '../../../lib/interactive' +import { log } from '../../../log' +import { TenantArgs, json_option, tenant_options } from '../options' +import { print_json } from '../render' +import { resolve_user_ref } from './resolve' + +interface TicketsListArgs extends TenantArgs { + user: string +} + +interface Ticket { + id: string + type: string + status: string + expires_at?: string + channel?: string + link?: string +} + +// The reset / verification / invitation tickets issued for a user, newest +// first. Each carries the link that was emailed WHILE it is still usable — +// the way to hand a recovery link over by another channel when the email does +// not reach the person. +const users_tickets_list: CommandModule = { + command: 'list ', + describe: 'List the tickets (reset/verify/invite links) issued for a user', + builder: yargs => + json_option(tenant_options(yargs)) + .positional('user', { + type: 'string', + demandOption: true, + description: 'User id (user_…) or email' + }) + .showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + const api = await requireAuthAdmin(args) + const user_id = await resolve_user_ref(api, args.user) + const tickets = (await api + .userListTickets(user_id) + .then(r => (r as { results?: Ticket[] }).results ?? [])) as Ticket[] + + if (args.json) return print_json({ user_id, tickets }) + if (tickets.length === 0) { + log.info('📭 No tickets for this user.') + return + } + log.info(`🎫 ${tickets.length} ticket(s):`) + for (const t of tickets) { + log.info(` ${t.id} ${t.type} [${t.status}]${t.expires_at ? ` exp ${t.expires_at}` : ''}`) + if (t.link) log.info(` 🔗 ${t.link}`) + } + }) +} + +interface TicketsRevokeArgs extends TenantArgs { + user: string + ticket_id: string + yes?: boolean +} + +// Revoke a ticket so its link stops working immediately — the counterpart of +// listing links: once a link has been copied out it can end up in the wrong +// window, and the TTL alone is too slow an answer. +const users_tickets_revoke: CommandModule = { + command: 'revoke ', + describe: 'Revoke a ticket (its link stops working immediately)', + builder: yargs => + json_option(tenant_options(yargs)) + .positional('user', { + type: 'string', + demandOption: true, + description: 'User id (user_…) or email' + }) + .positional('ticket_id', { + type: 'string', + demandOption: true, + description: 'Ticket id (from `tickets list`)' + }) + .option('yes', { + alias: 'y', + type: 'boolean', + default: false, + description: 'Skip the confirmation prompt' + }) + .showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + const api = await requireAuthAdmin(args) + const user_id = await resolve_user_ref(api, args.user) + const go = await confirm({ + message: `Revoke ticket ${args.ticket_id} for ${args.user}?`, + yes: args.yes + }) + if (!go) { + log.info('Cancelled.') + return + } + await api.userRevokeTicket(user_id, args.ticket_id) + if (args.json) return print_json({ user_id, ticket_id: args.ticket_id, revoked: true }) + log.info(`✅ Revoked ticket ${args.ticket_id}.`) + }) +} + +export const users_tickets: CommandModule = { + command: 'tickets', + describe: 'List or revoke the recovery/verification/invite tickets of a user', + builder: yargs => + yargs + .command(users_tickets_list) + .command(users_tickets_revoke) + .demandCommand(1) + .showHelpOnFail(false) as any, + handler: () => {} +} diff --git a/src/commands/auth/users/update.ts b/src/commands/auth/users/update.ts new file mode 100644 index 0000000..867fc4f --- /dev/null +++ b/src/commands/auth/users/update.ts @@ -0,0 +1,110 @@ +import { CommandModule } from 'yargs' +import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin' +import { confirm } from '../../../lib/interactive' +import { log } from '../../../log' +import { TenantArgs, json_option, tenant_options } from '../options' +import { print_json } from '../render' +import { resolve_user_credential, resolve_user_ref } from './resolve' + +interface UserUpdateArgs extends TenantArgs { + user: string + email?: string + name?: string + emailVerified?: boolean + profileOnly?: boolean + connection?: string + yes?: boolean +} + +// Updates a user's profile (email, name, verified flag). The catch with the +// email: the password login matches the CREDENTIAL identifier, not the +// profile email — change one without the other and the login keeps failing on +// the old address. So `--email` moves the database credential identifier too, +// unless `--profile-only` is set. (If the connection logs in by username, use +// `auth credentials update` instead.) +export const users_update: CommandModule = { + command: 'update ', + describe: "Update a user's profile (email, name, verified) and, with --email, their login identifier", + builder: yargs => + json_option(tenant_options(yargs)) + .positional('user', { + type: 'string', + demandOption: true, + description: 'User id (user_…) or email' + }) + .option('email', { + type: 'string', + description: 'New email — also becomes the database login identifier (see --profile-only)' + }) + .option('name', { type: 'string', description: 'Display name' }) + .option('email-verified', { + type: 'boolean', + description: 'Mark the email verified (true) or clear verification (false)' + }) + .option('profile-only', { + type: 'boolean', + default: false, + description: 'With --email, change only the profile email, not the login identifier' + }) + .option('connection', { + type: 'string', + description: 'Database connection id or name, when the user has more than one credential' + }) + .option('yes', { + alias: 'y', + type: 'boolean', + default: false, + description: 'Skip the confirmation prompt' + }) + .example( + '$0 auth users update ana@example.com --email ana@new.com', + 'Change the email and the login identifier together' + ) + .showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + const patch: Record = {} + if (args.email !== undefined) patch.email = args.email + if (args.name !== undefined) patch.name = args.name + if (args.emailVerified !== undefined) patch.email_verified = args.emailVerified + if (Object.keys(patch).length === 0) { + throw new Error('Nothing to update. Pass --email, --name or --email-verified.') + } + + const api = await requireAuthAdmin(args) + const user_id = await resolve_user_ref(api, args.user) + + const move_credential = args.email !== undefined && !args.profileOnly + // Resolved before the prompt so the summary is honest; a user with no + // database credential just updates the profile (nothing to move). + const cred = move_credential + ? await resolve_user_credential(api, user_id, args.connection).catch(() => undefined) + : undefined + + const summary = [ + args.email !== undefined ? `email → ${args.email}` : null, + args.name !== undefined ? `name → ${args.name}` : null, + args.emailVerified !== undefined ? `email_verified → ${args.emailVerified}` : null, + cred ? `login identifier → ${args.email}` : null + ] + .filter(Boolean) + .join(', ') + + const go = await confirm({ message: `Update ${args.user} (${summary})?`, yes: args.yes }) + if (!go) { + log.info('Cancelled.') + return + } + + const user = await api.userUpdate(user_id, patch) + if (cred) await api.credentialsUpdate(cred.id, { email: args.email }) + + if (args.json) { + return print_json({ ...user, login_identifier_updated: cred ? args.email : null }) + } + log.info(`✅ Updated ${user.id} (${user.email ?? '-'}).`) + if (cred) log.info(` Login identifier is now ${args.email}.`) + else if (args.email !== undefined && args.profileOnly) { + log.info(' Profile email changed; login identifier left as is (--profile-only).') + } + }) +} diff --git a/src/mcp/tools.auth_users.test.ts b/src/mcp/tools.auth_users.test.ts new file mode 100644 index 0000000..241766a --- /dev/null +++ b/src/mcp/tools.auth_users.test.ts @@ -0,0 +1,105 @@ +import test from 'ava' +import { TOOLS } from './tools' + +const tool = (name: string) => TOOLS.find(t => t.name === name)! +// Every shape takes (data, args); the tests only exercise the mapping. +const shape = (name: string, data: unknown): any => tool(name).shape!(data, {} as any) + +test('set_auth_user_password: the password goes on stdin, never in argv', t => { + const def = tool('set_auth_user_password') + // A literal password: on stdin, absent from the command line. + const flags = def.flags({ user: 'ana@example.com', password: 's3cr3t' }) + t.false(flags.includes('s3cr3t')) + t.false(flags.includes('--password')) + t.deepEqual(flags, ['ana@example.com', '--yes']) + t.is(def.stdin!({ user: 'ana@example.com', password: 's3cr3t' }), 's3cr3t') + // --generate: a flag, and nothing piped (the CLI makes its own). + const gen = def.flags({ user: 'ana@example.com', generate: true }) + t.true(gen.includes('--generate')) + t.is(def.stdin!({ user: 'ana@example.com', generate: true }), undefined) + t.true(def.write) + t.false(def.annotations.idempotentHint) + t.false(def.annotations.destructiveHint) +}) + +test('update_auth_user: maps profile flags and the login-identifier opt-out', t => { + const def = tool('update_auth_user') + t.deepEqual(def.flags({ user: 'u', email: 'ana@new.com' }), [ + 'u', + '--email', + 'ana@new.com', + '--yes' + ]) + // false → the negated flag; true → the plain one. + t.true(def.flags({ user: 'u', email_verified: false }).includes('--no-email-verified')) + t.true(def.flags({ user: 'u', email_verified: true }).includes('--email-verified')) + t.true( + def + .flags({ user: 'u', email: 'ana@new.com', profile_only: true }) + .includes('--profile-only') + ) + t.true(def.write) +}) + +test('get_auth_user shape: surfaces the database login identifier', t => { + const out = shape('get_auth_user', { + id: 'user_1', + email: 'ana@profile.com', + credentials: [ + { connection: 'conn_1', connection_name: 'default', email: 'ana@login.com' } + ], + identities: [] + }) + t.deepEqual(out.credentials, [{ connection: 'default', identifier: 'ana@login.com' }]) +}) + +test('list_auth_logs shape: a failed login carries the attempted identifier', t => { + const out = shape('list_auth_logs', { + data: [ + // Failed: no user resolves — the typed identifier is the whole point. + { + createdAt: 't1', + type: 'auth.password_login', + status: 'failed', + data: { email: 'esantos@usal.es' } + }, + // Success: user resolves and equals data.email → no redundant field. + { + createdAt: 't2', + type: 'auth.password_login', + status: 'success', + user: { id: 'user_1', email: 'ana@login.com' }, + data: { email: 'ana@login.com' } + } + ], + has_more: false + }) + t.is(out.events[0].attempted_identifier, 'esantos@usal.es') + t.false('attempted_identifier' in out.events[1]) + t.is(out.events[1].email, 'ana@login.com') +}) + +test('diagnose_auth_login: passes the identifier through, read-only', t => { + const def = tool('diagnose_auth_login') + t.deepEqual(def.flags({ identifier: 'ana@personal.com' }), ['ana@personal.com']) + t.true(def.annotations.readOnlyHint) + t.falsy(def.write) +}) + +test('get_auth_recovery_link: prints the link and returns it shaped', t => { + const def = tool('get_auth_recovery_link') + const flags = def.flags({ user: 'ana@example.com' }) + t.true(flags.includes('--print')) + t.true(flags.includes('--yes')) + const out = shape('get_auth_recovery_link', { + user_id: 'user_1', + ticket_id: 'tkt_1', + channel: 'email', + link: 'https://tenant.auth.faable.link/flow/change-password?ticket=tkt_1', + status: 'sent' + }) + t.is(out.link, 'https://tenant.auth.faable.link/flow/change-password?ticket=tkt_1') + t.is(out.ticket_id, 'tkt_1') + t.is(out.channel, 'email') + t.true(def.write) +}) diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts index 2823c51..9be85f7 100644 --- a/src/mcp/tools.ts +++ b/src/mcp/tools.ts @@ -615,7 +615,7 @@ export const TOOLS: ToolDef[] = [ name: 'get_auth_user', title: 'Get a user', description: - "One user of the Auth tenant by id or email: profile, verification, suspension (and why), last login and login count, and the social identities they sign in with. Use it to confirm who a user is before suspending them, or to see why they can't log in (together with list_auth_logs).", + "One user of the Auth tenant by id or email: profile, verification, suspension (and why), last login and login count, the social identities they sign in with, and `credentials` — the email/username they actually TYPE at the database (password) login. That login identifier can differ from the profile `email`; when it does, a login failing with the profile email is the bug. Use it to confirm who a user is before suspending them, or to see why they can't log in (together with list_auth_logs).", input: { user: user_ref, tenant, project }, command: ['auth', 'users', 'get'], flags: a => [a.user, ...auth_scope(a)], @@ -627,16 +627,38 @@ export const TOOLS: ToolDef[] = [ identities: (u.identities ?? []).map((i: any) => ({ provider: i.provider ?? i.connection_type, user_id: i.user_id ?? i.provider_user_id + })), + credentials: (u.credentials ?? []).map((c: any) => ({ + connection: c.connection_name ?? c.connection, + identifier: c.email ?? c.username })) }), annotations: AUTH_READ, example: { user: 'ana@example.com' } }, + { + name: 'diagnose_auth_login', + title: 'Diagnose a login identifier', + description: + "Given the exact email or username a person is trying to log in with, explain in one call whether it signs anyone in. `logs_in: true` → it is a real login identifier (so a failure is the password or a suspension, not the identifier). `logs_in: false` with `profile_email_only` populated → a user has that address as their PROFILE email but logs in with a different identifier (the usual trap: the address they were given is not the one on the account); `login_identifiers` lists what they must actually type. `suggestions` offers near matches when nothing matched. Use this first for 'X cannot log in'.", + input: { + identifier: z + .string() + .describe('The email or username the person is trying to log in with'), + tenant, + project + }, + command: ['auth', 'users', 'diagnose'], + flags: a => [a.identifier, ...auth_scope(a)], + untrusted: true, + annotations: AUTH_READ, + example: { identifier: 'ana@personal.com' } + }, { name: 'list_auth_logs', title: 'Read the Auth audit log', description: - "The Auth tenant's audit log, newest first: logins, failed logins (`status: failed`), sign-ups, password resets, admin changes (`type` prefix `admin.user`). Filter by user to answer 'why can't X log in?' — the failed attempts say why.", + "The Auth tenant's audit log, newest first: logins, failed logins (`status: failed`), sign-ups, password resets, admin changes (`type` prefix `admin.user`). Filter by user to answer 'why can't X log in?' — the failed attempts say why. On a failed login no user resolves, so each row also carries `attempted_identifier`: the email/username the person actually typed (diagnose_auth_login turns that into the account they should be using).", input: { email: z.string().optional().describe("Only this user's events (exact email)"), user: z.string().optional().describe('Only this user id (user_…)'), @@ -665,14 +687,24 @@ export const TOOLS: ToolDef[] = [ ], untrusted: true, shape: (d: any) => ({ - events: (d?.data ?? []).map((l: any) => ({ - at: l.createdAt, - type: l.type, - status: l.status, - ...log_user(l), - message: l.message, - ip: l.data?.ip - })), + events: (d?.data ?? []).map((l: any) => { + const resolved = log_user(l) + // The identifier the person TYPED. On a failed login no user resolves, + // so this is the only record of who tried and with what address — + // surface it when it adds something the resolved user does not. + const tried = l.data?.email + return { + at: l.createdAt, + type: l.type, + status: l.status, + ...resolved, + ...(tried && tried !== (resolved as { email?: string }).email + ? { attempted_identifier: tried } + : {}), + message: l.message, + ip: l.data?.ip + } + }), has_more: !!d?.has_more }), annotations: AUTH_READ, @@ -1387,5 +1419,95 @@ export const TOOLS: ToolDef[] = [ write: true, annotations: { ...AUTH_WRITE, idempotentHint: false }, example: { user: 'ana@example.com', channel: 'email' } + }, + { + name: 'update_auth_user', + title: 'Update a user profile', + description: + "Change a user's profile: `email`, `name`, `email_verified`. Changing `email` also moves their database login identifier (the email they type at the password login) so sign-in keeps working — pass `profile_only: true` to change only the profile email and leave the login identifier. Use this when someone cannot log in because the address they were given is not the one on their account. Confirm the person first with get_auth_user.", + input: { + user: user_ref, + email: z.string().optional().describe('New email — also the database login identifier unless profile_only'), + name: z.string().optional(), + email_verified: z.boolean().optional().describe('Mark the email verified (true) or clear verification (false)'), + profile_only: z + .boolean() + .optional() + .describe('With email, change only the profile email, not the login identifier'), + connection: z + .string() + .optional() + .describe('Database connection id or name, when the user has more than one credential'), + tenant, + project + }, + command: ['auth', 'users', 'update'], + flags: a => [ + a.user, + ...opt('--email', a.email), + ...opt('--name', a.name), + ...(a.email_verified === undefined + ? [] + : [a.email_verified ? '--email-verified' : '--no-email-verified']), + ...(a.profile_only ? ['--profile-only'] : []), + ...opt('--connection', a.connection), + '--yes', + ...auth_scope(a) + ], + write: true, + annotations: { ...AUTH_WRITE, idempotentHint: true }, + example: { user: 'ana@example.com', email: 'ana@new.com' } + }, + { + name: 'set_auth_user_password', + title: "Set a user's password", + description: + "Set a user's database password directly, to a value you choose or one this tool generates. Use it only when the person cannot receive a password-setup link at all (e.g. the email on the account does not exist) — with a link they pick their own password and it never passes through anyone else. Pass `generate: true` to get a strong password back once, or put the exact password in `password`. The password is sent to the CLI over stdin, never in the command line; it is returned only when generated.", + input: { + user: user_ref, + password: z + .string() + .optional() + .describe('The exact new password. Omit and set generate:true to have one made.'), + generate: z.boolean().optional().describe('Generate a strong password and return it once'), + connection: z + .string() + .optional() + .describe('Database connection id or name, when the user has more than one credential'), + tenant, + project + }, + command: ['auth', 'users', 'set-password'], + flags: a => [ + a.user, + ...(a.generate ? ['--generate'] : []), + ...opt('--connection', a.connection), + '--yes', + ...auth_scope(a) + ], + // The password goes on stdin, never in argv. Nothing is piped for the + // generate path (the CLI makes its own and never reads stdin then). + stdin: a => (a.generate ? undefined : (a.password as string | undefined)), + write: true, + annotations: { ...AUTH_WRITE, idempotentHint: false }, + example: { user: 'ana@example.com', generate: true } + }, + { + name: 'get_auth_recovery_link', + title: 'Get a password-reset link', + description: + "Mint a fresh password-reset link for a user and return it, so you can hand it over by another channel when the reset email will not reach them (e.g. the address on the account is not a real inbox). This ALSO sends the standard reset email. The link lets whoever holds it set the password, so treat it like a password; it works once, until used or expired. Returns `link` (email channel only), `ticket_id` and `channel`.", + input: { user: user_ref, tenant, project }, + command: ['auth', 'users', 'password-setup'], + flags: a => [a.user, '--print', '--yes', ...auth_scope(a)], + shape: (r: any) => ({ + link: r.link, + ticket_id: r.ticket_id, + channel: r.channel, + user_id: r.user_id + }), + write: true, + annotations: { ...AUTH_WRITE, idempotentHint: false }, + example: { user: 'ana@example.com' } } ]