diff --git a/README.md b/README.md index 400da97..f97f648 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,19 @@ Reply cannot fill is `contact.missing_variables`, with the names under the error # {"error":{"code":"contact.missing_variables",…,"details":{"missing_variables":["FirstName","Company"]}}} ``` +Reply holds a direct email to the mailbox's limits. `email.limit_reached` (`429`) is one of them +reached, with `details.limit` saying which: `daily`, the mailbox's day, which Reply counts in UTC, +or `active_contacts`, the contacts the account may email in its billing period. A send for later is +also refused `daily` when the day it is due already holds as many sends as the mailbox's limit. +`retry_after` passes on Reply's `Retry-After`, the seconds until the limit clears, and the CLI never +repeats the send itself. `email.sending_disabled` (`403`) is a mailbox or team that cannot send +direct emails now: the mailbox's daily limit is 0, or the team's plan does not send; no wait clears +it. Neither sends anything, and `reply_code` keeps Reply's own code, as on every refusal: + +```sh +# {"error":{"status":429,"code":"email.limit_reached",…,"reply_code":"contact.dailyLimitReached","retry_after":43200,"details":{"limit":"daily"}}} +``` + Every direct send also takes `--send-after `, `--schedule-id ` and `--idempotency-key `. Reply holds the send until the moment, given with its offset (`2026-11-03T14:00:00Z`, `2026-11-03T16:00:00+02:00`) and sent to Reply in UTC; a moment without an @@ -406,9 +419,14 @@ reply direct-send cancel linkedin-1042 Both answer the send under the CLI's names, each null when Reply gives none: `reference`, `channel`, `contact_id`, `state`, `send_after`, `sent_at`, `message_id`, `failure_reason` and `cancelled_at`. `failure_code`, `missing_variables`, `rendered_subject` and `rendered_body` are added only when -Reply gives them, and so is `estimated_send_at`, read the same way as on the send but as of the -read: set in `waitingForSchedule` only and null in every other state, and null there too when the -schedule does not open within 30 days counted from `--send-after`, or from now once that has passed. +Reply gives them, and so are `bounced`, `bounce_type` and `bounced_at`: whether a bounce came back +for the email after it went out (false until one does, and always false for LinkedIn), Reply's own +word for the kind of the latest bounce as given (`hard`, `soft`, `mailboxFull`, `unknown`, …), and +when it came. Reply leaves `bounce_type` and `bounced_at` null while `bounced` is false, and +`bounced_at` null when the bounce carried no date; the CLI passes on what Reply gives and checks +neither. So is `estimated_send_at`, read the same way as on the send but as of the read: set in +`waitingForSchedule` only and null in every other state, and null there too when the schedule does +not open within 30 days counted from `--send-after`, or from now once that has passed. `failure_reason` is a sentence for a person and never parsed; `failure_code` is Reply's code for the failure, the one to branch on. A failed send may carry no `failure_code`: it is then null, and `failure_reason` is all Reply says of it. `direct-send cancel` of a send already cancelled answers @@ -529,17 +547,13 @@ is in `account list`. An email link needs `--provider`; a reconnect takes the pr 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"]`. +A Reply without one-mailbox email links answers that route with a 404 and no code. `account +connect`, `account reconnect` and `account pending` then refuse with `email_link.not_available` +(exit 1), print nothing and offer nothing else. `"link_kind"` is always `"connection_link"`, and +`account pending` always answers `"supported":true` with `"unsupported_channels":[]`; the fields are +kept for callers that read them. `--allow-shared-page`, which printed the account user's hosted +mailbox page on such a Reply, is deprecated: it is still accepted, does nothing and is hidden from +the help, and a later release removes it. So is `--provider` on `account reconnect`. ```sh reply account connect --channel email --provider gmail --name "Sales mailbox" @@ -575,9 +589,10 @@ the others checks or relies on Reply's own state rather than repeating an effect **Retries.** Reads are retried on errors. A write is retried only when it can't have reached Reply: the connection was never made, or a `429` asked to wait 3 seconds or less. A longer `429` comes back -as `rate_limited` with `retry_after`. A `429` that names a `reference` or says a daily or weekly limit -was reached is never resent, whatever it asks to wait: Reply may have recorded the attempt, and a repeat -would record another. Each comes back at once as the refusal it is. +as `rate_limited` with `retry_after`. A `429` that names a `reference` or says a daily, weekly or +active contacts limit was reached is never resent, whatever it asks to wait: Reply may have +recorded the attempt, and a repeat would record another. Each comes back at once as the refusal it +is. ## Raw API access @@ -611,7 +626,7 @@ connection that broke after sending. That last case exits 3: the write may have goes by the method alone, so this includes a POST that only reads, such as the `…/filter` calls; run it again yourself if it failed. A `429` is waited out only when `Retry-After` asks for 3 seconds or less; a longer one is printed as the `429` it is, and so is one whose body names a `reference` or a -daily or weekly limit. +daily, weekly or active contacts limit. ### Windows: Git Bash rewrites the path diff --git a/skills/reply-adapter/reply-cli/SKILL.md b/skills/reply-adapter/reply-cli/SKILL.md index cb5fb6a..bb47c01 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.4.0 + version: 1.5.0 pack: reply-adapter category: execution maturity: reviewed @@ -117,8 +117,8 @@ Rules: the path is used **exactly as written in the API docs** (starts with `/v3 goes in the path). `--method GET|POST|PUT|PATCH|DELETE` overrides the default. Output is always `{"code": , "data": }` on stdout — check `code` yourself; stdout stays clean for piping. Transient failures (429/5xx) retry automatically honoring `Retry-After`, except a 429 -that names a `reference` or says a daily or weekly limit was reached, which is never resent and -comes back at once as the refusal it is. +that names a `reference` or says a daily, weekly or active contacts limit was reached, which is +never resent and comes back at once as the refusal it is. ### Exit codes & errors @@ -152,9 +152,8 @@ exit codes with their error `code` slugs. - `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. + or repeat it. `email_link.not_available` means this Reply has no one-mailbox email links, and + nothing else is offered. Do not pass `--allow-shared-page`: it is deprecated and does nothing. ## Safety @@ -171,6 +170,10 @@ explicit confirmation its Safety section requires. ## Changelog +- 1.5.0 (2026-11-21): *Failure modes* no longer offers the hosted mailbox page: the CLI prints only + one-mailbox connection links, and `--allow-shared-page` is deprecated and does nothing. +- 1.4.1 (2026-11-21): `reply api` says that a 429 saying an active contacts limit was reached is + never resent either, as the CLI now treats it. - 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 diff --git a/src/__tests__/operations/account-links.test.ts b/src/__tests__/operations/account-links.test.ts index c32026c..4f6bfe4 100644 --- a/src/__tests__/operations/account-links.test.ts +++ b/src/__tests__/operations/account-links.test.ts @@ -2,7 +2,6 @@ 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. @@ -10,7 +9,6 @@ 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})=>{ @@ -21,35 +19,6 @@ 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(); @@ -60,71 +29,32 @@ describe('account connect', ()=>{ 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) + it('email: a Reply without the route is email_link.not_available, offering nothing, with or without --allow-shared-page', async()=>{ + for (const allowSharedPage of [undefined, true]) { 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'], - ]); + answer(missing()); + const e = await fails(()=>handle_account_connect({channel: 'email', provider: 'office365', allowSharedPage}, ctx(), {})); + expect(e, String(allowSharedPage)).toMatchObject({code: 'email_link.not_available', status: 404, exit_code: 1, title: 'This Reply does not issue one-mailbox email connection links, so no link was made.'}); + expect((e as {hint?: string}).hint, String(allowSharedPage)).toBeUndefined(); + expect(sent().map(r=>r.url), String(allowSharedPage)).toEqual(['https://api/v3/email-accounts/connection-link']); } }); - 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}); + 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'}, ctx(), {}))) + .toMatchObject({code: 'email_account.not_found', reply_code: 'emailAccount.notFound', status: 404, 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))); + it('email --allow-shared-page is accepted and ignored: the one-mailbox link is made as without it', 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', allowSharedPage: true}, ctx(), g)); - expect(result).toMatchObject({link: `${APP}/hosted/eac/ConnectWithGMail?uidToken=${t}`, link_kind: 'shared_page'}); + expect(result).toStrictEqual({channel: 'email', link, expires_at: '2026-11-18T12:00:00Z', pending_id: 50, kind: 'connect', + link_kind: 'connection_link'}); + expect(sent().map(r=>[r.method, r.url])).toEqual([['POST', 'https://api/v3/email-accounts/connection-link']]); }); it('email: Reply\'s refusal comes under the CLI\'s code, with Reply\'s in reply_code', async()=>{ @@ -133,8 +63,10 @@ describe('account connect', ()=>{ .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()=>{ + it('email: without --provider, --allow-shared-page or not, 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', allowSharedPage: true}, 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}); @@ -150,13 +82,15 @@ describe('account connect', ()=>{ 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()=>{ + it('linkedin: needs --name, and takes no --provider; --allow-shared-page is ignored there too', 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(); + const link = linkedin_link(); + answer(json({connectionLink: link, pendingAccountId: 51}, 201)); + const {result} = await run(g=>handle_account_connect({channel: 'linkedin', name: 'D', allowSharedPage: true}, ctx(), g)); + expect(result).toMatchObject({channel: 'linkedin', link, link_kind: 'connection_link'}); }); 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()=>{ @@ -180,22 +114,15 @@ describe('account reconnect', ()=>{ 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) + it('email: a Reply without the route is email_link.not_available, offering nothing; --allow-shared-page and --provider are ignored', async()=>{ + for (const opts of [{channel: 'email'}, {channel: 'email', allowSharedPage: true}, {channel: 'email', provider: 'gmail', allowSharedPage: true}]) { 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}); + answer(missing()); + const e = await fails(()=>handle_account_reconnect('12', opts, ctx(), {})); + expect(e, JSON.stringify(opts)).toMatchObject({code: 'email_link.not_available', status: 404, exit_code: 1, title: 'This Reply does not issue one-mailbox email connection links, so no link was made.'}); + expect((e as {hint?: string}).hint, JSON.stringify(opts)).toBeUndefined(); + expect(sent().map(r=>r.url), JSON.stringify(opts)).toEqual(['https://api/v3/email-accounts/12/reconnect']); } }); @@ -248,13 +175,16 @@ describe('account pending', ()=>{ 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('a Reply without one-mailbox email links is email_link.not_available, offering nothing, with or without --channel email', async()=>{ + for (const opts of [{channel: 'email'}, {}]) + { + mock_fetch.mockReset(); + answer(missing(), json([])); + const e = await fails(()=>handle_account_pending(opts, ctx(), {})); + expect(e, JSON.stringify(opts)).toMatchObject({code: 'email_link.not_available', status: 404, exit_code: 1, title: 'This Reply does not issue one-mailbox email connection links, so no link was made.'}); + expect((e as {hint?: string}).hint, JSON.stringify(opts)).toBeUndefined(); + expect(sent().map(r=>r.url), JSON.stringify(opts)).toEqual(['https://api/v3/email-accounts/pending']); + } }); it('--channel linkedin reads only LinkedIn; a refusal comes under the CLI\'s code', async()=>{ diff --git a/src/__tests__/operations/account-secrets.test.ts b/src/__tests__/operations/account-secrets.test.ts index 9993d97..3dd0073 100644 --- a/src/__tests__/operations/account-secrets.test.ts +++ b/src/__tests__/operations/account-secrets.test.ts @@ -8,7 +8,7 @@ import {handle_account_connect, handle_account_reconnect, handle_account_pending 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 +// The secret rule: a link and any token in it 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. @@ -35,16 +35,6 @@ const CASES: Case[] = [ 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)}, @@ -54,28 +44,6 @@ const CASES: Case[] = [ {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)}, @@ -127,9 +95,8 @@ describe('the secret rule, through the program', ()=>{ 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}`})); + // Runs `reply` with the arguments given and answers how it exited: a usage refusal is exit 2 before any call. + const run_program = async(args: string[]): Promise<{code: number; err: string}>=>{ let exited!: (code: number) => void; const exit = new Promise(resolve=>{ exited = resolve; }); let first: number | undefined; @@ -140,18 +107,32 @@ describe('the secret rule, through the program', ()=>{ exited(first); } }) as typeof process.exit); - process.argv = ['node', 'reply', '--json', '-k', 'key-1', '--verbose', 'account', 'connect', '--channel', 'email', '--provider', 'gmail', - '--allow-shared-page']; + process.argv = ['node', 'reply', '--json', '-k', 'key-1', '--verbose', ...args]; vi.resetModules(); let code = -1; - const {out, err} = await capture(async()=>{ + const {err} = await capture(async()=>{ await import('../../index'); code = await exit; }); + return {code, err}; + }; + + it('--allow-shared-page is still accepted, and ignored: a Reply without the route is email_link.not_available, exit 1', async()=>{ + answer(missing()); + const {code, err} = await run_program(['account', 'connect', '--channel', 'email', '--provider', 'gmail', '--allow-shared-page']); + expect(code).toBe(1); + expect(err).toContain('> POST https://api.reply.io/v3/email-accounts/connection-link'); + expect(err).not.toContain('SharedPageUrl'); + expect(err).toContain('"code":"email_link.not_available"'); + }); + + it('an email reconnect still takes --provider and --allow-shared-page: neither is refused, and the reconnect is asked for', async()=>{ + answer(missing()); + const {code, err} = await run_program(['account', 'reconnect', '12', '--channel', 'email', '--provider', 'gmail', '--allow-shared-page']); 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); + expect(err).toContain('> POST https://api.reply.io/v3/email-accounts/12/reconnect'); + expect(err).not.toContain('SharedPageUrl'); + expect(err).toContain('"code":"email_link.not_available"'); + expect(err).not.toContain('"code":"usage.'); }); }); diff --git a/src/__tests__/operations/commands.test.ts b/src/__tests__/operations/commands.test.ts index 9a23772..67563b8 100644 --- a/src/__tests__/operations/commands.test.ts +++ b/src/__tests__/operations/commands.test.ts @@ -133,10 +133,16 @@ describe('operations/commands', ()=>{ { 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'); + // --allow-shared-page is still taken, so a caller passing it is not refused, and it is hidden: it does nothing. + expect(flat, name).not.toContain('--allow-shared-page'); + expect(flat, name).not.toMatch(/shared|hosted/i); + expect(flat, name).not.toContain('shared_page.not_enabled'); } + expect(help_of(sub(account_command, 'reconnect')), 'reconnect').not.toContain('--provider'); + expect(help_of(sub(account_command, 'pending')).replace(/\s+/g, ' ')) + .toContain('A Reply without one-mailbox email links answers email_link.not_available'); 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'); @@ -299,7 +305,7 @@ describe('operations/commands', ()=>{ const SENT_AT_AS_GIVEN = 'sentAtUtc as Reply gives them, each null when it gives none; the CLI adds no time of its own'; const DIRECT_SENDS: [string, string, string[], string][] = [ ['send-email', '--email-account-id', ['contact.not_found', ...IMPORT, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', - 'contact.missing_variables', 'contact.rendering_failed', 'schedule.not_found', 'schedule.no_slot', 'contact.time_zone_missing'], + 'contact.missing_variables', 'contact.rendering_failed', 'email.limit_reached', 'email.sending_disabled', 'schedule.not_found', 'schedule.no_slot', 'contact.time_zone_missing'], 'sent_at is always null; the CLI adds none of its own'], ['linkedin-connect', '--linkedin-account-id', [...LINKEDIN, 'linkedin.not_connected', 'linkedin.limit_reached', 'linkedin.message_too_long', 'linkedin.missing_variables'], SENT_AT_AS_GIVEN], @@ -403,6 +409,19 @@ describe('operations/commands', ()=>{ expect(flat, flat).toContain('contact.missing_variables names the variables Reply could not fill in details.missing_variables'); expect(flat, flat).toContain('contact.rendering_failed is a template Reply could not render, its message in detail'); expect(flat, flat).toContain('An email sent within the request adds rendered_subject and rendered_body'); + // Reply holds a direct email to the mailbox's limits, so the help names them and no longer says it goes outside them. + expect(flat, flat).not.toContain('outside the mailbox\'s daily limit'); + expect(flat, flat).toContain('email.limit_reached (429) is a limit Reply holds the send to: details.limit is daily'); + expect(flat, flat).toContain('or active_contacts'); + expect(flat, flat).toContain('email.sending_disabled (403) is a mailbox or team that cannot send direct emails now'); + }); + + it('direct-send get says when the bounce members are given and what each holds', ()=>{ + const flat = help_of(sub(direct_send_command, 'get')).replace(/\s+/g, ' '); + expect(flat, flat).toContain('bounced, bounce_type and bounced_at are added only when Reply gives them'); + expect(flat, flat).toContain('bounce_type is Reply\'s own word for the kind of the latest bounce, as given'); + expect(flat, flat).toContain('Reply leaves bounce_type and bounced_at null while bounced is false, and bounced_at null when the ' + + 'bounce carried no date; the CLI passes on what Reply gives and checks neither'); }); it('inbox reply takes its text only through --message, and says a repeat may send it twice', ()=>{ diff --git a/src/__tests__/operations/direct-send.test.ts b/src/__tests__/operations/direct-send.test.ts index 0de2c9c..dd8951e 100644 --- a/src/__tests__/operations/direct-send.test.ts +++ b/src/__tests__/operations/direct-send.test.ts @@ -1230,3 +1230,98 @@ describe('a 400 directLinkedIn.unknown on the send call', ()=>{ } }); }); + +describe('a direct email Reply refuses for its limits', ()=>{ + beforeEach(()=>{ instant_timers(); }); + afterEach(()=>{ real_timers(); }); + + const always = (body: Record, status: number, headers: Record = {})=>{ + mock_fetch.mockImplementation(async()=>json(body, status, headers)); + }; + const LIMITED = {title: 'Too Many Requests', status: 429}; + const EMAIL = {subject: SUBJECT, body: BODY}; + + it('the daily limit and the active contacts limit are one code, email.limit_reached, with which one and Reply\'s wait', async()=>{ + const cases: [string, string, string][] = [ + ['contact.dailyLimitReached', 'daily', 'The mailbox reached its daily limit, so nothing was sent.'], + ['contact.activeContactsLimitReached', 'active_contacts', + 'The account reached its active contacts limit for the billing period, so nothing was sent.'], + ]; + for (const [reply_code, limit, title] of cases) + { + mock_fetch.mockReset(); + always({...LIMITED, code: reply_code, detail: 'Limit reached. The Retry-After header says when to try again.'}, 429, + {'Retry-After': '86400'}); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e, reply_code).toMatchObject({ + code: 'email.limit_reached', title, exit_code: 1, status: 429, reply_code, retry_after: 86400, + detail: 'Limit reached. The Retry-After header says when to try again.', + ids: {contact_id: 456, email_account_id: 12}, + }); + expect((e as {details?: unknown}).details, reply_code).toStrictEqual({limit}); + expect(shown(e), reply_code).not.toContain('Marta'); + expect(mock_fetch, reply_code).toHaveBeenCalledTimes(1); + } + }); + + it('each limit is one call, also with no Retry-After or a short one to go by', async()=>{ + for (const [reply_code, headers] of [ + ['contact.dailyLimitReached', {}], ['contact.activeContactsLimitReached', {}], + ['contact.dailyLimitReached', {'Retry-After': '2'}], ['contact.activeContactsLimitReached', {'Retry-After': '2'}], + ] as [string, Record][]) + { + mock_fetch.mockReset(); + always({...LIMITED, code: reply_code}, 429, headers); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e, reply_code).toMatchObject({code: 'email.limit_reached'}); + expect(mock_fetch, reply_code).toHaveBeenCalledTimes(1); + } + }); + + it('a limit that recorded a failed send names that send beside which limit it was', async()=>{ + always({...LIMITED, code: 'contact.dailyLimitReached', reference: 'email-1001', state: 'failed', sendAfter: '2026-11-21T00:00:00Z'}, 429, + {'Retry-After': '3600'}); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e).toMatchObject({code: 'email.limit_reached', retry_after: 3600}); + expect((e as {details?: unknown}).details).toStrictEqual({ + limit: 'daily', reference: 'email-1001', state: 'failed', send_after: '2026-11-21T00:00:00Z', + }); + }); + + it('a mailbox or team that cannot send is email.sending_disabled, with no wait and no word of access', async()=>{ + always({title: 'Forbidden', status: 403, code: 'contact.emailAccountSendingDisabled', + detail: 'The daily limit of this email account is 0, so it cannot send direct emails.'}, 403, {'Retry-After': '60'}); + const e = await failure('send-email', EMAIL, EMAIL_OPTS); + expect(e).toMatchObject({ + code: 'email.sending_disabled', exit_code: 1, status: 403, reply_code: 'contact.emailAccountSendingDisabled', + detail: 'The daily limit of this email account is 0, so it cannot send direct emails.', + }); + expect((e as {retry_after?: unknown}).retry_after).toBeUndefined(); + expect((e as {title: string}).title).not.toMatch(/access/i); + expect((e as {title: string}).title).toMatch(/cannot send/); + expect(mock_fetch).toHaveBeenCalledTimes(1); + }); + + it('reads each code only under the status Reply publishes it with', async()=>{ + const cases: [string, number, string][] = [ + ['contact.dailyLimitReached', 400, 'reply.refused'], + ['contact.activeContactsLimitReached', 403, 'access.denied'], + ['contact.emailAccountSendingDisabled', 429, 'rate_limited'], + ['contact.emailAccountSendingDisabled', 400, 'reply.refused'], + ]; + for (const [reply_code, status, code] of cases) + { + mock_fetch.mockReset(); + always({title: 'Refused', status, code: reply_code}, status, {'Retry-After': '3600'}); + expect(await failure('send-email', EMAIL, EMAIL_OPTS), `${reply_code} ${status}`).toMatchObject({code, reply_code}); + } + }); + + it('a LinkedIn send answering an email code falls to the usual mapping', async()=>{ + always({...LIMITED, code: 'contact.dailyLimitReached'}, 429, {'Retry-After': '3600'}); + expect(await failure('linkedin-message', {body: TEXT}, LINKEDIN_OPTS)).toMatchObject({code: 'rate_limited'}); + mock_fetch.mockReset(); + always({title: 'Forbidden', status: 403, code: 'contact.emailAccountSendingDisabled'}, 403); + expect(await failure('linkedin-message', {body: TEXT}, LINKEDIN_OPTS)).toMatchObject({code: 'access.denied'}); + }); +}); diff --git a/src/__tests__/operations/direct-sends.test.ts b/src/__tests__/operations/direct-sends.test.ts index 53176cc..91fa865 100644 --- a/src/__tests__/operations/direct-sends.test.ts +++ b/src/__tests__/operations/direct-sends.test.ts @@ -237,6 +237,55 @@ describe('direct-send get', ()=>{ .toMatchObject({code: 'reply.unavailable', exit_code: 1}); } }); + + describe('a bounce', ()=>{ + const SENT = {...QUEUED, state: 'sent', sentAt: '2026-11-20T10:00:00Z', messageId: ''}; + + it('prints whether the email bounced, the provider\'s word for the kind as given, and when', async()=>{ + for (const word of ['hard', 'soft', 'mailboxFull', 'office365LimitWarning', 'unknown', 'Something Else']) + { + mock_fetch.mockReset(); + answer(json({...SENT, bounced: true, bounceType: word, bouncedAt: '2026-11-20T10:05:00Z'})); + expect(await get('email-1001'), word).toMatchObject({ + state: 'sent', bounced: true, bounce_type: word, bounced_at: '2026-11-20T10:05:00Z', + }); + } + }); + + it('a send that did not bounce, and a LinkedIn send, print bounced false with no kind and no moment', async()=>{ + answer(json({...SENT, bounced: false, bounceType: null, bouncedAt: null})); + expect(await get('email-1001')).toMatchObject({bounced: false, bounce_type: null, bounced_at: null}); + mock_fetch.mockReset(); + answer(json({...SENT, reference: 'linkedin-1042', channel: 'linkedin', bounced: false, bounceType: null, bouncedAt: null})); + expect(await get('linkedin-1042')).toMatchObject({bounced: false, bounce_type: null, bounced_at: null}); + }); + + it('a bounce with no date keeps bounced_at null', async()=>{ + answer(json({...SENT, bounced: true, bounceType: 'hard', bouncedAt: null})); + expect(await get('email-1001')).toMatchObject({bounced: true, bounce_type: 'hard', bounced_at: null}); + }); + + it('a Reply that gives no bounce member prints as before, and a member of another shape is left out', async()=>{ + answer(json(SENT)); + const plain = await get('email-1001'); + for (const name of ['bounced', 'bounce_type', 'bounced_at']) + { + expect(plain, name).not.toHaveProperty(name); + } + mock_fetch.mockReset(); + answer(json({...SENT, bounced: 'yes', bounceType: 2, bouncedAt: 17})); + const odd = await get('email-1001'); + for (const name of ['bounced', 'bounce_type', 'bounced_at']) + { + expect(odd, name).not.toHaveProperty(name); + } + }); + + it('cancel prints the same members when Reply gives them', async()=>{ + answer(json({...CANCELLED, bounced: false, bounceType: null, bouncedAt: null})); + expect(await cancel('email-1001')).toMatchObject({state: 'cancelled', bounced: false, bounce_type: null, bounced_at: null}); + }); + }); }); describe('direct-send cancel', ()=>{ diff --git a/src/__tests__/utils/client.test.ts b/src/__tests__/utils/client.test.ts index e193ad1..f2170e6 100644 --- a/src/__tests__/utils/client.test.ts +++ b/src/__tests__/utils/client.test.ts @@ -307,6 +307,8 @@ describe('utils/client', ()=>{ ['the daily allowance in another family', {code: 'supportRequest.dailyLimitReached'}], ['the weekly allowance with no family', {code: 'weeklyLimitReached'}], ['the daily allowance with no family', {code: 'dailyLimitReached'}], + ['the active contacts allowance of a direct email', {code: 'contact.activeContactsLimitReached'}], + ['the active contacts allowance with no family', {code: 'activeContactsLimitReached'}], ])('%s is not resent', async(_name, body)=>{ await once_only({title: 'Too Many Requests', ...body}); }); diff --git a/src/operations/account-call.ts b/src/operations/account-call.ts index b01fe5a..85d7708 100644 --- a/src/operations/account-call.ts +++ b/src/operations/account-call.ts @@ -4,21 +4,19 @@ import {call_reply, detail_of, is_object, refusal, reply_code_of, type Answer, t 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. +// The calls of the account commands, and what they write to stderr under --verbose. A connection link +// and any token in it 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']; +// The field Reply hands a link in: v3's connectionLink. +const LINK_FIELDS = ['connectionlink']; // 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); @@ -85,47 +83,11 @@ const links_in = (data: unknown, found: Set = new Set()): Set=>{ 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[]=>{ +// curl -v style, as `reply api --verbose` writes it, with the answer's body after its headers. +const trace_lines = (a: Answer): string[]=>{ const lines: string[] = []; if (a.request) { @@ -146,46 +108,24 @@ const trace_lines = (a: Answer, secret_body: boolean): string[]=>{ } if (a.data !== null && a.data !== '') { - const shown = secret_body ? LINK_REDACTED : typeof a.data === 'string' ? a.data : JSON.stringify(a.data); + const shown = 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. +// One call of an account command. The links in its answer never reach the trace. const account_call = async( - s: Op_session, g: Op_globals, method: string, path: string, kind: Call_kind, body?: unknown, opts: {secret_body?: boolean} = {}, + s: Op_session, g: Op_globals, method: string, path: string, kind: Call_kind, body?: unknown, ): 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))); + console.error(redact_links(trace_lines(a).join('\n'), links_in(a.data))); } 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 = { @@ -229,4 +169,4 @@ const account_refusal = (a: Answer, kind: Call_kind): Operation_error=>{ // 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}; +export {LINK_REDACTED, ACCOUNT_REFUSALS, account_call, account_refusal, route_missing, links_in, redact_links, add_link}; diff --git a/src/operations/account-links.ts b/src/operations/account-links.ts index 7e03276..422fe32 100644 --- a/src/operations/account-links.ts +++ b/src/operations/account-links.ts @@ -1,7 +1,6 @@ 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 {is_object, open_session, unreadable, type Answer, type Op_session} from './call'; +import {account_call, account_refusal, route_missing} from './account-call'; 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'; @@ -10,21 +9,25 @@ 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'; +// The providers a one-mailbox email link is made for. +const EMAIL_PROVIDERS = ['gmail', 'office365'] as const; +type Email_provider = typeof EMAIL_PROVIDERS[number]; + +// link_kind is always connection_link: the field is kept so a caller that reads it reads what it always read. 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; + kind: 'connect' | 'reconnect'; link_kind: 'connection_link'; }; +// allowSharedPage is accepted and ignored: the hosted mailbox page is no longer printed, and a caller that still passes +// the flag is not refused for it. Deprecated, to be removed in a later release. provider on a reconnect is ignored the +// same way: Reply takes the provider from the mailbox. 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 +// A Reply without one-mailbox email links: its route answers 404 with no code of Reply's own. Nothing else is offered. 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}.`, - }); + 'This Reply does not issue one-mailbox email connection links, so no link was made.', {status: 404}); 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); @@ -48,45 +51,12 @@ const connection_link = (channel: Account_channel, kind: 'connect' | 'reconnect' }; }; -// 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 parse_provider = (raw: string | undefined): Email_provider | undefined=>parse_choice(raw, '--provider', EMAIL_PROVIDERS); const email_only = (opts: Link_opts): void=>{ - for (const [value, flag] of [[opts.provider, '--provider'], [opts.allowSharedPage, '--allow-shared-page']] as const) + if (opts.provider !== undefined) { - if (value !== undefined && value !== false) - { - throw new UsageError(`${flag} applies to --channel email only.`, {code: 'usage.channel'}); - } + throw new UsageError('--provider applies to --channel email only.', {code: 'usage.channel'}); } }; @@ -100,41 +70,13 @@ const connect_linkedin = async(s: Op_session, g: Op_globals, name: string): Prom 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 connect_email = async(s: Op_session, g: Op_globals, provider: Email_provider, name: string | undefined): Promise=>{ 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); + throw route_missing(a) ? email_link_not_available() : account_refusal(a, 'write'); }; const handle_account_connect = async(opts: Link_opts, ctx: Cli_context, g: Op_globals): Promise=>{ @@ -158,16 +100,12 @@ const handle_account_connect = async(opts: Link_opts, ctx: Cli_context, g: Op_gl { throw new UsageError(`--name must be at most ${EMAIL_NAME_MAX} characters.`, {code: 'usage.name'}); } - if (provider === undefined && opts.allowSharedPage !== true) + if (provider === undefined) { - 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.', - }); + throw new UsageError('--provider is required for an email connection link: gmail or office365.', {code: 'usage.provider'}); } const s = await open_session(ctx, g); - print_result(await connect_email(s, g, provider, name, opts.allowSharedPage === true), g); + print_result(await connect_email(s, g, provider, name), g); }; const handle_account_reconnect = async(id_arg: string, opts: Link_opts, ctx: Cli_context, g: Op_globals): Promise=>{ @@ -190,24 +128,15 @@ const handle_account_reconnect = async(id_arg: string, opts: Link_opts, ctx: Cli 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. + // Reply takes the provider from the mailbox itself. 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); + throw route_missing(a) ? email_link_not_available() : account_refusal(a, 'write'); }; type Pending_item = { @@ -239,22 +168,14 @@ const handle_account_pending = async(opts: {channel?: string}, ctx: Cli_context, 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 + if (a.status !== 200) { - throw account_refusal(a, 'read'); + throw route_missing(a) ? email_link_not_available() : account_refusal(a, 'read'); } + items.push(...pending_items(a, 'email')); } if (only !== 'email') { @@ -265,7 +186,9 @@ const handle_account_pending = async(opts: {channel?: string}, ctx: Cli_context, } items.push(...pending_items(a, 'linkedin')); } - print_result({items, supported: unsupported.length === 0, unsupported_channels: unsupported}, g); + // supported and unsupported_channels are kept so a caller that reads them reads what it always read; a Reply + // without one-mailbox email links is refused above, so every channel listed is supported. + print_result({items, supported: true, unsupported_channels: []}, g); }; export {handle_account_connect, handle_account_reconnect, handle_account_pending}; diff --git a/src/operations/commands.ts b/src/operations/commands.ts index a6fe261..aeb81d1 100644 --- a/src/operations/commands.ts +++ b/src/operations/commands.ts @@ -1,4 +1,4 @@ -import {Command} from 'commander'; +import {Command, Option} from 'commander'; import {PROGRAM_NAME} from '../config'; import {build_context} from '../context'; import {read_op_globals} from './options'; @@ -431,12 +431,19 @@ time_zone_options(later_options(add_contact_options(contact_command.command('sen [`echo '{"subject":"Quick question","body":"

Hi Ann, does Tuesday work?

"}' | ${P} contact send-email --contact-id 456 --email-account-id 12 --message -`, piped_send('send-email', ANN_EMAIL, '{"subject":"Quick question","body":"

Hi Ann

"}', '--email-account-id 12')], ['contact.not_found', ...IMPORT_CODES, 'contact.already_held', 'email_account.not_found', 'contact.blacklisted', - 'contact.missing_variables', 'contact.rendering_failed', ...SCHEDULE_CODES, ...KEY_CODES], true, + 'contact.missing_variables', 'contact.rendering_failed', 'email.limit_reached', 'email.sending_disabled', + ...SCHEDULE_CODES, ...KEY_CODES], true, 'Result: {"status":"sent","contact_id","contact_created","message_id","sent_at","reply_status"}: sent means Reply\n' + 'accepted the email, and reply_status is Reply\'s own word for it (new or sent). message_id is Reply\'s messageId,\n' + 'null when it gives none. Reply\'s answer carries no time, so sent_at is always null; the CLI adds none of its own.\n' + 'The email is read from stdin only, so its text never sits in the argument list. The body is HTML. Without\n' - + '--send-after, Reply sends a direct email at once, outside the mailbox\'s daily limit and sending delay.\n' + + '--send-after, Reply sends a direct email at once.\n' + + 'email.limit_reached (429) is a limit Reply holds the send to: details.limit is daily, the mailbox\'s day, which\n' + + 'Reply counts in UTC, or active_contacts, the contacts the account may email in its billing period; a send for later\n' + + 'is also refused daily when the day it is due already holds as many sends as the mailbox\'s limit. retry_after\n' + + 'passes on Reply\'s Retry-After, the seconds until the limit clears, and the CLI never repeats the send itself.\n' + + 'email.sending_disabled (403) is a mailbox or team that cannot send direct emails now: the mailbox\'s daily limit\n' + + 'is 0, or the team\'s plan does not send. No wait clears it. Neither sends anything, and reply_code keeps Reply\'s code.\n' + 'Reply tracks neither links nor opens unless --track-links or --track-opens asks it to. An email sent within the\n' + 'request adds rendered_subject and rendered_body, the subject and body as Reply filled them in, when Reply gives\n' + 'them; a send held for later has neither. contact.missing_variables names the variables Reply could not fill in\n' @@ -661,29 +668,30 @@ const LINK_RULE = 'The link is a credential for whoever opens it: it is printed 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'; +// --allow-shared-page is still taken, hidden, and does nothing: the hosted mailbox page is no longer printed, and a +// caller that passes the flag is not refused for it. Deprecated, to be removed in a later release. +const ignored_shared_page = (): Option=>new Option('--allow-shared-page', 'Deprecated and ignored').hideHelp(); + +// What a link command says of a Reply that has no one-mailbox email links. +const NOT_AVAILABLE = 'email_link.not_available: this Reply\'s one-mailbox email route answers 404 with no code of Reply\'s, so it does\n' + + 'not issue such links; no link was made, and nothing else is offered.\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('--provider ', 'gmail | office365: the mailbox\'s provider (required for email)') .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') + .addOption(ignored_shared_page()) .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' + ['email_link.not_available', '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"}.\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, + + 'Without --provider, an email link is a usage error (usage.provider, exit 2).\n' + + LINK_RULE + NOT_AVAILABLE + ACCOUNT_REFUSALS, 'the link may have been made; it is listed by `account pending`')) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -693,19 +701,18 @@ account_command.command('connect') 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') + // Reply takes the provider from the mailbox: --provider is still taken on an email reconnect, hidden, and does nothing. + .addOption(new Option('--provider ', 'Ignored: Reply takes the provider from the mailbox').hideHelp()) + .addOption(ignored_shared_page()) .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', + ['email_link.not_available', '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, + + LINK_RULE + NOT_AVAILABLE + ACCOUNT_REFUSALS, 'a link may have been made')) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -715,12 +722,13 @@ account_command.command('reconnect') 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, + .addHelpText('after', help([ex('account pending'), ex('account pending --channel linkedin')], ['email_link.not_available'], 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' + + 'dropped from the answer. An entry leaves the list once the person finishes. A Reply without one-mailbox email links\n' + + 'answers email_link.not_available whenever email is read, and nothing is listed; so supported is always true and\n' + + 'unsupported_channels always empty, both kept for callers that read them.\n' + ACCOUNT_REFUSALS)) .action(run(async(cmd)=>{ const {g, ctx} = ctx_of(cmd); @@ -850,6 +858,11 @@ const DIRECT_SEND = 'Result: {"reference","channel","contact_id","state","send_a + 'the moment the send waits from: its --send-after, or now once that has passed. A Reply without this route answers\n' + 'reply.refused with status 404 and no reply_code; a reference of any other form never leaves the CLI, so that 404 means\n' + 'this Reply has no such route.\n' + + 'bounced, bounce_type and bounced_at are added only when Reply gives them: bounced is whether a bounce came back for\n' + + 'the email after it went out, false until one does and always false for LinkedIn; bounce_type is Reply\'s own word for\n' + + 'the kind of the latest bounce, as given (hard, soft, mailboxFull, unknown, ...), and bounced_at is when it came.\n' + + 'Reply leaves bounce_type and bounced_at null while bounced is false, and bounced_at null when the bounce carried no\n' + + 'date; the CLI passes on what Reply gives and checks neither.\n' + 'direct_send.not_found is a reference that Reply has no send for, a send of another team included.\n' + 'direct_send.not_owned is an email send made by a teammate this user may not act for.\n'; diff --git a/src/operations/direct-send.ts b/src/operations/direct-send.ts index bc201f2..67e9b6d 100644 --- a/src/operations/direct-send.ts +++ b/src/operations/direct-send.ts @@ -197,7 +197,42 @@ const REFUSALS: Record = { 'contact.contactTimeZoneMissing': TIME_ZONE_MISSING, }; -const LIMITS: Record = {'directLinkedIn.dailyLimitReached': 'daily', 'directLinkedIn.weeklyLimitReached': 'weekly'}; +// The allowances a send can meet, each under the code of the route that answers it, with the CLI code it maps to and the +// sentence it says. A LinkedIn account has a day and a week; a mailbox has a day, and the account a number of contacts it +// may email in its billing period. Reply sends a Retry-After with each, passed on as retry_after. +type Limit = {code: string; limit: string; title: string}; +const LIMITS: Record> = { + email: { + 'contact.dailyLimitReached': { + code: 'email.limit_reached', limit: 'daily', title: 'The mailbox reached its daily limit, so nothing was sent.', + }, + 'contact.activeContactsLimitReached': { + code: 'email.limit_reached', limit: 'active_contacts', + title: 'The account reached its active contacts limit for the billing period, so nothing was sent.', + }, + }, + linkedin: { + 'directLinkedIn.dailyLimitReached': { + code: 'linkedin.limit_reached', limit: 'daily', title: 'The LinkedIn account reached its daily limit, so nothing was sent.', + }, + 'directLinkedIn.weeklyLimitReached': { + code: 'linkedin.limit_reached', limit: 'weekly', title: 'The LinkedIn account reached its weekly limit, so nothing was sent.', + }, + }, +}; + +// The email route's refusal of a mailbox that cannot send at all: its daily limit is 0, or the team's plan sends nothing. +// No wait clears it, so Reply sends no Retry-After and none is passed on. Only the email route answers it. +const SENDING_REFUSALS: Record> = { + email: { + 'contact.emailAccountSendingDisabled': { + status: 403, code: 'email.sending_disabled', + title: 'The mailbox or its team cannot send direct emails now, so nothing was sent.', + hint: 'Reply says the mailbox\'s daily limit is 0, or the team\'s plan does not send; no retry can help until that changes.', + }, + }, + linkedin: {}, +}; // The codes of a send made for later, each Reply's code with the CLI code it maps to, here and // nowhere else. A send route answers a refused Idempotency-Key under its own family: contact for the @@ -281,15 +316,16 @@ const refusal_of_send = (a: Answer, contact_id: number, by: Channel): Operation_ { return contact_not_found(contact_id, a); } - if (a.status === 429 && reply_code !== undefined && LIMITS[reply_code] !== undefined) + const limit = a.status === 429 && reply_code !== undefined ? LIMITS[by][reply_code] : undefined; + if (limit !== undefined) { - return new Operation_error('linkedin.limit_reached', `The LinkedIn account reached its ${LIMITS[reply_code]} limit, so nothing was sent.`, { + return new Operation_error(limit.code, limit.title, { status: a.status, reply_code, detail: detail_of(a), - retry_after: parse_retry_after(a.headers['retry-after']) ?? undefined, details: {limit: LIMITS[reply_code]}, + retry_after: parse_retry_after(a.headers['retry-after']) ?? undefined, details: {limit: limit.limit}, }); } - return known_refusal(a, REFUSALS) ?? known_refusal(a, TEMPLATE_REFUSALS[by]) ?? known_refusal(a, KEY_REFUSALS[by]) - ?? refusal(a, 'write'); + return known_refusal(a, REFUSALS) ?? known_refusal(a, TEMPLATE_REFUSALS[by]) ?? known_refusal(a, SENDING_REFUSALS[by]) + ?? known_refusal(a, KEY_REFUSALS[by]) ?? refusal(a, 'write'); }; // A send Reply refused after its row existed, or the send a reused key was taken for, comes with diff --git a/src/operations/direct-sends.ts b/src/operations/direct-sends.ts index 1ddf0c9..0c96111 100644 --- a/src/operations/direct-sends.ts +++ b/src/operations/direct-sends.ts @@ -39,6 +39,15 @@ const rendering_of = (body: Record): Record=>{ return out; }; +// Whether an email bounced after it went out, Reply's word for the kind of the latest bounce, as given and never read +// here, and when it came, each only when Reply gives it in its shape: bounced as true or false, the kind and the moment +// as text or null. A Reply before them gives none, and the send prints as it did before them. +const bounce_of = (body: Record): Record=>({ + ...(typeof body.bounced === 'boolean' ? {bounced: body.bounced} : {}), + ...(typeof body.bounceType === 'string' || body.bounceType === null ? {bounce_type: body.bounceType} : {}), + ...(typeof body.bouncedAt === 'string' || body.bouncedAt === null ? {bounced_at: body.bouncedAt} : {}), +}); + // A send as Reply holds it, under the CLI's names; one of its first fields that Reply leaves out is null. Its state is Reply's word, passed on as given, so a state the CLI does // not know yet reaches the caller instead of failing the read. failure_reason is a sentence for a person and failure_code // Reply's code for the same failure: neither is read here. @@ -52,7 +61,7 @@ const direct_send_of = (a: Answer, kind: 'read' | 'write'): Record{ - 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}; diff --git a/src/utils/client.ts b/src/utils/client.ts index 693a243..1ef4e79 100644 --- a/src/utils/client.ts +++ b/src/utils/client.ts @@ -15,8 +15,9 @@ const RETRY_BASE_MS = 500; // The longest Retry-After waited out here. A longer one goes back to the caller as the 429 it // is: a wait inside one call spends a time budget the caller may not have. const MAX_WAIT_SECONDS = 3; -// The allowances a 429 can say have run out, as opposed to a pace that was too fast. -const ALLOWANCE_CODES = ['weeklyLimitReached', 'dailyLimitReached']; +// The allowances a 429 can say have run out, as opposed to a pace that was too fast: a LinkedIn +// account's week or day, a mailbox's day, and the contacts an account may email in its billing period. +const ALLOWANCE_CODES = ['weeklyLimitReached', 'dailyLimitReached', 'activeContactsLimitReached']; // Node's fetch reports every transport failure as TypeError('fetch failed') with the system // error on `.cause`. These are failures to connect at all, so the request never left: no route, // no answer to the connect, a URL that can't be parsed, or a TLS handshake that failed.