mirror of
https://github.com/warmbly/warmbly.git
synced 2026-11-28 16:06:08 +00:00
Merge pull request #1239 from warmbly/feat/connect-link-vendor
feat: let a client connect an inbox vendor account from a connect link and pick many mailboxes at once
This commit is contained in:
@@ -2129,6 +2129,10 @@ func main() {
|
|||||||
Cache: cache,
|
Cache: cache,
|
||||||
NewClient: sandboxVendors,
|
NewClient: sandboxVendors,
|
||||||
})
|
})
|
||||||
|
// A client names its own vendor account on a connect link.
|
||||||
|
if connectLinkService != nil {
|
||||||
|
connectLinkService.WireVendors(vendorConnService)
|
||||||
|
}
|
||||||
// An agency holds a vendor account once and uses it in any client workspace.
|
// An agency holds a vendor account once and uses it in any client workspace.
|
||||||
if agencyService != nil {
|
if agencyService != nil {
|
||||||
vendorConnService.WireAgencies(repository.NewAgencyVendorRepository(primaryDB), agencyService, repository.NewAgencyHomeRepository(primaryDB.Pool), credEncrypter)
|
vendorConnService.WireAgencies(repository.NewAgencyVendorRepository(primaryDB), agencyService, repository.NewAgencyHomeRepository(primaryDB.Pool), credEncrypter)
|
||||||
|
|||||||
@@ -372,7 +372,7 @@ The `/unibox/drafts` endpoints hold autosaved compose drafts, scoped to the call
|
|||||||
|
|
||||||
`POST /emails/:id/resume-sending` lifts a provider pause on the mailbox: it ends a timed pause (`rate_limited`, `daily_limit`, `sender_blocked`, `retry`) and releases a `permanent` or `domain_auth` hold. It answers `{"hold_released": bool, "cooldown_cleared": bool}`, both `false` when nothing was paused. An `authentication` hold is cleared by reconnecting the mailbox, and an unconfirmed (`unknown`) or `conflict` hold keeps its own recovery, so this leaves both in place. If the provider still refuses, the next send pauses the mailbox again. It is bodyless and idempotent, so it takes no `Idempotency-Key`. The mailbox's `send_pause` in [`GET /analytics/accounts/:id`](/api/reference/analytics/) says whether it applies (`resumable`). See [when a provider pauses sending](/guides/mailboxes/#when-a-provider-pauses-sending).
|
`POST /emails/:id/resume-sending` lifts a provider pause on the mailbox: it ends a timed pause (`rate_limited`, `daily_limit`, `sender_blocked`, `retry`) and releases a `permanent` or `domain_auth` hold. It answers `{"hold_released": bool, "cooldown_cleared": bool}`, both `false` when nothing was paused. An `authentication` hold is cleared by reconnecting the mailbox, and an unconfirmed (`unknown`) or `conflict` hold keeps its own recovery, so this leaves both in place. If the provider still refuses, the next send pauses the mailbox again. It is bodyless and idempotent, so it takes no `Idempotency-Key`. The mailbox's `send_pause` in [`GET /analytics/accounts/:id`](/api/reference/analytics/) says whether it applies (`resumable`). See [when a provider pauses sending](/guides/mailboxes/#when-a-provider-pauses-sending).
|
||||||
|
|
||||||
The `/emails/client-links` routes manage [client connect links](/guides/agencies/#client-connect-links), each with JWT permission `MANAGE_EMAILS`. `POST /emails/client-links` takes `label` (optional), `providers` (any of `gmail`, `outlook`, `smtp_imap`), `max_mailboxes` (1 to 500), `expires_in_days` (1 to 90, default 7), `tag_ids` (up to 20 of the workspace's mailbox tags) and `warmup`, and answers `201` with the `link` and its `url`, on the agency's verified portal domain when it has one, else on `PORTAL_DOMAIN` (`503 client_links_unavailable` without it). The URL appears in that response only; send an `Idempotency-Key` so a retry replays it instead of minting a second link. `GET /emails/connect-links` lists links newest first with their `status` (`active`, `expired`, `revoked`, `exhausted`) and `mailboxes_connected`, paginated with `cursor` and `limit` (1 to 100). `GET /emails/connect-links/:id/uses` lists the mailboxes a link connected. `POST /emails/connect-links/:id/revoke` turns a link off; a repeat returns the revoked link, so it needs no `Idempotency-Key`.
|
The `/emails/client-links` routes manage [client connect links](/guides/agencies/#client-connect-links), each with JWT permission `MANAGE_EMAILS`. `POST /emails/client-links` takes `label` (optional), `providers` (any of `gmail`, `outlook`, `smtp_imap` and `vendor`, an [inbox vendor account](/guides/agencies/#client-connect-links) the client names), `max_mailboxes` (1 to 500), `expires_in_days` (1 to 90, default 7), `tag_ids` (up to 20 of the workspace's mailbox tags) and `warmup`, and answers `201` with the `link` and its `url`, on the agency's verified portal domain when it has one, else on `PORTAL_DOMAIN` (`503 client_links_unavailable` without it). The URL appears in that response only; send an `Idempotency-Key` so a retry replays it instead of minting a second link. `GET /emails/connect-links` lists links newest first with their `status` (`active`, `expired`, `revoked`, `exhausted`) and `mailboxes_connected`, paginated with `cursor` and `limit` (1 to 100). `GET /emails/connect-links/:id/uses` lists the mailboxes a link connected. `POST /emails/connect-links/:id/revoke` turns a link off; a repeat returns the revoked link, so it needs no `Idempotency-Key`.
|
||||||
|
|
||||||
`GET /emails/allowance` reports how many mailboxes the workspace holds (`used`), how many it may hold (`allowance`, `null` for unlimited), `remaining`, and the `basis` of the number: `fair_use` (the plan's daily sends divided by `sends_per_mailbox`), `plan`, `override` (an approved request), `free` (no paid plan: `0`, or `10` for a workspace that kept the earlier free plan), or `unlimited`. `pending_request` is the open limit-increase request for mailboxes, if any. Every connect path refuses with `mailbox_allowance_reached` once `remaining` is `0`. See [mailbox allowance](/guides/mailboxes/#mailbox-allowance).
|
`GET /emails/allowance` reports how many mailboxes the workspace holds (`used`), how many it may hold (`allowance`, `null` for unlimited), `remaining`, and the `basis` of the number: `fair_use` (the plan's daily sends divided by `sends_per_mailbox`), `plan`, `override` (an approved request), `free` (no paid plan: `0`, or `10` for a workspace that kept the earlier free plan), or `unlimited`. `pending_request` is the open limit-increase request for mailboxes, if any. Every connect path refuses with `mailbox_allowance_reached` once `remaining` is `0`. See [mailbox allowance](/guides/mailboxes/#mailbox-allowance).
|
||||||
|
|
||||||
@@ -949,7 +949,7 @@ A key passes the recent-confirmation check the session routes ask for, since it
|
|||||||
| POST | `/agency/:agencyId/vendors` | Owner, admin, session only: `vendor`, `fields` (its API key) and an optional `label`. The key is verified with the vendor before it is stored. Accepts `Idempotency-Key`: send the same key again on a retry, or an account is connected twice |
|
| POST | `/agency/:agencyId/vendors` | Owner, admin, session only: `vendor`, `fields` (its API key) and an optional `label`. The key is verified with the vendor before it is stored. Accepts `Idempotency-Key`: send the same key again on a retry, or an account is connected twice |
|
||||||
| PATCH | `/agency/:agencyId/vendors/:id` | Owner, admin, session only: `label`, and `fields` to replace the key, which every client that uses the account reads from then on |
|
| PATCH | `/agency/:agencyId/vendors/:id` | Owner, admin, session only: `label`, and `fields` to replace the key, which every client that uses the account reads from then on |
|
||||||
| DELETE | `/agency/:agencyId/vendors/:id` | Owner, admin, session only: forgets the key in the agency and in every client. Mailboxes it connected stay |
|
| DELETE | `/agency/:agencyId/vendors/:id` | Owner, admin, session only: forgets the key in the agency and in every client. Mailboxes it connected stay |
|
||||||
| PUT | `/agency/:agencyId/vendors/:id/clients/:orgId` | Staff who manage mailboxes in that client, session only: the client workspace's connection to the account, made the first time, as a vendor connection to import from under `/emails/vendors/:id`. It holds no key of its own. `404 agency_client_not_found` for a workspace that is not a client, `403 agency_client_mailboxes_forbidden` without **Manage mailboxes** there |
|
| PUT | `/agency/:agencyId/vendors/:id/clients/:orgId` | Staff who manage mailboxes in that client, session only: the client workspace's connection to the account, made the first time, as a vendor connection. Its `id` in the answer, not the account's, is the `:id` to import from under `/emails/vendors/:id`. It holds no key of its own. `404 agency_client_not_found` for a workspace that is not a client, `403 agency_client_mailboxes_forbidden` without **Manage mailboxes** there |
|
||||||
| PUT | `/agency/:agencyId/brand/domain` | Owner, admin: `domain`, the portal host every client's links are built on (empty clears it); resolves it as part of saving. A malformed host answers `400 invalid_portal_domain`, one another workspace or agency holds `409 portal_domain_taken` |
|
| PUT | `/agency/:agencyId/brand/domain` | Owner, admin: `domain`, the portal host every client's links are built on (empty clears it); resolves it as part of saving. A malformed host answers `400 invalid_portal_domain`, one another workspace or agency holds `409 portal_domain_taken` |
|
||||||
| POST | `/agency/:agencyId/brand/domain/verify` | Owner, admin: re-resolves the portal host |
|
| POST | `/agency/:agencyId/brand/domain/verify` | Owner, admin: re-resolves the portal host |
|
||||||
| GET | `/agency/:agencyId/api-keys` | Owner, admin: the agency's [API keys](/api/authentication/#agency-api-keys), newest first, as `data` plus `pagination` (`cursor`, `limit` 1 to 100) |
|
| GET | `/agency/:agencyId/api-keys` | Owner, admin: the agency's [API keys](/api/authentication/#agency-api-keys), newest first, as `data` plus `pagination` (`cursor`, `limit` 1 to 100) |
|
||||||
|
|||||||
@@ -1625,7 +1625,7 @@ use generic errors and explicit unavailable/stale coverage, not outage inference
|
|||||||
|
|
||||||
| `code` | Status | Meaning |
|
| `code` | Status | Meaning |
|
||||||
|--------|--------|---------|
|
|--------|--------|---------|
|
||||||
| `client_link_invalid_providers` | 400 | `providers` is empty or names something other than `gmail`, `outlook` and `smtp_imap` |
|
| `client_link_invalid_providers` | 400 | `providers` is empty or names something other than `gmail`, `outlook`, `smtp_imap` and `vendor` |
|
||||||
| `client_link_invalid_max_mailboxes` | 400 | `max_mailboxes` is outside 1 to 500 |
|
| `client_link_invalid_max_mailboxes` | 400 | `max_mailboxes` is outside 1 to 500 |
|
||||||
| `client_link_invalid_expiry` | 400 | `expires_in_days` is outside 1 to 90 |
|
| `client_link_invalid_expiry` | 400 | `expires_in_days` is outside 1 to 90 |
|
||||||
| `client_link_invalid_tags` | 400 | More than 20 `tag_ids` |
|
| `client_link_invalid_tags` | 400 | More than 20 `tag_ids` |
|
||||||
@@ -1644,7 +1644,10 @@ The client's connect page shows these, each in its own words:
|
|||||||
| `client_link_provider_unavailable` | 400 | That sign-in is not configured on this instance |
|
| `client_link_provider_unavailable` | 400 | That sign-in is not configured on this instance |
|
||||||
| `client_link_signin_expired` | 400 | The provider sign-in took longer than 10 minutes or was already used |
|
| `client_link_signin_expired` | 400 | The provider sign-in took longer than 10 minutes or was already used |
|
||||||
| `client_link_signin_declined` | 400 | The client cancelled the sign-in at the provider |
|
| `client_link_signin_declined` | 400 | The client cancelled the sign-in at the provider |
|
||||||
| `client_link_captcha_failed` | 400 | The security check on the server-details form did not pass |
|
| `client_link_captcha_failed` | 400 | The security check on the server-details or vendor account form did not pass |
|
||||||
|
| `client_link_no_mailboxes` | 400 | A client started a vendor import through a connect link without picking a mailbox, or none of the ones picked is in the account any more |
|
||||||
|
| `client_link_too_many_mailboxes` | 409 | A client picked more vendor mailboxes than the connect link still allows |
|
||||||
|
| `mailbox_vendor_hold_expired` | 400 | The ticket a connect page holds for a client's vendor key was already used or is older than 15 minutes. The client enters the key again |
|
||||||
| `client_link_rate_limited` | 429 | Too many attempts through this link in the last hour |
|
| `client_link_rate_limited` | 429 | Too many attempts through this link in the last hour |
|
||||||
|
|
||||||
A workspace at its mailbox allowance refuses the connect with the usual `mailbox_allowance_reached`, which the page words for the client.
|
A workspace at its mailbox allowance refuses the connect with the usual `mailbox_allowance_reached`, which the page words for the client.
|
||||||
|
|||||||
@@ -181,6 +181,7 @@ Three things a workspace can set up alongside its mailboxes, each kept until the
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `mailbox_vendor_connections` | An [inbox vendor](/guides/mailbox-import/#import-from-an-inbox-vendor) account: which vendor, a label, its status and last error | The API key and account IDs, sealed with the workspace's data key. No response returns them |
|
| `mailbox_vendor_connections` | An [inbox vendor](/guides/mailbox-import/#import-from-an-inbox-vendor) account: which vendor, a label, its status and last error | The API key and account IDs, sealed with the workspace's data key. No response returns them |
|
||||||
| `agency_vendor_connections` | An inbox vendor account [an agency holds](/guides/agencies/#vendor-accounts-held-by-the-agency) for its clients: which vendor and a label | The API key and account IDs, sealed with `CREDENTIALS_ENCRYPTION_KEY` (an agency has no data key of its own). A client workspace that uses the account gets a `mailbox_vendor_connections` row that names it and holds no key: the key is read through the account, and only while the workspace is the agency's client. No response returns them |
|
| `agency_vendor_connections` | An inbox vendor account [an agency holds](/guides/agencies/#vendor-accounts-held-by-the-agency) for its clients: which vendor and a label | The API key and account IDs, sealed with `CREDENTIALS_ENCRYPTION_KEY` (an agency has no data key of its own). A client workspace that uses the account gets a `mailbox_vendor_connections` row that names it and holds no key: the key is read through the account, and only while the workspace is the agency's client. No response returns them |
|
||||||
|
| Cache: `mailbox_vendor_hold:*` | A vendor key a client typed on a [connect link](/guides/agencies/#client-connect-links), for up to 15 minutes while the client picks mailboxes | The key and account IDs, sealed with the workspace's data key, bound to the workspace and the link, read once and then deleted |
|
||||||
| `mailbox_domain_grants` | A [Google Workspace or Microsoft 365 admin grant](/guides/mailbox-import/#connect-a-whole-google-workspace-domain): the provider, the Workspace domain or Microsoft tenant ID, the domains it covers, and for Google the admin address used to read the directory | None. No token is stored for a grant or for any mailbox it connected; the backend mints a short-lived one from the instance's own Google service account or Microsoft app each time a worker needs it |
|
| `mailbox_domain_grants` | A [Google Workspace or Microsoft 365 admin grant](/guides/mailbox-import/#connect-a-whole-google-workspace-domain): the provider, the Workspace domain or Microsoft tenant ID, the domains it covers, and for Google the admin address used to read the directory | None. No token is stored for a grant or for any mailbox it connected; the backend mints a short-lived one from the instance's own Google service account or Microsoft app each time a worker needs it |
|
||||||
| `domain_redirects` | A [root redirect](/guides/sending-domains/#root-redirects): the domain, the website it sends visitors to, the ownership value for its `_warmbly` `TXT` record, the result of the last DNS check and of the last visit to the domain (what answered, and the proxy when it named itself), and whether this instance or Warmbly Cloud serves it. For one Cloud serves, a copy of the records and the tracking host Cloud listed | None. The ownership value is derived from `AUTH_SECRET`, the workspace and the domain, so it stays the same for that workspace and differs for every other workspace and instance |
|
| `domain_redirects` | A [root redirect](/guides/sending-domains/#root-redirects): the domain, the website it sends visitors to, the ownership value for its `_warmbly` `TXT` record, the result of the last DNS check and of the last visit to the domain (what answered, and the proxy when it named itself), and whether this instance or Warmbly Cloud serves it. For one Cloud serves, a copy of the records and the tracking host Cloud listed | None. The ownership value is derived from `AUTH_SECRET`, the workspace and the domain, so it stays the same for that workspace and differs for every other workspace and instance |
|
||||||
|
|
||||||
|
|||||||
@@ -207,7 +207,7 @@ Either of you can. Some clients run their own inboxes; for others you buy and ma
|
|||||||
| **From an inbox vendor** | You | Paste an API key for this client only and pick the mailboxes. See [import from an inbox vendor](/guides/mailbox-import/#import-from-an-inbox-vendor) |
|
| **From an inbox vendor** | You | Paste an API key for this client only and pick the mailboxes. See [import from an inbox vendor](/guides/mailbox-import/#import-from-an-inbox-vendor) |
|
||||||
| **Import a file or a list** | You | A spreadsheet from a vendor or another tool, or addresses and passwords pasted in. See [import mailboxes](/guides/mailbox-import/) |
|
| **Import a file or a list** | You | A spreadsheet from a vendor or another tool, or addresses and passwords pasted in. See [import mailboxes](/guides/mailbox-import/) |
|
||||||
| **Connect one yourself** | You | Google or Microsoft sign-in, or IMAP and SMTP details |
|
| **Connect one yourself** | You | Google or Microsoft sign-in, or IMAP and SMTP details |
|
||||||
| **Let the client do it** | The client | A [connect link](#client-connect-links): the client connects its own mailboxes with no account, and no password reaches you |
|
| **Let the client do it** | The client | A [connect link](#client-connect-links): the client connects its own mailboxes with no account, one at a time or many at once from its own vendor account, and no password reaches you |
|
||||||
|
|
||||||
Each one opens inside that client's workspace, in the same dialog its own **Accounts** page uses, so warmup, limits and the [mailbox allowance](/guides/mailboxes/#mailbox-allowance) apply exactly as they do there.
|
Each one opens inside that client's workspace, in the same dialog its own **Accounts** page uses, so warmup, limits and the [mailbox allowance](/guides/mailboxes/#mailbox-allowance) apply exactly as they do there.
|
||||||
|
|
||||||
@@ -227,13 +227,14 @@ The accounts are listed with `GET /agency/:agencyId/vendors` and connected with
|
|||||||
|
|
||||||
## Client connect links
|
## Client connect links
|
||||||
|
|
||||||
Stop asking clients for their mailbox passwords. In a client's workspace, open **Mailboxes** and choose **Invite client to connect**. Pick how the client may connect (Google sign-in, Microsoft sign-in, IMAP and SMTP details, or any of them), how many mailboxes the link connects (up to 500), when it expires (1, 7, 30 or 90 days), the tags each mailbox gets, and whether warmup starts as soon as it connects. A label you give the link is only for your team.
|
Stop asking clients for their mailbox passwords. In a client's workspace, open **Mailboxes** and choose **Invite client to connect**. Pick how the client may connect (Google sign-in, Microsoft sign-in, IMAP and SMTP details, an inbox vendor account, or any of them), how many mailboxes the link connects (up to 500), when it expires (1, 7, 30 or 90 days), the tags each mailbox gets, and whether warmup starts as soon as it connects. A label you give the link is only for your team.
|
||||||
|
|
||||||
The link is shown once. Copy it and send it to the client; Warmbly keeps only a fingerprint of it, so a lost link cannot be shown again. Revoke it and make a new one instead.
|
The link is shown once. Copy it and send it to the client; Warmbly keeps only a fingerprint of it, so a lost link cannot be shown again. Revoke it and make a new one instead.
|
||||||
|
|
||||||
The client needs no Warmbly account. The page shows the workspace's name and brand, and:
|
The client needs no Warmbly account. The page shows the workspace's name and brand, and:
|
||||||
|
|
||||||
- **Google or Microsoft**: the client signs in with their provider in a separate window and approves Warmbly there. Their password goes only to Google or Microsoft.
|
- **Google or Microsoft**: the client signs in with their provider in a separate window and approves Warmbly there. Their password goes only to Google or Microsoft.
|
||||||
|
- **Inbox vendor account**: for a client who bought its mailboxes from Zapmail, InboxKit or another [supported vendor](/guides/mailbox-import/#import-from-an-inbox-vendor). The client picks the vendor, pastes the account's API key, passes a security check, and sees the account's mailboxes with the ones already connected marked. It ticks the ones to connect, up to what the link still allows, and they are imported together in the background. The key is sent once and never returned to the page: it is checked with the vendor, held encrypted for up to 15 minutes while the client picks, and then kept as a vendor account of the workspace, named after the vendor with **(from a client)**, so rotated passwords are picked up later. Every mailbox the client picks counts toward the link when the import starts, including one that later fails to connect, and rows that need you are listed under **Imports** in the workspace.
|
||||||
- **IMAP and SMTP**: the client picks their mail host from a list (Gmail with an app password, Microsoft 365, Zoho, Yahoo, iCloud, Fastmail, GoDaddy) or enters the servers, passes a security check, and the details are tested against their mail server before anything is saved. The password is stored encrypted and nobody in the workspace can read it.
|
- **IMAP and SMTP**: the client picks their mail host from a list (Gmail with an app password, Microsoft 365, Zoho, Yahoo, iCloud, Fastmail, GoDaddy) or enters the servers, passes a security check, and the details are tested against their mail server before anything is saved. The password is stored encrypted and nobody in the workspace can read it.
|
||||||
|
|
||||||
Each mailbox lands in the workspace exactly as if you connected it, counted against the workspace's [mailbox allowance](/guides/mailboxes/#mailbox-allowance), and in your name: you get a notification each time one connects, and the mailbox list updates for the whole team. When the link reaches its limit the client sees that it is complete; a link that expired or was revoked tells them to ask for a new one, and one whose workspace is full tells them to let you know.
|
Each mailbox lands in the workspace exactly as if you connected it, counted against the workspace's [mailbox allowance](/guides/mailboxes/#mailbox-allowance), and in your name: you get a notification each time one connects, and the mailbox list updates for the whole team. When the link reaches its limit the client sees that it is complete; a link that expired or was revoked tells them to ask for a new one, and one whose workspace is full tells them to let you know.
|
||||||
|
|||||||
@@ -342,7 +342,7 @@ See [Import mailboxes](/guides/mailbox-import/) for the columns, what each provi
|
|||||||
|
|
||||||
## Letting a client connect their own mailboxes
|
## Letting a client connect their own mailboxes
|
||||||
|
|
||||||
When the mailboxes belong to someone else, such as a client, choose **Invite client to connect** on the Mailboxes page instead of asking for their passwords. You get a link to send them; they open it, sign in with Google or Microsoft or enter their server details, and each mailbox lands in this workspace with the tags and warmup setting you chose. Nobody shares a password with you, and you are notified each time one connects.
|
When the mailboxes belong to someone else, such as a client, choose **Invite client to connect** on the Mailboxes page instead of asking for their passwords. You get a link to send them; they open it, sign in with Google or Microsoft, enter their server details or connect their inbox vendor account and pick many at once, and each mailbox lands in this workspace with the tags and warmup setting you chose. Nobody shares a password with you, and you are notified each time one connects.
|
||||||
|
|
||||||
See [client connect links](/guides/agencies/#client-connect-links) for what the link allows, how long it lasts and how to revoke it.
|
See [client connect links](/guides/agencies/#client-connect-links) for what the link allows, how long it lasts and how to revoke it.
|
||||||
|
|
||||||
|
|||||||
@@ -166,7 +166,7 @@ Put `data-warmbly-connect="CONNECT_TOKEN"` on the tag instead for a connect page
|
|||||||
<iframe src="https://portal.youragency.com/r/REPORT_TOKEN?embed=1" title="Report" style="width:100%;min-height:720px;border:0"></iframe>
|
<iframe src="https://portal.youragency.com/r/REPORT_TOKEN?embed=1" title="Report" style="width:100%;min-height:720px;border:0"></iframe>
|
||||||
```
|
```
|
||||||
|
|
||||||
After each mailbox connects, the page fires a `warmbly:connected` event on `document`, with the link's connected count in `detail.connected`.
|
After each mailbox connects, the page fires a `warmbly:connected` event on `document`, with the link's connected count in `detail.connected`. When a client starts an import from an inbox vendor account, it fires `warmbly:importing` instead, with the number of mailboxes on their way in `detail.mailboxes` and the link's count in `detail.connected`; those mailboxes connect in the background and fire nothing more.
|
||||||
|
|
||||||
<Callout type="warn" title="The token is the key">
|
<Callout type="warn" title="The token is the key">
|
||||||
A connect link or a report link needs no sign-in: its token is the whole authorisation. A report embedded on a public page can be read by anyone who visits it, and a connect page embedded on a public page lets anyone connect a mailbox while the link is live. Embed them on pages only your client can reach, and revoke a link to take it down everywhere at once.
|
A connect link or a report link needs no sign-in: its token is the whole authorisation. A report embedded on a public page can be read by anyone who visits it, and a connect page embedded on a public page lets anyone connect a mailbox while the link is live. Embed them on pages only your client can reach, and revoke a link to take it down everywhere at once.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
@@ -151,6 +152,56 @@ func (h *Handler) InternalConnectSMTPIMAP(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InternalConnectVendorMailboxes is POST /api/v1/internal/connect-links/vendor/mailboxes: check a client's vendor key and list what it reaches.
|
||||||
|
func (h *Handler) InternalConnectVendorMailboxes(c *gin.Context) {
|
||||||
|
var req formwire.ConnectVendorAccount
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
connectRefusal(c, errx.New(errx.BadRequest, "The request could not be read."))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
link, ok := h.connectLinkOn(c, req.Token, req.Host)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, xerr := h.ConnectLinkService.VendorMailboxes(c.Request.Context(), link, connectlink.VendorAccountInput{
|
||||||
|
Vendor: req.Vendor, Fields: req.Fields, CaptchaToken: req.CaptchaToken, RemoteIP: req.RemoteIP,
|
||||||
|
})
|
||||||
|
if xerr != nil {
|
||||||
|
connectRefusal(c, xerr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// InternalConnectVendorImport is POST /api/v1/internal/connect-links/vendor/import: connect the mailboxes a client picked.
|
||||||
|
func (h *Handler) InternalConnectVendorImport(c *gin.Context) {
|
||||||
|
var req formwire.ConnectVendorImport
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
connectRefusal(c, errx.New(errx.BadRequest, "The request could not be read."))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
link, ok := h.connectLinkOn(c, req.Token, req.Host)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res, xerr := h.ConnectLinkService.VendorImport(c.Request.Context(), link, connectlink.VendorImportInput{
|
||||||
|
Ticket: req.Ticket, MailboxIDs: req.MailboxIDs, RemoteIP: req.RemoteIP,
|
||||||
|
})
|
||||||
|
if xerr != nil {
|
||||||
|
connectRefusal(c, xerr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// The import records its own creation; this records what the link was used for, in the creator's name.
|
||||||
|
if h.AuditService != nil && res.Import != nil {
|
||||||
|
meta := map[string]string{"via": "connect_link", "import_id": res.Import.ID.String(), "vendor": res.Vendor, "mailboxes": strconv.Itoa(len(res.Emails))}
|
||||||
|
h.AuditService.LogAction(c.Request.Context(), res.Link.OrganizationID, res.ActorID, models.AuditActionUpdate, models.AuditEntityClientConnectLink, &res.Link.ID,
|
||||||
|
req.RemoteIP, c.Request.UserAgent(), nil, meta)
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusCreated, formwire.ConnectVendorStarted{
|
||||||
|
Mailboxes: len(res.Emails), Connected: res.Link.MailboxesConnected, MaxMailboxes: res.Link.MaxMailboxes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
// auditConnectLinkUse records the connect in the creator's name, which is what refreshes every teammate's mailbox list.
|
// auditConnectLinkUse records the connect in the creator's name, which is what refreshes every teammate's mailbox list.
|
||||||
func (h *Handler) auditConnectLinkUse(c *gin.Context, res *connectlink.Result, remoteIP string) {
|
func (h *Handler) auditConnectLinkUse(c *gin.Context, res *connectlink.Result, remoteIP string) {
|
||||||
acc := res.Account
|
acc := res.Account
|
||||||
|
|||||||
@@ -281,6 +281,8 @@ func Run(
|
|||||||
portal.POST("/connect-links/oauth/start", h.InternalStartConnectOAuth)
|
portal.POST("/connect-links/oauth/start", h.InternalStartConnectOAuth)
|
||||||
portal.POST("/connect-links/oauth/result", h.InternalConnectOAuthResult)
|
portal.POST("/connect-links/oauth/result", h.InternalConnectOAuthResult)
|
||||||
portal.POST("/connect-links/smtp-imap", h.InternalConnectSMTPIMAP)
|
portal.POST("/connect-links/smtp-imap", h.InternalConnectSMTPIMAP)
|
||||||
|
portal.POST("/connect-links/vendor/mailboxes", h.InternalConnectVendorMailboxes)
|
||||||
|
portal.POST("/connect-links/vendor/import", h.InternalConnectVendorImport)
|
||||||
}
|
}
|
||||||
|
|
||||||
corsConfig := cors.Config{
|
corsConfig := cors.Config{
|
||||||
|
|||||||
@@ -30,11 +30,15 @@ var (
|
|||||||
ErrUnavailable = errx.NewWithIdentifier(errx.ServiceUnavailable, "client_links_unavailable",
|
ErrUnavailable = errx.NewWithIdentifier(errx.ServiceUnavailable, "client_links_unavailable",
|
||||||
"Client connect links need the portal service. Set PORTAL_DOMAIN on this instance and run the portal service.")
|
"Client connect links need the portal service. Set PORTAL_DOMAIN on this instance and run the portal service.")
|
||||||
ErrInvalidProviders = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_providers",
|
ErrInvalidProviders = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_providers",
|
||||||
"Choose at least one of gmail, outlook and smtp_imap.")
|
"Choose at least one of gmail, outlook, smtp_imap and vendor.")
|
||||||
ErrInvalidMax = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_max_mailboxes",
|
ErrInvalidMax = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_max_mailboxes",
|
||||||
"max_mailboxes must be between 1 and 500.")
|
"max_mailboxes must be between 1 and 500.")
|
||||||
ErrInvalidExpiry = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_expiry",
|
ErrInvalidExpiry = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_expiry",
|
||||||
"expires_in_days must be between 1 and 90.")
|
"expires_in_days must be between 1 and 90.")
|
||||||
|
ErrNoMailboxes = errx.NewWithIdentifier(errx.BadRequest, "client_link_no_mailboxes",
|
||||||
|
"Pick at least one mailbox to connect.")
|
||||||
|
ErrTooManyMailboxes = errx.NewWithIdentifier(errx.Conflict, "client_link_too_many_mailboxes",
|
||||||
|
"This link cannot connect that many mailboxes. Pick fewer, or ask whoever sent it for a link that takes more.")
|
||||||
ErrTooManyTags = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_tags",
|
ErrTooManyTags = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_tags",
|
||||||
"A link can apply at most 20 tags.")
|
"A link can apply at most 20 tags.")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -83,8 +83,13 @@ type Deps struct {
|
|||||||
// BaseURL is the origin a workspace's connect pages are served on; nil is the shared portal address.
|
// BaseURL is the origin a workspace's connect pages are served on; nil is the shared portal address.
|
||||||
BaseURL func(ctx context.Context, orgID uuid.UUID) string
|
BaseURL func(ctx context.Context, orgID uuid.UUID) string
|
||||||
Now func() time.Time
|
Now func() time.Time
|
||||||
|
// Vendors connects an inbox vendor account a client names; nil leaves that way in off.
|
||||||
|
Vendors Vendors
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WireVendors turns on connecting an inbox vendor account from a link; the two services are built apart.
|
||||||
|
func (s *Service) WireVendors(v Vendors) { s.d.Vendors = v }
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
d Deps
|
d Deps
|
||||||
states stateStore
|
states stateStore
|
||||||
@@ -284,9 +289,12 @@ func (s *Service) Page(ctx context.Context, link *models.ClientConnectLink) *for
|
|||||||
if a, xerr := s.d.Workspaces.MailboxAllowance(ctx, orgID); xerr == nil && a != nil && !a.CanAdd(1) {
|
if a, xerr := s.d.Workspaces.MailboxAllowance(ctx, orgID); xerr == nil && a != nil && !a.CanAdd(1) {
|
||||||
out.WorkspaceFull = true
|
out.WorkspaceFull = true
|
||||||
}
|
}
|
||||||
if s.d.Captcha != nil && config.CaptchaProvider() != "none" && link.Allows(models.InboxProviderSMTPIMAP) {
|
if s.d.Captcha != nil && config.CaptchaProvider() != "none" && (link.Allows(models.InboxProviderSMTPIMAP) || link.Allows(models.ConnectLinkVendor)) {
|
||||||
out.CaptchaSiteKey = config.TurnstileSiteKey()
|
out.CaptchaSiteKey = config.TurnstileSiteKey()
|
||||||
}
|
}
|
||||||
|
if link.Allows(models.ConnectLinkVendor) && s.d.Vendors != nil {
|
||||||
|
out.Vendors = s.vendorCatalog()
|
||||||
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,6 +313,8 @@ func (s *Service) providerAvailable(p models.InboxProvider) bool {
|
|||||||
switch p {
|
switch p {
|
||||||
case models.InboxProviderSMTPIMAP:
|
case models.InboxProviderSMTPIMAP:
|
||||||
return true
|
return true
|
||||||
|
case models.ConnectLinkVendor:
|
||||||
|
return s.d.Vendors != nil
|
||||||
case models.InboxProviderGoogle:
|
case models.InboxProviderGoogle:
|
||||||
if !config.GoogleOAuthConnect() {
|
if !config.GoogleOAuthConnect() {
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
package connectlink
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sort"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
"github.com/warmbly/warmbly/internal/app/vendorconn"
|
||||||
|
"github.com/warmbly/warmbly/internal/errx"
|
||||||
|
"github.com/warmbly/warmbly/internal/formwire"
|
||||||
|
"github.com/warmbly/warmbly/internal/models"
|
||||||
|
"github.com/warmbly/warmbly/internal/pkg/displayname"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A client who bought mailboxes from an inbox vendor connects the vendor account from the link
|
||||||
|
// instead of one mailbox at a time. Two steps, so the key is typed once and never returned:
|
||||||
|
// the key is checked and its mailboxes listed while it is held sealed under a ticket, then the
|
||||||
|
// mailboxes the client picks are imported in the creator's name, exactly as the dashboard's
|
||||||
|
// vendor import would.
|
||||||
|
|
||||||
|
// Vendors is the slice of the vendor connection service a link needs.
|
||||||
|
type Vendors interface {
|
||||||
|
Catalog() []vendorconn.Vendor
|
||||||
|
Hold(ctx context.Context, orgID uuid.UUID, scope string, in vendorconn.CreateInput) (string, []models.VendorMailbox, *errx.Error)
|
||||||
|
Redeem(ctx context.Context, orgID uuid.UUID, scope, ticket string) (*vendorconn.CreateInput, *errx.Error)
|
||||||
|
Create(ctx context.Context, orgID, userID uuid.UUID, in vendorconn.CreateInput) (*models.VendorConnection, *errx.Error)
|
||||||
|
ImportPicked(ctx context.Context, orgID, userID, id uuid.UUID, in vendorconn.ImportInput, limit ...int) (*models.MailboxImport, []string, *errx.Error)
|
||||||
|
Delete(ctx context.Context, orgID, id uuid.UUID) *errx.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) vendorCatalog() []formwire.ConnectVendor {
|
||||||
|
list := s.d.Vendors.Catalog()
|
||||||
|
out := make([]formwire.ConnectVendor, 0, len(list))
|
||||||
|
for _, v := range list {
|
||||||
|
cv := formwire.ConnectVendor{ID: v.ID, Label: v.Label, KeyHelpURL: v.KeyHelpURL}
|
||||||
|
for _, f := range v.Fields {
|
||||||
|
cv.Fields = append(cv.Fields, formwire.ConnectVendorField{Key: f.Key, Label: f.Label, Secret: f.Secret, Required: f.Required, Help: f.Help})
|
||||||
|
}
|
||||||
|
out = append(out, cv)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// VendorAccountInput is a vendor key a client typed, with the signals only the portal service sees.
|
||||||
|
type VendorAccountInput struct {
|
||||||
|
Vendor string
|
||||||
|
Fields map[string]string
|
||||||
|
CaptchaToken string
|
||||||
|
RemoteIP string
|
||||||
|
}
|
||||||
|
|
||||||
|
// VendorMailboxes checks a client's vendor key and lists what it reaches. The key stays on the server under the ticket.
|
||||||
|
func (s *Service) VendorMailboxes(ctx context.Context, link *models.ClientConnectLink, in VendorAccountInput) (*formwire.ConnectVendorMailboxes, *errx.Error) {
|
||||||
|
if s.d.Captcha != nil {
|
||||||
|
if xerr := s.d.Captcha.Verify(ctx, in.CaptchaToken, in.RemoteIP); xerr != nil {
|
||||||
|
return nil, ErrCaptcha
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if xerr := s.admit(ctx, link, models.ConnectLinkVendor); xerr != nil {
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
ticket, boxes, xerr := s.d.Vendors.Hold(ctx, link.OrganizationID, link.ID.String(), vendorconn.CreateInput{Vendor: in.Vendor, Fields: in.Fields})
|
||||||
|
if xerr != nil {
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
out := &formwire.ConnectVendorMailboxes{
|
||||||
|
Ticket: ticket, Vendor: in.Vendor, Remaining: link.MaxMailboxes - link.MailboxesConnected,
|
||||||
|
Mailboxes: make([]formwire.ConnectVendorMailbox, 0, len(boxes)),
|
||||||
|
}
|
||||||
|
for _, m := range boxes {
|
||||||
|
out.Mailboxes = append(out.Mailboxes, formwire.ConnectVendorMailbox{ID: m.ID, Email: m.Email, Name: m.Name, Provider: m.Provider, Connected: m.Connected})
|
||||||
|
}
|
||||||
|
sort.SliceStable(out.Mailboxes, func(i, j int) bool { return out.Mailboxes[i].Email < out.Mailboxes[j].Email })
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VendorImportInput picks mailboxes from the account a ticket holds.
|
||||||
|
type VendorImportInput struct {
|
||||||
|
Ticket string
|
||||||
|
MailboxIDs []string
|
||||||
|
RemoteIP string
|
||||||
|
}
|
||||||
|
|
||||||
|
// VendorResult is an import a client started through a link.
|
||||||
|
type VendorResult struct {
|
||||||
|
Link *models.ClientConnectLink
|
||||||
|
ActorID uuid.UUID
|
||||||
|
Import *models.MailboxImport
|
||||||
|
Vendor string
|
||||||
|
Emails []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// VendorImport connects the mailboxes a client picked. Their slots on the link are taken before
|
||||||
|
// anything is imported and are kept even for a mailbox that later fails to connect, so a link is
|
||||||
|
// never good for more attempts than it allows.
|
||||||
|
func (s *Service) VendorImport(ctx context.Context, link *models.ClientConnectLink, in VendorImportInput) (*VendorResult, *errx.Error) {
|
||||||
|
if xerr := s.admit(ctx, link, models.ConnectLinkVendor); xerr != nil {
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
ids := make([]string, 0, len(in.MailboxIDs))
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, id := range in.MailboxIDs {
|
||||||
|
if id != "" && !seen[id] {
|
||||||
|
seen[id] = true
|
||||||
|
ids = append(ids, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return nil, ErrNoMailboxes
|
||||||
|
}
|
||||||
|
// Refused before the ticket is spent, so picking fewer needs no key again.
|
||||||
|
if len(ids) > link.MaxMailboxes-link.MailboxesConnected {
|
||||||
|
return nil, ErrTooManyMailboxes
|
||||||
|
}
|
||||||
|
orgID := link.OrganizationID
|
||||||
|
if a, xerr := s.d.Workspaces.MailboxAllowance(ctx, orgID); xerr != nil {
|
||||||
|
return nil, xerr
|
||||||
|
} else if a != nil && !a.CanAdd(len(ids)) {
|
||||||
|
return nil, errx.MailboxAllowanceReached(a.Used, allowanceOf(a), a.Paid)
|
||||||
|
}
|
||||||
|
actor, xerr := s.creatorCanConnect(ctx, link)
|
||||||
|
if xerr != nil {
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
account, xerr := s.d.Vendors.Redeem(ctx, orgID, link.ID.String(), in.Ticket)
|
||||||
|
if xerr != nil {
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
reserved, xerr := s.d.Repo.ReserveMany(ctx, orgID, link.ID, len(ids))
|
||||||
|
if xerr != nil {
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
if !reserved {
|
||||||
|
fresh, gerr := s.d.Repo.Get(ctx, orgID, link.ID)
|
||||||
|
if gerr != nil || fresh == nil {
|
||||||
|
return nil, ErrRevoked
|
||||||
|
}
|
||||||
|
if se := statusError(fresh.StatusAt(s.d.Now())); se != nil {
|
||||||
|
return nil, se
|
||||||
|
}
|
||||||
|
return nil, ErrTooManyMailboxes
|
||||||
|
}
|
||||||
|
// Cleaning up must not depend on a request the client may have abandoned.
|
||||||
|
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
giveBack := func(n int) {
|
||||||
|
if rerr := s.d.Repo.ReleaseMany(cleanup, orgID, link.ID, n); rerr != nil {
|
||||||
|
log.Warn().Str("link_id", link.ID.String()).Int("slots", n).Msg("connect link: could not give back slots after a failed vendor import")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
account.Label = vendorLabel(s.d.Vendors.Catalog(), account.Vendor) + " (from a client)"
|
||||||
|
conn, xerr := s.d.Vendors.Create(ctx, orgID, actor, *account)
|
||||||
|
if xerr != nil {
|
||||||
|
giveBack(len(ids))
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
// A client adds mailboxes; it never changes one the workspace already has, whatever ids it sends.
|
||||||
|
opts := models.MailboxImportOptions{OnExisting: "skip"}
|
||||||
|
for _, t := range link.TagIDs {
|
||||||
|
opts.Settings.TagIDs = append(opts.Settings.TagIDs, t.String())
|
||||||
|
}
|
||||||
|
if link.Warmup {
|
||||||
|
on := true
|
||||||
|
opts.Settings.Warmup = &on
|
||||||
|
}
|
||||||
|
imp, emails, xerr := s.d.Vendors.ImportPicked(ctx, orgID, actor, conn.ID,
|
||||||
|
vendorconn.ImportInput{MailboxIDs: ids, Options: opts, SkipConnected: true}, len(ids))
|
||||||
|
if xerr == nil && len(emails) == 0 {
|
||||||
|
xerr = ErrNoMailboxes
|
||||||
|
}
|
||||||
|
if xerr != nil {
|
||||||
|
// A refusal means nothing was started, so the slots and the connection are taken back. Any other
|
||||||
|
// failure leaves it unknown whether the import exists: its rows read their credentials through this
|
||||||
|
// connection, so both are kept and the link stays counted.
|
||||||
|
if xerr.Code < errx.Internal {
|
||||||
|
giveBack(len(ids))
|
||||||
|
if derr := s.d.Vendors.Delete(cleanup, orgID, conn.ID); derr != nil {
|
||||||
|
log.Warn().Str("link_id", link.ID.String()).Msg("connect link: a vendor connection with no import was left behind")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Warn().Str("link_id", link.ID.String()).Msg("connect link: a vendor import may have started; its slots and connection are kept")
|
||||||
|
}
|
||||||
|
return nil, xerr
|
||||||
|
}
|
||||||
|
// An id the vendor no longer lists took a slot nothing will use.
|
||||||
|
if extra := len(ids) - len(emails); extra > 0 {
|
||||||
|
giveBack(extra)
|
||||||
|
}
|
||||||
|
// The stored count, not this request's own arithmetic: another import through the same link may have run beside it.
|
||||||
|
link.MailboxesConnected += len(emails)
|
||||||
|
if fresh, gerr := s.d.Repo.Get(ctx, orgID, link.ID); gerr == nil && fresh != nil {
|
||||||
|
link.MailboxesConnected = fresh.MailboxesConnected
|
||||||
|
}
|
||||||
|
hashed := ipHash(link.ID, in.RemoteIP)
|
||||||
|
for _, email := range emails {
|
||||||
|
use := &models.ClientConnectLinkUse{LinkID: link.ID, Email: email, Provider: string(models.ConnectLinkVendor)}
|
||||||
|
if xerr := s.d.Repo.RecordUse(ctx, use, orgID, hashed); xerr != nil {
|
||||||
|
log.Warn().Str("link_id", link.ID.String()).Msg("connect link: a vendor mailbox is importing but its use was not recorded")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.notifyVendorImport(ctx, link, actor, len(emails))
|
||||||
|
return &VendorResult{Link: s.withStatus(link), ActorID: actor, Import: imp, Vendor: account.Vendor, Emails: emails}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func vendorLabel(catalog []vendorconn.Vendor, id string) string {
|
||||||
|
for _, v := range catalog {
|
||||||
|
if v.ID == id {
|
||||||
|
return v.Label
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "Inbox vendor"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) notifyVendorImport(ctx context.Context, link *models.ClientConnectLink, creator uuid.UUID, n int) {
|
||||||
|
if s.d.Notifier == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
via := "your connect link"
|
||||||
|
if label := displayname.Displayable(link.Label); label != "" {
|
||||||
|
via = "your connect link \"" + label + "\""
|
||||||
|
}
|
||||||
|
orgID := link.OrganizationID
|
||||||
|
what := "a mailbox"
|
||||||
|
if n != 1 {
|
||||||
|
what = "mailboxes"
|
||||||
|
}
|
||||||
|
s.d.Notifier.Notify(ctx, creator, &orgID, models.NotifTeamActivity,
|
||||||
|
"A client is connecting "+what+" from a vendor account",
|
||||||
|
"An import was started through "+via+". Open Mailboxes to follow it; rows that need you are listed under Imports.",
|
||||||
|
"/app/emails",
|
||||||
|
map[string]any{"connect_link_id": link.ID.String(), "mailboxes": n})
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
package connectlink
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/warmbly/warmbly/internal/app/vendorconn"
|
||||||
|
"github.com/warmbly/warmbly/internal/errx"
|
||||||
|
"github.com/warmbly/warmbly/internal/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeVendors is a vendor account with three mailboxes; a ticket is good once, for the link it was made for.
|
||||||
|
type fakeVendors struct {
|
||||||
|
tickets map[string]string // ticket -> scope
|
||||||
|
created []vendorconn.CreateInput
|
||||||
|
deleted int
|
||||||
|
imported []string
|
||||||
|
importErr *errx.Error
|
||||||
|
options models.MailboxImportOptions
|
||||||
|
actor uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
var vendorBoxes = []models.VendorMailbox{
|
||||||
|
{ID: "m1", Email: "ava@client.test"}, {ID: "m2", Email: "leo@client.test"}, {ID: "m3", Email: "mia@client.test", Connected: true},
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeVendors) Catalog() []vendorconn.Vendor {
|
||||||
|
return []vendorconn.Vendor{{ID: "zapmail", Label: "Zapmail", Fields: []vendorconn.VendorField{{Key: "api_key", Label: "API key", Secret: true, Required: true}}}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeVendors) Hold(_ context.Context, _ uuid.UUID, scope string, in vendorconn.CreateInput) (string, []models.VendorMailbox, *errx.Error) {
|
||||||
|
if in.Fields["api_key"] != "good" {
|
||||||
|
return "", nil, errx.NewWithIdentifier(errx.BadRequest, "mailbox_vendor_unauthorized", "refused")
|
||||||
|
}
|
||||||
|
if f.tickets == nil {
|
||||||
|
f.tickets = map[string]string{}
|
||||||
|
}
|
||||||
|
ticket := uuid.NewString()
|
||||||
|
f.tickets[ticket] = scope
|
||||||
|
return ticket, vendorBoxes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeVendors) Redeem(_ context.Context, _ uuid.UUID, scope, ticket string) (*vendorconn.CreateInput, *errx.Error) {
|
||||||
|
if got, ok := f.tickets[ticket]; !ok || got != scope {
|
||||||
|
return nil, vendorconn.ErrHoldExpired
|
||||||
|
}
|
||||||
|
delete(f.tickets, ticket)
|
||||||
|
return &vendorconn.CreateInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "good"}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeVendors) Create(_ context.Context, _, userID uuid.UUID, in vendorconn.CreateInput) (*models.VendorConnection, *errx.Error) {
|
||||||
|
f.created, f.actor = append(f.created, in), userID
|
||||||
|
return &models.VendorConnection{ID: uuid.New(), Vendor: in.Vendor, Label: in.Label}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeVendors) ImportPicked(_ context.Context, _, _, _ uuid.UUID, in vendorconn.ImportInput, _ ...int) (*models.MailboxImport, []string, *errx.Error) {
|
||||||
|
if f.importErr != nil {
|
||||||
|
return nil, nil, f.importErr
|
||||||
|
}
|
||||||
|
f.options = in.Options
|
||||||
|
var emails []string
|
||||||
|
for _, id := range in.MailboxIDs {
|
||||||
|
for _, b := range vendorBoxes {
|
||||||
|
// A mailbox already in the workspace is left out when the caller says so, as the service does.
|
||||||
|
if b.ID == id && !(in.SkipConnected && b.Connected) {
|
||||||
|
emails = append(emails, b.Email)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.imported = emails
|
||||||
|
return &models.MailboxImport{ID: uuid.New()}, emails, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeVendors) Delete(context.Context, uuid.UUID, uuid.UUID) *errx.Error {
|
||||||
|
f.deleted++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *fakeRepo) ReserveMany(_ context.Context, orgID, id uuid.UUID, n int) (bool, *errx.Error) {
|
||||||
|
l := r.link
|
||||||
|
if l.OrganizationID != orgID || l.ID != id || l.MailboxesConnected+n > l.MaxMailboxes {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
l.MailboxesConnected += n
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *fakeRepo) ReleaseMany(_ context.Context, _, _ uuid.UUID, n int) *errx.Error {
|
||||||
|
r.link.MailboxesConnected -= n
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get lets Page read the workspace's name; none is needed here.
|
||||||
|
func (w *fakeWorkspaces) Get(context.Context, uuid.UUID) (*models.Organization, *errx.Error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func vendorFixture(t *testing.T) (*Service, *fakeRepo, *fakeVendors, *models.ClientConnectLink) {
|
||||||
|
t.Helper()
|
||||||
|
s, repo, _, _, token := newFixture(t)
|
||||||
|
repo.link.AllowedProviders = []string{"smtp_imap", "vendor"}
|
||||||
|
repo.link.Warmup = true
|
||||||
|
repo.link.TagIDs = []uuid.UUID{uuid.New()}
|
||||||
|
v := &fakeVendors{}
|
||||||
|
s.WireVendors(v)
|
||||||
|
link, xerr := s.Resolve(context.Background(), token)
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
return s, repo, v, link
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAClientConnectsMailboxesFromItsVendorAccount(t *testing.T) {
|
||||||
|
s, repo, v, link := vendorFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if page := s.Page(ctx, link); len(page.Vendors) != 1 || page.Vendors[0].ID != "zapmail" {
|
||||||
|
t.Fatalf("the page offers %+v", page.Vendors)
|
||||||
|
}
|
||||||
|
if _, xerr := s.VendorMailboxes(ctx, link, VendorAccountInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "bad"}}); xerr == nil {
|
||||||
|
t.Fatal("a key the vendor refuses was listed")
|
||||||
|
}
|
||||||
|
list, xerr := s.VendorMailboxes(ctx, link, VendorAccountInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "good"}})
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
if list.Ticket == "" || len(list.Mailboxes) != 3 || list.Remaining != 2 || !list.Mailboxes[2].Connected {
|
||||||
|
t.Fatalf("list = %+v", list)
|
||||||
|
}
|
||||||
|
|
||||||
|
res, xerr := s.VendorImport(ctx, link, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m1", "m2", "m1", ""}})
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
// Imported in the creator's name, with the link's tags and warmup, and each mailbox counted and recorded.
|
||||||
|
if v.actor != *repo.link.CreatedBy || len(v.imported) != 2 || len(repo.uses) != 2 || repo.link.MailboxesConnected != 2 || res.Link.MailboxesConnected != 2 {
|
||||||
|
t.Fatalf("imported %v as %s, uses %d, link at %d", v.imported, v.actor, len(repo.uses), repo.link.MailboxesConnected)
|
||||||
|
}
|
||||||
|
if v.options.Settings.Warmup == nil || !*v.options.Settings.Warmup || len(v.options.Settings.TagIDs) != 1 || v.created[0].Label != "Zapmail (from a client)" {
|
||||||
|
t.Fatalf("options %+v, connection %+v", v.options.Settings, v.created[0])
|
||||||
|
}
|
||||||
|
// The ticket was good once.
|
||||||
|
fresh, _ := repo.Get(ctx, link.OrganizationID, link.ID)
|
||||||
|
if _, xerr := s.VendorImport(ctx, fresh, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m3"}}); xerr == nil {
|
||||||
|
t.Fatal("a ticket was used twice")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAVendorImportIsHeldToTheLinksLimit(t *testing.T) {
|
||||||
|
s, repo, v, link := vendorFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
list, xerr := s.VendorMailboxes(ctx, link, VendorAccountInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "good"}})
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
if _, xerr := s.VendorImport(ctx, link, VendorImportInput{Ticket: list.Ticket}); xerr == nil || xerr.Identifier != "client_link_no_mailboxes" {
|
||||||
|
t.Fatalf("nothing picked: got %v", xerr)
|
||||||
|
}
|
||||||
|
// More than the link takes is refused before the ticket is spent, so picking fewer needs no key again.
|
||||||
|
if _, xerr := s.VendorImport(ctx, link, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m1", "m2", "m3"}}); xerr == nil || xerr.Identifier != "client_link_too_many_mailboxes" {
|
||||||
|
t.Fatalf("three on a link of two: got %v", xerr)
|
||||||
|
}
|
||||||
|
if len(v.created) != 0 || repo.link.MailboxesConnected != 0 {
|
||||||
|
t.Fatalf("a refused import left %d connections and %d slots taken", len(v.created), repo.link.MailboxesConnected)
|
||||||
|
}
|
||||||
|
if _, xerr := s.VendorImport(ctx, link, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m1"}}); xerr != nil {
|
||||||
|
t.Fatalf("picking fewer with the same ticket: %v", xerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestARefusedVendorImportGivesItsSlotsBack(t *testing.T) {
|
||||||
|
s, repo, v, link := vendorFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
list, xerr := s.VendorMailboxes(ctx, link, VendorAccountInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "good"}})
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
// Refused before anything was written: nothing is owed to the link.
|
||||||
|
v.importErr = errx.New(errx.BadRequest, "refused")
|
||||||
|
if _, xerr := s.VendorImport(ctx, link, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m1", "m2"}}); xerr == nil {
|
||||||
|
t.Fatal("a refused import was reported as started")
|
||||||
|
}
|
||||||
|
if repo.link.MailboxesConnected != 0 || v.deleted != 1 || len(repo.uses) != 0 {
|
||||||
|
t.Fatalf("slots %d, connections removed %d, uses %d", repo.link.MailboxesConnected, v.deleted, len(repo.uses))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAVendorImportThatMayHaveStartedKeepsItsSlotsAndItsKey(t *testing.T) {
|
||||||
|
s, repo, v, link := vendorFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
list, xerr := s.VendorMailboxes(ctx, link, VendorAccountInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "good"}})
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
// It is not known whether the import was written. Its rows would read their credentials through the
|
||||||
|
// connection, so that is kept, and the link stays counted so it is never good for more than it allows.
|
||||||
|
v.importErr = errx.InternalError()
|
||||||
|
if _, xerr := s.VendorImport(ctx, link, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m1", "m2"}}); xerr == nil {
|
||||||
|
t.Fatal("a failed import was reported as started")
|
||||||
|
}
|
||||||
|
if repo.link.MailboxesConnected != 2 || v.deleted != 0 {
|
||||||
|
t.Fatalf("slots %d, connections removed %d", repo.link.MailboxesConnected, v.deleted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAClientCannotTouchAMailboxTheWorkspaceAlreadyHas(t *testing.T) {
|
||||||
|
s, repo, v, link := vendorFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
in := VendorAccountInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "good"}}
|
||||||
|
list, xerr := s.VendorMailboxes(ctx, link, in)
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
// m3 is already connected. Naming it alongside a new one imports only the new one, and never as an update.
|
||||||
|
res, xerr := s.VendorImport(ctx, link, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m1", "m3"}})
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
if len(res.Emails) != 1 || res.Emails[0] != "ava@client.test" || repo.link.MailboxesConnected != 1 || v.options.OnExisting != "skip" {
|
||||||
|
t.Fatalf("imported %v, slots %d, on_existing %q", res.Emails, repo.link.MailboxesConnected, v.options.OnExisting)
|
||||||
|
}
|
||||||
|
// Naming only the connected one starts nothing and costs the link nothing.
|
||||||
|
fresh, _ := repo.Get(ctx, link.OrganizationID, link.ID)
|
||||||
|
list, xerr = s.VendorMailboxes(ctx, fresh, in)
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
if _, xerr := s.VendorImport(ctx, fresh, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m3"}}); xerr == nil || xerr.Identifier != "client_link_no_mailboxes" {
|
||||||
|
t.Fatalf("only a connected mailbox: got %v", xerr)
|
||||||
|
}
|
||||||
|
if repo.link.MailboxesConnected != 1 || v.deleted != 1 {
|
||||||
|
t.Fatalf("slots %d, connections removed %d", repo.link.MailboxesConnected, v.deleted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestALinkThatDoesNotTakeAVendorAccountRefusesOne(t *testing.T) {
|
||||||
|
s, repo, _, link := vendorFixture(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
in := VendorAccountInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "good"}}
|
||||||
|
|
||||||
|
repo.link.AllowedProviders = []string{"smtp_imap"}
|
||||||
|
plain, _ := repo.Get(ctx, link.OrganizationID, link.ID)
|
||||||
|
if _, xerr := s.VendorMailboxes(ctx, plain, in); xerr == nil || xerr.Identifier != "client_link_provider_not_allowed" {
|
||||||
|
t.Fatalf("a link without the vendor way in: got %v", xerr)
|
||||||
|
}
|
||||||
|
if page := s.Page(ctx, plain); len(page.Vendors) != 0 {
|
||||||
|
t.Fatalf("the page offers vendors it does not take: %+v", page.Vendors)
|
||||||
|
}
|
||||||
|
// A ticket made for one link is no good on another.
|
||||||
|
list, xerr := s.VendorMailboxes(ctx, link, in)
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
other := *link
|
||||||
|
other.ID = uuid.New()
|
||||||
|
repo.link.ID = other.ID
|
||||||
|
if _, xerr := s.VendorImport(ctx, &other, VendorImportInput{Ticket: list.Ticket, MailboxIDs: []string{"m1"}}); xerr == nil || xerr.Identifier != "mailbox_vendor_hold_expired" {
|
||||||
|
t.Fatalf("a ticket of another link: got %v", xerr)
|
||||||
|
}
|
||||||
|
// Without the vendor service the way in is simply not offered.
|
||||||
|
s.WireVendors(nil)
|
||||||
|
if _, xerr := s.VendorMailboxes(ctx, link, in); xerr == nil || xerr.Identifier != "client_link_provider_unavailable" {
|
||||||
|
t.Fatalf("no vendor service: got %v", xerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -198,13 +198,22 @@ func (s *Service) UpdateAgencyAccount(ctx context.Context, agencyID, userID, id
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errx.InternalError()
|
return nil, errx.InternalError()
|
||||||
}
|
}
|
||||||
|
failed := false
|
||||||
for _, l := range links {
|
for _, l := range links {
|
||||||
_, _ = s.repo.Update(ctx, l.OrganizationID, l.ConnectionID, label, "")
|
if _, err := s.repo.Update(ctx, l.OrganizationID, l.ConnectionID, label, ""); err != nil {
|
||||||
|
failed = true
|
||||||
|
}
|
||||||
if sealed != "" {
|
if sealed != "" {
|
||||||
_ = s.repo.SetStatus(ctx, l.ConnectionID, "active", "")
|
if err := s.repo.SetStatus(ctx, l.ConnectionID, "active", ""); err != nil {
|
||||||
|
failed = true
|
||||||
|
}
|
||||||
}
|
}
|
||||||
s.forget(l.ConnectionID)
|
s.forget(l.ConnectionID)
|
||||||
}
|
}
|
||||||
|
// The key is saved either way; asking again finishes what did not follow.
|
||||||
|
if failed {
|
||||||
|
return nil, errx.NewPublic(errx.Internal, "The account was saved, but not every client shows it yet. Save it again.")
|
||||||
|
}
|
||||||
return s.agencyAccountView(ctx, agencyID, userID, id)
|
return s.agencyAccountView(ctx, agencyID, userID, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -376,6 +376,31 @@ func TestAKeylessRefusalRecordedByAnOlderReleaseDoesNotStick(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAClientsKeyIsHeldSealedAndReadOnce(t *testing.T) {
|
||||||
|
client := &fakeClient{boxes: []mailvendor.Mailbox{{ID: "m1", Email: "ava@client.test"}}}
|
||||||
|
s, _, mb, _, _ := newTestService(t, client)
|
||||||
|
mb.existing["ava@client.test"] = models.EmailRef{ID: uuid.New()}
|
||||||
|
ctx := context.Background()
|
||||||
|
org := uuid.New()
|
||||||
|
|
||||||
|
// Nothing to hold it in: the way in is off, not half working.
|
||||||
|
if _, _, xerr := s.Hold(ctx, org, "link-1", CreateInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "k"}}); xerr == nil {
|
||||||
|
t.Fatal("a key was held with nowhere to hold it")
|
||||||
|
}
|
||||||
|
if _, xerr := s.Redeem(ctx, org, "link-1", strings.Repeat("a", 64)); xerr == nil || xerr.Identifier != "mailbox_vendor_hold_expired" {
|
||||||
|
t.Fatalf("an unknown ticket: got %v", xerr)
|
||||||
|
}
|
||||||
|
// Peek verifies and lists without storing anything, marking what the workspace already has.
|
||||||
|
boxes, raw, xerr := s.Peek(ctx, org, CreateInput{Vendor: "zapmail", Fields: map[string]string{"api_key": " k "}})
|
||||||
|
if xerr != nil || len(boxes) != 1 || !boxes[0].Connected || !strings.Contains(raw, `"api_key":"k"`) {
|
||||||
|
t.Fatalf("peek = %+v, %q, %v", boxes, raw, xerr)
|
||||||
|
}
|
||||||
|
client.verify = mailvendor.ErrUnauthorized
|
||||||
|
if _, _, xerr := s.Peek(ctx, org, CreateInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "k"}}); xerr == nil {
|
||||||
|
t.Fatal("a key the vendor refuses was listed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestAnAccountsMailboxCountsFollowTheCallersAccessToEachClient(t *testing.T) {
|
func TestAnAccountsMailboxCountsFollowTheCallersAccessToEachClient(t *testing.T) {
|
||||||
f := newAgencyFixture(t)
|
f := newAgencyFixture(t)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -410,3 +435,24 @@ func TestAnAccountsMailboxCountsFollowTheCallersAccessToEachClient(t *testing.T)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAnImportForSomeoneOutsideTheWorkspaceLeavesConnectedMailboxesAlone(t *testing.T) {
|
||||||
|
client := &fakeClient{boxes: []mailvendor.Mailbox{{ID: "m1", Email: "ava@client.test"}, {ID: "m2", Email: "leo@client.test"}}}
|
||||||
|
s, _, mb, imp, _ := newTestService(t, client)
|
||||||
|
ctx := context.Background()
|
||||||
|
org, user := uuid.New(), uuid.New()
|
||||||
|
mb.existing["ava@client.test"] = models.EmailRef{ID: uuid.New()}
|
||||||
|
conn, xerr := s.Create(ctx, org, user, CreateInput{Vendor: "zapmail", Fields: map[string]string{"api_key": "k"}})
|
||||||
|
if xerr != nil {
|
||||||
|
t.Fatal(xerr)
|
||||||
|
}
|
||||||
|
// Both are named; the one already in the workspace is not part of the import.
|
||||||
|
_, emails, xerr := s.ImportPicked(ctx, org, user, conn.ID, ImportInput{MailboxIDs: []string{"m1", "m2"}, SkipConnected: true})
|
||||||
|
if xerr != nil || len(emails) != 1 || emails[0] != "leo@client.test" || len(imp.in.Rows) != 1 {
|
||||||
|
t.Fatalf("emails %v, rows %d, %v", emails, len(imp.in.Rows), xerr)
|
||||||
|
}
|
||||||
|
// A member's own import still takes a named mailbox, which is how one is updated.
|
||||||
|
if _, emails, xerr := s.ImportPicked(ctx, org, user, conn.ID, ImportInput{MailboxIDs: []string{"m1", "m2"}}); xerr != nil || len(emails) != 2 {
|
||||||
|
t.Fatalf("a member's import: %v, %v", emails, xerr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
package vendorconn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/warmbly/warmbly/internal/errx"
|
||||||
|
"github.com/warmbly/warmbly/internal/models"
|
||||||
|
"github.com/warmbly/warmbly/internal/observability/errs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A key typed by someone who is not a member (a client on a connect page) is held for a few
|
||||||
|
// minutes while they pick mailboxes, so it is sent once and never returned to the page. The hold
|
||||||
|
// is sealed with the workspace's key, bound to the workspace and to what it was made for, and
|
||||||
|
// read exactly once.
|
||||||
|
|
||||||
|
const holdTTL = 15 * time.Minute
|
||||||
|
|
||||||
|
// ErrHoldExpired answers a ticket that was used, has expired or was made for something else.
|
||||||
|
var ErrHoldExpired = errx.NewWithIdentifier(errx.BadRequest, "mailbox_vendor_hold_expired",
|
||||||
|
"That took too long or was already used. Enter the key again.")
|
||||||
|
|
||||||
|
type heldAccount struct {
|
||||||
|
OrganizationID uuid.UUID `json:"organization_id"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
Vendor string `json:"vendor"`
|
||||||
|
Sealed string `json:"sealed"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func holdKey(ticket string) string { return "mailbox_vendor_hold:" + ticket }
|
||||||
|
|
||||||
|
// sealFor seals an already-marshalled field map with a workspace's key.
|
||||||
|
func (s *Service) sealFor(ctx context.Context, orgID uuid.UUID, raw string) (string, *errx.Error) {
|
||||||
|
ciph, err := s.cipher.Cipher(ctx, orgID)
|
||||||
|
if err != nil {
|
||||||
|
errs.CaptureException(err)
|
||||||
|
return "", errx.InternalError()
|
||||||
|
}
|
||||||
|
sealed, err := ciph.Encrypt(ctx, raw)
|
||||||
|
if err != nil {
|
||||||
|
errs.CaptureException(err)
|
||||||
|
return "", errx.InternalError()
|
||||||
|
}
|
||||||
|
return sealed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Peek verifies a key with the vendor and lists what it reaches, marking the mailboxes already in the workspace. Nothing is stored.
|
||||||
|
func (s *Service) Peek(ctx context.Context, orgID uuid.UUID, in CreateInput) ([]models.VendorMailbox, string, *errx.Error) {
|
||||||
|
raw, xerr := s.verified(ctx, in.Vendor, in.Fields)
|
||||||
|
if xerr != nil {
|
||||||
|
return nil, "", xerr
|
||||||
|
}
|
||||||
|
client, err := s.newClient(in.Vendor, trimFields(in.Fields))
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", vendorError(labelOf(in.Vendor), err)
|
||||||
|
}
|
||||||
|
list, err := client.List(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, "", vendorError(labelOf(in.Vendor), err)
|
||||||
|
}
|
||||||
|
out := make([]models.VendorMailbox, 0, len(list))
|
||||||
|
emails := make([]string, 0, len(list))
|
||||||
|
for _, m := range list {
|
||||||
|
if m.Email == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, models.VendorMailbox{
|
||||||
|
ID: m.ID, Email: m.Email, Name: strings.TrimSpace(m.FirstName + " " + m.LastName),
|
||||||
|
Domain: m.Domain, Provider: m.Provider, Status: m.Status, Workspace: m.Workspace,
|
||||||
|
})
|
||||||
|
emails = append(emails, m.Email)
|
||||||
|
}
|
||||||
|
existing, xerr := s.mailboxes.FindManyInOrganization(ctx, orgID, emails)
|
||||||
|
if xerr != nil {
|
||||||
|
return nil, "", xerr
|
||||||
|
}
|
||||||
|
for i := range out {
|
||||||
|
if ref, ok := existing[strings.ToLower(out[i].Email)]; ok {
|
||||||
|
id := ref.ID
|
||||||
|
out[i].Connected, out[i].AccountID = true, &id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, raw, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hold verifies a key, lists its mailboxes and keeps the key sealed under a ticket for scope.
|
||||||
|
func (s *Service) Hold(ctx context.Context, orgID uuid.UUID, scope string, in CreateInput) (string, []models.VendorMailbox, *errx.Error) {
|
||||||
|
if s.cache == nil {
|
||||||
|
return "", nil, errx.New(errx.ServiceUnavailable, "inbox vendors are not available here")
|
||||||
|
}
|
||||||
|
boxes, raw, xerr := s.Peek(ctx, orgID, in)
|
||||||
|
if xerr != nil {
|
||||||
|
return "", nil, xerr
|
||||||
|
}
|
||||||
|
sealed, xerr := s.sealFor(ctx, orgID, raw)
|
||||||
|
if xerr != nil {
|
||||||
|
return "", nil, xerr
|
||||||
|
}
|
||||||
|
buf := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(buf); err != nil {
|
||||||
|
return "", nil, errx.InternalError()
|
||||||
|
}
|
||||||
|
ticket := hex.EncodeToString(buf)
|
||||||
|
held := heldAccount{OrganizationID: orgID, Scope: scope, Vendor: in.Vendor, Sealed: sealed}
|
||||||
|
if err := s.cache.SetJSON(ctx, holdKey(ticket), held, holdTTL); err != nil {
|
||||||
|
errs.CaptureException(err)
|
||||||
|
return "", nil, errx.InternalError()
|
||||||
|
}
|
||||||
|
return ticket, boxes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redeem returns the key a ticket holds, once, to the workspace and scope it was made for.
|
||||||
|
func (s *Service) Redeem(ctx context.Context, orgID uuid.UUID, scope, ticket string) (*CreateInput, *errx.Error) {
|
||||||
|
if s.cache == nil || len(ticket) != 64 {
|
||||||
|
return nil, ErrHoldExpired
|
||||||
|
}
|
||||||
|
raw, err := s.cache.GetDel(ctx, holdKey(ticket)).Result()
|
||||||
|
if err != nil || raw == "" {
|
||||||
|
return nil, ErrHoldExpired
|
||||||
|
}
|
||||||
|
var held heldAccount
|
||||||
|
if json.Unmarshal([]byte(raw), &held) != nil || held.OrganizationID != orgID || held.Scope != scope {
|
||||||
|
return nil, ErrHoldExpired
|
||||||
|
}
|
||||||
|
ciph, err := s.cipher.Cipher(ctx, orgID)
|
||||||
|
if err != nil {
|
||||||
|
errs.CaptureException(err)
|
||||||
|
return nil, errx.InternalError()
|
||||||
|
}
|
||||||
|
plain, err := ciph.Decrypt(ctx, held.Sealed)
|
||||||
|
if err != nil {
|
||||||
|
errs.CaptureException(err)
|
||||||
|
return nil, errx.InternalError()
|
||||||
|
}
|
||||||
|
var fields map[string]string
|
||||||
|
if json.Unmarshal([]byte(plain), &fields) != nil {
|
||||||
|
return nil, errx.InternalError()
|
||||||
|
}
|
||||||
|
return &CreateInput{Vendor: held.Vendor, Fields: fields}, nil
|
||||||
|
}
|
||||||
@@ -480,39 +480,61 @@ type ImportInput struct {
|
|||||||
MailboxIDs []string `json:"mailbox_ids"`
|
MailboxIDs []string `json:"mailbox_ids"`
|
||||||
All bool `json:"all"`
|
All bool `json:"all"`
|
||||||
Options models.MailboxImportOptions `json:"options"`
|
Options models.MailboxImportOptions `json:"options"`
|
||||||
|
// SkipConnected leaves out a mailbox already in the workspace even when it is named; set by a caller
|
||||||
|
// acting for someone who is not a member, never from a request body.
|
||||||
|
SkipConnected bool `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Import starts a background import of the picked vendor mailboxes. Their
|
// Import starts a background import of the picked vendor mailboxes. Their
|
||||||
// credentials are read from the vendor as each row is worked, never earlier.
|
// credentials are read from the vendor as each row is worked, never earlier.
|
||||||
func (s *Service) Import(ctx context.Context, orgID, userID, id uuid.UUID, in ImportInput) (*models.MailboxImport, *errx.Error) {
|
func (s *Service) Import(ctx context.Context, orgID, userID, id uuid.UUID, in ImportInput) (*models.MailboxImport, *errx.Error) {
|
||||||
|
imp, _, xerr := s.ImportPicked(ctx, orgID, userID, id, in)
|
||||||
|
return imp, xerr
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImportPicked is Import that also names the addresses it took, at most limit of them when limit is above zero.
|
||||||
|
func (s *Service) ImportPicked(ctx context.Context, orgID, userID, id uuid.UUID, in ImportInput, limit ...int) (*models.MailboxImport, []string, *errx.Error) {
|
||||||
if s.importer == nil {
|
if s.importer == nil {
|
||||||
return nil, errx.InternalError()
|
return nil, nil, errx.InternalError()
|
||||||
}
|
}
|
||||||
c, xerr := s.get(ctx, orgID, id)
|
c, xerr := s.get(ctx, orgID, id)
|
||||||
if xerr != nil {
|
if xerr != nil {
|
||||||
return nil, xerr
|
return nil, nil, xerr
|
||||||
}
|
}
|
||||||
boxes, xerr := s.Mailboxes(ctx, orgID, id)
|
boxes, xerr := s.Mailboxes(ctx, orgID, id)
|
||||||
if xerr != nil {
|
if xerr != nil {
|
||||||
return nil, xerr
|
return nil, nil, xerr
|
||||||
|
}
|
||||||
|
max := 0
|
||||||
|
if len(limit) > 0 {
|
||||||
|
max = limit[0]
|
||||||
}
|
}
|
||||||
want := map[string]bool{}
|
want := map[string]bool{}
|
||||||
for _, m := range in.MailboxIDs {
|
for _, m := range in.MailboxIDs {
|
||||||
want[m] = true
|
want[m] = true
|
||||||
}
|
}
|
||||||
rows := make([]mailboximport.ListRow, 0)
|
rows := make([]mailboximport.ListRow, 0)
|
||||||
|
emails := make([]string, 0)
|
||||||
for _, m := range boxes {
|
for _, m := range boxes {
|
||||||
if !want[m.ID] && !(in.All && !m.Connected) {
|
if !want[m.ID] && !(in.All && !m.Connected) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if in.SkipConnected && m.Connected {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if max > 0 && len(rows) >= max {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
emails = append(emails, m.Email)
|
||||||
cid := c.ID
|
cid := c.ID
|
||||||
rows = append(rows, mailboximport.ListRow{
|
rows = append(rows, mailboximport.ListRow{
|
||||||
Email: m.Email, Name: m.Name, VendorConnectionID: &cid, VendorMailboxID: m.ID, VendorProvider: m.Provider,
|
Email: m.Email, Name: m.Name, VendorConnectionID: &cid, VendorMailboxID: m.ID, VendorProvider: m.Provider,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
return s.importer.CreateFromList(ctx, mailboximport.ListInput{
|
imp, xerr := s.importer.CreateFromList(ctx, mailboximport.ListInput{
|
||||||
OrgID: orgID, UserID: userID, Source: "vendor", Vendor: c.Vendor, Label: c.Label, Rows: rows, Options: in.Options,
|
OrgID: orgID, UserID: userID, Source: "vendor", Vendor: c.Vendor, Label: c.Label, Rows: rows, Options: in.Options,
|
||||||
})
|
})
|
||||||
|
return imp, emails, xerr
|
||||||
}
|
}
|
||||||
|
|
||||||
// credentials reads one vendor mailbox's credentials.
|
// credentials reads one vendor mailbox's credentials.
|
||||||
|
|||||||
@@ -29,6 +29,66 @@ type ConnectLink struct {
|
|||||||
// WorkspaceFull is the workspace at its mailbox allowance, so no connect can succeed now.
|
// WorkspaceFull is the workspace at its mailbox allowance, so no connect can succeed now.
|
||||||
WorkspaceFull bool `json:"workspace_full,omitempty"`
|
WorkspaceFull bool `json:"workspace_full,omitempty"`
|
||||||
CaptchaSiteKey string `json:"captcha_site_key,omitempty"`
|
CaptchaSiteKey string `json:"captcha_site_key,omitempty"`
|
||||||
|
// Vendors are the inbox vendors a client can connect an account of, when the link takes one.
|
||||||
|
Vendors []ConnectVendor `json:"vendors,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectVendor is one inbox vendor and what connecting an account of it asks for.
|
||||||
|
type ConnectVendor struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
KeyHelpURL string `json:"key_help_url,omitempty"`
|
||||||
|
Fields []ConnectVendorField `json:"fields"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnectVendorField struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Secret bool `json:"secret"`
|
||||||
|
Required bool `json:"required"`
|
||||||
|
Help string `json:"help,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectVendorAccount is a vendor key a client typed, to be checked and listed.
|
||||||
|
type ConnectVendorAccount struct {
|
||||||
|
ConnectLookup
|
||||||
|
Vendor string `json:"vendor"`
|
||||||
|
Fields map[string]string `json:"fields"`
|
||||||
|
CaptchaToken string `json:"captcha_token,omitempty"`
|
||||||
|
RemoteIP string `json:"remote_ip"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectVendorMailboxes is what a client's vendor key reaches. The key is held under Ticket and never sent back.
|
||||||
|
type ConnectVendorMailboxes struct {
|
||||||
|
Ticket string `json:"ticket"`
|
||||||
|
Vendor string `json:"vendor"`
|
||||||
|
Mailboxes []ConnectVendorMailbox `json:"mailboxes"`
|
||||||
|
// Remaining is how many more mailboxes the link connects.
|
||||||
|
Remaining int `json:"remaining"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConnectVendorMailbox struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
Provider string `json:"provider,omitempty"`
|
||||||
|
// Connected is a mailbox already in the workspace.
|
||||||
|
Connected bool `json:"connected,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectVendorImport picks mailboxes from the account a ticket holds.
|
||||||
|
type ConnectVendorImport struct {
|
||||||
|
ConnectLookup
|
||||||
|
Ticket string `json:"ticket"`
|
||||||
|
MailboxIDs []string `json:"mailbox_ids"`
|
||||||
|
RemoteIP string `json:"remote_ip"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnectVendorStarted is an import a client started: how many mailboxes are being connected, and the link's counts after it.
|
||||||
|
type ConnectVendorStarted struct {
|
||||||
|
Mailboxes int `json:"mailboxes"`
|
||||||
|
Connected int `json:"connected"`
|
||||||
|
MaxMailboxes int `json:"max_mailboxes"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConnectOAuthStart asks for a provider sign-in URL bound to the link.
|
// ConnectOAuthStart asks for a provider sign-in URL bound to the link.
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- Refuse rather than change links a client may already hold.
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM client_connect_links WHERE 'vendor' = ANY (allowed_providers)) THEN
|
||||||
|
RAISE EXCEPTION 'connect links take a vendor account, written after 000394; roll forward instead of downgrading past it';
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
ALTER TABLE client_connect_links DROP CONSTRAINT IF EXISTS client_connect_links_providers_check;
|
||||||
|
ALTER TABLE client_connect_links ADD CONSTRAINT client_connect_links_providers_check
|
||||||
|
CHECK (cardinality(allowed_providers) BETWEEN 1 AND 3
|
||||||
|
AND allowed_providers <@ ARRAY['gmail', 'outlook', 'smtp_imap']::text[]);
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
-- A client connect link can also let the client connect an inbox vendor account and pick its mailboxes.
|
||||||
|
ALTER TABLE client_connect_links DROP CONSTRAINT IF EXISTS client_connect_links_providers_check;
|
||||||
|
ALTER TABLE client_connect_links ADD CONSTRAINT client_connect_links_providers_check
|
||||||
|
CHECK (cardinality(allowed_providers) BETWEEN 1 AND 4
|
||||||
|
AND allowed_providers <@ ARRAY['gmail', 'outlook', 'smtp_imap', 'vendor']::text[]);
|
||||||
@@ -30,7 +30,8 @@ type AgencyMailbox struct {
|
|||||||
type AgencyMailboxQuery struct {
|
type AgencyMailboxQuery struct {
|
||||||
OrgIDs []uuid.UUID
|
OrgIDs []uuid.UUID
|
||||||
Search string
|
Search string
|
||||||
// Attention keeps only mailboxes that are disconnected, erroring or held from warmup.
|
// Attention keeps only mailboxes that are disconnected, erroring, or quarantined or blocked from warmup:
|
||||||
|
// the ones the agency home counts as problems.
|
||||||
Attention bool
|
Attention bool
|
||||||
Limit int
|
Limit int
|
||||||
// Before is the last row of the previous page; zero starts at the newest.
|
// Before is the last row of the previous page; zero starts at the newest.
|
||||||
|
|||||||
@@ -16,8 +16,11 @@ const (
|
|||||||
ClientConnectLinkExhausted ClientConnectLinkStatus = "exhausted"
|
ClientConnectLinkExhausted ClientConnectLinkStatus = "exhausted"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConnectLinkProviders are the ways a client may connect, as stored in email_provider.
|
// ConnectLinkVendor is the way in that is not one mailbox: the client connects an inbox vendor account and picks its mailboxes.
|
||||||
var ConnectLinkProviders = []InboxProvider{InboxProviderGoogle, InboxProviderOutlook, InboxProviderSMTPIMAP}
|
const ConnectLinkVendor InboxProvider = "vendor"
|
||||||
|
|
||||||
|
// ConnectLinkProviders are the ways a client may connect: the email_provider values, and a vendor account.
|
||||||
|
var ConnectLinkProviders = []InboxProvider{InboxProviderGoogle, InboxProviderOutlook, InboxProviderSMTPIMAP, ConnectLinkVendor}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// ClientConnectLinkMaxMailboxes bounds one link's mailboxes, matching the table's check.
|
// ClientConnectLinkMaxMailboxes bounds one link's mailboxes, matching the table's check.
|
||||||
|
|||||||
@@ -175,7 +175,7 @@ var agencyMailboxesSQL = `
|
|||||||
) m
|
) m
|
||||||
WHERE ea.organization_id = ANY($1::uuid[])
|
WHERE ea.organization_id = ANY($1::uuid[])
|
||||||
AND ($2 = '' OR position(lower($2) in lower(ea.email)) > 0)
|
AND ($2 = '' OR position(lower($2) in lower(ea.email)) > 0)
|
||||||
AND (NOT $3 OR ea.status <> 'active' OR m.erroring OR m.held <> '')
|
AND (NOT $3 OR ea.status <> 'active' OR m.erroring OR m.held IN ('quarantined', 'blocked'))
|
||||||
AND ($4::timestamp IS NULL OR (ea.created_at, ea.id) < ($4::timestamp, $5::uuid))
|
AND ($4::timestamp IS NULL OR (ea.created_at, ea.id) < ($4::timestamp, $5::uuid))
|
||||||
ORDER BY ea.created_at DESC, ea.id DESC
|
ORDER BY ea.created_at DESC, ea.id DESC
|
||||||
LIMIT $6`
|
LIMIT $6`
|
||||||
|
|||||||
@@ -26,6 +26,9 @@ type ClientConnectLinkRepository interface {
|
|||||||
Reserve(ctx context.Context, orgID, id uuid.UUID) (bool, *errx.Error)
|
Reserve(ctx context.Context, orgID, id uuid.UUID) (bool, *errx.Error)
|
||||||
// Release gives back a slot whose connect failed.
|
// Release gives back a slot whose connect failed.
|
||||||
Release(ctx context.Context, orgID, id uuid.UUID) *errx.Error
|
Release(ctx context.Context, orgID, id uuid.UUID) *errx.Error
|
||||||
|
// ReserveMany takes n slots at once, all or none; ReleaseMany gives n back.
|
||||||
|
ReserveMany(ctx context.Context, orgID, id uuid.UUID, n int) (bool, *errx.Error)
|
||||||
|
ReleaseMany(ctx context.Context, orgID, id uuid.UUID, n int) *errx.Error
|
||||||
RecordUse(ctx context.Context, use *models.ClientConnectLinkUse, orgID uuid.UUID, ipHash string) *errx.Error
|
RecordUse(ctx context.Context, use *models.ClientConnectLinkUse, orgID uuid.UUID, ipHash string) *errx.Error
|
||||||
ListUses(ctx context.Context, orgID, linkID uuid.UUID, limit int) ([]models.ClientConnectLinkUse, *errx.Error)
|
ListUses(ctx context.Context, orgID, linkID uuid.UUID, limit int) ([]models.ClientConnectLinkUse, *errx.Error)
|
||||||
}
|
}
|
||||||
@@ -159,6 +162,32 @@ func (r *clientConnectLinkRepository) Release(ctx context.Context, orgID, id uui
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (r *clientConnectLinkRepository) ReserveMany(ctx context.Context, orgID, id uuid.UUID, n int) (bool, *errx.Error) {
|
||||||
|
if n < 1 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
tag, err := r.DB.Exec(ctx, `UPDATE client_connect_links SET mailboxes_connected = mailboxes_connected + $3
|
||||||
|
WHERE organization_id = $1 AND id = $2 AND revoked_at IS NULL AND created_by IS NOT NULL
|
||||||
|
AND expires_at > now() AND mailboxes_connected + $3 <= max_mailboxes`, orgID, id, n)
|
||||||
|
if err != nil {
|
||||||
|
db.CaptureError(err, "connect links reserve many", []any{orgID}, "exec")
|
||||||
|
return false, errx.InternalError()
|
||||||
|
}
|
||||||
|
return tag.RowsAffected() == 1, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *clientConnectLinkRepository) ReleaseMany(ctx context.Context, orgID, id uuid.UUID, n int) *errx.Error {
|
||||||
|
if n < 1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, err := r.DB.Exec(ctx, `UPDATE client_connect_links SET mailboxes_connected = GREATEST(mailboxes_connected - $3, 0)
|
||||||
|
WHERE organization_id = $1 AND id = $2`, orgID, id, n); err != nil {
|
||||||
|
db.CaptureError(err, "connect links release many", []any{orgID}, "exec")
|
||||||
|
return errx.InternalError()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (r *clientConnectLinkRepository) RecordUse(ctx context.Context, use *models.ClientConnectLinkUse, orgID uuid.UUID, ipHash string) *errx.Error {
|
func (r *clientConnectLinkRepository) RecordUse(ctx context.Context, use *models.ClientConnectLinkUse, orgID uuid.UUID, ipHash string) *errx.Error {
|
||||||
err := r.DB.QueryRow(ctx, `
|
err := r.DB.QueryRow(ctx, `
|
||||||
INSERT INTO client_connect_link_uses (link_id, organization_id, email_account_id, email, provider, remote_ip_hash)
|
INSERT INTO client_connect_link_uses (link_id, organization_id, email_account_id, email, provider, remote_ip_hash)
|
||||||
|
|||||||
@@ -71,6 +71,12 @@
|
|||||||
} catch (err) {}
|
} catch (err) {}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (d.type === "warmbly:connect:importing") {
|
||||||
|
try {
|
||||||
|
document.dispatchEvent(new CustomEvent("warmbly:importing", { detail: { mailboxes: d.mailboxes | 0, connected: d.connected | 0 } }));
|
||||||
|
} catch (err) {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (d.type === "warmbly:resize" && d.page && pages.hasOwnProperty(d.page)) {
|
if (d.type === "warmbly:resize" && d.page && pages.hasOwnProperty(d.page)) {
|
||||||
var frames = document.querySelectorAll('iframe[data-warmbly-frame="' + d.page + '"]');
|
var frames = document.querySelectorAll('iframe[data-warmbly-frame="' + d.page + '"]');
|
||||||
for (var i = 0; i < frames.length; i++) {
|
for (var i = 0; i < frames.length; i++) {
|
||||||
|
|||||||
@@ -23,13 +23,15 @@ import {
|
|||||||
navigateForSignin,
|
navigateForSignin,
|
||||||
openSigninWindow,
|
openSigninWindow,
|
||||||
postConnected,
|
postConnected,
|
||||||
|
postImporting,
|
||||||
readSigninResult,
|
readSigninResult,
|
||||||
type SigninResult,
|
type SigninResult,
|
||||||
startConnectResizeReporting,
|
startConnectResizeReporting,
|
||||||
} from "./connectEmbed";
|
} from "./connectEmbed";
|
||||||
import { CUSTOM_PRESET, MAIL_PRESETS } from "./connectPresets";
|
import { CUSTOM_PRESET, MAIL_PRESETS } from "./connectPresets";
|
||||||
|
import { VendorForm } from "./ConnectVendor";
|
||||||
import { isEmbedded } from "./embed";
|
import { isEmbedded } from "./embed";
|
||||||
import { AlertIcon, BackIcon, CheckIcon, ChevronIcon, MailIcon } from "./icons";
|
import { AlertIcon, BackIcon, CheckIcon, ChevronIcon, MailIcon, StackIcon } from "./icons";
|
||||||
import { useBrandLook } from "./look";
|
import { useBrandLook } from "./look";
|
||||||
import { StalePage } from "./NotFound";
|
import { StalePage } from "./NotFound";
|
||||||
import type { Brand } from "./theme";
|
import type { Brand } from "./theme";
|
||||||
@@ -42,7 +44,7 @@ interface Connected {
|
|||||||
provider: string;
|
provider: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
type View = "choose" | "imap" | "waiting";
|
type View = "choose" | "imap" | "vendor" | "waiting";
|
||||||
|
|
||||||
const POLL_MS = 2000;
|
const POLL_MS = 2000;
|
||||||
const POLL_MAX_MS = 10 * 60 * 1000;
|
const POLL_MAX_MS = 10 * 60 * 1000;
|
||||||
@@ -194,6 +196,20 @@ export function ConnectPage() {
|
|||||||
setView("choose");
|
setView("choose");
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
) : view === "vendor" ? (
|
||||||
|
<VendorForm
|
||||||
|
token={token}
|
||||||
|
link={live}
|
||||||
|
errorCopy={(e) => errorCopy(e, workspace)}
|
||||||
|
onBack={() => setView("choose")}
|
||||||
|
// The link's count is moved on here, not re-read: a link this import filled answers "complete",
|
||||||
|
// which would replace the confirmation the client is reading.
|
||||||
|
onStarted={(started) => {
|
||||||
|
qc.setQueryData<ConnectLink>(["connect", token], (prev) => (prev ? { ...prev, connected: started.connected } : prev));
|
||||||
|
// An embedding page is told an import began; "connected" stays for a mailbox that is.
|
||||||
|
postImporting(started.mailboxes, started.connected);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
) : view === "waiting" ? (
|
) : view === "waiting" ? (
|
||||||
<div className="cx-state">
|
<div className="cx-state">
|
||||||
<span className="cx-spinner" aria-hidden />
|
<span className="cx-spinner" aria-hidden />
|
||||||
@@ -261,6 +277,10 @@ export function ConnectPage() {
|
|||||||
setError(null);
|
setError(null);
|
||||||
setView("imap");
|
setView("imap");
|
||||||
}}
|
}}
|
||||||
|
onVendor={() => {
|
||||||
|
setError(null);
|
||||||
|
setView("vendor");
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
@@ -359,6 +379,7 @@ function ProviderButtons({
|
|||||||
onWaiting,
|
onWaiting,
|
||||||
onDone,
|
onDone,
|
||||||
onImap,
|
onImap,
|
||||||
|
onVendor,
|
||||||
}: {
|
}: {
|
||||||
token: string;
|
token: string;
|
||||||
link: ConnectLink;
|
link: ConnectLink;
|
||||||
@@ -366,6 +387,7 @@ function ProviderButtons({
|
|||||||
onWaiting: () => void;
|
onWaiting: () => void;
|
||||||
onDone: (o: { status: string; email?: string; provider?: string; code?: string; message?: string; connected?: number }) => void;
|
onDone: (o: { status: string; email?: string; provider?: string; code?: string; message?: string; connected?: number }) => void;
|
||||||
onImap: () => void;
|
onImap: () => void;
|
||||||
|
onVendor: () => void;
|
||||||
}) {
|
}) {
|
||||||
const [busy, setBusy] = useState<ConnectProvider | null>(null);
|
const [busy, setBusy] = useState<ConnectProvider | null>(null);
|
||||||
const poll = useRef<number | null>(null);
|
const poll = useRef<number | null>(null);
|
||||||
@@ -432,6 +454,12 @@ function ProviderButtons({
|
|||||||
Use IMAP and SMTP details
|
Use IMAP and SMTP details
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{has("vendor") && (link.vendors?.length ?? 0) > 0 && (
|
||||||
|
<button type="button" className="cx-provider" disabled={busy !== null} onClick={onVendor}>
|
||||||
|
<StackIcon className="cx-mark cx-mark-mail" />
|
||||||
|
Connect many from my inbox vendor
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
{link.providers.length === 0 && <p className="cx-error">This link has no way to connect a mailbox on this server. Ask for a new link.</p>}
|
{link.providers.length === 0 && <p className="cx-error">This link has no way to connect a mailbox on this server. Ask for a new link.</p>}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,257 @@
|
|||||||
|
// The connect page's vendor route: a client who bought mailboxes from an inbox vendor names the
|
||||||
|
// account once, picks the mailboxes, and they are connected for them. The key is sent a single
|
||||||
|
// time and never comes back to this page: the pick refers to it by a short-lived ticket.
|
||||||
|
|
||||||
|
import type React from "react";
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
|
||||||
|
import {
|
||||||
|
ConnectError,
|
||||||
|
type ConnectLink,
|
||||||
|
importVendorMailboxes,
|
||||||
|
listVendorMailboxes,
|
||||||
|
type VendorImportStarted,
|
||||||
|
type VendorMailboxes,
|
||||||
|
} from "./connectApi";
|
||||||
|
import { BackIcon, CheckIcon, ChevronIcon } from "./icons";
|
||||||
|
import { Turnstile } from "./Turnstile";
|
||||||
|
import { resetTurnstile } from "./turnstileScript";
|
||||||
|
|
||||||
|
const PROVIDER: Record<string, string> = { google: "Google", microsoft: "Microsoft", smtp: "IMAP and SMTP" };
|
||||||
|
|
||||||
|
export function VendorForm({
|
||||||
|
token,
|
||||||
|
link,
|
||||||
|
errorCopy,
|
||||||
|
onBack,
|
||||||
|
onStarted,
|
||||||
|
}: {
|
||||||
|
token: string;
|
||||||
|
link: ConnectLink;
|
||||||
|
errorCopy: (err: unknown) => string;
|
||||||
|
onBack: () => void;
|
||||||
|
onStarted: (started: VendorImportStarted) => void;
|
||||||
|
}) {
|
||||||
|
const vendors = link.vendors ?? [];
|
||||||
|
const [vendorId, setVendorId] = useState(vendors[0]?.id ?? "");
|
||||||
|
const [fields, setFields] = useState<Record<string, string>>({});
|
||||||
|
const [captcha, setCaptcha] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [found, setFound] = useState<VendorMailboxes | null>(null);
|
||||||
|
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||||
|
const [started, setStarted] = useState<VendorImportStarted | null>(null);
|
||||||
|
|
||||||
|
const vendor = vendors.find((v) => v.id === vendorId);
|
||||||
|
const open = useMemo(() => (found?.mailboxes ?? []).filter((m) => !m.connected), [found]);
|
||||||
|
const room = found ? Math.max(0, found.remaining) : 0;
|
||||||
|
|
||||||
|
const find = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!vendor) return;
|
||||||
|
if (link.captcha_site_key && !captcha) {
|
||||||
|
setError("Complete the security check first.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const out = await listVendorMailboxes(token, { vendor: vendor.id, fields, captcha_token: captcha || undefined });
|
||||||
|
// The key has done its job here; the ticket stands in for it from now on.
|
||||||
|
setFields({});
|
||||||
|
setFound(out);
|
||||||
|
const fits = out.mailboxes.filter((m) => !m.connected).slice(0, Math.max(0, out.remaining));
|
||||||
|
setPicked(new Set(fits.map((m) => m.id)));
|
||||||
|
} catch (err) {
|
||||||
|
setError(errorCopy(err));
|
||||||
|
setCaptcha("");
|
||||||
|
resetTurnstile();
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startOver = () => {
|
||||||
|
setFound(null);
|
||||||
|
setPicked(new Set());
|
||||||
|
setCaptcha("");
|
||||||
|
setError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const connect = async () => {
|
||||||
|
if (!found || picked.size === 0) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const out = await importVendorMailboxes(token, found.ticket, [...picked]);
|
||||||
|
setStarted(out);
|
||||||
|
onStarted(out);
|
||||||
|
} catch (err) {
|
||||||
|
// A ticket is good once and for a few minutes; after that the key is asked for again, with the reason.
|
||||||
|
if (err instanceof ConnectError && err.code === "mailbox_vendor_hold_expired") startOver();
|
||||||
|
setError(errorCopy(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggle = (id: string) =>
|
||||||
|
setPicked((cur) => {
|
||||||
|
const next = new Set(cur);
|
||||||
|
if (next.has(id)) next.delete(id);
|
||||||
|
else if (next.size < room) next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (started) {
|
||||||
|
return (
|
||||||
|
<div className="cx-state">
|
||||||
|
<span className="cx-state-icon cx-check" aria-hidden>
|
||||||
|
<CheckIcon />
|
||||||
|
</span>
|
||||||
|
<h1>{started.mailboxes === 1 ? "Your mailbox is being connected" : `Your ${started.mailboxes} mailboxes are being connected`}</h1>
|
||||||
|
<p>
|
||||||
|
This takes a minute or two and finishes on its own. {link.workspace} is told if any of them needs something from you. You can
|
||||||
|
close this page.
|
||||||
|
</p>
|
||||||
|
<button type="button" className="cx-link" onClick={onBack}>
|
||||||
|
<BackIcon /> Connect more
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (found) {
|
||||||
|
return (
|
||||||
|
<div className="cx-form">
|
||||||
|
<button type="button" className="cx-link cx-back" onClick={startOver} disabled={busy}>
|
||||||
|
<BackIcon /> Use a different account
|
||||||
|
</button>
|
||||||
|
<h1 className="cx-title">Pick the mailboxes to connect</h1>
|
||||||
|
<p className="cx-sub">
|
||||||
|
{open.length === 0
|
||||||
|
? `Every mailbox in this account is already connected to ${link.workspace}.`
|
||||||
|
: `${picked.size} of ${open.length} selected. This link connects up to ${room} more.`}
|
||||||
|
</p>
|
||||||
|
{open.length > 0 && (
|
||||||
|
<div className="cx-pick-tools">
|
||||||
|
<button type="button" className="cx-link" disabled={busy} onClick={() => setPicked(new Set(open.slice(0, room).map((m) => m.id)))}>
|
||||||
|
{open.length > room ? `Select the first ${room}` : "Select all"}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="cx-link" disabled={busy || picked.size === 0} onClick={() => setPicked(new Set())}>
|
||||||
|
Clear
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<ul className="cx-pick">
|
||||||
|
{found.mailboxes.map((m) => {
|
||||||
|
const on = picked.has(m.id);
|
||||||
|
const full = !on && picked.size >= room;
|
||||||
|
return (
|
||||||
|
<li key={m.id}>
|
||||||
|
<label className={m.connected || full ? "cx-pick-off" : undefined}>
|
||||||
|
<input type="checkbox" checked={on} disabled={busy || m.connected || full} onChange={() => toggle(m.id)} />
|
||||||
|
<span className="cx-addr">
|
||||||
|
{m.email}
|
||||||
|
{m.name && <small>{m.name}</small>}
|
||||||
|
</span>
|
||||||
|
<span className="cx-via">{m.connected ? "Already connected" : PROVIDER[m.provider ?? ""] ?? ""}</span>
|
||||||
|
</label>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
{error && (
|
||||||
|
<p className="cx-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<button type="button" className="cx-primary" disabled={busy || picked.size === 0} onClick={() => void connect()}>
|
||||||
|
{busy ? (
|
||||||
|
<>
|
||||||
|
<span className="cx-spinner cx-spinner-sm" aria-hidden /> Starting…
|
||||||
|
</>
|
||||||
|
) : picked.size === 1 ? (
|
||||||
|
"Connect 1 mailbox"
|
||||||
|
) : (
|
||||||
|
`Connect ${picked.size} mailboxes`
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="cx-form" onSubmit={(e) => void find(e)}>
|
||||||
|
<button type="button" className="cx-link cx-back" onClick={onBack} disabled={busy}>
|
||||||
|
<BackIcon /> Other ways to connect
|
||||||
|
</button>
|
||||||
|
<h1 className="cx-title">Connect mailboxes from your inbox vendor</h1>
|
||||||
|
<p className="cx-sub">
|
||||||
|
Bought your mailboxes from a vendor? Enter the account's API key and pick the ones to connect, all at once. The key is checked with
|
||||||
|
the vendor and stored encrypted, so {link.workspace} can keep them connected. It is never shown to anyone.
|
||||||
|
</p>
|
||||||
|
{vendors.length > 1 && (
|
||||||
|
<label className="cx-field">
|
||||||
|
<span>Vendor</span>
|
||||||
|
<span className="cx-select">
|
||||||
|
<select
|
||||||
|
value={vendorId}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) => {
|
||||||
|
setVendorId(e.target.value);
|
||||||
|
setFields({});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{vendors.map((v) => (
|
||||||
|
<option key={v.id} value={v.id}>
|
||||||
|
{v.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<ChevronIcon />
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{vendor?.fields.map((f) => (
|
||||||
|
<label key={f.key} className="cx-field">
|
||||||
|
<span>
|
||||||
|
{vendors.length === 1 ? `${vendor.label} ` : ""}
|
||||||
|
{f.label}
|
||||||
|
</span>
|
||||||
|
<input
|
||||||
|
type={f.secret ? "password" : "text"}
|
||||||
|
required={f.required}
|
||||||
|
autoComplete="off"
|
||||||
|
value={fields[f.key] ?? ""}
|
||||||
|
onChange={(e) => setFields((cur) => ({ ...cur, [f.key]: e.target.value }))}
|
||||||
|
disabled={busy}
|
||||||
|
/>
|
||||||
|
{f.help && <small>{f.help}</small>}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
{vendor?.key_help_url && (
|
||||||
|
<p className="cx-note cx-note-left">
|
||||||
|
<a href={vendor.key_help_url} target="_blank" rel="noreferrer">
|
||||||
|
Where to find the {vendor.label} key
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{link.captcha_site_key && <Turnstile siteKey={link.captcha_site_key} onToken={setCaptcha} theme={link.brand.theme.appearance} />}
|
||||||
|
{error && (
|
||||||
|
<p className="cx-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<button type="submit" className="cx-primary" disabled={busy || !vendor}>
|
||||||
|
{busy ? (
|
||||||
|
<>
|
||||||
|
<span className="cx-spinner cx-spinner-sm" aria-hidden /> Asking {vendor?.label ?? "the vendor"}…
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Find my mailboxes"
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -540,3 +540,52 @@ body.embed .cx-card {
|
|||||||
.cx-sk-button + .cx-sk-button {
|
.cx-sk-button + .cx-sk-button {
|
||||||
margin-top: 0.6rem;
|
margin-top: 0.6rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The vendor route: a list of the account's mailboxes to pick from. */
|
||||||
|
.cx-pick-tools {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
margin: -0.35rem 0 0;
|
||||||
|
}
|
||||||
|
.cx-pick {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
max-height: 22rem;
|
||||||
|
overflow: auto;
|
||||||
|
border: 1px solid var(--pt-line);
|
||||||
|
border-radius: var(--cx-r-box);
|
||||||
|
background: var(--pt-raised);
|
||||||
|
}
|
||||||
|
.cx-pick li + li {
|
||||||
|
border-top: 1px solid var(--pt-line);
|
||||||
|
}
|
||||||
|
.cx-pick label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem;
|
||||||
|
padding: 0.55rem 0.8rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.cx-pick label.cx-pick-off {
|
||||||
|
cursor: default;
|
||||||
|
color: var(--pt-muted);
|
||||||
|
}
|
||||||
|
.cx-pick input {
|
||||||
|
flex: none;
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
accent-color: var(--pt-accent);
|
||||||
|
}
|
||||||
|
.cx-pick .cx-addr small {
|
||||||
|
display: block;
|
||||||
|
color: var(--pt-muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
.cx-note-left {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.cx-note-left a {
|
||||||
|
color: var(--pt-accent);
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,7 +4,23 @@
|
|||||||
import { apiHeaders } from "./api";
|
import { apiHeaders } from "./api";
|
||||||
import { type Brand, parseBrand } from "./theme";
|
import { type Brand, parseBrand } from "./theme";
|
||||||
|
|
||||||
export type ConnectProvider = "gmail" | "outlook" | "smtp_imap";
|
export type ConnectProvider = "gmail" | "outlook" | "smtp_imap" | "vendor";
|
||||||
|
|
||||||
|
export interface ConnectVendorField {
|
||||||
|
key: string;
|
||||||
|
label: string;
|
||||||
|
secret: boolean;
|
||||||
|
required: boolean;
|
||||||
|
help?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An inbox vendor a client can connect an account of, and what it asks for. */
|
||||||
|
export interface ConnectVendor {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
key_help_url?: string;
|
||||||
|
fields: ConnectVendorField[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface ConnectLink {
|
export interface ConnectLink {
|
||||||
workspace: string;
|
workspace: string;
|
||||||
@@ -16,6 +32,8 @@ export interface ConnectLink {
|
|||||||
expires_at: string;
|
expires_at: string;
|
||||||
workspace_full?: boolean;
|
workspace_full?: boolean;
|
||||||
captcha_site_key?: string;
|
captcha_site_key?: string;
|
||||||
|
/** Present when the link takes a vendor account. */
|
||||||
|
vendors?: ConnectVendor[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MailService {
|
export interface MailService {
|
||||||
@@ -96,3 +114,37 @@ export function connectSMTPIMAP(token: string, payload: SMTPIMAPPayload): Promis
|
|||||||
export function fetchSigninOutcome(token: string, resultKey: string): Promise<SigninOutcome> {
|
export function fetchSigninOutcome(token: string, resultKey: string): Promise<SigninOutcome> {
|
||||||
return call(token, "/oauth/result", { method: "POST", body: JSON.stringify({ result_key: resultKey }) });
|
return call(token, "/oauth/result", { method: "POST", body: JSON.stringify({ result_key: resultKey }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface VendorMailbox {
|
||||||
|
id: string;
|
||||||
|
email: string;
|
||||||
|
name?: string;
|
||||||
|
provider?: string;
|
||||||
|
/** Already connected to the workspace. */
|
||||||
|
connected?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What a vendor key reaches. The key stays on the server under the ticket. */
|
||||||
|
export interface VendorMailboxes {
|
||||||
|
ticket: string;
|
||||||
|
vendor: string;
|
||||||
|
mailboxes: VendorMailbox[];
|
||||||
|
remaining: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VendorImportStarted {
|
||||||
|
mailboxes: number;
|
||||||
|
connected: number;
|
||||||
|
max_mailboxes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listVendorMailboxes(
|
||||||
|
token: string,
|
||||||
|
payload: { vendor: string; fields: Record<string, string>; captcha_token?: string },
|
||||||
|
): Promise<VendorMailboxes> {
|
||||||
|
return call(token, "/vendor", { method: "POST", body: JSON.stringify(payload) });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function importVendorMailboxes(token: string, ticket: string, mailboxIds: string[]): Promise<VendorImportStarted> {
|
||||||
|
return call(token, "/vendor/import", { method: "POST", body: JSON.stringify({ ticket, mailbox_ids: mailboxIds }) });
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
export const CONNECT_RESIZE_MESSAGE = "warmbly:connect:resize";
|
export const CONNECT_RESIZE_MESSAGE = "warmbly:connect:resize";
|
||||||
/** Posted to the parent after each mailbox connects, with the link's new count. */
|
/** Posted to the parent after each mailbox connects, with the link's new count. */
|
||||||
export const CONNECT_CONNECTED_MESSAGE = "warmbly:connect:connected";
|
export const CONNECT_CONNECTED_MESSAGE = "warmbly:connect:connected";
|
||||||
|
export const CONNECT_IMPORTING_MESSAGE = "warmbly:connect:importing";
|
||||||
|
|
||||||
export function startConnectResizeReporting(): () => void {
|
export function startConnectResizeReporting(): () => void {
|
||||||
if (window.parent === window) return () => {};
|
if (window.parent === window) return () => {};
|
||||||
@@ -22,6 +23,16 @@ export function startConnectResizeReporting(): () => void {
|
|||||||
return () => ro.disconnect();
|
return () => ro.disconnect();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A vendor import was started: mailboxes are on their way, none is claimed as connected yet. */
|
||||||
|
export function postImporting(mailboxes: number, connected: number) {
|
||||||
|
if (window.parent === window) return;
|
||||||
|
try {
|
||||||
|
window.parent.postMessage({ type: CONNECT_IMPORTING_MESSAGE, mailboxes, connected }, "*");
|
||||||
|
} catch {
|
||||||
|
// same as above
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function postConnected(connected: number) {
|
export function postConnected(connected: number) {
|
||||||
if (window.parent === window) return;
|
if (window.parent === window) return;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -92,3 +92,13 @@ export function ChevronIcon({ className }: { className?: string }) {
|
|||||||
</Icon>
|
</Icon>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function StackIcon({ className }: { className?: string }) {
|
||||||
|
return (
|
||||||
|
<Icon className={className}>
|
||||||
|
<path d="m12 3.5 8.5 4.3L12 12 3.5 7.8 12 3.5Z" />
|
||||||
|
<path d="m3.5 12 8.5 4.2 8.5-4.2" />
|
||||||
|
<path d="m3.5 16.2 8.5 4.3 8.5-4.3" />
|
||||||
|
</Icon>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ const PLACEHOLDER = '<meta name="wf-token" content="" />';
|
|||||||
const LINK_TOKEN = /^[A-Za-z0-9_-]{43}$/;
|
const LINK_TOKEN = /^[A-Za-z0-9_-]{43}$/;
|
||||||
const CONNECT_MAX_BODY = 16 << 10;
|
const CONNECT_MAX_BODY = 16 << 10;
|
||||||
const ACTION_MAX_BODY = 8 << 10;
|
const ACTION_MAX_BODY = 8 << 10;
|
||||||
|
const VENDOR_IMPORT_MAX_BODY = 192 << 10;
|
||||||
const BACKEND_MAX_BODY = 4 << 20;
|
const BACKEND_MAX_BODY = 4 << 20;
|
||||||
const LIMITER_KEYS_MAX = 16384;
|
const LIMITER_KEYS_MAX = 16384;
|
||||||
|
|
||||||
@@ -168,7 +169,7 @@ export function pathKind(path) {
|
|||||||
if (m) return { kind: "connect", token: m[1] };
|
if (m) return { kind: "connect", token: m[1] };
|
||||||
m = /^\/r\/([^/]*)$/.exec(path);
|
m = /^\/r\/([^/]*)$/.exec(path);
|
||||||
if (m) return { kind: "report", token: m[1] };
|
if (m) return { kind: "report", token: m[1] };
|
||||||
m = /^\/api\/connect\/([^/]+)(|\/oauth|\/oauth\/result|\/smtp-imap)$/.exec(path);
|
m = /^\/api\/connect\/([^/]+)(|\/oauth|\/oauth\/result|\/smtp-imap|\/vendor|\/vendor\/import)$/.exec(path);
|
||||||
if (m) return { kind: "connect-api", token: m[1], action: m[2] };
|
if (m) return { kind: "connect-api", token: m[1], action: m[2] };
|
||||||
m = /^\/api\/reports\/([^/]+)$/.exec(path);
|
m = /^\/api\/reports\/([^/]+)$/.exec(path);
|
||||||
if (m) return { kind: "report-api", token: m[1] };
|
if (m) return { kind: "report-api", token: m[1] };
|
||||||
@@ -351,6 +352,27 @@ function service(v) {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A vendor asks for a key and at most a few ids; a pick is bounded by the largest link.
|
||||||
|
const VENDOR_FIELDS_MAX = 8;
|
||||||
|
const VENDOR_PICK_MAX = 500;
|
||||||
|
// vendorFields keeps a flat map of short strings; undefined marks a shape the backend would refuse.
|
||||||
|
function vendorFields(v) {
|
||||||
|
if (!v || typeof v !== "object" || Array.isArray(v)) return undefined;
|
||||||
|
const entries = Object.entries(v);
|
||||||
|
if (entries.length === 0 || entries.length > VENDOR_FIELDS_MAX) return undefined;
|
||||||
|
const out = {};
|
||||||
|
for (const [name, value] of entries) {
|
||||||
|
if (typeof value !== "string" || name.length > 64 || value.length > 1024) return undefined;
|
||||||
|
out[name] = value;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// mailboxIDs keeps a list of short ids; undefined marks a shape the backend would refuse.
|
||||||
|
function mailboxIDs(v) {
|
||||||
|
if (!Array.isArray(v) || v.length === 0 || v.length > VENDOR_PICK_MAX) return undefined;
|
||||||
|
return v.every((id) => typeof id === "string" && id.length > 0 && id.length <= 256) ? v : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
// relayConnect passes the backend's verdict through as-is, or a fixed sentence when it could not be reached.
|
// relayConnect passes the backend's verdict through as-is, or a fixed sentence when it could not be reached.
|
||||||
async function relayConnect(ctx, path, body) {
|
async function relayConnect(ctx, path, body) {
|
||||||
try {
|
try {
|
||||||
@@ -375,7 +397,7 @@ async function connectAPI(ctx, token, action) {
|
|||||||
const lookup = { token, host: ctx.host };
|
const lookup = { token, host: ctx.host };
|
||||||
if (action === "") return relayConnect(ctx, "/lookup", lookup);
|
if (action === "") return relayConnect(ctx, "/lookup", lookup);
|
||||||
|
|
||||||
const max = action === "/smtp-imap" ? CONNECT_MAX_BODY : ACTION_MAX_BODY;
|
const max = action === "/vendor/import" ? VENDOR_IMPORT_MAX_BODY : action === "/smtp-imap" || action === "/vendor" ? CONNECT_MAX_BODY : ACTION_MAX_BODY;
|
||||||
const { value: b, error } = await readBody(ctx.request, max);
|
const { value: b, error } = await readBody(ctx.request, max);
|
||||||
if (action === "/smtp-imap") {
|
if (action === "/smtp-imap") {
|
||||||
if (error === "overflow") return abort(413, "body_too_large", "The details are too large.");
|
if (error === "overflow") return abort(413, "body_too_large", "The details are too large.");
|
||||||
@@ -389,6 +411,21 @@ async function connectAPI(ctx, token, action) {
|
|||||||
captcha_token: str(b.captcha_token, Infinity), remote_ip: ctx.ip,
|
captcha_token: str(b.captcha_token, Infinity), remote_ip: ctx.ip,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (action === "/vendor") {
|
||||||
|
const fields = b && vendorFields(b.fields);
|
||||||
|
if (error || fields === undefined || typeof b.vendor !== "string" || !isStr(b.captcha_token)) {
|
||||||
|
return abort(400, "invalid_body", "The details could not be read.");
|
||||||
|
}
|
||||||
|
return relayConnect(ctx, "/vendor/mailboxes", {
|
||||||
|
...lookup, vendor: str(b.vendor, 32), fields, captcha_token: str(b.captcha_token, Infinity), remote_ip: ctx.ip,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (action === "/vendor/import") {
|
||||||
|
if (error === "overflow") return abort(413, "body_too_large", "That is too many mailboxes at once.");
|
||||||
|
const ids = b && mailboxIDs(b.mailbox_ids);
|
||||||
|
if (error || ids === undefined || typeof b.ticket !== "string") return abort(400, "invalid_body", "The request could not be read.");
|
||||||
|
return relayConnect(ctx, "/vendor/import", { ...lookup, ticket: str(b.ticket, 128), mailbox_ids: ids, remote_ip: ctx.ip });
|
||||||
|
}
|
||||||
if (action === "/oauth") {
|
if (action === "/oauth") {
|
||||||
if (error || !isStr(b.provider)) return abort(400, "invalid_body", "The request could not be read.");
|
if (error || !isStr(b.provider)) return abort(400, "invalid_body", "The request could not be read.");
|
||||||
return relayConnect(ctx, "/oauth/start", { ...lookup, provider: str(b.provider, 32), remote_ip: ctx.ip });
|
return relayConnect(ctx, "/oauth/start", { ...lookup, provider: str(b.provider, 32), remote_ip: ctx.ip });
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ test("paths are split between the portal's own pages, the dashboard and nothing"
|
|||||||
"/embed.js": "loader", "/_portal/assets/index-abc.js": "bundle", [`/connect/${tok("a")}`]: "connect", [`/r/${tok("a")}`]: "report",
|
"/embed.js": "loader", "/_portal/assets/index-abc.js": "bundle", [`/connect/${tok("a")}`]: "connect", [`/r/${tok("a")}`]: "report",
|
||||||
[`/api/connect/${tok("a")}`]: "connect-api", [`/api/connect/${tok("a")}/oauth`]: "connect-api", [`/api/connect/${tok("a")}/oauth/result`]: "connect-api",
|
[`/api/connect/${tok("a")}`]: "connect-api", [`/api/connect/${tok("a")}/oauth`]: "connect-api", [`/api/connect/${tok("a")}/oauth/result`]: "connect-api",
|
||||||
[`/api/connect/${tok("a")}/smtp-imap`]: "connect-api", [`/api/reports/${tok("a")}`]: "report-api",
|
[`/api/connect/${tok("a")}/smtp-imap`]: "connect-api", [`/api/reports/${tok("a")}`]: "report-api",
|
||||||
|
[`/api/connect/${tok("a")}/vendor`]: "connect-api", [`/api/connect/${tok("a")}/vendor/import`]: "connect-api", [`/api/connect/${tok("a")}/vendor/other`]: "api-none",
|
||||||
"/api/forms/pub/submit": "api-none", "/api/v1/me": "api-none",
|
"/api/forms/pub/submit": "api-none", "/api/v1/me": "api-none",
|
||||||
"/f/pub123": "none", "/forms.js": "none", "/_portal/index.html": "none", "/connect/a/b": "none", "/r/a/b": "none",
|
"/f/pub123": "none", "/forms.js": "none", "/_portal/index.html": "none", "/connect/a/b": "none", "/r/a/b": "none",
|
||||||
"/": "dashboard", "/connect": "dashboard", "/app/campaigns": "dashboard", "/assets/index-def.js": "dashboard", "/rx": "dashboard",
|
"/": "dashboard", "/connect": "dashboard", "/app/campaigns": "dashboard", "/assets/index-def.js": "dashboard", "/rx": "dashboard",
|
||||||
@@ -134,6 +135,8 @@ test("connect calls reach the backend's internal routes with the portal token, t
|
|||||||
"/api/v1/internal/connect-links/oauth/start": async () => Response.json({ url: "https://accounts.example/x", result_key: "k" }),
|
"/api/v1/internal/connect-links/oauth/start": async () => Response.json({ url: "https://accounts.example/x", result_key: "k" }),
|
||||||
"/api/v1/internal/connect-links/oauth/result": async () => Response.json({ status: "pending" }),
|
"/api/v1/internal/connect-links/oauth/result": async () => Response.json({ status: "pending" }),
|
||||||
"/api/v1/internal/connect-links/smtp-imap": async () => Response.json({ code: "client_link_full", message: "Full." }, { status: 409 }),
|
"/api/v1/internal/connect-links/smtp-imap": async () => Response.json({ code: "client_link_full", message: "Full." }, { status: 409 }),
|
||||||
|
"/api/v1/internal/connect-links/vendor/mailboxes": async () => Response.json({ ticket: "t", mailboxes: [], remaining: 5 }),
|
||||||
|
"/api/v1/internal/connect-links/vendor/import": async () => Response.json({ mailboxes: 2, connected: 2, max_mailboxes: 5 }, { status: 201 }),
|
||||||
};
|
};
|
||||||
const headers = { "X-Warmbly-Render": render, "CF-Connecting-IP": "203.0.113.9", "X-Forwarded-Host": "other.example", "Content-Type": "application/json" };
|
const headers = { "X-Warmbly-Render": render, "CF-Connecting-IP": "203.0.113.9", "X-Forwarded-Host": "other.example", "Content-Type": "application/json" };
|
||||||
const call = (suffix, body) => servePortal(at(`/api/connect/${token}${suffix}`, body === undefined ? { headers } : { method: "POST", headers, body: JSON.stringify(body) }),
|
const call = (suffix, body) => servePortal(at(`/api/connect/${token}${suffix}`, body === undefined ? { headers } : { method: "POST", headers, body: JSON.stringify(body) }),
|
||||||
@@ -151,9 +154,22 @@ test("connect calls reach the backend's internal routes with the portal token, t
|
|||||||
});
|
});
|
||||||
assert.equal(smtp.status, 409);
|
assert.equal(smtp.status, 409);
|
||||||
assert.equal((await smtp.json()).code, "client_link_full");
|
assert.equal((await smtp.json()).code, "client_link_full");
|
||||||
|
// A vendor key goes to the backend once; only a ticket comes back, and the pick names it.
|
||||||
|
const listed = await call("/vendor", { vendor: "zapmail", fields: { api_key: "zm_secret" }, captcha_token: "c", extra: "dropped" });
|
||||||
|
assert.equal(listed.status, 200);
|
||||||
|
assert.deepEqual(await listed.json(), { ticket: "t", mailboxes: [], remaining: 5 });
|
||||||
|
assert.equal((await call("/vendor/import", { ticket: "t", mailbox_ids: ["m1", "m2"], fields: { api_key: "dropped" } })).status, 201);
|
||||||
|
for (const bad of [{ vendor: "zapmail" }, { vendor: "zapmail", fields: {} }, { vendor: "zapmail", fields: { api_key: 7 } }, { vendor: 7, fields: { api_key: "k" } },
|
||||||
|
{ vendor: "zapmail", fields: Object.fromEntries(Array.from({ length: 9 }, (_, i) => ["k" + i, "v"])) }]) {
|
||||||
|
assert.equal((await call("/vendor", bad)).status, 400, JSON.stringify(bad));
|
||||||
|
}
|
||||||
|
for (const bad of [{ ticket: "t" }, { ticket: "t", mailbox_ids: [] }, { ticket: "t", mailbox_ids: ["m1", 2] }, { mailbox_ids: ["m1"] },
|
||||||
|
{ ticket: "t", mailbox_ids: Array.from({ length: 501 }, (_, i) => "m" + i) }]) {
|
||||||
|
assert.equal((await call("/vendor/import", bad)).status, 400, JSON.stringify(bad).slice(0, 60));
|
||||||
|
}
|
||||||
|
|
||||||
const sent = calls.filter((c) => c.url.pathname.startsWith("/api/v1/internal/connect-links"));
|
const sent = calls.filter((c) => c.url.pathname.startsWith("/api/v1/internal/connect-links"));
|
||||||
assert.deepEqual(sent.map((c) => c.url.pathname.replace("/api/v1/internal/connect-links", "")), ["/lookup", "/oauth/start", "/oauth/result", "/smtp-imap"]);
|
assert.deepEqual(sent.map((c) => c.url.pathname.replace("/api/v1/internal/connect-links", "")), ["/lookup", "/oauth/start", "/oauth/result", "/smtp-imap", "/vendor/mailboxes", "/vendor/import"]);
|
||||||
for (const c of sent) {
|
for (const c of sent) {
|
||||||
assert.equal(c.auth, `Bearer ${TOKEN}`);
|
assert.equal(c.auth, `Bearer ${TOKEN}`);
|
||||||
assert.equal(c.body.token, token);
|
assert.equal(c.body.token, token);
|
||||||
@@ -163,6 +179,8 @@ test("connect calls reach the backend's internal routes with the portal token, t
|
|||||||
assert.deepEqual(sent[2].body, { token, host: PORTAL, result_key: "k" });
|
assert.deepEqual(sent[2].body, { token, host: PORTAL, result_key: "k" });
|
||||||
assert.deepEqual(sent[3].body.smtp, { host: "smtp.b.test", port: 465, username: "a", password: "p", security: "tls" });
|
assert.deepEqual(sent[3].body.smtp, { host: "smtp.b.test", port: 465, username: "a", password: "p", security: "tls" });
|
||||||
assert.equal(sent[3].body.imap, null);
|
assert.equal(sent[3].body.imap, null);
|
||||||
|
assert.deepEqual(sent[4].body, { token, host: PORTAL, vendor: "zapmail", fields: { api_key: "zm_secret" }, captcha_token: "c", remote_ip: "203.0.113.9" });
|
||||||
|
assert.deepEqual(sent[5].body, { token, host: PORTAL, ticket: "t", mailbox_ids: ["m1", "m2"], remote_ip: "203.0.113.9" });
|
||||||
assert.equal(sent[3].body.remote_ip, "203.0.113.9");
|
assert.equal(sent[3].body.remote_ip, "203.0.113.9");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -211,6 +211,14 @@ recording: it removes the vendor account the flow connects) and the mock inbox v
|
|||||||
beside itself when started with `QA_VENDOR_MOCK=1 pnpm stack up lite`. Then:
|
beside itself when started with `QA_VENDOR_MOCK=1 pnpm stack up lite`. Then:
|
||||||
`QA_ADMIN_AGENCY_FIXTURES=1 pnpm proof agency-mailboxes`.
|
`QA_ADMIN_AGENCY_FIXTURES=1 pnpm proof agency-mailboxes`.
|
||||||
|
|
||||||
|
`flows/client-connect-vendor.flow.ts` records a client connecting many mailboxes from its own vendor account through
|
||||||
|
a connect link: the link is made in the dashboard, opened on the portal, and the mock vendor's mailboxes are picked
|
||||||
|
and imported. It needs the same fixture (it marks the product tour as seen), the mock inbox vendors
|
||||||
|
(`QA_VENDOR_MOCK=1 pnpm stack up lite`) and the portal service in front of this stack, started as described under
|
||||||
|
[agency clients and the portal domain](#agency-clients-and-the-portal-domain); the dashboard build and preview there
|
||||||
|
are not needed for this flow. Then: `QA_PORTAL_URL=http://localhost:8095 pnpm proof client-connect-vendor`. Stop the
|
||||||
|
portal process afterwards along with the stack.
|
||||||
|
|
||||||
## Member access proof fixtures
|
## Member access proof fixtures
|
||||||
|
|
||||||
`flows/member-access.flow.ts` is opt-in: apply `fixtures/member-access.sql` to
|
`flows/member-access.flow.ts` is opt-in: apply `fixtures/member-access.sql` to
|
||||||
|
|||||||
@@ -3,7 +3,9 @@
|
|||||||
-- proof), and "Meridian Outbound" has the seeded workspace as a client and no plan yet. Re-runnable.
|
-- proof), and "Meridian Outbound" has the seeded workspace as a client and no plan yet. Re-runnable.
|
||||||
BEGIN;
|
BEGIN;
|
||||||
|
|
||||||
UPDATE users SET admin_permissions = 8388607 WHERE id = '11111111-0000-0000-0000-000000000001';
|
-- The product tour is marked seen, so it does not open over a walkthrough on a fresh database.
|
||||||
|
UPDATE users SET admin_permissions = 8388607, product_tour_completed_at = COALESCE(product_tour_completed_at, now())
|
||||||
|
WHERE id = '11111111-0000-0000-0000-000000000001';
|
||||||
UPDATE sessions SET mfa_verified = true WHERE user_id = '11111111-0000-0000-0000-000000000001';
|
UPDATE sessions SET mfa_verified = true WHERE user_id = '11111111-0000-0000-0000-000000000001';
|
||||||
|
|
||||||
INSERT INTO agencies (id, name, owner_user_id, status)
|
INSERT INTO agencies (id, name, owner_user_id, status)
|
||||||
|
|||||||
@@ -22,11 +22,6 @@ async function confirmIfAsked(page: Page) {
|
|||||||
|
|
||||||
test("an agency sees every client's mailboxes and hands a vendor account to a client", async ({ page, proof }) => {
|
test("an agency sees every client's mailboxes and hands a vendor account to a client", async ({ page, proof }) => {
|
||||||
test.skip(process.env.QA_ADMIN_AGENCY_FIXTURES !== "1", "Apply fixtures/admin-agencies.sql, start the stack with QA_VENDOR_MOCK=1, and set QA_ADMIN_AGENCY_FIXTURES=1.");
|
test.skip(process.env.QA_ADMIN_AGENCY_FIXTURES !== "1", "Apply fixtures/admin-agencies.sql, start the stack with QA_VENDOR_MOCK=1, and set QA_ADMIN_AGENCY_FIXTURES=1.");
|
||||||
// A workspace nobody has opened starts with the product tour; it is dismissed before the walkthrough.
|
|
||||||
await page.goto("/app/emails");
|
|
||||||
const skip = page.getByRole("button", { name: "Skip tour" });
|
|
||||||
if (await skip.waitFor({ state: "visible", timeout: 5000 }).then(() => true, () => false)) await skip.click();
|
|
||||||
|
|
||||||
await page.goto("/app/agency/mailboxes");
|
await page.goto("/app/agency/mailboxes");
|
||||||
await expect(page.getByText("Inbox vendor accounts")).toBeVisible();
|
await expect(page.getByText("Inbox vendor accounts")).toBeVisible();
|
||||||
await expect(page.getByRole("button", { name: /Open in|@/ }).first()).toBeVisible();
|
await expect(page.getByRole("button", { name: /Open in|@/ }).first()).toBeVisible();
|
||||||
@@ -47,11 +42,12 @@ test("an agency sees every client's mailboxes and hands a vendor account to a cl
|
|||||||
await connect.getByRole("radio", { name: "Mailforge" }).click();
|
await connect.getByRole("radio", { name: "Mailforge" }).click();
|
||||||
await connect.getByLabel("API key").fill("qa-agency-key");
|
await connect.getByLabel("API key").fill("qa-agency-key");
|
||||||
await connect.getByLabel("Name, for your team").fill("Agency Mailforge");
|
await connect.getByLabel("Name, for your team").fill("Agency Mailforge");
|
||||||
await proof.dwell(700);
|
|
||||||
await proof.shot("agency-vendor-connect", { caption: "A vendor account connected once for the whole agency" });
|
|
||||||
await connect.getByRole("button", { name: "Connect", exact: true }).click();
|
await connect.getByRole("button", { name: "Connect", exact: true }).click();
|
||||||
await confirmIfAsked(page);
|
await confirmIfAsked(page);
|
||||||
await expect(page.getByText("Not used for a client yet")).toBeVisible();
|
await expect(page.getByText("Not used for a client yet")).toBeVisible();
|
||||||
|
await expect(page.getByText("Agency Mailforge")).toBeVisible();
|
||||||
|
await proof.dwell(700);
|
||||||
|
await proof.shot("agency-vendor-connect", { caption: "A vendor account connected once for the whole agency" });
|
||||||
|
|
||||||
// Handing it to a client opens that client's own import on the account, with no key to paste.
|
// Handing it to a client opens that client's own import on the account, with no key to paste.
|
||||||
await page.getByRole("button", { name: "Add to a client" }).click();
|
await page.getByRole("button", { name: "Add to a client" }).click();
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { expect, test } from "../lib/proof.ts";
|
||||||
|
|
||||||
|
// A client connects many mailboxes at once from its own inbox vendor account, through a connect link.
|
||||||
|
// Needs fixtures/admin-agencies.sql, the portal service in front of this stack and the mock vendors; see the README.
|
||||||
|
const PORTAL = process.env.QA_PORTAL_URL ?? "";
|
||||||
|
|
||||||
|
test("a client connects mailboxes from its vendor account through a connect link", async ({ page, proof }) => {
|
||||||
|
test.skip(!PORTAL, "Run the portal service against this stack, start it with QA_VENDOR_MOCK=1, and set QA_PORTAL_URL.");
|
||||||
|
|
||||||
|
await page.goto("/app/emails");
|
||||||
|
|
||||||
|
// The agency makes the link; a vendor account is one of the ways in.
|
||||||
|
await page.getByRole("button", { name: "Invite client to connect" }).click();
|
||||||
|
const dialog = page.getByRole("dialog", { name: "Invite client to connect" });
|
||||||
|
await expect(dialog.getByText("Inbox vendor account")).toBeVisible();
|
||||||
|
await proof.dwell(900);
|
||||||
|
await proof.shot("connect-link-vendor-option", { caption: "The link's ways to connect now include an inbox vendor account" });
|
||||||
|
await dialog.getByRole("button", { name: "Create link" }).click();
|
||||||
|
const address = await dialog.locator("input[readonly]").inputValue();
|
||||||
|
expect(address).toContain("/connect/");
|
||||||
|
|
||||||
|
// The client opens it with no account.
|
||||||
|
await page.goto(address.replace(/^https?:\/\/[^/]+/, PORTAL));
|
||||||
|
await page.getByRole("button", { name: "Connect many from my inbox vendor" }).click();
|
||||||
|
await page.getByLabel("Vendor").selectOption({ label: "Mailforge" });
|
||||||
|
await page.getByLabel("API key").fill("qa-client-key");
|
||||||
|
await proof.dwell(900);
|
||||||
|
await proof.shot("client-vendor-key", { caption: "The client names its vendor account once" });
|
||||||
|
await page.getByRole("button", { name: "Find my mailboxes" }).click();
|
||||||
|
|
||||||
|
await expect(page.getByRole("heading", { name: "Pick the mailboxes to connect" })).toBeVisible();
|
||||||
|
await expect(page.getByText(/@sunrisehq\.test/).first()).toBeVisible();
|
||||||
|
await proof.dwell(900);
|
||||||
|
await proof.shot("client-vendor-pick", { caption: "The account's mailboxes, picked up to what the link allows" });
|
||||||
|
await page.getByRole("button", { name: /^Connect \d+ mailbox/ }).click();
|
||||||
|
|
||||||
|
await expect(page.getByRole("heading", { name: /being connected/ })).toBeVisible();
|
||||||
|
await proof.dwell(900);
|
||||||
|
await proof.shot("client-vendor-started", { caption: "The import runs in the workspace; the client is done" });
|
||||||
|
});
|
||||||
@@ -140,6 +140,8 @@ function VendorAccounts({
|
|||||||
{a.clients.length === 0
|
{a.clients.length === 0
|
||||||
? "Not used for a client yet"
|
? "Not used for a client yet"
|
||||||
: `${plural(a.mailboxes, "mailbox", "mailboxes")} in ${a.clients.map((c) => c.name).join(", ")}`}
|
: `${plural(a.mailboxes, "mailbox", "mailboxes")} in ${a.clients.map((c) => c.name).join(", ")}`}
|
||||||
|
{/* A client whose mailboxes the caller cannot list is named, and its count is not in the number. */}
|
||||||
|
{a.clients.some((c) => c.mailboxes_hidden) && " (not counting clients whose mailboxes you cannot list)"}
|
||||||
</div>
|
</div>
|
||||||
{a.status === "invalid" && (
|
{a.status === "invalid" && (
|
||||||
<p className="text-[11.5px] text-red-700 leading-snug">{a.last_error || "The vendor no longer accepts this key."}</p>
|
<p className="text-[11.5px] text-red-700 leading-snug">{a.last_error || "The vendor no longer accepts this key."}</p>
|
||||||
@@ -212,6 +214,14 @@ function AgencyMailboxes() {
|
|||||||
const [vendorDialog, setVendorDialog] = React.useState<{ account?: AgencyVendorAccount } | null>(null);
|
const [vendorDialog, setVendorDialog] = React.useState<{ account?: AgencyVendorAccount } | null>(null);
|
||||||
const [linkOpen, setLinkOpen] = React.useState(false);
|
const [linkOpen, setLinkOpen] = React.useState(false);
|
||||||
|
|
||||||
|
// A dialog belongs to the agency it was opened in. When another agency is selected (here or in another
|
||||||
|
// tab) it is closed, so a key typed for one agency is never submitted to another.
|
||||||
|
React.useEffect(() => {
|
||||||
|
setVendorDialog(null);
|
||||||
|
setAdding(null);
|
||||||
|
setClientFilter([]);
|
||||||
|
}, [agencyId]);
|
||||||
|
|
||||||
if (!agency) return null;
|
if (!agency) return null;
|
||||||
const canManage = agency.role === "owner" || agency.role === "admin";
|
const canManage = agency.role === "owner" || agency.role === "admin";
|
||||||
const clients = overview.data?.clients ?? [];
|
const clients = overview.data?.clients ?? [];
|
||||||
@@ -220,6 +230,9 @@ function AgencyMailboxes() {
|
|||||||
const totals = overview.data?.totals;
|
const totals = overview.data?.totals;
|
||||||
const filtered = attention || q !== "" || chosen.length > 0;
|
const filtered = attention || q !== "" || chosen.length > 0;
|
||||||
const busy = pending || giveAccount.isPending;
|
const busy = pending || giveAccount.isPending;
|
||||||
|
// The overview carries a client's mailbox numbers only when the caller can list its mailboxes.
|
||||||
|
const inView = chosen.length ? clients.filter((c) => chosen.includes(c.organization_id)) : clients;
|
||||||
|
const noAccess = !!overview.data && inView.length > 0 && inView.every((c) => !c.mailboxes);
|
||||||
// Adding mailboxes needs a client the caller manages mailboxes in; without one the action cannot succeed.
|
// Adding mailboxes needs a client the caller manages mailboxes in; without one the action cannot succeed.
|
||||||
const canAdd = clients.some((c) => c.manage_mailboxes);
|
const canAdd = clients.some((c) => c.manage_mailboxes);
|
||||||
const cannotAdd = clients.length === 0 ? "Add a client first." : "You do not manage mailboxes in any of this agency's clients.";
|
const cannotAdd = clients.length === 0 ? "Add a client first." : "You do not manage mailboxes in any of this agency's clients.";
|
||||||
@@ -250,9 +263,12 @@ function AgencyMailboxes() {
|
|||||||
user.setAddEmail(true);
|
user.setAddEmail(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
const askRemove = (a: AgencyVendorAccount) =>
|
const askRemove = (a: AgencyVendorAccount) => {
|
||||||
confirm.show(
|
// A client whose mailboxes the caller cannot list is used all the same, and its count is not in the total.
|
||||||
`Remove ${a.label}? The ${plural(a.mailboxes, "mailbox", "mailboxes")} it brought in stay connected in every client. They just stop picking up new passwords from ${vendorLabel(a.vendor)} on their own.`,
|
const unseen = a.clients.filter((c) => c.mailboxes_hidden).length;
|
||||||
|
const also = unseen ? `, and the ones in ${plural(unseen, "client", "clients")} whose mailboxes you cannot list,` : "";
|
||||||
|
return confirm.show(
|
||||||
|
`Remove ${a.label}? The ${plural(a.mailboxes, "mailbox", "mailboxes")} it brought in${also} stay connected. They just stop picking up new passwords from ${vendorLabel(a.vendor)} on their own.`,
|
||||||
async () => {
|
async () => {
|
||||||
try {
|
try {
|
||||||
await removeAccount.mutateAsync(a.id);
|
await removeAccount.mutateAsync(a.id);
|
||||||
@@ -264,6 +280,7 @@ function AgencyMailboxes() {
|
|||||||
undefined,
|
undefined,
|
||||||
{ title: "Remove vendor account", confirmLabel: "Remove" },
|
{ title: "Remove vendor account", confirmLabel: "Remove" },
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<PageBody>
|
<PageBody>
|
||||||
@@ -329,11 +346,13 @@ function AgencyMailboxes() {
|
|||||||
<LoadFailed what="the mailboxes" error={mailboxes.error} onRetry={() => void mailboxes.refetch()} />
|
<LoadFailed what="the mailboxes" error={mailboxes.error} onRetry={() => void mailboxes.refetch()} />
|
||||||
) : rows.length === 0 ? (
|
) : rows.length === 0 ? (
|
||||||
<EmptyBlock
|
<EmptyBlock
|
||||||
title={filtered ? "No mailbox matches" : "No mailboxes yet"}
|
title={noAccess ? "No mailboxes you can list" : filtered ? "No mailbox matches" : "No mailboxes yet"}
|
||||||
body={
|
body={
|
||||||
filtered
|
noAccess
|
||||||
? "Nothing matches these filters."
|
? "You cannot list the mailboxes of the clients shown here. Your access in a client's workspace decides what this page shows."
|
||||||
: "Add mailboxes for a client yourself, from a vendor account or a file, or send the client a link to connect its own."
|
: filtered
|
||||||
|
? "Nothing matches these filters."
|
||||||
|
: "Add mailboxes for a client yourself, from a vendor account or a file, or send the client a link to connect its own."
|
||||||
}
|
}
|
||||||
cta={!filtered && canAdd ? <TopbarAction onClick={() => setAdding({})}>Add mailboxes</TopbarAction> : undefined}
|
cta={!filtered && canAdd ? <TopbarAction onClick={() => setAdding({})}>Add mailboxes</TopbarAction> : undefined}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ function Panel({
|
|||||||
onToggle,
|
onToggle,
|
||||||
failure,
|
failure,
|
||||||
card,
|
card,
|
||||||
|
cardMissing,
|
||||||
used,
|
used,
|
||||||
dirty,
|
dirty,
|
||||||
saving,
|
saving,
|
||||||
@@ -92,6 +93,8 @@ function Panel({
|
|||||||
onToggle: (on: boolean) => void;
|
onToggle: (on: boolean) => void;
|
||||||
failure?: Failure;
|
failure?: Failure;
|
||||||
card?: Card;
|
card?: Card;
|
||||||
|
/** The card was looked up and there is none; false when it simply could not be read. */
|
||||||
|
cardMissing?: boolean;
|
||||||
/** What this month has used of its limit, shown while on. */
|
/** What this month has used of its limit, shown while on. */
|
||||||
used?: string;
|
used?: string;
|
||||||
/** The numbers differ from what is saved. Nothing is sent, and nothing can be charged, until Save. */
|
/** The numbers differ from what is saved. Nothing is sent, and nothing can be charged, until Save. */
|
||||||
@@ -168,7 +171,9 @@ function Panel({
|
|||||||
<span>
|
<span>
|
||||||
{card
|
{card
|
||||||
? `Charged to ${cardName(card)}, the card your plan is paid with. You get an invoice and a notification for each top-up.`
|
? `Charged to ${cardName(card)}, the card your plan is paid with. You get an invoice and a notification for each top-up.`
|
||||||
: "You have no saved card yet. Automatic top-up charges the card your plan is paid with, so it can be turned on once a plan is bought with a card."}
|
: cardMissing
|
||||||
|
? "You have no saved card yet. Automatic top-up charges the card your plan is paid with, so it can be turned on once a plan is bought with a card."
|
||||||
|
: "We could not read your saved card just now, so automatic top-up cannot be turned on. Reload the page to try again."}
|
||||||
{enabled && used && ` ${used}`}
|
{enabled && used && ` ${used}`}
|
||||||
</span>
|
</span>
|
||||||
</p>
|
</p>
|
||||||
@@ -227,11 +232,12 @@ export function SendsAutoTopup({ agencyId, canManage }: { agencyId: string; canM
|
|||||||
}
|
}
|
||||||
enabled={data.enabled}
|
enabled={data.enabled}
|
||||||
loading={false}
|
loading={false}
|
||||||
// Turning it off always works; turning it on needs a pool to top up and a card to charge.
|
// Turning it off always works; turning it on needs a pool to top up and a card that was read.
|
||||||
canToggle={canManage && !save.isPending && (data.enabled || (data.available && !data.card_missing))}
|
canToggle={canManage && !save.isPending && (data.enabled || (data.available && !!data.card))}
|
||||||
onToggle={(enabled) => void apply(enabled, !enabled)}
|
onToggle={(enabled) => void apply(enabled, !enabled)}
|
||||||
failure={data.failure}
|
failure={data.failure}
|
||||||
card={data.card}
|
card={data.card}
|
||||||
|
cardMissing={data.card_missing}
|
||||||
used={`This month: ${data.bought_this_period} of ${data.max_packs} used.`}
|
used={`This month: ${data.bought_this_period} of ${data.max_packs} used.`}
|
||||||
dirty={dirty}
|
dirty={dirty}
|
||||||
saving={save.isPending}
|
saving={save.isPending}
|
||||||
@@ -320,10 +326,11 @@ export function AIAutoTopup({ agencyId, canManage }: { agencyId: string; canMana
|
|||||||
enabled={data.enabled}
|
enabled={data.enabled}
|
||||||
loading={false}
|
loading={false}
|
||||||
// Turning it off always works; turning it on needs a balance to add to and numbers that can be saved.
|
// Turning it off always works; turning it on needs a balance to add to and numbers that can be saved.
|
||||||
canToggle={canManage && !save.isPending && (data.enabled || (data.available && !problem && !data.card_missing))}
|
canToggle={canManage && !save.isPending && (data.enabled || (data.available && !problem && !!data.card))}
|
||||||
onToggle={(enabled) => void apply(enabled, !enabled)}
|
onToggle={(enabled) => void apply(enabled, !enabled)}
|
||||||
failure={data.failure}
|
failure={data.failure}
|
||||||
card={data.card}
|
card={data.card}
|
||||||
|
cardMissing={data.card_missing}
|
||||||
used={`This month: ${fmtUsdTrim(data.added_this_period_usd)} of ${fmtUsdTrim(data.limit_usd)} used.`}
|
used={`This month: ${fmtUsdTrim(data.added_this_period_usd)} of ${fmtUsdTrim(data.limit_usd)} used.`}
|
||||||
dirty={dirty}
|
dirty={dirty}
|
||||||
saving={save.isPending}
|
saving={save.isPending}
|
||||||
|
|||||||
@@ -96,19 +96,20 @@ export default function AddMailboxesDialog({
|
|||||||
return (
|
return (
|
||||||
<AgencyDialog
|
<AgencyDialog
|
||||||
open={open}
|
open={open}
|
||||||
onClose={onClose}
|
// A choice in flight ends in a client's workspace; it is not abandoned half way.
|
||||||
|
onClose={busy ? () => undefined : onClose}
|
||||||
eyebrow="Mailboxes"
|
eyebrow="Mailboxes"
|
||||||
title={preset ? `Add mailboxes from ${preset.label}` : client ? `Add mailboxes to ${client.name}` : "Add mailboxes"}
|
title={preset ? `Add mailboxes from ${preset.label}` : client ? `Add mailboxes to ${client.name}` : "Add mailboxes"}
|
||||||
icon={<PlusIcon className="w-3 h-3" />}
|
icon={<PlusIcon className="w-3 h-3" />}
|
||||||
footer={
|
footer={
|
||||||
<>
|
<>
|
||||||
{step === "how" && clients.length > 1 && (
|
{step === "how" && clients.length > 1 && (
|
||||||
<button type="button" onClick={() => setOrgId(null)} className={cn(ghostBtn, "inline-flex items-center gap-1.5")}>
|
<button type="button" onClick={() => setOrgId(null)} disabled={busy} className={cn(ghostBtn, "inline-flex items-center gap-1.5 disabled:opacity-60")}>
|
||||||
<ArrowLeftIcon className="w-3 h-3" />
|
<ArrowLeftIcon className="w-3 h-3" />
|
||||||
Another client
|
Another client
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<button type="button" onClick={onClose} className={cn(ghostBtn, "ml-auto")}>
|
<button type="button" onClick={onClose} disabled={busy} className={cn(ghostBtn, "ml-auto disabled:opacity-60")}>
|
||||||
Cancel
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -38,6 +38,12 @@ export default function VendorAccountDialog({
|
|||||||
const accountId = account?.id;
|
const accountId = account?.id;
|
||||||
const start = React.useRef(account);
|
const start = React.useRef(account);
|
||||||
start.current = account;
|
start.current = account;
|
||||||
|
// One key per opening and per form as it stands, name included: sending the same form again is the same
|
||||||
|
// submission, and a changed one is never sent under a key that stood for something else.
|
||||||
|
const attempt = React.useRef("");
|
||||||
|
React.useEffect(() => {
|
||||||
|
attempt.current = crypto.randomUUID();
|
||||||
|
}, [open, accountId, vendorId, fields, label]);
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
setVendorId(start.current?.vendor ?? "");
|
setVendorId(start.current?.vendor ?? "");
|
||||||
@@ -65,6 +71,7 @@ export default function VendorAccountDialog({
|
|||||||
try {
|
try {
|
||||||
await save.mutateAsync({
|
await save.mutateAsync({
|
||||||
id: account?.id,
|
id: account?.id,
|
||||||
|
idempotencyKey: attempt.current,
|
||||||
input: { vendor: vendor.id, label: label.trim() || undefined, fields: !account || typed ? fields : undefined },
|
input: { vendor: vendor.id, label: label.trim() || undefined, fields: !account || typed ? fields : undefined },
|
||||||
});
|
});
|
||||||
toast.success(account ? (typed ? "Key updated for every client that uses it" : "Saved") : `${vendor.label} connected`);
|
toast.success(account ? (typed ? "Key updated for every client that uses it" : "Saved") : `${vendor.label} connected`);
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ interface Draft {
|
|||||||
|
|
||||||
const emptyDraft = (): Draft => ({
|
const emptyDraft = (): Draft => ({
|
||||||
label: "",
|
label: "",
|
||||||
providers: ["gmail", "outlook", "smtp_imap"],
|
providers: ["gmail", "outlook", "smtp_imap", "vendor"],
|
||||||
max: 5,
|
max: 5,
|
||||||
expiry: "7",
|
expiry: "7",
|
||||||
tags: [],
|
tags: [],
|
||||||
@@ -254,6 +254,12 @@ function NewLinkForm({ draft, setDraft }: { draft: Draft; setDraft: React.Dispat
|
|||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
{draft.providers.includes("vendor") && (
|
||||||
|
<span className="text-[11px] leading-snug text-slate-400">
|
||||||
|
With a vendor account, the client pastes the API key of Zapmail, InboxKit or another vendor and picks its mailboxes, many at
|
||||||
|
once. The key is kept here as one of this workspace's vendor accounts.
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||||
<div className="flex flex-col gap-1.5">
|
<div className="flex flex-col gap-1.5">
|
||||||
|
|||||||
@@ -25,8 +25,15 @@ export const listAgencyMailboxes = (agencyId: string, filters: AgencyMailboxFilt
|
|||||||
export const listAgencyVendors = (agencyId: string, signal?: AbortSignal) =>
|
export const listAgencyVendors = (agencyId: string, signal?: AbortSignal) =>
|
||||||
Request<AgencyVendorAccountList>({ method: "GET", url: `/agency/${agencyId}/vendors`, authorization: true, signal });
|
Request<AgencyVendorAccountList>({ method: "GET", url: `/agency/${agencyId}/vendors`, authorization: true, signal });
|
||||||
|
|
||||||
export const createAgencyVendor = (agencyId: string, data: AgencyVendorAccountInput) =>
|
/** The key names one submission, so sending it again after a lost answer does not connect the account twice. */
|
||||||
Request<AgencyVendorAccount>({ method: "POST", url: `/agency/${agencyId}/vendors`, data, authorization: true });
|
export const createAgencyVendor = (agencyId: string, data: AgencyVendorAccountInput, idempotencyKey?: string) =>
|
||||||
|
Request<AgencyVendorAccount>({
|
||||||
|
method: "POST",
|
||||||
|
url: `/agency/${agencyId}/vendors`,
|
||||||
|
data,
|
||||||
|
headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined,
|
||||||
|
authorization: true,
|
||||||
|
});
|
||||||
|
|
||||||
export const updateAgencyVendor = (agencyId: string, id: string, data: AgencyVendorAccountInput) =>
|
export const updateAgencyVendor = (agencyId: string, id: string, data: AgencyVendorAccountInput) =>
|
||||||
Request<AgencyVendorAccount>({ method: "PATCH", url: `/agency/${agencyId}/vendors/${id}`, data, authorization: true });
|
Request<AgencyVendorAccount>({ method: "PATCH", url: `/agency/${agencyId}/vendors/${id}`, data, authorization: true });
|
||||||
|
|||||||
@@ -57,7 +57,6 @@ export function useAgencyMailboxes(agencyId: string | undefined, filters: Agency
|
|||||||
return useInfiniteQuery({
|
return useInfiniteQuery({
|
||||||
...agencyMailboxesQuery(agencyId ?? "", filters),
|
...agencyMailboxesQuery(agencyId ?? "", filters),
|
||||||
enabled: !!agencyId,
|
enabled: !!agencyId,
|
||||||
placeholderData: (prev) => prev,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,8 +76,8 @@ function useRefreshVendors(agencyId: string) {
|
|||||||
export function useSaveAgencyVendor(agencyId: string) {
|
export function useSaveAgencyVendor(agencyId: string) {
|
||||||
const refresh = useRefreshVendors(agencyId);
|
const refresh = useRefreshVendors(agencyId);
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: ({ id, input }: { id?: string; input: AgencyVendorAccountInput }) =>
|
mutationFn: ({ id, input, idempotencyKey }: { id?: string; input: AgencyVendorAccountInput; idempotencyKey?: string }) =>
|
||||||
id ? updateAgencyVendor(agencyId, id, input) : createAgencyVendor(agencyId, input),
|
id ? updateAgencyVendor(agencyId, id, input) : createAgencyVendor(agencyId, input, idempotencyKey),
|
||||||
onSettled: refresh,
|
onSettled: refresh,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// A client connect link: a client opens it and connects their own mailboxes into the workspace.
|
// A client connect link: a client opens it and connects their own mailboxes into the workspace.
|
||||||
|
|
||||||
export type ConnectLinkProvider = "gmail" | "outlook" | "smtp_imap";
|
/** The ways a client may connect: one mailbox at a time, or many from an inbox vendor account. */
|
||||||
|
export type ConnectLinkProvider = "gmail" | "outlook" | "smtp_imap" | "vendor";
|
||||||
export type ConnectLinkStatus = "active" | "expired" | "revoked" | "exhausted";
|
export type ConnectLinkStatus = "active" | "expired" | "revoked" | "exhausted";
|
||||||
|
|
||||||
export interface ConnectLink {
|
export interface ConnectLink {
|
||||||
@@ -53,4 +54,5 @@ export const CONNECT_LINK_PROVIDERS: { id: ConnectLinkProvider; label: string }[
|
|||||||
{ id: "gmail", label: "Google" },
|
{ id: "gmail", label: "Google" },
|
||||||
{ id: "outlook", label: "Microsoft" },
|
{ id: "outlook", label: "Microsoft" },
|
||||||
{ id: "smtp_imap", label: "IMAP / SMTP" },
|
{ id: "smtp_imap", label: "IMAP / SMTP" },
|
||||||
|
{ id: "vendor", label: "Inbox vendor account" },
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in New Issue
Block a user