diff --git a/src/commands/auth/email_subscriptions/create.ts b/src/commands/auth/email_subscriptions/create.ts new file mode 100644 index 0000000..10c7724 --- /dev/null +++ b/src/commands/auth/email_subscriptions/create.ts @@ -0,0 +1,63 @@ +import { CommandModule } from 'yargs' +import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin' +import { log } from '../../../log' +import { TenantArgs, json_option, tenant_options } from '../options' +import { print_json } from '../render' +import { EMAIL_EVENTS, assertEmailEvents, assertRecipients } from './shared' + +interface EmailSubscriptionsCreateArgs extends TenantArgs { + to: string[] + event: string[] + disabled?: boolean +} + +export const email_subscriptions_create: CommandModule< + unknown, + EmailSubscriptionsCreateArgs +> = { + command: 'create', + describe: 'Email these addresses on tenant events (e.g. a new user)', + builder: yargs => + json_option(tenant_options(yargs)) + .option('to', { + type: 'string', + array: true, + demandOption: true, + description: 'Recipient email address — repeatable' + }) + .option('event', { + alias: 'e', + type: 'string', + array: true, + demandOption: true, + description: `Event to email about — repeatable. One of: ${EMAIL_EVENTS.join(', ')}` + }) + .option('disabled', { + type: 'boolean', + default: false, + description: 'Create it inactive: nothing is sent until enabled' + }) + .example( + '$0 auth email-subscriptions create --to ops@example.com -e user.created -e user.updated', + 'Get an email (with the form fields) every time a user is created or updated' + ) + .showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + assertRecipients(args.to) + assertEmailEvents(args.event) + const api = await requireAuthAdmin(args) + const created = (await api.notificationsubscriptionCreate({ + channel: 'email', + events: args.event, + active: !args.disabled, + config: { recipients: args.to } + } as any)) as any + + if (args.json) return print_json(created) + + log.info(`✅ Created email subscription ${created.id}`) + log.info(` To: ${(created.config?.recipients ?? []).join(', ')}`) + log.info(` Events: ${(created.events ?? []).join(', ')}`) + log.info(` Active: ${created.active ? 'yes' : 'no'}`) + }) +} diff --git a/src/commands/auth/email_subscriptions/index.ts b/src/commands/auth/email_subscriptions/index.ts new file mode 100644 index 0000000..bbf8f93 --- /dev/null +++ b/src/commands/auth/email_subscriptions/index.ts @@ -0,0 +1,23 @@ +import { CommandModule } from 'yargs' +import { email_subscriptions_create } from './create' +import { email_subscriptions_list } from './list' +import { email_subscriptions_rm } from './rm' +import { email_subscriptions_update } from './update' + +// Emails to the tenant's own people on its events (user.created, +// user.updated, credentials.exported), e.g. to hear about every form that +// lands as a user. Same resource as webhooks, `channel: 'email'`. +export const email_subscriptions: CommandModule = { + command: 'email-subscriptions', + aliases: ['emails'], + describe: 'Manage email subscriptions (emails to your team on tenant events)', + builder: yargs => + yargs + .command(email_subscriptions_list) + .command(email_subscriptions_create) + .command(email_subscriptions_update) + .command(email_subscriptions_rm) + .demandCommand(1) + .showHelpOnFail(false) as any, + handler: () => {} +} diff --git a/src/commands/auth/email_subscriptions/list.ts b/src/commands/auth/email_subscriptions/list.ts new file mode 100644 index 0000000..d24c212 --- /dev/null +++ b/src/commands/auth/email_subscriptions/list.ts @@ -0,0 +1,52 @@ +import { CommandModule } from 'yargs' +import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin' +import { + fetch_page, + from_paginator, + more_hint, + print +} from '../../../lib/listing' +import { log } from '../../../log' +import { AuthListArgs, list_options, tenant_options } from '../options' +import { print_json, table_lines, yes_no } from '../render' +import { EmailSubscription, isEmail } from './shared' + +export const email_subscriptions_list: CommandModule = { + command: 'list', + describe: 'List email subscriptions', + builder: yargs => + list_options(tenant_options(yargs)).showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + const api = await requireAuthAdmin(args) + const page = await fetch_page( + from_paginator(api.notificationsubscriptionList({})), + args + ) + // The resource also holds webhooks; this command is email. + const data = (page.data as EmailSubscription[]).filter(isEmail) + + if (args.json) return print_json({ ...page, data }) + + if (data.length === 0) { + log.info( + '📭 No email subscriptions. Create one with `faable auth email-subscriptions create`.' + ) + return + } + log.info(`📧 ${data.length} email subscription(s):`) + const rows = data.map(s => [ + s.id, + (s.config?.recipients ?? []).join(','), + s.events.join(','), + yes_no(s.active) + ]) + for (const line of table_lines( + ['ID', 'RECIPIENTS', 'EVENTS', 'ACTIVE'], + rows + )) { + print(line) + } + const hint = more_hint(page) + if (hint) log.info(hint) + }) +} diff --git a/src/commands/auth/email_subscriptions/rm.ts b/src/commands/auth/email_subscriptions/rm.ts new file mode 100644 index 0000000..dcef1cd --- /dev/null +++ b/src/commands/auth/email_subscriptions/rm.ts @@ -0,0 +1,56 @@ +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 { isEmail } from './shared' + +interface EmailSubscriptionsRmArgs extends TenantArgs { + subscription_id: string + yes?: boolean +} + +export const email_subscriptions_rm: CommandModule< + unknown, + EmailSubscriptionsRmArgs +> = { + command: 'rm ', + describe: 'Delete an email subscription', + builder: yargs => + json_option(tenant_options(yargs)) + .positional('subscription_id', { + type: 'string', + demandOption: true, + description: 'Subscription id (notificationsubscription_…)' + }) + .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 s = (await api.notificationsubscriptionGet( + args.subscription_id + )) as any + if (!isEmail(s)) { + throw new Error( + `${s.id} is a webhook, not an email subscription: use \`faable auth webhooks rm\`.` + ) + } + const go = await confirm({ + message: `Delete email subscription ${s.id} → ${(s.config?.recipients ?? []).join(', ')}? Those emails stop.`, + yes: args.yes + }) + if (!go) { + log.info('Cancelled.') + return + } + await api.notificationsubscriptionDelete(s.id) + if (args.json) return print_json({ deleted: true, id: s.id }) + log.info(`🗑️ Deleted email subscription ${s.id}.`) + }) +} diff --git a/src/commands/auth/email_subscriptions/shared.test.ts b/src/commands/auth/email_subscriptions/shared.test.ts new file mode 100644 index 0000000..7e46f15 --- /dev/null +++ b/src/commands/auth/email_subscriptions/shared.test.ts @@ -0,0 +1,25 @@ +import test from 'ava' +import { assertEmailEvents, assertRecipients, isEmail } from './shared' + +test('email events: the three with a template pass', t => { + t.notThrows(() => + assertEmailEvents(['user.created', 'user.updated', 'credentials.exported']) + ) +}) + +test('email events: one without a template is refused and named', t => { + const err = t.throws(() => assertEmailEvents(['user.created', 'auth.login'])) + t.regex(err!.message, /auth\.login/) + t.regex(err!.message, /faable auth webhooks/) +}) + +test('recipients: a malformed address is refused and named', t => { + t.notThrows(() => assertRecipients(['marc@faable.com'])) + const err = t.throws(() => assertRecipients(['marc@faable.com', 'nope'])) + t.regex(err!.message, /nope/) +}) + +test('isEmail tells email subscriptions from webhooks', t => { + t.true(isEmail({ channel: 'email' })) + t.false(isEmail({ channel: 'webhook' })) +}) diff --git a/src/commands/auth/email_subscriptions/shared.ts b/src/commands/auth/email_subscriptions/shared.ts new file mode 100644 index 0000000..a417e1a --- /dev/null +++ b/src/commands/auth/email_subscriptions/shared.ts @@ -0,0 +1,43 @@ +// Pieces shared by the `faable auth email-subscriptions` commands. +// +// An email subscription is a notification subscription with `channel: 'email'` +// (the same resource as webhooks): Faable Auth emails the tenant's own people +// on an event — e.g. every time a form creates or updates a user, the +// recipients get an email with the user's `faable.com/fields`. + +export type EmailSubscription = { + id: string + channel: 'webhook' | 'email' + events: string[] + active: boolean + config: { recipients?: string[] } + createdAt?: string +} + +export const isEmail = (s: { channel?: string }) => s.channel === 'email' + +// The only events with an email template in Faable Auth +// (auth: EMAIL_SUBSCRIPTION_EVENTS). Any other event would be stored and never +// sent, so it is refused here, before the request. +export const EMAIL_EVENTS = [ + 'user.created', + 'user.updated', + 'credentials.exported' +] as const + +export const assertEmailEvents = (events: string[]) => { + const unknown = events.filter( + e => !(EMAIL_EVENTS as readonly string[]).includes(e) + ) + if (unknown.length) { + throw new Error( + `Email subscriptions can only send ${EMAIL_EVENTS.join(', ')} (no email template for: ${unknown.join(', ')}). For other events use \`faable auth webhooks\`.` + ) + } +} + +const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ +export const assertRecipients = (to: string[]) => { + const bad = to.filter(r => !EMAIL.test(r)) + if (bad.length) throw new Error(`Not an email address: ${bad.join(', ')}`) +} diff --git a/src/commands/auth/email_subscriptions/update.ts b/src/commands/auth/email_subscriptions/update.ts new file mode 100644 index 0000000..accbf22 --- /dev/null +++ b/src/commands/auth/email_subscriptions/update.ts @@ -0,0 +1,67 @@ +import { CommandModule } from 'yargs' +import { requireAuthAdmin, withAuthHints } from '../../../api/auth_admin' +import { log } from '../../../log' +import { TenantArgs, json_option, tenant_options } from '../options' +import { print_json, yes_no } from '../render' +import { assertEmailEvents, assertRecipients } from './shared' + +interface EmailSubscriptionsUpdateArgs extends TenantArgs { + subscription_id: string + to?: string[] + event?: string[] + enabled?: boolean +} + +export const email_subscriptions_update: CommandModule< + unknown, + EmailSubscriptionsUpdateArgs +> = { + command: 'update ', + describe: 'Change an email subscription (recipients, events, enabled)', + builder: yargs => + json_option(tenant_options(yargs)) + .positional('subscription_id', { + type: 'string', + demandOption: true, + description: 'Subscription id (notificationsubscription_…)' + }) + .option('to', { + type: 'string', + array: true, + description: 'Replace the recipients — repeatable' + }) + .option('event', { + alias: 'e', + type: 'string', + array: true, + description: 'Replace the events — repeatable' + }) + .option('enabled', { + type: 'boolean', + description: 'Enable (--enabled) or pause (--no-enabled) the emails' + }) + .showHelpOnFail(false) as any, + handler: withAuthHints(async args => { + if (args.to?.length) assertRecipients(args.to) + if (args.event?.length) assertEmailEvents(args.event) + const patch = { + ...(args.to?.length ? { config: { recipients: args.to } } : {}), + ...(args.event?.length ? { events: args.event } : {}), + ...(args.enabled !== undefined ? { active: args.enabled } : {}) + } + if (Object.keys(patch).length === 0) { + throw new Error( + 'Nothing to update — pass at least one of --to, --event, --enabled' + ) + } + const api = await requireAuthAdmin(args) + const s = (await api.notificationsubscriptionUpdate( + args.subscription_id, + patch as any + )) as any + if (args.json) return print_json(s) + log.info( + `✅ Updated email subscription ${s.id} (${(s.config?.recipients ?? []).join(', ')}, ${(s.events ?? []).join(', ')}, active ${yes_no(s.active)})` + ) + }) +} diff --git a/src/commands/auth/index.ts b/src/commands/auth/index.ts index 9b4109b..ce549f5 100644 --- a/src/commands/auth/index.ts +++ b/src/commands/auth/index.ts @@ -9,6 +9,7 @@ import { roles } from './roles' import { sessions } from './sessions' import { users } from './users' import { webhooks } from './webhooks' +import { email_subscriptions } from './email_subscriptions' // `faable auth` — management commands for a Faable Auth tenant. Auth: reuses // the `faable login` session (or FAABLE_TOKEN); tenant: --account / @@ -17,7 +18,7 @@ import { webhooks } from './webhooks' export const auth: CommandModule = { command: 'auth', describe: - 'Manage Faable Auth (users, roles, APIs, sessions, logins, actions, clients, webhooks, audit logs)', + 'Manage Faable Auth (users, roles, APIs, sessions, logins, actions, clients, webhooks, email subscriptions, audit logs)', builder: yargs => yargs .command(users) @@ -29,6 +30,7 @@ export const auth: CommandModule = { .command(sessions) .command(connections) .command(webhooks) + .command(email_subscriptions) .command(accounts) .command(auth_use) .demandCommand(1)