diff --git a/README.md b/README.md index cc7a782..400da97 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,13 @@ prints JSON (indented; compact with `--json`) and says what happened in a stable | `reply inbox mark-read ` · `reply inbox mark-unread ` | → `read` / `unread` | | `reply account list [--channel email\|linkedin]` | the email and LinkedIn accounts a send can go from, whose each is, and the state of each | | `reply schedule list` | the sending schedules the account can use, each with its time zone and its windows by weekday | +| `reply account connect --channel email --provider gmail\|office365 [--name N]` · `--channel linkedin --name N` | a link that connects one new account, for the person who signs in to open → `link`, `expires_at`, `pending_id` | +| `reply account reconnect --channel email\|linkedin` | a link that reconnects an account that lost its connection → `link` | +| `reply account pending [--channel email\|linkedin]` | the connection links made and not used yet, without the links | +| `reply account limits --channel email\|linkedin [--daily N] [--set …]` | read an account's sending limits, or change some of them | +| `reply account pause --channel linkedin` · `resume --channel linkedin` | → `inactive` / `active`, toggled only when it is not already so | +| `reply account unblock ` | let a mailbox its provider stopped from sending pick its sequences back up → `unblocked` | +| `reply account delete --channel email\|linkedin --yes [--force]` | → `deleted`; without `--yes` nothing is sent | `` is exactly one of `--contact |@file|-`, `--email
` (with `--first-name`, `--last-name`, `--company`, `--title`), or `--contact-id `. The JSON takes the same fields @@ -512,6 +519,49 @@ For `inbox reply`, read the thread with `reply inbox get` before trying again. F `sequence list --name -` first. Every other work command can simply be run again; a `contact delete` repeated after its first one took effect answers `contact.not_found`. +**Connecting accounts.** `account connect` and `account reconnect` print a link for the person who +signs in to the account: they open it in a browser and sign in on Google's, Microsoft's or LinkedIn's +own page, so no password passes through the CLI. The link is a credential for whoever holds it. It is +printed once, in the stdout field `link`, and never on stderr, in a `--verbose` trace (where it reads +``), in an error or in a log. A connection link connects one account, works once and +expires, and the attempt is listed by `account pending` until the person finishes; then the account +is in `account list`. An email link needs `--provider`; a reconnect takes the provider from the +mailbox, and the person must sign in with the same address. A LinkedIn connect needs `--name`, which +Reply lists the pending account under. + +A Reply without one-mailbox email links answers that route with a 404 and no code. The email +commands then refuse with `email_link.not_available` (exit 1) and print nothing, unless +`--allow-shared-page` is given: then they print the account user's hosted mailbox page, the +provider's connect on it with `--provider` and its index without, with `"link_kind":"shared_page"`, +`"expires_at":null` and a `warning`. That address does not expire and lets its holder manage all of +this user's mailboxes, deletion included, so ask for it only when that is acceptable. For +`account reconnect` the provider's connect is marked as a reconnect, so a user with no free mailbox +slot reconnects the mailbox rather than being refused a new one; on the index, the person opens the +mailbox and reconnects it from there. +`shared_page.not_enabled` means the plan does not include hosted pages. `account pending` then lists +no email entries and answers `"supported":false` with `"unsupported_channels":["email"]`. + +```sh +reply account connect --channel email --provider gmail --name "Sales mailbox" +reply account connect --channel linkedin --name "Dana Example" +reply account reconnect 34 --channel linkedin +reply account pending +``` + +`account limits` prints the limits in Reply's names: an email account's `safety` section, which +`--daily` and `--set '{"minSendingDelaySeconds":90}'` change, and a LinkedIn account's `limits`, +which `--set` changes as Reply's limits update does. `account pause` and `account resume` act on a +LinkedIn account; Reply's only call flips the state, so it is read first and left alone when it is +already the one asked for. The flip turns an enabled account off and any other on, so `pause` flips +only an enabled account and `resume` only a disabled one. An account at its daily limit is active: +`resume` leaves it alone, and `pause` refuses it with `account.pause_unavailable` before any write. A +state the CLI does not know is refused with `account.status_unknown`, also before any write. Reply +has no way to pause a mailbox through its API. `account delete` +needs `--yes`, and `--force` deletes a LinkedIn account sequences still use. Reply's refusals come +under the CLI's codes, as every work command's do (`linkedin.account_in_use`, `email_account.not_found`, +`linkedin.invalid_cookie`), with Reply's own code in `reply_code`. After exit 3 from `account connect` or `account reconnect`, read +`account pending` before running it again: a link may already have been made. + **Errors.** With `--json`, a failure is one line on stderr: `{"error":{"code":"contact.opted_out","title":…,"status":…,"reply_code":…,"ids":{…}}}`. `ids` is whatever the command learned before failing, for example the id of a contact it created before diff --git a/skills/reply-adapter/reply-cli/SKILL.md b/skills/reply-adapter/reply-cli/SKILL.md index 0dc6265..cb5fb6a 100644 --- a/skills/reply-adapter/reply-cli/SKILL.md +++ b/skills/reply-adapter/reply-cli/SKILL.md @@ -6,7 +6,7 @@ description: > Use when executing any Reply.io operation from a shell, setting up authentication, or when another Reply skill needs commands executed. metadata: - version: 1.3.2 + version: 1.4.0 pack: reply-adapter category: execution maturity: reviewed @@ -149,6 +149,12 @@ exit codes with their error `code` slugs. `contact`, `inbox`, `account`, `schedule`, `direct-send`); `reply --help` lists them and each command's `--help` gives its result and error codes. Don't invent one: reach any other operation through `reply api`, using the endpoint mapping in `reply-operations-mapping`. +- `reply account connect` and `reply account reconnect` print a link for the person who signs in to + the account to open. The link is a credential: it is in the stdout field `link` once and nowhere + else (a `--verbose` trace shows ``). Hand it to that person and do not store, log + or repeat it. `email_link.not_available` means this Reply has no one-mailbox email link yet; pass + `--allow-shared-page` only when the user accepts the hosted mailbox page, whose address does not + expire and lets its holder manage all of that user's mailboxes, deletion included. ## Safety @@ -165,6 +171,8 @@ explicit confirmation its Safety section requires. ## Changelog +- 1.4.0 (2026-11-11): *Failure modes* says how to treat the link `account connect` and `account + reconnect` print, and when `--allow-shared-page` is right. - 1.3.2 (2026-11-06): *Failure modes* no longer says the work commands don't exist: it names the groups (`sequence`, `contact-list`, `live-data`, `contact`, `inbox`, `account`, `schedule`, `direct-send`) and keeps `reply api` for every other operation. diff --git a/src/__tests__/operations/account-links.test.ts b/src/__tests__/operations/account-links.test.ts new file mode 100644 index 0000000..c32026c --- /dev/null +++ b/src/__tests__/operations/account-links.test.ts @@ -0,0 +1,269 @@ +import crypto from 'crypto'; +import {describe, it, expect, beforeEach} from 'vitest'; +import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import {handle_account_connect, handle_account_reconnect, handle_account_pending} from '../../operations/account-links'; +import {read_shared_page, shared_page_link, SHARED_PAGE_WARNING} from '../../operations/shared-page'; +import type {Op_globals} from '../../operations/options'; + +// Generated for every run: no test holds a real link or token. +const token = (): string=>crypto.randomBytes(24).toString('hex'); +const APP = 'https://app.example.test'; +const email_link = (t = token())=>`${APP}/email-connect/${t}`; +const linkedin_link = (t = token())=>`${APP}/linkedin-connect/${t}`; +const shared_url = (t: string)=>`${APP}/hosted/eac/index/${t}`; +const missing = ()=>json({type: 'about:blank', title: 'Not Found', status: 404}, 404); + +const run = async(fn: (g: Op_globals) => Promise, g: Op_globals = {json: true})=>{ + const {out, err} = await capture(()=>fn(g)); + return {result: JSON.parse(out) as Record, err}; +}; +const fails = (fn: () => Promise)=>fn().catch((x: unknown)=>x); + +beforeEach(()=>{ mock_fetch.mockReset(); }); + +describe('the hosted page forms', ()=>{ + it('builds each provider\'s connect from the token of the index Reply answers, and the index without a provider', ()=>{ + const t = token(); + const page = read_shared_page(shared_url(t)); + expect(page).toEqual({index: shared_url(t), token: t, base: APP}); + expect(shared_page_link(page!, 'gmail', 'connect')).toBe(`${APP}/hosted/eac/ConnectWithGMail?uidToken=${t}`); + expect(shared_page_link(page!, 'office365', 'connect')).toBe(`${APP}/hosted/eac/ConnectWithOffice?uidToken=${t}&isExchange=false`); + expect(shared_page_link(page!, undefined, 'connect')).toBe(shared_url(t)); + }); + + it('marks a provider\'s connect for a reconnect, so the hosted page does not count it as a new mailbox; the index is as Reply gave it', ()=>{ + const t = token(); + const page = read_shared_page(shared_url(t)); + expect(shared_page_link(page!, 'gmail', 'reconnect')).toBe(`${APP}/hosted/eac/ConnectWithGMail?uidToken=${t}&reconnect=true`); + expect(shared_page_link(page!, 'office365', 'reconnect')) + .toBe(`${APP}/hosted/eac/ConnectWithOffice?uidToken=${t}&isExchange=false&reconnect=true`); + expect(shared_page_link(page!, undefined, 'reconnect')).toBe(shared_url(t)); + }); + + it('keeps a path the app is served under, and reads nothing else as the hosted index', ()=>{ + const t = token(); + expect(read_shared_page(`${APP}/app/hosted/eac/index/${t}/`)).toMatchObject({base: `${APP}/app`, token: t}); + for (const url of ['not a url', `${APP}/hosted/eac/${t}`, `ftp://app.example.test/hosted/eac/index/${t}`, `${APP}/hosted/eac/index/`]) + { + expect(read_shared_page(url), url).toBeNull(); + } + }); +}); + +describe('account connect', ()=>{ + it('email: asks Reply for a one-mailbox link and prints it with its expiry and pending entry', async()=>{ + const link = email_link(); + answer(json({connectionLink: link, pendingAccountId: 50, provider: 'gmail', expiresAtUtc: '2026-11-18T12:00:00Z'}, 201)); + const {result} = await run(g=>handle_account_connect({channel: 'email', provider: 'gmail', name: ' Sales '}, ctx(), g)); + expect(result).toStrictEqual({channel: 'email', link, expires_at: '2026-11-18T12:00:00Z', pending_id: 50, kind: 'connect', + link_kind: 'connection_link'}); + expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/email-accounts/connection-link', body: {provider: 'gmail', name: 'Sales'}}]); + }); + + it('email: a Reply without the route is refused, email_link.not_available, and the shared page is never asked for', async()=>{ + answer(missing()); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'office365'}, ctx(), {}))) + .toMatchObject({code: 'email_link.not_available', exit_code: 1}); + expect(sent().map(r=>r.url)).toEqual(['https://api/v3/email-accounts/connection-link']); + }); + + it('email: a 404 Reply gives a code to is Reply\'s refusal, never a missing route', async()=>{ + answer(json({code: 'emailAccount.notFound', title: 'Not Found', status: 404}, 404)); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), {}))) + .toMatchObject({code: 'email_account.not_found', reply_code: 'emailAccount.notFound', status: 404, exit_code: 1}); + expect(sent()).toHaveLength(1); + }); + + it('email --allow-shared-page: on a Reply without the route, prints the provider\'s hosted connect, with no expiry and the warning', async()=>{ + for (const [provider, path] of [['gmail', 'ConnectWithGMail?uidToken='], ['office365', 'ConnectWithOffice?uidToken=']] as const) + { + mock_fetch.mockReset(); + const t = token(); + answer(missing(), json({url: shared_url(t)})); + const {result} = await run(g=>handle_account_connect({channel: 'email', provider, allowSharedPage: true}, ctx(), g)); + expect(result).toStrictEqual({channel: 'email', link: `${APP}/hosted/eac/${path}${t}${provider === 'office365' ? '&isExchange=false' : ''}`, + expires_at: null, pending_id: null, kind: 'connect', link_kind: 'shared_page', warning: SHARED_PAGE_WARNING}); + expect(sent().map(r=>[r.method, r.url])).toEqual([ + ['POST', 'https://api/v3/email-accounts/connection-link'], ['GET', 'https://api/v1/SharedPageUrl'], + ]); + } + }); + + it('email --allow-shared-page without --provider: a Reply without one-mailbox links gives the hosted index', async()=>{ + const t = token(); + answer(missing(), json({url: shared_url(t)})); + const {result} = await run(g=>handle_account_connect({channel: 'email', allowSharedPage: true}, ctx(), g)); + expect(result).toMatchObject({link: shared_url(t), link_kind: 'shared_page'}); + expect(sent().map(r=>[r.method, r.url])).toEqual([['GET', 'https://api/v3/email-accounts/pending'], ['GET', 'https://api/v1/SharedPageUrl']]); + }); + + it('email --allow-shared-page without --provider: a Reply with them is refused, and no shared page is asked for', async()=>{ + answer(json([])); + expect(await fails(()=>handle_account_connect({channel: 'email', allowSharedPage: true}, ctx(), {}))) + .toMatchObject({code: 'email_link.provider_required', exit_code: 1}); + expect(sent()).toHaveLength(1); + }); + + it('email: the plan without hosted pages is sharedPage.notEnabled; any other v1 refusal reads as every refusal does', async()=>{ + answer(missing(), json('Shared page is not enabled for your account', 403)); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), {}))) + .toMatchObject({code: 'shared_page.not_enabled', status: 403, exit_code: 1}); + mock_fetch.mockReset(); + answer(missing(), json({message: 'denied due to the organization permissions / payment plan settings'}, 403)); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), {}))) + .toMatchObject({code: 'access.feature_unavailable', exit_code: 1}); + }); + + it('email: a shared page in a form the CLI cannot read is reply.unavailable', async()=>{ + answer(missing(), json({url: `${APP}/somewhere/else/${token()}`})); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), {}))) + .toMatchObject({code: 'reply.unavailable', exit_code: 1}); + }); + + it('email: a shared page Reply answers as a bare string is read as the address', async()=>{ + const t = token(); + answer(missing(), json(shared_url(t))); + const {result} = await run(g=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), g)); + expect(result).toMatchObject({link: `${APP}/hosted/eac/ConnectWithGMail?uidToken=${t}`, link_kind: 'shared_page'}); + }); + + it('email: Reply\'s refusal comes under the CLI\'s code, with Reply\'s in reply_code', async()=>{ + answer(json({code: 'emailAccount.noFreeMailboxSlots', title: 'Conflict', status: 409, detail: 'One more email account would need a paid seat'}, 409)); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'gmail'}, ctx(), {}))) + .toMatchObject({code: 'email_account.no_free_mailbox_slots', reply_code: 'emailAccount.noFreeMailboxSlots', status: 409, detail: 'One more email account would need a paid seat', exit_code: 1}); + }); + + it('email: without --provider and without --allow-shared-page, or with a provider it does not know, is a usage error before any call', async()=>{ + expect(await fails(()=>handle_account_connect({channel: 'email'}, ctx(), {}))).toMatchObject({code: 'usage.provider', exit_code: 2}); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'yahoo'}, ctx(), {}))).toMatchObject({code: 'usage.choice', exit_code: 2}); + expect(await fails(()=>handle_account_connect({channel: 'email', provider: 'gmail', name: 'x'.repeat(101)}, ctx(), {}))) + .toMatchObject({code: 'usage.name', exit_code: 2}); + expect(await fails(()=>handle_account_connect({provider: 'gmail'}, ctx(), {}))).toMatchObject({code: 'usage.channel', exit_code: 2}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('linkedin: asks for a connection link under the name, and prints it with its pending entry', async()=>{ + const link = linkedin_link(); + answer(json({connectionLink: link, pendingAccountId: 51}, 201)); + const {result} = await run(g=>handle_account_connect({channel: 'linkedin', name: 'Dana Example'}, ctx(), g)); + expect(result).toStrictEqual({channel: 'linkedin', link, expires_at: null, pending_id: 51, kind: 'connect', link_kind: 'connection_link'}); + expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/linkedin-accounts/connection-link', body: {name: 'Dana Example'}}]); + }); + + it('linkedin: needs --name, and takes neither --provider nor --allow-shared-page', async()=>{ + expect(await fails(()=>handle_account_connect({channel: 'linkedin'}, ctx(), {}))).toMatchObject({code: 'usage.name', exit_code: 2}); + expect(await fails(()=>handle_account_connect({channel: 'linkedin', name: 'D', provider: 'gmail'}, ctx(), {}))) + .toMatchObject({code: 'usage.channel', exit_code: 2}); + expect(await fails(()=>handle_account_connect({channel: 'linkedin', name: 'D', allowSharedPage: true}, ctx(), {}))) + .toMatchObject({code: 'usage.channel', exit_code: 2}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('linkedin: Reply\'s limit comes under the CLI\'s code; an answer without the link is outcome.unknown, since a link may exist', async()=>{ + answer(json({code: 'linkedInAccount.limitReached', status: 409}, 409)); + expect(await fails(()=>handle_account_connect({channel: 'linkedin', name: 'D'}, ctx(), {}))) + .toMatchObject({code: 'linkedin.account_limit_reached', reply_code: 'linkedInAccount.limitReached', exit_code: 1}); + mock_fetch.mockReset(); + answer(json({pendingAccountId: 51}, 201)); + expect(await fails(()=>handle_account_connect({channel: 'linkedin', name: 'D'}, ctx(), {}))) + .toMatchObject({code: 'outcome.unknown', exit_code: 3}); + }); +}); + +describe('account reconnect', ()=>{ + it('email: asks Reply for a reconnect link for the mailbox, and prints it', async()=>{ + const link = email_link(); + answer(json({connectionLink: link, pendingAccountId: 52, provider: 'office365', expiresAtUtc: '2026-11-18T12:00:00Z'})); + const {result} = await run(g=>handle_account_reconnect('4294967296', {channel: 'email'}, ctx(), g)); + expect(result).toStrictEqual({channel: 'email', id: 4294967296, link, expires_at: '2026-11-18T12:00:00Z', pending_id: 52, + kind: 'reconnect', link_kind: 'connection_link'}); + expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/email-accounts/4294967296/reconnect', body: undefined}]); + }); + + it('email: a Reply without the route is refused, and --allow-shared-page gives the provider\'s hosted connect, marked as a reconnect', async()=>{ + answer(missing()); + expect(await fails(()=>handle_account_reconnect('12', {channel: 'email'}, ctx(), {}))).toMatchObject({code: 'email_link.not_available'}); + const rows = [ + ['gmail', (t: string)=>`${APP}/hosted/eac/ConnectWithGMail?uidToken=${t}&reconnect=true`], + ['office365', (t: string)=>`${APP}/hosted/eac/ConnectWithOffice?uidToken=${t}&isExchange=false&reconnect=true`], + [undefined, shared_url], + ] as const; + for (const [provider, link] of rows) + { + mock_fetch.mockReset(); + const t = token(); + answer(missing(), json({url: shared_url(t)})); + const {result} = await run(g=>handle_account_reconnect('12', {channel: 'email', provider, allowSharedPage: true}, ctx(), g)); + expect(result, provider).toStrictEqual({channel: 'email', id: 12, link: link(t), expires_at: null, + pending_id: null, kind: 'reconnect', link_kind: 'shared_page', warning: SHARED_PAGE_WARNING}); + } + }); + + it('email: a mailbox Reply cannot reconnect by link, or not the user\'s, is Reply\'s refusal, under the CLI\'s code', async()=>{ + for (const [status, reply_code, code] of [[400, 'emailAccount.reconnectNotSupported', 'email_account.reconnect_not_supported'], + [404, 'emailAccount.notFound', 'email_account.not_found']] as const) + { + mock_fetch.mockReset(); + answer(json({code: reply_code, status}, status)); + expect(await fails(()=>handle_account_reconnect('12', {channel: 'email', allowSharedPage: true}, ctx(), {}))) + .toMatchObject({code, reply_code, status, exit_code: 1}); + expect(sent()).toHaveLength(1); + } + }); + + it('linkedin: asks Reply for a reconnect link; it has no pending entry and no expiry', async()=>{ + const link = linkedin_link(); + answer(json({connectionLink: link})); + const {result} = await run(g=>handle_account_reconnect('34', {channel: 'linkedin'}, ctx(), g)); + expect(result).toStrictEqual({channel: 'linkedin', id: 34, link, expires_at: null, pending_id: null, kind: 'reconnect', + link_kind: 'connection_link'}); + expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/linkedin-accounts/34/reconnect', body: undefined}]); + }); + + it('a bad id, a missing channel or --name is a usage error before any call', async()=>{ + expect(await fails(()=>handle_account_reconnect('0', {channel: 'email'}, ctx(), {}))).toMatchObject({code: 'usage.id', exit_code: 2}); + expect(await fails(()=>handle_account_reconnect('4294967296', {channel: 'linkedin'}, ctx(), {}))).toMatchObject({code: 'usage.id'}); + expect(await fails(()=>handle_account_reconnect('12', {}, ctx(), {}))).toMatchObject({code: 'usage.channel'}); + expect(await fails(()=>handle_account_reconnect('12', {channel: 'email', name: 'x'}, ctx(), {}))).toMatchObject({code: 'usage.name'}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); +}); + +describe('account pending', ()=>{ + it('lists both channels\' entries in one shape, and never a LinkedIn entry\'s link', async()=>{ + const link = linkedin_link(); + answer( + json([{id: 50, name: 'Sales', provider: 'gmail', kind: 'connect', emailAccountId: null, expiresAtUtc: '2026-11-18T12:00:00Z', isExpired: false}, + {id: 52, name: null, provider: 'office365', kind: 'reconnect', emailAccountId: 4294967296, expiresAtUtc: '2026-11-01T12:00:00Z', + isExpired: true}]), + json([{id: 7, name: 'Dana Example', connectionLink: link, expiresAtUtc: '2026-11-19T00:00:00Z', isExpired: false}]), + ); + const {result} = await run(g=>handle_account_pending({}, ctx(), g)); + expect(result).toStrictEqual({items: [ + {channel: 'email', id: 50, name: 'Sales', kind: 'connect', account_id: null, expires_at: '2026-11-18T12:00:00Z', expired: false}, + {channel: 'email', id: 52, name: null, kind: 'reconnect', account_id: 4294967296, expires_at: '2026-11-01T12:00:00Z', expired: true}, + {channel: 'linkedin', id: 7, name: 'Dana Example', kind: 'connect', account_id: null, expires_at: '2026-11-19T00:00:00Z', expired: false}, + ], supported: true, unsupported_channels: []}); + expect(JSON.stringify(result)).not.toContain(link); + expect(sent().map(r=>r.url)).toEqual(['https://api/v3/email-accounts/pending', 'https://api/v3/linkedin-accounts/pending']); + }); + + it('a Reply without one-mailbox email links: email lists nothing and says it is not supported', async()=>{ + answer(missing()); + expect((await run(g=>handle_account_pending({channel: 'email'}, ctx(), g))).result) + .toStrictEqual({items: [], supported: false, unsupported_channels: ['email']}); + mock_fetch.mockReset(); + answer(missing(), json([])); + expect((await run(g=>handle_account_pending({}, ctx(), g))).result).toStrictEqual({items: [], supported: false, unsupported_channels: ['email']}); + }); + + it('--channel linkedin reads only LinkedIn; a refusal comes under the CLI\'s code', async()=>{ + answer(json([])); + expect((await run(g=>handle_account_pending({channel: 'linkedin'}, ctx(), g))).result).toStrictEqual({items: [], supported: true, + unsupported_channels: []}); + expect(sent().map(r=>r.url)).toEqual(['https://api/v3/linkedin-accounts/pending']); + mock_fetch.mockReset(); + answer(json({code: 'linkedInAccount.forbidden', status: 403}, 403)); + expect(await fails(()=>handle_account_pending({channel: 'linkedin'}, ctx(), {}))).toMatchObject({code: 'access.feature_unavailable', reply_code: 'linkedInAccount.forbidden'}); + }); +}); diff --git a/src/__tests__/operations/account-manage.test.ts b/src/__tests__/operations/account-manage.test.ts new file mode 100644 index 0000000..11c6a8a --- /dev/null +++ b/src/__tests__/operations/account-manage.test.ts @@ -0,0 +1,232 @@ +import {describe, it, expect, beforeEach, vi} from 'vitest'; +import fs from 'fs'; +import {mock_fetch, json, ctx, sent, answer, capture} from './helpers'; +import { + handle_account_limits, handle_account_pause, handle_account_resume, handle_account_unblock, handle_account_delete, +} from '../../operations/account-manage'; +import type {Op_globals} from '../../operations/options'; + +const SAFETY = {dailyLimit: 500, isEmailsThrottlingEnabled: false, emailsPerInterval: null, emailsThrottlingSecondsInterval: null, + isSendingDelayEnabled: true, maxSendingDelaySeconds: 120, minSendingDelaySeconds: 60}; +const mailbox = (safety: Record = SAFETY)=>({id: 12, ownerUserId: 1, emailAccountType: 'gmail', connectionStatus: 'connected', safety}); +const LIMITS = {limitsMode: 'fixed', fixedMax: {dailySendMessageCount: 50}, rangeMin: null, rangeMax: null, actionDelayMinSeconds: 60, + actionDelayMaxSeconds: 120}; +const linkedin = (over: Record = {})=>({id: 34, name: 'Dana Example', status: 'enabled', limits: LIMITS, ...over}); + +const run = async(fn: (g: Op_globals) => Promise)=>{ + const {out, err} = await capture(()=>fn({json: true})); + return {result: JSON.parse(out) as Record, err}; +}; +const fails = (fn: () => Promise)=>fn().catch((x: unknown)=>x); + +beforeEach(()=>{ mock_fetch.mockReset(); vi.restoreAllMocks(); }); + +describe('account limits', ()=>{ + it('email: without a change reads the account and prints its safety section', async()=>{ + answer(json(mailbox())); + expect((await run(g=>handle_account_limits('12', {channel: 'email'}, ctx(), g))).result).toStrictEqual({channel: 'email', id: 12, limits: SAFETY}); + expect(sent()).toEqual([{method: 'GET', url: 'https://api/v3/email-accounts/12', body: undefined}]); + }); + + it('email: --daily and --set go into one PATCH of the safety section, and the answer is printed', async()=>{ + const after = {...SAFETY, dailyLimit: 200, minSendingDelaySeconds: 90}; + answer(json(mailbox(after))); + const {result} = await run(g=>handle_account_limits('12', {channel: 'email', daily: '200', set: '{"minSendingDelaySeconds":90}'}, ctx(), g)); + expect(result).toStrictEqual({channel: 'email', id: 12, limits: after}); + expect(sent()).toEqual([{method: 'PATCH', url: 'https://api/v3/email-accounts/12', body: {safety: {minSendingDelaySeconds: 90, dailyLimit: 200}}}]); + }); + + it('email: --set from stdin, and a field Reply\'s safety section does not have is a usage error before any call', async()=>{ + vi.spyOn(fs, 'readFileSync').mockReturnValueOnce('{"dailyLimit":300}'); + answer(json(mailbox({...SAFETY, dailyLimit: 300}))); + await run(g=>handle_account_limits('12', {channel: 'email', set: '-'}, ctx(), g)); + expect(sent()[0].body).toEqual({safety: {dailyLimit: 300}}); + mock_fetch.mockReset(); + expect(await fails(()=>handle_account_limits('12', {channel: 'email', set: '{"signature":"x"}'}, ctx(), {}))) + .toMatchObject({code: 'usage.limits', exit_code: 2}); + expect(await fails(()=>handle_account_limits('12', {channel: 'email', set: '{}'}, ctx(), {}))).toMatchObject({code: 'usage.limits'}); + expect(await fails(()=>handle_account_limits('12', {channel: 'email', daily: '-1'}, ctx(), {}))).toMatchObject({code: 'usage.range'}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('linkedin: --set is Reply\'s limits update, then the account is read for the limits as they are', async()=>{ + const after = {...LIMITS, fixedMax: {dailySendMessageCount: 40}}; + answer(json(null, 204), json(linkedin({limits: after}))); + const {result} = await run(g=>handle_account_limits('34', {channel: 'linkedin', set: '{"fixedMax":{"dailySendMessageCount":40}}'}, ctx(), g)); + expect(result).toStrictEqual({channel: 'linkedin', id: 34, limits: after}); + expect(sent()).toEqual([ + {method: 'PUT', url: 'https://api/v3/linkedin-accounts/34/limits', body: {fixedMax: {dailySendMessageCount: 40}}}, + {method: 'GET', url: 'https://api/v3/linkedin-accounts/34', body: undefined}, + ]); + }); + + it('linkedin: a saved change whose read-back fails prints null and says so on stderr, not a failure', async()=>{ + answer(json(null, 204), json({code: 'linkedInAccount.notFound', status: 404}, 404)); + const {result, err} = await run(g=>handle_account_limits('34', {channel: 'linkedin', set: '{"limitsMode":"ranged"}'}, ctx(), g)); + expect(result).toStrictEqual({channel: 'linkedin', id: 34, limits: null}); + expect(err).toContain('The limits were saved, but reading them back failed (linkedin.account_not_found)'); + }); + + it('linkedin: --daily is a usage error; a refusal with no CLI code of its own is reply.refused, Reply\'s code in reply_code', async()=>{ + expect(await fails(()=>handle_account_limits('34', {channel: 'linkedin', daily: '10'}, ctx(), {}))).toMatchObject({code: 'usage.limits'}); + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json({code: 'linkedInAccount.invalidInput', status: 400, detail: 'actionDelayMaxSeconds must be at least 60 higher'}, 400)); + expect(await fails(()=>handle_account_limits('34', {channel: 'linkedin', set: '{"actionDelayMinSeconds":90}'}, ctx(), {}))) + .toMatchObject({code: 'reply.refused', reply_code: 'linkedInAccount.invalidInput', detail: 'actionDelayMaxSeconds must be at least 60 higher', status: 400, exit_code: 1}); + }); +}); + +describe('account pause and resume', ()=>{ + it('read the state first and toggle only when it is not the one asked for', async()=>{ + answer(json(linkedin({status: 'enabled'})), json({status: 'disabled'})); + expect((await run(g=>handle_account_pause('34', {channel: 'linkedin'}, ctx(), g))).result) + .toStrictEqual({channel: 'linkedin', id: 34, status: 'inactive', reply_status: 'disabled', changed: true}); + expect(sent().map(r=>[r.method, r.url])).toEqual([['GET', 'https://api/v3/linkedin-accounts/34'], + ['POST', 'https://api/v3/linkedin-accounts/34/toggle-status']]); + + mock_fetch.mockReset(); + answer(json(linkedin({status: 'disabled'}))); + expect((await run(g=>handle_account_pause('34', {channel: 'linkedin'}, ctx(), g))).result) + .toStrictEqual({channel: 'linkedin', id: 34, status: 'inactive', reply_status: 'disabled', changed: false}); + expect(sent()).toHaveLength(1); + + mock_fetch.mockReset(); + answer(json(linkedin({status: 'disabled'})), json({status: 'enabled'})); + expect((await run(g=>handle_account_resume('34', {channel: 'linkedin'}, ctx(), g))).result) + .toStrictEqual({channel: 'linkedin', id: 34, status: 'active', reply_status: 'enabled', changed: true}); + + // At its daily limit an account is on: resuming it changes nothing. + mock_fetch.mockReset(); + answer(json(linkedin({status: 'dailyLimitReached'}))); + expect((await run(g=>handle_account_resume('34', {channel: 'linkedin'}, ctx(), g))).result) + .toMatchObject({status: 'active', reply_status: 'dailyLimitReached', changed: false}); + expect(sent()).toHaveLength(1); + }); + + // Reply's toggle turns enabled off and any other state on, so each verb may call it from one state only. + const TOGGLE = ['POST', 'https://api/v3/linkedin-accounts/34/toggle-status']; + const toggles = ()=>sent().filter(r=>r.method === TOGGLE[0] && r.url === TOGGLE[1]).length; + + it('pause, from each state Reply gives: one toggle from enabled, and none from any other', async()=>{ + const cases: [string, Record][] = [ + ['enabled', {status: 'inactive', reply_status: 'disabled', changed: true}], + ['disabled', {status: 'inactive', reply_status: 'disabled', changed: false}], + ['cookieInvalid', {code: 'linkedin.invalid_cookie'}], + ['dailyLimitReached', {code: 'account.pause_unavailable', details: {reply_status: 'dailyLimitReached'}}], + ]; + for (const [status, expected] of cases) + { + mock_fetch.mockReset(); + answer(json(linkedin({status})), json({status: 'disabled'})); + const outcome = await run(g=>handle_account_pause('34', {channel: 'linkedin'}, ctx(), g)).then(r=>r.result, (e: unknown)=>e); + expect(outcome, status).toMatchObject(expected); + expect(toggles(), status).toBe(status === 'enabled' ? 1 : 0); + } + }); + + it('pause at the daily limit is refused before any write, never toggled on and then reported as changed by someone else', async()=>{ + answer(json(linkedin({status: 'dailyLimitReached'})), json({status: 'enabled'})); + const e = await fails(()=>handle_account_pause('34', {channel: 'linkedin'}, ctx(), {})); + expect(e).toMatchObject({code: 'account.pause_unavailable', status: 200, exit_code: 1, details: {reply_status: 'dailyLimitReached'}, + title: 'Reply cannot pause the LinkedIn account from its state \'dailyLimitReached\', so nothing was changed.'}); + expect(sent().map(r=>[r.method, r.url])).toEqual([['GET', 'https://api/v3/linkedin-accounts/34']]); + }); + + it('resume, from each state Reply gives: one toggle from disabled, and none from any other', async()=>{ + const cases: [string, Record][] = [ + ['enabled', {status: 'active', reply_status: 'enabled', changed: false}], + ['disabled', {status: 'active', reply_status: 'enabled', changed: true}], + ['cookieInvalid', {code: 'linkedin.invalid_cookie'}], + ['dailyLimitReached', {status: 'active', reply_status: 'dailyLimitReached', changed: false}], + ]; + for (const [status, expected] of cases) + { + mock_fetch.mockReset(); + answer(json(linkedin({status})), json({status: 'enabled'})); + const outcome = await run(g=>handle_account_resume('34', {channel: 'linkedin'}, ctx(), g)).then(r=>r.result, (e: unknown)=>e); + expect(outcome, status).toMatchObject(expected); + expect(toggles(), status).toBe(status === 'disabled' ? 1 : 0); + } + }); + + it('a state the CLI does not know, or none it can read, is status_unknown for both verbs, before any write', async()=>{ + for (const status of ['suspended', 'Enabled', 'paused', '', 7, null]) + { + for (const verb of [handle_account_pause, handle_account_resume]) + { + mock_fetch.mockReset(); + answer(json(linkedin({status})), json({status: 'enabled'})); + expect(await fails(()=>verb('34', {channel: 'linkedin'}, ctx(), {})), String(status)) + .toMatchObject({code: 'account.status_unknown', details: {reply_status: typeof status === 'string' ? status : null}}); + expect(toggles(), String(status)).toBe(0); + } + } + }); + + it('refuse a disconnected account, a state the CLI does not know, and a flip that went the other way', async()=>{ + answer(json(linkedin({status: 'cookieInvalid'}))); + expect(await fails(()=>handle_account_resume('34', {channel: 'linkedin'}, ctx(), {}))) + .toMatchObject({code: 'linkedin.invalid_cookie', exit_code: 1}); + mock_fetch.mockReset(); + answer(json(linkedin({status: 'suspended'}))); + expect(await fails(()=>handle_account_pause('34', {channel: 'linkedin'}, ctx(), {}))).toMatchObject({code: 'account.status_unknown'}); + expect(sent()).toHaveLength(1); + mock_fetch.mockReset(); + answer(json(linkedin({status: 'enabled'})), json({status: 'enabled'})); + expect(await fails(()=>handle_account_pause('34', {channel: 'linkedin'}, ctx(), {}))).toMatchObject({code: 'account.status_changed'}); + }); + + it('email has no pause or resume: a usage error before any call; Reply\'s refusal of the toggle comes under the CLI\'s code', async()=>{ + expect(await fails(()=>handle_account_pause('12', {channel: 'email'}, ctx(), {}))).toMatchObject({code: 'usage.unsupported', exit_code: 2}); + expect(await fails(()=>handle_account_resume('12', {channel: 'email'}, ctx(), {}))) + .toMatchObject({code: 'usage.unsupported', hint: expect.stringContaining('account unblock')}); + expect(await fails(()=>handle_account_pause('12', {}, ctx(), {}))).toMatchObject({code: 'usage.channel'}); + expect(mock_fetch).not.toHaveBeenCalled(); + answer(json(linkedin({status: 'enabled'})), json({code: 'linkedInAccount.cookieInvalid', status: 400}, 400)); + expect(await fails(()=>handle_account_pause('34', {channel: 'linkedin'}, ctx(), {}))) + .toMatchObject({code: 'linkedin.invalid_cookie', reply_code: 'linkedInAccount.cookieInvalid', status: 400}); + }); +}); + +describe('account unblock', ()=>{ + it('clears the provider\'s block on a mailbox', async()=>{ + answer(json(null, 204)); + expect((await run(g=>handle_account_unblock('4294967296', ctx(), g))).result).toStrictEqual({channel: 'email', id: 4294967296, unblocked: true}); + expect(sent()).toEqual([{method: 'POST', url: 'https://api/v3/email-accounts/4294967296/resume-sending', body: undefined}]); + mock_fetch.mockReset(); + answer(json({code: 'emailAccount.notFound', status: 404}, 404)); + expect(await fails(()=>handle_account_unblock('12', ctx(), {}))).toMatchObject({code: 'email_account.not_found', reply_code: 'emailAccount.notFound', exit_code: 1}); + }); +}); + +describe('account delete', ()=>{ + it('needs --yes: without it, a usage error before any call', async()=>{ + expect(await fails(()=>handle_account_delete('12', {channel: 'email'}, ctx(), {}))).toMatchObject({code: 'usage.confirm', exit_code: 2}); + expect(await fails(()=>handle_account_delete('34', {channel: 'linkedin', force: true}, ctx(), {}))).toMatchObject({code: 'usage.confirm'}); + expect(await fails(()=>handle_account_delete('12', {channel: 'email', yes: true, force: true}, ctx(), {}))) + .toMatchObject({code: 'usage.force', exit_code: 2}); + expect(await fails(()=>handle_account_delete('12', {yes: true}, ctx(), {}))).toMatchObject({code: 'usage.channel'}); + expect(mock_fetch).not.toHaveBeenCalled(); + }); + + it('deletes by channel; --force adds Reply\'s force for LinkedIn only', async()=>{ + answer(json(null, 204), json(null, 204), json(null, 204)); + expect((await run(g=>handle_account_delete('12', {channel: 'email', yes: true}, ctx(), g))).result) + .toStrictEqual({channel: 'email', id: 12, deleted: true}); + await run(g=>handle_account_delete('34', {channel: 'linkedin', yes: true}, ctx(), g)); + await run(g=>handle_account_delete('34', {channel: 'linkedin', yes: true, force: true}, ctx(), g)); + expect(sent().map(r=>[r.method, r.url])).toEqual([ + ['DELETE', 'https://api/v3/email-accounts/12'], ['DELETE', 'https://api/v3/linkedin-accounts/34'], + ['DELETE', 'https://api/v3/linkedin-accounts/34?force=true'], + ]); + }); + + it('an account sequences use is Reply\'s refusal, under the CLI\'s code; a failure of Reply\'s is outcome.unknown', async()=>{ + answer(json({code: 'linkedInAccount.accountInUse', status: 409}, 409)); + expect(await fails(()=>handle_account_delete('34', {channel: 'linkedin', yes: true}, ctx(), {}))) + .toMatchObject({code: 'linkedin.account_in_use', reply_code: 'linkedInAccount.accountInUse', exit_code: 1}); + mock_fetch.mockReset(); + answer(json('', 503)); + expect(await fails(()=>handle_account_delete('12', {channel: 'email', yes: true}, ctx(), {}))).toMatchObject({code: 'outcome.unknown', exit_code: 3}); + }); +}); diff --git a/src/__tests__/operations/account-secrets.test.ts b/src/__tests__/operations/account-secrets.test.ts new file mode 100644 index 0000000..9993d97 --- /dev/null +++ b/src/__tests__/operations/account-secrets.test.ts @@ -0,0 +1,157 @@ +import crypto from 'crypto'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest'; +import {mock_fetch, json, ctx, answer, capture} from './helpers'; +import {handle_account_connect, handle_account_reconnect, handle_account_pending} from '../../operations/account-links'; +import {CliError} from '../../utils/errors'; +import type {Op_globals} from '../../operations/options'; + +// The secret rule: a link, the shared page's address and any token in them are printed once, in the stdout +// field `link`, and nowhere else. Every link command runs here with --verbose against a stubbed Reply; the +// whole of stderr, the trace and any error are searched for the token and the link. + +const APP = 'https://app.example.test'; +const missing = ()=>json({title: 'Not Found', status: 404}, 404); + +type Case = { + name: string; + answers: (t: string) => Response[]; + run: (g: Op_globals) => Promise; + printed: number; // how many times the token is on stdout: once in `link`, or never + traced_link: boolean; // whether an answer carried a link, so the trace shows it redacted +}; + +// A header that repeats the link, as a proxy or a debug build might: it must not leak either. +const leaky = (data: unknown, t: string, status = 200)=>json(data, status, {'X-Debug-Link': `${APP}/email-connect/${t}`}); + +const CASES: Case[] = [ + {name: 'connect email, connection link', printed: 1, traced_link: true, + answers: t=>[json({connectionLink: `${APP}/email-connect/${t}`, pendingAccountId: 50, provider: 'gmail', expiresAtUtc: '2026-11-18T12:00:00Z'}, + 201, {Location: 'v3/email-accounts/pending/50'})], + run: g=>handle_account_connect({channel: 'email', provider: 'gmail'}, ctx(), g)}, + {name: 'reconnect email, connection link', printed: 1, traced_link: true, + answers: t=>[leaky({connectionLink: `${APP}/email-connect/${t}`, pendingAccountId: 52, provider: 'office365', + expiresAtUtc: '2026-11-18T12:00:00Z'}, t)], + run: g=>handle_account_reconnect('12', {channel: 'email'}, ctx(), g)}, + ...(['gmail', 'office365', undefined] as const).map((provider): Case=>({ + name: `connect email, shared page, ${provider ?? 'index'}`, printed: 1, traced_link: true, + answers: t=>[provider === undefined ? json([], 404) : missing(), leaky({url: `${APP}/hosted/eac/index/${t}`}, t)], + run: g=>handle_account_connect({channel: 'email', provider, allowSharedPage: true}, ctx(), g), + })), + ...(['gmail', 'office365', undefined] as const).map((provider): Case=>({ + name: `reconnect email, shared page, ${provider ?? 'index'}`, printed: 1, traced_link: true, + answers: t=>[missing(), json({url: `${APP}/hosted/eac/index/${t}`})], + run: g=>handle_account_reconnect('12', {channel: 'email', provider, allowSharedPage: true}, ctx(), g), + })), + {name: 'connect linkedin', printed: 1, traced_link: true, + answers: t=>[json({connectionLink: `${APP}/linkedin-connect/${t}`, pendingAccountId: 51}, 201)], + run: g=>handle_account_connect({channel: 'linkedin', name: 'Dana Example'}, ctx(), g)}, + {name: 'reconnect linkedin, a provider\'s link with the token in its query', printed: 1, traced_link: true, + answers: t=>[json({connectionLink: `https://auth.example.test/wizard?state=${t}&lang=en`})], + run: g=>handle_account_reconnect('34', {channel: 'linkedin'}, ctx(), g)}, + {name: 'pending, a LinkedIn entry with its link', printed: 0, traced_link: true, + answers: t=>[json([]), json([{id: 7, name: 'Dana', connectionLink: `${APP}/linkedin-connect/${t}`, expiresAtUtc: null, isExpired: false}])], + run: g=>handle_account_pending({}, ctx(), g)}, + {name: 'a shared page in a form the CLI cannot read, so an error', printed: 0, traced_link: true, + answers: t=>[missing(), json({url: `${APP}/hosted/elsewhere/${t}`})], + run: g=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), g)}, + // The shared page's answer is a secret whatever its shape: a bare string, or a body with no address in it. + {name: 'connect email, shared page answered as a bare string', printed: 1, traced_link: true, + answers: t=>[missing(), leaky(`${APP}/hosted/eac/index/${t}`, t)], + run: g=>handle_account_connect({channel: 'email', provider: 'office365', allowSharedPage: true}, ctx(), g)}, + {name: 'reconnect email, shared page answered as a bare string, the index', printed: 1, traced_link: true, + answers: t=>[missing(), json(`${APP}/hosted/eac/index/${t}`)], + run: g=>handle_account_reconnect('12', {channel: 'email', allowSharedPage: true}, ctx(), g)}, + {name: 'a shared page answered as a bare token, not an address, so an error', printed: 0, traced_link: true, + answers: t=>[missing(), json(t)], + run: g=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), g)}, + {name: 'a shared page answered as text that is not an address, so an error', printed: 0, traced_link: true, + answers: t=>[missing(), json(`hosted token ${t} for this user`)], + run: g=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), g)}, + {name: 'a shared page answered as an object holding no address, so an error', printed: 0, traced_link: true, + answers: t=>[missing(), json({hostedToken: t})], + run: g=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), g)}, + {name: 'a shared page refused with the address in the refusal, so an error', printed: 0, traced_link: true, + answers: t=>[missing(), json({title: 'Bad Request', detail: `open ${APP}/hosted/eac/index/${t} instead`}, 400)], + run: g=>handle_account_connect({channel: 'email', provider: 'gmail', allowSharedPage: true}, ctx(), g)}, + {name: 'an answer without a usable link, so outcome unknown', printed: 0, traced_link: true, + answers: t=>[json({connectionLink: 42, pendingAccountId: 51, debug: {url: `${APP}/linkedin-connect/${t}`}}, 201)], + run: g=>handle_account_connect({channel: 'linkedin', name: 'Dana'}, ctx(), g)}, +]; + +const occurrences = (text: string, s: string): number=>text.split(s).length - 1; + +beforeEach(()=>{ mock_fetch.mockReset(); }); + +describe('the secret rule', ()=>{ + for (const c of CASES) + { + it(`${c.name}: the token is on stdout ${c.printed === 1 ? 'once, in link' : 'nowhere'}, and in no trace, error or stderr`, async()=>{ + const t = crypto.randomBytes(24).toString('base64url'); + answer(...c.answers(t)); + let error: unknown; + const {out, err} = await capture(()=>c.run({json: true, verbose: true}).catch((e: unknown)=>{ error = e; })); + const said = [err, ...(error instanceof CliError ? [error.message, JSON.stringify(error.to_json()), error.hint ?? ''] : [])].join('\n'); + + expect(err, 'the trace ran').toMatch(/^> (GET|POST) https:\/\/api\//m); + const link = c.printed === 1 ? JSON.parse(out).link as string : undefined; + for (const form of [t, encodeURIComponent(t), ...(link === undefined ? [] : [link])]) + { + expect(occurrences(said, form), `${form} in:\n${said}`).toBe(0); + } + expect(said.includes(''), said).toBe(c.traced_link); + expect(occurrences(out, t), out).toBe(c.printed); + if (link !== undefined) + { + expect(link).toContain(t); + } + }); + } +}); + +// The same through the program as `reply` runs it: --verbose reaches the account commands, and the error +// line is written with the link nowhere in it. +describe('the secret rule, through the program', ()=>{ + const argv = process.argv; + let dir: string; + beforeEach(()=>{ + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-secrets-')); + process.env.REPLY_CONFIG_DIR = dir; + }); + afterEach(()=>{ + vi.restoreAllMocks(); + process.argv = argv; + delete process.env.REPLY_CONFIG_DIR; + fs.rmSync(dir, {recursive: true, force: true}); + }); + + it('a shared page the CLI cannot read: exit 1, a trace on stderr, the token nowhere', async()=>{ + const t = crypto.randomBytes(24).toString('base64url'); + answer(missing(), json({url: `${APP}/hosted/elsewhere/${t}`})); + let exited!: (code: number) => void; + const exit = new Promise(resolve=>{ exited = resolve; }); + let first: number | undefined; + vi.spyOn(process, 'exit').mockImplementation(((code?: number)=>{ + if (first === undefined) + { + first = code ?? 0; + exited(first); + } + }) as typeof process.exit); + process.argv = ['node', 'reply', '--json', '-k', 'key-1', '--verbose', 'account', 'connect', '--channel', 'email', '--provider', 'gmail', + '--allow-shared-page']; + vi.resetModules(); + let code = -1; + const {out, err} = await capture(async()=>{ + await import('../../index'); + code = await exit; + }); + expect(code).toBe(1); + expect(err).toContain('> GET https://api.reply.io/v1/SharedPageUrl'); + expect(err).toContain(''); + expect(err).toContain('"code":"reply.unavailable"'); + expect(occurrences(err + out, t), err).toBe(0); + }); +}); diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index ef8142f..9a23772 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -27,7 +27,8 @@ describe('operations/commands', ()=>{ expect(contact_command.commands.map(c=>c.name())).toEqual(['find', 'get', 'update', 'delete', 'opt-out', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']); expect(inbox_command.commands.map(c=>c.name())).toEqual(['list', 'changes', 'get', 'reply', 'categories', 'categorize', 'mark-read', 'mark-unread']); - expect(account_command.commands.map(c=>c.name())).toEqual(['list']); + expect(account_command.commands.map(c=>c.name())).toEqual( + ['list', 'connect', 'reconnect', 'pending', 'limits', 'pause', 'resume', 'unblock', 'delete']); expect(schedule_command.commands.map(c=>c.name())).toEqual(['list']); expect(direct_send_command.commands.map(c=>c.name())).toEqual(['get', 'cancel']); }); @@ -113,6 +114,36 @@ describe('operations/commands', ()=>{ expect(text, text).not.toContain('outcome.unknown'); }); + it('the account commands take the flags of their channel, and the link commands state the secret rule', ()=>{ + const expected: [string, string[]][] = [ + ['connect', ['--channel', '--provider', '--name', '--allow-shared-page']], + ['reconnect', ['--channel', '--provider', '--allow-shared-page']], + ['pending', ['--channel']], + ['limits', ['--channel', '--daily', '--set']], + ['pause', ['--channel']], + ['resume', ['--channel']], + ['unblock', []], + ['delete', ['--channel', '--yes', '--force']], + ]; + for (const [name, names] of expected) + { + expect(flags(sub(account_command, name)), name).toEqual(names); + } + for (const name of ['connect', 'reconnect']) + { + const flat = help_of(sub(account_command, name)).replace(/\s+/g, ' '); + expect(flat, name).toContain('it is printed once, in "link", and never on stderr, in a --verbose trace (where it reads )'); + expect(flat, name).toContain('That address does not expire and lets its holder manage all of this user\'s mailboxes, deletion included'); + expect(flat, name).toContain('email_link.not_available'); + expect(flat, name).toContain('outcome.unknown'); + } + const pending = help_of(sub(account_command, 'pending')).replace(/\s+/g, ' '); + expect(pending).toContain('The links themselves are never printed'); + expect(pending).not.toContain('outcome.unknown'); + expect(help_of(sub(account_command, 'delete')).replace(/\s+/g, ' ')).toContain('Without --yes it is a usage error (usage.confirm, exit 2)'); + expect(help_of(sub(account_command, 'pause')).replace(/\s+/g, ' ')).toContain('Reply has no way to pause a mailbox through its API'); + }); + // The sends and contact update find or import the person as the add commands do. const SENDS_AND_UPDATE = ['update', 'send-email', 'linkedin-connect', 'linkedin-message', 'linkedin-inmail', 'linkedin-voice']; const CONTACT_FLAGS = ['--contact-id', '--email', '--first-name', '--last-name', '--company', '--title', '--contact']; diff --git a/src/index.ts b/src/index.ts index 37e8c45..6ef38f2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -39,7 +39,7 @@ const build_program = (): Command=>{ .option('--user-email ', 'Act as this user email — organization API keys only (needs a team id)') .option('--json', 'Output compact JSON to stdout') .option('--pretty', 'Output indented JSON to stdout') - .option('--verbose', 'Print the full request/response to stderr, credentials redacted (api)') + .option('--verbose', 'Print the full request/response to stderr, credentials and links redacted (api, account)') .option('-q, --quiet', 'Suppress progress messages on stderr (warnings and errors still shown)') .showHelpAfterError(); diff --git a/src/operations/account-call.ts b/src/operations/account-call.ts new file mode 100644 index 0000000..b01fe5a --- /dev/null +++ b/src/operations/account-call.ts @@ -0,0 +1,232 @@ +import {REDACTED} from '../utils/output'; +import {Operation_error} from '../utils/errors'; +import {call_reply, detail_of, is_object, refusal, reply_code_of, type Answer, type Op_session} from './call'; +import type {Call_kind} from '../utils/client'; +import type {Op_globals} from './options'; + +// The calls of the account commands, and what they write to stderr under --verbose. A connection link, +// the shared page's address and any token in them are handed over once, in the stdout field `link`: in a +// trace each is replaced by LINK_REDACTED, wherever it appears. + +const LINK_REDACTED = ''; + +// The fields Reply hands a link in: v3's connectionLink and the v1 shared page's url. +const LINK_FIELDS = ['connectionlink', 'url']; + +// Too short to be a token, and short enough to be an ordinary word of a URL. +const SHORTEST_TOKEN = 8; +const SHORTEST_INNER_TOKEN = 16; + +const URL_IN_TEXT = /https?:\/\/[^\s"'<>]+/gi; + +const safe_decode = (part: string): string=>{ + try { + return decodeURIComponent(part); + } catch { + return part; + } +}; + +// A link, and every token it carries: its last path segment, every query value, and any inner path +// segment that looks generated (long, with a digit in it), each as written and decoded. +const add_link = (link: string, found: Set): void=>{ + found.add(link); + let url: URL; + try { + url = new URL(link); + } catch { + return; + } + const segments = url.pathname.split('/').filter(Boolean); + const parts = [ + ...segments.slice(0, -1).filter(p=>p.length >= SHORTEST_INNER_TOKEN && /[0-9]/.test(p)), + ...segments.slice(-1), + ...[...url.searchParams.values()], + ]; + for (const part of parts) + { + for (const form of [part, safe_decode(part), encodeURIComponent(safe_decode(part))]) + { + if (form.length >= SHORTEST_TOKEN) + { + found.add(form); + } + } + } +}; + +const is_address = (text: string): boolean=>/^https?:\/\//i.test(text.trim()); + +// Every link in an answer's body, with its tokens: in a link field at any depth, or the body itself when +// it is nothing but an address. +const links_in = (data: unknown, found: Set = new Set()): Set=>{ + if (typeof data === 'string' && is_address(data)) + { + add_link(data.trim(), found); + } + else if (Array.isArray(data)) + { + data.forEach(d=>links_in(d, found)); + } + else if (is_object(data)) + { + for (const [k, v] of Object.entries(data)) + { + if (typeof v === 'string' && LINK_FIELDS.includes(k.toLowerCase())) + { + add_link(v, found); + } + else + { + links_in(v, found); + } + } + } + return found; +}; + +// Every string of a body at any depth, the body itself when it is one. +const strings_of = (data: unknown, found: string[] = []): string[]=>{ + if (typeof data === 'string') + { + found.push(data); + } + else if (Array.isArray(data)) + { + data.forEach(d=>strings_of(d, found)); + } + else if (is_object(data)) + { + Object.values(data).forEach(v=>strings_of(v, found)); + } + return found; +}; + +// The secrets of a body that is secret whatever its shape: every address inside any of its strings, +// with its tokens, and every string that is wholly one value, such as a bare token. +const body_secrets = (data: unknown): Set=>{ + const found = links_in(data); + for (const text of strings_of(data)) + { + for (const url of text.match(URL_IN_TEXT) ?? []) + { + add_link(url, found); + } + if (!/\s/.test(text.trim()) && text.trim().length >= SHORTEST_TOKEN) + { + add_link(text.trim(), found); + } + } + return found; +}; + +const redact_links = (text: string, secrets: Iterable): string=> + [...secrets].sort((a, b)=>b.length - a.length).reduce((t, s)=>t.split(s).join(LINK_REDACTED), text); + +// curl -v style, as `reply api --verbose` writes it, with the answer's body after its headers. A secret +// body is never shown, only that there was one. +const trace_lines = (a: Answer, secret_body: boolean): string[]=>{ + const lines: string[] = []; + if (a.request) + { + lines.push(`> ${a.request.method} ${a.request.url}`); + for (const [k, v] of Object.entries(a.request.headers)) + { + lines.push(`> ${k}: ${v}`); + } + if (a.request.body) + { + lines.push('>', `> ${a.request.body}`); + } + } + lines.push(`< ${a.status}`); + for (const [k, v] of Object.entries(a.headers)) + { + lines.push(`< ${k}: ${/cookie/i.test(k) ? REDACTED : v}`); + } + if (a.data !== null && a.data !== '') + { + const shown = secret_body ? LINK_REDACTED : typeof a.data === 'string' ? a.data : JSON.stringify(a.data); + lines.push('<', `< ${shown}`); + } + return lines; +}; + +const secrets_of = (a: Answer, secret_body: boolean): Set=>(secret_body ? body_secrets(a.data) : links_in(a.data)); + +// One call of an account command. The links in its answer never reach the trace. With `secret_body` +// (the shared page, whose answer is the address in whatever shape Reply gives it) the trace shows none +// of the body, and nothing of it appears anywhere else in the trace either. +const account_call = async( + s: Op_session, g: Op_globals, method: string, path: string, kind: Call_kind, body?: unknown, opts: {secret_body?: boolean} = {}, +): Promise=>{ + const a = await call_reply(s, method, path, kind, body); + if (g.verbose) + { + const secret_body = opts.secret_body === true; + console.error(redact_links(trace_lines(a, secret_body).join('\n'), secrets_of(a, secret_body))); + } + return a; +}; + +// The same answer with every secret of its body replaced, for an error built from a secret body. +const without_secrets = (a: Answer): Answer=>{ + const secrets = body_secrets(a.data); + const clean = (v: unknown): unknown=>{ + if (typeof v === 'string') + { + return redact_links(v, secrets); + } + if (Array.isArray(v)) + { + return v.map(clean); + } + return is_object(v) ? Object.fromEntries(Object.entries(v).map(([k, x])=>[k, clean(x)])) : v; + }; + return {...a, data: clean(a.data)}; +}; + +// Reply's refusals of the account routes, each at the status Reply answers it with, under the CLI's +// code. Reply's own code always travels in reply_code; any other answer reads as every operation reads it. +const ACCOUNT_REFUSALS: Record = { + 'emailAccount.notFound': { + status: 404, code: 'email_account.not_found', title: 'Reply has no email account by that id that this user can act on.', + }, + 'emailAccount.limitReached': { + status: 409, code: 'email_account.limit_reached', title: 'The plan\'s email account limit is reached, so no link was made.', + }, + 'emailAccount.noFreeMailboxSlots': { + status: 409, code: 'email_account.no_free_mailbox_slots', title: 'One more email account would need a paid seat, so no link was made.', + }, + 'emailAccount.reconnectNotSupported': { + status: 400, code: 'email_account.reconnect_not_supported', + title: 'Only a Gmail or Office 365 single-click mailbox can be reconnected by link, so no link was made.', + }, + 'linkedInAccount.notFound': { + status: 404, code: 'linkedin.account_not_found', title: 'Reply has no LinkedIn account by that id that this user can act on.', + }, + 'linkedInAccount.limitReached': { + status: 409, code: 'linkedin.account_limit_reached', title: 'The plan has no room for another LinkedIn account, so no link was made.', + }, + 'linkedInAccount.accountInUse': { + status: 409, code: 'linkedin.account_in_use', title: 'Sequences use the LinkedIn account, so it was not deleted; --force deletes it anyway.', + }, + 'linkedInAccount.cookieInvalid': { + status: 400, code: 'linkedin.invalid_cookie', title: 'The LinkedIn account\'s session is no longer valid; reconnect the account.', + }, +}; + +const account_refusal = (a: Answer, kind: Call_kind): Operation_error=>{ + const reply_code = reply_code_of(a); + const known = reply_code === undefined ? undefined : ACCOUNT_REFUSALS[reply_code]; + if (known === undefined || known.status !== a.status) + { + return refusal(a, kind); + } + return new Operation_error(known.code, known.title, {status: a.status, reply_code, detail: detail_of(a)}); +}; + +// A route this Reply does not have answers 404 with no code of Reply's; one it has answers its own. +const route_missing = (a: Answer): boolean=>a.status === 404 && reply_code_of(a) === undefined; + +export {LINK_REDACTED, ACCOUNT_REFUSALS, account_call, account_refusal, route_missing, links_in, redact_links, add_link, without_secrets}; diff --git a/src/operations/account-links.ts b/src/operations/account-links.ts new file mode 100644 index 0000000..7e03276 --- /dev/null +++ b/src/operations/account-links.ts @@ -0,0 +1,271 @@ +import {Operation_error, UsageError} from '../utils/errors'; +import {is_object, open_session, refusal, unreadable, type Answer, type Op_session} from './call'; +import {account_call, account_refusal, route_missing, without_secrets} from './account-call'; +import {HOSTED_PROVIDERS, SHARED_PAGE_WARNING, read_shared_page, shared_page_link, type Hosted_provider} from './shared-page'; +import {ACCOUNT_CHANNELS, require_channel, type Account_channel} from './accounts'; +import {parse_choice, parse_id, LARGEST_SAFE_ID, type Op_globals} from './options'; +import {print_result} from './result'; +import type {Cli_context} from '../context'; + +// connect, reconnect and pending. A link is a credential for whoever opens it: it is printed once, in the +// stdout field `link`, and nowhere else (see account-call.ts for the trace). + +type Link_kind = 'connection_link' | 'shared_page'; +type Link_result = { + channel: Account_channel; id?: number; link: string; expires_at: string | null; pending_id: number | null; + kind: 'connect' | 'reconnect'; link_kind: Link_kind; warning?: string; +}; +type Link_opts = {channel?: string; provider?: string; name?: string; allowSharedPage?: boolean}; + +const EMAIL_NAME_MAX = 100; // Reply's limit on a connection link's label + +const email_link_not_available = (): Operation_error=>new Operation_error('email_link.not_available', + 'This Reply does not issue one-mailbox email connection links yet, so no link was made.', { + status: 404, + hint: 'With --allow-shared-page the account\'s hosted mailbox page is printed instead; ' + + `${SHARED_PAGE_WARNING}.`, + }); + +const text_or_null = (v: unknown): string | null=>(typeof v === 'string' && v.trim() !== '' ? v : null); +const positive_or_null = (v: unknown): number | null=>(typeof v === 'number' && Number.isSafeInteger(v) && v > 0 ? v : null); + +// The link of a v3 answer, or an unreadable answer: the write was made, so a link Reply did not give back +// means one may exist that nobody holds. +const link_of = (a: Answer): {link: string; body: Record}=>{ + if (!is_object(a.data) || typeof a.data.connectionLink !== 'string' || a.data.connectionLink === '') + { + throw unreadable(a, 'write'); + } + return {link: a.data.connectionLink, body: a.data}; +}; + +const connection_link = (channel: Account_channel, kind: 'connect' | 'reconnect', a: Answer, id?: number): Link_result=>{ + const {link, body} = link_of(a); + return { + channel, ...(id === undefined ? {} : {id}), link, + expires_at: text_or_null(body.expiresAtUtc), pending_id: positive_or_null(body.pendingAccountId), + kind, link_kind: 'connection_link', + }; +}; + +// The account user's hosted mailbox page, from Reply's v1 route: the provider's connect when one is named, +// else the index. Reply's v1 gives no code, so the plan's refusal is named here. +const shared_page = async( + s: Op_session, g: Op_globals, kind: 'connect' | 'reconnect', provider: Hosted_provider | undefined, id?: number, +): Promise=>{ + // Its answer is the address, in whatever shape Reply gives it, so the whole body is a secret. + const a = await account_call(s, g, 'GET', '/v1/SharedPageUrl', 'read', undefined, {secret_body: true}); + if (a.status === 403 && /shared page is not enabled/i.test(JSON.stringify(a.data ?? ''))) + { + throw new Operation_error('shared_page.not_enabled', 'The account\'s plan does not include hosted pages, so there is no shared page.', { + status: 403, + }); + } + if (a.status !== 200) + { + throw refusal(without_secrets(a), 'read'); + } + // {"url": …} as Reply's v1 answers it; a bare string is read as the address too. + const url = typeof a.data === 'string' ? a.data.trim() : is_object(a.data) ? a.data.url ?? a.data.Url : undefined; + const page = typeof url === 'string' ? read_shared_page(url) : null; + if (page === null) + { + throw unreadable(a, 'read'); + } + return { + channel: 'email', ...(id === undefined ? {} : {id}), link: shared_page_link(page, provider, kind), + expires_at: null, pending_id: null, kind, link_kind: 'shared_page', warning: SHARED_PAGE_WARNING, + }; +}; + +const parse_provider = (raw: string | undefined): Hosted_provider | undefined=>parse_choice(raw, '--provider', HOSTED_PROVIDERS); + +const email_only = (opts: Link_opts): void=>{ + for (const [value, flag] of [[opts.provider, '--provider'], [opts.allowSharedPage, '--allow-shared-page']] as const) + { + if (value !== undefined && value !== false) + { + throw new UsageError(`${flag} applies to --channel email only.`, {code: 'usage.channel'}); + } + } +}; + +const connect_linkedin = async(s: Op_session, g: Op_globals, name: string): Promise=>{ + // connection-link, not connect: it makes a pending entry, so the attempt can be listed and revoked. + const a = await account_call(s, g, 'POST', '/v3/linkedin-accounts/connection-link', 'write', {name}); + if (a.status !== 201 && a.status !== 200) + { + throw account_refusal(a, 'write'); + } + return connection_link('linkedin', 'connect', a); +}; + +const connect_email = async( + s: Op_session, g: Op_globals, provider: Hosted_provider | undefined, name: string | undefined, allow_shared_page: boolean, +): Promise=>{ + if (provider === undefined) + { + // Reply's one-mailbox link is made for one provider. The shared page's index needs none, and is + // given only by a Reply without those links: a read of their list says which Reply this is. + const probe = await account_call(s, g, 'GET', '/v3/email-accounts/pending', 'read'); + if (!route_missing(probe)) + { + if (probe.status === 401 || probe.status === 429 || probe.status >= 500) + { + throw refusal(probe, 'read'); + } + throw new Operation_error('email_link.provider_required', + 'This Reply issues one-mailbox connection links, and each is made for one provider, so none was made.', { + status: probe.status, hint: 'Name the mailbox\'s provider: --provider gmail or --provider office365.', + }); + } + return shared_page(s, g, 'connect', undefined); + } + const a = await account_call(s, g, 'POST', '/v3/email-accounts/connection-link', 'write', {provider, ...(name === undefined ? {} : {name})}); + if (a.status === 201 || a.status === 200) + { + return connection_link('email', 'connect', a); + } + if (!route_missing(a)) + { + throw account_refusal(a, 'write'); + } + if (!allow_shared_page) + { + throw email_link_not_available(); + } + return shared_page(s, g, 'connect', provider); +}; + +const handle_account_connect = async(opts: Link_opts, ctx: Cli_context, g: Op_globals): Promise=>{ + const channel = require_channel(opts.channel); + const name = opts.name?.trim() === '' ? undefined : opts.name?.trim(); + if (channel === 'linkedin') + { + email_only(opts); + if (name === undefined) + { + throw new UsageError('--name is required for a LinkedIn connection link: Reply lists the pending account under it.', { + code: 'usage.name', + }); + } + const s = await open_session(ctx, g); + print_result(await connect_linkedin(s, g, name), g); + return; + } + const provider = parse_provider(opts.provider); + if (name !== undefined && name.length > EMAIL_NAME_MAX) + { + throw new UsageError(`--name must be at most ${EMAIL_NAME_MAX} characters.`, {code: 'usage.name'}); + } + if (provider === undefined && opts.allowSharedPage !== true) + { + throw new UsageError('--provider is required for an email connection link: gmail or office365.', { + code: 'usage.provider', + hint: 'Only with --allow-shared-page, and only on a Reply without one-mailbox links, does the CLI print the hosted ' + + 'mailbox page without a provider.', + }); + } + const s = await open_session(ctx, g); + print_result(await connect_email(s, g, provider, name, opts.allowSharedPage === true), g); +}; + +const handle_account_reconnect = async(id_arg: string, opts: Link_opts, ctx: Cli_context, g: Op_globals): Promise=>{ + const channel = require_channel(opts.channel); + if (opts.name !== undefined) + { + throw new UsageError('--name applies to account connect only.', {code: 'usage.name'}); + } + if (channel === 'linkedin') + { + email_only(opts); + const id = parse_id(id_arg, 'LinkedIn account id'); + const s = await open_session(ctx, g); + const a = await account_call(s, g, 'POST', `/v3/linkedin-accounts/${id}/reconnect`, 'write'); + if (a.status !== 200) + { + throw account_refusal(a, 'write'); + } + print_result(connection_link('linkedin', 'reconnect', a, id), g); + return; + } + const id = parse_id(id_arg, 'Email account id', LARGEST_SAFE_ID); + const provider = parse_provider(opts.provider); + const s = await open_session(ctx, g); + // Reply takes the provider from the mailbox itself; --provider picks only the shared page's address. + const a = await account_call(s, g, 'POST', `/v3/email-accounts/${id}/reconnect`, 'write'); + if (a.status === 200 || a.status === 201) + { + print_result(connection_link('email', 'reconnect', a, id), g); + return; + } + if (!route_missing(a)) + { + throw account_refusal(a, 'write'); + } + if (opts.allowSharedPage !== true) + { + throw email_link_not_available(); + } + print_result(await shared_page(s, g, 'reconnect', provider, id), g); +}; + +type Pending_item = { + channel: Account_channel; id: number; name: string | null; kind: 'connect' | 'reconnect' | null; account_id: number | null; + expires_at: string | null; expired: boolean | null; +}; + +const pending_items = (a: Answer, channel: Account_channel): Pending_item[]=>{ + if (!Array.isArray(a.data)) + { + throw unreadable(a, 'read'); + } + return a.data.map(entry=>{ + if (!is_object(entry) || positive_or_null(entry.id) === null) + { + throw new Operation_error('reply.unavailable', 'Reply listed a pending account without a usable id.', {status: a.status}); + } + // A pending LinkedIn account is always a connect, and its link is not kept: it is a credential. + const kind = channel === 'linkedin' ? 'connect' : (entry.kind === 'connect' || entry.kind === 'reconnect' ? entry.kind : null); + return { + channel, id: entry.id as number, name: text_or_null(entry.name), kind, + account_id: channel === 'email' ? positive_or_null(entry.emailAccountId) : null, + expires_at: text_or_null(entry.expiresAtUtc), expired: typeof entry.isExpired === 'boolean' ? entry.isExpired : null, + }; + }); +}; + +const handle_account_pending = async(opts: {channel?: string}, ctx: Cli_context, g: Op_globals): Promise=>{ + const only = parse_choice(opts.channel, '--channel', ACCOUNT_CHANNELS); + const s = await open_session(ctx, g); + const items: Pending_item[] = []; + const unsupported: Account_channel[] = []; + if (only !== 'linkedin') + { + const a = await account_call(s, g, 'GET', '/v3/email-accounts/pending', 'read'); + if (route_missing(a)) + { + unsupported.push('email'); + } + else if (a.status === 200) + { + items.push(...pending_items(a, 'email')); + } + else + { + throw account_refusal(a, 'read'); + } + } + if (only !== 'email') + { + const a = await account_call(s, g, 'GET', '/v3/linkedin-accounts/pending', 'read'); + if (a.status !== 200) + { + throw account_refusal(a, 'read'); + } + items.push(...pending_items(a, 'linkedin')); + } + print_result({items, supported: unsupported.length === 0, unsupported_channels: unsupported}, g); +}; + +export {handle_account_connect, handle_account_reconnect, handle_account_pending}; diff --git a/src/operations/account-manage.ts b/src/operations/account-manage.ts new file mode 100644 index 0000000..f42151c --- /dev/null +++ b/src/operations/account-manage.ts @@ -0,0 +1,225 @@ +import {Operation_error, UsageError} from '../utils/errors'; +import {warn} from '../utils/output'; +import {read_json_arg} from '../utils/json-arg'; +import {expect_object, is_object, open_session, type Op_session} from './call'; +import {account_call, account_refusal} from './account-call'; +import {LINKEDIN_STATUSES, require_channel, type Account_channel, type Account_status} from './accounts'; +import {parse_id, parse_int_in, LARGEST_SAFE_ID, type Op_globals} from './options'; +import {print_result} from './result'; +import type {Cli_context} from '../context'; + +// limits, pause, resume, unblock and delete: an account's settings and state, by channel. + +const email_id = (raw: string): number=>parse_id(raw, 'Email account id', LARGEST_SAFE_ID); +const linkedin_id = (raw: string): number=>parse_id(raw, 'LinkedIn account id'); + +// The fields of each channel's limits a caller may set, in Reply's names: an email account's safety +// section, and a LinkedIn account's limits update. +const EMAIL_LIMIT_FIELDS = [ + 'dailyLimit', 'isEmailsThrottlingEnabled', 'emailsPerInterval', 'emailsThrottlingSecondsInterval', 'isSendingDelayEnabled', + 'maxSendingDelaySeconds', 'minSendingDelaySeconds', +]; +const LINKEDIN_LIMIT_FIELDS = ['limitsMode', 'rangeMin', 'rangeMax', 'fixedMax', 'actionDelayMinSeconds', 'actionDelayMaxSeconds']; +const LARGEST_DAILY = 2147483647; + +const read_limits_arg = (raw: string, fields: string[]): Record=>{ + const value = read_json_arg(raw, {flag: '--set', what: 'limits', code: 'usage.limits'}); + if (!is_object(value) || Object.keys(value).length === 0) + { + throw new UsageError('--set must be a JSON object naming at least one limit.', {code: 'usage.limits', hint: `Fields: ${fields.join(', ')}.`}); + } + const unknown_field = Object.keys(value).find(k=>!fields.includes(k)); + if (unknown_field !== undefined) + { + throw new UsageError(`--set has an unknown field '${unknown_field}'.`, {code: 'usage.limits', hint: `Fields: ${fields.join(', ')}.`}); + } + return value; +}; + +const section_of = (data: Record, field: string): Record | null=> + (is_object(data[field]) ? data[field] as Record : null); + +const email_limits = async(s: Op_session, g: Op_globals, id: number, change: Record | null): Promise=>{ + // PATCH answers the account as it is afterwards, so a change needs no read after it. + const a = change === null + ? await account_call(s, g, 'GET', `/v3/email-accounts/${id}`, 'read') + : await account_call(s, g, 'PATCH', `/v3/email-accounts/${id}`, 'write', {safety: change}); + const kind = change === null ? 'read' : 'write'; + if (a.status !== 200) + { + throw account_refusal(a, kind); + } + return section_of(expect_object(a, kind), 'safety'); +}; + +const read_linkedin_account = async(s: Op_session, g: Op_globals, id: number): Promise>=>{ + const a = await account_call(s, g, 'GET', `/v3/linkedin-accounts/${id}`, 'read'); + if (a.status !== 200) + { + throw account_refusal(a, 'read'); + } + return expect_object(a, 'read'); +}; + +const linkedin_limits = async(s: Op_session, g: Op_globals, id: number, change: Record | null): Promise=>{ + if (change !== null) + { + const a = await account_call(s, g, 'PUT', `/v3/linkedin-accounts/${id}/limits`, 'write', change); + if (a.status !== 204 && a.status !== 200) + { + throw account_refusal(a, 'write'); + } + try { + return section_of(await read_linkedin_account(s, g, id), 'limits'); + } catch (e) { + if (!(e instanceof Operation_error)) + { + throw e; + } + // The limits are saved; only reading them back failed, and failing the command would say they were not. + warn(`The limits were saved, but reading them back failed (${e.code}); run the command without --set to read them.`); + return null; + } + } + return section_of(await read_linkedin_account(s, g, id), 'limits'); +}; + +const handle_account_limits = async( + id_arg: string, opts: {channel?: string; daily?: string; set?: string}, ctx: Cli_context, g: Op_globals, +): Promise=>{ + const channel = require_channel(opts.channel); + if (channel === 'linkedin') + { + const id = linkedin_id(id_arg); + if (opts.daily !== undefined) + { + throw new UsageError('--daily applies to --channel email only: a LinkedIn account\'s limits are per action.', { + code: 'usage.limits', hint: `Set them with --set, e.g. --set '{"fixedMax":{"dailySendMessageCount":50}}'.`, + }); + } + const change = opts.set === undefined ? null : read_limits_arg(opts.set, LINKEDIN_LIMIT_FIELDS); + const s = await open_session(ctx, g); + print_result({channel, id, limits: await linkedin_limits(s, g, id, change)}, g); + return; + } + const id = email_id(id_arg); + const set = opts.set === undefined ? {} : read_limits_arg(opts.set, EMAIL_LIMIT_FIELDS); + const daily = opts.daily === undefined ? undefined : parse_int_in(opts.daily, '--daily', 0, LARGEST_DAILY, 0); + const change = {...set, ...(daily === undefined ? {} : {dailyLimit: daily})}; + const s = await open_session(ctx, g); + print_result({channel, id, limits: await email_limits(s, g, id, Object.keys(change).length === 0 ? null : change)}, g); +}; + +// Reply has no pause for a mailbox; what it has clears a block the provider put on sending. +const linkedin_only = (channel: Account_channel, verb: 'pause' | 'resume'): void=>{ + if (channel === 'email') + { + throw new UsageError(`Reply has no way to ${verb} a mailbox through its API.`, { + code: 'usage.unsupported', + hint: verb === 'resume' ? 'A mailbox its provider stopped from sending is unblocked with `account unblock `.' : undefined, + }); + } +}; + +const is_known_status = (v: unknown): v is string=>typeof v === 'string' && Object.prototype.hasOwnProperty.call(LINKEDIN_STATUSES, v); + +const status_word = (v: unknown): Account_status=>(is_known_status(v) ? LINKEDIN_STATUSES[v] : 'other'); + +// Reply's only call flips the state: enabled becomes disabled, and every other state becomes enabled. So +// each verb makes it from the one state it moves the right way, and from no other. +const TOGGLES_FROM = {pause: 'enabled', resume: 'disabled'} as const; + +// The state is read first, and the call made only when the account is in the state the flip starts from. +const set_linkedin_state = async(id_arg: string, opts: {channel?: string}, verb: 'pause' | 'resume', ctx: Cli_context, g: Op_globals)=>{ + const channel = require_channel(opts.channel); + linkedin_only(channel, verb); + const id = linkedin_id(id_arg); + const wanted: Account_status = verb === 'pause' ? 'inactive' : 'active'; + const s = await open_session(ctx, g); + const account = await read_linkedin_account(s, g, id); + const reply_status = account.status; + if (reply_status === 'cookieInvalid') + { + throw new Operation_error('linkedin.invalid_cookie', `The LinkedIn account's session is no longer valid, so it cannot be ${verb}d.`, { + status: 200, hint: `Reconnect it first: account reconnect ${id} --channel linkedin.`, + }); + } + // Whether the flip would move a state the CLI does not know the right way cannot be told, so it is never made. + if (!is_known_status(reply_status)) + { + throw new Operation_error('account.status_unknown', 'Reply gave the LinkedIn account a state the CLI does not know, so nothing was changed.', { + status: 200, details: {reply_status: typeof reply_status === 'string' ? reply_status : null}, + }); + } + const before = LINKEDIN_STATUSES[reply_status]; + if (before === wanted) + { + print_result({channel, id, status: before, reply_status, changed: false}, g); + return; + } + // A known state that is neither the one asked for nor the one the flip starts from. At its daily limit an + // account is active, and the flip would turn it on, not off. Only pause reaches this with today's states. + if (reply_status !== TOGGLES_FROM[verb]) + { + throw new Operation_error(`account.${verb}_unavailable`, `Reply cannot ${verb} the LinkedIn account from its state '${reply_status}', so nothing was changed.`, { + status: 200, details: {reply_status}, + hint: `It can be ${verb}d once its state is ${TOGGLES_FROM[verb]}; \`account list --channel linkedin\` reads it.`, + }); + } + const a = await account_call(s, g, 'POST', `/v3/linkedin-accounts/${id}/toggle-status`, 'write'); + if (a.status !== 200) + { + throw account_refusal(a, 'write'); + } + const after = expect_object(a, 'write').status; + if (status_word(after) !== wanted) + { + // Someone else changed it between the read and the call, and the flip undid theirs. + throw new Operation_error('account.status_changed', `The account's state changed while it was being ${verb}d; read it and try again.`, { + status: 200, details: {reply_status: typeof after === 'string' ? after : null}, + }); + } + print_result({channel, id, status: wanted, reply_status: after, changed: true}, g); +}; + +const handle_account_pause = (id_arg: string, opts: {channel?: string}, ctx: Cli_context, g: Op_globals): Promise=> + set_linkedin_state(id_arg, opts, 'pause', ctx, g); + +const handle_account_resume = (id_arg: string, opts: {channel?: string}, ctx: Cli_context, g: Op_globals): Promise=> + set_linkedin_state(id_arg, opts, 'resume', ctx, g); + +const handle_account_unblock = async(id_arg: string, ctx: Cli_context, g: Op_globals): Promise=>{ + const id = email_id(id_arg); + const s = await open_session(ctx, g); + const a = await account_call(s, g, 'POST', `/v3/email-accounts/${id}/resume-sending`, 'write'); + if (a.status !== 204 && a.status !== 200) + { + throw account_refusal(a, 'write'); + } + print_result({channel: 'email', id, unblocked: true}, g); +}; + +const handle_account_delete = async( + id_arg: string, opts: {channel?: string; yes?: boolean; force?: boolean}, ctx: Cli_context, g: Op_globals, +): Promise=>{ + const channel = require_channel(opts.channel); + const id = channel === 'email' ? email_id(id_arg) : linkedin_id(id_arg); + if (opts.force === true && channel === 'email') + { + throw new UsageError('--force applies to --channel linkedin only.', {code: 'usage.force'}); + } + if (opts.yes !== true) + { + throw new UsageError('Deleting an account cannot be undone: pass --yes to delete it.', {code: 'usage.confirm'}); + } + const path = channel === 'email' ? `/v3/email-accounts/${id}` : `/v3/linkedin-accounts/${id}${opts.force === true ? '?force=true' : ''}`; + const s = await open_session(ctx, g); + const a = await account_call(s, g, 'DELETE', path, 'write'); + if (a.status !== 204 && a.status !== 200) + { + throw account_refusal(a, 'write'); + } + print_result({channel, id, deleted: true}, g); +}; + +export {handle_account_limits, handle_account_pause, handle_account_resume, handle_account_unblock, handle_account_delete}; diff --git a/src/operations/accounts.ts b/src/operations/accounts.ts index 82315fc..b2439c1 100644 --- a/src/operations/accounts.ts +++ b/src/operations/accounts.ts @@ -1,4 +1,4 @@ -import {Operation_error} from '../utils/errors'; +import {Operation_error, UsageError} from '../utils/errors'; import {call_reply, read_page, refusal, unreadable, is_object, open_session, type Op_session} from './call'; import {parse_choice, type Op_globals} from './options'; import {print_result} from './result'; @@ -20,6 +20,16 @@ const LINKEDIN_STATUSES: Record = { enabled: 'active', disabled: 'inactive', cookieInvalid: 'disconnected', dailyLimitReached: 'active', }; +// --channel, where a command acts differently by channel and so cannot guess one. +const require_channel = (raw: string | undefined): Account_channel=>{ + const channel = parse_choice(raw, '--channel', ACCOUNT_CHANNELS); + if (channel === undefined) + { + throw new UsageError('--channel is required: email or linkedin.', {code: 'usage.channel'}); + } + return channel; +}; + const PAGE = 1000; // the most Reply gives in one page of email accounts const MAX_PAGES = 20; @@ -91,4 +101,5 @@ const handle_account_list = async(opts: {channel?: string}, ctx: Cli_context, g: print_result({items}, g); }; -export {handle_account_list}; +export {handle_account_list, require_channel, ACCOUNT_CHANNELS, LINKEDIN_STATUSES}; +export type {Account_channel, Account_status}; diff --git a/src/operations/call.ts b/src/operations/call.ts index 4504abd..3d19775 100644 --- a/src/operations/call.ts +++ b/src/operations/call.ts @@ -1,4 +1,4 @@ -import {request_raw, parse_retry_after, type Call_kind} from '../utils/client'; +import {request_raw, parse_retry_after, type Call_kind, type Raw_response} from '../utils/client'; import {Operation_error, RuntimeError, Unknown_outcome_error} from '../utils/errors'; import {team_error_guidance} from '../teams'; import {authed} from '../commands/authed'; @@ -6,7 +6,8 @@ import {LARGEST_REPLY_ID, type Op_globals} from './options'; import type {Cli_context} from '../context'; type Op_session = {api_base: string; token: string; headers: Record}; -type Answer = {status: number; data: unknown; headers: Record}; +// `request` is the request as sent, its credential already redacted, for a --verbose trace. +type Answer = {status: number; data: unknown; headers: Record; request?: Raw_response['request']}; type Item_failure = {error: string | null; details: string | null}; const open_session = async(ctx: Cli_context, g: Op_globals): Promise=>{ @@ -44,7 +45,7 @@ const call_reply = async( ): Promise=>{ try { const r = await request_raw(s.api_base, s.token, method, path, body, {headers: {...s.headers, ...headers}, kind}); - return {status: r.status, data: r.data, headers: r.response_headers}; + return {status: r.status, data: r.data, headers: r.response_headers, request: r.request}; } catch (e) { if (e instanceof RuntimeError) { diff --git a/src/operations/commands.ts b/src/operations/commands.ts index be69cb0..a6fe261 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -19,6 +19,8 @@ import {handle_contact_opt_out} from './contact'; import {handle_contact_find, handle_contact_get, handle_contact_update, handle_contact_delete} from './contact-record'; import {handle_direct_send, type Direct_send_name} from './direct-send'; import {handle_account_list} from './accounts'; +import {handle_account_connect, handle_account_reconnect, handle_account_pending} from './account-links'; +import {handle_account_limits, handle_account_pause, handle_account_resume, handle_account_unblock, handle_account_delete} from './account-manage'; import {handle_schedule_list} from './schedules'; import {handle_direct_send_get, handle_direct_send_cancel} from './direct-sends'; import { @@ -632,7 +634,8 @@ inbox_command.command('mark-unread') await handle_inbox_mark_unread(cmd.args[0], ctx, g); })); -const account_command = new Command('account').description('List the email and LinkedIn accounts a send can go from'); +const account_command = new Command('account') + .description('List, connect, reconnect, limit, pause, resume, unblock or delete the email and LinkedIn accounts a send can go from'); account_command.command('list') .option('--channel ', 'email | linkedin: only the accounts of this channel') @@ -651,6 +654,164 @@ account_command.command('list') await handle_account_list(cmd.opts(), ctx, g); })); +// What every link command says of the link it prints. +const LINK_RULE = 'The link is a credential for whoever opens it: it is printed once, in "link", and never on stderr, in a --verbose\n' + + 'trace (where it reads ), in an error or in a log. Hand it to the person who signs in, and do not keep it.\n'; + +const ACCOUNT_REFUSALS = 'Reply\'s own code for a refusal is always in reply_code, as Reply gave it; a refusal not listed here is\n' + + 'read like any other command\'s, e.g. reply.refused.\n'; + +const SHARED_PAGE = '--allow-shared-page: on a Reply without one-mailbox email links (its route answers 404 with no code), print the\n' + + 'account user\'s hosted mailbox page instead, with "link_kind":"shared_page", "expires_at":null and a "warning". That\n' + + 'address does not expire and lets its holder manage all of this user\'s mailboxes, deletion included. With --provider it\n' + + 'is that provider\'s connect on the hosted page; without, the hosted index. Without the flag such a Reply is refused,\n' + + 'email_link.not_available, and nothing is printed. shared_page.not_enabled: the plan does not include hosted pages.\n'; + +account_command.command('connect') + .option('--channel ', 'email | linkedin (required)') + .option('--provider ', 'gmail | office365: the mailbox\'s provider (email; required unless --allow-shared-page)') + .option('--name ', 'A label for the pending entry (required for LinkedIn; up to 100 characters for email)') + .option('--allow-shared-page', 'Email: on a Reply without one-mailbox links, print the hosted mailbox page instead') + .description('Make a link that connects one new account, for the person who signs in to it to open') + .addHelpText('after', help([ex('account connect --channel email --provider gmail --name "Sales mailbox"'), + ex('account connect --channel linkedin --name "Dana Example"')], + ['email_link.not_available', 'email_link.provider_required', 'shared_page.not_enabled', 'email_account.limit_reached', + 'email_account.no_free_mailbox_slots', 'linkedin.account_limit_reached'], true, + 'Result: {"channel","link","expires_at","pending_id","kind":"connect","link_kind":"connection_link"|"shared_page"}.\n' + + 'A connection link connects exactly one account, works once and expires: an email link after 7 days, at expires_at; a\n' + + 'LinkedIn link\'s expiry is not in Reply\'s answer, so expires_at is null there and `account pending` reads it.\n' + + 'pending_id is the entry `account pending` lists until the person finishes. Then the account is in `account list`.\n' + + 'Without --provider, an email link is a usage error unless --allow-shared-page is given; then a Reply with one-mailbox\n' + + 'links answers email_link.provider_required, and one without them gives the hosted index.\n' + + LINK_RULE + SHARED_PAGE + ACCOUNT_REFUSALS, + 'the link may have been made; it is listed by `account pending`')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_connect(cmd.opts(), ctx, g); + })); + +account_command.command('reconnect') + .argument('', 'The account\'s id, as `account list` gives it') + .option('--channel ', 'email | linkedin (required)') + .option('--provider ', 'gmail | office365: with --allow-shared-page, which provider\'s hosted connect to print') + .option('--allow-shared-page', 'Email: on a Reply without one-mailbox links, print the hosted mailbox page instead') + .description('Make a link that reconnects one account that lost its connection, for the person who signs in to it to open') + .addHelpText('after', help([ex('account reconnect 12 --channel email'), ex('account reconnect 34 --channel linkedin')], + ['email_link.not_available', 'shared_page.not_enabled', 'email_account.not_found', 'email_account.reconnect_not_supported', + 'linkedin.account_not_found'], true, + 'Result: {"channel","id","link","expires_at","pending_id","kind":"reconnect","link_kind"}. An email link reconnects\n' + + 'only the user\'s own Gmail or Office 365 mailbox, and the person must sign in with the same address; Reply takes\n' + + 'the provider from the mailbox. A LinkedIn link has no pending entry and no expiry in Reply\'s answer, so\n' + + 'pending_id and expires_at are null; the account\'s status in `account list` says when it is connected again.\n' + + 'On the shared page, --provider prints the provider\'s connect marked as a reconnect: the person signs in with\n' + + 'the same address. Without it the index is printed: the person opens the mailbox there and reconnects it.\n' + + LINK_RULE + SHARED_PAGE + ACCOUNT_REFUSALS, + 'a link may have been made')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_reconnect(cmd.args[0], cmd.opts(), ctx, g); + })); + +account_command.command('pending') + .option('--channel ', 'email | linkedin: only this channel\'s entries') + .description('The connection links made and not used yet, recently expired ones included') + .addHelpText('after', help([ex('account pending'), ex('account pending --channel linkedin')], [], false, + 'Result: {"items":[{"channel","id","name","kind","account_id","expires_at","expired"}],"supported",\n' + + '"unsupported_channels"}. kind is connect or reconnect, and account_id the email account a reconnect is for (null\n' + + 'otherwise). The links themselves are never printed: Reply shows an email link only once, and a LinkedIn one is\n' + + 'dropped from the answer. A Reply without one-mailbox email links has no email entries to list: supported is then\n' + + 'false and unsupported_channels names email. An entry leaves the list once the person finishes.\n' + + ACCOUNT_REFUSALS)) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_pending(cmd.opts(), ctx, g); + })); + +account_command.command('limits') + .argument('', 'The account\'s id, as `account list` gives it') + .option('--channel ', 'email | linkedin (required)') + .option('--daily ', 'Email: the most emails the mailbox sends in a day') + .option('--set ', 'The limits to change, in Reply\'s names: inline JSON, @file, or - for stdin') + .description('Read an account\'s sending limits, or change some of them') + .addHelpText('after', help([ex('account limits 12 --channel email'), ex('account limits 12 --channel email --daily 200'), + `${P} account limits 34 --channel linkedin --set '{"fixedMax":{"dailySendMessageCount":50}}'`], + ['email_account.not_found', 'linkedin.account_not_found'], true, + 'Result: {"channel","id","limits"}: the limits as Reply holds them afterwards, in Reply\'s names. For email they are the\n' + + 'safety section (dailyLimit, isEmailsThrottlingEnabled, emailsPerInterval, emailsThrottlingSecondsInterval,\n' + + 'isSendingDelayEnabled, minSendingDelaySeconds, maxSendingDelaySeconds), and --set takes those fields. For LinkedIn\n' + + 'they are the account\'s limits (limitsMode, rangeMin, rangeMax, fixedMax, actionDelayMinSeconds,\n' + + 'actionDelayMaxSeconds), and --set takes them as Reply\'s limits update does: a field left out keeps its value.\n' + + 'Without --daily or --set the limits are only read. Reply caps a value above what the plan allows. When a LinkedIn\n' + + 'change is saved and reading it back fails, limits is null and stderr says so.\n' + + ACCOUNT_REFUSALS)) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_limits(cmd.args[0], cmd.opts(), ctx, g); + })); + +const PAUSE_RESUME = 'Result: {"channel","id","status","reply_status","changed"}: status is active or inactive, reply_status Reply\'s own\n' + + 'word, and changed whether a call was made. Reply\'s only call flips the state, so the state is read first and an\n' + + 'account already in the state asked for is left alone. The flip turns an enabled account off and any other on, so\n' + + 'pause flips only an enabled account and resume only a disabled one. A LinkedIn account at its daily limit is\n' + + 'active: resume leaves it alone, and pause refuses it before any write (account.pause_unavailable).\n' + + 'account.status_unknown: Reply gave a state the CLI does not know; nothing was changed.\n' + + 'linkedin.invalid_cookie: the account\'s session is no longer valid; reconnect it first. account.status_changed: the\n' + + 'state changed between the read and the call; read it again. Reply has no way to pause a mailbox through its API, so\n' + + '--channel email is refused (usage.unsupported); a mailbox its provider stopped from sending is `account unblock`.\n'; + +account_command.command('pause') + .argument('', 'The LinkedIn account\'s id') + .option('--channel ', 'linkedin (required; email has no pause)') + .description('Stop a LinkedIn account\'s automation until it is resumed') + .addHelpText('after', help([ex('account pause 34 --channel linkedin')], + ['linkedin.account_not_found', 'linkedin.invalid_cookie', 'account.pause_unavailable', 'account.status_changed', 'account.status_unknown'], + true, PAUSE_RESUME)) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_pause(cmd.args[0], cmd.opts(), ctx, g); + })); + +account_command.command('resume') + .argument('', 'The LinkedIn account\'s id') + .option('--channel ', 'linkedin (required; email has no pause)') + .description('Start a paused LinkedIn account\'s automation again') + .addHelpText('after', help([ex('account resume 34 --channel linkedin')], + ['linkedin.account_not_found', 'linkedin.invalid_cookie', 'account.status_changed', 'account.status_unknown'], true, PAUSE_RESUME)) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_resume(cmd.args[0], cmd.opts(), ctx, g); + })); + +account_command.command('unblock') + .argument('', 'The email account\'s id') + .description('Let a mailbox its provider stopped from sending pick its sequences back up') + .addHelpText('after', help([ex('account unblock 12')], ['email_account.not_found'], true, + 'Result: {"channel":"email","id","unblocked":true}. It clears the block Reply recorded when the provider refused to send\n' + + '(sendingLockedByProvider on the account); it does not reconnect a mailbox that lost its connection.\n' + + ACCOUNT_REFUSALS)) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_unblock(cmd.args[0], ctx, g); + })); + +account_command.command('delete') + .argument('', 'The account\'s id, as `account list` gives it') + .option('--channel ', 'email | linkedin (required)') + .option('--yes', 'Delete it: there is no prompt, and without --yes nothing is sent') + .option('--force', 'LinkedIn: delete it even while sequences use it') + .description('Remove an account from Reply; it cannot be undone') + .addHelpText('after', help([ex('account delete 12 --channel email --yes'), ex('account delete 34 --channel linkedin --yes --force')], + ['email_account.not_found', 'linkedin.account_not_found', 'linkedin.account_in_use'], true, + 'Result: {"channel","id","deleted":true}. Without --yes it is a usage error (usage.confirm, exit 2) and nothing is sent.\n' + + 'linkedin.account_in_use: sequences use the LinkedIn account; --force deletes it anyway. --force with --channel\n' + + 'email is a usage error.\n' + + ACCOUNT_REFUSALS, + 'the account may have been deleted; `account list` says whether it is still there')) + .action(run(async(cmd)=>{ + const {g, ctx} = ctx_of(cmd); + await handle_account_delete(cmd.args[0], cmd.opts(), ctx, g); + })); + const schedule_command = new Command('schedule').description('List the sending schedules a sequence can send within'); schedule_command.command('list') diff --git a/src/operations/options.ts b/src/operations/options.ts index 7d6a330..0b78ce0 100644 --- a/src/operations/options.ts +++ b/src/operations/options.ts @@ -9,6 +9,7 @@ type Op_globals = { userEmail?: string; json?: boolean; pretty?: boolean; + verbose?: boolean; }; const read_op_globals = (cmd: Command): Op_globals=>{ @@ -16,7 +17,7 @@ const read_op_globals = (cmd: Command): Op_globals=>{ return { apiKey: o.apiKey, profile: o.profile, teamId: o.teamId, userId: o.userId, userEmail: o.userEmail, - json: o.json, pretty: o.pretty, + json: o.json, pretty: o.pretty, verbose: o.verbose, }; }; diff --git a/src/operations/shared-page.ts b/src/operations/shared-page.ts new file mode 100644 index 0000000..f4c779b --- /dev/null +++ b/src/operations/shared-page.ts @@ -0,0 +1,62 @@ +// The addresses of Reply's hosted mailbox page, all built from the one address Reply's v1 shared-page +// route answers. Every form here carries the account user's hosted token: it does not expire, and it lets +// whoever holds it manage all of that user's mailboxes, deletion included. So none of them is ever +// written anywhere but the one stdout field that hands it over. + +const HOSTED_PROVIDERS = ['gmail', 'office365'] as const; +type Hosted_provider = typeof HOSTED_PROVIDERS[number]; + +const SHARED_PAGE_WARNING = 'this address does not expire and lets its holder manage all of this user\'s mailboxes, deletion included'; + +// Reply answers the hosted index, `{origin}/hosted/eac/index/{token}`. +const INDEX_PATH = /^(.*)\/hosted\/eac\/index\/([^/]+)\/?$/i; + +type Shared_page = { + index: string; // the address as Reply gave it + token: string; + base: string; // the origin, with any path the app is served under +}; + +// The parts of the address Reply answered, or null when it is not in that form. Nothing of the +// address goes into an error, so a caller says only that it could not be read. +const read_shared_page = (url: string): Shared_page | null=>{ + let parsed: URL; + try { + parsed = new URL(url); + } catch { + return null; + } + const m = INDEX_PATH.exec(parsed.pathname); + if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') || m === null) + { + return null; + } + let token: string; + try { + token = decodeURIComponent(m[2]); + } catch { + return null; + } + return token === '' ? null : {index: url, token, base: `${parsed.origin}${m[1]}`}; +}; + +// The page to open: the provider's own connect when one is named, else the index of every mailbox. A +// provider's connect for a reconnect says so: without it the hosted page counts the sign-in as a new +// mailbox, and a user with no free mailbox slot is sent to that error instead of reconnecting. The index +// needs nothing: it adds the flag itself when the person reconnects a mailbox already on it. +const shared_page_link = (page: Shared_page, provider: Hosted_provider | undefined, kind: 'connect' | 'reconnect'): string=>{ + const token = encodeURIComponent(page.token); + const reconnect = kind === 'reconnect' ? '&reconnect=true' : ''; + switch (provider) + { + case 'gmail': + return `${page.base}/hosted/eac/ConnectWithGMail?uidToken=${token}${reconnect}`; + case 'office365': + return `${page.base}/hosted/eac/ConnectWithOffice?uidToken=${token}&isExchange=false${reconnect}`; + default: + return page.index; + } +}; + +export {HOSTED_PROVIDERS, SHARED_PAGE_WARNING, read_shared_page, shared_page_link}; +export type {Hosted_provider, Shared_page};