Authentication
Workbench sessions, HTTP boundaries, and auth persistence.
Sessions and API access
Workbench uses one Better Auth instance through @alchemy.run/better-auth, pinned to Alchemy 2.0.0-beta.85 and Better Auth 1.7.12. packages/auth/src/index.ts defines its typed Effect AuthService. The CLI configuration in packages/auth/auth.config.ts repeats the schema settings; keep field mappings, model names, and plugins aligned when changing either configuration. Google sign-in is enabled when both OAuth credentials are configured; see credential setup.
Browser clients use Better Auth’s /api/auth base path on the frontend origin. Its native endpoints establish sessions, read them at GET /api/auth/get-session, and revoke them with POST /api/auth/sign-out. The sign-in and session UI calls them through Better Auth’s browser client in lib/auth-client.ts. Do not store a second session or provider tokens in browser storage.
The session endpoint returns Better Auth’s session and user object when authenticated, or 200 with null for a missing, invalid, revoked, or expired session. There is no separate Workbench session endpoint or session response contract.
The organization and task endpoint groups use the shared Authentication middleware. Before decoding the request, it checks the origin of mutations and resolves the session once. An untrusted mutation origin returns 403, a missing session returns 401, and a missing active organization returns 403. The middleware supplies the user ID and selected organization to handlers through CurrentUser. Domain operations check the actor’s current permissions. Health, demo, API reference, and Better Auth routes use their own access rules.
Callers can bind a request to the actor context used to render a form or key a query by sending UUID headers x-workbench-expected-user-id and x-workbench-expected-organization-id. The user header activates the complete assertion; omitting the organization header then asserts a null active organization. An organization header alone or malformed UUID fails closed. After resolving the session, the middleware compares the assertion with that same snapshot before decoding or executing the endpoint. A mismatch returns 409 ActorScopeChanged without disclosing the current actor. The assertion grants no authority; matching requests still require current permissions. Callers must refresh their verified context on this error and must not silently retry mutations under another actor. Legacy requests with neither header retain session-selected behavior.
Better Auth retains its native response and error bodies. Shared response policy follows the HTTP boundaries.
Better Auth uses its default logger. Application HTTP failures use the existing Effect error middleware; Better Auth’s internal messages have no Workbench request-context bridge.
Google requests only openid, email, and profile. The browser cannot supply additional scopes or provider tokens, request token retrieval or start explicit account linking. Provider tokens remain in the server database; Better Auth encrypts access and refresh tokens with its signing secret, while its ID token field is stored as provided. A new Google identity creates a user. An existing user is linked by matching email only when both the existing email and Google email are verified; an unverified or different email cannot be linked. Google is not treated as a trusted provider that bypasses verification. Authentication alone grants no access to other organizations or client data.
API reference
Open /docs on the direct API Worker host for the combined Scalar reference. Its dropdown selects Workbench or Better Auth. The same API host serves the generated Workbench schema at /openapi.json and the Better Auth schema at /api/auth/open-api/generate-schema. Workbench examples use the direct host’s / API base. The reference loads Scalar from jsDelivr; the specifications remain available as JSON if the script cannot load. The auth schema CLI omits the OpenAPI plugin, which adds no database fields.
Frontend documentation and schema requests return HTTP 404, including encoded paths, trailing-slash equivalents and forwarded aliases. Hosted preview requests first pass the Cloudflare Access gate. The blocked paths include /api/docs, /api/openapi.json, the Better Auth schema at /api/auth/open-api/generate-schema, and its forwarded alias /api/api/auth/open-api/generate-schema. Request middleware enforces this before UI authentication or rendering; the local Vite proxy applies the same exclusions. Ordinary application /api requests, Google sign-in, and session endpoints keep their existing forwarding behavior.
Hosted stacks declare a Cloudflare Access application for the direct API reference and both schemas, including Worker version URLs. It allows @wurthy.co addresses authenticated with the shared Google login method in Cloudflare Access. This is separate from Workbench’s Google sign-in. CLOUDFLARE_ACCESS_GOOGLE_IDP_ID selects the Access login method; preview and production read it from their Proton environment items. Preview frontends additionally attach the application through Alchemy’s native access property, protecting the whole frontend. CI uses the existing preview Access service token; production has no CI bypass policy.
Access destinations come from the Server and Web resources’ Alchemy URL outputs. Production and hosted personal stages keep Alchemy’s generated Worker identities; previews keep their existing PR-based names. BETTER_AUTH_URL configures application authentication and does not determine Worker names or Access destinations. Local development skips Access. The deployed Worker also skips Access provisioning during startup; it does not need deployment credentials to serve requests.
The Workers bind the Access audience through an Alchemy Action that waits for Access reconciliation to finish before application code uploads. A fresh deployment input makes the Action wait on every deployment, including updates that keep the same audience but change protected paths. If Access fails, neither Worker uploads application code. On initial creation, Alchemy first creates placeholder Workers to obtain their URLs. This ordering runs automatically within the existing deployment command; no separate rollout is needed.
Run read-only plans for production, a preview, and any existing personal stage; verify no Worker, database, or role replacements. Hosted personal stages need the Google Access provider in .env.development.local. The deployment identity needs permission to manage Access applications and policies. Verify protection on every reachable hostname after an authorized deployment. The Google OAuth audience must also admit the intended users; a project in Testing mode permits only its configured test users.
The Workbench organization and task endpoints require a session with an active organization selection and current membership in that organization. The generated schema does not yet encode these authorization requirements. Example requests run with the caller’s normal permissions. Effect’s isMinLength(3) checks UTF-16 code units, while OpenAPI’s minLength counts Unicode code points. Effect therefore generates minLength: 2 as a permissive approximation: for example, it accepts 😀a at runtime, while ab passes the generated minimum but fails runtime validation. The server remains authoritative.
Platform administration
Better Auth’s Admin plugin owns platform user roles and user/session management through /api/auth/admin/*. The shared UserRoles definition is ["platform_user", "platform_admin"], exported through @workbench/contracts/user. New and existing ordinary accounts default to platform_user; platform administrators have the user-level platform_admin role. The plugin’s native permissions govern role changes, user management, bans, session revocation, and impersonation. Organization membership roles cannot grant these permissions.
Platform admins can add existing users to their selected active organization through Workbench’s membership endpoint, provided they hold a current membership there. That application permission explicitly checks the user role. Other organization and resource operations retain their existing membership and permission checks. The first platform admin must be established through a controlled engineering process; no account becomes an admin merely by creating an organization.
The Admin plugin migration adds user.role, banned, ban_reason, ban_expires, and session.impersonated_by. Apply the migration through the existing schema pipeline before deploying the plugin.
Organizations
The Better Auth Organization plugin owns organizations, memberships, native membership invitations, and organization roles through /api/auth/organization/*. Native invitation creation is enabled for provider admins, provider leads and client admins, with the existing target-role guard, current active-organization selection and active-status checks. Native resend: true is rejected; use the controlled People resend endpoint described below. Native cancellation remains disabled because the pinned route does not condition its update on pending status. A user can belong to multiple organizations, with one membership per user and organization. Teams and dynamic roles are disabled. Relationship operations require a current membership.
The configured membership roles are provider_admin, provider_lead, provider_operator, client_admin, and client_member. Better Auth stores multiple roles as a comma-separated string. Member permissions are generated from create, update, and delete for each configured role, such as member:createProviderOperator and member:updateClientMember. Provider admins can create provider leads and provider operators; provider leads can create provider operators and client members; client admins can create client members. No role currently has a role-specific update or delete permission. Better Auth’s update and remove routes additionally check the target’s roles; an update requires permission for every current and requested role. Its update-member-role, remove-member, and invite-member routes require an explicit, nonempty organizationId, even when the session has an active organization. Better Auth normally checks generic member actions too, but its update route bypasses that generic check for the creator role; the role-specific check still applies. The role capabilities describe the human policy; business and space assignments, account status, archived-space restrictions, and visibility of internal or private work must also be enforced before authorizing work. Those scoped checks are not yet implemented for business work.
Users do not receive a personal organization when their account is created. The platform_admin role and the provider_admin membership role have organization:createLegalEntity, organization:createIndividual, and organization:createGroup permissions. Better Auth’s /api/auth/organization/create permits a user with a provider_admin membership in any organization or with the platform_admin role to create those kinds; a platform_user role alone does not permit creation. The creator receives the provider_lead membership role. A valid kind and the corresponding creation permission are required, including for trusted server-only creation. Only the five configured membership roles may be assigned through the membership and invitation hooks, even though Better Auth recognizes built-in role names internally.
Organization permissions are generated for each combination of create, read, update, and delete with LegalEntity, Individual, and Group. All five membership roles have readLegalEntity, readIndividual, and readGroup; none has kind-specific update or delete permissions. Better Auth’s organization read, list, and selection routes check the stored kind, and its update and delete routes require the corresponding kind-specific permission in addition to Better Auth’s native permission. Changing kind requires update permissions for both the current and proposed kinds. Records without a valid kind cannot be read, selected, updated, or deleted through these routes and are excluded from organization lists.
POST /organizations/:organizationId/members adds an existing user to the actor’s selected organization with active status. The application requires the request organization to match the session selection and checks current membership. A platform admin who is a member can add any of the five membership roles. A provider admin can add provider leads and operators; a provider lead can add provider operators and client members; a client admin can add client members. The domain operation checks the corresponding member:create<Role> permission, with the platform-admin override, then calls Better Auth’s server-only addMember API, preserving its membership limit and before/after member hooks. Membership alone does not establish a business-space assignment. For an actively linked client business, all three firm roles can also add an existing account as a client admin, including its first admin, through the narrow client-onboarding policy described below. Existing memberships keep their roles; this does not authorize role updates. The API returns 404 for an unavailable organization, user, membership, or permission and uses the /api browser prefix.
The older cross-organization guard, organization relationship mutations, and access-grant management endpoints still require permissions not assigned to human roles. The work APIs below enforce their own explicit resource permissions and existing grants. ResourceOwnership resolves the creator and owning organization of spaces and tasks for the grant service.
Organization kind is a PostgreSQL enum restricted to legal_entity, group, or individual. Better Auth requires a verified recipient email to accept a membership invitation. Invitation-email delivery defaults to disabled; recipients sign in with Google, which supplies verified account identity. There is no separate email-verification sender.
Workbench stores established directed relationships separately from its organization relationship invitations and Better Auth’s membership invitations. client_of points from a client to its service provider, and member_of points from a member organization to its group. Containment cannot refer to itself or form a cycle. A database trigger serializes and checks graph changes. The access-grant table stores an array of permissions per resource. The cross-organization guard requires a grant scoped to a relationship, requires the requested acting organization to match the session selection, and accepts a nonempty list of required permissions for one resource.
People settings
Administration People and client People load current organization memberships and pending native Better Auth membership invitations through GET /organizations/:organizationId/members. Member records include the stored Google profile image URL for People avatars, with initials when the photo is absent or cannot load. Own-organization reads require current membership in the active, selected organization. For a linked client business, firm admins, leads and operators receive a restricted projection: current client admins, only that firm’s pending client-admin invitations, and creatableRoles: [client_admin] with management: client-admins. Other client members and other firms’ invitations are not exposed. Inactive organizations and denied targets return the same 404.
The response includes allowed creation roles from the existing canAddOrganizationMember policy. POST /organizations/:organizationId/members/by-email checks that permission before looking up an account. It adds an existing account, preserves an existing membership’s role, and reports account-required without creating or sending an invitation when the email has no account. Use the separate invitation form for a person who has not signed in yet. Actor-scoped queries and expected-actor headers protect both reads and additions against account or organization changes.
People can create native person invitations through POST /organizations/:organizationId/member-invitations, using exactly the same current canAddOrganizationMember target-role policy as existing-account additions, including the platform-admin override. The target is either the selected active organization or an active legal-entity/individual client business linked by client_of to the selected active firm; the latter permits only client_admin and requires a current firm-admin, firm-lead or firm-operator membership. Invitations use the native invitation table, expire after 48 hours, and return delivery: copy-link when email is disabled, or delivery: email-queued when enabled. People provides a copy button and a selectable link fallback. See invitation email for configuration and delivery limits. Organization relationship invitations remain a separate workflow and cannot onboard people.
Compatible own-organization creation uses Better Auth’s native createInvitation API with the caller’s real session headers, bound at the HTTP boundary. Application domain operations do not receive Request or cookie objects. Better Auth supplies duplicate detection, pending-invitation limits, expiry and creation hooks. Pending duplicates are rejected; refresh People to find and copy the existing link.
Two native limitations require small server-only extensions in the pinned Better Auth 1.7.12 release. Firm-to-client creation requires a caller who is not a target member. The existing provider-admin-to-provider-lead and platform-admin override policies also exceed the native creator-role/membership-role checks. createPolicyInvitation handles those grants through Better Auth’s public organization adapter, invoking the configured before/after creation hooks and enforcing the same duplicate and pending-invitation limits. It does not create a fake membership, impersonate another account or change the organization creator role.
Cancellation uses the server-only cancelPolicyInvitation extension and Better Auth’s public updateInvitation adapter with fromStatus: pending. The native HTTP cancellation route updates status without that condition. The extension invokes cancellation hooks and fires the after hook only for a successful transition, preserving accepted invitations even when acceptance wins a race with cancellation. Application database modules only read membership/invitation records; they no longer insert memberships or create/cancel invitations directly.
POST /organizations/:organizationId/member-invitations/:invitationId/cancel requires current permission to add the invitation’s target role. A firm acting for a linked client can cancel only client-admin invitations originating from that same firm; another firm’s invitations are unavailable. It changes only pending invitations to canceled; an accepted invitation stays accepted. Expiry and cancellation prevent acceptance. Role changes and member removal remain disabled.
The /accept-invitation?invitationId=... page retains its URL through Google sign-in and requires an explicit Accept action. Native Better Auth get/accept endpoints require the invited email and verified identity; no active organization or prior membership is needed. Workbench additionally checks active organization status and the inviter’s current membership, target-role authority, and account ban state (an expired ban does not block acceptance). Existing members cannot use a stale invitation to change their role. Better Auth conditionally claims the pending invitation, creates membership and selects the organization; a full navigation to the directory clears the old actor cache. Membership acceptance creates no access grants. For newly created client-bound spaces, the default Client conversation grant already covers current and future members of the client business; it grants conversation access without sharing internal Finance-space work.
Firm-to-client admin onboarding
All firm admins, firm leads and firm operators may add or invite client admins, including the first client admin, for an active client business linked to the selected active firm. This is the approved WB-12 client-onboarding policy. It does not require an existing client admin’s approval. The actor must currently belong to that firm with one of those three roles. No membership is created for the inviter, and no authority is granted to invite firm admins, change existing roles, remove members, manage unrelated businesses or grant space access.
Cross-organization person invitations retain the original firm in the nullable native invitation.inviter_organization_id column. Null preserves own-organization invitation semantics. The field is server-only in Better Auth and references the organization with cascade deletion, so deleting a firm cannot convert its invitation into an own-organization link. Acceptance rechecks the recorded firm, the original inviter’s current firm membership/role and ban state, both organizations’ active status, the target’s business kind and the live client_of relationship. Another membership or another firm’s relationship cannot substitute for the original firm. Revoked authority makes the link unavailable; cancellation and expiry still apply.
Better Auth’s native invitation-preview endpoint assumes the inviter belongs to the target organization. For firm invitations, the existing permission hook supplies the preview only after checking the named verified recipient, pending/unexpired state and live authority; it never manufactures an inviter membership. Acceptance continues through Better Auth’s native pending-state claim, member creation and active-organization selection. Finance-space grants remain a separate explicit sharing operation.
Client directory
GET /clients requires an authenticated user, a selected active organization, and current membership. Provider roles see active client businesses linked to that firm by client_of (source client, target firm). Client roles see only their own active business; spaces and tasks still require their existing resource permissions. A relationship or membership alone never shares a space. Missing selection returns 403; unavailable or revoked directory access returns 404 with the JSON tag ClientDirectoryUnavailable. An empty fallback 404 is not a directory-access decision. An authorized provider with no clients receives an empty directory, while database failures remain errors.
The response projects read capabilities per space after resource authorization. Provider internal-read capability includes Client-side viewing on an authorized space without granting every underlying task or client authority. Client-side viewers need the existing explicit share and client-facing role permission. Client-wide read capabilities only summarize the spaces returned. UI routes must use the selected space’s capabilities rather than broad client capabilities.
POST /clients is a narrow client-onboarding workflow for a current Firm Admin (provider_admin), Firm Lead (provider_lead), or Firm Operator (provider_operator) in the acting firm. It atomically creates a legal-entity organization and its client-to-firm relationship. The creator gets no client membership or access grant, and the request cannot choose another owning firm. This leaves the general organization and relationship permission rules intact. Client roles and users without a legitimately provisioned firm membership cannot use it; onboarding must obtain that membership through the existing administrator/invitation process.
Names are trimmed and compared case-insensitively within the firm. A firm-row lock serializes concurrent duplicate checks, so duplicate or lost-response retries return 409 rather than replaying a successful result. Refresh the directory to find a client whose response was lost. The workflow does not create owner accounts, invitations, grants, Finance spaces, connections, or setup operations. It stores only the submitted business name; unknown profile fields remain unavailable.
Spaces and tasks
Spaces are owned records with a creator, organization, name, optional preset type, and optional description. Tasks belong to a space and carry a title, optional description and assignee, labels, and status. Task items store content and a server-managed integer version that starts at 1 and increments atomically with every content update. Clients send only content when creating or updating an item; responses include the current version. All three resources record the creating user and the active organization on whose behalf they were created, as supplied by the actor. A creator may be a person or an agent; every agent requires its own user record. API updates exclude creator and organization fields and cannot move a resource to another parent. See ownership and access for the development convention that these creation fields never change.
| Resource | List and create | Read, patch, delete |
|---|---|---|
| Spaces | /organizations/:organizationId/spaces |
/spaces/:spaceId |
| Tasks | /spaces/:spaceId/tasks |
/tasks/:taskId |
| Task items | /tasks/:taskId/items |
/task-items/:itemId |
| Task relationships | List at /tasks/:taskId/relationships; create at /task-relationships |
/task-relationships/:relationshipId |
Use GET for lists/reads, POST for creation, PATCH for a nonempty set of mutable fields, and DELETE for removal. Browser requests use the /api prefix. GET /tasks/:taskId/subtasks lists tasks whose subtask_of relationship points to that parent. Relationships are directed and typed as subtask_of, blocks, duplicates, or relates_to; self-links and duplicate source/target/type tuples are rejected. Subtask relationships form an acyclic hierarchy with at most one parent per task; the other types allow multiple links and cycles. See the task model. Both endpoints must be accessible for relationship reads and authorized for the requested relationship mutation, including the old and new endpoints of an update.
Workbench’s organization and work HTTP handlers receive the authenticated actor, call one application operation, and map its errors to HTTP responses using a mapping per group. Operations in apps/server/src/domain/organizations/ and domain/tasks/ take (actor, input), where Actor contains userId and organizationId, enforce permissions, and then call database functions in each feature’s data/ folder. The middleware takes these fields from user.id and session.activeOrganizationId. Request parameters and payload form the separate operation input; they cannot override the actor. Jobs and other trusted callers provide both actor fields explicitly to the same functions; no HTTP request or session service is required. Operations without request input take only the actor. The application returns domain errors, including AccessDenied, while database operations remain focused on data access. Membership capabilities, platform-admin overrides, invitation visibility and recipient eligibility, and grant ownership checks belong to the application layer. Permission decisions use current stored user and membership records and the shared role rules in packages/auth.
Application authorization uses explicit action guards such as canReadTask and canCreateTask. Role checks require the actor’s organization to be active, read the actor’s current membership in that organization, and use the same native Better Auth role definitions as the authentication plugin. Memberships and roles in other organizations do not contribute permissions. Grant lookups select only grants matching the actor, requested permission, and resource scope. Application list operations filter results through the read guards.
Each of space, task, taskItem, and taskRelationship has explicit create, read, update, and delete role permissions. The initial assignments are:
| Roles in the acting organization | Spaces | Tasks | Task items | Task relationships |
|---|---|---|---|---|
| Provider admin, provider lead | All | All | All | All |
| Provider operator | Read | All | All | All |
| Client admin | All | Read | All | Read |
| Client member | Read | Read | All | Read |
Members acting from the owning organization can read its spaces when their role permits it. Reading, updating, or deleting an existing task requires a grant for the task and requested action, including for members of the owning organization. See task visibility for the grant patterns. Reading an item requires read access to its task. Reading a task relationship or listing a subtask requires read access to both tasks. All work access requires the owning organization to be active.
For a client-bound space, an actor acting within its owning firm also needs the current businessWork.readInternal capability for implicit space access and task, item, or relationship grants. Downgrading that membership to a client-only role revokes internal access on the next request, even when a default Team grant or creator-specific grant remains. A Team grant to the owner organization is not a client share. The persisted business binding and current client_of relationship identify this firm-work boundary; the organization’s legal form does not. Explicit external client grants keep their role/action checks, and unbound client-owned legacy work retains its existing access rules.
External access requires both the action permission in the acting organization and an explicit relationship-scoped grant. Lists filter each record using the same visibility rules as reads. External callers can discover explicitly shared spaces through the owning organization’s space list. Without any readable shared spaces, that list returns 404. Listing a space’s tasks requires read access to the space and returns only tasks for which the caller has a read grant. Direct task and item reads check the task grant independently of space access. Grant removal, membership removal, and organization deactivation take effect on the next request.
Creating a task or task item requires the corresponding create permission in the parent’s owning organization. Creating an item also requires the parent task’s taskItem:create grant. Both create endpoints return 404 when the actor is acting for another organization.
Space and task grants support read, update, and delete. Task grants also support taskItem:create, taskItem:update, taskItem:delete, taskRelationship:create, taskRelationship:update, and taskRelationship:delete. Each write grant applies only to the named action. Relationship writes require that action on both tasks.
Updating or deleting a relationship returns 404 if either stored task ID differs from the value checked during authorization.
Missing sessions return 401; missing active organization selections and untrusted mutation origins return 403; inaccessible or missing individual resources and collection parents return 404. List operations validate the parent and collection access even when there are no children. A successful empty list means the caller can access the collection but it has no visible results; inaccessible entries are omitted. Invitation lists return 404 when the selected organization is unavailable or the caller is no longer a member. Invalid input returns 400. Duplicate space names, duplicate/self relationships, a second subtask parent, a subtask cycle, and nonexistent assignees return 409. Successful deletes return 204. Deleting a space cascades to its tasks, items, and relationships; deleting a task cascades to its items and relationships.
The WB-72 migration replaces space_organization and its enum with the owned work tables and the space_type enum. The approved starting state has no user data or assignments to backfill. Apply through the normal migration workflow; this change does not run a live cleanup or deployment.
The subsequent subtask_hierarchy migration validates existing links before completing. Multiple parents or a cycle cause migration failure; it preserves the links for explicit correction rather than silently removing them.
Space sharing
access_grant is the source of truth for explicit space access. A space grant uses resource_type = 'space' and resource_id = space.id. A matching read grant lets its recipient open the space, subject to their current organization membership and role. Derive the list of people granted access from these rows and current organization memberships. This design requires no separate space membership table.
An organization-wide grant sets access_grant.organization_id to the receiving organization and leaves user_id null. It covers eligible members acting for that organization, including members who join later. Set user_id as well for a grant to one member. Grants to another organization also require organization_relationship_id. Existing relationship-scoped grants take their recipient from the target of an owner-to-recipient relationship. A grant that explicitly names a client as its recipient can use the client’s client_of relationship to the firm.
Organization lifecycle and invitations
Organization status and deactivation time are stored on the Better Auth organization. Status is a PostgreSQL enum with values active and deactivated, defaulting to active. A database constraint requires deactivated_at to be present exactly when the status is deactivated; updates must change both fields together.
The Workbench /organization-invitations endpoints invite an organization to establish a client–provider or group relationship; they do not invite a person to become a member. The sender supplies the recipient email, the recipient’s role, and optionally the recipient organization ID. The recipient organization must differ from the inviting organization, though the same person can administer both. Invitations expire after seven days; creation and listing responses include expiresAt as an ISO 8601 timestamp, and expired pending records are returned as expired. Email delivery is not configured. Acceptance requires the invited email to match the current verified user and the user to have the required relationship permission in the selected organization. A specified recipient organization must also match. Acceptance records the organization and creates the relationship in one database statement; it does not add membership or create access grants. Removing relationships or cancelling invitations also requires the relevant relationship permission. An invited client is client_of the inviter; an invited provider receives the inverse relationship. An invited group member is member_of the inviter; an invited group receives the inverse relationship.
The shared API exposes GET /organizations/:organizationId/relationships, GET and POST /organization-invitations, and POST /organization-invitations/accept, /organization-invitations/cancel, and /organization-relationships/remove. Browser requests use the /api prefix. Invitation creation and acceptance check Better Auth’s organizationRelationship:create permission for the acting organization; removal checks organizationRelationship:remove for the acting organization, which must match one end of the relationship. Cancellation checks organizationRelationship:remove for the inviting organization. No configured role currently has these permissions. Invitation lists contain invitations sent by the acting organization and invitations for the verified user email whose recipient organization is either unspecified or matches the acting organization. Relationship lists require the requested organization to match the actor. A missing session returns 401; a missing active organization selection or an untrusted mutation origin returns 403; unavailable records or required membership return 404. Successful cancellation and removal return 204. Accepting an invitation returns 409 if the relationship already exists or would create a containment cycle; other database errors follow standard server error handling.
Organization, member, and invitation primary keys and their user/organization foreign keys are native UUIDs. The reviewed schema in auth-schema.ts stores the optional session active_organization_id selection as a UUID. It preserves Better Auth’s lack of a foreign-key constraint on that selection; authorization must check current membership.
Firm signup
Firm signup is invite-only. A verified, unbanned platform admin opens /firm-invitations in the separate internal admin app (apps/admin), enters the prospective firm admin’s email and issues an invitation. Firm Admin membership alone does not grant this platform authority. Invitations last 48 hours, are bound to the invited email, and can be canceled before acceptance. Issuing the same live pending email reuses its link without another email. An expired invitation can be replaced by issuing a new one. The page lists the latest 100 invitations and their delivery status; use Refresh status to check again.
When email is enabled, creation commits the invitation and a delivery job together. The existing durable invitation-email workflow sends a branded signup link and checks that the invitation is still pending, unexpired and issued by a current platform admin before sending. With email disabled, the page explicitly offers a link to share manually. Cancellation, expiry or loss of issuer platform authority prevents redemption. The invitation itself does not create a firm or membership.
The recipient opens /sign-up?invitationId=<UUID>, signs in with the existing Google identity flow and enters only the firm name. The signed-in contact name and email are displayed, not collected again. Google must provide a verified email matching the invitation. Opening /sign-up without an invitation explains that signup is invitation-only. Existing Advisor accounts and login URLs remain independent; new-firm invitation emails point to Workbench.
POST /firm-signups requires the invitation ID, trusted frontend origin, verified session and rendered actor precondition, but no existing organization membership. It locks the founder and invitation, then creates the active legal-entity organization, Firm Admin membership and accepted invitation in one transaction. Selecting the firm opens an empty client directory. The stable firm-<user UUID> slug supports one self-service firm per identity. An accepted link can reopen that firm after a lost response, including after expiry, only while its original recipient retains active founding Firm Admin authority. It never restores revoked membership or changes general organization-creation permissions.
GET /firm-signups/invitations/:invitationId inspects a recipient’s access. GET and POST /firm-signup-invitations, plus DELETE /firm-signup-invitations/:invitationId, require current platform-admin authority on the server. Accepted invitations cannot be canceled. These records are separate from Better Auth membership invitations: the target firm does not exist when its signup invitation is issued.
Adding a client creates its business, firm relationship and default Finance space in one transaction, then opens Finance directly. The existing space initializer saves Team and Client conversations, Wes’s introduction, storage intent and Finance setup intent. Provisioning starts after commit; provider readiness remains separate from space creation. Firm Operators retain client creation through this fixed operation without receiving arbitrary space-management authority or client membership. Existing clients are not backfilled. Connect QuickBooks through the existing Finance connections flow; connection provisioning owns its consent and readiness behavior.
Internal admin app
The internal app is a separate TanStack Start workspace, frontend Worker and browser origin. It uses coss UI’s neutral tokens and Base UI primitives, with form/card/table particle composition. Workbench has no invitation-management page or account-menu entry; /sign-up remains in Workbench. Both apps use same-origin /api forwarding and the existing backend contracts. Platform-admin authority is checked in the database for every management operation, not inferred from the admin hostname or email domain. Firm Admin membership alone does not grant access.
Set WORKBENCH_ADMIN_URL to the exact separate HTTP(S) admin origin, using the same protocol as BETTER_AUTH_URL. Better Auth permits only those two configured hosts, uses separate host-only session cookies, and continues to share its user and role records. Management mutations require the admin origin; signup mutations require the Workbench origin. Invitation emails always use BETTER_AUTH_URL, so recipients enter the customer app. No extra permissions or identity migration is introduced.
Local startup launches both frontends. PR preview supplies its pr-<number>-admin URL and provisions the admin Worker. Production config selects https://admin.workbench.wurthy.co; Alchemy attaches that hostname to the separate Admin Worker through its native custom-domain property, which owns DNS and TLS. PR previews retain their workers.dev names. The existing workbench.wurthy.co Web Worker custom domain remains unchanged. Outside previews, the admin Worker is provisioned only when WORKBENCH_ADMIN_URL is configured. With no admin URL, the original single-origin authentication configuration is preserved.
Production admin sign-in uses native Google OAuth. Register https://admin.workbench.wurthy.co/api/auth/callback/google in the existing Google client before enabling it. The admin shares production’s database, so it refuses sealed proxy-profile completion just like the stable and legacy production callback hosts. The proxy hooks are skipped only for the configured direct admin origin; native Google state verification still applies. This preserves the existing protection against a proxy-secret holder forging a production session.
Preview admin sign-in uses the existing stable OAuth proxy and the preview database. Its origin pattern must be included in the stable proxy’s OAUTH_PROXY_ORIGINS, alongside the existing Web preview pattern. The per-request host checks preserve both the canonical Workbench and OAUTH_PROXY_LEGACY_URL callback behavior. Workbench and admin cookies remain host-only. Ordinary page requests to the production admin Worker alias redirect to the canonical admin hostname, preserving path and query; API, server-function and mutation traffic are not redirected.
Hostname ownership is separate:
| Hostname | Owner | Resource |
|---|---|---|
workbench.wurthy.co |
Existing Workbench stack, PR #279 | Web Worker custom domain |
admin.workbench.wurthy.co |
Same stack, PR #278 | Separate Admin Worker custom domain |
executor.wurthy.co |
workbench-executor-domain stack, PR #280 |
Existing Railway service domain and scoped DNS records |
The API stays behind each frontend’s /api service-binding proxy. Neither stack should publish records for the other stack’s hostname. Existing app.wurthy.co, Advisor and mail records stay unchanged. Executor connections continue returning to https://workbench.wurthy.co/executor/callback.
A verified platform-admin account must already exist; there is no self-promotion control. Google callback registration and stable proxy preview-admin allowlisting are release prerequisites. Live Google consent, TLS on the new hostname and screen-reader operation require hosted verification.
Sign-in and session UI
Every page except /sign-in and /sign-up requires a session. The root route’s beforeLoad calls the getSessionUser server function before a page renders and again on each navigation. The function reads GET /api/auth/get-session from the API Worker with the request’s headers, and passes Better Auth’s Set-Cookie on to the browser. Without a session, the route redirects to /sign-in?redirect=<path>; an expired session takes the same path on the next navigation. Routes read the signed-in user from the root route context as user.
/sign-in offers Google only, through authClient.signIn.social. After sign-in the user returns to redirect when it is a path on this site, otherwise to the clients list. A signed-in user who opens /sign-in goes there directly.
| Failure | Signal | Message |
|---|---|---|
| After Google | error code that Better Auth adds to /sign-in |
access_denied: sign-in was cancelled. account_not_linked, email_not_found, email_not_verified: this Google account cannot sign in. Any other code: sign-in did not finish. |
| Starting sign-in | Status of POST /api/auth/sign-in/social |
404: Google sign-in is unavailable, because its credentials are not configured. 429: too many attempts. No response: check the connection. Any other status: a server problem. |
| Session check | getSessionUser fails, such as a 500 from the API Worker |
The root route’s ErrorPage, with a Try again button that reloads. |
| Signing out | POST /api/auth/sign-out fails |
A toast; the user stays signed in. |
A sign-in state Better Auth cannot read, such as state_not_found, also returns to /sign-in with its code through onAPIError.errorURL, and shows the generic message.
The account menu at the foot of the rail shows the user’s name and email, and signs out with authClient.signOut. A successful sign-out loads /sign-in as a full page, which drops all client state.
Signed-in users see verified organization access and explicit client-service availability. Client and space capabilities require their owning integrations; see frontend data fetching.
Routing and cookies
Both frontend proxies preserve /api/auth and remove /api from other API paths. The backend mounts Better Auth at /api/auth/* and passes the request directly to it. Endpoint matching and future OAuth callbacks use the same public path without a backend URL rewrite. Better Auth routes compose alongside ServerApi inside the same http/Api.ts layer; all responses use Cache-Control: no-store.
BETTER_AUTH_URL is the public frontend origin, not the API Worker URL. Only that origin is trusted. Better Auth’s origin and CSRF checks remain enabled. Session cookies are host-only, HttpOnly, and SameSite=Lax; HTTPS origins use Secure cookies. Cookie session caching is disabled so revocation is checked against the database. Hyperdrive caching also stays disabled.
| Environment | Origin and cookie behavior |
|---|---|
| Full local development | bun run dev derives BETTER_AUTH_URL from this checkout’s Portless frontend URL. Default HTTP uses non-Secure cookies; configured Portless HTTPS uses Secure cookies. |
| Frontend-only development | The default origin is http://localhost:3000. The hosted personal API must have been configured for that exact origin and have the auth migration applied. |
| PR preview | The preview command sets the isolated PR frontend’s HTTPS origin. Its cookie and database branch are separate from production. |
| Production | Alchemy attaches workbench.wurthy.co to the existing Web Worker for the prod stage. The Production workflow supplies https://workbench.wurthy.co through BETTER_AUTH_URL. Cookies are scoped to that frontend host. |
Do not share parent-domain cookies or add wildcard trusted origins to accommodate previews.
The stable callback
Production’s Google client registers https://workbench.wurthy.co/api/auth/callback/google, and production and future previews use https://workbench.wurthy.co as OAUTH_PROXY_URL. Alchemy’s native custom domain provisions the Web Worker’s DNS and TLS; the API remains behind the frontend’s same-origin /api proxy. PR previews retain their existing workers.dev hostnames and isolated databases.
During the hostname migration, retain the previous production Google callback registration. Production’s optional OAUTH_PROXY_LEGACY_URL names that exact previous origin, so already deployed previews can still exchange codes issued for the old callback. This changes the exchange redirect URI only for a validated proxied state received at that configured origin; canonical sign-ins and completion-endpoint restrictions stay in place. Remove the legacy setting and provider registration only after old previews and in-flight sign-ins no longer use them. Existing sessions remain scoped to the old host; users sign in again on the new hostname.
Production page requests on the old Worker hostname redirect temporarily to the configured origin, preserving the path and query. API calls, server functions and Executor callback pages remain on their requested host so a return with one-use codes or browser-held connection state is not redirected during processing. Preview and local page origins are unchanged.
Google accepts only registered callback URLs, and previews and local checkouts have origins Google cannot know in advance. Better Auth’s OAuth proxy lets one registered callback serve them all. OAUTH_PROXY_URL names the stable frontend origin whose /api/auth/callback/google is registered with the Google client; OAUTH_PROXY_SECRET is shared by every stage behind that client. A stage with both values sends Google to the stable origin with its own origin sealed in the state. The stable origin exchanges the code and redirects the browser to <origin>/api/auth/callback/google/oauth-proxy with the Google profile encrypted under the proxy secret; that stage then creates the user and session in its own database and sets its own host-only cookie. The stable origin stores nothing for a proxied sign-in. The proxy is a no-op on the stable origin itself, which still needs both values to complete proxied callbacks. Two guards in packages/auth/src/oauth-proxy-guard.ts limit what the shared secret can do, following Executor’s production guard. The stable origin refuses the plugin’s completion endpoints, so a holder of the secret cannot forge a profile and sign in there, and before it exchanges a Google code it checks every redirect sealed in the proxied state (callbackURL, its nested callbackURL, errorURL, newUserURL) against OAUTH_PROXY_ORIGINS, origin patterns such as https://workbench-pr-*-web.<subdomain>.workers.dev and http://localhost:*; relative paths and its own origin always pass. Every host re-checks the final Location of the callback the same way, because the plugin rewrites it from the nested callback.
Each stage keeps its own Better Auth signing secret; only the dedicated proxy secret is shared, so a leaked proxy secret exposes proxied sign-ins but not sessions. Previews and development share one non-production client and proxy secret; production uses its own. onAPIError.errorURL points at /sign-in, so a proxy failure such as payload_expired shows the sign-in page’s error message.
Login rate limiting
Better Auth rate limiting is explicitly enabled in every environment. The pinned Worker bundle does not provide the runtime NODE_ENV value needed by Better Auth’s production default. Its standard per-endpoint rules limit sign-in and sign-up requests to three attempts per ten seconds and return 429 when exceeded.
Counters use the shared PostgreSQL rate_limit table through the auth adapter, so separate Worker executions and isolates share the limit. Client identity comes from Cloudflare’s edge-provided cf-connecting-ip header; caller-supplied x-forwarded-for values do not select a different bucket. Keep the frontend proxy forwarding the original request headers. Local clients can supply cf-connecting-ip for testing; clients without a resolved address share Better Auth’s fallback bucket.
The additive rate-limit migration must be applied before deploying this configuration, through the existing schema pipeline. Regenerate the auth schema and Drizzle migration together when changing persisted rate-limit fields.
The pinned Alchemy schema reader supports Drizzle v9 incremental snapshots directly. The previous local patch is removed; committed migration SQL, snapshot IDs, and migration history are unchanged.
Database and signing secret
The existing Hyperdrive connection feeds the integration’s CloudflareHyperdrive database layer. The application retains its separate Effect Drizzle Db service. The auth adapter uses a request-scoped PostgreSQL pool, capped at one connection, rather than passing the incompatible Effect Drizzle client to a Promise adapter.
Alchemy provisions the stable random signing secret for auth ID WorkbenchAuth at the stack resource ID WorkbenchAuthSecret and binds it to the Worker. Keep this ID, stack name, stage, and Alchemy state intact across deployments. Losing state or replacing the secret invalidates existing session signatures. Local Alchemy stages have their own state and secret. The former manually supplied BETTER_AUTH_SECRET setting is removed.
packages/db owns the reviewed user, session, account, verification, organization, member, invitation, and rate_limit tables and migrations. These are authentication records, not the removed business data model. Explicit Better Auth field mappings match the snake_case SQL columns. The CLI configuration selects Better Auth’s Relations V2 Drizzle adapter, following Alchemy’s Drizzle guide. The official CLI writes a temporary reference schema; compare it when changing auth options and edit the checked-in Drizzle definitions directly. Its generated organization status and kind use text with enum type metadata, while the reviewed schema uses PostgreSQL enums. Preserve UUID storage for the active organization selection and the existing slug and membership uniqueness constraints; the CLI defaults differ. There is no custom generator or output-rewriting script.
Auth primary keys and their foreign keys use native PostgreSQL UUIDs, configured through advanced.database.generateId: "uuid". PostgreSQL generates IDs with pg_catalog.gen_random_uuid(). IDs remain strings in JSON. External provider/account identifiers and session tokens remain text.
Run the schema generation commands after changing auth options and review both schema and SQL. Wrapper migration is disabled with migrate: false; the existing PlanetScale deployment workflow applies migrations before the dependent API Worker. Local startup neither applies migrations nor provisions database resources. An existing personal stage needs an approved provisioning run before testing authentication against it. Database cleanup, role rotation, and manual deployment remain separate approvals.
Executor host admission
The custom self-hosted Executor host can recheck a Workbench subject with POST /internal/executor/access. The request and successful response contain UUID userId and organizationId fields. This compatibility endpoint is restricted to EXECUTOR_PILOT_ORGANIZATION_ID; it is not the production Finance space authorization model.
The host authenticates with Authorization: Bearer <EXECUTOR_ACCESS_SECRET>. Both configuration values must be present, and the secret must contain at least 32 characters; otherwise admission returns 503. A missing or incorrect credential returns 401. Browser cookies do not authenticate this endpoint. The secret comparison uses constant-time comparison for equal-length credentials.
Each authenticated request reads current membership, organization status and user ban state from the database. A missing membership, unsupported role, deactivated organization, unexpired ban or different organization returns 403, even if the user still has a valid Workbench browser session. Responses are not cached. The host must fail closed when admission is denied or unavailable and call this endpoint for existing host sessions and saved work, not only at sign-in.
Admission establishes identity eligibility only. It does not grant Executor app management, provider consent, tool execution or access to a shared Finance space. Firm-owned Finance needs a separate app/group per authorized space and current action grants; a participant must not inherit broad tool access from membership. Provider credentials and consent remain owned by Executor.
Activation requires the reviewed custom host image with live checks, an explicit deployment organization, and a dedicated host/server secret configured on both ends. Production and preview credentials must be separate. This slice does not provision Railway, activate OIDC, create provider accounts or authorize a provider. OIDC registration and subject/grant binding must be verified before presenting the host as integrated in the product.
Executor OIDC
Set EXECUTOR_OIDC_CLIENT_ID together with EXECUTOR_PILOT_ORGANIZATION_ID to enable Workbench as the custom host’s OIDC provider. Partial configuration keeps the provider disabled. The issuer is <frontend-origin>/api/auth; its discovery document is /api/auth/.well-known/openid-configuration, and signing keys are /api/auth/jwks. The existing sign-in page carries the signed authorization request through Better Auth’s OAuth provider client plugin.
An operator with the platform-admin role registers one trusted, skip-consent client through Better Auth’s admin client API, with the host’s exact HTTPS /api/auth/callback/sso URI. Preserve the returned client identifier and client secret in the appropriate server/host configuration. The client must use authorization-code flow with PKCE and openid profile email scopes. Dynamic and unauthenticated registration are disabled. Ordinary users cannot manage OAuth clients. Browser-session JWT issuance at /api/auth/token and the JWT response header are disabled, as required by the OAuth provider’s security configuration.
The configured client is admitted only when a live Workbench session explicitly selects the configured organization and its user remains an eligible member. Sign-in does not silently select or replace an organization. The ID token subject is the immutable Workbench user ID and includes the configured organization claim. Membership, organization status, ban and complete comma-separated role set are checked again at code exchange, so removal during authorization cannot issue an identity. Existing host sessions and provider grants still require the separate live admission check above.
The additive migration creates the pinned OAuth provider and signing-key tables; it leaves existing auth, space and task records intact. Apply it through the normal deployment pipeline before enabling the provider. Hosted configuration, operator registration and the custom Railway image are activation prerequisites; local integration tests exercise a real persisted authorization-code exchange and verify its signature, not a live Railway SSO session.
Restricted shared provider consent
Pinned Executor beta.59 requires app-management rights to start an app-scoped account connection. Each connection step and OAuth callback also requires the original creator and current management rights; reconnect requires credential ownership. A manager’s connection URL is therefore not a transferable authorization invitation.
A restricted client cannot use that native UI path to supply a shared account. A November 20, 2026 disposable test of the unmodified beta.59 image established an alternative: a backend service identity can create a pending app connection, start OAuth and complete it with its bearer credential. The consenting browser needs no Executor session. The saved account belongs to the service identity; Workbench must record the actual consenting person separately. This preserves native management checks instead of granting clients administration.
The disabled-by-default Workbench consent broker binds the consenting subject, firm, space/app, provider requirement and pending connection, and checks current connect-only authority at start and callback. Keep new accounts on a private intake app until their provider company or mailbox has been verified, then link them to the intended Finance app. The intake must isolate concurrent intents, or serialize verification and transfer against the exact saved account; a mutable shared slot cannot establish which account was verified. The implementation creates an isolated private intake app for every intent. The test verified native account linking, authorized teammate reads and continued client denial. The server now has durable recipient-bound intents and HTTP integration tests for competing claims, changed state, removed or expired authority, replay and cancellation; these changes are local and have not been deployed. See the implemented consent boundary for exact behavior and gaps.
Callback routing remains integration work: beta.59 sends the provider to /api/oauth/callback on the Executor origin. Workbench must receive that return through an explicitly routed callback, validate its intent, and forward the original callback URL to native completion under the service identity. Do not assume a manager’s browser callback can be handed to another person. The test submitted that callback programmatically against a synthetic OAuth provider; real QuickBooks consent, refresh, reconnect/disconnect and browser return routing remain unverified. Keep connection capability unavailable until those boundaries are implemented and tested. OIDC admission does not implement this flow.
Invitation email
Use the email activation guide for provider, backlog and approved hosted verification steps.
Invitation messages use the shared transactional email shell with the approved Wurthy logo, Workbench product name, friendly role labels, an explicit UTC expiry, an acceptance button and a copyable fallback URL. HTML and plain text carry the same acceptance destination. The layout remains readable without images and uses system fonts. The email-compatible PNG is derived from the canonical header SVG; its public HTTPS URL uses the stage’s frontend origin. Preview fixtures and the command live in the CLI reference.
Invitation email uses Effect workflows with Alchemy’s Cloudflare NativeEngine. PostgreSQL owns the durable send intent; Cloudflare Workflows owns activity checkpoints and waits. Delivery defaults to disabled. Configure the approved stage through the environment configuration, review the Alchemy plan, and approve deployment before activation.
| Setting | Value |
|---|---|
WORKBENCH_EMAIL_ENABLED |
true to request delivery for new person invitations |
WORKBENCH_EMAIL_STAGE |
Exact approved Alchemy stage, such as prod; other stages receive disabled delivery and no provider credentials |
WORKBENCH_EMAIL_FROM |
Bare mailbox on a Resend-verified sending domain |
WORKBENCH_EMAIL_REPLY_TO |
Monitored reply mailbox |
WORKBENCH_EMAIL_RESEND_API_KEY |
Dedicated stage-owned Resend sending key, stored as a secret |
WORKBENCH_EMAIL_WEBHOOK_SECRET |
Signing secret for this stage’s Resend webhook endpoint |
BETTER_AUTH_URL |
This stage’s HTTPS frontend origin; acceptance links use this origin |
SMB Portal’s recorded sender was Wurthy <notifications@mail.wurthy.co> with reply-to support@wurthy.co. Confirm current domain verification and mailbox routing before reusing those addresses. No provider credentials or DNS settings were copied. Native Google sign-in remains the authentication flow.
Durable handoff and recovery
The server-only Better Auth invitation field emailDelivery stores the approved stage, origin, sender and reply-to snapshot. A PostgreSQL trigger creates invitation_email in the same transaction as the invitation. A rollback removes both records. Disabled creations retain manual copy-link delivery and create no job; existing manual invitations are not backfilled. An authorized explicit resend retains its routing settings and creates a fresh expiry-qualified job atomically with the renewed expiry. Organization relationship invitations remain separate.
Explicit resend
People offers Resend invitation email for invitations originally enrolled in email delivery. POST /organizations/:organizationId/member-invitations/:invitationId/resend rechecks the acting manager, original inviter, target role, active organizations and original firm relationship. It cannot resend an accepted or canceled invitation, an invitation from another firm, or an invitation whose recipient already belongs to the target organization. Expired but still pending invitations may be renewed for 48 hours. The original inviter, recipient, role and routing snapshot remain unchanged.
The operation locks the invitation and its delivery history, then permits at most three resends after the original email, at least one minute apart. Queued or sending jobs block another resend. An uncertain send blocks a fresh identity to avoid duplicate delivery. Canceled jobs with an unacknowledged provider attempt, and expired sending jobs in that state, display uncertain and block resending too. Any recorded bounce or spam complaint blocks resending this invitation, and jobs belonging to another stage cannot be sent from the current stage. The native auth resend flag is rejected so it cannot bypass these checks. No provider request runs in the HTTP operation.
Success reports email-queued, not delivered. A blocked response explains the cooldown, limit or recovery state without changing the invitation. Disabled delivery and original manual invitations report copy-link without renewing expiry or creating an email job. Copy-link invitations can be canceled and recreated when email is enabled; they are never silently enrolled. People disables resend while delivery is active or uncertain, keeps copy/cancel available and refreshes expiry and delivery after an explicit resend. A lost response asks the manager to refresh and check status before trying again; the browser does not automatically retry the mutation.
The server’s minute cron claims up to 25 pending jobs with short dispatch leases. It starts an Effect workflow by deterministic job identity. A missed dispatch becomes eligible after two minutes; repeat dispatch observes the same execution. Jobs are selected by stage. Each attempt rechecks pending status, exact expiry, recipient, role and the original inviter’s current organization authority. Canceled, expired, superseded and unauthorized jobs stop before contacting Resend. A request already accepted by Resend cannot be unsent.
Before the first provider request, the job saves the rendered HTML/text and sender snapshot. Retries use that exact message and a stable Resend idempotency key. Each request has a 15-second timeout. The workflow uses Activity.retry around a typed send activity, with DurableClock.sleep between attempts. It makes at most four application attempts, uses durable backoff and respects Retry-After; permanent errors stop immediately. A permanent rejection on the first attempt is failed; after an earlier unacknowledged attempt it remains uncertain, because that earlier request may have sent the email. The retry policy and conditional database claim share one attempt limit; persisted counts also bound replays after interruption. Ambiguous attempts stop after 23 hours from the first attempt, before Resend’s 24-hour duplicate-protection window ends. Exhausted or interrupted executions become uncertain for review; recovery never creates a fresh send identity automatically.
Disabling a stage prevents dispatch of queued jobs. An already running workflow observes the disabled configuration at its next attempt and cancels that job. Retained queued jobs can resume when the stage is enabled again; review pending jobs before reactivation. Do not rotate provider accounts or change delivery snapshots to recover an ambiguous send.
Delivery status and events
GET /organizations/:organizationId/member-invitations/:invitationId/delivery returns the current delivery state to an authorized membership manager, including the original firm restriction for delegated invitations. People refreshes active delivery states while the row is visible. States include manual, queued, sending, accepted, delivered, bounced, failed, complained, canceled and uncertain.
Invitation creation returns delivery: email-queued only for the configured email path, or copy-link when disabled. Wes returns emailSent: null for queued delivery and false for manual sharing, and always includes the fallback link. Returning an existing pending invitation does not send another email. Workflow completion does not prove inbox delivery.
Configure a Resend webhook on the public API origin at /email/events, subscribing to email.delivered, email.bounced, email.failed and email.complained. Verify the target origin through the application’s stage outputs. Store its signing secret in the stage’s environment. The handler bounds the raw body to 64 KiB and verifies its Svix signature before decoding. Receipts deduplicate by stage and event ID, match the provider ID or signed job tag, and reconcile receipts that arrive before send acknowledgment. Delayed delivery events cannot erase a bounce or complaint. delivered means delivery to the recipient’s mail server, not inbox placement or reading.
Provider errors, credentials, email bodies and acceptance URLs are not logged. The outbox retains message snapshots and provider identifiers for recovery and review. Signed event records retain only event/provider identifiers, stage and outcome. Live sending, provider webhook registration and hosted restart verification require a separately approved activation; local tests do not establish live deliverability.
Access addition emails
New direct organization memberships and user-specific Client conversation access use the branded transactional email shell and the same stage-owned sender settings as invitation email. A membership email opens Workbench and tells the recipient which organization to choose; it does not require invitation acceptance. A Client conversation email links to that conversation with the recipient’s acting organization and states that existing Client history is available. Group-wide grants and repeated additions do not create additional source events.
The scheduled notification consumer claims up to 25 unprocessed addition events and atomically saves each rendered message, recipient mailbox and fixed source set. Every source can belong to one email channel job. Source groups and message snapshots are sealed before dispatch; a later event cannot change an existing provider request or reuse its identity. Sources already unavailable when captured receive a terminal canceled record so revoked events cannot block new work. Enabling the stage processes existing uncaptured addition intents; review that backlog before activation.
Effect workflows on Cloudflare dispatch sealed notification jobs with the same bounded attempts, durable backoff, dispatch leases and 23-hour ambiguity limit as invitation email. The Resend key uses the notification job identity. Every attempt rechecks every source against current recipient membership and conversation access, the verified current email, the deployment stage and mailbox suppression. Removed sources, changed mailboxes and suppressed recipients stop further attempts. Jobs with no provider attempt become canceled; jobs stopped after an unacknowledged attempt retain uncertain delivery. Retries send the exact persisted HTML and text.
The shared signed /email/events endpoint reconciles notification receipts as well as invitation receipts. A receipt received before provider acknowledgment is applied when the provider ID is saved. Bounce and complaint outcomes suppress later notification emails for that stage and mailbox; a late delivery cannot clear suppression. The database retains suppression and uncertain jobs for operator review. A permanent provider rejection after an earlier unacknowledged attempt also retains uncertain delivery; only a permanent rejection on the first attempt establishes failure. Re-enabling delivery does not mint fresh identities for canceled or uncertain jobs. These records and local integration tests do not establish live deliverability; activation follows the invitation email configuration and approved deployment workflow.