AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(web): redesign SSO as Authentication with a SAML setup walkthrough (#16557)
lina-alomari120f7ba371ef
diff --git a/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md b/brain/knowledge/connections-auth/ee-authentication-sso-rbac.mdindex c8b4bbb793c..985dc63d3a4 100644--- a/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md+++ b/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md@@ -27,7 +27,17 @@ Enterprise auth layer extending CE with SAML 2.0 SSO, Google/GitHub federated OA- **The SAML round-trip used to forget where the login was going, and the obvious fix moves a trust boundary.** Three losses, all in the redirect and none in the assertion handling: the web app called `/api/v1/authn/saml/login` with no `from` (`saml-login-form.tsx`, `third-party-logins.tsx`), `/authenticate` hardcoded `navigate('/flows')`, and `/acs` redirected to `networkUtils.getRequestBaseUrl(req)` — an origin with no path — so a subpath instance 404'd at `example.com/authenticate`. Password sign-in hid all three by never leaving the origin; they surfaced the moment a login *started* elsewhere, so MCP OAuth (`/mcp-authorize` → `/sign-in?from=…`) abandoned the authorize request. **The trap worth remembering:** it is tempting to carry the starting origin through the IdP in RelayState. Do not. `/acs` derives its redirect from the IdP's POST, whose `x-forwarded-host` only the operator's edge sets; capturing the origin at `/login` instead hands that decision to an endpoint an attacker can call directly, and `networkUtils.candidateHosts` deliberately *prefers* `x-forwarded-host` — so a spoofed header would mint a return target for `evil.com`, and a phished IdP link carrying it would deliver the victim's session token to `/authenticate?response=`. Signing or storing the captured origin does not close that; only resolving it against an allowlist would. **What shipped avoids the question entirely:** MCP consent is served from the frontend base (see [[mcp-server]]), so login leaves and returns to the same origin in the same tab. `from` rides `sessionStorage` (`lib/federated-login-redirect.ts`, saved by `useStartSamlLogin` at the three SAML entry points, consumed and cleared at `/authenticate`). It stores **only** `/mcp-authorize`, exactly or followed by `?` — every other destination, including legitimate in-app deep links, is refused and SSO lands on the default page as it always has. That narrowness is deliberate: the mechanism exists for the one flow that cannot survive losing its continuation, and scoping it by destination keeps deployments without MCP on their existing code path. Gating it on `AP_MCP_URL` instead would not work — `getMcpUrl` falls back to `AP_FRONTEND_URL`, so the `MCP_URL` flag is never null, and `/authenticate` consumes synchronously on mount while flags arrive async, and `/acs` builds its redirect from the request origin (`new URL('/authenticate', networkUtils.getRequestBaseUrl(req))`), which is the one place the SPA can route it. No RelayState, no Redis, no allowlist, and the origin never crosses the IdP.- **Restoring the subpath on the SSO return *breaks* SAML sign-in on a prefixed instance, because the SPA cannot route a prefixed path — and the bare-origin version it replaced accidentally could.** Verified end to end against a real SimpleSAMLphp IdP behind Kong (`strip_path: true`) with `AP_FRONTEND_URL=http://host/activepieces`: the assertion validates and `/acs` redirects to `http://host/activepieces/authenticate?response=…` exactly as intended — and the SPA then bounces away with the session response unconsumed, because `createBrowserRouter` has no `basename` (see [[web-feature-anatomy]]). Measured both ways on one harness: `new URL('/authenticate', getRequestBaseUrl(req))` drops the path, lands at the origin root, and signs in; restoring the prefix kills the login. So the two kinds of URL AP emits have opposite requirements and **must not share a helper**: *protocol URLs the server advertises* (OAuth issuer and endpoints, ACS `Destination`, webhooks, invitation links) need the configured base, while *browser landing routes* (`/authenticate`, `/mcp-authorize`, `/sign-in`) must stay wherever the SPA can actually route, which today is the origin root. With the origin-root return and the UI at the root, the whole SSO-into-MCP chain completes in a browser — IdP credential form → `/acs` → `/authenticate` → `from` restored from `sessionStorage` → consent → code → token → `tools/list`; that chain is the point of the `from` round trip, and it is what a prefixed instance loses. Until the SPA gains `basename` + vite `base`, prefixing a browser landing route is always wrong.- **AP accepts only *plaintext* SAML assertions, and an encrypting IdP fails with a misleading error.** `createSp` sets `isAssertionEncrypted: true`, but samlify reads that flag off the **remote** entity (`flow.js`: `decryptRequired = from.entitySetting.isAssertionEncrypted`), where `createIdp` sets `false` — so the SP-side flag is inert. It could not work anyway: samlify decrypts with `entitySetting.encPrivateKey`, which AP never sets (`privateKey` holds `samlProvider.idpCertificate`, used for signing). Point an IdP with `assertion.encryption` on at it and the failure surfaces as `ERR_UNMATCH_ISSUER` — not a decryption error — because the issuer comparison reads the *assertion's* issuer out of a decrypted document that does not exist. Configure IdPs to sign but not encrypt.-- SSO settings page wrapped in `LockedFeatureGuard` keyed on `ssoEnabled`.+- The SSO settings page (titled **Authentication** since ENG-977, route still `/platform/sso`) is wrapped in `PlanFeatureSample feature="sso"`, which renders the real page faded under an upgrade card when `ssoEnabled` is off. It has no sample data, so a locked platform sees its own real values.+- **The allowed-domain list only runs once a platform is known, so on Cloud it misses most first sign-ins.** Self-hosted always knows the platform (the oldest one), so `assertDomainIsAllowed` runs in `signUp` for every provider and on every email-and-password and email-code sign-in; returning Google/SAML users skip it. On Cloud `getPlatformIdForRequest` is `null` for anyone not signed in, so `signUp` runs without a platform and skips the check, and `provisionUserInvitation` then makes the person a member of every invited platform without checking either. Net effect on Cloud: password and email-code sign-ins are checked once the person is a member, Google is never checked, SAML only when the person has no account anywhere, and an invited person outside the list joins and is then refused at their next password sign-in. Community never checks. Until ENG-999 fixes this, the Authentication page copy is split by edition: Enterprise says the list limits who can *join*, Cloud says only "email and password sign-in"; ENG-999 removes the split.+- **To reproduce "SAML connected + pending domain" locally, go through the API, since the UI cannot create it.** Verify a domain, save SAML (`POST /v1/platforms/:id` with `federatedAuthProviders.saml`; placeholder metadata is accepted), then `POST /v1/authn/saml/sso-domain` with a different domain: the new one is pending and SAML is kept. Switching discards the old domain's verification, so re-verifying it later needs a new TXT record.+- **"Verify DNS" asks the API host's own resolver, so a correct TXT record can still fail for a few minutes.** `txtRecordMatches` calls Node's `resolveTxt`, which uses the OS resolver (locally often Tailscale's `100.100.100.100`), not a public one; until that cache expires the old record set comes back. Compare `dig TXT _activepieces-verify.<domain> @8.8.8.8` with plain `dig` before suspecting code. Leftover `activepieces-verify=` records from earlier attempts are harmless: any matching record passes.+- **The Authentication page blocks removing the last working sign-in method in the UI only; the API still accepts it (ENG-483).** `useSignInMethods` is the one place that decides what works: email on, Google really working (the provider flag, not the switch), SAML connected and, on Cloud, a verified domain (without one the sign-in page cannot reach SAML). Remove domain and Disable SSO are blocked when SAML is the only one left; turning email off is blocked when SAML is not connected and Google does not really work; turning Google off is blocked only when Google really works and email and SAML are both off, so a self-hosted Google switch without an OAuth client can always be turned off.+- **`platform.googleAuthEnabled` is a saved switch that defaults to `true`, not proof Google sign-in works.** On self-hosted Google only works once `AP_GOOGLE_CLIENT_ID` and `AP_GOOGLE_CLIENT_SECRET` are set. Whether it really works is `THIRD_PARTY_AUTH_PROVIDERS_TO_SHOW_MAP.google` (credentials set and switch on), the flag the sign-in page uses for its Google button; any "is another sign-in method left?" check must read that flag, not the platform column. Because the flag folds in the switch, the frontend can only tell "not set up" while the switch is on; with it off the state is unknown. The Authentication page shows "Not set up" plus a Setup guide link only on self-hosted with the switch on, and the turn-on dialog states the requirement instead (link built with `adminDocs.url` from the admin kit).+- **The SAML walkthrough keeps both steps mounted and hides the inactive one with a `hidden` class, so a test that finds step 2 text passes even when navigation is broken.** Assert on the step bar instead (`aria-current="step"`, `disabled`) and on `Next`/`Save` state. The SAML step opens only once the domain is verified, except when SAML is already connected (pre-domain setups), so those admins can still reach their connection and Disable.+- **Only removing a verified SSO domain deletes SAML; a pending one goes and SAML stays.** `updateSsoDomain(null)` deletes SAML only when the current verification is `VERIFIED`, so "Cancel verification" matches `expirePendingSsoDomains`, which clears `ssoDomain` and `ssoDomainVerification` after `PENDING_DOMAIN_TTL_HOURS` (3) without touching `federatedAuthProviders`. A platform reaches "SAML + pending domain" when it set up SAML before #13071 added domains (May 2026, no backfill) and only now verifies one, or by changing the domain (the pre-ENG-977 page's "Update domain", or the API; ENG-994); deleting SAML there would remove SSO that was working.+- **Removing the SSO domain also deletes SAML, in one update.** `updateSsoDomain` with `null` clears `ssoDomain`, `ssoDomainVerification` and `federatedAuthProviders.saml` in the same `platformService.update`; the page's Remove domain is that one request. Without a domain the sign-in page could not start SSO anyway (`/discover` needs a verified domain), and new SAML connections already require one. History: #13071 shipped a Remove button that never worked (see the next bullet); #13072 dropped the button without a stated reason; ENG-977 fixed the server and brought it back. **Changing** to a different domain still keeps SAML while the new one is pending. The sign-in page's SSO path is closed then (no verified domain for `/discover`), but IdP-initiated sign-in or a direct `/login?platformId=` link still works, and `assertEmailMatchesSsoDomain` skips unverified domains on purpose so platforms that had SAML before domain verification keep working; so the platform's own IdP can sign in any email until the new domain verifies (ENG-994). `verifySsoDomain` on an already-verified domain returns without re-checking DNS, so the page only offers "Verify DNS" while pending. Removal deletes SAML rather than keeping it saved because SAML has no on/off state: a kept config would stay live with no domain check. When ENG-982 adds on/off, removal should switch to turning SAML off (and the remove dialog and docs that say "deletes" change with it).+- **Every domain claim gets a fresh TXT value, so a record left at the DNS provider never re-verifies anything.** `computeNextVerification` issues `activepieces-verify=<new apId>` for any new or re-added domain, and `txtRecordMatches` needs that exact value at `_activepieces-verify.<domain>` (any of the TXT strings there may match, so admins can add the new value beside the old one). Removing and re-adding a domain therefore always lands on PENDING, and a stale record cannot verify the domain for this platform or another one.+- **`platformService.update` writes most fields with `spreadIfDefined`, which drops `null` as well as `undefined`, so those fields cannot be cleared through it.** That silently made "remove the SSO domain" a no-op while the endpoint still answered `{ ssoDomain: null }`. `ssoDomain` and `ssoDomainVerification` now use `spreadIfNotUndefined`, like `themeColors`; any other field that needs clearing must switch the same way, and a test that reads the row back is the only thing that catches it.- Managed auth gated separately by `embeddingEnabled` (signing keys). See the Managed Auth page.- The authn rate limiter (`core/security/rate-limit.ts`) is registered with `global: false` — it protects NOTHING by default. Every public endpoint that sends email or does auth work must opt in per-route via `config.rateLimit` (see `authentication.controller.ts` / `otp-controller.ts` for the `API_RATE_LIMIT_AUTHN_*` pattern).diff --git a/brain/knowledge/design-system/index.md b/brain/knowledge/design-system/index.mdindex b32c9e1c823..532e349e55a 100644--- a/brain/knowledge/design-system/index.md+++ b/brain/knowledge/design-system/index.md@@ -38,6 +38,7 @@ themes, because we cannot recolour someone else's artwork. `<LogoPlate>` renders- **`CommandList` (`components/ui/command.tsx`) defaults to `overflow-y-hidden`, so a cmdk list silently cannot scroll.** Every caller must add `overflow-y-auto` (or nest a `ScrollArea`); passing only a `max-h-*` looks fine with few rows and clips the rest. Bit the tiers model picker (2026-10-05).- **`border-dashed` on anything under ~16px renders as a broken squiggle, not a dashed circle.** Browsers cannot fit whole dashes around an 8px `rounded-full`, so a tiny dashed dot reads as a glitch. Use a solid border in a lighter step (`border-gray-7`) for a "placeholder" dot and keep dashed borders for boxes.+- **An irreversible consequence in a confirm dialog goes in the dialog's `warning` slot, not in hand-styled description text.** `ConfirmationDeleteDialog` already has a `warning` prop that renders `Alert variant="warning"` with the triangle icon below the header (embed hostname, billing, connections, Authentication remove-domain), and `MethodConfirmDialog` takes the same `warning` prop. Keep `message`/`description` to one plain sentence. A custom red/amber `<span>` callout in the description looked foreign in review. Both dialogs also take `confirmText` for a type-to-confirm box (Authentication asks for the domain name to remove a verified domain, and `disable` to disable SSO) and `confirmDisabled` to block the action outright. Keep the typed text in `useTypeToConfirm({ open, text })` (next to `TypeToConfirm`): it resets whenever `open` changes, so Cancel, Esc, a parent closing the dialog and a successful confirm all start the next open empty, without wiring a reset into each close path.- **`ConfirmationDeleteDialog` renders `message` inside `DialogDescription`, a `<p>`.** A select or any other form control placed in the message is invalid nesting and becomes the dialog's `aria-describedby`. A delete flow that needs an input (the tier delete's "Move them to" select) builds its own `Dialog` and keeps only the confirm button's `adminControl` id.- `styles.css` points the `--shadow-*` theme keys that change per theme at a plain custom property(`--shadow-edge: var(--edge)`). Tailwind copies a `--shadow-*` value into the utility literally, so a dark override ofdiff --git a/brain/knowledge/engineering/ci-pr-review-hygiene.md b/brain/knowledge/engineering/ci-pr-review-hygiene.mdindex df4d514eb5c..36b3cbdb059 100644--- a/brain/knowledge/engineering/ci-pr-review-hygiene.md+++ b/brain/knowledge/engineering/ci-pr-review-hygiene.md@@ -90,6 +90,7 @@ Enforcement is the **`Codeowners review` repository ruleset** (active on the def- **A `beforeAll` that overrides the vitest timeout *downwards* is a slow-motion flake, and it fails in a way that blames your diff.** [`execute-flow-e2e.test.ts`](../../../packages/server/api/test/integration/ce/flows/flow-run/execute-flow-e2e.test.ts) passes `30_000` to `beforeAll` even though `packages/server/api/vitest.config.ts` sets `hookTimeout: 60000`, and spends 5s of that budget on a hardcoded `setTimeout`. Inside the remaining ~25s it boots a fresh app, runs the **whole migration chain**, starts queue consumers and a worker. That chain has grown 293 → 376 postgres migrations since the hook was written (`d2c42816013`, "feat: worker v2", #11608, 2026-03-15 — authored *after* the 60s default was already in place), so on a loaded runner it now times out. When it does, all 9 of its tests report **skipped**, not failed: the summary reads `1 failed | 84 passed` with no failing assertion anywhere, and `--bail 1` kills the rest of the CE task. Seen on [#15078](https://github.com/activepieces/activepieces/pull/15078), an MCP-OAuth-only PR that cannot reach that code. No single commit broke it, so there is nobody to blame and nothing to revert — the fix is to delete the override and poll for worker readiness instead of sleeping blind. When triaging a red CE task, check whether the failure is an assertion or a hook timeout **before** blaming the diff.- **Git hooks cannot run from a `git worktree`: `.husky/_/husky.sh` is an install artifact that only exists in the tree where `bun install` ran.** Every commit and push from a worktree dies on `.: cannot open .husky/_/husky.sh`, before the hook's own logic is reached. Don't reach for `--no-verify` — push the worktree's commit from the main checkout (`git push origin <local-branch>:<remote-branch>`; worktrees share the object store), so `pre-push` actually bootstraps and its "no direct pushes to `main`" guard runs. `SKIP_CHECK=1` is the repo's own sanctioned way to skip the lint/test prompt. Note `pre-push` special-cases `CLAUDE_PUSH=yes` into running the **full** lint + unit + API suite, so an agent that silently bypasses the hook is skipping a check the repo added deliberately for it — say so out loud when you do.- **Merging up a stacked chain, a parent's rename reaches a child's call sites as a clean auto-merge — only the typecheck finds it.** Git conflicts on lines both sides edited, so a symbol renamed on the parent merges silently into a child that merely *calls* the old name: `feat/barrier-service` renamed `barrierService.receive` → `receiveSignal`, and `feat/barrier-edges`' `resume-controller.ts` kept calling `.receive(...)` with no conflict marker. Worse, both sides can each be right and still merge wrong — the same commit renamed `findPreCompletedByFlowRunId` while the child had rewritten that function's *body* to fix a real bug, so the conflict exposed only the signature and taking either side whole silently dropped work. Two habits: typecheck **every** branch in the chain after its merge rather than trusting a conflict-free result, and before picking a side run `git log --oneline $(git merge-base HEAD MERGE_HEAD)..HEAD -- <file>` on both to read what each side was actually doing. Stacks here run deep (the waitpoints → process-in-batches chain was 17 PRs), so one missed rename propagates through every branch above it.+- **App links into the docs use Mintlify heading anchors, so renaming a docs heading silently breaks them.** Mintlify derives `#google` from `### Google`; the app's `adminDocs.url('admin-guide/guides/sso#google')` stops landing on the section if the heading changes, and nothing in CI checks it. Before renaming a heading, grep `packages/web/src` for its anchor.- **Docs videos belong on `cdn.activepieces.com/videos/docs/`, never in the repo — and `docs/resources/` is the legacy path that suggests otherwise.** Every `<video>` already in the wiki points at that CDN prefix, but `docs/resources/` still holds ~43 MB of in-repo gifs from before the convention, so the tree itself gives mixed signals and a contributor reasonably copies the wrong one. [#15399](https://github.com/activepieces/activepieces/pull/15399) added a fresh `docs/videos/` folder with 155 MB of `.mp4` against an 880 MB `.git`, including one byte-identical duplicate. Nothing in CI catches it: `PR size` exempts unmatched areas and counts lines, not bytes, and a binary blob contributes zero lines. Review the *file list* of a docs PR, not just its diff. Once such a branch is pushed the blobs are already on the remote — dropping them at the tip only keeps them out of `main` if the PR is **squash**-merged and the branch deleted, so a merge commit ships them permanently. Because the blobs stay reachable until the branch is deleted, nobody has to re-request the assets from whoever recorded them — pull them straight back out of history with `git archive <commit> docs/videos | tar -x --strip-components=2 -C <dir>`, picking the commit *before* the removal, which is also how you get them under the post-rename filenames the pages already reference.- **Mintlify-editor PRs arrive with `untitled-page*.mdx` at the docs root and `(1)`/`(2)`-suffixed media, wired into `docs.json` under those names.** The bot commits whatever the web editor autosaved, so pages land as `docs/untitled-page-5.mdx` rather than in the folder their nav group implies, and re-uploaded assets keep the browser's download-collision suffix (`data-flow-(1).mp4`, `01---insert-panel-(1.2x).mp4`). Mintlify's own link check passes — the names are internally consistent — so nothing flags it. Rename the files, fix the `docs.json` entries, then diff the *flattened nav tree* against `main` rather than reading the raw JSON diff: the editor also reindents, which buried a real change (the Enterprise Control `Security` group demoted to a child of `Guides`) inside 242 lines of whitespace churn on that PR.- **After rewriting a lower branch of a stack, the `--onto` upstream you need is that branch's *old* tip, and `<branch>@{1}` is where to read it.** Every commit above a rewritten branch has to be replayed with `git rebase --onto <new lower tip> <old lower tip> <upper>`, and the old tip stops being reachable by name the moment the rebase finishes. Guessing a SHA from an earlier terminal scroll either fails outright with `invalid upstream` or, worse, succeeds against the wrong base and replays a handful of commits instead of all of them, which surfaces as a pile of conflicts the branch has with itself. `git rev-parse <branch>@{1}` reads it from the reflog every time. Re-run the whole `--onto` chain top-down after any lower-branch amend, and confirm afterwards that `git log --format=%s main..<top>` has no duplicate subjects.diff --git a/brain/knowledge/engineering/server-module-anatomy.md b/brain/knowledge/engineering/server-module-anatomy.mdindex f338188a3b9..3693b300f92 100644--- a/brain/knowledge/engineering/server-module-anatomy.md+++ b/brain/knowledge/engineering/server-module-anatomy.md@@ -167,5 +167,6 @@ Verify with `npm run lint-dev` and `npm run test-api`.- **`security` goes under `config`, never under `schema`, and putting it in the wrong half fails silently.** Fastify reads the security config off `config`; a `security` key inside `schema` is just an unknown property on the schema object, so nothing validates it, nothing warns, and the route ships with no security config at all. It reads as correct at a glance because the two keys sit next to each other in the same literal and every route in the file has both. Caught on `GET /v1/ai-providers/tiers` before merge only because the diff was being read line by line. When you add a route, compare its literal against the one above it: `config: { security }` then `schema: { body, response }`, in that order.- **Inside `transaction(...)`, every read must go through `repo(entityManager)`, including reads inside helpers you call.** A bare `repo()` takes a second pool connection while the transaction still holds its own, so with `AP_POSTGRES_POOL_SIZE=1` it waits forever and any row lock you took stays held. Thread `entityManager` down as an optional param (as `aiProviderService.findRunKeyId` does for agent move). PGlite tests cannot catch this either: one in-process connection never runs out.- **Every query filters by `projectId` or `platformId`.** For connections with multi-project access, use `ArrayContains([projectId])` on the `projectIds` array column.+- **API test suites resolve `AP_DENO_PATH` from the `deno` devDependency (`vitest.setup.ts`), so a checkout installed before #16639 fails every suite with `Cannot find module 'deno/bin.cjs'` and "no tests".** It is a stale install, not your change: run `bun install` and rerun.- **A mutation test against a `packages/core/*` package proves nothing until you rebuild its dist.** The api package resolves `@activepieces/core-utils` and friends through `node_modules` to `dist/`, not through the tsconfig path to `src/`, so breaking the source and re-running an api test reports a pass while the test is still executing the old build. Measured: removing the connection-template unwrap from `core-utils/src` left `agent-tool-pinning.test.ts` fully green, and the same mutation failed it once `turbo run build --filter=@activepieces/core-utils` had run. Web tests do not share the trap — vitest aliases the core packages to `src` in `packages/web/vitest.config.ts` — so a web suite catching a core mutation while the api suite ignores it is the signature of a stale dist rather than of missing coverage. Same cause as the phantom "has no exported member" errors after merging a branch that adds a core export.- **`npx vitest` must be run from `packages/server/api`, never the repo root.** The config's `setupFiles` is what loads `.env.tests`, and from the root that setup never runs, so every suite dies in `beforeAll` with `SYSTEM_PROP_NOT_DEFINED: AP_POSTGRES_DATABASE` (thrown from `createPostgresDataSource`) and vitest reports the file as a failed *suite* with all its tests skipped. It reads exactly like a real breakage in whatever you just changed — the tell is that the stack bottoms out in `test-setup.ts`/`database-connection.ts` and never reaches your code, and that the run's stdout is missing the `Configuring vitest …/.env.tests` line a healthy run prints first. `npm run test-api` sets the cwd for you; a hand-written `npx vitest run test/…` does not.diff --git a/brain/knowledge/engineering/web-feature-anatomy.md b/brain/knowledge/engineering/web-feature-anatomy.mdindex 21e380a8b15..ea6094ddd33 100644--- a/brain/knowledge/engineering/web-feature-anatomy.md+++ b/brain/knowledge/engineering/web-feature-anatomy.md@@ -64,6 +64,8 @@ Every customer-facing surface must be checked on all five edition paths — CE,A default local dev instance runs `edition=ce` (check `/api/v1/flags`), and most of the platform-admin surface is unreachable there — Global Connections, Pieces, Templates, Billing, Usage, Embedding, SSO, Project Roles, API Keys, Secret Managers, Audit Logs and Event Streaming all render `LockedFeatureGuard` instead of their body, and the AI Center's Capabilities tab is not rendered at all. So a change to any of those cannot be seen locally without first flipping the `platform_plan` flags in the dev Postgres; Embedding needs more than that, since `useEmbedSubdomain` is gated on `edition === CLOUD` and so needs `AP_EDITION=cloud` and a restart. Plan for that before promising a screenshot of a gated page.+To switch a local backend's edition without editing `.env.dev`, prefix the command: `AP_EDITION=cloud npm run dev:backend`. Turbo passes `AP_EDITION` through (`globalPassThroughEnv`) and `bootstrap.ts` loads `.env.dev` without overriding variables already set, so the shell value wins; the startup log says `Activepieces Edition … edition: cloud`. Stop the old backend first, or the new one dies with `EADDRINUSE :3000` while the old edition keeps answering. If the old one runs in another terminal, find it with `lsof -nP -iTCP:3000 -sTCP:LISTEN` and stop its `tsx watch` parent as well as the node child, or the watcher starts it again; the new watcher that already failed retries after any change under `packages/server/api/src` (a `touch` of `bootstrap.ts` is enough).+Running one frontend per edition side by side (a vite port each against its own backend) is the quickestway to check all of them, but **every port serves the same working tree**, so checking out another branchchanges the code under all three at once. Comparing editions and comparing branches are therefore the same@@ -78,6 +80,10 @@ way back was to stash the handful of intended edits, `git checkout` the package,## Gotchas+- **To style one word inside a translated sentence, translate the whole sentence and split it around a sentinel; nothing in the app uses `Trans`.** Call `t('Type {text} to confirm', { text: SLOT })`, `split(SLOT)`, and render `before`, the styled word, `after`, so translators can still move the word (see `TypeToConfirm` in `components/custom`). Concatenating two separately translated halves fixes the word order to English.+- **Flags are cached with `staleTime: Infinity`, so a setting that feeds a flag must invalidate `flagsHooks.queryKey` after it changes.** Several flags are computed from platform settings (`THIRD_PARTY_AUTH_PROVIDERS_TO_SHOW_MAP` from the Google switch, `EMAIL_AUTH_ENABLED`, `THEME`), and refetching only the platform leaves the flag stale until reload. `ssoMutations.useUpdatePlatformSso` and the appearance section both do `queryClient.invalidateQueries({ queryKey: flagsHooks.queryKey })`.+- **Gate edition-specific UI on the edition you mean, not on "not the other one".** `flagsHooks.useFlag(ApFlagId.EDITION)` is `undefined` until flags load, so `edition !== ApEdition.CLOUD` is true for a moment on Cloud and self-hosted-only copy flashes there. Write `edition === ApEdition.ENTERPRISE` (or the edition you need) so the loading state falls into the safe branch.+- **Inside a `FormField`, a plain `<Label>` + input is not wired: wrap the input in `FormControl` and use `FormLabel`.** Without `FormControl` the label points at an id the input never gets (screen readers announce nothing, clicking the label does nothing, `getByLabelText` fails), and `FormMessage` errors get no `aria-invalid`/`aria-describedby`. Adding `htmlFor` + `id` by hand fixes the label but still leaves the error unlinked. Test it with `getByLabelText` and by checking `aria-describedby` contains the error's id.- **A web test that mocks `@tanstack/react-query` breaks at import once the component under test starts reading a `*-hooks.ts` module.** Those modules reference `QueryClient`, the partial mock doesn't export it, and the file fails to load: vitest prints `Test Files 1 failed` while `Tests N passed` still looks green, so read the `Test Files` line. Mock the hooks module the component imports (as `config-detail-save.test.tsx` does for the tier and provider hooks) instead of widening the react-query mock (#16116).- **The SPA is hardcoded to the host root, so `AP_FRONTEND_URL`'s path prefix does not reach the frontend at all.** `index.html` carries `<base href="/" />`, there is no vite `base`, and `API_BASE_URL` in `lib/api.ts` is `window.location.origin` — origin only, path dropped. An instance served at `example.com/activepieces` therefore loads its bundle, its assets and every `/api/v1/...` call from `example.com/...` at the root, and only works because the operator's proxy exposes those at root too. The server-side subpath support (`domainHelper.getPublicUrlFromRequest`, which prepends the configured base path to advertised URLs) covers what AP *tells* clients, not what the browser *fetches* — the two do not meet. So "we support subpath hosting" is only half true: it holds for what the server advertises and for anything the browser never has to fetch. A second host escapes the constraint only if it serves no SPA at all — which is exactly why MCP consent is redirected back to the frontend base rather than served on the MCP host (see [[mcp-server]]), leaving `AP_MCP_URL` free to carry a prefix.- **A disabled TanStack query keeps `isPending: true` forever, so a skeleton driven by it never resolves.** `enabled: false` means "has no data and is not fetching", and `isPending` only reports the first half — the spinner spins for the life of the page. Drive loading UI off `isLoading` (`isPending && isFetching`), which is false while disabled. This bites hardest on the plan-gated queries the repo requires an `enabled: platform.plan.<flag>` on: every one of them is permanently pending for a platform without the feature. Also decide what the surface shows in that state — a count rendered from `data ?? 0` reads as a real zero, when the honest answer is that the feature is not on the plan.diff --git a/docs/admin-guide/guides/sso.mdx b/docs/admin-guide/guides/sso.mdxindex a4f9927a26b..714c1cf650d 100644--- a/docs/admin-guide/guides/sso.mdx+++ b/docs/admin-guide/guides/sso.mdx@@ -15,69 +15,103 @@ Single Sign-On (SSO) allows your team to authenticate using your organization'sBefore configuring SSO, ensure you have:- **Admin access** to your Activepieces platform-- **Admin access** to your identity provider (Google, GitHub, Okta, or JumpCloud)-- The **redirect URL** from your Activepieces SSO configuration screen+- **Admin access** to your identity provider (Okta, Microsoft Entra ID, JumpCloud, or any SAML 2.0 provider)+- Access to your company domain's **DNS settings**, to verify the domain-## Accessing SSO Configuration+## The Authentication page-Navigate to **Platform Settings** → **SSO** in your Activepieces admin dashboard to access the SSO configuration screen.+Go to **Platform admin** → **Security** → **Authentication**. The page has three sections:-+- **Domain**: the company domain your people sign in with.+- **Sign-in methods**: single sign-on (SAML 2.0), Continue with Google, and email and password.+- **Allowed domains**: the email domains allowed to sign in with email and password.-## Enforcing SSO+-You can enforce SSO by specifying your organization's email domain. When SSO enforcement is enabled:+## Verify your domain-- Users with matching email domains must authenticate through the SSO provider-- Email/password login can be disabled for enhanced security-- All authentication is routed through your designated identity provider+Single sign-on needs a verified company domain (for example `acme.com`).-<Tip>- We recommend testing SSO with a small group of users before enforcing it organization-wide.-</Tip>+<Steps>+ <Step title="Enter the domain">+ Under **Domain**, click **Verify domain** and enter your company domain. It must be a public hostname containing a dot, and on Cloud each domain can be claimed by only one platform.+ </Step>+ <Step title="Add the TXT record">+ Copy the TXT record's **Name** and **Value** and add them at your DNS provider.+ </Step>+ <Step title="Verify DNS">+ Click **Verify DNS**. DNS changes can take a few minutes to show up, so try again if the record isn't found yet. Verify within 3 hours, or the domain is dropped and you start again with a new record.+ </Step>+</Steps>-## SSO Domain+While a domain is being verified it shows as **Verifying**. Its menu lets you **Continue verifying** or **Cancel verification**. Once verified, use **View DNS record** to see the record again.-The **SSO Domain** lets you map a public domain (e.g. `acme.com`) to your platform's SAML provider so users can discover the right IdP from the shared sign-in page.+You can also verify the domain from the first step of the SAML setup, described below.-You can set it in the SAML configuration dialog (**Platform Settings → SSO → SAML 2.0 → Enable**), in the **SSO Domain** field. Leave it empty to disable domain-based discovery.+<Warning>+ **Remove domain** also deletes your SAML connection, so single sign-on stops working. To confirm, type the domain name. You can't remove it while single sign-on is the only way to sign in: turn on email and password or Google sign-in first.+</Warning>-**How it works on Cloud**+## Set up SAML-On the cloud sign-in page, clicking **Sign in with SAML** opens a dialog asking the user for their organization's domain. When they enter `acme.com`, the platform whose SSO Domain matches is looked up and the user is redirected to that platform's identity provider.+Under **Sign-in methods**, click **Set up** next to **Single sign-on** (or **Manage** once it's connected). The setup has two steps:-**Constraints**+1. **SSO Domain**: verify your domain, or confirm the one you already verified.+2. **SAML 2.0**:+ - **Copy these into your identity provider**: the **Single sign-on URL** and the **Audience URI (SP Entity ID)**, which is `Activepieces`.+ - **Paste these from your identity provider**: the **IDP Metadata** (the metadata XML, or a metadata URL) and the **IDP Certificate**.-- Must be a valid public hostname containing a dot (e.g. `acme.com`, not `acme`).-- Each domain can be claimed by only one platform on Cloud.+The **SAML 2.0** step opens once the domain is verified. Once saved, the fields say **Saved**; paste new values only to replace them.++To turn single sign-on off, open **Manage**, click **Disable** under the SAML step and type `disable` to confirm. This deletes the SAML connection but keeps your verified domain, so you can connect again later. As with removing the domain, it's blocked while single sign-on is the only way to sign in.++**Signing in with SAML on Cloud**++On the cloud sign-in page, **Sign in with SAML** asks for the organization's domain. Entering `acme.com` sends the person to the identity provider of the platform that verified `acme.com`. The signed-in email must be at that domain.<Note>- On self-hosted Enterprise instances the SAML button on the sign-in page redirects directly to the configured identity provider, so the **SSO Domain** field is effectively ignored at login. You can still leave it empty.+ On self-hosted Enterprise instances the SAML button on the sign-in page redirects directly to the configured identity provider.</Note>+## Google and email and password++Turn **Continue with Google** and **Email and password** on or off under **Sign-in methods**. Each change asks you to confirm. You can't turn off the last sign-in method that works: turn on another one first. On a self-hosted server, Google only counts once it's set up.++On self-hosted instances, the Google button only appears once `AP_GOOGLE_CLIENT_ID` and `AP_GOOGLE_CLIENT_SECRET` are set. See [Google sign-in on self-hosted](#google).++## Allowed domains++**Allowed domains** limits sign-in to email addresses at the domains you list. Add your company domain too, or people at your company are refused.++- **Cloud**: the list applies to email and password sign-in.+- **Self-hosted Enterprise**: the list also applies to anyone creating an account, with any sign-in method.++Removing the last domain turns the restriction off.++<Tip>+ We recommend testing SSO with a small group of users before turning other sign-in methods off.+</Tip>+## Supported SSO ProvidersActivepieces supports multiple SSO providers to integrate with your existing identity management system.+On Cloud, Continue with Google works without setup. On self-hosted instances, create a Google OAuth client and pass it to Activepieces with environment variables.+<Steps><Step title="Access Google Cloud Console">Go to the [Google Cloud Console](https://console.cloud.google.com/) and select your project (or create a new one).</Step><Step title="Create OAuth2 Credentials">- Navigate to **APIs & Services** → **Credentials** → **Create Credentials** → **OAuth client ID**.-- Select **Web application** as the application type.+ Navigate to **APIs & Services** → **Credentials** → **Create Credentials** → **OAuth client ID**, and select **Web application**.</Step><Step title="Configure Redirect URI">- Copy the **Redirect URL** from the Activepieces SSO configuration screen and add it to the **Authorized redirect URIs** in Google Cloud Console.+ Add `<your Activepieces URL>/redirect` to the **Authorized redirect URIs**. If you set `AP_INTERNAL_URL`, use that URL instead.</Step>- <Step title="Copy Credentials to Activepieces">- Copy the **Client ID** and **Client Secret** from Google and paste them into the corresponding fields in Activepieces.- </Step>- <Step title="Save Configuration">- Click **Finish** to complete the setup.+ <Step title="Set the environment variables">+ Set `AP_GOOGLE_CLIENT_ID` and `AP_GOOGLE_CLIENT_SECRET` to the client's ID and secret, then restart Activepieces. See [environment variables](/install/reference/environment-variables).</Step></Steps>@@ -94,7 +128,7 @@ Activepieces supports multiple SSO providers to integrate with your existing ideEnter an **App name** (e.g., "Activepieces") and optionally upload a logo. Click **Next**.</Step><Step title="Configure SAML Settings">- - **Single sign-on URL**: Copy the SSO URL from the Activepieces configuration screen+ - **Single sign-on URL**: Copy the **Single sign-on URL** from step 2 of the SAML setup- **Audience URI (SP Entity ID)**: Enter `Activepieces`- **Name ID format**: Select `EmailAddress`</Step>@@ -115,8 +149,7 @@ Activepieces supports multiple SSO providers to integrate with your existing ide</Step><Step title="Configure Activepieces">- Paste the **IdP Metadata** XML into the corresponding field- - Copy the **X.509 Certificate** from Okta and paste it into the **Signing Key** field- - (Optional, Cloud) Set the **SSO Domain** to your organization's public domain (e.g. `acme.com`) so users can sign in by entering it on the cloud sign-in page. See [SSO Domain](#sso-domain) above.+ - Copy the **X.509 Certificate** from Okta and paste it into the **IDP Certificate** field</Step><Step title="Save Configuration">Click **Save** to complete the setup.@@ -138,7 +171,7 @@ Activepieces supports multiple SSO providers to integrate with your existing ideEdit **Basic SAML Configuration**:- **Identifier (Entity ID)**: `Activepieces`- - **Reply URL (Assertion Consumer Service URL)**: paste the SSO URL from the Activepieces configuration screen+ - **Reply URL (Assertion Consumer Service URL)**: paste the **Single sign-on URL** from step 2 of the SAML setup</Step><Step title="Configure User Attributes & Claims">Edit **Attributes & Claims** and add these additional claims (leave **Namespace** empty):@@ -155,7 +188,7 @@ Activepieces supports multiple SSO providers to integrate with your existing ideYou can paste this URL directly into the **IdP Metadata** field in Activepieces — Activepieces will fetch the metadata XML automatically. Alternatively, open the URL in a browser, save the XML, and paste its contents.</Step><Step title="Copy the Signing Certificate">- Download the **Certificate (Base64)** from the **SAML Certificates** section. Open the file and copy its contents (including the `-----BEGIN CERTIFICATE-----` / `-----END CERTIFICATE-----` markers) into the **Signing Key** field in Activepieces.+ Download the **Certificate (Base64)** from the **SAML Certificates** section. Open the file and copy its contents (including the `-----BEGIN CERTIFICATE-----` / `-----END CERTIFICATE-----` markers) into the **IDP Certificate** field in Activepieces.</Step><Step title="Assign Users">Go to **Users and groups** in the application and assign the users or groups that should be allowed to sign in.@@ -172,7 +205,7 @@ Activepieces supports multiple SSO providers to integrate with your existing ideGo to the [JumpCloud Admin Portal](https://console.jumpcloud.com/) → **SSO Applications** → **Add New Application** → **Custom SAML App**.</Step><Step title="Configure ACS URL">- Copy the **ACS URL** from the Activepieces configuration screen and paste it into the **ACS URLs** field in JumpCloud.+ Copy the **Single sign-on URL** from step 2 of the SAML setup and paste it into the **ACS URLs** field in JumpCloud.</Step>@@ -220,7 +253,7 @@ Activepieces supports multiple SSO providers to integrate with your existing ide-----END CERTIFICATE-----```- Paste this into the **Signing Key** field.+ Paste this into the **IDP Certificate** field.</Step><Step title="Assign Users to Application">In JumpCloud, assign the application to the appropriate users or user groups.@@ -238,7 +271,8 @@ Activepieces supports multiple SSO providers to integrate with your existing ide<Accordion title="Users cannot log in after SSO configuration">- Verify the redirect URL is correctly configured in your identity provider- Ensure users are assigned to the application in your identity provider- - Check that email domains match the SSO enforcement settings+ - Check that the user's email is at your verified domain+ - If you use allowed domains, check that the user's domain is on the list</Accordion><Accordion title="SAML authentication fails">diff --git a/docs/resources/screenshots/sso.png b/docs/resources/screenshots/sso.pngindex c675a6cfe94..770812792ab 100644Binary files a/docs/resources/screenshots/sso.png and b/docs/resources/screenshots/sso.png differdiff --git a/packages/core/utils/src/lib/form-errors.ts b/packages/core/utils/src/lib/form-errors.tsindex b2728aff806..90731758ffe 100644--- a/packages/core/utils/src/lib/form-errors.ts+++ b/packages/core/utils/src/lib/form-errors.ts@@ -29,6 +29,8 @@ export const formErrors = {reservedHeaderName: translationKey('reservedHeaderName'),duplicateHeaderName: translationKey('duplicateHeaderName'),invalidHeaderValue: translationKey('invalidHeaderValue'),+ invalidDomain: translationKey('invalidDomain'),+ duplicateDomain: translationKey('duplicateDomain'),} as constexport const SAFE_EXTERNAL_ID_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,128}$/diff --git a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.tsindex 60aee73ccaa..85830be43a7 100644--- a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts+++ b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts@@ -1,5 +1,5 @@import { resolveTxt } from 'dns/promises'-import { ActivepiecesError, apId, assertNotNullOrUndefined, ErrorCode, isNil, PlatformId, tryCatch } from '@activepieces/core-utils'+import { ActivepiecesError, apId, assertNotNullOrUndefined, ErrorCode, isNil, PlatformId, spreadIfDefined, tryCatch } from '@activepieces/core-utils'import { ApEdition, AuthenticationResponse, SAMLAuthnProviderConfig, SsoDomainVerification, SsoDomainVerificationRecordType, SsoDomainVerificationStatus, UserIdentityProvider } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { z } from 'zod'@@ -104,7 +104,14 @@ export const authnSsoSamlService = (log: FastifyBaseLogger) => {const current = await platformService(log).getOneOrThrow(platformId)const verification = computeNextVerification({ nextDomain: value, currentDomain: current.ssoDomain ?? null, currentVerification: current.ssoDomainVerification ?? null })- await platformService(log).update({ id: platformId, ssoDomain: value, ssoDomainVerification: verification })+ const removesVerifiedDomain = isNil(value) && current.ssoDomainVerification?.status === SsoDomainVerificationStatus.VERIFIED+ const removesSaml = removesVerifiedDomain && await platformService(log).hasSamlConfigured(platformId)+ await platformService(log).update({+ id: platformId,+ ssoDomain: value,+ ssoDomainVerification: verification,+ ...spreadIfDefined('federatedAuthProviders', removesSaml ? { saml: null } : undefined),+ })return { ssoDomain: value, ssoDomainVerification: verification }},async verifySsoDomain({ platformId }: VerifySsoDomainParams): Promise<SsoDomainState> {diff --git a/packages/server/api/src/app/platform/platform.service.ts b/packages/server/api/src/app/platform/platform.service.tsindex 7a006132740..af2a26211cb 100644--- a/packages/server/api/src/app/platform/platform.service.ts+++ b/packages/server/api/src/app/platform/platform.service.ts@@ -198,8 +198,8 @@ export const platformService = (log: FastifyBaseLogger) => ({),...spreadIfDefined('allowedAuthDomains', params.allowedAuthDomains),...spreadIfDefined('allowedEmbedOrigins', params.allowedEmbedOrigins),- ...spreadIfDefined('ssoDomain', params.ssoDomain),- ...spreadIfDefined('ssoDomainVerification', params.ssoDomainVerification),+ ...spreadIfNotUndefined('ssoDomain', params.ssoDomain),+ ...spreadIfNotUndefined('ssoDomainVerification', params.ssoDomainVerification),...spreadIfDefined('pinnedPieces', params.pinnedPieces),...spreadIfNotUndefined('pieceSelectorConfig', params.pieceSelectorConfig),}diff --git a/packages/server/api/test/integration/ee/sso-domain/sso-domain.test.ts b/packages/server/api/test/integration/ee/sso-domain/sso-domain.test.tsnew file mode 100644index 00000000000..21bdabb7c8c--- /dev/null+++ b/packages/server/api/test/integration/ee/sso-domain/sso-domain.test.ts@@ -0,0 +1,182 @@+import { SsoDomainVerification, SsoDomainVerificationRecordType, SsoDomainVerificationStatus } from '@activepieces/shared'+import { FastifyInstance } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { databaseConnection } from '../../../../src/app/database/database-connection'+import { createTestContext } from '../../../helpers/test-context'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance | null = null++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('SSO domain API', () => {+ describe('POST /v1/authn/saml/sso-domain', () => {+ it('removing the domain also clears its verification and turns SAML off', async () => {+ const ctx = await createTestContext(app!, {+ plan: { ssoEnabled: true },+ platform: {+ ssoDomain: 'remove-with-saml.example.com',+ ssoDomainVerification: verified('remove-with-saml.example.com'),+ federatedAuthProviders: { saml: SAML },+ },+ })++ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: null })+ const platform = await findPlatform(ctx.platform.id)++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(platform.ssoDomain).toBeNull()+ expect(platform.ssoDomainVerification).toBeNull()+ expect(platform.federatedAuthProviders.saml).toBeNull()+ })++ it('removing a domain without SAML clears only the domain', async () => {+ const ctx = await createTestContext(app!, {+ plan: { ssoEnabled: true },+ platform: {+ ssoDomain: 'remove-only.example.com',+ ssoDomainVerification: verified('remove-only.example.com'),+ federatedAuthProviders: { saml: null },+ },+ })++ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: null })+ const platform = await findPlatform(ctx.platform.id)++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(platform.ssoDomain).toBeNull()+ expect(platform.ssoDomainVerification).toBeNull()+ expect(platform.federatedAuthProviders.saml).toBeNull()+ })++ it('cancelling a pending domain keeps SAML, like an expired one', async () => {+ const ctx = await createTestContext(app!, {+ plan: { ssoEnabled: true },+ platform: {+ ssoDomain: 'cancel-pending.example.com',+ ssoDomainVerification: pending('cancel-pending.example.com'),+ federatedAuthProviders: { saml: SAML },+ },+ })++ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: null })+ const platform = await findPlatform(ctx.platform.id)++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(platform.ssoDomain).toBeNull()+ expect(platform.ssoDomainVerification).toBeNull()+ expect(platform.federatedAuthProviders.saml).toEqual(SAML)+ })++ it('adding a removed domain back needs a new DNS record', async () => {+ const ctx = await createTestContext(app!, {+ plan: { ssoEnabled: true },+ platform: {+ ssoDomain: 're-add.example.com',+ ssoDomainVerification: verified('re-add.example.com'),+ },+ })++ await ctx.post(SSO_DOMAIN, { ssoDomain: null })+ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: 're-add.example.com' })+ const platform = await findPlatform(ctx.platform.id)++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(platform.ssoDomainVerification?.status).toBe(SsoDomainVerificationStatus.PENDING_VERIFICATION)+ expect(platform.ssoDomainVerification?.record.value).not.toBe('activepieces-verify=test-token')+ })++ it('saving the same domain keeps its verification and SAML', async () => {+ const ctx = await createTestContext(app!, {+ plan: { ssoEnabled: true },+ platform: {+ ssoDomain: 'same-domain.example.com',+ ssoDomainVerification: verified('same-domain.example.com'),+ federatedAuthProviders: { saml: SAML },+ },+ })++ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: 'Same-Domain.example.com ' })+ const platform = await findPlatform(ctx.platform.id)++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(platform.ssoDomain).toBe('same-domain.example.com')+ expect(platform.ssoDomainVerification?.status).toBe(SsoDomainVerificationStatus.VERIFIED)+ expect(platform.federatedAuthProviders.saml).not.toBeNull()+ })++ it('setting a new domain starts a pending verification', async () => {+ const ctx = await createTestContext(app!, { plan: { ssoEnabled: true } })++ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: 'fresh-domain.example.com' })+ const platform = await findPlatform(ctx.platform.id)++ expect(response.statusCode).toBe(StatusCodes.OK)+ expect(platform.ssoDomain).toBe('fresh-domain.example.com')+ expect(platform.ssoDomainVerification?.status).toBe(SsoDomainVerificationStatus.PENDING_VERIFICATION)+ })++ it('refuses a domain another platform already uses', async () => {+ await createTestContext(app!, {+ plan: { ssoEnabled: true },+ platform: {+ ssoDomain: 'taken.example.com',+ ssoDomainVerification: verified('taken.example.com'),+ },+ })+ const ctx = await createTestContext(app!, { plan: { ssoEnabled: true } })++ const response = await ctx.post(SSO_DOMAIN, { ssoDomain: 'taken.example.com' })+ const platform = await findPlatform(ctx.platform.id)++ expect(response.statusCode).toBe(StatusCodes.CONFLICT)+ expect(platform.ssoDomain).toBeNull()+ })+ })+})++async function findPlatform(id: string): Promise<PlatformSsoRow> {+ return databaseConnection().getRepository<PlatformSsoRow>('platform').findOneOrFail({+ where: { id },+ select: { id: true, ssoDomain: true, ssoDomainVerification: true, federatedAuthProviders: true },+ })+}++function verified(domain: string): SsoDomainVerification {+ return {+ status: SsoDomainVerificationStatus.VERIFIED,+ record: {+ type: SsoDomainVerificationRecordType.TXT,+ name: `_activepieces-verify.${domain}`,+ value: 'activepieces-verify=test-token',+ },+ createdAt: new Date().toISOString(),+ }+}++function pending(domain: string): SsoDomainVerification {+ return {+ ...verified(domain),+ status: SsoDomainVerificationStatus.PENDING_VERIFICATION,+ }+}++const SSO_DOMAIN = '/v1/authn/saml/sso-domain'++const SAML = {+ idpMetadata: '<EntityDescriptor />',+ idpCertificate: 'test-certificate',+}++type PlatformSsoRow = {+ id: string+ ssoDomain: string | null+ ssoDomainVerification: { status: string, record: { value: string } } | null+ federatedAuthProviders: { saml: unknown }+}diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 714205feff6..7cb5612aa71 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -1778,20 +1778,13 @@"Single sign-on settings updated": "Single sign-on settings updated","Configure SAML 2.0 SSO": "Configure SAML 2.0 SSO","SSO Domain": "SSO Domain",- "SSO domain saved": "SSO domain saved","Domain verified": "Domain verified","TXT record not found yet — DNS can take a few minutes.": "TXT record not found yet — DNS can take a few minutes.","Couldn't verify domain": "Couldn't verify domain",- "When a user enters this domain on the sign-in page, they will be redirected to your SAML identity provider.": "When a user enters this domain on the sign-in page, they will be redirected to your SAML identity provider.",- "Update SSO domain?": "Update SSO domain?",- "Users won't be able to sign in via SSO until you verify the new domain.": "Users won't be able to sign in via SSO until you verify the new domain.",- "\n**Setup Instructions**:\nPlease check the following documentation: [SAML SSO](https://activepieces.com/docs/security/sso)\n\n**Single sign-on URL**:\n```text\n{samlAcs}\n```\n**Audience URI (SP Entity ID)**:\n```text\nActivepieces\n```\n": "\n**Setup Instructions**:\nPlease check the following documentation: [SAML SSO](https://activepieces.com/docs/security/sso)\n\n**Single sign-on URL**:\n```text\n{samlAcs}\n```\n**Audience URI (SP Entity ID)**:\n```text\nActivepieces\n```\n","IDP Metadata": "IDP Metadata","Paste the metadata XML contents or the metadata URL provided by your identity provider.": "Paste the metadata XML contents or the metadata URL provided by your identity provider.","IDP Certificate": "IDP Certificate",- "Add this TXT record at your DNS provider. We'll detect it once it propagates — this usually takes a few minutes.": "Add this TXT record at your DNS provider. We'll detect it once it propagates — this usually takes a few minutes.","Verify DNS": "Verify DNS",- "DNS verified — domain is ready": "DNS verified — domain is ready","Failed to save. Please check the API key and try again.": "Failed to save. Please check the API key and try again.","Image model": "Image model","Choose a model": "Choose a model",@@ -3284,5 +3277,92 @@"1 min ago": "1 min ago","{count} mins ago": "{count} mins ago","1 hour ago": "1 hour ago",- "{count} hours ago": "{count} hours ago"+ "{count} hours ago": "{count} hours ago",+ "Actions for {domain}": "Actions for {domain}",+ "Add domain": "Add domain",+ "Add this TXT record at your DNS provider.": "Add this TXT record at your DNS provider.",+ "Authentication": "Authentication",+ "Choose how people at your verified domain sign in.": "Choose how people at your verified domain sign in.",+ "Verify your domain and choose how people sign in.": "Verify your domain and choose how people sign in.",+ "Connect a SAML 2.0 identity provider.": "Connect a SAML 2.0 identity provider.",+ "Couldn't add domain": "Couldn't add domain",+ "Couldn't remove domain": "Couldn't remove domain",+ "DNS record for {domain}": "DNS record for {domain}",+ "Domain actions": "Domain actions",+ "Email and password": "Email and password",+ "Manage": "Manage",+ "No domain verified": "No domain verified",+ "OAuth 2.0": "OAuth 2.0",+ "Remove domain": "Remove domain",+ "Remove {domain}?": "Remove {domain}?",+ "Set up": "Set up",+ "Sign-in methods": "Sign-in methods",+ "View DNS record": "View DNS record",+ "invalidDomain": "Enter a domain like acme.com",+ "duplicateDomain": "This domain is already on the list",+ "Allowed domains": "Allowed domains",+ "No allowed domains": "No allowed domains",+ "Allowed domain added": "Allowed domain added",+ "You can't do this while single sign-on is the only way to sign in. Turn on email or Google sign-in first.": "You can't do this while single sign-on is the only way to sign in. Turn on email or Google sign-in first.",+ "To set up single sign-on later, you'll need to verify the domain again with a new DNS record.": "To set up single sign-on later, you'll need to verify the domain again with a new DNS record.",+ "Verify your domain before saving. You can already copy the values above into your identity provider.": "Verify your domain before saving. You can already copy the values above into your identity provider.",+ "Single sign-on URL": "Single sign-on URL",+ "Audience URI (SP Entity ID)": "Audience URI (SP Entity ID)",+ "Verify your company's email domain to set up single sign-on.": "Verify your company's email domain to set up single sign-on.",+ "Copy these into your identity provider": "Copy these into your identity provider",+ "Paste these from your identity provider": "Paste these from your identity provider",+ "Turn on Google sign-in?": "Turn on Google sign-in?",+ "Turn off Google sign-in?": "Turn off Google sign-in?",+ "Google sign-in will be on for this platform.": "Google sign-in will be on for this platform.",+ "Google sign-in will be off for this platform.": "Google sign-in will be off for this platform.",+ "Turn off": "Turn off",+ "Turn on email sign-in?": "Turn on email sign-in?",+ "Turn off email sign-in?": "Turn off email sign-in?",+ "People can sign in with email and password again.": "People can sign in with email and password again.",+ "Disable single sign-on?": "Disable single sign-on?",+ "Disable single sign-on": "Disable single sign-on",+ "Deletes the SAML connection. Your verified domain stays, so you can connect again later.": "Deletes the SAML connection. Your verified domain stays, so you can connect again later.",+ "Saved. Paste new metadata to replace it.": "Saved. Paste new metadata to replace it.",+ "Saved. Paste a new certificate to replace it.": "Saved. Paste a new certificate to replace it.",+ "Remove {domain} and delete your SAML connection?": "Remove {domain} and delete your SAML connection?",+ "Remove domain and disable SAML": "Remove domain and disable SAML",+ "This disables single sign-on and deletes its SAML connection.": "This disables single sign-on and deletes its SAML connection.",+ "Verify later": "Verify later",+ "Verify a domain": "Verify a domain",+ "Prove your company owns its email domain with a DNS record.": "Prove your company owns its email domain with a DNS record.",+ "Verify the domain your people sign in with.": "Verify the domain your people sign in with.",+ "Verify domain": "Verify domain",+ "Verification in progress. Add the TXT record within 3 hours or it's dropped.": "Verification in progress. Add the TXT record within 3 hours or it's dropped.",+ "Verifying": "Verifying",+ "Continue verifying": "Continue verifying",+ "Cancel verifying {domain}?": "Cancel verifying {domain}?",+ "The domain and its DNS record are discarded. You can start again anytime.": "The domain and its DNS record are discarded. You can start again anytime.",+ "Cancel verification": "Cancel verification",+ "Verify {domain}": "Verify {domain}",+ "Add this TXT record at your DNS provider, then verify. Verify within 3 hours or the domain is dropped.": "Add this TXT record at your DNS provider, then verify. Verify within 3 hours or the domain is dropped.",+ "Your domain is verified. Next, connect your identity provider.": "Your domain is verified. Next, connect your identity provider.",+ "Limit who can join, and who can sign in with email and password, to the domains you add.": "Limit who can join, and who can sign in with email and password, to the domains you add.",+ "Anyone can join or sign in with email and password until you add a domain.": "Anyone can join or sign in with email and password until you add a domain.",+ "With no domains left, anyone can join or sign in with email and password.": "With no domains left, anyone can join or sign in with email and password.",+ "Once a domain is on this list, only people at listed domains can join or sign in with email and password. Add your company domain too.": "Once a domain is on this list, only people at listed domains can join or sign in with email and password. Add your company domain too.",+ "People at this domain can join and sign in with email and password.": "People at this domain can join and sign in with email and password.",+ "Add your company domain too, or people at your company can't join or sign in with email and password.": "Add your company domain too, or people at your company can't join or sign in with email and password.",+ "People at {domain} can no longer join or sign in with email and password.": "People at {domain} can no longer join or sign in with email and password.",+ "Limit email and password sign-in to the domains you add.": "Limit email and password sign-in to the domains you add.",+ "Anyone can sign in with email and password until you add a domain.": "Anyone can sign in with email and password until you add a domain.",+ "With no domains left, anyone can sign in with email and password.": "With no domains left, anyone can sign in with email and password.",+ "People at {domain} can no longer sign in with email and password.": "People at {domain} can no longer sign in with email and password.",+ "Add your company domain too, or people at your company can't sign in with email and password.": "Add your company domain too, or people at your company can't sign in with email and password.",+ "Once a domain is on this list, only people at listed domains can sign in with email and password. Add your company domain too.": "Once a domain is on this list, only people at listed domains can sign in with email and password. Add your company domain too.",+ "People at this domain can sign in with email and password.": "People at this domain can sign in with email and password.",+ "Type {text} to confirm": "Type {text} to confirm",+ "People who use single sign-on will have to sign in another way.": "People who use single sign-on will have to sign in another way.",+ "Not set up": "Not set up",+ "Needs a Google OAuth client on this server.": "Needs a Google OAuth client on this server.",+ "On a self-hosted server it also needs a Google OAuth client.": "On a self-hosted server it also needs a Google OAuth client.",+ "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.": "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.",+ "People can no longer sign in with email and password.": "People can no longer sign in with email and password.",+ "Couldn't disable single sign-on": "Couldn't disable single sign-on",+ "Couldn't save single sign-on settings": "Couldn't save single sign-on settings",+ "To change the connection, paste both values again.": "To change the connection, paste both values again."}diff --git a/packages/web/src/app/components/admin/admin-docs.ts b/packages/web/src/app/components/admin/admin-docs.tsnew file mode 100644index 00000000000..1416a345b2a--- /dev/null+++ b/packages/web/src/app/components/admin/admin-docs.ts@@ -0,0 +1,5 @@+const DOCS_BASE_URL = 'https://www.activepieces.com/docs';++export const adminDocs = {+ url: (path: string): string => `${DOCS_BASE_URL}/${path}`,+};diff --git a/packages/web/src/app/components/admin/admin-page-resources.ts b/packages/web/src/app/components/admin/admin-page-resources.tsindex 17dadbeb8e2..cb9bdc25ce9 100644--- a/packages/web/src/app/components/admin/admin-page-resources.ts+++ b/packages/web/src/app/components/admin/admin-page-resources.ts@@ -2,6 +2,7 @@ import { t } from 'i18next';import { AdminControl } from '@/lib/admin-control';+import { adminDocs } from './admin-docs';import { AdminResource } from './admin-resources';const docs = ({@@ -15,12 +16,10 @@ const docs = ({}): AdminResource => ({kind: 'doc',label,- url: `${DOCS_BASE_URL}/${path}`,+ url: adminDocs.url(path),control,});-const DOCS_BASE_URL = 'https://www.activepieces.com/docs';-export const adminPageResources = {projects: [docs({diff --git a/packages/web/src/app/components/admin/index.ts b/packages/web/src/app/components/admin/index.tsindex 90e6de0e55d..3883d780b1c 100644--- a/packages/web/src/app/components/admin/index.ts+++ b/packages/web/src/app/components/admin/index.ts@@ -1,6 +1,7 @@export { AdminPage, AdminPageHeader, AdminSection } from './admin-page';export { AdminResources, AdminVideoDialog } from './admin-resources';export type { AdminResource } from './admin-resources';+export { adminDocs } from './admin-docs';export { adminPageResources } from './admin-page-resources';export { adminSurface } from './admin-surface';export { adminLayout } from './admin-layout';diff --git a/packages/web/src/app/components/global-search/static-pages.ts b/packages/web/src/app/components/global-search/static-pages.tsindex 0f9e8dcac67..54163e1d04f 100644--- a/packages/web/src/app/components/global-search/static-pages.ts+++ b/packages/web/src/app/components/global-search/static-pages.ts@@ -157,7 +157,7 @@ export const STATIC_PAGES: StaticPage[] = [},{id: 'page-platform-sso',- label: 'Platform Admin — Single Sign On',+ label: 'Platform Admin — Authentication',href: '/platform/sso',icon: LogInIcon,requiresPlatformAdmin: true,diff --git a/packages/web/src/app/components/sidebar/platform/index.tsx b/packages/web/src/app/components/sidebar/platform/index.tsxindex a0a2f0b2986..032ef9d30a2 100644--- a/packages/web/src/app/components/sidebar/platform/index.tsx+++ b/packages/web/src/app/components/sidebar/platform/index.tsx@@ -122,7 +122,7 @@ export function PlatformNav() {items: [{to: '/platform/sso',- label: t('Single Sign On'),+ label: t('Authentication'),icon: LogInIcon,locked: !platform.plan.ssoEnabled,tier: PLATFORM_FEATURES.sso.tier,diff --git a/packages/web/src/app/routes/platform-routes.tsx b/packages/web/src/app/routes/platform-routes.tsxindex 2fd4ed0c26c..3c37dee5d29 100644--- a/packages/web/src/app/routes/platform-routes.tsx+++ b/packages/web/src/app/routes/platform-routes.tsx@@ -63,6 +63,11 @@ const EmbedPage = React.lazy(() =>const SSOPage = React.lazy(() =>import('./platform/security/sso').then((m) => ({ default: m.SSOPage })),);+const SamlSetupPage = React.lazy(() =>+ import('./platform/security/sso/saml-setup-page').then((m) => ({+ default: m.SamlSetupPage,+ })),+);const AIProvidersPage = React.lazy(() => import('./platform/setup/ai'));const PlatformMcpPage = React.lazy(() => import('./platform/setup/mcp'));const GeneralPage = React.lazy(() =>@@ -420,7 +425,7 @@ export const platformRoutes = [path: '/platform/sso',element: (<PlatformLayout>- <PageTitle title="SSO">+ <PageTitle title="Authentication"><PlanFeatureSample feature="sso"><SuspenseWrapper><SSOPage />@@ -430,6 +435,20 @@ export const platformRoutes = [</PlatformLayout>),},+ {+ path: '/platform/sso/saml',+ element: (+ <PlatformLayout>+ <PageTitle title="Single sign-on">+ <PlanFeatureGuard feature="sso">+ <SuspenseWrapper>+ <SamlSetupPage />+ </SuspenseWrapper>+ </PlanFeatureGuard>+ </PageTitle>+ </PlatformLayout>+ ),+ },{path: '/platform/users/roles',element: (diff --git a/packages/web/src/app/routes/platform/security/sso/add-allowed-domain-dialog.tsx b/packages/web/src/app/routes/platform/security/sso/add-allowed-domain-dialog.tsxnew file mode 100644index 00000000000..c5152a8f337--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/add-allowed-domain-dialog.tsx@@ -0,0 +1,178 @@+import { formErrors, PlatformWithoutSensitiveData } from '@activepieces/shared';+import { zodResolver } from '@hookform/resolvers/zod';+import { useMutation } from '@tanstack/react-query';+import { t } from 'i18next';+import { ReactNode, useState } from 'react';+import { useForm } from 'react-hook-form';+import { toast } from 'sonner';+import { z } from 'zod';++import { platformApi } from '@/api/platforms-api';+import { adminLayout } from '@/app/components/admin';+import { domainSchema } from '@/app/routes/platform/security/sso/domain-schema';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@/components/ui/dialog';+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@/components/ui/form';+import { Input } from '@/components/ui/input';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { api } from '@/lib/api';++export const AddAllowedDomainDialog = ({+ platform,+ refetch,+ restrictsJoining,+ children,+}: AddAllowedDomainDialogProps) => {+ const [open, setOpen] = useState(false);+ const existing = platform.allowedAuthDomains;+ const form = useForm<AllowedDomainFormValues>({+ defaultValues: { domain: '' },+ resolver: zodResolver(allowedDomainSchema(existing)),+ mode: 'onChange',+ });++ const { mutate, isPending } = useMutation({+ mutationFn: async ({ domain }: AllowedDomainFormValues) => {+ await platformApi.update(+ {+ allowedAuthDomains: [...existing, domain],+ enforceAllowedAuthDomains: true,+ },+ platform.id,+ );+ await refetch();+ },+ onSuccess: () => {+ toast.success(t('Allowed domain added'));+ setOpen(false);+ },+ onError: (error) => {+ form.setError('root.serverError', {+ type: 'manual',+ message: api.extractServerErrorMessage(error, t("Couldn't add domain")),+ });+ },+ });++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ form.reset({ domain: '' });+ setOpen(nextOpen);+ }}+ >+ <DialogTrigger asChild>{children}</DialogTrigger>+ <DialogContent+ className={adminLayout.dialog.md}+ onInteractOutside={(event) => event.preventDefault()}+ >+ <DialogHeader>+ <DialogTitle>{t('Add domain')}</DialogTitle>+ <DialogDescription>+ {describeAddingDomain({+ isFirstDomain: existing.length === 0,+ restrictsJoining,+ })}+ </DialogDescription>+ </DialogHeader>+ <Form {...form}>+ <form+ className="flex flex-col gap-4"+ onSubmit={form.handleSubmit((values) => mutate(values))}+ >+ <FormField+ control={form.control}+ name="domain"+ render={({ field }) => (+ <FormItem className="grid space-y-2">+ <FormLabel>{t('Domain')}</FormLabel>+ <FormControl>+ <Input {...field} placeholder="contractors.io" autoFocus />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {form.formState.errors.root?.serverError && (+ <FormMessage>+ {form.formState.errors.root.serverError.message}+ </FormMessage>+ )}+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ onClick={() => setOpen(false)}+ >+ {t('Cancel')}+ </Button>+ <Button+ {...adminControl(AdminControl.SSO_ALLOWED_DOMAINS_SUBMIT)}+ type="submit"+ loading={isPending}+ disabled={!form.formState.isValid}+ >+ {t('Add domain')}+ </Button>+ </DialogFooter>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+};++function describeAddingDomain({+ isFirstDomain,+ restrictsJoining,+}: {+ isFirstDomain: boolean;+ restrictsJoining: boolean;+}): string {+ if (isFirstDomain) {+ return restrictsJoining+ ? t(+ 'Once a domain is on this list, only people at listed domains can join or sign in with email and password. Add your company domain too.',+ )+ : t(+ 'Once a domain is on this list, only people at listed domains can sign in with email and password. Add your company domain too.',+ );+ }+ return restrictsJoining+ ? t('People at this domain can join and sign in with email and password.')+ : t('People at this domain can sign in with email and password.');+}++function allowedDomainSchema(existing: string[]) {+ return z.object({+ domain: domainSchema.refine(+ (value) => !existing.includes(value),+ formErrors.duplicateDomain,+ ),+ });+}++type AllowedDomainFormValues = { domain: string };++type AddAllowedDomainDialogProps = {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+ restrictsJoining: boolean;+ children: ReactNode;+};diff --git a/packages/web/src/app/routes/platform/security/sso/allowed-domain.tsx b/packages/web/src/app/routes/platform/security/sso/allowed-domain.tsxdeleted file mode 100644index 8ed0729e66f..00000000000--- a/packages/web/src/app/routes/platform/security/sso/allowed-domain.tsx+++ /dev/null@@ -1,182 +0,0 @@-import {- PlatformWithoutSensitiveData,- UpdatePlatformRequestBody,-} from '@activepieces/shared';-import { zodResolver } from '@hookform/resolvers/zod';-import { useMutation } from '@tanstack/react-query';-import { t } from 'i18next';-import { Plus, X } from 'lucide-react';-import { useState } from 'react';-import { useForm, useFieldArray } from 'react-hook-form';-import { toast } from 'sonner';-import { z } from 'zod';--import { platformApi } from '@/api/platforms-api';-import { adminLayout } from '@/app/components/admin';-import { Button } from '@/components/ui/button';-import {- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from '@/components/ui/dialog';-import { Form, FormField, FormItem, FormMessage } from '@/components/ui/form';-import { Input } from '@/components/ui/input';-import { AdminControl, adminControl } from '@/lib/admin-control';--type AllowedDomainDialogProps = {- platform: PlatformWithoutSensitiveData;- refetch: () => Promise<void>;-};--const AllowedDomainsFormValues = z.object({- allowedAuthDomains: z.array(- z.object({- domain: z.string().min(1),- }),- ),-});-type AllowedDomainsFormValues = z.infer<typeof AllowedDomainsFormValues>;--export const AllowedDomainDialog = ({- platform,- refetch,-}: AllowedDomainDialogProps) => {- const [open, setOpen] = useState(false);- const form = useForm<AllowedDomainsFormValues>({- defaultValues: {- allowedAuthDomains: (platform?.allowedAuthDomains ?? []).map(- (domain) => ({- domain,- }),- ),- },- resolver: zodResolver(AllowedDomainsFormValues),- });-- const { fields, append, remove } = useFieldArray({- control: form.control,- name: 'allowedAuthDomains',- });-- const { mutate, isPending } = useMutation({- mutationFn: async (request: UpdatePlatformRequestBody) => {- await platformApi.update(request, platform.id);- await refetch();- },- onSuccess: () => {- toast.success(t('Allowed domains updated'), {- duration: 3000,- });- setOpen(false);- },- });-- return (- <Dialog- open={open}- onOpenChange={(open) => {- if (!open) {- form.reset();- }- setOpen(open);- }}- >- <DialogTrigger asChild>- <Button- {...adminControl(AdminControl.SSO_ALLOWED_DOMAINS_OPEN)}- size={'sm'}- variant={'basic'}- onClick={() => setOpen(true)}- >- {platform.allowedAuthDomains.length > 0 ? t('Update') : t('Enable')}- </Button>- </DialogTrigger>- <DialogContent className={adminLayout.dialog.md}>- <DialogHeader>- <DialogTitle>{t('Configure Allowed Domains')}</DialogTitle>- </DialogHeader>- <Form {...form}>- <form- className="flex flex-col gap-4"- onSubmit={form.handleSubmit((data) => {- mutate({- allowedAuthDomains: data.allowedAuthDomains.map(- (d) => d.domain,- ),- enforceAllowedAuthDomains:- data.allowedAuthDomains.length === 0 ? false : true,- });- })}- >- <p className="text-sm text-gray-11">- {t(- 'Enter the allowed domains for the users to authenticate with. An empty list will allow all domains.',- )}- </p>- {fields.map((field, index) => (- <FormField- key={field.id}- name={`allowedAuthDomains.${index}.domain`}- render={({ field }) => (- <FormItem className="space-y-0">- <div className="flex gap-2">- <Input- {...field}- id={`allowedAuthDomains.${index}`}- placeholder={t('example.com')}- />- <Button- type="button"- onClick={() => remove(index)}- variant="outline"- size="icon"- aria-label={t('Remove')}- >- <X />- </Button>- </div>- </FormItem>- )}- />- ))}- <Button- type="button"- onClick={() => append({ domain: '' })}- variant="outline"- size="sm"- >- <Plus />- {t('Add Domain')}- </Button>- {form?.formState?.errors?.root?.serverError && (- <FormMessage>- {form.formState.errors.root.serverError.message}- </FormMessage>- )}-- <DialogFooter>- <Button- variant="outline"- onClick={() => setOpen(false)}- type="button"- >- {t('Cancel')}- </Button>- <Button- {...adminControl(AdminControl.SSO_ALLOWED_DOMAINS_SUBMIT)}- loading={isPending}- disabled={!form.formState.isValid}- type="submit"- >- {t('Save')}- </Button>- </DialogFooter>- </form>- </Form>- </DialogContent>- </Dialog>- );-};diff --git a/packages/web/src/app/routes/platform/security/sso/allowed-domains-section.tsx b/packages/web/src/app/routes/platform/security/sso/allowed-domains-section.tsxnew file mode 100644index 00000000000..fcb2ae61e38--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/allowed-domains-section.tsx@@ -0,0 +1,221 @@+import { PlatformWithoutSensitiveData } from '@activepieces/shared';+import { t } from 'i18next';+import { Globe, MoreHorizontal, Plus, Trash } from 'lucide-react';+import { toast } from 'sonner';++import { platformApi } from '@/api/platforms-api';+import {+ AdminSection,+ SettingsPanel,+ SettingsRow,+ adminLayout,+} from '@/app/components/admin';+import { AddAllowedDomainDialog } from '@/app/routes/platform/security/sso/add-allowed-domain-dialog';+import { useSignInMethods } from '@/app/routes/platform/security/sso/use-sign-in-methods';+import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';+import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { api } from '@/lib/api';++export const AllowedDomainsSection = ({+ platform,+ refetch,+}: AllowedDomainsSectionProps) => {+ const domains = platform.allowedAuthDomains;+ const restrictsJoining = useSignInMethods(platform).selfHosted;+ const listsCompanyDomain =+ !!platform.ssoDomain && domains.includes(platform.ssoDomain);++ return (+ <AdminSection+ title={t('Allowed domains')}+ description={+ restrictsJoining+ ? t(+ 'Limit who can join, and who can sign in with email and password, to the domains you add.',+ )+ : t('Limit email and password sign-in to the domains you add.')+ }+ action={+ domains.length > 0 && (+ <AddAllowedDomainDialog+ platform={platform}+ refetch={refetch}+ restrictsJoining={restrictsJoining}+ >+ <Button+ {...adminControl(AdminControl.SSO_ALLOWED_DOMAINS_OPEN)}+ size="sm"+ variant="outline"+ >+ <Plus />+ {t('Add domain')}+ </Button>+ </AddAllowedDomainDialog>+ )+ }+ >+ {domains.length === 0 ? (+ <SettingsPanel flush>+ <SettingsRow+ icon={<Globe />}+ title={t('No allowed domains')}+ description={+ restrictsJoining+ ? t(+ 'Anyone can join or sign in with email and password until you add a domain.',+ )+ : t(+ 'Anyone can sign in with email and password until you add a domain.',+ )+ }+ >+ <AddAllowedDomainDialog+ platform={platform}+ refetch={refetch}+ restrictsJoining={restrictsJoining}+ >+ <Button+ {...adminControl(AdminControl.SSO_ALLOWED_DOMAINS_OPEN)}+ size="sm"+ variant="outline"+ >+ {t('Add domain')}+ </Button>+ </AddAllowedDomainDialog>+ </SettingsRow>+ </SettingsPanel>+ ) : (+ <>+ <SettingsPanel flush>+ {domains.map((domain) => (+ <SettingsRow key={domain} icon={<Globe />} title={domain}>+ <DropdownMenu modal={true}>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t('Actions for {domain}', { domain })}+ >+ <MoreHorizontal className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <ConfirmationDeleteDialog+ title={t('Remove {domain}?', { domain })}+ message={describeRemovingDomain({+ domain,+ isLastDomain: domains.length === 1,+ restrictsJoining,+ })}+ entityName={domain}+ buttonText={t('Remove domain')}+ controlId={AdminControl.SSO_ALLOWED_DOMAIN_REMOVE_CONFIRM}+ contentClassName={adminLayout.dialog.md}+ keepOpenOnOutsideClick+ showToast+ mutationFn={async () => {+ await removeAllowedDomain({+ platformId: platform.id,+ domains,+ domain,+ });+ await refetch();+ }}+ onError={(error) =>+ toast.error(+ api.extractServerErrorMessage(+ error,+ t("Couldn't remove domain"),+ ),+ )+ }+ >+ <DropdownMenuItem+ {...adminControl(+ AdminControl.SSO_ALLOWED_DOMAIN_REMOVE_OPEN,+ )}+ variant="destructive"+ onSelect={(e) => e.preventDefault()}+ >+ <Trash className="size-4" />+ {t('Remove domain')}+ </DropdownMenuItem>+ </ConfirmationDeleteDialog>+ </DropdownMenuContent>+ </DropdownMenu>+ </SettingsRow>+ ))}+ </SettingsPanel>+ {!listsCompanyDomain && (+ <p className="text-xs text-gray-11">+ {restrictsJoining+ ? t(+ "Add your company domain too, or people at your company can't join or sign in with email and password.",+ )+ : t(+ "Add your company domain too, or people at your company can't sign in with email and password.",+ )}+ </p>+ )}+ </>+ )}+ </AdminSection>+ );+};++function describeRemovingDomain({+ domain,+ isLastDomain,+ restrictsJoining,+}: {+ domain: string;+ isLastDomain: boolean;+ restrictsJoining: boolean;+}): string {+ if (isLastDomain) {+ return restrictsJoining+ ? t(+ 'With no domains left, anyone can join or sign in with email and password.',+ )+ : t('With no domains left, anyone can sign in with email and password.');+ }+ return restrictsJoining+ ? t(+ 'People at {domain} can no longer join or sign in with email and password.',+ { domain },+ )+ : t('People at {domain} can no longer sign in with email and password.', {+ domain,+ });+}++async function removeAllowedDomain({+ platformId,+ domains,+ domain,+}: {+ platformId: string;+ domains: string[];+ domain: string;+}): Promise<void> {+ const remaining = domains.filter((existing) => existing !== domain);+ await platformApi.update(+ {+ allowedAuthDomains: remaining,+ enforceAllowedAuthDomains: remaining.length > 0,+ },+ platformId,+ );+}++type AllowedDomainsSectionProps = {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+};diff --git a/packages/web/src/app/routes/platform/security/sso/domain-dns-record.tsx b/packages/web/src/app/routes/platform/security/sso/domain-dns-record.tsxnew file mode 100644index 00000000000..b0ac0ad17d6--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/domain-dns-record.tsx@@ -0,0 +1,31 @@+import { SsoDomainVerificationRecord } from '@activepieces/shared';+import { t } from 'i18next';++import { CopyToClipboardInput } from '@/components/custom/clipboard/copy-to-clipboard';+import { Label } from '@/components/ui/label';+import { AdminControl } from '@/lib/admin-control';++export const DomainDnsRecord = ({+ record,+}: {+ record: SsoDomainVerificationRecord;+}) => (+ <div className="flex flex-col gap-4">+ <div className="flex min-w-0 flex-col gap-2">+ <Label>{t('Name')}</Label>+ <CopyToClipboardInput+ textToCopy={record.name}+ useInput={true}+ controlId={AdminControl.SSO_SAML_DNS_NAME_COPY}+ />+ </div>+ <div className="flex min-w-0 flex-col gap-2">+ <Label>{t('Value')}</Label>+ <CopyToClipboardInput+ textToCopy={record.value}+ useInput={true}+ controlId={AdminControl.SSO_SAML_DNS_VALUE_COPY}+ />+ </div>+ </div>+);diff --git a/packages/web/src/app/routes/platform/security/sso/domain-schema.ts b/packages/web/src/app/routes/platform/security/sso/domain-schema.tsnew file mode 100644index 00000000000..f16e14b787d--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/domain-schema.ts@@ -0,0 +1,12 @@+import { formErrors } from '@activepieces/shared';+import { z } from 'zod';++export const domainSchema = z+ .string()+ .transform((value) => value.trim().toLowerCase())+ .pipe(+ z+ .hostname(formErrors.invalidDomain)+ .max(253, formErrors.invalidDomain)+ .refine((value) => value.includes('.'), formErrors.invalidDomain),+ );diff --git a/packages/web/src/app/routes/platform/security/sso/domain-status-icon.tsx b/packages/web/src/app/routes/platform/security/sso/domain-status-icon.tsxnew file mode 100644index 00000000000..660921a82aa--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/domain-status-icon.tsx@@ -0,0 +1,23 @@+import { Clock, ShieldCheck } from 'lucide-react';++import { cn } from '@/lib/utils';++export const DomainStatusIcon = ({ status }: { status: DomainStatus }) => (+ <div+ data-status={status}+ className={cn(+ 'flex size-9 items-center justify-center rounded-lg [&_svg]:size-4',+ STATUS_STYLES[status],+ )}+ >+ {status === 'pending' ? <Clock /> : <ShieldCheck />}+ </div>+);++const STATUS_STYLES: Record<DomainStatus, string> = {+ none: 'border bg-panel text-gray-9 opacity-60',+ pending: 'bg-warning-3 text-warning-11',+ verified: 'bg-success-3 text-success-11',+};++export type DomainStatus = 'none' | 'pending' | 'verified';diff --git a/packages/web/src/app/routes/platform/security/sso/domain-verification.tsx b/packages/web/src/app/routes/platform/security/sso/domain-verification.tsxnew file mode 100644index 00000000000..350a2de2a56--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/domain-verification.tsx@@ -0,0 +1,226 @@+import {+ PlatformWithoutSensitiveData,+ SsoDomainVerificationRecord,+ SsoDomainVerificationStatus,+} from '@activepieces/shared';+import { zodResolver } from '@hookform/resolvers/zod';+import { useMutation } from '@tanstack/react-query';+import { t } from 'i18next';+import { ReactNode } from 'react';+import { useForm } from 'react-hook-form';+import { z } from 'zod';++import { SettingsPanel, SettingsRow, StatusDot } from '@/app/components/admin';+import { DomainDnsRecord } from '@/app/routes/platform/security/sso/domain-dns-record';+import { domainSchema } from '@/app/routes/platform/security/sso/domain-schema';+import { DomainStatusIcon } from '@/app/routes/platform/security/sso/domain-status-icon';+import { FormActions } from '@/app/routes/platform/security/sso/form-actions';+import { Button } from '@/components/ui/button';+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@/components/ui/form';+import { Input } from '@/components/ui/input';+import { samlSsoApi, ssoMutations } from '@/features/platform-admin';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { api } from '@/lib/api';++export const DomainVerification = ({+ platform,+ refetch,+ onVerified,+ secondaryAction,+ nextAction,+ showIntro = true,+}: DomainVerificationProps) => {+ const verification = platform.ssoDomainVerification;+ if (!platform.ssoDomain || !verification) {+ return (+ <DomainEntry+ refetch={refetch}+ secondaryAction={secondaryAction}+ nextAction={nextAction}+ />+ );+ }+ if (verification.status === SsoDomainVerificationStatus.VERIFIED) {+ return (+ <VerifiedDomain domain={platform.ssoDomain} nextAction={nextAction} />+ );+ }+ return (+ <PendingDomain+ domain={platform.ssoDomain}+ record={verification.record}+ refetch={refetch}+ onVerified={onVerified}+ secondaryAction={secondaryAction}+ nextAction={nextAction}+ showIntro={showIntro}+ />+ );+};++const DomainEntry = ({+ refetch,+ secondaryAction,+ nextAction,+}: {+ refetch: () => Promise<void>;+ secondaryAction?: ReactNode;+ nextAction?: ReactNode;+}) => {+ const form = useForm<DomainFormValues>({+ defaultValues: { domain: '' },+ resolver: zodResolver(DomainFormValues),+ mode: 'onChange',+ });++ const { mutate: saveDomain, isPending } = useMutation({+ mutationFn: async ({ domain }: DomainFormValues) => {+ await samlSsoApi.updateSsoDomain(domain);+ await refetch();+ },+ onError: (error) => {+ form.setError('root.serverError', {+ type: 'manual',+ message: api.extractServerErrorMessage(+ error,+ t("Couldn't save domain"),+ ),+ });+ },+ });++ return (+ <Form {...form}>+ <form+ className="flex flex-col gap-4"+ onSubmit={form.handleSubmit((values) => saveDomain(values))}+ >+ <FormField+ control={form.control}+ name="domain"+ render={({ field }) => (+ <FormItem className="grid space-y-2">+ <FormLabel>{t('Domain')}</FormLabel>+ <FormControl>+ <Input {...field} placeholder="acme.com" autoFocus />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ {form.formState.errors.root?.serverError && (+ <FormMessage>+ {form.formState.errors.root.serverError.message}+ </FormMessage>+ )}+ <FormActions trailing={nextAction}>+ {secondaryAction}+ <Button+ {...adminControl(AdminControl.SSO_SAML_DOMAIN_SUBMIT)}+ type="submit"+ loading={isPending}+ disabled={!form.formState.isValid}+ >+ {t('Continue')}+ </Button>+ </FormActions>+ </form>+ </Form>+ );+};++const PendingDomain = ({+ domain,+ record,+ refetch,+ onVerified,+ secondaryAction,+ nextAction,+ showIntro,+}: {+ domain: string;+ record: SsoDomainVerificationRecord;+ refetch: () => Promise<void>;+ onVerified?: () => void;+ secondaryAction?: ReactNode;+ nextAction?: ReactNode;+ showIntro: boolean;+}) => {+ const { mutate: verifyDomain, isPending } = ssoMutations.useVerifySsoDomain({+ refetch,+ onVerified,+ });++ return (+ <div className="flex flex-col gap-4">+ {showIntro && (+ <div className="flex flex-col gap-1">+ <h3 className="text-sm font-semibold text-gray-12">+ {t('Verify {domain}', { domain })}+ </h3>+ <p className="text-sm text-gray-11">+ {t(+ 'Add this TXT record at your DNS provider, then verify. Verify within 3 hours or the domain is dropped.',+ )}+ </p>+ </div>+ )}+ <DomainDnsRecord record={record} />+ <FormActions trailing={nextAction}>+ {secondaryAction}+ <Button+ {...adminControl(AdminControl.SSO_DOMAIN_DNS_RUN)}+ type="button"+ loading={isPending}+ onClick={() => verifyDomain()}+ >+ {t('Verify DNS')}+ </Button>+ </FormActions>+ </div>+ );+};++const VerifiedDomain = ({+ domain,+ nextAction,+}: {+ domain: string;+ nextAction?: ReactNode;+}) => (+ <div className="flex flex-col gap-3">+ <p className="text-sm text-gray-11">+ {t('Your domain is verified. Next, connect your identity provider.')}+ </p>+ <SettingsPanel flush>+ <SettingsRow+ media={<DomainStatusIcon status="verified" />}+ title={domain}+ >+ <StatusDot tone="success" className="text-xs text-gray-11">+ {t('Verified')}+ </StatusDot>+ </SettingsRow>+ </SettingsPanel>+ {nextAction && <FormActions trailing={nextAction} />}+ </div>+);++const DomainFormValues = z.object({ domain: domainSchema });+type DomainFormValues = { domain: string };++type DomainVerificationProps = {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+ onVerified?: () => void;+ secondaryAction?: ReactNode;+ nextAction?: ReactNode;+ showIntro?: boolean;+};diff --git a/packages/web/src/app/routes/platform/security/sso/domains-section.tsx b/packages/web/src/app/routes/platform/security/sso/domains-section.tsxnew file mode 100644index 00000000000..2c9f09ceb7b--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/domains-section.tsx@@ -0,0 +1,251 @@+import {+ PlatformWithoutSensitiveData,+ SsoDomainVerification,+ SsoDomainVerificationStatus,+} from '@activepieces/shared';+import { t } from 'i18next';+import { FileText, MoreHorizontal, ShieldCheck, Trash } from 'lucide-react';+import { useState } from 'react';+import { toast } from 'sonner';++import {+ AdminSection,+ SettingsPanel,+ SettingsRow,+ StatusDot,+ adminLayout,+} from '@/app/components/admin';+import { DomainDnsRecord } from '@/app/routes/platform/security/sso/domain-dns-record';+import { DomainStatusIcon } from '@/app/routes/platform/security/sso/domain-status-icon';+import { SamlDeletionWarning } from '@/app/routes/platform/security/sso/saml-deletion-warning';+import { useSignInMethods } from '@/app/routes/platform/security/sso/use-sign-in-methods';+import { VerifyDomainDialog } from '@/app/routes/platform/security/sso/verify-domain-dialog';+import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { samlSsoApi } from '@/features/platform-admin';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { api } from '@/lib/api';++export const DomainsSection = ({ platform, refetch }: DomainsSectionProps) => {+ const samlConnected = !!platform.federatedAuthProviders?.saml;+ const [verifyOpen, setVerifyOpen] = useState(false);++ return (+ <AdminSection+ title={t('Domain')}+ description={t(+ "Verify your company's email domain to set up single sign-on.",+ )}+ >+ {platform.ssoDomain && platform.ssoDomainVerification ? (+ <SettingsPanel flush>+ <DomainRow+ platform={platform}+ refetch={refetch}+ domain={platform.ssoDomain}+ verification={platform.ssoDomainVerification}+ samlConnected={samlConnected}+ onContinueVerifying={() => setVerifyOpen(true)}+ />+ </SettingsPanel>+ ) : (+ <SettingsPanel flush>+ <SettingsRow+ media={<DomainStatusIcon status="none" />}+ title={t('No domain verified')}+ description={t('Verify the domain your people sign in with.')}+ >+ <Button+ {...adminControl(AdminControl.SSO_DOMAIN_ADD_OPEN)}+ size="sm"+ onClick={() => setVerifyOpen(true)}+ >+ {t('Verify domain')}+ </Button>+ </SettingsRow>+ </SettingsPanel>+ )}+ <VerifyDomainDialog+ platform={platform}+ refetch={refetch}+ open={verifyOpen}+ onOpenChange={setVerifyOpen}+ />+ </AdminSection>+ );+};++const DomainRow = ({+ platform,+ refetch,+ domain,+ verification,+ samlConnected,+ onContinueVerifying,+}: DomainRowProps) => {+ const samlIsOnlyMethod =+ useSignInMethods(platform).isOnlyWorkingMethod('saml');+ const [dnsRecordOpen, setDnsRecordOpen] = useState(false);+ const verified = verification.status === SsoDomainVerificationStatus.VERIFIED;++ return (+ <SettingsRow+ media={<DomainStatusIcon status={verified ? 'verified' : 'pending'} />}+ title={domain}+ description={+ verified+ ? undefined+ : t(+ "Verification in progress. Add the TXT record within 3 hours or it's dropped.",+ )+ }+ >+ <StatusDot+ tone={verified ? 'success' : 'warning'}+ className="text-xs text-gray-11"+ >+ {verified ? t('Verified') : t('Verifying')}+ </StatusDot>+ <DropdownMenu modal={true}>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t('Domain actions')}+ >+ <MoreHorizontal className="size-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {verified ? (+ <DropdownMenuItem+ {...adminControl(AdminControl.SSO_DOMAIN_DNS_RECORD_OPEN)}+ onSelect={() => setDnsRecordOpen(true)}+ >+ <FileText className="size-4" />+ {t('View DNS record')}+ </DropdownMenuItem>+ ) : (+ <DropdownMenuItem+ {...adminControl(AdminControl.SSO_DOMAIN_VERIFY_OPEN)}+ onSelect={onContinueVerifying}+ >+ <ShieldCheck className="size-4" />+ {t('Continue verifying')}+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <ConfirmationDeleteDialog+ title={+ !verified+ ? t('Cancel verifying {domain}?', { domain })+ : samlConnected+ ? t('Remove {domain} and delete your SAML connection?', {+ domain,+ })+ : t('Remove {domain}?', { domain })+ }+ message={+ verified+ ? samlConnected+ ? t(+ 'People who use single sign-on will have to sign in another way.',+ )+ : t(+ "To set up single sign-on later, you'll need to verify the domain again with a new DNS record.",+ )+ : t(+ 'The domain and its DNS record are discarded. You can start again anytime.',+ )+ }+ warning={+ verified && samlConnected ? (+ <SamlDeletionWarning blocked={samlIsOnlyMethod} />+ ) : undefined+ }+ confirmText={verified ? domain : undefined}+ confirmDisabled={verified && samlConnected && samlIsOnlyMethod}+ entityName={domain}+ buttonText={+ !verified+ ? t('Cancel verification')+ : samlConnected+ ? t('Remove domain and disable SAML')+ : t('Remove domain')+ }+ controlId={AdminControl.SSO_DOMAIN_REMOVE_CONFIRM}+ contentClassName={adminLayout.dialog.md}+ keepOpenOnOutsideClick+ showToast={verified}+ mutationFn={async () => {+ await samlSsoApi.updateSsoDomain(null);+ await refetch();+ }}+ onError={(error) => {+ refetch().catch(() => undefined);+ toast.error(+ api.extractServerErrorMessage(+ error,+ t("Couldn't remove domain"),+ ),+ );+ }}+ >+ <DropdownMenuItem+ {...adminControl(AdminControl.SSO_DOMAIN_REMOVE_OPEN)}+ variant="destructive"+ onSelect={(e) => e.preventDefault()}+ >+ <Trash className="size-4" />+ {verified ? t('Remove domain') : t('Cancel verification')}+ </DropdownMenuItem>+ </ConfirmationDeleteDialog>+ </DropdownMenuContent>+ </DropdownMenu>+ <Dialog open={dnsRecordOpen} onOpenChange={setDnsRecordOpen}>+ <DialogContent+ className={adminLayout.dialog.md}+ onInteractOutside={(event) => event.preventDefault()}+ >+ <DialogHeader>+ <DialogTitle>+ {t('DNS record for {domain}', { domain })}+ </DialogTitle>+ <DialogDescription>+ {t('Add this TXT record at your DNS provider.')}+ </DialogDescription>+ </DialogHeader>+ <DomainDnsRecord record={verification.record} />+ </DialogContent>+ </Dialog>+ </SettingsRow>+ );+};++type DomainsSectionProps = {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+};++type DomainRowProps = {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+ domain: string;+ verification: SsoDomainVerification;+ samlConnected: boolean;+ onContinueVerifying: () => void;+};diff --git a/packages/web/src/app/routes/platform/security/sso/form-actions.tsx b/packages/web/src/app/routes/platform/security/sso/form-actions.tsxnew file mode 100644index 00000000000..cbc8c29991a--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/form-actions.tsx@@ -0,0 +1,19 @@+import { ReactNode } from 'react';++export const FormActions = ({+ children,+ trailing,+}: {+ children?: ReactNode;+ trailing?: ReactNode;+}) =>+ trailing ? (+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between">+ <div className="flex flex-col-reverse gap-2 sm:flex-row">{children}</div>+ {trailing}+ </div>+ ) : (+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">+ {children}+ </div>+ );diff --git a/packages/web/src/app/routes/platform/security/sso/index.tsx b/packages/web/src/app/routes/platform/security/sso/index.tsxindex c4a41d0f78d..6ed3734f3ea 100644--- a/packages/web/src/app/routes/platform/security/sso/index.tsx+++ b/packages/web/src/app/routes/platform/security/sso/index.tsx@@ -1,152 +1,28 @@-import { SsoDomainVerificationStatus } from '@activepieces/shared';import { t } from 'i18next';-import { LockIcon, MailIcon, Earth } from 'lucide-react';-import { toast } from 'sonner';import {AdminPage,AdminPageHeader,- SettingsPanel,- SettingsRow,- StatusDot,adminPageResources,} from '@/app/components/admin';-import { AllowedDomainDialog } from '@/app/routes/platform/security/sso/allowed-domain';-import { ConfigureSamlDialog } from '@/app/routes/platform/security/sso/saml-dialog';-import { Badge } from '@/components/ui/badge';-import { Switch } from '@/components/ui/switch';-import { ssoMutations } from '@/features/platform-admin';+import { AllowedDomainsSection } from '@/app/routes/platform/security/sso/allowed-domains-section';+import { DomainsSection } from '@/app/routes/platform/security/sso/domains-section';+import { SignInMethodsSection } from '@/app/routes/platform/security/sso/sign-in-methods-section';import { platformHooks } from '@/hooks/platform-hooks';-import { AdminControl, adminControl } from '@/lib/admin-control';--import GoogleIcon from '../../../../../assets/img/custom/auth/google-icon.svg';const SSOPage = () => {const { platform, refetch } = platformHooks.useCurrentPlatform();- const samlConnected = !!platform.federatedAuthProviders?.saml;- const ssoDomainVerified =- platform.ssoDomainVerification?.status ===- SsoDomainVerificationStatus.VERIFIED;- const emailAuthEnabled = platform.emailAuthEnabled;- const allowedDomains = platform.allowedAuthDomains ?? [];-- const { mutate: toggleEmailAuthentication, isPending: isEmailAuthPending } =- ssoMutations.useUpdatePlatformSso({- platformId: platform.id,- refetch,- onSuccess: () => {- toast.success(t('Email authentication updated'), { duration: 3000 });- },- });-- const { mutate: toggleGoogleAuth, isPending: isGoogleAuthPending } =- ssoMutations.useUpdatePlatformSso({- platformId: platform.id,- refetch,- onSuccess: () => {- toast.success(t('Google authentication updated'), { duration: 3000 });- },- });-return (<AdminPage width="content"><AdminPageHeader- title={t('Single Sign On')}- description={t('Manage single sign on providers')}+ title={t('Authentication')}+ description={t('Verify your domain and choose how people sign in.')}resources={adminPageResources.sso}/>- <SettingsPanel flush>- <SettingsRow- icon={<Earth />}- title={t('Allowed Domains')}- description={- <div className="flex flex-col gap-2">- {t('Restrict authentication to specific email domains.')}- {allowedDomains.length > 0 && (- <div className="flex flex-wrap gap-2">- {allowedDomains.map((domain, index) => (- <Badge key={`${domain}-${index}`} variant="outline">- {domain}- </Badge>- ))}- </div>- )}- </div>- }- >- <AllowedDomainDialog platform={platform} refetch={refetch} />- </SettingsRow>-- <SettingsRow- icon={<img className="size-5" src={GoogleIcon} alt="icon" />}- title="Google"- description={t(- "Allow logins through google's single sign-on functionality.",- )}- >- <Switch- {...adminControl(AdminControl.SSO_GOOGLE_TOGGLE)}- aria-label="Google"- checked={platform.googleAuthEnabled}- onCheckedChange={() =>- toggleGoogleAuth({- googleAuthEnabled: !platform.googleAuthEnabled,- })- }- disabled={isGoogleAuthPending}- />- </SettingsRow>-- <SettingsRow- icon={<LockIcon />}- title={t('SAML 2.0')}- description={- <div className="flex flex-col gap-2">- {t(- "Allow logins through saml 2.0's single sign-on functionality.",- )}- {platform.ssoDomain && (- <div className="flex flex-wrap items-center gap-2">- <Badge variant="outline">{platform.ssoDomain}</Badge>- <StatusDot- tone={ssoDomainVerified ? 'success' : 'warning'}- className="text-xs text-gray-11"- >- {ssoDomainVerified- ? t('Verified')- : t('Pending verification')}- </StatusDot>- </div>- )}- </div>- }- >- <ConfigureSamlDialog- platform={platform}- refetch={refetch}- connected={samlConnected}- />- </SettingsRow>-- <SettingsRow- icon={<MailIcon />}- title={t('Allowed Email Login')}- description={t('Allow logins through email and password.')}- >- <Switch- {...adminControl(AdminControl.SSO_EMAIL_LOGIN_TOGGLE)}- aria-label={t('Allowed Email Login')}- checked={emailAuthEnabled}- onCheckedChange={() =>- toggleEmailAuthentication({- emailAuthEnabled: !platform.emailAuthEnabled,- })- }- disabled={isEmailAuthPending}- />- </SettingsRow>- </SettingsPanel>+ <DomainsSection platform={platform} refetch={refetch} />+ <SignInMethodsSection platform={platform} refetch={refetch} />+ <AllowedDomainsSection platform={platform} refetch={refetch} /></AdminPage>);};diff --git a/packages/web/src/app/routes/platform/security/sso/method-confirm-dialog.tsx b/packages/web/src/app/routes/platform/security/sso/method-confirm-dialog.tsxnew file mode 100644index 00000000000..869d73d9f81--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/method-confirm-dialog.tsx@@ -0,0 +1,99 @@+import { t } from 'i18next';+import { TriangleAlert } from 'lucide-react';+import { ReactNode } from 'react';++import { adminLayout } from '@/app/components/admin';+import {+ TypeToConfirm,+ useTypeToConfirm,+} from '@/components/custom/type-to-confirm';+import { Alert, AlertDescription } from '@/components/ui/alert';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { AdminControl, adminControl } from '@/lib/admin-control';++export const MethodConfirmDialog = ({+ open,+ onOpenChange,+ title,+ description,+ confirmLabel,+ destructive,+ isPending,+ controlId,+ warning,+ confirmDisabled = false,+ confirmText,+ onConfirm,+}: MethodConfirmDialogProps) => {+ const typed = useTypeToConfirm({ open, text: confirmText });+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ className={adminLayout.dialog.md}+ onInteractOutside={(event) => event.preventDefault()}+ >+ <DialogHeader>+ <DialogTitle>{title}</DialogTitle>+ <DialogDescription>{description}</DialogDescription>+ </DialogHeader>+ {warning && (+ <Alert variant="warning">+ <TriangleAlert className="h-4 w-4" />+ <AlertDescription>{warning}</AlertDescription>+ </Alert>+ )}+ {confirmText && !confirmDisabled && (+ <TypeToConfirm+ id="method-confirm-text"+ text={confirmText}+ value={typed.value}+ onChange={typed.setValue}+ />+ )}+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ disabled={isPending}+ onClick={() => onOpenChange(false)}+ >+ {t('Cancel')}+ </Button>+ <Button+ {...adminControl(controlId)}+ type="button"+ variant={destructive ? 'destructive' : 'default'}+ loading={isPending}+ disabled={confirmDisabled || !typed.confirmed}+ onClick={onConfirm}+ >+ {confirmLabel}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};++type MethodConfirmDialogProps = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ title: string;+ description: ReactNode;+ confirmLabel: string;+ destructive: boolean;+ isPending: boolean;+ controlId: AdminControl;+ warning?: ReactNode;+ confirmDisabled?: boolean;+ confirmText?: string;+ onConfirm: () => void;+};diff --git a/packages/web/src/app/routes/platform/security/sso/saml-deletion-warning.tsx b/packages/web/src/app/routes/platform/security/sso/saml-deletion-warning.tsxnew file mode 100644index 00000000000..5da8f7bf797--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/saml-deletion-warning.tsx@@ -0,0 +1,16 @@+import { t } from 'i18next';++export const SamlDeletionWarning = ({ blocked }: { blocked: boolean }) => (+ <span className="flex flex-col gap-1">+ <span>+ {t('This disables single sign-on and deletes its SAML connection.')}+ </span>+ {blocked && (+ <span>+ {t(+ "You can't do this while single sign-on is the only way to sign in. Turn on email or Google sign-in first.",+ )}+ </span>+ )}+ </span>+);diff --git a/packages/web/src/app/routes/platform/security/sso/saml-dialog.tsx b/packages/web/src/app/routes/platform/security/sso/saml-dialog.tsxdeleted file mode 100644index b363e0343b9..00000000000--- a/packages/web/src/app/routes/platform/security/sso/saml-dialog.tsx+++ /dev/null@@ -1,627 +0,0 @@-import {- ApFlagId,- PlatformWithoutSensitiveData,- SsoDomainVerification,- SsoDomainVerificationRecord,- SsoDomainVerificationStatus,- UpdatePlatformRequestBody,-} from '@activepieces/shared';-import { zodResolver } from '@hookform/resolvers/zod';-import { useMutation } from '@tanstack/react-query';-import { t } from 'i18next';-import { CheckCircle, Loader2, TriangleAlert } from 'lucide-react';-import { useState } from 'react';-import { useForm } from 'react-hook-form';-import { toast } from 'sonner';-import { z } from 'zod';--import { platformApi } from '@/api/platforms-api';-import { adminLayout } from '@/app/components/admin';-import { CopyToClipboardInput } from '@/components/custom/clipboard/copy-to-clipboard';-import { ApMarkdown } from '@/components/custom/markdown';-import { Alert, AlertDescription } from '@/components/ui/alert';-import { Button } from '@/components/ui/button';-import {- Dialog,- DialogContent,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from '@/components/ui/dialog';-import {- Form,- FormDescription,- FormField,- FormItem,- FormMessage,-} from '@/components/ui/form';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { Textarea } from '@/components/ui/textarea';-import { samlSsoApi } from '@/features/platform-admin';-import { flagsHooks } from '@/hooks/flags-hooks';-import { AdminControl, adminControl } from '@/lib/admin-control';-import { api } from '@/lib/api';-import { cn } from '@/lib/utils';--export const ConfigureSamlDialog = ({- platform,- connected,- refetch,-}: ConfigureSamlDialogProps) => {- const [open, setOpen] = useState(false);-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <Button- {...adminControl(AdminControl.SSO_SAML_OPEN)}- size="sm"- variant="basic"- onClick={() => setOpen(true)}- >- {connected ? t('Edit') : t('Enable')}- </Button>- </DialogTrigger>- <DialogContent className={adminLayout.dialog.md}>- {open && (- <SamlWizard- key={open ? 'open' : 'closed'}- platform={platform}- connected={connected}- refetch={refetch}- onClose={() => setOpen(false)}- />- )}- </DialogContent>- </Dialog>- );-};--const SamlWizard = ({- platform,- connected,- refetch,- onClose,-}: {- platform: PlatformWithoutSensitiveData;- connected: boolean;- refetch: () => Promise<void>;- onClose: () => void;-}) => {- const domainVerified =- platform.ssoDomainVerification?.status ===- SsoDomainVerificationStatus.VERIFIED;- const [step, setStep] = useState<WizardStep>(- connected || !domainVerified ? 'domain' : 'saml',- );-- const { mutate: disableSaml, isPending: isDisabling } = useMutation({- mutationFn: async () => {- await platformApi.update(- { federatedAuthProviders: { saml: null } },- platform.id,- );- await refetch();- },- onSuccess: () => {- toast.success(t('Single sign-on settings updated'), { duration: 3000 });- onClose();- },- });-- const disableAction = connected- ? { onDisable: () => disableSaml(), isDisabling }- : null;-- return (- <>- <DialogHeader>- <DialogTitle>{t('Configure SAML 2.0 SSO')}</DialogTitle>- </DialogHeader>- <StepIndicator step={step} />- <div className={cn(step !== 'domain' && 'hidden')}>- <DomainStep- platform={platform}- refetch={refetch}- onVerified={() => setStep('saml')}- onNext={() => setStep('saml')}- canProceed={domainVerified}- disableAction={disableAction}- />- </div>- <div className={cn(step !== 'saml' && 'hidden')}>- <SamlStep- platform={platform}- refetch={refetch}- onBack={() => setStep('domain')}- onClose={onClose}- disableAction={disableAction}- />- </div>- </>- );-};--const StepIndicator = ({ step }: { step: WizardStep }) => (- <div className="flex items-center gap-3 text-xs text-gray-11">- <div- className={cn(- 'flex items-center gap-2',- step === 'domain' && 'text-gray-12 font-medium',- )}- >- <span- className={cn(- 'flex size-5 items-center justify-center rounded-full border text-xs',- step === 'domain'- ? 'border-accent-9 bg-accent-9 text-on-accent'- : 'border-gray-7',- )}- >- 1- </span>- {t('SSO Domain')}- </div>- <div className="h-px w-6 bg-gray-6" />- <div- className={cn(- 'flex items-center gap-2',- step === 'saml' && 'text-gray-12 font-medium',- )}- >- <span- className={cn(- 'flex size-5 items-center justify-center rounded-full border text-xs',- step === 'saml'- ? 'border-accent-9 bg-accent-9 text-on-accent'- : 'border-gray-7',- )}- >- 2- </span>- {t('SAML 2.0')}- </div>- </div>-);--const DomainStep = ({- platform,- refetch,- onVerified,- onNext,- canProceed,- disableAction,-}: {- platform: PlatformWithoutSensitiveData;- refetch: () => Promise<void>;- onVerified: () => void;- onNext: () => void;- canProceed: boolean;- disableAction: DisableAction;-}) => {- const form = useForm<SsoDomainFormValues>({- resolver: zodResolver(SsoDomainFormValues),- defaultValues: { ssoDomain: platform.ssoDomain ?? '' },- mode: 'onChange',- });- const verification = platform.ssoDomainVerification ?? null;- const ssoDomainValue = form.watch('ssoDomain');- const isDirty =- ssoDomainValue.trim().toLowerCase() !== (platform.ssoDomain ?? '');- const [showUpdateWarning, setShowUpdateWarning] = useState(false);-- const { mutate: saveDomain, isPending: isSaving } = useMutation({- mutationFn: async (values: SsoDomainFormValues) => {- await samlSsoApi.updateSsoDomain(values.ssoDomain.trim().toLowerCase());- await refetch();- },- onSuccess: () => {- toast.success(t('SSO domain saved'));- setShowUpdateWarning(false);- },- onError: (error) => {- form.setError('root.serverError', {- type: 'manual',- message: api.extractServerErrorMessage(- error,- t("Couldn't save domain"),- ),- });- setShowUpdateWarning(false);- },- });-- const { mutate: verifyDomain, isPending: isVerifying } = useMutation({- mutationFn: async () => {- const result = await samlSsoApi.verifySsoDomain();- await refetch();- return result;- },- onSuccess: (result) => {- if (- result.ssoDomainVerification?.status ===- SsoDomainVerificationStatus.VERIFIED- ) {- toast.success(t('Domain verified'));- onVerified();- } else {- toast.message(- t('TXT record not found yet — DNS can take a few minutes.'),- );- }- },- onError: (error) => {- toast.error(- api.extractServerErrorMessage(error, t("Couldn't verify domain")),- );- },- });-- const handleSubmit = (values: SsoDomainFormValues) => {- if (platform.ssoDomain) {- setShowUpdateWarning(true);- return;- }- saveDomain(values);- };-- return (- <Form {...form}>- <form- className="grid space-y-4"- onSubmit={form.handleSubmit(handleSubmit)}- >- <FormField- name="ssoDomain"- render={({ field }) => (- <FormItem className="grid space-y-2">- <Label htmlFor="ssoDomain">{t('Domain')}</Label>- <Input {...field} id="ssoDomain" placeholder="acme.com" />- <FormDescription>- {t(- 'When a user enters this domain on the sign-in page, they will be redirected to your SAML identity provider.',- )}- </FormDescription>- <FormMessage />- </FormItem>- )}- />-- {verification && !isDirty && (- <DomainVerificationPanel- verification={verification}- isVerifying={isVerifying}- onVerify={() => verifyDomain()}- />- )}-- {form.formState.errors.root?.serverError && (- <FormMessage>- {form.formState.errors.root.serverError.message}- </FormMessage>- )}-- <DialogFooter>- {disableAction && (- <Button- {...adminControl(AdminControl.SSO_SAML_DISABLE_RUN)}- type="button"- variant="basic"- className="text-danger-11"- loading={disableAction.isDisabling}- onClick={disableAction.onDisable}- >- {t('Disable')}- </Button>- )}- {isDirty ? (- <Button- {...adminControl(- platform.ssoDomain- ? AdminControl.SSO_SAML_DOMAIN_UPDATE_SUBMIT- : AdminControl.SSO_SAML_DOMAIN_SUBMIT,- )}- type="submit"- loading={isSaving}- disabled={!form.formState.isValid}- >- {platform.ssoDomain ? t('Update domain') : t('Save domain')}- </Button>- ) : (- <Button type="button" onClick={onNext} disabled={!canProceed}>- {t('Next')}- </Button>- )}- </DialogFooter>- </form>- <Dialog open={showUpdateWarning} onOpenChange={setShowUpdateWarning}>- <DialogContent className={adminLayout.dialog.md}>- <DialogHeader>- <DialogTitle>{t('Update SSO domain?')}</DialogTitle>- </DialogHeader>- <Alert variant="warning">- <TriangleAlert className="size-4" />- <AlertDescription>- {t(- "Users won't be able to sign in via SSO until you verify the new domain.",- )}- </AlertDescription>- </Alert>- <DialogFooter>- <Button- variant="outline"- type="button"- disabled={isSaving}- onClick={() => setShowUpdateWarning(false)}- >- {t('Cancel')}- </Button>- <Button- {...adminControl(AdminControl.SSO_SAML_DOMAIN_UPDATE_CONFIRM)}- type="button"- loading={isSaving}- onClick={() => saveDomain(form.getValues())}- >- {t('Update domain')}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </Form>- );-};--const SamlStep = ({- platform,- refetch,- onBack,- onClose,- disableAction,-}: {- platform: PlatformWithoutSensitiveData;- refetch: () => Promise<void>;- onBack: () => void;- onClose: () => void;- disableAction: DisableAction;-}) => {- const form = useForm<Saml2FormValues>({- resolver: zodResolver(Saml2FormValues),- defaultValues: { idpMetadata: '', idpCertificate: '' },- mode: 'onChange',- });-- const { data: samlAcs } = flagsHooks.useFlag<string>(- ApFlagId.SAML_AUTH_ACS_URL,- );-- const { mutate, isPending } = useMutation({- mutationFn: async (request: UpdatePlatformRequestBody) => {- await platformApi.update(request, platform.id);- await refetch();- },- onSuccess: () => {- toast.success(t('Single sign-on settings updated'), { duration: 3000 });- onClose();- },- });-- return (- <>- {samlAcs && (- <div className="mb-4">- <ApMarkdown- markdown={t(- `-**Setup Instructions**:-Please check the following documentation: [SAML SSO](https://activepieces.com/docs/security/sso)--**Single sign-on URL**:-\`\`\`text-{samlAcs}-\`\`\`-**Audience URI (SP Entity ID)**:-\`\`\`text-Activepieces-\`\`\`-`,- { samlAcs: samlAcs ?? '' },- )}- />- </div>- )}-- <Form {...form}>- <form- className="grid space-y-4"- onSubmit={form.handleSubmit((data) => {- mutate({ federatedAuthProviders: { saml: data } });- })}- >- <FormField- name="idpMetadata"- render={({ field }) => (- <FormItem className="grid space-y-2">- <Label htmlFor="idpMetadata">{t('IDP Metadata')}</Label>- <Textarea- {...field}- required- id="idpMetadata"- rows={6}- className="font-mono text-xs"- />- <FormDescription>- {t(- 'Paste the metadata XML contents or the metadata URL provided by your identity provider.',- )}- </FormDescription>- <FormMessage />- </FormItem>- )}- />- <FormField- name="idpCertificate"- render={({ field }) => (- <FormItem className="grid space-y-4">- <Label htmlFor="idpCertificate">{t('IDP Certificate')}</Label>- <Textarea {...field} required id="idpCertificate" />- <FormMessage />- </FormItem>- )}- />- {form?.formState?.errors?.root?.serverError && (- <FormMessage>- {form.formState.errors.root.serverError.message}- </FormMessage>- )}-- <DialogFooter>- {disableAction && (- <Button- {...adminControl(AdminControl.SSO_SAML_DISABLE_RUN)}- type="button"- variant="basic"- className="text-danger-11 mr-auto"- loading={disableAction.isDisabling}- onClick={disableAction.onDisable}- >- {t('Disable')}- </Button>- )}- <Button variant="outline" type="button" onClick={onBack}>- {t('Back')}- </Button>- <Button- {...adminControl(AdminControl.SSO_SAML_CONFIG_SUBMIT)}- loading={isPending}- disabled={!form.formState.isValid}- type="submit"- >- {t('Save')}- </Button>- </DialogFooter>- </form>- </Form>- </>- );-};--const DomainVerificationPanel = ({- verification,- isVerifying,- onVerify,-}: {- verification: SsoDomainVerification;- isVerifying: boolean;- onVerify: () => void;-}) => {- const verified = verification.status === SsoDomainVerificationStatus.VERIFIED;- return (- <div className="flex flex-col gap-3">- <VerificationStatusBadge status={verification.status} />- {!verified && (- <>- <p className="text-xs text-gray-11">- {t(- "Add this TXT record at your DNS provider. We'll detect it once it propagates — this usually takes a few minutes.",- )}- </p>- <VerificationRecordRow record={verification.record} />- <div>- <Button- {...adminControl(AdminControl.SSO_SAML_DNS_RUN)}- type="button"- size="sm"- variant="outline"- loading={isVerifying}- onClick={onVerify}- >- {t('Verify DNS')}- </Button>- </div>- </>- )}- </div>- );-};--const VerificationStatusBadge = ({- status,-}: {- status: SsoDomainVerificationStatus;-}) => {- if (status === SsoDomainVerificationStatus.VERIFIED) {- return (- <div className="flex items-center gap-2 text-sm text-success-11">- <CheckCircle className="size-4" />- {t('DNS verified — domain is ready')}- </div>- );- }- return (- <div className="flex items-center gap-2 text-sm text-warning-11">- <Loader2 className="size-4 animate-spin" />- {t('Waiting for DNS')}- </div>- );-};--const VerificationRecordRow = ({- record,-}: {- record: SsoDomainVerificationRecord;-}) => (- <div className="flex flex-col gap-2 rounded-md border p-4">- <div className="flex items-center gap-2">- <span className="text-xs font-mono px-1.5 py-0.5 rounded-md bg-gray-3">- {record.type}- </span>- </div>- <div className="grid grid-cols-2 gap-3">- <div className="flex flex-col gap-1.5 min-w-0">- <Label className="text-xs text-gray-11">{t('Name')}</Label>- <CopyToClipboardInput- textToCopy={record.name}- useInput={true}- controlId={AdminControl.SSO_SAML_DNS_NAME_COPY}- />- </div>- <div className="flex flex-col gap-1.5 min-w-0">- <Label className="text-xs text-gray-11">{t('Value')}</Label>- <CopyToClipboardInput- textToCopy={record.value}- useInput={true}- controlId={AdminControl.SSO_SAML_DNS_VALUE_COPY}- />- </div>- </div>- </div>-);--const SsoDomainFormValues = z.object({- ssoDomain: z- .hostname('invalidSsoDomain')- .max(253, 'invalidSsoDomain')- .refine((v) => v.includes('.'), 'invalidSsoDomain'),-});-type SsoDomainFormValues = z.infer<typeof SsoDomainFormValues>;--const Saml2FormValues = z.object({- idpMetadata: z.string().min(1),- idpCertificate: z.string().min(1),-});-type Saml2FormValues = z.infer<typeof Saml2FormValues>;--type WizardStep = 'domain' | 'saml';--type DisableAction = {- onDisable: () => void;- isDisabling: boolean;-} | null;--type ConfigureSamlDialogProps = {- platform: PlatformWithoutSensitiveData;- connected: boolean;- refetch: () => Promise<void>;-};diff --git a/packages/web/src/app/routes/platform/security/sso/saml-setup-page.tsx b/packages/web/src/app/routes/platform/security/sso/saml-setup-page.tsxnew file mode 100644index 00000000000..266f4742480--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/saml-setup-page.tsx@@ -0,0 +1,506 @@+import {+ ApFlagId,+ formErrors,+ PlatformWithoutSensitiveData,+ SsoDomainVerificationStatus,+ UpdatePlatformRequestBody,+} from '@activepieces/shared';+import { zodResolver } from '@hookform/resolvers/zod';+import { useMutation } from '@tanstack/react-query';+import { t } from 'i18next';+import { TriangleAlert } from 'lucide-react';+import { ReactNode, useState } from 'react';+import { useForm } from 'react-hook-form';+import { useNavigate } from 'react-router-dom';+import { toast } from 'sonner';+import { z } from 'zod';++import { platformApi } from '@/api/platforms-api';+import {+ AdminPage,+ AdminPageHeader,+ SettingsPanel,+ SettingsRow,+ adminPageResources,+} from '@/app/components/admin';+import { DomainVerification } from '@/app/routes/platform/security/sso/domain-verification';+import { FormActions } from '@/app/routes/platform/security/sso/form-actions';+import { MethodConfirmDialog } from '@/app/routes/platform/security/sso/method-confirm-dialog';+import { SamlDeletionWarning } from '@/app/routes/platform/security/sso/saml-deletion-warning';+import { ssoPaths } from '@/app/routes/platform/security/sso/sso-paths';+import { useSignInMethods } from '@/app/routes/platform/security/sso/use-sign-in-methods';+import { CopyToClipboardInput } from '@/components/custom/clipboard/copy-to-clipboard';+import { Alert, AlertDescription } from '@/components/ui/alert';+import { Button } from '@/components/ui/button';+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@/components/ui/form';+import { Label } from '@/components/ui/label';+import { Textarea } from '@/components/ui/textarea';+import { flagsHooks } from '@/hooks/flags-hooks';+import { platformHooks } from '@/hooks/platform-hooks';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { api } from '@/lib/api';+import { cn } from '@/lib/utils';++export const SamlSetupPage = () => {+ const { platform, refetch } = platformHooks.useCurrentPlatform();+ const navigate = useNavigate();+ const connected = !!platform.federatedAuthProviders?.saml;+ const domainVerified =+ platform.ssoDomainVerification?.status ===+ SsoDomainVerificationStatus.VERIFIED;+ const [step, setStep] = useState<WizardStep>(+ connected || domainVerified ? 'saml' : 'domain',+ );++ return (+ <AdminPage width="content">+ <AdminPageHeader+ title={t('Single sign-on')}+ description={t('Connect a SAML 2.0 identity provider.')}+ back={{ label: t('Authentication'), to: ssoPaths.authentication }}+ resources={adminPageResources.sso}+ />+ <SettingsPanel>+ <SamlWizard+ platform={platform}+ connected={connected}+ domainVerified={domainVerified}+ step={step}+ onStepChange={setStep}+ refetch={refetch}+ onClose={() => navigate(ssoPaths.authentication)}+ />+ </SettingsPanel>+ {connected && step === 'saml' && (+ <DisableSamlRow+ platform={platform}+ refetch={refetch}+ onDisabled={() => navigate(ssoPaths.authentication)}+ />+ )}+ </AdminPage>+ );+};++const DisableSamlRow = ({+ platform,+ refetch,+ onDisabled,+}: {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+ onDisabled: () => void;+}) => {+ const [confirmOpen, setConfirmOpen] = useState(false);+ const samlIsOnlyMethod =+ useSignInMethods(platform).isOnlyWorkingMethod('saml');+ const { mutate: disableSaml, isPending } = useMutation({+ mutationFn: async () => {+ await platformApi.update(+ { federatedAuthProviders: { saml: null } },+ platform.id,+ );+ await refetch();+ },+ onSuccess: () => {+ toast.success(t('Single sign-on settings updated'), { duration: 3000 });+ onDisabled();+ },+ onError: (error) => {+ toast.error(+ api.extractServerErrorMessage(+ error,+ t("Couldn't disable single sign-on"),+ ),+ );+ },+ });++ return (+ <SettingsPanel flush>+ <SettingsRow+ title={t('Disable single sign-on')}+ description={t(+ 'Deletes the SAML connection. Your verified domain stays, so you can connect again later.',+ )}+ >+ <Button+ {...adminControl(AdminControl.SSO_SAML_DISABLE_RUN)}+ type="button"+ variant="destructive"+ size="sm"+ onClick={() => setConfirmOpen(true)}+ >+ {t('Disable')}+ </Button>+ </SettingsRow>+ <MethodConfirmDialog+ open={confirmOpen}+ onOpenChange={setConfirmOpen}+ title={t('Disable single sign-on?')}+ description={t(+ 'People who use single sign-on will have to sign in another way.',+ )}+ warning={<SamlDeletionWarning blocked={samlIsOnlyMethod} />}+ confirmDisabled={samlIsOnlyMethod}+ confirmLabel={t('Disable')}+ destructive+ isPending={isPending}+ controlId={AdminControl.SSO_SAML_DISABLE_CONFIRM}+ confirmText="disable"+ onConfirm={() => disableSaml()}+ />+ </SettingsPanel>+ );+};++const SamlWizard = ({+ platform,+ connected,+ domainVerified,+ step,+ onStepChange: setStep,+ refetch,+ onClose,+}: {+ platform: PlatformWithoutSensitiveData;+ connected: boolean;+ domainVerified: boolean;+ step: WizardStep;+ onStepChange: (step: WizardStep) => void;+ refetch: () => Promise<void>;+ onClose: () => void;+}) => {+ const samlUnlocked = domainVerified || connected;+ return (+ <>+ <StepIndicator+ step={step}+ samlLocked={!samlUnlocked}+ onSelect={setStep}+ />+ <div className={cn(step !== 'domain' && 'hidden')}>+ <DomainStep+ platform={platform}+ refetch={refetch}+ canContinue={samlUnlocked}+ onVerified={() => setStep('saml')}+ onNext={() => setStep('saml')}+ />+ </div>+ <div className={cn(step !== 'saml' && 'hidden')}>+ <SamlStep+ platform={platform}+ connected={connected}+ domainVerified={domainVerified}+ refetch={refetch}+ onBack={() => setStep('domain')}+ onClose={onClose}+ />+ </div>+ </>+ );+};++const StepIndicator = ({+ step,+ samlLocked,+ onSelect,+}: {+ step: WizardStep;+ samlLocked: boolean;+ onSelect: (step: WizardStep) => void;+}) => (+ <div className="flex items-center gap-3 text-xs text-gray-11">+ <StepButton+ number={1}+ label={t('SSO Domain')}+ active={step === 'domain'}+ onClick={() => onSelect('domain')}+ />+ <div className="h-px w-6 bg-gray-6" />+ <StepButton+ number={2}+ label={t('SAML 2.0')}+ active={step === 'saml'}+ disabled={samlLocked}+ onClick={() => onSelect('saml')}+ />+ </div>+);++const StepButton = ({+ number,+ label,+ active,+ disabled = false,+ onClick,+}: {+ number: number;+ label: string;+ active: boolean;+ disabled?: boolean;+ onClick: () => void;+}) => (+ <button+ type="button"+ aria-current={active ? 'step' : undefined}+ disabled={disabled}+ onClick={onClick}+ className={cn(+ 'flex items-center gap-2 rounded-md hover:text-gray-12 focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-gray-8/50 disabled:pointer-events-none disabled:opacity-50',+ active && 'font-medium text-gray-12',+ )}+ >+ <span+ className={cn(+ 'flex size-5 items-center justify-center rounded-full border text-xs',+ active ? 'border-accent-9 bg-accent-9 text-on-accent' : 'border-gray-7',+ )}+ >+ {number}+ </span>+ {label}+ </button>+);++const DomainStep = ({+ platform,+ refetch,+ canContinue,+ onVerified,+ onNext,+}: {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+ canContinue: boolean;+ onVerified: () => void;+ onNext: () => void;+}) => {+ const verified =+ !!platform.ssoDomain &&+ platform.ssoDomainVerification?.status ===+ SsoDomainVerificationStatus.VERIFIED;++ return (+ <DomainVerification+ platform={platform}+ refetch={refetch}+ onVerified={onVerified}+ nextAction={+ <Button+ type="button"+ variant={verified ? 'default' : 'outline'}+ disabled={!canContinue}+ onClick={onNext}+ >+ {t('Next')}+ </Button>+ }+ />+ );+};++const SamlStep = ({+ platform,+ connected,+ domainVerified,+ refetch,+ onBack,+ onClose,+}: {+ platform: PlatformWithoutSensitiveData;+ connected: boolean;+ domainVerified: boolean;+ refetch: () => Promise<void>;+ onBack: () => void;+ onClose: () => void;+}) => {+ const form = useForm<Saml2FormValues>({+ resolver: zodResolver(Saml2FormValues),+ defaultValues: { idpMetadata: '', idpCertificate: '' },+ mode: 'onChange',+ });++ const { data: samlAcs } = flagsHooks.useFlag<string>(+ ApFlagId.SAML_AUTH_ACS_URL,+ );++ const { mutate, isPending } = useMutation({+ mutationFn: async (request: UpdatePlatformRequestBody) => {+ await platformApi.update(request, platform.id);+ await refetch();+ },+ onSuccess: () => {+ toast.success(t('Single sign-on settings updated'), { duration: 3000 });+ onClose();+ },+ onError: (error) => {+ form.setError('root.serverError', {+ type: 'manual',+ message: api.extractServerErrorMessage(+ error,+ t("Couldn't save single sign-on settings"),+ ),+ });+ },+ });++ return (+ <div className="flex flex-col gap-6">+ {samlAcs && (+ <StepSection title={t('Copy these into your identity provider')}>+ <div className="flex min-w-0 flex-col gap-2">+ <Label>{t('Single sign-on URL')}</Label>+ <CopyToClipboardInput+ textToCopy={samlAcs}+ useInput={true}+ controlId={AdminControl.SSO_SAML_ACS_URL_COPY}+ />+ </div>+ <div className="flex min-w-0 flex-col gap-2">+ <Label>{t('Audience URI (SP Entity ID)')}</Label>+ <CopyToClipboardInput+ textToCopy={SAML_ENTITY_ID}+ useInput={true}+ controlId={AdminControl.SSO_SAML_ENTITY_ID_COPY}+ />+ </div>+ </StepSection>+ )}++ <Form {...form}>+ <form+ className="flex flex-col gap-6"+ onSubmit={form.handleSubmit((data) => {+ mutate({ federatedAuthProviders: { saml: data } });+ })}+ >+ <StepSection+ title={t('Paste these from your identity provider')}+ description={+ connected+ ? t('To change the connection, paste both values again.')+ : undefined+ }+ divided={!!samlAcs}+ >+ <FormField+ name="idpMetadata"+ render={({ field }) => (+ <FormItem className="grid space-y-2">+ <FormLabel>{t('IDP Metadata')}</FormLabel>+ <FormControl>+ <Textarea+ {...field}+ required+ rows={6}+ placeholder={+ connected+ ? t('Saved. Paste new metadata to replace it.')+ : undefined+ }+ />+ </FormControl>+ <FormDescription>+ {t(+ 'Paste the metadata XML contents or the metadata URL provided by your identity provider.',+ )}+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ name="idpCertificate"+ render={({ field }) => (+ <FormItem className="grid space-y-2">+ <FormLabel>{t('IDP Certificate')}</FormLabel>+ <FormControl>+ <Textarea+ {...field}+ required+ placeholder={+ connected+ ? t('Saved. Paste a new certificate to replace it.')+ : undefined+ }+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </StepSection>+ {!domainVerified && (+ <Alert variant="warning">+ <TriangleAlert className="size-4" />+ <AlertDescription>+ {t(+ 'Verify your domain before saving. You can already copy the values above into your identity provider.',+ )}+ </AlertDescription>+ </Alert>+ )}+ {form?.formState?.errors?.root?.serverError && (+ <FormMessage>+ {form.formState.errors.root.serverError.message}+ </FormMessage>+ )}++ <FormActions>+ <Button variant="outline" type="button" onClick={onBack}>+ {t('Back')}+ </Button>+ <Button+ {...adminControl(AdminControl.SSO_SAML_CONFIG_SUBMIT)}+ loading={isPending}+ disabled={!domainVerified || !form.formState.isValid}+ type="submit"+ >+ {t('Save')}+ </Button>+ </FormActions>+ </form>+ </Form>+ </div>+ );+};++const StepSection = ({+ title,+ description,+ divided = false,+ children,+}: {+ title: string;+ description?: string;+ divided?: boolean;+ children: ReactNode;+}) => (+ <section className={cn('flex flex-col gap-4', divided && 'border-t pt-6')}>+ <div className="flex flex-col gap-1">+ <h3 className="text-sm font-semibold text-gray-12">{title}</h3>+ {description && <p className="text-sm text-gray-11">{description}</p>}+ </div>+ {children}+ </section>+);++const SAML_ENTITY_ID = 'Activepieces';++const Saml2FormValues = z.object({+ idpMetadata: z.string().min(1, formErrors.required),+ idpCertificate: z.string().min(1, formErrors.required),+});+type Saml2FormValues = z.infer<typeof Saml2FormValues>;++type WizardStep = 'domain' | 'saml';diff --git a/packages/web/src/app/routes/platform/security/sso/sign-in-methods-section.tsx b/packages/web/src/app/routes/platform/security/sso/sign-in-methods-section.tsxnew file mode 100644index 00000000000..21870a5369d--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/sign-in-methods-section.tsx@@ -0,0 +1,260 @@+import { PlatformWithoutSensitiveData } from '@activepieces/shared';+import { t } from 'i18next';+import { ArrowUpRight, LockKeyhole, MailIcon } from 'lucide-react';+import { ReactNode, useState } from 'react';+import { Link } from 'react-router-dom';+import { toast } from 'sonner';++import {+ adminDocs,+ AdminSection,+ SettingsPanel,+ SettingsRow,+ StatusDot,+} from '@/app/components/admin';+import { MethodConfirmDialog } from '@/app/routes/platform/security/sso/method-confirm-dialog';+import { ssoPaths } from '@/app/routes/platform/security/sso/sso-paths';+import { useSignInMethods } from '@/app/routes/platform/security/sso/use-sign-in-methods';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import { Switch } from '@/components/ui/switch';+import { ssoMutations } from '@/features/platform-admin';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { cn } from '@/lib/utils';++import GoogleIcon from '../../../../../assets/img/custom/auth/google-icon.svg';++export const SignInMethodsSection = ({+ platform,+ refetch,+}: SignInMethodsSectionProps) => {+ const samlConnected = !!platform.federatedAuthProviders?.saml;+ const [googleChange, setGoogleChange] = useState<boolean | null>(null);+ const [emailChange, setEmailChange] = useState<boolean | null>(null);+ const { selfHosted, working, isOnlyWorkingMethod } =+ useSignInMethods(platform);+ const googleNotSetUp =+ selfHosted && platform.googleAuthEnabled && !working.google;+ const emailIsLastMethod = isOnlyWorkingMethod('email');+ const googleIsLastMethod = isOnlyWorkingMethod('google');++ const { mutate: toggleGoogleAuth, isPending: isGoogleAuthPending } =+ ssoMutations.useUpdatePlatformSso({+ platformId: platform.id,+ refetch,+ onSuccess: () => {+ setGoogleChange(null);+ toast.success(t('Google authentication updated'), { duration: 3000 });+ },+ });++ const { mutate: toggleEmailAuth, isPending: isEmailAuthPending } =+ ssoMutations.useUpdatePlatformSso({+ platformId: platform.id,+ refetch,+ onSuccess: () => {+ setEmailChange(null);+ toast.success(t('Email authentication updated'), { duration: 3000 });+ },+ });++ return (+ <AdminSection+ title={t('Sign-in methods')}+ description={t('Choose how people at your verified domain sign in.')}+ >+ <SettingsPanel flush>+ <SettingsRow+ media={+ <MethodIcon on={samlConnected}>+ <LockKeyhole />+ </MethodIcon>+ }+ title={+ <>+ {t('Single sign-on')}+ <Badge variant="outline">{t('SAML 2.0')}</Badge>+ {samlConnected && (+ <StatusDot tone="success" className="text-xs text-gray-11">+ {t('Connected')}+ </StatusDot>+ )}+ </>+ }+ >+ <Button asChild size="sm" variant="outline">+ <Link+ {...adminControl(AdminControl.SSO_SAML_OPEN)}+ to={ssoPaths.samlSetup}+ >+ {samlConnected ? t('Manage') : t('Set up')}+ </Link>+ </Button>+ </SettingsRow>++ <SettingsRow+ media={+ <MethodIcon on={platform.googleAuthEnabled}>+ <img+ className={cn(+ 'size-4',+ !platform.googleAuthEnabled && 'grayscale',+ )}+ src={GoogleIcon}+ alt=""+ />+ </MethodIcon>+ }+ title={+ <>+ {t('Continue with Google')}+ <Badge variant="outline">{t('OAuth 2.0')}</Badge>+ {googleNotSetUp && (+ <StatusDot tone="warning" className="text-xs text-gray-11">+ {t('Not set up')}+ </StatusDot>+ )}+ </>+ }+ description={+ googleNotSetUp && (+ <>+ {t('Needs a Google OAuth client on this server.')}{' '}+ <GoogleSetupGuideLink />+ </>+ )+ }+ >+ <Switch+ {...adminControl(AdminControl.SSO_GOOGLE_TOGGLE)}+ aria-label={t('Continue with Google')}+ checked={platform.googleAuthEnabled}+ onCheckedChange={(checked) => setGoogleChange(checked)}+ disabled={isGoogleAuthPending}+ />+ </SettingsRow>++ <SettingsRow+ media={+ <MethodIcon on={platform.emailAuthEnabled}>+ <MailIcon />+ </MethodIcon>+ }+ title={t('Email and password')}+ >+ <Switch+ {...adminControl(AdminControl.SSO_EMAIL_LOGIN_TOGGLE)}+ aria-label={t('Email and password')}+ checked={platform.emailAuthEnabled}+ onCheckedChange={(checked) => setEmailChange(checked)}+ disabled={isEmailAuthPending}+ />+ </SettingsRow>+ </SettingsPanel>++ <MethodConfirmDialog+ open={googleChange !== null}+ onOpenChange={(open) => !open && setGoogleChange(null)}+ title={+ googleChange+ ? t('Turn on Google sign-in?')+ : t('Turn off Google sign-in?')+ }+ description={+ googleChange ? (+ <>+ {t('Google sign-in will be on for this platform.')}+ {selfHosted && (+ <>+ {' '}+ {t(+ 'On a self-hosted server it also needs a Google OAuth client.',+ )}{' '}+ <GoogleSetupGuideLink />+ </>+ )}+ </>+ ) : (+ t('Google sign-in will be off for this platform.')+ )+ }+ confirmLabel={googleChange ? t('Turn on') : t('Turn off')}+ destructive={googleChange === false}+ warning={+ googleChange === false && googleIsLastMethod ? (+ <LastMethodWarning />+ ) : undefined+ }+ confirmDisabled={googleChange === false && googleIsLastMethod}+ isPending={isGoogleAuthPending}+ controlId={AdminControl.SSO_GOOGLE_TOGGLE_CONFIRM}+ onConfirm={() =>+ googleChange !== null &&+ toggleGoogleAuth({ googleAuthEnabled: googleChange })+ }+ />++ <MethodConfirmDialog+ open={emailChange !== null}+ onOpenChange={(open) => !open && setEmailChange(null)}+ title={+ emailChange+ ? t('Turn on email sign-in?')+ : t('Turn off email sign-in?')+ }+ description={+ emailChange+ ? t('People can sign in with email and password again.')+ : t('People can no longer sign in with email and password.')+ }+ confirmLabel={emailChange ? t('Turn on') : t('Turn off')}+ destructive={emailChange === false}+ warning={+ emailChange === false && emailIsLastMethod ? (+ <LastMethodWarning />+ ) : undefined+ }+ confirmDisabled={emailChange === false && emailIsLastMethod}+ isPending={isEmailAuthPending}+ controlId={AdminControl.SSO_EMAIL_LOGIN_TOGGLE_CONFIRM}+ onConfirm={() =>+ emailChange !== null &&+ toggleEmailAuth({ emailAuthEnabled: emailChange })+ }+ />+ </AdminSection>+ );+};++const LastMethodWarning = () =>+ t(+ "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.",+ );++const GoogleSetupGuideLink = () => (+ <a+ href={adminDocs.url('admin-guide/guides/sso#google')}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-0.5 font-medium text-accent-11 hover:underline"+ >+ {t('Setup guide')}+ <ArrowUpRight className="size-3.5" />+ </a>+);++const MethodIcon = ({ on, children }: { on: boolean; children: ReactNode }) => (+ <div+ className={cn(+ 'flex size-9 items-center justify-center rounded-lg border bg-panel [&_svg]:size-4',+ on ? 'border-gray-7 text-gray-12' : 'text-gray-9 opacity-60',+ )}+ >+ {children}+ </div>+);++type SignInMethodsSectionProps = {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+};diff --git a/packages/web/src/app/routes/platform/security/sso/sso-paths.ts b/packages/web/src/app/routes/platform/security/sso/sso-paths.tsnew file mode 100644index 00000000000..de531d225d1--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/sso-paths.ts@@ -0,0 +1,4 @@+export const ssoPaths = {+ authentication: '/platform/sso',+ samlSetup: '/platform/sso/saml',+};diff --git a/packages/web/src/app/routes/platform/security/sso/use-sign-in-methods.ts b/packages/web/src/app/routes/platform/security/sso/use-sign-in-methods.tsnew file mode 100644index 00000000000..a8736ea83ee--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/use-sign-in-methods.ts@@ -0,0 +1,43 @@+import {+ ApEdition,+ ApFlagId,+ PlatformWithoutSensitiveData,+ SsoDomainVerificationStatus,+ ThirdPartyAuthnProvidersToShowMap,+} from '@activepieces/shared';++import { flagsHooks } from '@/hooks/flags-hooks';++export function useSignInMethods(+ platform: PlatformWithoutSensitiveData,+): SignInMethods {+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);+ const { data: providers } =+ flagsHooks.useFlag<ThirdPartyAuthnProvidersToShowMap>(+ ApFlagId.THIRD_PARTY_AUTH_PROVIDERS_TO_SHOW_MAP,+ );+ const selfHosted = edition === ApEdition.ENTERPRISE;+ const domainVerified =+ platform.ssoDomainVerification?.status ===+ SsoDomainVerificationStatus.VERIFIED;+ const working: Record<SignInMethod, boolean> = {+ email: platform.emailAuthEnabled,+ google: Boolean(providers?.google),+ saml:+ !!platform.federatedAuthProviders?.saml && (selfHosted || domainVerified),+ };+ return {+ selfHosted,+ working,+ isOnlyWorkingMethod: (method) =>+ working[method] && Object.values(working).filter(Boolean).length === 1,+ };+}++export type SignInMethod = 'email' | 'google' | 'saml';++type SignInMethods = {+ selfHosted: boolean;+ working: Record<SignInMethod, boolean>;+ isOnlyWorkingMethod: (method: SignInMethod) => boolean;+};diff --git a/packages/web/src/app/routes/platform/security/sso/verify-domain-dialog.tsx b/packages/web/src/app/routes/platform/security/sso/verify-domain-dialog.tsxnew file mode 100644index 00000000000..4ea38347c4b--- /dev/null+++ b/packages/web/src/app/routes/platform/security/sso/verify-domain-dialog.tsx@@ -0,0 +1,81 @@+import {+ PlatformWithoutSensitiveData,+ SsoDomainVerificationStatus,+} from '@activepieces/shared';+import { t } from 'i18next';+import { ReactNode } from 'react';++import { adminLayout } from '@/app/components/admin';+import { DomainVerification } from '@/app/routes/platform/security/sso/domain-verification';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@/components/ui/dialog';++export const VerifyDomainDialog = ({+ platform,+ refetch,+ open,+ onOpenChange,+ children,+}: VerifyDomainDialogProps) => {+ const pending =+ !!platform.ssoDomain &&+ platform.ssoDomainVerification?.status ===+ SsoDomainVerificationStatus.PENDING_VERIFICATION;++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ {children && <DialogTrigger asChild>{children}</DialogTrigger>}+ <DialogContent+ className={adminLayout.dialog.md}+ onInteractOutside={(event) => event.preventDefault()}+ >+ <DialogHeader>+ <DialogTitle>+ {pending+ ? t('Verify {domain}', { domain: platform.ssoDomain })+ : t('Verify a domain')}+ </DialogTitle>+ <DialogDescription>+ {pending+ ? t(+ 'Add this TXT record at your DNS provider, then verify. Verify within 3 hours or the domain is dropped.',+ )+ : t(+ 'Prove your company owns its email domain with a DNS record.',+ )}+ </DialogDescription>+ </DialogHeader>+ <DomainVerification+ platform={platform}+ refetch={refetch}+ onVerified={() => onOpenChange(false)}+ showIntro={false}+ secondaryAction={+ <Button+ type="button"+ variant="outline"+ onClick={() => onOpenChange(false)}+ >+ {pending ? t('Verify later') : t('Cancel')}+ </Button>+ }+ />+ </DialogContent>+ </Dialog>+ );+};++type VerifyDomainDialogProps = {+ platform: PlatformWithoutSensitiveData;+ refetch: () => Promise<void>;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ children?: ReactNode;+};diff --git a/packages/web/src/components/custom/delete-dialog.tsx b/packages/web/src/components/custom/delete-dialog.tsxindex 4ce09a61282..20928c8d5e9 100644--- a/packages/web/src/components/custom/delete-dialog.tsx+++ b/packages/web/src/components/custom/delete-dialog.tsx@@ -4,6 +4,10 @@ import { TriangleAlert } from 'lucide-react';import { useState } from 'react';import { toast } from 'sonner';+import {+ TypeToConfirm,+ useTypeToConfirm,+} from '@/components/custom/type-to-confirm';import { Alert, AlertDescription } from '@/components/ui/alert';import { Button } from '@/components/ui/button';import {@@ -31,7 +35,10 @@ interface ConfirmationDeleteDialogProps {onError?: (error: Error) => void;warning?: React.ReactNode | string;confirmDisabled?: boolean;+ confirmText?: string;controlId?: AdminControl;+ contentClassName?: string;+ keepOpenOnOutsideClick?: boolean;}export const ConfirmationDeleteDialog = ({@@ -48,12 +55,17 @@ export const ConfirmationDeleteDialog = ({onOpenChange,warning,confirmDisabled,+ confirmText,controlId,+ contentClassName,+ keepOpenOnOutsideClick = false,}: ConfirmationDeleteDialogProps) => {const [isControlled] = useState(open !== undefined && onOpenChange !== undefined,);const [isUncontrolledOpen, setIsUncontrolledOpen] = useState(false);+ const isOpen = isControlled ? open : isUncontrolledOpen;+ const typed = useTypeToConfirm({ open: !!isOpen, text: confirmText });const { mutate, isPending } = useMutation({mutationFn,@@ -74,8 +86,6 @@ export const ConfirmationDeleteDialog = ({}};- const isOpen = isControlled ? open : isUncontrolledOpen;-return (<Dialogopen={isOpen}@@ -83,7 +93,15 @@ export const ConfirmationDeleteDialog = ({>{children && <DialogTrigger asChild>{children}</DialogTrigger>}- <DialogContent onClick={(e) => e.stopPropagation()}>+ <DialogContent+ className={contentClassName}+ onClick={(e) => e.stopPropagation()}+ onInteractOutside={(event) => {+ if (keepOpenOnOutsideClick) {+ event.preventDefault();+ }+ }}+ ><DialogHeader className="min-w-0"><DialogTitle>{title}</DialogTitle><DialogDescription className="pt-2 break-words">@@ -96,6 +114,14 @@ export const ConfirmationDeleteDialog = ({<AlertDescription>{warning}</AlertDescription></Alert>)}+ {confirmText && !confirmDisabled && (+ <TypeToConfirm+ id="delete-confirm-text"+ text={confirmText}+ value={typed.value}+ onChange={typed.setValue}+ />+ )}<DialogFooter className="mt-3"><Buttonvariant="outline"@@ -107,7 +133,7 @@ export const ConfirmationDeleteDialog = ({<Buttonvariant="destructive"loading={isPending}- disabled={confirmDisabled}+ disabled={confirmDisabled || !typed.confirmed}onClick={() => mutate()}{...adminControl(controlId)}>diff --git a/packages/web/src/components/custom/type-to-confirm.tsx b/packages/web/src/components/custom/type-to-confirm.tsxnew file mode 100644index 00000000000..eb391bc6e82--- /dev/null+++ b/packages/web/src/components/custom/type-to-confirm.tsx@@ -0,0 +1,54 @@+import { t } from 'i18next';+import { useState } from 'react';++import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';++export const TypeToConfirm = ({+ id,+ text,+ value,+ onChange,+}: {+ id: string;+ text: string;+ value: string;+ onChange: (value: string) => void;+}) => {+ const [before, after] = t('Type {text} to confirm', {+ text: TEXT_SLOT,+ }).split(TEXT_SLOT);+ return (+ <div className="flex flex-col gap-2">+ <Label htmlFor={id} className="font-normal text-gray-11">+ {before}+ <span className="font-semibold text-gray-12">{text}</span>+ {after}+ </Label>+ <Input+ id={id}+ value={value}+ onChange={(event) => onChange(event.target.value)}+ autoComplete="off"+ />+ </div>+ );+};++export function useTypeToConfirm({+ open,+ text,+}: {+ open: boolean;+ text?: string;+}) {+ const [value, setValue] = useState('');+ const [openSeen, setOpenSeen] = useState(open);+ if (open !== openSeen) {+ setOpenSeen(open);+ setValue('');+ }+ return { value, setValue, confirmed: !text || value === text };+}++const TEXT_SLOT = '\u0000';diff --git a/packages/web/src/features/platform-admin/hooks/sso-hooks.ts b/packages/web/src/features/platform-admin/hooks/sso-hooks.tsindex 3d80e74ab1e..0db0ef55f0d 100644--- a/packages/web/src/features/platform-admin/hooks/sso-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/sso-hooks.ts@@ -1,7 +1,16 @@-import { UpdatePlatformRequestBody } from '@activepieces/shared';-import { useMutation } from '@tanstack/react-query';+import {+ SsoDomainVerificationStatus,+ UpdatePlatformRequestBody,+} from '@activepieces/shared';+import { useMutation, useQueryClient } from '@tanstack/react-query';+import { t } from 'i18next';+import { toast } from 'sonner';import { platformApi } from '@/api/platforms-api';+import { flagsHooks } from '@/hooks/flags-hooks';+import { api } from '@/lib/api';++import { samlSsoApi } from '../api/saml-sso-api';export const ssoMutations = {useUpdatePlatformSso: ({@@ -13,10 +22,14 @@ export const ssoMutations = {refetch: () => Promise<void>;onSuccess?: () => void;}) => {+ const queryClient = useQueryClient();return useMutation({mutationFn: async (request: UpdatePlatformRequestBody) => {await platformApi.update(request, platformId);- await refetch();+ await Promise.all([+ refetch(),+ queryClient.invalidateQueries({ queryKey: flagsHooks.queryKey }),+ ]);},onSuccess: () => {if (onSuccess) {@@ -25,4 +38,37 @@ export const ssoMutations = {},});},+ useVerifySsoDomain: ({+ refetch,+ onVerified,+ }: {+ refetch: () => Promise<void>;+ onVerified?: () => void;+ }) => {+ return useMutation({+ mutationFn: async () => {+ const result = await samlSsoApi.verifySsoDomain();+ await refetch();+ return result;+ },+ onSuccess: (result) => {+ if (+ result.ssoDomainVerification?.status ===+ SsoDomainVerificationStatus.VERIFIED+ ) {+ toast.success(t('Domain verified'));+ onVerified?.();+ return;+ }+ toast.message(+ t('TXT record not found yet — DNS can take a few minutes.'),+ );+ },+ onError: (error) => {+ toast.error(+ api.extractServerErrorMessage(error, t("Couldn't verify domain")),+ );+ },+ });+ },};diff --git a/packages/web/src/lib/admin-control.ts b/packages/web/src/lib/admin-control.tsindex 180ebefacf2..d72d339837f 100644--- a/packages/web/src/lib/admin-control.ts+++ b/packages/web/src/lib/admin-control.ts@@ -167,18 +167,28 @@ export enum AdminControl {SECRET_MANAGERS_CONNECTION_EDIT_OPEN = 'secret-managers.connection-edit.open',SECRET_MANAGERS_CONNECTION_OPEN = 'secret-managers.connection.open',SECRET_MANAGERS_CONNECTION_SUBMIT = 'secret-managers.connection.submit',+ SSO_ALLOWED_DOMAIN_REMOVE_CONFIRM = 'sso.allowed-domain-remove.confirm',+ SSO_ALLOWED_DOMAIN_REMOVE_OPEN = 'sso.allowed-domain-remove.open',SSO_ALLOWED_DOMAINS_OPEN = 'sso.allowed-domains.open',SSO_ALLOWED_DOMAINS_SUBMIT = 'sso.allowed-domains.submit',+ SSO_DOMAIN_ADD_OPEN = 'sso.domain-add.open',+ SSO_DOMAIN_DNS_RECORD_OPEN = 'sso.domain-dns-record.open',+ SSO_DOMAIN_DNS_RUN = 'sso.domain-dns.run',+ SSO_DOMAIN_REMOVE_CONFIRM = 'sso.domain-remove.confirm',+ SSO_DOMAIN_REMOVE_OPEN = 'sso.domain-remove.open',+ SSO_DOMAIN_VERIFY_OPEN = 'sso.domain-verify.open',SSO_EMAIL_LOGIN_TOGGLE = 'sso.email-login.toggle',+ SSO_EMAIL_LOGIN_TOGGLE_CONFIRM = 'sso.email-login-toggle.confirm',SSO_GOOGLE_TOGGLE = 'sso.google.toggle',+ SSO_GOOGLE_TOGGLE_CONFIRM = 'sso.google-toggle.confirm',+ SSO_SAML_ACS_URL_COPY = 'sso.saml-acs-url.copy',SSO_SAML_CONFIG_SUBMIT = 'sso.saml-config.submit',+ SSO_SAML_DISABLE_CONFIRM = 'sso.saml-disable.confirm',SSO_SAML_DISABLE_RUN = 'sso.saml-disable.run',SSO_SAML_DNS_NAME_COPY = 'sso.saml-dns-name.copy',SSO_SAML_DNS_VALUE_COPY = 'sso.saml-dns-value.copy',- SSO_SAML_DNS_RUN = 'sso.saml-dns.run',- SSO_SAML_DOMAIN_UPDATE_CONFIRM = 'sso.saml-domain-update.confirm',- SSO_SAML_DOMAIN_UPDATE_SUBMIT = 'sso.saml-domain-update.submit',SSO_SAML_DOMAIN_SUBMIT = 'sso.saml-domain.submit',+ SSO_SAML_ENTITY_ID_COPY = 'sso.saml-entity-id.copy',SSO_SAML_OPEN = 'sso.saml.open',TELEMETRY_DOCS_LINK = 'telemetry.docs.link',TELEMETRY_EVENTS_OPEN = 'telemetry.events.open',diff --git a/packages/web/test/app/routes/platform/security/sso/sso-page.test.tsx b/packages/web/test/app/routes/platform/security/sso/sso-page.test.tsxnew file mode 100644index 00000000000..3ac04be89dc--- /dev/null+++ b/packages/web/test/app/routes/platform/security/sso/sso-page.test.tsx@@ -0,0 +1,1247 @@+/**+ * @vitest-environment jsdom+ */+/* eslint-disable jest-dom/prefer-in-document, jest-dom/prefer-to-have-attribute -- @testing-library/jest-dom is not a dependency of packages/web */+import { SsoDomainVerificationStatus } from '@activepieces/shared';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from '@testing-library/react';+import * as React from 'react';+import { MemoryRouter, Route, Routes } from 'react-router-dom';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const {+ toastMock,+ platformApiMock,+ samlSsoApiMock,+ platformState,+ refetchMock,+ flagState,+} = vi.hoisted(() => {+ function initialFlagState(): {+ edition: string;+ thirdPartyProviders: Record<string, boolean>;+ } {+ return { edition: 'ee', thirdPartyProviders: { google: false } };+ }+ const state: { current: Record<string, unknown> } = { current: {} };+ return {+ flagState: initialFlagState(),+ toastMock: { success: vi.fn(), error: vi.fn(), message: vi.fn() },+ platformApiMock: { update: vi.fn() },+ samlSsoApiMock: {+ discover: vi.fn(),+ updateSsoDomain: vi.fn(),+ verifySsoDomain: vi.fn(),+ },+ platformState: state,+ refetchMock: vi.fn(async () => undefined),+ };+});++vi.mock('i18next', () => ({+ t: (key: string, values?: Record<string, string>) =>+ Object.entries(values ?? {}).reduce(+ (text, [name, value]) => text.replace(`{${name}}`, value),+ key,+ ),+}));++vi.mock('sonner', () => ({ toast: toastMock }));++vi.mock('@/lib/api', () => ({+ api: {+ extractServerErrorMessage: (error: unknown, fallback: string) =>+ error instanceof Error ? error.message : fallback,+ },+}));++vi.mock('@/api/platforms-api', () => ({ platformApi: platformApiMock }));++vi.mock('@/features/platform-admin/api/saml-sso-api', () => ({+ samlSsoApi: samlSsoApiMock,+}));++vi.mock('@/hooks/platform-hooks', () => ({+ platformHooks: {+ useCurrentPlatform: () => ({+ platform: platformState.current,+ refetch: refetchMock,+ }),+ },+}));++vi.mock('@/hooks/flags-hooks', () => ({+ flagsHooks: {+ queryKey: ['flags'],+ useFlag: (id: string) => ({+ data:+ id === 'EDITION'+ ? flagState.edition+ : id === 'THIRD_PARTY_AUTH_PROVIDERS_TO_SHOW_MAP'+ ? flagState.thirdPartyProviders+ : 'https://cloud.test/acs',+ }),+ },+}));++vi.mock('@/components/ui/dropdown-menu', () => ({+ DropdownMenu: ({ children }: React.PropsWithChildren) => <>{children}</>,+ DropdownMenuTrigger: ({ children }: React.PropsWithChildren) => (+ <>{children}</>+ ),+ DropdownMenuContent: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DropdownMenuSeparator: () => <hr />,+ DropdownMenuItem: ({+ children,+ onSelect,+ disabled,+ }: React.PropsWithChildren<{+ onSelect?: (event: { preventDefault: () => void }) => void;+ disabled?: boolean;+ variant?: string;+ }>) => (+ <div+ role="menuitem"+ aria-disabled={disabled}+ onClick={() => onSelect?.({ preventDefault: () => undefined })}+ >+ {children}+ </div>+ ),+}));++vi.mock('@/components/ui/dialog', async () => {+ const { createContext, useContext } = await import('react');+ const DialogContext = createContext<{+ open: boolean;+ onOpenChange: (open: boolean) => void;+ }>({ open: false, onOpenChange: () => undefined });+ return {+ Dialog: ({+ children,+ open,+ onOpenChange,+ }: React.PropsWithChildren<{+ open: boolean;+ onOpenChange: (open: boolean) => void;+ }>) => (+ <DialogContext.Provider value={{ open, onOpenChange }}>+ {children}+ </DialogContext.Provider>+ ),+ DialogTrigger: ({ children }: React.PropsWithChildren) => {+ const { onOpenChange } = useContext(DialogContext);+ return <span onClick={() => onOpenChange(true)}>{children}</span>;+ },+ DialogContent: ({ children }: React.PropsWithChildren) => {+ const { open } = useContext(DialogContext);+ return open ? <div role="dialog">{children}</div> : null;+ },+ DialogHeader: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DialogTitle: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DialogDescription: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ DialogFooter: ({ children }: React.PropsWithChildren) => (+ <div>{children}</div>+ ),+ };+});++vi.mock('@/components/ui/button', () => ({+ Button: ({+ children,+ asChild: _asChild,+ variant: _variant,+ size: _size,+ loading: _loading,+ ...props+ }: React.ComponentProps<'button'> & {+ asChild?: boolean;+ variant?: string;+ size?: string;+ loading?: boolean;+ }) => (+ <button type="button" {...props}>+ {children}+ </button>+ ),+}));++import { SSOPage } from '@/app/routes/platform/security/sso';+import { SamlSetupPage } from '@/app/routes/platform/security/sso/saml-setup-page';++const pendingVerification = {+ status: SsoDomainVerificationStatus.PENDING_VERIFICATION,+ record: { type: 'TXT', name: '_activepieces.acme.com', value: 'ap-verify=1' },+ createdAt: '2026-10-14T00:00:00.000Z',+};++const verifiedVerification = {+ ...pendingVerification,+ status: SsoDomainVerificationStatus.VERIFIED,+};++const samlConfig = { idpMetadata: '<xml />', idpCertificate: 'cert' };++describe('SSOPage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ platformApiMock.update.mockResolvedValue(undefined);+ samlSsoApiMock.updateSsoDomain.mockResolvedValue({+ ssoDomain: null,+ ssoDomainVerification: null,+ });+ setPlatform({});+ flagState.edition = 'ee';+ flagState.thirdPartyProviders = { google: false };+ });++ it('shows the empty states when nothing is set up', () => {+ mount();++ expect(screen.getByText('Authentication')).toBeDefined();+ expect(screen.getByText('No domain verified')).toBeDefined();+ expect(screen.getByText('No allowed domains')).toBeDefined();+ expect(findButton('Set up')).toBeDefined();+ expect(screen.queryByText('Connected')).toBeNull();+ });++ it('starts verifying a domain from its own dialog, not the SAML walkthrough', async () => {+ mount();++ click(findButton('Verify domain'));+ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('Verify a domain')).toBeDefined();+ fireEvent.change(within(dialog).getByRole('textbox'), {+ target: { value: ' Acme.com ' },+ });+ await waitFor(() =>+ expect(findButton('Continue', dialog)?.disabled).toBe(false),+ );+ click(findButton('Continue', dialog));++ await waitFor(() =>+ expect(samlSsoApiMock.updateSsoDomain).toHaveBeenCalledWith('acme.com'),+ );+ });++ it('shows a domain being verified and continues verifying from its menu', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: pendingVerification,+ });+ samlSsoApiMock.verifySsoDomain.mockResolvedValue({+ ssoDomain: 'acme.com',+ ssoDomainVerification: pendingVerification,+ });+ mount();++ expect(screen.getByText('acme.com')).toBeDefined();+ expect(screen.getByText('Verifying')).toBeDefined();+ click(menuItem('Continue verifying'));+ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('Verify acme.com')).toBeDefined();+ expect(within(dialog).getByText('Verify later')).toBeDefined();+ click(findButton('Verify DNS', dialog));++ await waitFor(() =>+ expect(samlSsoApiMock.verifySsoDomain).toHaveBeenCalledTimes(1),+ );+ await waitFor(() =>+ expect(toastMock.message).toHaveBeenCalledWith(+ 'TXT record not found yet — DNS can take a few minutes.',+ ),+ );+ });++ it('cancels a verification in progress', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: pendingVerification,+ });+ mount();++ click(menuItem('Cancel verification'));+ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByText('Cancel verifying acme.com?'),+ ).toBeDefined();+ click(findButton('Cancel verification', dialog));++ await waitFor(() =>+ expect(samlSsoApiMock.updateSsoDomain).toHaveBeenCalledWith(null),+ );+ });++ it('shows a verified domain without the DNS check', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mount();++ expect(screen.getByText('Verified')).toBeDefined();+ expect(screen.queryByText('Check DNS again')).toBeNull();+ });++ it('shows the TXT record from the domain menu', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mount();++ click(menuItem('View DNS record'));++ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('DNS record for acme.com')).toBeDefined();+ expect(within(dialog).getByDisplayValue('ap-verify=1')).toBeDefined();+ });++ it('removes the domain and turns off single sign-on in one request', async () => {+ setPlatform({+ id: 'platform-1',+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ });+ mount();++ click(menuItem('Remove domain'));+ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByText(+ 'Remove acme.com and delete your SAML connection?',+ ),+ ).toBeDefined();+ expect(+ within(dialog).getByText(+ 'This disables single sign-on and deletes its SAML connection.',+ ),+ ).toBeDefined();+ expect(findButton('Remove domain and disable SAML', dialog)?.disabled).toBe(+ true,+ );+ typeToConfirm(dialog, 'acme.com');+ click(findButton('Remove domain and disable SAML', dialog));++ await waitFor(() =>+ expect(samlSsoApiMock.updateSsoDomain).toHaveBeenCalledWith(null),+ );+ expect(samlSsoApiMock.updateSsoDomain).toHaveBeenCalledTimes(1);+ expect(platformApiMock.update).not.toHaveBeenCalled();+ });++ it('warns that no other sign-in method is on before removing a domain with SAML connected', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ emailAuthEnabled: false,+ });+ mount();++ click(menuItem('Remove domain'));++ expect(+ within(screen.getByRole('dialog')).getByText(+ "You can't do this while single sign-on is the only way to sign in. Turn on email or Google sign-in first.",+ ),+ ).toBeDefined();+ });++ it('blocks removing the domain when SAML is the only working sign-in method', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ emailAuthEnabled: false,+ });+ mount();++ click(menuItem('Remove domain'));+ const dialog = screen.getByRole('dialog');++ expect(+ within(dialog).queryByLabelText('Type acme.com to confirm'),+ ).toBeNull();+ expect(findButton('Remove domain and disable SAML', dialog)?.disabled).toBe(+ true,+ );+ });++ it('does not warn about other sign-in methods while Google sign-in is on', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ emailAuthEnabled: false,+ googleAuthEnabled: true,+ });+ flagState.thirdPartyProviders = { google: true };+ mount();++ click(menuItem('Remove domain'));++ expect(+ within(screen.getByRole('dialog')).queryByText(+ "You can't do this while single sign-on is the only way to sign in. Turn on email or Google sign-in first.",+ ),+ ).toBeNull();+ });++ it('still warns when the Google switch is on but Google sign-in is not set up', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ emailAuthEnabled: false,+ googleAuthEnabled: true,+ });+ mount();++ click(menuItem('Remove domain'));++ expect(+ within(screen.getByRole('dialog')).getByText(+ "You can't do this while single sign-on is the only way to sign in. Turn on email or Google sign-in first.",+ ),+ ).toBeDefined();+ });++ it('drops the add-your-company-domain hint once the company domain is listed', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ allowedAuthDomains: ['acme.com', 'contractors.io'],+ });+ mount();++ expect(+ screen.queryByText(+ "Add your company domain too, or people at your company can't join or sign in with email and password.",+ ),+ ).toBeNull();+ });++ it('shows the server error when removing the domain fails', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ });+ samlSsoApiMock.updateSsoDomain.mockRejectedValue(+ new Error('Request failed'),+ );+ mount();++ click(menuItem('Remove domain'));+ typeToConfirm(screen.getByRole('dialog'), 'acme.com');+ click(+ findButton('Remove domain and disable SAML', screen.getByRole('dialog')),+ );++ await waitFor(() =>+ expect(toastMock.error).toHaveBeenCalledWith('Request failed'),+ );+ });++ it('removes a domain that has no SAML connection', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mount();++ click(menuItem('Remove domain'));+ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByText(+ "To set up single sign-on later, you'll need to verify the domain again with a new DNS record.",+ ),+ ).toBeDefined();+ typeToConfirm(dialog, 'acme.com');+ click(findButton('Remove domain', dialog));++ await waitFor(() =>+ expect(samlSsoApiMock.updateSsoDomain).toHaveBeenCalledWith(null),+ );+ expect(platformApiMock.update).not.toHaveBeenCalled();+ });++ it('shows a connected SAML provider as Manage', () => {+ setPlatform({ federatedAuthProviders: { saml: samlConfig } });+ mount();++ expect(screen.getByText('Connected')).toBeDefined();+ expect(findButton('Manage')).toBeDefined();+ });++ it('asks before turning Google off and email on, then sends the same requests as before', async () => {+ setPlatform({+ id: 'platform-1',+ googleAuthEnabled: true,+ emailAuthEnabled: false,+ });+ mount();++ click(screen.getByRole('switch', { name: 'Continue with Google' }));+ expect(platformApiMock.update).not.toHaveBeenCalled();+ let dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('Turn off Google sign-in?')).toBeDefined();+ click(findButton('Turn off', dialog));+ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ { googleAuthEnabled: false },+ 'platform-1',+ ),+ );++ click(screen.getByRole('switch', { name: 'Email and password' }));+ dialog = await screen.findByRole('dialog');+ expect(within(dialog).getByText('Turn on email sign-in?')).toBeDefined();+ click(findButton('Turn on', dialog));+ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ { emailAuthEnabled: true },+ 'platform-1',+ ),+ );+ });++ it('refreshes the flags after changing Google so the sign-in checks use the new state', async () => {+ const invalidate = vi.spyOn(QueryClient.prototype, 'invalidateQueries');+ setPlatform({ id: 'platform-1' });+ mount();++ click(screen.getByRole('switch', { name: 'Continue with Google' }));+ click(findButton('Turn on', screen.getByRole('dialog')));++ await waitFor(() =>+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ['flags'] }),+ );+ invalidate.mockRestore();+ });++ it('says Google is not set up on a self-hosted server without Google credentials', () => {+ setPlatform({ googleAuthEnabled: true });+ mount();++ expect(screen.getByText('Not set up')).toBeDefined();+ expect(+ screen.getByText('Needs a Google OAuth client on this server.'),+ ).toBeDefined();+ expect(+ screen.getByRole('link', { name: 'Setup guide' }).getAttribute('href'),+ ).toBe('https://www.activepieces.com/docs/admin-guide/guides/sso#google');+ });++ it('shows no Google note once Google sign-in works', () => {+ setPlatform({ googleAuthEnabled: true });+ flagState.thirdPartyProviders = { google: true };+ mount();++ expect(screen.queryByText('Not set up')).toBeNull();+ });++ it('never shows the Google note on Cloud', () => {+ flagState.edition = 'cloud';+ setPlatform({ googleAuthEnabled: true });+ mount();++ expect(screen.queryByText('Not set up')).toBeNull();+ });++ it('says what self-hosted needs when turning Google on', () => {+ mount();+ click(screen.getByRole('switch', { name: 'Continue with Google' }));+ expect(+ within(screen.getByRole('dialog')).getByText(+ 'On a self-hosted server it also needs a Google OAuth client.',+ { exact: false },+ ),+ ).toBeDefined();+ });++ it('does not mention self-hosted setup when turning Google on in Cloud', () => {+ flagState.edition = 'cloud';+ mount();+ click(screen.getByRole('switch', { name: 'Continue with Google' }));+ expect(+ within(screen.getByRole('dialog')).queryByText(+ 'On a self-hosted server it also needs a Google OAuth client.',+ { exact: false },+ ),+ ).toBeNull();+ });++ it('blocks turning email off when it is the last working sign-in method', () => {+ setPlatform({ emailAuthEnabled: true, googleAuthEnabled: true });+ mount();++ click(screen.getByRole('switch', { name: 'Email and password' }));+ const dialog = screen.getByRole('dialog');++ expect(+ within(dialog).getByText(+ "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.",+ ),+ ).toBeDefined();+ expect(findButton('Turn off', dialog)?.disabled).toBe(true);+ });++ it('lets email be turned off when single sign-on is connected', () => {+ setPlatform({+ emailAuthEnabled: true,+ federatedAuthProviders: { saml: samlConfig },+ });+ mount();++ click(screen.getByRole('switch', { name: 'Email and password' }));+ const dialog = screen.getByRole('dialog');++ expect(+ within(dialog).queryByText(+ "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.",+ ),+ ).toBeNull();+ expect(findButton('Turn off', dialog)?.disabled).toBe(false);+ });++ it('lets email be turned off when Google sign-in works', () => {+ setPlatform({ emailAuthEnabled: true, googleAuthEnabled: true });+ flagState.thirdPartyProviders = { google: true };+ mount();++ click(screen.getByRole('switch', { name: 'Email and password' }));++ expect(findButton('Turn off', screen.getByRole('dialog'))?.disabled).toBe(+ false,+ );+ });++ it('blocks turning Google off when it works and is the last sign-in method', () => {+ setPlatform({ emailAuthEnabled: false, googleAuthEnabled: true });+ flagState.thirdPartyProviders = { google: true };+ mount();++ click(screen.getByRole('switch', { name: 'Continue with Google' }));+ const dialog = screen.getByRole('dialog');++ expect(+ within(dialog).getByText(+ "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.",+ ),+ ).toBeDefined();+ expect(findButton('Turn off', dialog)?.disabled).toBe(true);+ });++ it('lets Google be turned off when it does not actually work', () => {+ setPlatform({ emailAuthEnabled: false, googleAuthEnabled: true });+ mount();++ click(screen.getByRole('switch', { name: 'Continue with Google' }));+ const dialog = screen.getByRole('dialog');++ expect(+ within(dialog).queryByText(+ "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.",+ ),+ ).toBeNull();+ expect(findButton('Turn off', dialog)?.disabled).toBe(false);+ });++ it('does not count single sign-on as working on Cloud without a verified domain', () => {+ flagState.edition = 'cloud';+ setPlatform({+ emailAuthEnabled: true,+ federatedAuthProviders: { saml: samlConfig },+ });+ mount();++ click(screen.getByRole('switch', { name: 'Email and password' }));++ expect(+ within(screen.getByRole('dialog')).getByText(+ "You can't turn this off while it's the only way to sign in. Turn on another sign-in method first.",+ ),+ ).toBeDefined();+ });++ it('shows no Google note while the edition is still loading', () => {+ flagState.edition = '';+ setPlatform({ googleAuthEnabled: true });+ mount();++ expect(screen.queryByText('Not set up')).toBeNull();+ });++ it('changes nothing when a method change is cancelled', () => {+ setPlatform({ emailAuthEnabled: true });+ mount();++ click(screen.getByRole('switch', { name: 'Email and password' }));+ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByText(+ 'People can no longer sign in with email and password.',+ ),+ ).toBeDefined();+ click(findButton('Cancel', dialog));++ expect(screen.queryByRole('dialog')).toBeNull();+ expect(platformApiMock.update).not.toHaveBeenCalled();+ });++ it('says on self-hosted that allowed domains also limit who can join', () => {+ mount();++ expect(+ screen.getByText(+ 'Limit who can join, and who can sign in with email and password, to the domains you add.',+ ),+ ).toBeDefined();+ expect(+ screen.getByText(+ 'Anyone can join or sign in with email and password until you add a domain.',+ ),+ ).toBeDefined();+ });++ it('says on Cloud that allowed domains limit email and password sign-in only', () => {+ flagState.edition = 'cloud';+ setPlatform({ allowedAuthDomains: ['contractors.io', 'partners.io'] });+ mount();++ expect(+ screen.getByText(+ 'Limit email and password sign-in to the domains you add.',+ ),+ ).toBeDefined();+ expect(+ screen.getByText(+ "Add your company domain too, or people at your company can't sign in with email and password.",+ ),+ ).toBeDefined();+ expect(screen.queryByText(/join/)).toBeNull();++ click(menuItem('Remove domain'));+ expect(+ within(screen.getByRole('dialog')).getByText(+ 'People at contractors.io can no longer sign in with email and password.',+ ),+ ).toBeDefined();+ });++ it('describes adding the first allowed domain on Cloud without mentioning joining', () => {+ flagState.edition = 'cloud';+ mount();++ click(findButton('Add domain'));+ expect(+ within(screen.getByRole('dialog')).getByText(+ 'Once a domain is on this list, only people at listed domains can sign in with email and password. Add your company domain too.',+ ),+ ).toBeDefined();+ });++ it('removes one allowed domain and keeps the list enforced', async () => {+ setPlatform({+ id: 'platform-1',+ allowedAuthDomains: ['contractors.io', 'partners.io'],+ });+ mount();++ expect(screen.getByText('contractors.io')).toBeDefined();+ click(menuItem('Remove domain'));+ click(findButton('Remove domain', screen.getByRole('dialog')));++ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ {+ allowedAuthDomains: ['partners.io'],+ enforceAllowedAuthDomains: true,+ },+ 'platform-1',+ ),+ );+ });++ it('stops enforcing the list when the last allowed domain is removed', async () => {+ setPlatform({ id: 'platform-1', allowedAuthDomains: ['contractors.io'] });+ mount();++ click(menuItem('Remove domain'));+ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByText(+ 'With no domains left, anyone can join or sign in with email and password.',+ ),+ ).toBeDefined();+ click(findButton('Remove domain', dialog));++ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ { allowedAuthDomains: [], enforceAllowedAuthDomains: false },+ 'platform-1',+ ),+ );+ });++ it('adds the first allowed domain in one step and warns to add your company domain', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mount();++ click(findButton('Add domain'));+ const dialog = screen.getByRole('dialog');+ expect(+ within(dialog).getByText(+ 'Once a domain is on this list, only people at listed domains can join or sign in with email and password. Add your company domain too.',+ ),+ ).toBeDefined();+ fireEvent.change(within(dialog).getByLabelText('Domain'), {+ target: { value: ' Contractors.IO ' },+ });+ await submitWhenValid(dialog);++ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ {+ allowedAuthDomains: ['contractors.io'],+ enforceAllowedAuthDomains: true,+ },+ 'platform-1',+ ),+ );+ });++ it('appends a allowed domain to the existing list', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ allowedAuthDomains: ['contractors.io'],+ });+ mount();++ click(findButton('Add domain'));+ const dialog = screen.getByRole('dialog');+ fireEvent.change(within(dialog).getByRole('textbox'), {+ target: { value: 'partners.io' },+ });+ await submitWhenValid(dialog);++ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ {+ allowedAuthDomains: ['contractors.io', 'partners.io'],+ enforceAllowedAuthDomains: true,+ },+ 'platform-1',+ ),+ );+ });++ it('refuses a allowed domain that is already on the list', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ allowedAuthDomains: ['contractors.io'],+ });+ mount();++ click(findButton('Add domain'));+ const dialog = screen.getByRole('dialog');+ fireEvent.change(within(dialog).getByRole('textbox'), {+ target: { value: 'contractors.io' },+ });++ expect(await within(dialog).findByText('duplicateDomain')).toBeDefined();+ expect(findButton('Add domain', dialog)?.disabled).toBe(true);+ });+});++describe('SamlSetupPage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ platformApiMock.update.mockResolvedValue(undefined);+ setPlatform({});+ flagState.edition = 'ee';+ flagState.thirdPartyProviders = { google: false };+ });++ it('is opened from the sign-in methods row as a page, not a dialog', () => {+ mount();++ expect(+ screen.getByRole('link', { name: 'Set up' }).getAttribute('href'),+ ).toBe('/platform/sso/saml');+ });++ it('saves the SAML connection with the same request as before and returns to Authentication', async () => {+ setPlatform({+ id: 'platform-1',+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mountSetupPage();++ fireEvent.change(screen.getByLabelText('IDP Metadata'), {+ target: { value: '<xml />' },+ });+ fireEvent.change(screen.getByLabelText('IDP Certificate'), {+ target: { value: 'cert' },+ });+ await waitFor(() => expect(findButton('Save')?.disabled).toBe(false));+ click(findButton('Save'));++ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ {+ federatedAuthProviders: {+ saml: { idpMetadata: '<xml />', idpCertificate: 'cert' },+ },+ },+ 'platform-1',+ ),+ );+ expect(await screen.findByText('authentication page')).toBeDefined();+ });++ it('shows the server error when saving the SAML connection fails', async () => {+ platformApiMock.update.mockRejectedValue(+ new Error('SSO domain must be verified before configuring SAML'),+ );+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mountSetupPage();++ fireEvent.change(screen.getByLabelText('IDP Metadata'), {+ target: { value: '<xml />' },+ });+ fireEvent.change(screen.getByLabelText('IDP Certificate'), {+ target: { value: 'cert' },+ });+ await waitFor(() => expect(findButton('Save')?.disabled).toBe(false));+ click(findButton('Save'));++ expect(+ await screen.findByText(+ 'SSO domain must be verified before configuring SAML',+ ),+ ).toBeDefined();+ });++ it('offers Disable on the SAML step only, and disables after confirming', async () => {+ setPlatform({+ id: 'platform-1',+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ });+ mountSetupPage();++ expect(+ screen+ .getByRole('button', { name: '2 SAML 2.0' })+ .getAttribute('aria-current'),+ ).toBe('step');+ expect(screen.getByText('Disable single sign-on')).toBeDefined();+ click(findButton('1SSO Domain'));+ expect(screen.queryByText('Disable single sign-on')).toBeNull();+ click(findButton('2SAML 2.0'));+ click(findButton('Disable'));+ expect(platformApiMock.update).not.toHaveBeenCalled();+ const dialog = screen.getByRole('dialog');+ expect(within(dialog).getByText('Disable single sign-on?')).toBeDefined();+ expect(findButton('Disable', dialog)?.disabled).toBe(true);+ fireEvent.change(within(dialog).getByLabelText('Type disable to confirm'), {+ target: { value: 'Disable' },+ });+ expect(findButton('Disable', dialog)?.disabled).toBe(true);+ fireEvent.change(within(dialog).getByLabelText('Type disable to confirm'), {+ target: { value: 'disable' },+ });+ click(findButton('Disable', dialog));++ await waitFor(() =>+ expect(platformApiMock.update).toHaveBeenCalledWith(+ { federatedAuthProviders: { saml: null } },+ 'platform-1',+ ),+ );+ expect(await screen.findByText('authentication page')).toBeDefined();+ });++ it('clears the typed confirmation when the Disable dialog is cancelled', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ });+ mountSetupPage();++ click(findButton('Disable'));+ typeToConfirm(screen.getByRole('dialog'), 'disable');+ click(findButton('Cancel', screen.getByRole('dialog')));+ click(findButton('Disable'));++ expect(findButton('Disable', screen.getByRole('dialog'))?.disabled).toBe(+ true,+ );+ });++ it('blocks disabling single sign-on when it is the only working sign-in method', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ emailAuthEnabled: false,+ });+ mountSetupPage();++ click(findButton('Disable'));+ const dialog = screen.getByRole('dialog');++ expect(+ within(dialog).queryByLabelText('Type disable to confirm'),+ ).toBeNull();+ expect(findButton('Disable', dialog)?.disabled).toBe(true);+ });+ it('shows no Disable when SAML is not connected', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mountSetupPage();++ expect(findButton('Disable')).toBeUndefined();+ expect(screen.queryByText('Disable single sign-on')).toBeNull();+ });++ it('shows the domain read-only on the first step', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ });+ mountSetupPage();++ expect(screen.getByText('acme.com')).toBeDefined();+ expect(screen.queryByDisplayValue('acme.com')).toBeNull();+ expect(findButton('Next')).toBeDefined();+ });++ it('names the domain being verified in the walkthrough', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: pendingVerification,+ });+ mountSetupPage();++ expect(screen.getByText('Verify acme.com')).toBeDefined();+ expect(screen.getByDisplayValue('_activepieces.acme.com')).toBeDefined();+ });++ it('verifies a domain inside the walkthrough when there is none yet', async () => {+ mountSetupPage();++ fireEvent.change(screen.getByLabelText('Domain'), {+ target: { value: 'acme.com' },+ });+ await waitFor(() => expect(findButton('Continue')?.disabled).toBe(false));+ click(findButton('Continue'));++ await waitFor(() =>+ expect(samlSsoApiMock.updateSsoDomain).toHaveBeenCalledWith('acme.com'),+ );+ });++ it('keeps the SAML step locked until the domain is verified', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: pendingVerification,+ });+ mountSetupPage();++ expect(findButton('Next')?.disabled).toBe(true);+ expect(findButton('Verify DNS')?.disabled).toBe(false);+ expect(findButton('2SAML 2.0')?.disabled).toBe(true);+ });++ it('opens the SAML step while the domain is pending when SAML is already connected', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: pendingVerification,+ federatedAuthProviders: { saml: {} },+ });+ mountSetupPage();++ expect(findButton('2SAML 2.0')?.disabled).toBe(false);+ click(findButton('Next'));+ expect(+ screen+ .getByRole('button', { name: '2 SAML 2.0' })+ .getAttribute('aria-current'),+ ).toBe('step');+ expect(findButton('Save')?.disabled).toBe(true);+ });++ it('moves between steps from the step labels', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mountSetupPage();++ click(findButton('1SSO Domain'));+ expect(+ screen+ .getByRole('button', { name: '1 SSO Domain' })+ .getAttribute('aria-current'),+ ).toBe('step');+ click(findButton('2SAML 2.0'));+ expect(+ screen+ .getByRole('button', { name: '2 SAML 2.0' })+ .getAttribute('aria-current'),+ ).toBe('step');+ });++ it('shows the values to copy into the identity provider', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mountSetupPage();++ expect(screen.getByDisplayValue('https://cloud.test/acs')).toBeDefined();+ expect(screen.getByDisplayValue('Activepieces')).toBeDefined();+ });++ it('says a cleared SAML field is required', async () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ });+ mountSetupPage();++ const metadata = screen.getByLabelText('IDP Metadata');+ fireEvent.change(metadata, { target: { value: 'x' } });+ fireEvent.change(metadata, { target: { value: '' } });++ const error = await screen.findByText('required');+ await waitFor(() =>+ expect(metadata.getAttribute('aria-invalid')).toBe('true'),+ );+ expect(metadata.getAttribute('aria-describedby')).toContain(error.id);+ });++ it('says the SAML values are saved instead of looking empty', () => {+ setPlatform({+ ssoDomain: 'acme.com',+ ssoDomainVerification: verifiedVerification,+ federatedAuthProviders: { saml: samlConfig },+ });+ mountSetupPage();++ expect(+ screen.getByText('To change the connection, paste both values again.'),+ ).toBeDefined();++ expect(+ screen.getByLabelText('IDP Metadata').getAttribute('placeholder'),+ ).toBe('Saved. Paste new metadata to replace it.');+ expect(+ screen.getByLabelText('IDP Certificate').getAttribute('placeholder'),+ ).toBe('Saved. Paste a new certificate to replace it.');+ });+});++async function submitWhenValid(dialog: HTMLElement) {+ await waitFor(() =>+ expect(findButton('Add domain', dialog)?.disabled).toBe(false),+ );+ click(findButton('Add domain', dialog));+}++function typeToConfirm(dialog: HTMLElement, text: string) {+ fireEvent.change(within(dialog).getByLabelText(`Type ${text} to confirm`), {+ target: { value: text },+ });+}++function setPlatform(overrides: Record<string, unknown>) {+ platformState.current = {+ id: 'platform-1',+ ssoDomain: null,+ ssoDomainVerification: null,+ federatedAuthProviders: {},+ googleAuthEnabled: false,+ emailAuthEnabled: true,+ allowedAuthDomains: [],+ ...overrides,+ };+}++function mount() {+ render(+ <MemoryRouter>+ <QueryClientProvider client={new QueryClient()}>+ <SSOPage />+ </QueryClientProvider>+ </MemoryRouter>,+ );+}++function mountSetupPage() {+ render(+ <MemoryRouter initialEntries={['/platform/sso/saml']}>+ <QueryClientProvider client={new QueryClient()}>+ <Routes>+ <Route+ path="/platform/sso"+ element={<div>authentication page</div>}+ />+ <Route path="/platform/sso/saml" element={<SamlSetupPage />} />+ </Routes>+ </QueryClientProvider>+ </MemoryRouter>,+ );+}++function click(element: Element | null | undefined) {+ if (!element) {+ throw new Error('element not found');+ }+ fireEvent.click(element);+}++function menuItem(text: string) {+ return screen+ .getAllByRole('menuitem')+ .find((item) => item.textContent === text);+}++function findButton(text: string, scope: ParentNode = document.body) {+ return Array.from(scope.querySelectorAll('button')).find(+ (button) => button.textContent === text,+ );+}