@faable/faable 4.31.1 → 4.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,6 +29,7 @@ npm i -g @faable/faable
29
29
  | --- | --- | --- |
30
30
  | `faable login` / `whoami` / `logout` | Session management (device flow; CI uses OIDC, no login needed) | [Authentication](https://faable.com/docs/cli#authentication) |
31
31
  | `faable project` | The project commands act on: `list`, `use`, `current`, `clear` (or `--project` on any command) | [Projects](https://faable.com/docs/cli#projects) |
32
+ | `faable organization` | Group projects under a company: `list`, `get`, `create`, `projects add`/`rm`, `admins add`/`rm` (`org` for short) | [Organizations](https://faable.com/docs/cli#organizations) |
32
33
  | `faable deploy` | `launch` (the default: a bare `faable deploy` deploys the current directory), then `status`, `logs`, `deployments`, `inspect`, `trigger`, `redeploy`, `cancel`, `traffic`, `usage`, `quota`, `open` | [Deployment](https://faable.com/docs/cli#deployment) |
33
34
  | `faable deploy apps` | `list`, `get`, `create` (from a GitHub repository, first deploy included), `set` (branch, root directory, deploy mode) | [Apps](https://faable.com/docs/cli#apps) |
34
35
  | `faable deploy secrets` | Environment variables: `list`, `set` (`KEY=VALUE`, `--env-file`, or `-f -` from stdin), `rm` | [Secrets](https://faable.com/docs/cli#secrets) |
@@ -192,6 +192,31 @@ class FaableApi {
192
192
  }
193
193
  }));
194
194
  }
195
+ // ---- organizations (a person's session: api keys are refused) ----
196
+ async listOrganizations() {
197
+ return data(this.client.get(`/organization`));
198
+ }
199
+ async getOrganization(id) {
200
+ return data(this.client.get(`/organization/${id}`));
201
+ }
202
+ async createOrganization(name, project_id) {
203
+ return data(this.client.post(`/organization`, {
204
+ name,
205
+ project_id
206
+ }));
207
+ }
208
+ async addOrganizationProject(id, project_id) {
209
+ return data(this.client.post(`/organization/${id}/project`, { project_id }));
210
+ }
211
+ async removeOrganizationProject(id, project_id) {
212
+ return data(this.client.delete(`/organization/${id}/project/${project_id}`));
213
+ }
214
+ async addOrganizationAdmin(id, user_id) {
215
+ return data(this.client.post(`/organization/${id}/admin`, { user_id }));
216
+ }
217
+ async removeOrganizationAdmin(id, user_id) {
218
+ return data(this.client.delete(`/organization/${id}/admin/${user_id}`));
219
+ }
195
220
  async getProject(project_id) {
196
221
  return data(this.client.get(`/project/${project_id}`));
197
222
  }
@@ -85,15 +85,25 @@ const logs_list = {
85
85
  return;
86
86
  }
87
87
  log.info(`📜 ${page.data.length} entr${page.data.length === 1 ? 'y' : 'ies'}:`);
88
+ // The USER column: the resolved user when there is one; otherwise the
89
+ // identifier the person actually TYPED (`data.email`), marked `(tried)`.
90
+ // A failed login never resolves a user — that typed value is the whole
91
+ // point of the row (who was trying, with what address).
92
+ const user_cell = (entry) => {
93
+ const resolved = typeof entry.user === 'string'
94
+ ? entry.user
95
+ : (entry.user?.email ??
96
+ entry.user?.id);
97
+ if (resolved)
98
+ return resolved;
99
+ const tried = entry.data?.email;
100
+ return tried ? `${tried} (tried)` : '-';
101
+ };
88
102
  const rows = page.data.map(entry => [
89
103
  entry.createdAt ?? '-',
90
104
  entry.type ?? '-',
91
105
  log_status_badge(entry.status),
92
- typeof entry.user === 'string'
93
- ? entry.user
94
- : (entry.user?.email ??
95
- entry.user?.id ??
96
- '-'),
106
+ user_cell(entry),
97
107
  truncate(entry.message, 48),
98
108
  entry.id ?? '-'
99
109
  ]);
@@ -0,0 +1,104 @@
1
+ import { withAuthHints, requireAuthAdmin } from '../../../api/auth_admin.js';
2
+ import { json_option, fetch_page, from_paginator, print_json } from '../../../lib/listing.js';
3
+ import { log } from '../../../log.js';
4
+ import { tenant_options } from '../options.js';
5
+
6
+ const user_of = (c) => typeof c.user === 'string' ? { id: c.user } : (c.user ?? {});
7
+ // Answers "why can't X log in?" from the identifier the person typed. The
8
+ // password login matches a CREDENTIAL identifier, not the profile email, so a
9
+ // login can fail for a reason get_auth_user alone does not show: the address
10
+ // they were given is simply not one any account logs in with. This resolves
11
+ // that in one call.
12
+ const users_diagnose = {
13
+ command: 'diagnose <identifier>',
14
+ describe: 'Explain why an email/username someone typed does (or does not) log in',
15
+ builder: yargs => json_option(tenant_options(yargs))
16
+ .positional('identifier', {
17
+ type: 'string',
18
+ demandOption: true,
19
+ description: 'The email or username the person is trying to log in with'
20
+ })
21
+ .example('$0 auth users diagnose jtamargo@med.ucm.es', 'Check whether that identifier logs in, and if not, what the account actually uses')
22
+ .showHelpOnFail(false),
23
+ handler: withAuthHints(async (args) => {
24
+ const api = await requireAuthAdmin(args);
25
+ const id = args.identifier.trim();
26
+ const as_email = id.includes('@');
27
+ const needle = as_email ? id.toLowerCase() : id;
28
+ const first = async (params) => fetch_page(from_paginator(api.credentialsList(params)), { limit: 20 })
29
+ .then(r => r.data)
30
+ .catch(() => []);
31
+ // 1. Exact: does any database credential log in with this identifier?
32
+ const matches = await first({
33
+ ...(as_email ? { email: needle } : { username: needle }),
34
+ expand: ['user']
35
+ });
36
+ // 2. If not, is it a user's PROFILE email while they log in with another
37
+ // identifier? (the trap: a right-looking email that is not the login.)
38
+ const profile_users = matches.length === 0 && as_email
39
+ ? await fetch_page(from_paginator(api.userList({ email: needle })), {
40
+ limit: 5
41
+ })
42
+ .then(r => r.data)
43
+ .catch(() => [])
44
+ : [];
45
+ const alt_creds = {};
46
+ for (const u of profile_users) {
47
+ alt_creds[u.id] = await first({ user: u.id });
48
+ }
49
+ // 3. Fuzzy suggestions when nothing matched at all.
50
+ const suggestions = matches.length === 0 && profile_users.length === 0
51
+ ? await first({ q: as_email ? id.split('@')[0] : id })
52
+ : [];
53
+ if (args.json) {
54
+ return print_json({
55
+ identifier: id,
56
+ logs_in: matches.length > 0,
57
+ matches: matches.map(c => ({
58
+ credential: c.id,
59
+ connection: c.connection,
60
+ identifier: c.email ?? c.username,
61
+ user: user_of(c)
62
+ })),
63
+ profile_email_only: profile_users.map(u => ({
64
+ user: u.id,
65
+ email: u.email,
66
+ login_identifiers: (alt_creds[u.id] ?? []).map(c => c.email ?? c.username)
67
+ })),
68
+ suggestions: suggestions.map(c => c.email ?? c.username).filter(Boolean)
69
+ });
70
+ }
71
+ log.info(`🔎 Diagnosing login for: ${id}`);
72
+ if (matches.length > 0) {
73
+ log.info('✅ This IS a login identifier. It signs in as:');
74
+ for (const c of matches) {
75
+ const u = user_of(c);
76
+ log.info(` ${u.email ?? u.id ?? '-'} (${u.id ?? '-'}) · connection ${c.connection ?? '-'}`);
77
+ }
78
+ log.info(' If login still fails, it is the password or a suspension — not the identifier.');
79
+ log.info(' Set a password: faable auth users set-password <user> --generate');
80
+ return;
81
+ }
82
+ log.info(`❌ No account logs in with ${id}.`);
83
+ if (profile_users.length > 0) {
84
+ log.info('⚠️ But a user has it as their PROFILE email — they must log in with their identifier:');
85
+ for (const u of profile_users) {
86
+ const ids = (alt_creds[u.id] ?? []).map(c => c.email ?? c.username).filter(Boolean);
87
+ log.info(` ${u.email} → logs in with: ${ids.length ? ids.join(', ') : '(no database credential)'}`);
88
+ }
89
+ log.info(' Fix: tell them that identifier, or move it with: faable auth users update <user> --email ' + id);
90
+ return;
91
+ }
92
+ if (suggestions.length > 0) {
93
+ log.info(' Did you mean one of these login identifiers?');
94
+ for (const c of suggestions.slice(0, 5)) {
95
+ log.info(` - ${c.email ?? c.username} (${user_of(c).email ?? user_of(c).id ?? '-'})`);
96
+ }
97
+ }
98
+ else {
99
+ log.info(' No similar identifier found in this tenant.');
100
+ }
101
+ })
102
+ };
103
+
104
+ export { users_diagnose };
@@ -13,7 +13,7 @@ const sanitize_identity = (i) => {
13
13
  };
14
14
  const users_get = {
15
15
  command: 'get <user_id>',
16
- describe: 'Show a user (by id or email), including their federated identities',
16
+ describe: 'Show a user (by id or email), their federated identities and their database login identifiers',
17
17
  builder: yargs => json_option(tenant_options(yargs))
18
18
  .positional('user_id', {
19
19
  type: 'string',
@@ -33,17 +33,51 @@ const users_get = {
33
33
  const identities = await fetch_page(from_paginator(api.identityList({ query: `user:${user_id}` })), { limit: 200, all: true })
34
34
  .then(r => r.data.map(i => sanitize_identity(i)))
35
35
  .catch(() => []);
36
- // Resolve connection ids to names ("github") once per distinct id.
36
+ // Database-connection credentials: the email/username the user actually
37
+ // TYPES to log in. Distinct from `user.email` (the profile email), which
38
+ // is NOT what the password login matches — the gap that otherwise sends
39
+ // you to the dashboard to find out why a login keeps failing. Best-effort.
40
+ const credentials = await fetch_page(from_paginator(api.credentialsList({ user: user_id })), { limit: 200, all: true })
41
+ .then(r => r.data.map(c => ({
42
+ id: String(c.id ?? ''),
43
+ connection: String(c.connection ?? ''),
44
+ email: c.email,
45
+ username: c.username
46
+ })))
47
+ .catch(() => []);
48
+ // Resolve connection ids to names ("github", "default") once per distinct
49
+ // id — identities and credentials alike.
37
50
  const connection_names = new Map();
38
- for (const id of new Set(identities.map(i => String(i.connection ?? '')).filter(Boolean))) {
51
+ for (const id of new Set([
52
+ ...identities.map(i => String(i.connection ?? '')),
53
+ ...credentials.map(c => c.connection)
54
+ ].filter(Boolean))) {
39
55
  const conn = (await api.connectionGet(id).catch(() => null));
40
56
  connection_names.set(id, conn?.connection_name ?? conn?.connection_type ?? id);
41
57
  }
42
58
  if (args.json)
43
- return print_json({ ...user, identities });
59
+ return print_json({
60
+ ...user,
61
+ identities,
62
+ credentials: credentials.map(c => ({
63
+ ...c,
64
+ connection_name: connection_names.get(c.connection) ?? c.connection
65
+ }))
66
+ });
44
67
  log.info(`👤 ${user.id}`);
45
68
  log.info(` Email: ${user.email ?? '-'} (verified: ${yes_no(user.email_verified)})`);
46
69
  log.info(` Name: ${user.name ?? '-'}`);
70
+ if (credentials.length > 0) {
71
+ // What the user types at the password login — may differ from the
72
+ // profile email above, in which case that mismatch is the bug.
73
+ const ids = credentials
74
+ .map(c => {
75
+ const conn = connection_names.get(c.connection) ?? (c.connection || 'default');
76
+ return `${c.email ?? c.username ?? '-'} (${conn})`;
77
+ })
78
+ .join(', ');
79
+ log.info(` Login IDs: ${ids}`);
80
+ }
47
81
  if (user.phone)
48
82
  log.info(` Phone: ${user.phone}`);
49
83
  if (user.country_iso)
@@ -1,3 +1,4 @@
1
+ import { users_diagnose } from './diagnose.js';
1
2
  import { users_export } from './export.js';
2
3
  import { users_get } from './get.js';
3
4
  import { users_import } from './import.js';
@@ -6,17 +7,24 @@ import { users_password_setup } from './password_setup.js';
6
7
  import { users_permissions } from './permissions.js';
7
8
  import { users_reinstate } from './reinstate.js';
8
9
  import { users_roles } from './roles.js';
10
+ import { users_set_password } from './set_password.js';
9
11
  import { users_suspend } from './suspend.js';
12
+ import { users_tickets } from './tickets.js';
13
+ import { users_update } from './update.js';
10
14
 
11
15
  const users = {
12
16
  command: 'users',
13
- describe: 'List, count, inspect, suspend, reinstate, import and export users, and manage their roles',
17
+ describe: 'List, count, inspect, update, suspend, reinstate, set passwords for, import and export users, and manage their roles',
14
18
  builder: yargs => yargs
15
19
  .command(users_list)
16
20
  .command(users_get)
21
+ .command(users_diagnose)
22
+ .command(users_update)
17
23
  .command(users_suspend)
18
24
  .command(users_reinstate)
25
+ .command(users_set_password)
19
26
  .command(users_password_setup)
27
+ .command(users_tickets)
20
28
  .command(users_roles)
21
29
  .command(users_permissions)
22
30
  .command(users_import)
@@ -20,6 +20,11 @@ const users_password_setup = {
20
20
  type: 'string',
21
21
  choices: ['email', 'sms', 'whatsapp'],
22
22
  description: "How to deliver it (default: the tenant's)"
23
+ })
24
+ .option('print', {
25
+ type: 'boolean',
26
+ default: false,
27
+ description: 'Also print the recovery link, to hand it over by another channel when the email will not reach the person (email channel only)'
23
28
  })
24
29
  .option('yes', {
25
30
  alias: 'y',
@@ -27,6 +32,7 @@ const users_password_setup = {
27
32
  default: false,
28
33
  description: 'Skip the confirmation prompt'
29
34
  })
35
+ .example('$0 auth users password-setup ana@example.com --print', 'Mint a reset link and print it (also sends the email)')
30
36
  .showHelpOnFail(false),
31
37
  handler: withAuthHints(async (args) => {
32
38
  // An email is resolved first (a read), so the prompt names one user; an
@@ -42,12 +48,35 @@ const users_password_setup = {
42
48
  return;
43
49
  }
44
50
  const api = early ?? (await requireAuthAdmin(args));
45
- const res = await api.userPasswordSetup(await resolve_user_ref(api, user_id), {
51
+ const id = await resolve_user_ref(api, user_id);
52
+ const res = await api.userPasswordSetup(id, {
46
53
  ...(args.channel ? { channel: args.channel } : {})
47
54
  });
55
+ const channel = res.channel ?? 'email';
56
+ // The setup response carries only the ticket id; the usable link lives on
57
+ // the ticket. Read it back when asked — the way to deliver a reset to
58
+ // someone whose mailbox does not receive (a login identifier that is not a
59
+ // real inbox). A link exists only for the email channel.
60
+ let link;
61
+ if (args.print && channel === 'email') {
62
+ const ticket_id = res.ticket_id;
63
+ const tickets = await api
64
+ .userListTickets(id)
65
+ .then(r => r.results ?? [])
66
+ .catch(() => []);
67
+ link = tickets.find(t => t.id === ticket_id)?.link ?? tickets.find(t => t.link)?.link;
68
+ }
48
69
  if (args.json)
49
- return print_json({ user_id, ...res });
50
- log.info(`📨 Sent to ${args.user} (${res.channel ?? 'email'}).`);
70
+ return print_json({ user_id: id, ...res, ...(link ? { link } : {}) });
71
+ log.info(`📨 Sent to ${args.user} (${channel}).`);
72
+ if (args.print) {
73
+ if (link)
74
+ log.info(`🔗 ${link}`);
75
+ else if (channel === 'email')
76
+ log.info(' (link not available — it may already be consumed or expired)');
77
+ else
78
+ log.info(` (no link: the ${channel} channel delivers a code, not a link)`);
79
+ }
51
80
  })
52
81
  };
53
82
 
@@ -1,5 +1,35 @@
1
1
  import { CliError } from '../../../lib/errors.js';
2
+ import { fetch_page, from_paginator } from '../../../lib/listing.js';
2
3
 
4
+ // The database credential a password login matches — the email/username the
5
+ // user actually types, which can differ from their profile email. One per
6
+ // database connection: a single-connection tenant has exactly one. With more,
7
+ // `connection` (id or the name it was created with) disambiguates. Throws when
8
+ // the user has none (they sign in only through social/passwordless).
9
+ const resolve_user_credential = async (api, user_id, connection) => {
10
+ const { data } = await fetch_page(from_paginator(api.credentialsList({ user: user_id })), { limit: 200, all: true });
11
+ const creds = data.map(c => ({
12
+ id: String(c.id ?? ''),
13
+ connection: String(c.connection ?? ''),
14
+ email: c.email,
15
+ username: c.username
16
+ }));
17
+ if (creds.length === 0) {
18
+ throw new CliError('not_found', `User ${user_id} has no database credential — they sign in only through a social or passwordless connection.`);
19
+ }
20
+ if (connection) {
21
+ const match = creds.filter(c => c.connection === connection);
22
+ if (match.length === 1)
23
+ return match[0];
24
+ throw new CliError('usage', `User ${user_id} has no single credential on connection ${connection} (${match.length} matched).`);
25
+ }
26
+ if (creds.length > 1) {
27
+ throw new CliError('usage', `User ${user_id} has ${creds.length} database credentials (${creds
28
+ .map(c => c.connection)
29
+ .join(', ')}): pass --connection.`);
30
+ }
31
+ return creds[0];
32
+ };
3
33
  // A user given as an id (`user_…`) or as an email. An email is looked up with
4
34
  // an exact `?email=` (stored lowercase) and must match ONE user: a write by
5
35
  // email never acts on a partial or ambiguous match.
@@ -33,4 +63,4 @@ const resolve_user_refs = async (api, refs) => {
33
63
  return out;
34
64
  };
35
65
 
36
- export { resolve_user_ref, resolve_user_refs };
66
+ export { resolve_user_credential, resolve_user_ref, resolve_user_refs };
@@ -0,0 +1,90 @@
1
+ import crypto from 'crypto';
2
+ import { withAuthHints, requireAuthAdmin } from '../../../api/auth_admin.js';
3
+ import { confirm } from '../../../lib/interactive.js';
4
+ import { read_stdin } from '../../../lib/stdin.js';
5
+ import { log } from '../../../log.js';
6
+ import { tenant_options } from '../options.js';
7
+ import { json_option, print_json } from '../../../lib/listing.js';
8
+ import { resolve_user_ref, resolve_user_credential } from './resolve.js';
9
+
10
+ // 24 url-safe characters from 18 random bytes — ample entropy and nothing a
11
+ // shell will mangle when the admin pastes it on.
12
+ const generate_password = () => crypto.randomBytes(18).toString('base64url');
13
+ // Sets a user's database password directly, to the given value. The link flow
14
+ // (`password-setup`) is the right tool when the person can receive the email;
15
+ // this is for when they cannot and an admin must hand them a working password.
16
+ // The value never travels in argv: it is read from stdin (or generated).
17
+ const users_set_password = {
18
+ command: 'set-password <user>',
19
+ describe: "Set a user's database password directly (overwrites the current one)",
20
+ builder: yargs => json_option(tenant_options(yargs))
21
+ .positional('user', {
22
+ type: 'string',
23
+ demandOption: true,
24
+ description: 'User id (user_…) or email'
25
+ })
26
+ .option('password', {
27
+ type: 'string',
28
+ description: 'The new password. Prefer stdin (keeps it out of shell history) or --generate.'
29
+ })
30
+ .option('generate', {
31
+ type: 'boolean',
32
+ default: false,
33
+ description: 'Generate a strong password and print it once'
34
+ })
35
+ .option('connection', {
36
+ type: 'string',
37
+ description: "Database connection id or name, when the user has more than one credential"
38
+ })
39
+ .option('yes', {
40
+ alias: 'y',
41
+ type: 'boolean',
42
+ default: false,
43
+ description: 'Skip the confirmation prompt'
44
+ })
45
+ .example('$0 auth users set-password ana@example.com --generate', 'Set a random password and print it once')
46
+ .example('printf %s "s3cr3t" | $0 auth users set-password ana@example.com -y', 'Set a password read from stdin (never in shell history)')
47
+ .showHelpOnFail(false),
48
+ handler: withAuthHints(async (args) => {
49
+ if (args.password && args.generate) {
50
+ throw new Error('Pass either a password (stdin/--password) or --generate, not both.');
51
+ }
52
+ // Resolve the password before any request, so a piped value is consumed
53
+ // deterministically and nothing runs when there is none.
54
+ let password = args.password;
55
+ if (args.generate)
56
+ password = generate_password();
57
+ if (!password && !process.stdin.isTTY)
58
+ password = (await read_stdin()).trim();
59
+ if (!password) {
60
+ throw new Error('No password given. Use --generate, or pipe the password on stdin.');
61
+ }
62
+ const api = await requireAuthAdmin(args);
63
+ const user_id = await resolve_user_ref(api, args.user);
64
+ const cred = await resolve_user_credential(api, user_id, args.connection);
65
+ const login = cred.email ?? cred.username ?? cred.id;
66
+ const go = await confirm({
67
+ message: `Set a new password for ${args.user} (login ${login})?`,
68
+ yes: args.yes
69
+ });
70
+ if (!go) {
71
+ log.info('Cancelled.');
72
+ return;
73
+ }
74
+ await api.credentialsSetPassword(cred.id, { password });
75
+ if (args.json) {
76
+ return print_json({
77
+ user_id,
78
+ credential: cred.id,
79
+ login,
80
+ ...(args.generate ? { password } : {})
81
+ });
82
+ }
83
+ log.info(`✅ Password set for ${args.user} (login ${login}).`);
84
+ if (args.generate)
85
+ log.info(` Password (shown once): ${password}`);
86
+ log.info(' They can change it from their profile once signed in.');
87
+ })
88
+ };
89
+
90
+ export { users_set_password };
@@ -0,0 +1,94 @@
1
+ import { withAuthHints, requireAuthAdmin } from '../../../api/auth_admin.js';
2
+ import { confirm } from '../../../lib/interactive.js';
3
+ import { log } from '../../../log.js';
4
+ import { tenant_options } from '../options.js';
5
+ import { print_json, json_option } from '../../../lib/listing.js';
6
+ import { resolve_user_ref } from './resolve.js';
7
+
8
+ // The reset / verification / invitation tickets issued for a user, newest
9
+ // first. Each carries the link that was emailed WHILE it is still usable —
10
+ // the way to hand a recovery link over by another channel when the email does
11
+ // not reach the person.
12
+ const users_tickets_list = {
13
+ command: 'list <user>',
14
+ describe: 'List the tickets (reset/verify/invite links) issued for a user',
15
+ builder: yargs => json_option(tenant_options(yargs))
16
+ .positional('user', {
17
+ type: 'string',
18
+ demandOption: true,
19
+ description: 'User id (user_…) or email'
20
+ })
21
+ .showHelpOnFail(false),
22
+ handler: withAuthHints(async (args) => {
23
+ const api = await requireAuthAdmin(args);
24
+ const user_id = await resolve_user_ref(api, args.user);
25
+ const tickets = (await api
26
+ .userListTickets(user_id)
27
+ .then(r => r.results ?? []));
28
+ if (args.json)
29
+ return print_json({ user_id, tickets });
30
+ if (tickets.length === 0) {
31
+ log.info('📭 No tickets for this user.');
32
+ return;
33
+ }
34
+ log.info(`🎫 ${tickets.length} ticket(s):`);
35
+ for (const t of tickets) {
36
+ log.info(` ${t.id} ${t.type} [${t.status}]${t.expires_at ? ` exp ${t.expires_at}` : ''}`);
37
+ if (t.link)
38
+ log.info(` 🔗 ${t.link}`);
39
+ }
40
+ })
41
+ };
42
+ // Revoke a ticket so its link stops working immediately — the counterpart of
43
+ // listing links: once a link has been copied out it can end up in the wrong
44
+ // window, and the TTL alone is too slow an answer.
45
+ const users_tickets_revoke = {
46
+ command: 'revoke <user> <ticket_id>',
47
+ describe: 'Revoke a ticket (its link stops working immediately)',
48
+ builder: yargs => json_option(tenant_options(yargs))
49
+ .positional('user', {
50
+ type: 'string',
51
+ demandOption: true,
52
+ description: 'User id (user_…) or email'
53
+ })
54
+ .positional('ticket_id', {
55
+ type: 'string',
56
+ demandOption: true,
57
+ description: 'Ticket id (from `tickets list`)'
58
+ })
59
+ .option('yes', {
60
+ alias: 'y',
61
+ type: 'boolean',
62
+ default: false,
63
+ description: 'Skip the confirmation prompt'
64
+ })
65
+ .showHelpOnFail(false),
66
+ handler: withAuthHints(async (args) => {
67
+ const api = await requireAuthAdmin(args);
68
+ const user_id = await resolve_user_ref(api, args.user);
69
+ const go = await confirm({
70
+ message: `Revoke ticket ${args.ticket_id} for ${args.user}?`,
71
+ yes: args.yes
72
+ });
73
+ if (!go) {
74
+ log.info('Cancelled.');
75
+ return;
76
+ }
77
+ await api.userRevokeTicket(user_id, args.ticket_id);
78
+ if (args.json)
79
+ return print_json({ user_id, ticket_id: args.ticket_id, revoked: true });
80
+ log.info(`✅ Revoked ticket ${args.ticket_id}.`);
81
+ })
82
+ };
83
+ const users_tickets = {
84
+ command: 'tickets',
85
+ describe: 'List or revoke the recovery/verification/invite tickets of a user',
86
+ builder: yargs => yargs
87
+ .command(users_tickets_list)
88
+ .command(users_tickets_revoke)
89
+ .demandCommand(1)
90
+ .showHelpOnFail(false),
91
+ handler: () => { }
92
+ };
93
+
94
+ export { users_tickets };
@@ -0,0 +1,96 @@
1
+ import { withAuthHints, requireAuthAdmin } from '../../../api/auth_admin.js';
2
+ import { confirm } from '../../../lib/interactive.js';
3
+ import { log } from '../../../log.js';
4
+ import { tenant_options } from '../options.js';
5
+ import { json_option, print_json } from '../../../lib/listing.js';
6
+ import { resolve_user_ref, resolve_user_credential } from './resolve.js';
7
+
8
+ // Updates a user's profile (email, name, verified flag). The catch with the
9
+ // email: the password login matches the CREDENTIAL identifier, not the
10
+ // profile email — change one without the other and the login keeps failing on
11
+ // the old address. So `--email` moves the database credential identifier too,
12
+ // unless `--profile-only` is set. (If the connection logs in by username, use
13
+ // `auth credentials update` instead.)
14
+ const users_update = {
15
+ command: 'update <user>',
16
+ describe: "Update a user's profile (email, name, verified) and, with --email, their login identifier",
17
+ builder: yargs => json_option(tenant_options(yargs))
18
+ .positional('user', {
19
+ type: 'string',
20
+ demandOption: true,
21
+ description: 'User id (user_…) or email'
22
+ })
23
+ .option('email', {
24
+ type: 'string',
25
+ description: 'New email — also becomes the database login identifier (see --profile-only)'
26
+ })
27
+ .option('name', { type: 'string', description: 'Display name' })
28
+ .option('email-verified', {
29
+ type: 'boolean',
30
+ description: 'Mark the email verified (true) or clear verification (false)'
31
+ })
32
+ .option('profile-only', {
33
+ type: 'boolean',
34
+ default: false,
35
+ description: 'With --email, change only the profile email, not the login identifier'
36
+ })
37
+ .option('connection', {
38
+ type: 'string',
39
+ description: 'Database connection id or name, when the user has more than one credential'
40
+ })
41
+ .option('yes', {
42
+ alias: 'y',
43
+ type: 'boolean',
44
+ default: false,
45
+ description: 'Skip the confirmation prompt'
46
+ })
47
+ .example('$0 auth users update ana@example.com --email ana@new.com', 'Change the email and the login identifier together')
48
+ .showHelpOnFail(false),
49
+ handler: withAuthHints(async (args) => {
50
+ const patch = {};
51
+ if (args.email !== undefined)
52
+ patch.email = args.email;
53
+ if (args.name !== undefined)
54
+ patch.name = args.name;
55
+ if (args.emailVerified !== undefined)
56
+ patch.email_verified = args.emailVerified;
57
+ if (Object.keys(patch).length === 0) {
58
+ throw new Error('Nothing to update. Pass --email, --name or --email-verified.');
59
+ }
60
+ const api = await requireAuthAdmin(args);
61
+ const user_id = await resolve_user_ref(api, args.user);
62
+ const move_credential = args.email !== undefined && !args.profileOnly;
63
+ // Resolved before the prompt so the summary is honest; a user with no
64
+ // database credential just updates the profile (nothing to move).
65
+ const cred = move_credential
66
+ ? await resolve_user_credential(api, user_id, args.connection).catch(() => undefined)
67
+ : undefined;
68
+ const summary = [
69
+ args.email !== undefined ? `email → ${args.email}` : null,
70
+ args.name !== undefined ? `name → ${args.name}` : null,
71
+ args.emailVerified !== undefined ? `email_verified → ${args.emailVerified}` : null,
72
+ cred ? `login identifier → ${args.email}` : null
73
+ ]
74
+ .filter(Boolean)
75
+ .join(', ');
76
+ const go = await confirm({ message: `Update ${args.user} (${summary})?`, yes: args.yes });
77
+ if (!go) {
78
+ log.info('Cancelled.');
79
+ return;
80
+ }
81
+ const user = await api.userUpdate(user_id, patch);
82
+ if (cred)
83
+ await api.credentialsUpdate(cred.id, { email: args.email });
84
+ if (args.json) {
85
+ return print_json({ ...user, login_identifier_updated: cred ? args.email : null });
86
+ }
87
+ log.info(`✅ Updated ${user.id} (${user.email ?? '-'}).`);
88
+ if (cred)
89
+ log.info(` Login identifier is now ${args.email}.`);
90
+ else if (args.email !== undefined && args.profileOnly) {
91
+ log.info(' Profile email changed; login identifier left as is (--profile-only).');
92
+ }
93
+ })
94
+ };
95
+
96
+ export { users_update };
@@ -0,0 +1,193 @@
1
+ import { requireApi } from '../../api/context.js';
2
+ import { requireProject, resolveProjectRef } from '../../api/project.js';
3
+ import { CliError } from '../../lib/errors.js';
4
+ import { confirm } from '../../lib/interactive.js';
5
+ import { print_json, table_lines, print, json_option } from '../../lib/listing.js';
6
+ import { log } from '../../log.js';
7
+
8
+ // `faable organization` — the companies that group projects. An organization
9
+ // gives nobody access to its projects and is not billed. The api decides who
10
+ // may: its admins and the projects' owners, or staff; a person, never an API
11
+ // key (`Organizations are managed by people`).
12
+ const ID_RE = /^organization_[0-9a-f]{24}$/;
13
+ const resolveOrganization = async (api, ref) => {
14
+ if (ID_RE.test(ref))
15
+ return ref;
16
+ const wanted = ref.toLowerCase();
17
+ const { results } = await api.listOrganizations();
18
+ const matches = results.filter(o => o.name.toLowerCase() === wanted || o.slug.toLowerCase() === wanted);
19
+ if (matches.length === 1)
20
+ return matches[0].id;
21
+ throw new CliError('not_found', matches.length === 0
22
+ ? `No organization named "${ref}". See them with: faable organization list`
23
+ : `"${ref}" is more than one organization: use its id.`);
24
+ };
25
+ const project_names = (o) => o.projects.map(p => p.name).join(', ') || '-';
26
+ const organization_list = {
27
+ command: 'list',
28
+ describe: 'List the organizations you administer or have a project in',
29
+ builder: yargs => json_option(yargs).showHelpOnFail(false),
30
+ handler: async (args) => {
31
+ const { api } = await requireApi();
32
+ const { results } = await api.listOrganizations();
33
+ if (args.json)
34
+ return print_json(results);
35
+ if (results.length === 0)
36
+ return log.info('📭 No organizations.');
37
+ for (const line of table_lines(['ID', 'NAME', 'ADMIN', 'PROJECTS'], results.map(o => [
38
+ o.id,
39
+ o.name,
40
+ o.is_admin ? 'yes' : 'no',
41
+ project_names(o)
42
+ ]))) {
43
+ print(line);
44
+ }
45
+ }
46
+ };
47
+ const organization_get = {
48
+ command: 'get <organization>',
49
+ describe: 'Show an organization: its projects and admins',
50
+ builder: yargs => json_option(yargs)
51
+ .positional('organization', { type: 'string', demandOption: true })
52
+ .showHelpOnFail(false),
53
+ handler: async (args) => {
54
+ const { api } = await requireApi();
55
+ const org = await api.getOrganization(await resolveOrganization(api, args.organization));
56
+ if (args.json)
57
+ return print_json(org);
58
+ print(`${org.name} (${org.id})`);
59
+ print(`Projects: ${project_names(org)}`);
60
+ print(`Admins: ${org.admins?.join(', ') || '-'}`);
61
+ }
62
+ };
63
+ const organization_create = {
64
+ command: 'create <name>',
65
+ describe: 'Create an organization from a project (--project or the active one); you become its admin',
66
+ builder: yargs => json_option(yargs)
67
+ .positional('name', { type: 'string', demandOption: true })
68
+ .example('$0 organization create "Acme SL" --project acme-web', '')
69
+ .showHelpOnFail(false),
70
+ handler: async (args) => {
71
+ const { api } = await requireApi();
72
+ const { id } = await requireProject(api);
73
+ const org = await api.createOrganization(args.name, id);
74
+ if (args.json)
75
+ return print_json(org);
76
+ log.info(`✅ Organization ${org.name} (${org.id})`);
77
+ }
78
+ };
79
+ const project_positionals = (yargs) => yargs
80
+ .positional('organization', { type: 'string', demandOption: true })
81
+ .positional('project_ref', {
82
+ type: 'string',
83
+ demandOption: true,
84
+ describe: 'Project id, name or slug'
85
+ });
86
+ const projects_add = {
87
+ command: 'add <organization> <project_ref>',
88
+ describe: 'Put a project in the organization (moves it from any other)',
89
+ builder: yargs => project_positionals(yargs).showHelpOnFail(false),
90
+ handler: async (args) => {
91
+ const { api } = await requireApi();
92
+ const id = await resolveOrganization(api, args.organization);
93
+ const project = await resolveProjectRef(api, args.project_ref);
94
+ await api.addOrganizationProject(id, project);
95
+ log.info(`✅ ${args.project_ref} is in ${args.organization}`);
96
+ }
97
+ };
98
+ const projects_rm = {
99
+ command: 'rm <organization> <project_ref>',
100
+ describe: 'Take a project out of the organization: it becomes personal',
101
+ builder: yargs => project_positionals(yargs)
102
+ .option('yes', {
103
+ type: 'boolean',
104
+ alias: 'y',
105
+ description: 'Skip the confirmation prompt'
106
+ })
107
+ .showHelpOnFail(false),
108
+ handler: async (args) => {
109
+ const { api } = await requireApi();
110
+ const id = await resolveOrganization(api, args.organization);
111
+ const project = await resolveProjectRef(api, args.project_ref);
112
+ const go = await confirm({
113
+ message: `Take ${args.project_ref} out of ${args.organization}?`,
114
+ yes: args.yes
115
+ });
116
+ if (!go)
117
+ return log.info('Cancelled.');
118
+ await api.removeOrganizationProject(id, project);
119
+ log.info(`✅ ${args.project_ref} is no longer in ${args.organization}`);
120
+ }
121
+ };
122
+ const organization_projects = {
123
+ command: 'projects',
124
+ describe: "Add or remove an organization's projects",
125
+ builder: yargs => yargs
126
+ .command(projects_add)
127
+ .command(projects_rm)
128
+ .demandCommand(1)
129
+ .showHelpOnFail(false),
130
+ handler: () => { }
131
+ };
132
+ const admin_positionals = (yargs) => yargs
133
+ .positional('organization', { type: 'string', demandOption: true })
134
+ .positional('user_id', { type: 'string', demandOption: true });
135
+ const admins_add = {
136
+ command: 'add <organization> <user_id>',
137
+ describe: 'Make someone an admin (gives no access to its projects)',
138
+ builder: yargs => admin_positionals(yargs).showHelpOnFail(false),
139
+ handler: async (args) => {
140
+ const { api } = await requireApi();
141
+ const id = await resolveOrganization(api, args.organization);
142
+ await api.addOrganizationAdmin(id, args.user_id);
143
+ log.info(`✅ ${args.user_id} administers ${args.organization}`);
144
+ }
145
+ };
146
+ const admins_rm = {
147
+ command: 'rm <organization> <user_id>',
148
+ describe: 'Remove an admin (an organization keeps at least one)',
149
+ builder: yargs => admin_positionals(yargs)
150
+ .option('yes', {
151
+ type: 'boolean',
152
+ alias: 'y',
153
+ description: 'Skip the confirmation prompt'
154
+ })
155
+ .showHelpOnFail(false),
156
+ handler: async (args) => {
157
+ const { api } = await requireApi();
158
+ const id = await resolveOrganization(api, args.organization);
159
+ const go = await confirm({
160
+ message: `Remove ${args.user_id} as admin of ${args.organization}?`,
161
+ yes: args.yes
162
+ });
163
+ if (!go)
164
+ return log.info('Cancelled.');
165
+ await api.removeOrganizationAdmin(id, args.user_id);
166
+ log.info(`✅ ${args.user_id} no longer administers ${args.organization}`);
167
+ }
168
+ };
169
+ const organization_admins = {
170
+ command: 'admins',
171
+ describe: "Add or remove an organization's admins",
172
+ builder: yargs => yargs
173
+ .command(admins_add)
174
+ .command(admins_rm)
175
+ .demandCommand(1)
176
+ .showHelpOnFail(false),
177
+ handler: () => { }
178
+ };
179
+ const organization = {
180
+ command: ['organization', 'org'],
181
+ describe: 'Group projects under a company (list, get, create, projects, admins)',
182
+ builder: yargs => yargs
183
+ .command(organization_list)
184
+ .command(organization_get)
185
+ .command(organization_create)
186
+ .command(organization_projects)
187
+ .command(organization_admins)
188
+ .demandCommand(1)
189
+ .showHelpOnFail(false),
190
+ handler: () => { }
191
+ };
192
+
193
+ export { organization };
package/dist/index.js CHANGED
@@ -6,6 +6,7 @@ import { link_deprecated } from './commands/link/index.js';
6
6
  import { login } from './commands/login/index.js';
7
7
  import { logout } from './commands/logout/index.js';
8
8
  import { mcp } from './commands/mcp/index.js';
9
+ import { organization } from './commands/organization/index.js';
9
10
  import { project } from './commands/project/index.js';
10
11
  import { upgrade } from './commands/upgrade/index.js';
11
12
  import { whoami } from './commands/whoami/index.js';
@@ -94,6 +95,7 @@ yg.scriptName('faable')
94
95
  .command(deploy)
95
96
  .command(auth)
96
97
  .command(project)
98
+ .command(organization)
97
99
  .command(login)
98
100
  .command(logout)
99
101
  .command(whoami)
package/dist/mcp/tools.js CHANGED
@@ -525,7 +525,7 @@ const TOOLS = [
525
525
  {
526
526
  name: 'get_auth_user',
527
527
  title: 'Get a user',
528
- 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).",
528
+ description: "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).",
529
529
  input: { user: user_ref, tenant, project },
530
530
  command: ['auth', 'users', 'get'],
531
531
  flags: a => [a.user, ...auth_scope(a)],
@@ -537,15 +537,36 @@ const TOOLS = [
537
537
  identities: (u.identities ?? []).map((i) => ({
538
538
  provider: i.provider ?? i.connection_type,
539
539
  user_id: i.user_id ?? i.provider_user_id
540
+ })),
541
+ credentials: (u.credentials ?? []).map((c) => ({
542
+ connection: c.connection_name ?? c.connection,
543
+ identifier: c.email ?? c.username
540
544
  }))
541
545
  }),
542
546
  annotations: AUTH_READ,
543
547
  example: { user: 'ana@example.com' }
544
548
  },
549
+ {
550
+ name: 'diagnose_auth_login',
551
+ title: 'Diagnose a login identifier',
552
+ 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'.",
553
+ input: {
554
+ identifier: z
555
+ .string()
556
+ .describe('The email or username the person is trying to log in with'),
557
+ tenant,
558
+ project
559
+ },
560
+ command: ['auth', 'users', 'diagnose'],
561
+ flags: a => [a.identifier, ...auth_scope(a)],
562
+ untrusted: true,
563
+ annotations: AUTH_READ,
564
+ example: { identifier: 'ana@personal.com' }
565
+ },
545
566
  {
546
567
  name: 'list_auth_logs',
547
568
  title: 'Read the Auth audit log',
548
- 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.",
569
+ 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. 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).",
549
570
  input: {
550
571
  email: z.string().optional().describe("Only this user's events (exact email)"),
551
572
  user: z.string().optional().describe('Only this user id (user_…)'),
@@ -574,14 +595,24 @@ const TOOLS = [
574
595
  ],
575
596
  untrusted: true,
576
597
  shape: (d) => ({
577
- events: (d?.data ?? []).map((l) => ({
578
- at: l.createdAt,
579
- type: l.type,
580
- status: l.status,
581
- ...log_user(l),
582
- message: l.message,
583
- ip: l.data?.ip
584
- })),
598
+ events: (d?.data ?? []).map((l) => {
599
+ const resolved = log_user(l);
600
+ // The identifier the person TYPED. On a failed login no user resolves,
601
+ // so this is the only record of who tried and with what address —
602
+ // surface it when it adds something the resolved user does not.
603
+ const tried = l.data?.email;
604
+ return {
605
+ at: l.createdAt,
606
+ type: l.type,
607
+ status: l.status,
608
+ ...resolved,
609
+ ...(tried && tried !== resolved.email
610
+ ? { attempted_identifier: tried }
611
+ : {}),
612
+ message: l.message,
613
+ ip: l.data?.ip
614
+ };
615
+ }),
585
616
  has_more: !!d?.has_more
586
617
  }),
587
618
  annotations: AUTH_READ,
@@ -1255,6 +1286,93 @@ const TOOLS = [
1255
1286
  write: true,
1256
1287
  annotations: { ...AUTH_WRITE, idempotentHint: false },
1257
1288
  example: { user: 'ana@example.com', channel: 'email' }
1289
+ },
1290
+ {
1291
+ name: 'update_auth_user',
1292
+ title: 'Update a user profile',
1293
+ 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.",
1294
+ input: {
1295
+ user: user_ref,
1296
+ email: z.string().optional().describe('New email — also the database login identifier unless profile_only'),
1297
+ name: z.string().optional(),
1298
+ email_verified: z.boolean().optional().describe('Mark the email verified (true) or clear verification (false)'),
1299
+ profile_only: z
1300
+ .boolean()
1301
+ .optional()
1302
+ .describe('With email, change only the profile email, not the login identifier'),
1303
+ connection: z
1304
+ .string()
1305
+ .optional()
1306
+ .describe('Database connection id or name, when the user has more than one credential'),
1307
+ tenant,
1308
+ project
1309
+ },
1310
+ command: ['auth', 'users', 'update'],
1311
+ flags: a => [
1312
+ a.user,
1313
+ ...opt('--email', a.email),
1314
+ ...opt('--name', a.name),
1315
+ ...(a.email_verified === undefined
1316
+ ? []
1317
+ : [a.email_verified ? '--email-verified' : '--no-email-verified']),
1318
+ ...(a.profile_only ? ['--profile-only'] : []),
1319
+ ...opt('--connection', a.connection),
1320
+ '--yes',
1321
+ ...auth_scope(a)
1322
+ ],
1323
+ write: true,
1324
+ annotations: { ...AUTH_WRITE, idempotentHint: true },
1325
+ example: { user: 'ana@example.com', email: 'ana@new.com' }
1326
+ },
1327
+ {
1328
+ name: 'set_auth_user_password',
1329
+ title: "Set a user's password",
1330
+ 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.",
1331
+ input: {
1332
+ user: user_ref,
1333
+ password: z
1334
+ .string()
1335
+ .optional()
1336
+ .describe('The exact new password. Omit and set generate:true to have one made.'),
1337
+ generate: z.boolean().optional().describe('Generate a strong password and return it once'),
1338
+ connection: z
1339
+ .string()
1340
+ .optional()
1341
+ .describe('Database connection id or name, when the user has more than one credential'),
1342
+ tenant,
1343
+ project
1344
+ },
1345
+ command: ['auth', 'users', 'set-password'],
1346
+ flags: a => [
1347
+ a.user,
1348
+ ...(a.generate ? ['--generate'] : []),
1349
+ ...opt('--connection', a.connection),
1350
+ '--yes',
1351
+ ...auth_scope(a)
1352
+ ],
1353
+ // The password goes on stdin, never in argv. Nothing is piped for the
1354
+ // generate path (the CLI makes its own and never reads stdin then).
1355
+ stdin: a => (a.generate ? undefined : a.password),
1356
+ write: true,
1357
+ annotations: { ...AUTH_WRITE, idempotentHint: false },
1358
+ example: { user: 'ana@example.com', generate: true }
1359
+ },
1360
+ {
1361
+ name: 'get_auth_recovery_link',
1362
+ title: 'Get a password-reset link',
1363
+ 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`.",
1364
+ input: { user: user_ref, tenant, project },
1365
+ command: ['auth', 'users', 'password-setup'],
1366
+ flags: a => [a.user, '--print', '--yes', ...auth_scope(a)],
1367
+ shape: (r) => ({
1368
+ link: r.link,
1369
+ ticket_id: r.ticket_id,
1370
+ channel: r.channel,
1371
+ user_id: r.user_id
1372
+ }),
1373
+ write: true,
1374
+ annotations: { ...AUTH_WRITE, idempotentHint: false },
1375
+ example: { user: 'ana@example.com' }
1258
1376
  }
1259
1377
  ];
1260
1378
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faable/faable",
3
- "version": "4.31.1",
3
+ "version": "4.33.0",
4
4
  "main": "dist/index.js",
5
5
  "license": "MIT",
6
6
  "author": "Marc Pomar <marc@faable.com>",