From b862ef280458ebff538f1e13d2d3c4ba62de15b2 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 16:26:28 +0100 Subject: [PATCH 1/9] feat: let a client connect an inbox vendor account from a connect link and pick many mailboxes at once, with the key sent once, held sealed for minutes and never returned to the page, the picked mailboxes imported in the creator's name within the link's limit, and the option offered in the dashboard's link dialog --- cmd/backend/main.go | 4 + docs/content/docs/api/endpoints.mdx | 2 +- docs/content/docs/api/error-codes.mdx | 7 +- .../content/docs/development/data-control.mdx | 1 + docs/content/docs/guides/agencies.mdx | 5 +- docs/content/docs/guides/mailboxes.mdx | 2 +- internal/api/handler/internal_connect.go | 54 ++++ internal/api/routes.go | 2 + internal/app/connectlink/errors.go | 6 +- internal/app/connectlink/service.go | 12 +- internal/app/connectlink/vendor.go | 217 +++++++++++++++ internal/app/connectlink/vendor_test.go | 216 +++++++++++++++ internal/app/vendorconn/agency_test.go | 23 ++ internal/app/vendorconn/hold.go | 130 +++++++++ internal/app/vendorconn/service.go | 24 +- internal/formwire/connect.go | 60 ++++ .../000390_connect_link_vendor.down.sql | 8 + .../000390_connect_link_vendor.up.sql | 5 + internal/models/connect_link.go | 7 +- internal/repository/pg_client_connect_link.go | 29 ++ portal/src/ConnectPage.tsx | 25 +- portal/src/ConnectVendor.tsx | 257 ++++++++++++++++++ portal/src/connect.css | 49 ++++ portal/src/connectApi.ts | 54 +++- portal/src/icons.tsx | 10 + portal/worker/portal.mjs | 41 ++- portal/worker/portal.test.mjs | 20 +- .../connect-links/ConnectLinksDialog.tsx | 8 +- .../lib/api/models/app/emails/ConnectLink.ts | 4 +- 29 files changed, 1260 insertions(+), 22 deletions(-) create mode 100644 internal/app/connectlink/vendor.go create mode 100644 internal/app/connectlink/vendor_test.go create mode 100644 internal/app/vendorconn/hold.go create mode 100644 internal/infrastructure/db/migrations/000390_connect_link_vendor.down.sql create mode 100644 internal/infrastructure/db/migrations/000390_connect_link_vendor.up.sql create mode 100644 portal/src/ConnectVendor.tsx diff --git a/cmd/backend/main.go b/cmd/backend/main.go index 32227eaf9..b76747203 100644 --- a/cmd/backend/main.go +++ b/cmd/backend/main.go @@ -2129,6 +2129,10 @@ func main() { Cache: cache, 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. if agencyService != nil { vendorConnService.WireAgencies(repository.NewAgencyVendorRepository(primaryDB), agencyService, repository.NewAgencyHomeRepository(primaryDB.Pool), credEncrypter) diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 199dfa691..9aaf5a7f6 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -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). -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). diff --git a/docs/content/docs/api/error-codes.mdx b/docs/content/docs/api/error-codes.mdx index 601bdd2ba..33f007eb5 100644 --- a/docs/content/docs/api/error-codes.mdx +++ b/docs/content/docs/api/error-codes.mdx @@ -1625,7 +1625,7 @@ use generic errors and explicit unavailable/stale coverage, not outage inference | `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_expiry` | 400 | `expires_in_days` is outside 1 to 90 | | `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_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_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 | A workspace at its mailbox allowance refuses the connect with the usual `mailbox_allowance_reached`, which the page words for the client. diff --git a/docs/content/docs/development/data-control.mdx b/docs/content/docs/development/data-control.mdx index 9618841b7..19f217495 100644 --- a/docs/content/docs/development/data-control.mdx +++ b/docs/content/docs/development/data-control.mdx @@ -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 | | `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 | | `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 | diff --git a/docs/content/docs/guides/agencies.mdx b/docs/content/docs/guides/agencies.mdx index e50695403..98346e933 100644 --- a/docs/content/docs/guides/agencies.mdx +++ b/docs/content/docs/guides/agencies.mdx @@ -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) | | **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 | -| **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. @@ -227,13 +227,14 @@ The accounts are listed with `GET /agency/:agencyId/vendors` and connected with ## 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 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. +- **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. 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. diff --git a/docs/content/docs/guides/mailboxes.mdx b/docs/content/docs/guides/mailboxes.mdx index 5bd50f9eb..16d0e4993 100644 --- a/docs/content/docs/guides/mailboxes.mdx +++ b/docs/content/docs/guides/mailboxes.mdx @@ -342,7 +342,7 @@ See [Import mailboxes](/guides/mailbox-import/) for the columns, what each provi ## 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. diff --git a/internal/api/handler/internal_connect.go b/internal/api/handler/internal_connect.go index df2a4f6ca..79e1e134a 100644 --- a/internal/api/handler/internal_connect.go +++ b/internal/api/handler/internal_connect.go @@ -4,6 +4,7 @@ import ( "context" "net/http" "net/url" + "strconv" "github.com/gin-gonic/gin" "github.com/rs/zerolog/log" @@ -151,6 +152,59 @@ 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 + } + // Recorded in the creator's name, which is what refreshes every teammate's mailbox list and imports. + if h.AuditService != nil && res.Import != nil { + importID := res.Import.ID + meta := map[string]string{"via": "connect_link", "connect_link_id": res.Link.ID.String(), "vendor": res.Vendor, "mailboxes": strconv.Itoa(len(res.Emails))} + h.AuditService.LogAction(c.Request.Context(), res.Link.OrganizationID, res.ActorID, models.AuditActionCreate, models.AuditEntityMailboxImport, &importID, + req.RemoteIP, c.Request.UserAgent(), nil, meta) + 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. func (h *Handler) auditConnectLinkUse(c *gin.Context, res *connectlink.Result, remoteIP string) { acc := res.Account diff --git a/internal/api/routes.go b/internal/api/routes.go index 865805f5c..dd8fdf003 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -281,6 +281,8 @@ func Run( portal.POST("/connect-links/oauth/start", h.InternalStartConnectOAuth) portal.POST("/connect-links/oauth/result", h.InternalConnectOAuthResult) 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{ diff --git a/internal/app/connectlink/errors.go b/internal/app/connectlink/errors.go index cbbaa2040..fcffd25b4 100644 --- a/internal/app/connectlink/errors.go +++ b/internal/app/connectlink/errors.go @@ -30,11 +30,15 @@ var ( 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.") 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", "max_mailboxes must be between 1 and 500.") ErrInvalidExpiry = errx.NewWithIdentifier(errx.BadRequest, "client_link_invalid_expiry", "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", "A link can apply at most 20 tags.") ) diff --git a/internal/app/connectlink/service.go b/internal/app/connectlink/service.go index 9b5fe4424..6f9abbe77 100644 --- a/internal/app/connectlink/service.go +++ b/internal/app/connectlink/service.go @@ -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 func(ctx context.Context, orgID uuid.UUID) string 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 { d Deps 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) { 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() } + if link.Allows(models.ConnectLinkVendor) && s.d.Vendors != nil { + out.Vendors = s.vendorCatalog() + } return out } @@ -305,6 +313,8 @@ func (s *Service) providerAvailable(p models.InboxProvider) bool { switch p { case models.InboxProviderSMTPIMAP: return true + case models.ConnectLinkVendor: + return s.d.Vendors != nil case models.InboxProviderGoogle: if !config.GoogleOAuthConnect() { return false diff --git a/internal/app/connectlink/vendor.go b/internal/app/connectlink/vendor.go new file mode 100644 index 000000000..5fd4a7195 --- /dev/null +++ b/internal/app/connectlink/vendor.go @@ -0,0 +1,217 @@ +package connectlink + +import ( + "context" + "sort" + + "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 + } + giveBack := func(n int) { + if rerr := s.d.Repo.ReleaseMany(ctx, orgID, link.ID, n); rerr != nil { + log.Warn().Str("link_id", link.ID.String()).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 + } + opts := models.MailboxImportOptions{} + 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}, len(ids)) + if xerr == nil && len(emails) == 0 { + xerr = ErrNoMailboxes + } + if xerr != nil { + giveBack(len(ids)) + if derr := s.d.Vendors.Delete(ctx, 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") + } + 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) + } + link.MailboxesConnected += len(emails) + 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}) +} diff --git a/internal/app/connectlink/vendor_test.go b/internal/app/connectlink/vendor_test.go new file mode 100644 index 000000000..3c67b8282 --- /dev/null +++ b/internal/app/connectlink/vendor_test.go @@ -0,0 +1,216 @@ +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 { + if b.ID == id { + 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 TestAFailedVendorImportGivesItsSlotsBack(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) + } + 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 != 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 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) + } +} diff --git a/internal/app/vendorconn/agency_test.go b/internal/app/vendorconn/agency_test.go index 670a9f533..502abf645 100644 --- a/internal/app/vendorconn/agency_test.go +++ b/internal/app/vendorconn/agency_test.go @@ -373,6 +373,29 @@ func TestAKeylessRefusalRecordedByAnOlderReleaseDoesNotStick(t *testing.T) { f.svc.healAgencyLinks(ctx) if f.conns.conns[conn.ID].Status != "invalid" { t.Fatal("a refusal by the vendor was cleared") + +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") } } diff --git a/internal/app/vendorconn/hold.go b/internal/app/vendorconn/hold.go new file mode 100644 index 000000000..8e49dd9cb --- /dev/null +++ b/internal/app/vendorconn/hold.go @@ -0,0 +1,130 @@ +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 } + +// 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 +} diff --git a/internal/app/vendorconn/service.go b/internal/app/vendorconn/service.go index 500167bf7..a9ab2776c 100644 --- a/internal/app/vendorconn/service.go +++ b/internal/app/vendorconn/service.go @@ -485,34 +485,50 @@ type ImportInput struct { // Import starts a background import of the picked vendor mailboxes. Their // 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) { + 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 { - return nil, errx.InternalError() + return nil, nil, errx.InternalError() } c, xerr := s.get(ctx, orgID, id) if xerr != nil { - return nil, xerr + return nil, nil, xerr } boxes, xerr := s.Mailboxes(ctx, orgID, id) if xerr != nil { - return nil, xerr + return nil, nil, xerr + } + max := 0 + if len(limit) > 0 { + max = limit[0] } want := map[string]bool{} for _, m := range in.MailboxIDs { want[m] = true } rows := make([]mailboximport.ListRow, 0) + emails := make([]string, 0) for _, m := range boxes { if !want[m.ID] && !(in.All && !m.Connected) { continue } + if max > 0 && len(rows) >= max { + break + } + emails = append(emails, m.Email) cid := c.ID rows = append(rows, mailboximport.ListRow{ 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, }) + return imp, emails, xerr } // credentials reads one vendor mailbox's credentials. diff --git a/internal/formwire/connect.go b/internal/formwire/connect.go index 19782026f..2c093700e 100644 --- a/internal/formwire/connect.go +++ b/internal/formwire/connect.go @@ -29,6 +29,66 @@ type ConnectLink struct { // WorkspaceFull is the workspace at its mailbox allowance, so no connect can succeed now. WorkspaceFull bool `json:"workspace_full,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. diff --git a/internal/infrastructure/db/migrations/000390_connect_link_vendor.down.sql b/internal/infrastructure/db/migrations/000390_connect_link_vendor.down.sql new file mode 100644 index 000000000..3258c17db --- /dev/null +++ b/internal/infrastructure/db/migrations/000390_connect_link_vendor.down.sql @@ -0,0 +1,8 @@ +-- A link that only took a vendor account has no way left to connect, so it is turned off. +UPDATE client_connect_links SET revoked_at = COALESCE(revoked_at, now()), allowed_providers = ARRAY['smtp_imap']::text[] +WHERE allowed_providers = ARRAY['vendor']::text[]; +UPDATE client_connect_links SET allowed_providers = array_remove(allowed_providers, 'vendor') WHERE 'vendor' = ANY (allowed_providers); +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[]); diff --git a/internal/infrastructure/db/migrations/000390_connect_link_vendor.up.sql b/internal/infrastructure/db/migrations/000390_connect_link_vendor.up.sql new file mode 100644 index 000000000..4324f3030 --- /dev/null +++ b/internal/infrastructure/db/migrations/000390_connect_link_vendor.up.sql @@ -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[]); diff --git a/internal/models/connect_link.go b/internal/models/connect_link.go index 6104ca4d1..5f106386b 100644 --- a/internal/models/connect_link.go +++ b/internal/models/connect_link.go @@ -16,8 +16,11 @@ const ( ClientConnectLinkExhausted ClientConnectLinkStatus = "exhausted" ) -// ConnectLinkProviders are the ways a client may connect, as stored in email_provider. -var ConnectLinkProviders = []InboxProvider{InboxProviderGoogle, InboxProviderOutlook, InboxProviderSMTPIMAP} +// ConnectLinkVendor is the way in that is not one mailbox: the client connects an inbox vendor account and picks its mailboxes. +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 ( // ClientConnectLinkMaxMailboxes bounds one link's mailboxes, matching the table's check. diff --git a/internal/repository/pg_client_connect_link.go b/internal/repository/pg_client_connect_link.go index 5d0e38cca..bbb3e090d 100644 --- a/internal/repository/pg_client_connect_link.go +++ b/internal/repository/pg_client_connect_link.go @@ -26,6 +26,9 @@ type ClientConnectLinkRepository interface { Reserve(ctx context.Context, orgID, id uuid.UUID) (bool, *errx.Error) // Release gives back a slot whose connect failed. 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 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 } +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 { err := r.DB.QueryRow(ctx, ` INSERT INTO client_connect_link_uses (link_id, organization_id, email_account_id, email, provider, remote_ip_hash) diff --git a/portal/src/ConnectPage.tsx b/portal/src/ConnectPage.tsx index 99437730a..007dd9d1f 100644 --- a/portal/src/ConnectPage.tsx +++ b/portal/src/ConnectPage.tsx @@ -28,8 +28,9 @@ import { startConnectResizeReporting, } from "./connectEmbed"; import { CUSTOM_PRESET, MAIL_PRESETS } from "./connectPresets"; +import { VendorForm } from "./ConnectVendor"; 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 { StalePage } from "./NotFound"; import type { Brand } from "./theme"; @@ -42,7 +43,7 @@ interface Connected { provider: string; } -type View = "choose" | "imap" | "waiting"; +type View = "choose" | "imap" | "vendor" | "waiting"; const POLL_MS = 2000; const POLL_MAX_MS = 10 * 60 * 1000; @@ -194,6 +195,14 @@ export function ConnectPage() { setView("choose"); }} /> + ) : view === "vendor" ? ( + errorCopy(e, workspace)} + onBack={() => setView("choose")} + onStarted={() => void qc.invalidateQueries({ queryKey: ["connect", token] })} + /> ) : view === "waiting" ? (
@@ -261,6 +270,10 @@ export function ConnectPage() { setError(null); setView("imap"); }} + onVendor={() => { + setError(null); + setView("vendor"); + }} /> )} @@ -359,6 +372,7 @@ function ProviderButtons({ onWaiting, onDone, onImap, + onVendor, }: { token: string; link: ConnectLink; @@ -366,6 +380,7 @@ function ProviderButtons({ onWaiting: () => void; onDone: (o: { status: string; email?: string; provider?: string; code?: string; message?: string; connected?: number }) => void; onImap: () => void; + onVendor: () => void; }) { const [busy, setBusy] = useState(null); const poll = useRef(null); @@ -432,6 +447,12 @@ function ProviderButtons({ Use IMAP and SMTP details )} + {has("vendor") && (link.vendors?.length ?? 0) > 0 && ( + + )} {link.providers.length === 0 &&

This link has no way to connect a mailbox on this server. Ask for a new link.

}
); diff --git a/portal/src/ConnectVendor.tsx b/portal/src/ConnectVendor.tsx new file mode 100644 index 000000000..ec776e43a --- /dev/null +++ b/portal/src/ConnectVendor.tsx @@ -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 = { 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>({}); + const [captcha, setCaptcha] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [found, setFound] = useState(null); + const [picked, setPicked] = useState>(new Set()); + const [started, setStarted] = useState(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) { + setError(errorCopy(err)); + // A ticket is good once and for a few minutes; after that the key is asked for again. + if (err instanceof ConnectError && err.code === "mailbox_vendor_hold_expired") startOver(); + } 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 ( +
+ + + +

{started.mailboxes === 1 ? "Your mailbox is being connected" : `Your ${started.mailboxes} mailboxes are being connected`}

+

+ 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. +

+ +
+ ); + } + + if (found) { + return ( +
+ +

Pick the mailboxes to connect

+

+ {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.`} +

+ {open.length > 0 && ( +
+ + +
+ )} +
    + {found.mailboxes.map((m) => { + const on = picked.has(m.id); + const full = !on && picked.size >= room; + return ( +
  • + +
  • + ); + })} +
+ {error && ( +

+ {error} +

+ )} + +
+ ); + } + + return ( +
void find(e)}> + +

Connect mailboxes from your inbox vendor

+

+ 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. +

+ {vendors.length > 1 && ( + + )} + {vendor?.fields.map((f) => ( + + ))} + {vendor?.key_help_url && ( +

+ + Where to find the {vendor.label} key + +

+ )} + {link.captcha_site_key && } + {error && ( +

+ {error} +

+ )} + + + ); +} diff --git a/portal/src/connect.css b/portal/src/connect.css index c00309078..e158bd820 100644 --- a/portal/src/connect.css +++ b/portal/src/connect.css @@ -540,3 +540,52 @@ body.embed .cx-card { .cx-sk-button + .cx-sk-button { 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); +} diff --git a/portal/src/connectApi.ts b/portal/src/connectApi.ts index 421d2ff58..7a81185a6 100644 --- a/portal/src/connectApi.ts +++ b/portal/src/connectApi.ts @@ -4,7 +4,23 @@ import { apiHeaders } from "./api"; 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 { workspace: string; @@ -16,6 +32,8 @@ export interface ConnectLink { expires_at: string; workspace_full?: boolean; captcha_site_key?: string; + /** Present when the link takes a vendor account. */ + vendors?: ConnectVendor[]; } export interface MailService { @@ -96,3 +114,37 @@ export function connectSMTPIMAP(token: string, payload: SMTPIMAPPayload): Promis export function fetchSigninOutcome(token: string, resultKey: string): Promise { 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; captcha_token?: string }, +): Promise { + return call(token, "/vendor", { method: "POST", body: JSON.stringify(payload) }); +} + +export function importVendorMailboxes(token: string, ticket: string, mailboxIds: string[]): Promise { + return call(token, "/vendor/import", { method: "POST", body: JSON.stringify({ ticket, mailbox_ids: mailboxIds }) }); +} diff --git a/portal/src/icons.tsx b/portal/src/icons.tsx index bd15f66fa..f186f7fa5 100644 --- a/portal/src/icons.tsx +++ b/portal/src/icons.tsx @@ -92,3 +92,13 @@ export function ChevronIcon({ className }: { className?: string }) { ); } + +export function StackIcon({ className }: { className?: string }) { + return ( + + + + + + ); +} diff --git a/portal/worker/portal.mjs b/portal/worker/portal.mjs index 29c83d328..e756dab5f 100644 --- a/portal/worker/portal.mjs +++ b/portal/worker/portal.mjs @@ -20,6 +20,7 @@ const PLACEHOLDER = ''; const LINK_TOKEN = /^[A-Za-z0-9_-]{43}$/; const CONNECT_MAX_BODY = 16 << 10; const ACTION_MAX_BODY = 8 << 10; +const VENDOR_IMPORT_MAX_BODY = 192 << 10; const BACKEND_MAX_BODY = 4 << 20; const LIMITER_KEYS_MAX = 16384; @@ -168,7 +169,7 @@ export function pathKind(path) { if (m) return { kind: "connect", token: m[1] }; m = /^\/r\/([^/]*)$/.exec(path); 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] }; m = /^\/api\/reports\/([^/]+)$/.exec(path); if (m) return { kind: "report-api", token: m[1] }; @@ -351,6 +352,27 @@ function service(v) { 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. async function relayConnect(ctx, path, body) { try { @@ -375,7 +397,7 @@ async function connectAPI(ctx, token, action) { const lookup = { token, host: ctx.host }; 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); if (action === "/smtp-imap") { 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, }); } + 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 (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 }); diff --git a/portal/worker/portal.test.mjs b/portal/worker/portal.test.mjs index ddbc7ce99..1b127dcd6 100644 --- a/portal/worker/portal.test.mjs +++ b/portal/worker/portal.test.mjs @@ -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", [`/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")}/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", "/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", @@ -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/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/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 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((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")); - 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) { assert.equal(c.auth, `Bearer ${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[3].body.smtp, { host: "smtp.b.test", port: 465, username: "a", password: "p", security: "tls" }); 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"); }); diff --git a/web/src/components/app/emails/connect-links/ConnectLinksDialog.tsx b/web/src/components/app/emails/connect-links/ConnectLinksDialog.tsx index 55de9defc..636099f92 100644 --- a/web/src/components/app/emails/connect-links/ConnectLinksDialog.tsx +++ b/web/src/components/app/emails/connect-links/ConnectLinksDialog.tsx @@ -54,7 +54,7 @@ interface Draft { const emptyDraft = (): Draft => ({ label: "", - providers: ["gmail", "outlook", "smtp_imap"], + providers: ["gmail", "outlook", "smtp_imap", "vendor"], max: 5, expiry: "7", tags: [], @@ -254,6 +254,12 @@ function NewLinkForm({ draft, setDraft }: { draft: Draft; setDraft: React.Dispat ))} + {draft.providers.includes("vendor") && ( + + 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. + + )}
diff --git a/web/src/lib/api/models/app/emails/ConnectLink.ts b/web/src/lib/api/models/app/emails/ConnectLink.ts index b4f63b8ae..8b2bf5350 100644 --- a/web/src/lib/api/models/app/emails/ConnectLink.ts +++ b/web/src/lib/api/models/app/emails/ConnectLink.ts @@ -1,6 +1,7 @@ // 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 interface ConnectLink { @@ -53,4 +54,5 @@ export const CONNECT_LINK_PROVIDERS: { id: ConnectLinkProvider; label: string }[ { id: "gmail", label: "Google" }, { id: "outlook", label: "Microsoft" }, { id: "smtp_imap", label: "IMAP / SMTP" }, + { id: "vendor", label: "Inbox vendor account" }, ]; From 696ed2b2d429ef51d9a5a9079c2d8059f6c77edb Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 16:34:05 +0100 Subject: [PATCH 2/9] feat: record a client connecting its vendor account through a connect link, and mark the product tour seen in the agency fixture so it does not open over a walkthrough --- qa/README.md | 8 ++++++ qa/fixtures/admin-agencies.sql | 4 ++- qa/flows/agency-mailboxes.flow.ts | 5 ---- qa/flows/client-connect-vendor.flow.ts | 40 ++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 6 deletions(-) create mode 100644 qa/flows/client-connect-vendor.flow.ts diff --git a/qa/README.md b/qa/README.md index f50361a94..c28d6f510 100644 --- a/qa/README.md +++ b/qa/README.md @@ -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: `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 `flows/member-access.flow.ts` is opt-in: apply `fixtures/member-access.sql` to diff --git a/qa/fixtures/admin-agencies.sql b/qa/fixtures/admin-agencies.sql index 5d72d0473..df017c711 100644 --- a/qa/fixtures/admin-agencies.sql +++ b/qa/fixtures/admin-agencies.sql @@ -3,7 +3,9 @@ -- proof), and "Meridian Outbound" has the seeded workspace as a client and no plan yet. Re-runnable. 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'; INSERT INTO agencies (id, name, owner_user_id, status) diff --git a/qa/flows/agency-mailboxes.flow.ts b/qa/flows/agency-mailboxes.flow.ts index 2f1b06cfb..1d397f4ed 100644 --- a/qa/flows/agency-mailboxes.flow.ts +++ b/qa/flows/agency-mailboxes.flow.ts @@ -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.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 expect(page.getByText("Inbox vendor accounts")).toBeVisible(); await expect(page.getByRole("button", { name: /Open in|@/ }).first()).toBeVisible(); diff --git a/qa/flows/client-connect-vendor.flow.ts b/qa/flows/client-connect-vendor.flow.ts new file mode 100644 index 000000000..8448d1d38 --- /dev/null +++ b/qa/flows/client-connect-vendor.flow.ts @@ -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" }); +}); From d11b35a583c921bbd83c021a47d1b0af9a819a96 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 16:47:39 +0100 Subject: [PATCH 3/9] feat: number the connect link vendor migration after main's newest and keep the workspace sealing helper beside the hold that uses it --- internal/app/vendorconn/hold.go | 15 +++++++++++++++ ...wn.sql => 000393_connect_link_vendor.down.sql} | 0 ...r.up.sql => 000393_connect_link_vendor.up.sql} | 0 3 files changed, 15 insertions(+) rename internal/infrastructure/db/migrations/{000390_connect_link_vendor.down.sql => 000393_connect_link_vendor.down.sql} (100%) rename internal/infrastructure/db/migrations/{000390_connect_link_vendor.up.sql => 000393_connect_link_vendor.up.sql} (100%) diff --git a/internal/app/vendorconn/hold.go b/internal/app/vendorconn/hold.go index 8e49dd9cb..16acb6635 100644 --- a/internal/app/vendorconn/hold.go +++ b/internal/app/vendorconn/hold.go @@ -34,6 +34,21 @@ type heldAccount struct { 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) diff --git a/internal/infrastructure/db/migrations/000390_connect_link_vendor.down.sql b/internal/infrastructure/db/migrations/000393_connect_link_vendor.down.sql similarity index 100% rename from internal/infrastructure/db/migrations/000390_connect_link_vendor.down.sql rename to internal/infrastructure/db/migrations/000393_connect_link_vendor.down.sql diff --git a/internal/infrastructure/db/migrations/000390_connect_link_vendor.up.sql b/internal/infrastructure/db/migrations/000393_connect_link_vendor.up.sql similarity index 100% rename from internal/infrastructure/db/migrations/000390_connect_link_vendor.up.sql rename to internal/infrastructure/db/migrations/000393_connect_link_vendor.up.sql From f01f791d6ef86cfbc227ef1c395157c6a85e8225 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 17:41:12 +0100 Subject: [PATCH 4/9] feat: number the connect link vendor migration after the agency vendor accounts' --- ...t_link_vendor.down.sql => 000394_connect_link_vendor.down.sql} | 0 ...nnect_link_vendor.up.sql => 000394_connect_link_vendor.up.sql} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename internal/infrastructure/db/migrations/{000393_connect_link_vendor.down.sql => 000394_connect_link_vendor.down.sql} (100%) rename internal/infrastructure/db/migrations/{000393_connect_link_vendor.up.sql => 000394_connect_link_vendor.up.sql} (100%) diff --git a/internal/infrastructure/db/migrations/000393_connect_link_vendor.down.sql b/internal/infrastructure/db/migrations/000394_connect_link_vendor.down.sql similarity index 100% rename from internal/infrastructure/db/migrations/000393_connect_link_vendor.down.sql rename to internal/infrastructure/db/migrations/000394_connect_link_vendor.down.sql diff --git a/internal/infrastructure/db/migrations/000393_connect_link_vendor.up.sql b/internal/infrastructure/db/migrations/000394_connect_link_vendor.up.sql similarity index 100% rename from internal/infrastructure/db/migrations/000393_connect_link_vendor.up.sql rename to internal/infrastructure/db/migrations/000394_connect_link_vendor.up.sql From 072bec989fbe90107710a441892f8ddd596a7ee3 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 18:34:24 +0100 Subject: [PATCH 5/9] feat: keep both sets of vendor connection tests after the rebase onto the agency mailboxes branch --- internal/app/vendorconn/agency_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/internal/app/vendorconn/agency_test.go b/internal/app/vendorconn/agency_test.go index 502abf645..94a13b3ab 100644 --- a/internal/app/vendorconn/agency_test.go +++ b/internal/app/vendorconn/agency_test.go @@ -373,6 +373,8 @@ func TestAKeylessRefusalRecordedByAnOlderReleaseDoesNotStick(t *testing.T) { f.svc.healAgencyLinks(ctx) if f.conns.conns[conn.ID].Status != "invalid" { t.Fatal("a refusal by the vendor was cleared") + } +} func TestAClientsKeyIsHeldSealedAndReadOnce(t *testing.T) { client := &fakeClient{boxes: []mailvendor.Mailbox{{ID: "m1", Email: "ava@client.test"}}} From 5678ca915a8301d8cb4d5661fef3edafa7b6ad45 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 19:35:50 +0100 Subject: [PATCH 6/9] feat: never change a mailbox the workspace already has from a client's connect link, keep a vendor import's slots and key when it may have started, refuse the connect link down migration while a link takes a vendor account, and tighten the agency mailboxes page's empty states, filters and add flow --- docs/content/docs/api/endpoints.mdx | 2 +- internal/api/handler/internal_connect.go | 7 +-- internal/app/connectlink/vendor.go | 27 ++++++--- internal/app/connectlink/vendor_test.go | 58 +++++++++++++++++-- internal/app/vendorconn/agency.go | 13 ++++- internal/app/vendorconn/agency_test.go | 21 +++++++ internal/app/vendorconn/service.go | 6 ++ .../000394_connect_link_vendor.down.sql | 12 ++-- internal/models/agency_mailbox.go | 3 +- internal/repository/pg_agency_home.go | 2 +- portal/src/ConnectPage.tsx | 6 +- portal/src/ConnectVendor.tsx | 4 +- qa/flows/agency-mailboxes.flow.ts | 5 +- web/src/app/app/agency/mailboxes/page.tsx | 23 +++++--- web/src/components/app/agency/AutoTopup.tsx | 15 +++-- .../agency/mailboxes/AddMailboxesDialog.tsx | 7 ++- .../agency/mailboxes/VendorAccountDialog.tsx | 6 ++ .../api/client/app/agency/agencyMailboxes.ts | 11 +++- .../hooks/app/agency/useAgencyMailboxes.ts | 5 +- 19 files changed, 184 insertions(+), 49 deletions(-) diff --git a/docs/content/docs/api/endpoints.mdx b/docs/content/docs/api/endpoints.mdx index 9aaf5a7f6..146313c4d 100644 --- a/docs/content/docs/api/endpoints.mdx +++ b/docs/content/docs/api/endpoints.mdx @@ -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 | | 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 | -| 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` | | 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) | diff --git a/internal/api/handler/internal_connect.go b/internal/api/handler/internal_connect.go index 79e1e134a..efc3f7857 100644 --- a/internal/api/handler/internal_connect.go +++ b/internal/api/handler/internal_connect.go @@ -191,12 +191,9 @@ func (h *Handler) InternalConnectVendorImport(c *gin.Context) { connectRefusal(c, xerr) return } - // Recorded in the creator's name, which is what refreshes every teammate's mailbox list and imports. + // 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 { - importID := res.Import.ID - meta := map[string]string{"via": "connect_link", "connect_link_id": res.Link.ID.String(), "vendor": res.Vendor, "mailboxes": strconv.Itoa(len(res.Emails))} - h.AuditService.LogAction(c.Request.Context(), res.Link.OrganizationID, res.ActorID, models.AuditActionCreate, models.AuditEntityMailboxImport, &importID, - req.RemoteIP, c.Request.UserAgent(), nil, meta) + 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) } diff --git a/internal/app/connectlink/vendor.go b/internal/app/connectlink/vendor.go index 5fd4a7195..0316877da 100644 --- a/internal/app/connectlink/vendor.go +++ b/internal/app/connectlink/vendor.go @@ -3,6 +3,7 @@ package connectlink import ( "context" "sort" + "time" "github.com/google/uuid" "github.com/rs/zerolog/log" @@ -141,9 +142,12 @@ func (s *Service) VendorImport(ctx context.Context, link *models.ClientConnectLi } 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(ctx, orgID, link.ID, n); rerr != nil { - log.Warn().Str("link_id", link.ID.String()).Msg("connect link: could not give back slots after a failed vendor import") + 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)" @@ -152,7 +156,8 @@ func (s *Service) VendorImport(ctx context.Context, link *models.ClientConnectLi giveBack(len(ids)) return nil, xerr } - opts := models.MailboxImportOptions{} + // 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()) } @@ -160,14 +165,22 @@ func (s *Service) VendorImport(ctx context.Context, link *models.ClientConnectLi on := true opts.Settings.Warmup = &on } - imp, emails, xerr := s.d.Vendors.ImportPicked(ctx, orgID, actor, conn.ID, vendorconn.ImportInput{MailboxIDs: ids, Options: opts}, len(ids)) + 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 { - giveBack(len(ids)) - if derr := s.d.Vendors.Delete(ctx, 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") + // 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 } diff --git a/internal/app/connectlink/vendor_test.go b/internal/app/connectlink/vendor_test.go index 3c67b8282..9b423ef33 100644 --- a/internal/app/connectlink/vendor_test.go +++ b/internal/app/connectlink/vendor_test.go @@ -62,7 +62,8 @@ func (f *fakeVendors) ImportPicked(_ context.Context, _, _, _ uuid.UUID, in vend var emails []string for _, id := range in.MailboxIDs { for _, b := range vendorBoxes { - if b.ID == id { + // 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) } } @@ -168,19 +169,68 @@ func TestAVendorImportIsHeldToTheLinksLimit(t *testing.T) { } } -func TestAFailedVendorImportGivesItsSlotsBack(t *testing.T) { +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 != 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)) + 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) } } diff --git a/internal/app/vendorconn/agency.go b/internal/app/vendorconn/agency.go index daf433556..179224196 100644 --- a/internal/app/vendorconn/agency.go +++ b/internal/app/vendorconn/agency.go @@ -198,13 +198,22 @@ func (s *Service) UpdateAgencyAccount(ctx context.Context, agencyID, userID, id if err != nil { return nil, errx.InternalError() } + failed := false 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 != "" { - _ = s.repo.SetStatus(ctx, l.ConnectionID, "active", "") + if err := s.repo.SetStatus(ctx, l.ConnectionID, "active", ""); err != nil { + failed = true + } } 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) } diff --git a/internal/app/vendorconn/agency_test.go b/internal/app/vendorconn/agency_test.go index 94a13b3ab..d96482001 100644 --- a/internal/app/vendorconn/agency_test.go +++ b/internal/app/vendorconn/agency_test.go @@ -435,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) + } +} diff --git a/internal/app/vendorconn/service.go b/internal/app/vendorconn/service.go index a9ab2776c..15a71a2b0 100644 --- a/internal/app/vendorconn/service.go +++ b/internal/app/vendorconn/service.go @@ -480,6 +480,9 @@ type ImportInput struct { MailboxIDs []string `json:"mailbox_ids"` All bool `json:"all"` 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 @@ -516,6 +519,9 @@ func (s *Service) ImportPicked(ctx context.Context, orgID, userID, id uuid.UUID, if !want[m.ID] && !(in.All && !m.Connected) { continue } + if in.SkipConnected && m.Connected { + continue + } if max > 0 && len(rows) >= max { break } diff --git a/internal/infrastructure/db/migrations/000394_connect_link_vendor.down.sql b/internal/infrastructure/db/migrations/000394_connect_link_vendor.down.sql index 3258c17db..08f40785d 100644 --- a/internal/infrastructure/db/migrations/000394_connect_link_vendor.down.sql +++ b/internal/infrastructure/db/migrations/000394_connect_link_vendor.down.sql @@ -1,7 +1,11 @@ --- A link that only took a vendor account has no way left to connect, so it is turned off. -UPDATE client_connect_links SET revoked_at = COALESCE(revoked_at, now()), allowed_providers = ARRAY['smtp_imap']::text[] -WHERE allowed_providers = ARRAY['vendor']::text[]; -UPDATE client_connect_links SET allowed_providers = array_remove(allowed_providers, 'vendor') WHERE 'vendor' = ANY (allowed_providers); +-- 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 diff --git a/internal/models/agency_mailbox.go b/internal/models/agency_mailbox.go index 4dde9f73b..32eff6f92 100644 --- a/internal/models/agency_mailbox.go +++ b/internal/models/agency_mailbox.go @@ -30,7 +30,8 @@ type AgencyMailbox struct { type AgencyMailboxQuery struct { OrgIDs []uuid.UUID 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 Limit int // Before is the last row of the previous page; zero starts at the newest. diff --git a/internal/repository/pg_agency_home.go b/internal/repository/pg_agency_home.go index 0ab595206..6573ecac4 100644 --- a/internal/repository/pg_agency_home.go +++ b/internal/repository/pg_agency_home.go @@ -175,7 +175,7 @@ var agencyMailboxesSQL = ` ) m WHERE ea.organization_id = ANY($1::uuid[]) 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)) ORDER BY ea.created_at DESC, ea.id DESC LIMIT $6` diff --git a/portal/src/ConnectPage.tsx b/portal/src/ConnectPage.tsx index 007dd9d1f..3e2253a3d 100644 --- a/portal/src/ConnectPage.tsx +++ b/portal/src/ConnectPage.tsx @@ -201,7 +201,11 @@ export function ConnectPage() { link={live} errorCopy={(e) => errorCopy(e, workspace)} onBack={() => setView("choose")} - onStarted={() => void qc.invalidateQueries({ queryKey: ["connect", token] })} + // 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(["connect", token], (prev) => (prev ? { ...prev, connected: started.connected } : prev)) + } /> ) : view === "waiting" ? (
diff --git a/portal/src/ConnectVendor.tsx b/portal/src/ConnectVendor.tsx index ec776e43a..464c407d7 100644 --- a/portal/src/ConnectVendor.tsx +++ b/portal/src/ConnectVendor.tsx @@ -87,9 +87,9 @@ export function VendorForm({ setStarted(out); onStarted(out); } catch (err) { - setError(errorCopy(err)); - // A ticket is good once and for a few minutes; after that the key is asked for again. + // 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); } diff --git a/qa/flows/agency-mailboxes.flow.ts b/qa/flows/agency-mailboxes.flow.ts index 1d397f4ed..5dd91e0b8 100644 --- a/qa/flows/agency-mailboxes.flow.ts +++ b/qa/flows/agency-mailboxes.flow.ts @@ -42,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.getByLabel("API key").fill("qa-agency-key"); 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 confirmIfAsked(page); 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. await page.getByRole("button", { name: "Add to a client" }).click(); diff --git a/web/src/app/app/agency/mailboxes/page.tsx b/web/src/app/app/agency/mailboxes/page.tsx index 2e2e113d1..0319b65c3 100644 --- a/web/src/app/app/agency/mailboxes/page.tsx +++ b/web/src/app/app/agency/mailboxes/page.tsx @@ -220,6 +220,9 @@ function AgencyMailboxes() { const totals = overview.data?.totals; const filtered = attention || q !== "" || chosen.length > 0; 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. 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."; @@ -250,9 +253,12 @@ function AgencyMailboxes() { user.setAddEmail(true); }; - const askRemove = (a: AgencyVendorAccount) => - confirm.show( - `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 askRemove = (a: AgencyVendorAccount) => { + // A client whose mailboxes the caller cannot list is used all the same, and its count is not in the total. + 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 () => { try { await removeAccount.mutateAsync(a.id); @@ -264,6 +270,7 @@ function AgencyMailboxes() { undefined, { title: "Remove vendor account", confirmLabel: "Remove" }, ); + }; return ( @@ -329,11 +336,13 @@ function AgencyMailboxes() { void mailboxes.refetch()} /> ) : rows.length === 0 ? ( setAdding({})}>Add mailboxes : undefined} /> diff --git a/web/src/components/app/agency/AutoTopup.tsx b/web/src/components/app/agency/AutoTopup.tsx index a08ea696b..856c9a111 100644 --- a/web/src/components/app/agency/AutoTopup.tsx +++ b/web/src/components/app/agency/AutoTopup.tsx @@ -74,6 +74,7 @@ function Panel({ onToggle, failure, card, + cardMissing, used, dirty, saving, @@ -92,6 +93,8 @@ function Panel({ onToggle: (on: boolean) => void; failure?: Failure; 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. */ used?: string; /** The numbers differ from what is saved. Nothing is sent, and nothing can be charged, until Save. */ @@ -168,7 +171,9 @@ function Panel({ {card ? `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}`}

@@ -227,11 +232,12 @@ export function SendsAutoTopup({ agencyId, canManage }: { agencyId: string; canM } enabled={data.enabled} loading={false} - // Turning it off always works; turning it on needs a pool to top up and a card to charge. - canToggle={canManage && !save.isPending && (data.enabled || (data.available && !data.card_missing))} + // 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))} onToggle={(enabled) => void apply(enabled, !enabled)} failure={data.failure} card={data.card} + cardMissing={data.card_missing} used={`This month: ${data.bought_this_period} of ${data.max_packs} used.`} dirty={dirty} saving={save.isPending} @@ -320,10 +326,11 @@ export function AIAutoTopup({ agencyId, canManage }: { agencyId: string; canMana enabled={data.enabled} loading={false} // 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)} failure={data.failure} card={data.card} + cardMissing={data.card_missing} used={`This month: ${fmtUsdTrim(data.added_this_period_usd)} of ${fmtUsdTrim(data.limit_usd)} used.`} dirty={dirty} saving={save.isPending} diff --git a/web/src/components/app/agency/mailboxes/AddMailboxesDialog.tsx b/web/src/components/app/agency/mailboxes/AddMailboxesDialog.tsx index bdba59e68..2f712688c 100644 --- a/web/src/components/app/agency/mailboxes/AddMailboxesDialog.tsx +++ b/web/src/components/app/agency/mailboxes/AddMailboxesDialog.tsx @@ -96,19 +96,20 @@ export default function AddMailboxesDialog({ return ( undefined : onClose} eyebrow="Mailboxes" title={preset ? `Add mailboxes from ${preset.label}` : client ? `Add mailboxes to ${client.name}` : "Add mailboxes"} icon={} footer={ <> {step === "how" && clients.length > 1 && ( - )} - diff --git a/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx b/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx index 9fd53d9d8..51b38ad73 100644 --- a/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx +++ b/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx @@ -38,6 +38,11 @@ export default function VendorAccountDialog({ const accountId = account?.id; const start = React.useRef(account); start.current = account; + // One key per opening and per changed form, so a retry of the same submission connects one account. + const attempt = React.useRef(""); + React.useEffect(() => { + attempt.current = crypto.randomUUID(); + }, [open, accountId, vendorId, fields]); React.useEffect(() => { if (!open) return; setVendorId(start.current?.vendor ?? ""); @@ -65,6 +70,7 @@ export default function VendorAccountDialog({ try { await save.mutateAsync({ id: account?.id, + idempotencyKey: attempt.current, 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`); diff --git a/web/src/lib/api/client/app/agency/agencyMailboxes.ts b/web/src/lib/api/client/app/agency/agencyMailboxes.ts index df83c050d..7a25ec365 100644 --- a/web/src/lib/api/client/app/agency/agencyMailboxes.ts +++ b/web/src/lib/api/client/app/agency/agencyMailboxes.ts @@ -25,8 +25,15 @@ export const listAgencyMailboxes = (agencyId: string, filters: AgencyMailboxFilt export const listAgencyVendors = (agencyId: string, signal?: AbortSignal) => Request({ method: "GET", url: `/agency/${agencyId}/vendors`, authorization: true, signal }); -export const createAgencyVendor = (agencyId: string, data: AgencyVendorAccountInput) => - Request({ method: "POST", url: `/agency/${agencyId}/vendors`, data, authorization: true }); +/** The key names one submission, so sending it again after a lost answer does not connect the account twice. */ +export const createAgencyVendor = (agencyId: string, data: AgencyVendorAccountInput, idempotencyKey?: string) => + Request({ + method: "POST", + url: `/agency/${agencyId}/vendors`, + data, + headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined, + authorization: true, + }); export const updateAgencyVendor = (agencyId: string, id: string, data: AgencyVendorAccountInput) => Request({ method: "PATCH", url: `/agency/${agencyId}/vendors/${id}`, data, authorization: true }); diff --git a/web/src/lib/api/hooks/app/agency/useAgencyMailboxes.ts b/web/src/lib/api/hooks/app/agency/useAgencyMailboxes.ts index cc0ab2055..3977a86bc 100644 --- a/web/src/lib/api/hooks/app/agency/useAgencyMailboxes.ts +++ b/web/src/lib/api/hooks/app/agency/useAgencyMailboxes.ts @@ -57,7 +57,6 @@ export function useAgencyMailboxes(agencyId: string | undefined, filters: Agency return useInfiniteQuery({ ...agencyMailboxesQuery(agencyId ?? "", filters), enabled: !!agencyId, - placeholderData: (prev) => prev, }); } @@ -77,8 +76,8 @@ function useRefreshVendors(agencyId: string) { export function useSaveAgencyVendor(agencyId: string) { const refresh = useRefreshVendors(agencyId); return useMutation({ - mutationFn: ({ id, input }: { id?: string; input: AgencyVendorAccountInput }) => - id ? updateAgencyVendor(agencyId, id, input) : createAgencyVendor(agencyId, input), + mutationFn: ({ id, input, idempotencyKey }: { id?: string; input: AgencyVendorAccountInput; idempotencyKey?: string }) => + id ? updateAgencyVendor(agencyId, id, input) : createAgencyVendor(agencyId, input, idempotencyKey), onSettled: refresh, }); } From 7ecb484fae4a8ce93edac7257e469a0f1b171ee1 Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 19:54:59 +0100 Subject: [PATCH 7/9] feat: say on a vendor account's row when its mailbox count leaves out clients the caller cannot list --- web/src/app/app/agency/mailboxes/page.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/web/src/app/app/agency/mailboxes/page.tsx b/web/src/app/app/agency/mailboxes/page.tsx index 0319b65c3..2a6187a18 100644 --- a/web/src/app/app/agency/mailboxes/page.tsx +++ b/web/src/app/app/agency/mailboxes/page.tsx @@ -140,6 +140,8 @@ function VendorAccounts({ {a.clients.length === 0 ? "Not used for a client yet" : `${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)"}
{a.status === "invalid" && (

{a.last_error || "The vendor no longer accepts this key."}

From eb4df6d98f237a681bd40dbc29900d8435f1fc1b Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 20:02:20 +0100 Subject: [PATCH 8/9] feat: answer a client's vendor import with the link's stored count, tell an embedding page when an import starts, and bind a vendor account submission's retry key to the whole form --- docs/content/docs/guides/white-label.mdx | 2 +- internal/app/connectlink/vendor.go | 4 ++++ portal/public/embed.js | 6 ++++++ portal/src/ConnectPage.tsx | 9 ++++++--- portal/src/connectEmbed.ts | 11 +++++++++++ .../app/agency/mailboxes/VendorAccountDialog.tsx | 5 +++-- 6 files changed, 31 insertions(+), 6 deletions(-) diff --git a/docs/content/docs/guides/white-label.mdx b/docs/content/docs/guides/white-label.mdx index 281d3cddb..fb297265b 100644 --- a/docs/content/docs/guides/white-label.mdx +++ b/docs/content/docs/guides/white-label.mdx @@ -166,7 +166,7 @@ Put `data-warmbly-connect="CONNECT_TOKEN"` on the tag instead for a connect page ``` -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. 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. diff --git a/internal/app/connectlink/vendor.go b/internal/app/connectlink/vendor.go index 0316877da..42b6c8a30 100644 --- a/internal/app/connectlink/vendor.go +++ b/internal/app/connectlink/vendor.go @@ -188,7 +188,11 @@ func (s *Service) VendorImport(ctx context.Context, link *models.ClientConnectLi 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)} diff --git a/portal/public/embed.js b/portal/public/embed.js index ffcb5860c..87d70bf94 100644 --- a/portal/public/embed.js +++ b/portal/public/embed.js @@ -71,6 +71,12 @@ } catch (err) {} 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)) { var frames = document.querySelectorAll('iframe[data-warmbly-frame="' + d.page + '"]'); for (var i = 0; i < frames.length; i++) { diff --git a/portal/src/ConnectPage.tsx b/portal/src/ConnectPage.tsx index 3e2253a3d..9b4c072fd 100644 --- a/portal/src/ConnectPage.tsx +++ b/portal/src/ConnectPage.tsx @@ -23,6 +23,7 @@ import { navigateForSignin, openSigninWindow, postConnected, + postImporting, readSigninResult, type SigninResult, startConnectResizeReporting, @@ -203,9 +204,11 @@ export function ConnectPage() { 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(["connect", token], (prev) => (prev ? { ...prev, connected: started.connected } : prev)) - } + onStarted={(started) => { + qc.setQueryData(["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" ? (
diff --git a/portal/src/connectEmbed.ts b/portal/src/connectEmbed.ts index 778748ea6..3ce9b7321 100644 --- a/portal/src/connectEmbed.ts +++ b/portal/src/connectEmbed.ts @@ -6,6 +6,7 @@ export const CONNECT_RESIZE_MESSAGE = "warmbly:connect:resize"; /** 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_IMPORTING_MESSAGE = "warmbly:connect:importing"; export function startConnectResizeReporting(): () => void { if (window.parent === window) return () => {}; @@ -22,6 +23,16 @@ export function startConnectResizeReporting(): () => void { 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) { if (window.parent === window) return; try { diff --git a/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx b/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx index 51b38ad73..f52eac71f 100644 --- a/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx +++ b/web/src/components/app/agency/mailboxes/VendorAccountDialog.tsx @@ -38,11 +38,12 @@ export default function VendorAccountDialog({ const accountId = account?.id; const start = React.useRef(account); start.current = account; - // One key per opening and per changed form, so a retry of the same submission connects one 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]); + }, [open, accountId, vendorId, fields, label]); React.useEffect(() => { if (!open) return; setVendorId(start.current?.vendor ?? ""); From 79381ffc654640638c319cf059d068a19c6e5cbc Mon Sep 17 00:00:00 2001 From: Matthew Meszaros Date: Wed, 11 Nov 2026 20:06:34 +0100 Subject: [PATCH 9/9] feat: close the agency mailboxes page's dialogs when another agency is selected, so a vendor key typed for one agency is never submitted to another --- web/src/app/app/agency/mailboxes/page.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/web/src/app/app/agency/mailboxes/page.tsx b/web/src/app/app/agency/mailboxes/page.tsx index 2a6187a18..99e7ec738 100644 --- a/web/src/app/app/agency/mailboxes/page.tsx +++ b/web/src/app/app/agency/mailboxes/page.tsx @@ -214,6 +214,14 @@ function AgencyMailboxes() { const [vendorDialog, setVendorDialog] = React.useState<{ account?: AgencyVendorAccount } | null>(null); 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; const canManage = agency.role === "owner" || agency.role === "admin"; const clients = overview.data?.clients ?? [];