diff --git a/apps/landing/src/content/docs/reference/single-sign-on.md b/apps/landing/src/content/docs/reference/single-sign-on.md new file mode 100644 index 0000000000..21a4dcf2c8 --- /dev/null +++ b/apps/landing/src/content/docs/reference/single-sign-on.md @@ -0,0 +1,118 @@ +--- +title: "Single sign-on and SCIM provisioning" +description: "Sign in to Maple through your identity provider with SAML 2.0 or OIDC, verify your email domains, enforce SSO, and provision members, roles and deprovisioning with SCIM 2.0." +group: "Reference" +order: 11 +--- + +Single sign-on (SSO) lets members sign in to Maple through your identity provider (IdP). SCIM provisioning lets the IdP create, update and remove Maple members, and set their roles from IdP groups. + +Both are available on the Enterprise plan. Only organization admins can configure them, under **Settings → SSO & SCIM** in the dashboard. Every change is recorded in the organization's audit log, under **Security → Audit log**. + +SSO and SCIM work the same for organizations in the US and EU [regions](/docs/reference/regions). + +## Supported identity providers + +| Protocol | Identity providers | +| -------- | ------------------------------------------------------------------- | +| SAML 2.0 | Okta, Microsoft Entra ID, Google Workspace, any custom SAML 2.0 IdP | +| OIDC | GitHub Enterprise, GitLab, any OpenID Connect provider | + +## Set up single sign-on + +Setup has four steps. Until the last one, members keep signing in the way they do today. + +### 1. Verify a domain + +SSO applies to email addresses on domains you have verified. + +1. Under **Settings → SSO & SCIM**, add your domain, for example `example.com`. +2. Maple shows a value of the form `maple-domain-verification=...`. Publish it as a DNS TXT record named `_maple-challenge.example.com`. +3. Click **Verify**. + +DNS changes can take a few minutes to be visible. If verification fails, wait and try again. Add every domain your members sign in with. + +### 2. Connect your identity provider + +Choose SAML or OIDC and enter your IdP's details. + +**SAML 2.0** + +- In Maple, give the IdP metadata URL. If your IdP has no metadata URL, give its SSO URL, entity ID and signing certificate instead. +- In your IdP, create a SAML application and paste the values Maple shows: the ACS URL, and the SP entity ID or SP metadata URL. + +**OIDC** + +- In your IdP, create an OIDC application. +- In Maple, give the discovery URL, client ID and client secret. + +A new connection starts **not enforced**. Members who use the IdP can sign in through it, and everyone else can still sign in as before. Use this to test the connection with your own account. + +### 3. Add a break-glass admin + +Add at least one admin to the bypass list. Only members with a verified email on one of the connection's domains can be added. A member on this list can still sign in with an email code when the IdP is down or misconfigured, so you cannot lock the whole organization out. + +### 4. Enforce SSO + +Turn on enforcement. From then on, everyone who signs in with an email address on a verified domain must go through the IdP. The only exception is the bypass list. + +Existing members do not need to do anything in advance. On their next sign-in they go through the IdP, and their Maple account is linked to their IdP identity. + +## Set up SCIM provisioning + +SCIM needs a connected IdP. Once the connection from step 2 is in place, click **Set up SCIM**. Maple shows: + +- a SCIM 2.0 base URL +- a bearer token + +The token is shown once. Copy it before you close the dialog. + +Paste both into your IdP's provisioning settings: + +| IdP | Where | What to enter | +| ------------------ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- | +| Okta | **Provisioning → API integration** | The base URL and the token. Then enable **Create Users**, **Update User Attributes**, **Deactivate Users** and **Push Groups**. | +| Microsoft Entra ID | **Provisioning**, mode **Automatic** | The base URL as **Tenant URL** and the token as **Secret token**. | +| Other IdPs | The SCIM or provisioning settings | The base URL and the token as a bearer token. | + +Every provisioned user needs an email address on a verified domain. Users without one fail to provision. + +### Manage the SCIM connection + +- **Rotate token** issues a new token. The old token keeps working for a short grace period, so you can update the IdP without interrupting provisioning. +- **Pause** stops provisioning. Members already provisioned stay in the organization. +- **Remove** stops provisioning and removes the memberships that SCIM granted. Members who joined another way are not affected. + +## Map groups to roles + +Groups your IdP pushes appear in Maple under **Settings → SSO & SCIM**. Map each group to a Maple role: **Admin**, **Engineer**, **Member** or **Analyst**. + +- The order of the mappings sets precedence. A user in several mapped groups gets the role of the highest mapping in the list. +- A user in no mapped group gets the default **Member** role. +- A new or changed mapping applies the next time your IdP pushes the group. In Okta, open **Push Groups** and choose **Push now**; Entra ID applies it on its next provisioning cycle. +- A role assigned by a mapping follows the IdP. When the user's groups change in the IdP, their Maple role changes with them. + +Nested groups are not followed. Add users directly to the group you mapped. + +## Deprovisioning + +When you deactivate or remove a user in the IdP, Maple: + +- signs them out of every session +- removes the membership that SCIM granted +- revokes their Maple API keys, CLI credentials and device credentials + +## Troubleshooting + +| Problem | What to do | +| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Domain verification says the TXT record is not found | Wait a few minutes for DNS to update, then click **Verify** again. Check that the record is named `_maple-challenge.`, not the bare domain. | +| "Verify the domain before using it for SSO" | The domain is added but not verified yet. Finish [step 1](#1-verify-a-domain) first. | +| A user fails to provision | The user has no email address, or it is not on a verified domain. Set an email on a verified domain in the IdP, or verify that domain in Maple. | +| A user gets the Member role instead of a mapped role | Push the group again from your IdP after saving the mapping. If they are only in a group nested inside the mapped group, add them to the mapped group directly. | + +## Next steps + +- [Authentication](/docs/reference/authentication): the API keys and other credentials deprovisioning revokes +- [Regions](/docs/reference/regions): US and EU hosts +- [Audit log detections](/docs/alerting/alert-rules#audit-log-detections): alert on SSO and membership changes diff --git a/apps/web/src/lab/entries/sso.ts b/apps/web/src/lab/entries/sso.ts new file mode 100644 index 0000000000..a57b508b2a --- /dev/null +++ b/apps/web/src/lab/entries/sso.ts @@ -0,0 +1,16 @@ +import { defineShellLab } from "../shell-lab" +import { breadcrumbs, Flags, flags, init, Message, Model, update, view } from "../sso-lab" + +// `/lab/sso`: the settings SSO & SCIM tab over fixtures, its states and dialogs on demand (`?state=`). + +export const lab = defineShellLab("SSO & SCIM", { + Model, + Message, + Flags, + flags, + init, + update, + view, + currentPath: "/lab/sso", + breadcrumbs, +}) diff --git a/apps/web/src/lab/registry.ts b/apps/web/src/lab/registry.ts index 096714eb03..692bd252d3 100644 --- a/apps/web/src/lab/registry.ts +++ b/apps/web/src/lab/registry.ts @@ -93,6 +93,14 @@ export const LAB_ENTRIES: ReadonlyArray = [ kind: "lab", session: "none", }, + { + path: "/lab/sso", + title: "SSO & SCIM", + description: + "The settings SSO & SCIM tab: not entitled, empty, a pending domain, connected, fully configured, the one-time token, the enforce confirm and a read-only member (`?state=`).", + kind: "lab", + session: "none", + }, { path: "/lab/members", title: "Members", diff --git a/apps/web/src/lab/sso-lab.ts b/apps/web/src/lab/sso-lab.ts new file mode 100644 index 0000000000..1c34087851 --- /dev/null +++ b/apps/web/src/lab/sso-lab.ts @@ -0,0 +1,242 @@ +import { + EnterpriseSsoDocument, + IsoDateTimeString, + ScimDirectoryDocument, + ScimGroupDocument, + ScimRoleMappingDocument, + ScimTokenIssued, + SsoBypassUserDocument, + SsoConnectionDocument, + SsoDomainDocument, + UserId, +} from "@maple/domain/http" +import { Array as Arr, Effect, Option, Result, Schema } from "effect" +import { Command, type Update } from "foldkit" +import type { Html, HtmlBuilder } from "foldkit/html" +import { defineMessageUnion } from "foldkit/message" +import * as SsoModel from "../page/settings/sso/model" +import * as SsoUpdate from "../page/settings/sso/update" +import * as SsoView from "../page/settings/sso/view" +import type { Resources } from "../platform/resources" +import { keepLocal } from "./local-commands" + +// `/lab/sso`: the settings SSO & SCIM tab over fixtures. `?state=` picks one: not-entitled, empty, +// pending (a domain awaiting its TXT record), connected, configured, token, enforce, member. + +export const LabState = Schema.Literals([ + "not-entitled", + "empty", + "pending", + "connected", + "configured", + "token", + "enforce", + "member", +]) +export type LabState = typeof LabState.Type + +export const Flags = Schema.Struct({ state: LabState }) +export type Flags = typeof Flags.Type + +export const flags: Effect.Effect = Effect.sync(() => ({ + state: Option.getOrElse( + Schema.decodeUnknownOption(LabState)(new URLSearchParams(window.location.search).get("state")), + (): LabState => "configured", + ), +})) + +export const Model = Schema.Struct({ sso: SsoModel.Model }) +export type Model = typeof Model.Type + +export const Message = defineMessageUnion({ GotSsoMessage: { message: SsoModel.Message } }) +export type Message = typeof Message.Type + +type Return = Update.Return + +const iso = Schema.decodeSync(IsoDateTimeString) +const userId = Schema.decodeSync(UserId) + +const pendingDomain = new SsoDomainDocument({ + domain: "acmelabs.io", + status: "pending", + recordName: "_maple-challenge.acmelabs.io", + recordValue: "maple-domain-verification=3f9c2a71d04b4e8e9a6b51c07d2e8f14", + verifiedAt: null, +}) +const verifiedDomain = new SsoDomainDocument({ + domain: "acme.com", + status: "verified", + recordName: "_maple-challenge.acme.com", + recordValue: "maple-domain-verification=91b0c4d2e7f84a3b8c5d6e7f9a0b1c2d", + verifiedAt: iso("2026-11-14T09:12:00.000Z"), +}) + +const connection = (enforced: boolean) => + new SsoConnectionDocument({ + name: "Acme Okta", + provider: "saml_okta", + protocol: "saml", + domains: ["acme.com"], + enforced, + acsUrl: "https://clerk.maple.dev/v1/saml/acs/samlc_2xAcmeOkta", + spEntityId: "https://clerk.maple.dev/saml/samlc_2xAcmeOkta", + spMetadataUrl: "https://clerk.maple.dev/v1/saml/metadata/samlc_2xAcmeOkta", + idpMetadataUrl: "https://acme.okta.com/app/exk1a2b3c4/sso/saml/metadata", + idpSsoUrl: null, + idpEntityId: null, + idpCertificateExpiresAt: iso("2029-03-01T00:00:00.000Z"), + oidcDiscoveryUrl: null, + oidcClientId: null, + createdAt: iso("2026-11-14T09:20:00.000Z"), + }) + +const directory = new ScimDirectoryDocument({ + endpointUrl: "https://api.clerk.com/scim/v2", + enabled: true, + paused: false, + createdAt: iso("2026-11-14T09:30:00.000Z"), +}) + +const groups = [ + new ScimGroupDocument({ groupId: "grp_eng", displayName: "Engineering" }), + new ScimGroupDocument({ groupId: "grp_fin", displayName: "Finance" }), + new ScimGroupDocument({ groupId: "grp_it", displayName: "IT Admins" }), + new ScimGroupDocument({ groupId: "grp_sre", displayName: "SRE" }), +] + +const bypass = [new SsoBypassUserDocument({ userId: userId("user_ada"), identifier: "ada@acme.com" })] + +const documentOf = (state: LabState): EnterpriseSsoDocument => { + const base = { + entitled: true, + domains: [] as Array, + connection: null, + directory: null, + roleMappings: [] as Array, + groups: [] as Array, + bypassUsers: [] as Array, + } + switch (state) { + case "not-entitled": + return new EnterpriseSsoDocument({ ...base, entitled: false }) + case "empty": + return new EnterpriseSsoDocument(base) + case "pending": + return new EnterpriseSsoDocument({ ...base, domains: [verifiedDomain, pendingDomain] }) + case "connected": + case "enforce": + return new EnterpriseSsoDocument({ + ...base, + domains: [verifiedDomain, pendingDomain], + connection: connection(false), + bypassUsers: bypass, + }) + case "configured": + case "token": + case "member": + return new EnterpriseSsoDocument({ + ...base, + domains: [verifiedDomain], + connection: connection(true), + directory, + groups, + bypassUsers: bypass, + roleMappings: [ + new ScimRoleMappingDocument({ + groupId: "grp_it", + groupName: "IT Admins", + role: "org:admin", + }), + new ScimRoleMappingDocument({ + groupId: "grp_sre", + groupName: "SRE", + role: "org:engineer", + }), + new ScimRoleMappingDocument({ + groupId: "grp_eng", + groupName: "Engineering", + role: "org:member", + }), + new ScimRoleMappingDocument({ + groupId: "grp_fin", + groupName: "Finance", + role: "org:analyst", + }), + ], + }) + } +} + +const MEMBERS: ReadonlyArray = [ + { userId: "user_ada", name: "Ada Lovelace", identifier: "ada@acme.com" }, + { userId: "user_grace", name: "Grace Hopper", identifier: "grace@acme.com" }, + { userId: "user_linus", name: "Linus Contractor", identifier: "linus@gmail.com" }, +] + +const step = (model: SsoModel.Model, message: SsoModel.Message): SsoModel.Model => + SsoUpdate.update(model, message).model + +export const init = (flags: Flags): Return => { + const document = documentOf(flags.state) + const loaded = Arr.reduce( + [ + SsoModel.Message.CompletedFetchDocument({ result: Result.succeed(document) }), + SsoModel.Message.CompletedFetchMembers({ result: Result.succeed(MEMBERS) }), + ], + SsoUpdate.init(flags.state !== "member").model, + step, + ) + const opening = + flags.state === "token" + ? SsoModel.Message.CompletedIssueToken({ + action: "rotateToken", + result: Result.succeed( + new ScimTokenIssued({ + document, + token: "scim_live_7Qm2c9VxR4tLpZ8aKfJ3wY6nB1hD5sE0", + }), + ), + }) + : flags.state === "enforce" + ? SsoModel.Message.ToggledEnforcement() + : null + if (opening === null) return { model: { sso: loaded } } + // The dialog's open commands run, so it mounts as it would from a click. + const opened = SsoUpdate.update(loaded, opening) + return { + model: { sso: opened.model }, + commands: Command.mapMessages(keepLocal(opened.commands), (message) => + Message.GotSsoMessage({ message }), + ), + } +} + +/** Kit commands run; every API read and write is dropped. */ +export const update = (model: Model, message: Message): Return => + Message.match(message, { + GotSsoMessage: ({ message: child }) => { + const next = SsoUpdate.update(model.sso, child) + return { + model: { sso: next.model }, + commands: Command.mapMessages(keepLocal(next.commands), (message) => + Message.GotSsoMessage({ message }), + ), + } + }, + }) + +export const breadcrumbs = [{ label: "Lab", href: "/lab" }, { label: "SSO & SCIM" }] as const + +export const view = (model: Model, h: HtmlBuilder): Html => + h.div( + [h.Class("mx-auto w-full max-w-4xl p-6")], + [ + h.submodel({ + slotId: "lab-sso", + model: model.sso, + view: SsoView.view, + viewInputs: { isKnownMember: true }, + toParentMessage: (message: SsoModel.Message) => Message.GotSsoMessage({ message }), + }), + ], + ) diff --git a/apps/web/src/page/settings/message.ts b/apps/web/src/page/settings/message.ts index aa316e163a..c8169463d5 100644 --- a/apps/web/src/page/settings/message.ts +++ b/apps/web/src/page/settings/message.ts @@ -9,6 +9,7 @@ import { Message as BillingMessage } from "./billing/model" import { Message as MembersMessage } from "./members/model" import { Message as GeneralMessage } from "./general/model" import { Message as DomainsMessage } from "./domains/model" +import { Message as SsoMessage } from "./sso/model" import { Message as DataPlatformMessage } from "./data-platform/model" import { Message as DataSourcesMessage } from "./data-sources/model" import { Message as AuditLogMessage } from "./audit-log/model" @@ -33,6 +34,7 @@ export const Message = defineMessageUnion({ GotMembersMessage: { message: MembersMessage }, GotGeneralMessage: { message: GeneralMessage }, GotDomainsMessage: { message: DomainsMessage }, + GotSsoMessage: { message: SsoMessage }, GotDataPlatformMessage: { message: DataPlatformMessage }, GotDataSourcesMessage: { message: DataSourcesMessage }, GotAuditLogMessage: { message: AuditLogMessage }, diff --git a/apps/web/src/page/settings/model.ts b/apps/web/src/page/settings/model.ts index 24bfa7b841..b0067e021d 100644 --- a/apps/web/src/page/settings/model.ts +++ b/apps/web/src/page/settings/model.ts @@ -10,6 +10,7 @@ import * as Billing from "./billing/model" import * as Members from "./members/model" import * as General from "./general/model" import * as Domains from "./domains/model" +import * as Sso from "./sso/model" import * as DataPlatform from "./data-platform/model" import * as DataSources from "./data-sources/model" import * as AuditLog from "./audit-log/model" @@ -48,6 +49,7 @@ export const TabModel = Schema.Union([ Schema.TaggedStruct("General", { model: General.Model }), Schema.TaggedStruct("Members", { model: Members.Model }), Schema.TaggedStruct("Domains", { model: Domains.Model }), + Schema.TaggedStruct("Sso", { model: Sso.Model }), Schema.TaggedStruct("Billing", { model: Billing.Model }), ]) export type TabModel = typeof TabModel.Type diff --git a/apps/web/src/page/settings/nav.ts b/apps/web/src/page/settings/nav.ts index 2fbacf4a33..92479996b1 100644 --- a/apps/web/src/page/settings/nav.ts +++ b/apps/web/src/page/settings/nav.ts @@ -12,6 +12,7 @@ export const settingsTabLabels = { general: "General", members: "Members", domains: "Verified domains", + sso: "SSO & SCIM", billing: "Billing & usage", "audit-log": "Audit log", keys: "Keys", @@ -78,6 +79,7 @@ const navSections: ReadonlyArray> = [ icon: "GridIcon", href: "/integrations", }, + tab("sso", "ShieldIcon"), tab("keys", "KeyIcon"), tab("mcp", "SquareTerminalIcon"), tab("ai", "ChatBubbleSparkleIcon"), @@ -109,6 +111,8 @@ export type Visibility = Readonly<{ const isVisible = (id: string, visibility: Visibility): boolean => { if (id === "general" || id === "members" || id === "billing") return visibility.isClerk + // SSO lives in Clerk; every member reads it, admins change it. + if (id === "sso") return visibility.isClerk // Clerk refuses a member reading the domains, so the tab is for admins only. if (id === "domains") return visibility.isClerk && Policy.has(visibility.grants, "organization:manage") if (!visibility.isClerk) return true diff --git a/apps/web/src/page/settings/sso/model.ts b/apps/web/src/page/settings/sso/model.ts new file mode 100644 index 0000000000..31430b017f --- /dev/null +++ b/apps/web/src/page/settings/sso/model.ts @@ -0,0 +1,167 @@ +import { EnterpriseSsoDocument, ScimTokenIssued, SsoMappedRole, SsoProvider } from "@maple/domain/http" +import { Schema } from "effect" +import { AsyncData } from "foldkit" +import { defineMessageUnion } from "foldkit/message" +import { LoadFailure } from "@maple/views/data/load-failure" +import * as CopyButton from "@maple/views/ui/copy-button" +import * as Dialog from "@maple/views/ui/dialog" +import * as Field from "@maple/views/ui/field" +import * as Menu from "@maple/views/ui/menu" +import * as Select from "@maple/views/ui/select" + +// The SSO & SCIM tab: verified domains, the org's identity provider, break-glass users and SCIM +// provisioning, all read and written through `/internal/enterprise-sso`. + +export const DocumentData = AsyncData.Schema(EnterpriseSsoDocument, LoadFailure) + +/** An org member the break-glass picker offers. */ +export const MemberOption = Schema.Struct({ + userId: Schema.String, + name: Schema.String, + identifier: Schema.String, +}) +export type MemberOption = typeof MemberOption.Type +export const MembersData = AsyncData.Schema(Schema.Array(MemberOption), LoadFailure) + +/** Each write the tab makes; it names the toast and which dialog closes on success. */ +export const WriteAction = Schema.Literals([ + "addDomain", + "verifyDomain", + "removeDomain", + "createConnection", + "updateConnection", + "enforce", + "unenforce", + "deleteConnection", + "createDirectory", + "rotateToken", + "pause", + "resume", + "deleteDirectory", + "saveMappings", + "addBypass", + "removeBypass", +]) +export type WriteAction = typeof WriteAction.Type + +export const SamlMode = Schema.Literals(["metadata", "manual"]) +export type SamlMode = typeof SamlMode.Type + +/** The connection dialog's text fields. */ +export const DraftField = Schema.Literals([ + "name", + "metadataUrl", + "ssoUrl", + "entityId", + "certificate", + "discoveryUrl", + "clientId", + "clientSecret", +]) +export type DraftField = typeof DraftField.Type + +export const ConnectionDraft = Schema.Struct({ + mode: Schema.Literals(["create", "edit"]), + provider: SsoProvider, + domains: Schema.Array(Schema.String), + samlMode: SamlMode, + fields: Schema.Record(DraftField, Field.Model), +}) +export type ConnectionDraft = typeof ConnectionDraft.Type + +/** One role-mapping row being edited; `key` keeps the row's identity across reorders. */ +export const MappingDraft = Schema.Struct({ + key: Schema.String, + groupId: Schema.String, + role: SsoMappedRole, +}) +export type MappingDraft = typeof MappingDraft.Type + +export const Model = Schema.Struct({ + /** The viewer holds `sso:manage`; everyone else reads. */ + canManage: Schema.Boolean, + document: DocumentData.schema, + members: MembersData.schema, + /** The write in flight, one at a time. */ + pending: Schema.NullOr(WriteAction), + copies: Schema.Record(Schema.String, CopyButton.Model), + selects: Schema.Record(Schema.String, Select.Model), + domainMenus: Schema.Record(Schema.String, Menu.Model), + addDomainDialog: Dialog.Model, + domainField: Field.Model, + removingDomain: Schema.NullOr(Schema.String), + removeDomainDialog: Dialog.Model, + connectionDialog: Dialog.Model, + draft: Schema.NullOr(ConnectionDraft), + enforceDialog: Dialog.Model, + removeConnectionDialog: Dialog.Model, + bypassDialog: Dialog.Model, + bypassPick: Schema.NullOr(Schema.String), + removingBypass: Schema.NullOr(Schema.String), + removeBypassDialog: Dialog.Model, + removeDirectoryDialog: Dialog.Model, + rotateDialog: Dialog.Model, + tokenDialog: Dialog.Model, + /** The SCIM token, only while its reveal dialog is open. */ + issuedToken: Schema.NullOr(Schema.String), + /** `null` while the rows match the saved mappings. */ + mappings: Schema.NullOr(Schema.Array(MappingDraft)), + nextMappingKey: Schema.Number, +}) +export type Model = typeof Model.Type + +export const Message = defineMessageUnion({ + CompletedFetchDocument: { result: Schema.Result(EnterpriseSsoDocument, LoadFailure) }, + CompletedFetchMembers: { result: Schema.Result(Schema.Array(MemberOption), LoadFailure) }, + ClickedRetry: {}, + CompletedWrite: { action: WriteAction, result: Schema.Result(EnterpriseSsoDocument, LoadFailure) }, + CompletedIssueToken: { action: WriteAction, result: Schema.Result(ScimTokenIssued, LoadFailure) }, + GotCopyMessage: { key: Schema.String, message: CopyButton.Message }, + GotSelectMessage: { key: Schema.String, message: Select.Message }, + // Domains + ClickedAddDomain: {}, + GotAddDomainDialogMessage: { message: Dialog.Message }, + GotDomainFieldMessage: { message: Field.Message }, + SubmittedAddDomain: {}, + ClickedVerifyDomain: { domain: Schema.String }, + GotDomainMenuMessage: { domain: Schema.String, message: Menu.Message }, + GotRemoveDomainDialogMessage: { message: Dialog.Message }, + ClickedConfirmRemoveDomain: {}, + // Identity provider + ClickedConnect: {}, + ClickedEditConnection: {}, + GotConnectionDialogMessage: { message: Dialog.Message }, + GotDraftFieldMessage: { field: DraftField, message: Field.Message }, + PickedSamlMode: { mode: SamlMode }, + ToggledDraftDomain: { domain: Schema.String }, + SubmittedConnection: {}, + ToggledEnforcement: {}, + GotEnforceDialogMessage: { message: Dialog.Message }, + ClickedConfirmEnforce: {}, + ClickedRemoveConnection: {}, + GotRemoveConnectionDialogMessage: { message: Dialog.Message }, + ClickedConfirmRemoveConnection: {}, + // Break-glass + ClickedAddBypass: {}, + GotBypassDialogMessage: { message: Dialog.Message }, + SubmittedBypass: {}, + ClickedRemoveBypass: { userId: Schema.String }, + GotRemoveBypassDialogMessage: { message: Dialog.Message }, + ClickedConfirmRemoveBypass: {}, + // SCIM + ClickedSetUpScim: {}, + ClickedTogglePaused: {}, + ClickedRotateToken: {}, + GotRotateDialogMessage: { message: Dialog.Message }, + ClickedConfirmRotate: {}, + GotTokenDialogMessage: { message: Dialog.Message }, + ClickedRemoveDirectory: {}, + GotRemoveDirectoryDialogMessage: { message: Dialog.Message }, + ClickedConfirmRemoveDirectory: {}, + ClickedAddMapping: {}, + ClickedMoveMapping: { key: Schema.String, by: Schema.Literals([-1, 1]) }, + ClickedRemoveMapping: { key: Schema.String }, + ClickedDiscardMappings: {}, + ClickedSaveMappings: {}, +}) +export type Message = typeof Message.Type diff --git a/apps/web/src/page/settings/sso/sso.scene.test.ts b/apps/web/src/page/settings/sso/sso.scene.test.ts new file mode 100644 index 0000000000..59333c22c8 --- /dev/null +++ b/apps/web/src/page/settings/sso/sso.scene.test.ts @@ -0,0 +1,318 @@ +import { EnterpriseSsoDocument, ScimTokenIssued } from "@maple/domain/http" +import { Array as Arr, Option, Result, Schema } from "effect" +import { expect as expectView, given, Mount, role, scene, text, withViewInputs } from "foldkit/scene" +import { describe, expect, test } from "vitest" +import { toLoadFailure } from "@maple/views/data/load-failure" +import * as Dialog from "@maple/views/ui/dialog" +import * as Field from "@maple/views/ui/field" +import * as Select from "@maple/views/ui/select" +import { type DraftField, Message, type Model } from "./model" +import { draftProblem, init, requestOf, update } from "./update" +import { view as ssoView } from "./view" + +const CREATED = "2026-11-16T10:00:00.000Z" + +const connection = { + name: "Okta", + provider: "saml_okta", + protocol: "saml", + domains: ["acme.com"], + enforced: false, + acsUrl: "https://clerk.maple.dev/v1/saml/acs/abc", + spEntityId: "https://clerk.maple.dev/saml/abc", + spMetadataUrl: "https://clerk.maple.dev/v1/saml/metadata/abc", + idpMetadataUrl: "https://acme.okta.com/metadata", + idpSsoUrl: null, + idpEntityId: null, + idpCertificateExpiresAt: null, + oidcDiscoveryUrl: null, + oidcClientId: null, + createdAt: CREATED, +} as const + +const verifiedDomain = { + domain: "acme.com", + status: "verified", + recordName: "_maple-challenge.acme.com", + recordValue: "maple-verify=abc", + verifiedAt: CREATED, +} as const + +const doc = (overrides: Partial = {}): EnterpriseSsoDocument => + Schema.decodeSync(EnterpriseSsoDocument)({ + entitled: true, + domains: [], + connection: null, + directory: null, + roleMappings: [], + groups: [], + bypassUsers: [], + ...overrides, + }) + +const loaded = (document: EnterpriseSsoDocument, canManage = true): Model => + update(init(canManage).model, Message.CompletedFetchDocument({ result: Result.succeed(document) })).model + +const names = (step: { readonly commands?: ReadonlyArray<{ readonly name: string }> }) => + Arr.map(step.commands ?? [], (command) => command.name) + +const view = withViewInputs(ssoView, { isKnownMember: true })() + +const dialogMounted = Mount.resolve(Dialog.MountDialog, Dialog.Message.CompletedMountDialog()) + +describe("sso tab", () => { + test("an org without the Enterprise plan sees one notice and no setup actions", () => { + scene( + { update, view }, + given(loaded(doc({ entitled: false }))), + expectView(text("SSO and SCIM are part of the Enterprise plan")).toExist(), + expectView(role("link", { name: "Contact sales" })).toExist(), + expectView(role("button", { name: "Add domain" })).not.toExist(), + expectView(text("Identity provider")).not.toExist(), + ) + }) + + test("an entitled admin starts from the empty state, and SCIM waits for a connection", () => { + scene( + { update, view }, + given(loaded(doc({ domains: [verifiedDomain] }))), + expectView(text("No identity provider")).toExist(), + expectView(role("button", { name: "Add domain" })).toExist(), + expectView(role("button", { name: "Connect identity provider" })).toBeEnabled(), + expectView(text("SCIM provisioning")).not.toExist(), + ) + }) + + test("a pending domain shows the TXT record to publish", () => { + const pending = { + ...verifiedDomain, + status: "pending" as const, + verifiedAt: null, + } + const model = loaded(doc({ domains: [pending] })) + scene( + { update, view }, + given(model), + expectView(text("_maple-challenge.acme.com")).toExist(), + expectView(text("maple-verify=abc")).toExist(), + ) + expect( + update(model, Message.ClickedVerifyDomain({ domain: "acme.com" })).commands?.[0], + ).toMatchObject({ + name: "VerifySsoDomain", + args: { domain: "acme.com" }, + }) + }) + + test("a member reads the settings but cannot change them", () => { + const model = loaded(doc({ domains: [verifiedDomain], connection }), false) + scene( + { update, view }, + given(model), + expectView(text("Only admins can change SSO and SCIM settings.")).toExist(), + expectView(role("button", { name: "Add domain" })).not.toExist(), + expectView(role("button", { name: "Edit" })).not.toExist(), + ) + expect(names(update(model, Message.ClickedConfirmEnforce()))).toEqual([]) + expect(names(update(model, Message.ClickedSetUpScim()))).toEqual([]) + }) + + test("a connected IdP shows what to paste, and requiring SSO asks first", () => { + const model = loaded(doc({ domains: [verifiedDomain], connection })) + scene( + { update, view }, + given(model), + expectView(text("https://clerk.maple.dev/v1/saml/acs/abc")).toExist(), + expectView(role("switch", { name: "Require SSO" })).toExist(), + ) + const asked = update(model, Message.ToggledEnforcement()) + expect(asked.model.enforceDialog.isOpen).toBe(true) + expect(names(asked)).not.toContain("SetSsoEnforcement") + scene( + { update, view }, + given(asked.model), + dialogMounted, + expectView(text("Require SSO?")).toExist(), + expectView(text(/Add a break-glass member first/)).toExist(), + ) + expect(update(asked.model, Message.ClickedConfirmEnforce()).commands?.[0]).toMatchObject({ + name: "SetSsoEnforcement", + args: { enforced: true }, + }) + }) + + test("turning enforcement off needs no confirm", () => { + const model = loaded( + doc({ domains: [verifiedDomain], connection: { ...connection, enforced: true } }), + ) + const step = update(model, Message.ToggledEnforcement()) + expect(step.model.enforceDialog.isOpen).toBe(false) + expect(step.commands?.[0]).toMatchObject({ name: "SetSsoEnforcement", args: { enforced: false } }) + }) + + test("the SCIM token shows once and leaves the model when its dialog closes", () => { + const model = loaded(doc({ domains: [verifiedDomain], connection })) + const started = update(model, Message.ClickedSetUpScim()) + expect(started.commands?.[0]).toMatchObject({ name: "IssueScimToken", args: { kind: "create" } }) + const directory = { + endpointUrl: "https://api.maple.dev/scim/v2/abc", + enabled: true, + paused: false, + createdAt: CREATED, + } + const issued = new ScimTokenIssued({ + document: doc({ domains: [verifiedDomain], connection, directory }), + token: "scim_secret_token", + }) + const revealed = update( + started.model, + Message.CompletedIssueToken({ action: "createDirectory", result: Result.succeed(issued) }), + ).model + expect(revealed.issuedToken).toBe("scim_secret_token") + expect(revealed.tokenDialog.isOpen).toBe(true) + scene( + { update, view }, + given(revealed), + dialogMounted, + expectView(text(/You will not see this token again/)).toExist(), + expectView(text("https://api.maple.dev/scim/v2/abc")).toExist(), + ) + const closed = update( + revealed, + Message.GotTokenDialogMessage({ message: Dialog.Message.ClickedClose() }), + ) + expect(closed.model.tokenDialog.isOpen).toBe(false) + expect(closed.model.issuedToken).toBeNull() + }) + + test("role mappings save in row order with the picked roles", () => { + const directory = { + endpointUrl: "https://api.maple.dev/scim/v2/abc", + enabled: true, + paused: false, + createdAt: CREATED, + } + const groups = [ + { groupId: "grp_eng", displayName: "Engineering" }, + { groupId: "grp_admins", displayName: "Admins" }, + ] + const start = loaded(doc({ domains: [verifiedDomain], connection, directory, groups })) + const twoRows = update( + update(start, Message.ClickedAddMapping()).model, + Message.ClickedAddMapping(), + ).model + expect(Arr.map(twoRows.mappings ?? [], (row) => row.groupId)).toEqual(["grp_eng", "grp_admins"]) + const adminRole = update( + twoRows, + Message.GotSelectMessage({ + key: "role-new-1", + message: Select.Message.SelectedItem({ index: 0, value: "org:admin" }), + }), + ).model + const reordered = update(adminRole, Message.ClickedMoveMapping({ key: "new-1", by: -1 })).model + const saving = update(reordered, Message.ClickedSaveMappings()) + expect(saving.commands?.[0]).toMatchObject({ + name: "SetScimRoleMappings", + args: { + mappings: [ + { groupId: "grp_admins", role: "org:admin" }, + { groupId: "grp_eng", role: "org:member" }, + ], + }, + }) + }) + + test("without pushed groups the mapping section explains where they come from", () => { + const directory = { + endpointUrl: "https://api.maple.dev/scim/v2/abc", + enabled: true, + paused: true, + createdAt: CREATED, + } + scene( + { update, view }, + given(loaded(doc({ domains: [verifiedDomain], connection, directory }))), + expectView( + text("Groups appear here after your identity provider pushes them over SCIM."), + ).toExist(), + expectView(role("button", { name: "Resume" })).toExist(), + ) + }) + + test("a SAML draft needs a metadata URL, or the manual fields and a certificate on create", () => { + const opened = update(loaded(doc({ domains: [verifiedDomain] })), Message.ClickedConnect()).model + const typed = (model: Model, values: ReadonlyArray): Model => + Arr.reduce( + values, + model, + (current, [field, value]) => + update( + current, + Message.GotDraftFieldMessage({ + field, + message: Field.Message.ChangedValue({ value }), + }), + ).model, + ) + const named = typed(opened, [["name", "Okta"]]) + expect(Option.flatMap(Option.fromNullishOr(named.draft), requestOf)._tag).toBe("None") + const withMetadata = typed(named, [["metadataUrl", "https://acme.okta.com/metadata"]]) + expect(Option.flatMap(Option.fromNullishOr(withMetadata.draft), requestOf)).toMatchObject({ + _tag: "Some", + value: { domains: ["acme.com"], saml: { metadataUrl: "https://acme.okta.com/metadata" } }, + }) + const manual = typed(update(named, Message.PickedSamlMode({ mode: "manual" })).model, [ + ["ssoUrl", "https://acme.okta.com/sso"], + ["entityId", "acme"], + ]) + expect(Option.flatMap(Option.fromNullishOr(manual.draft), requestOf)._tag).toBe("None") + // A disabled submit names what is missing. + expect(Option.map(Option.fromNullishOr(manual.draft), draftProblem)).toEqual( + Option.some("Add the IdP signing certificate."), + ) + const signed = typed(manual, [["certificate", "CERT"]]) + expect(Option.map(Option.fromNullishOr(signed.draft), draftProblem)).toEqual(Option.some(null)) + expect(names(update(signed, Message.SubmittedConnection()))).toEqual(["SaveSsoConnection"]) + }) + + test("an org that left Enterprise can still relax SSO and pause or remove SCIM, but not set anything up", () => { + const model = loaded( + doc({ + entitled: false, + domains: [verifiedDomain], + connection: { ...connection, enforced: true }, + directory: { + endpointUrl: "https://api.clerk.com/scim/v2", + enabled: true, + paused: false, + createdAt: CREATED, + }, + }), + ) + scene( + { update, view }, + given(model), + expectView(role("switch", { name: "Require SSO" })).toBeEnabled(), + expectView(role("button", { name: "Pause" })).toExist(), + expectView(role("button", { name: "Edit" })).not.toExist(), + expectView(role("button", { name: "Rotate token" })).not.toExist(), + ) + }) + + test("a failed member list loads again when the break-glass dialog reopens", () => { + const failed = update( + loaded(doc({ domains: [verifiedDomain], connection })), + Message.CompletedFetchMembers({ result: Result.fail(toLoadFailure(new Error("Clerk down"))) }), + ).model + expect(names(update(failed, Message.ClickedAddBypass()))).toContain("FetchSsoMembers") + }) + + test("an unconfirmed role never claims the viewer is not an admin", () => { + scene( + { update, view: withViewInputs(ssoView, { isKnownMember: false })() }, + given(loaded(doc({ domains: [verifiedDomain], connection }), false)), + expectView(text("Only admins can change SSO and SCIM settings.")).not.toExist(), + expectView(role("button", { name: "Edit" })).not.toExist(), + ) + }) +}) diff --git a/apps/web/src/page/settings/sso/update.ts b/apps/web/src/page/settings/sso/update.ts new file mode 100644 index 0000000000..513fa3e166 --- /dev/null +++ b/apps/web/src/page/settings/sso/update.ts @@ -0,0 +1,833 @@ +import { + type EnterpriseSsoDocument, + ScimDirectoryStateRequest, + ScimRoleMappingsRequest, + SsoAddDomainRequest, + SsoBypassRequest, + SsoConnectionRequest, + SsoEnforcementRequest, + SsoMappedRole, + SsoProvider, + ssoProtocolOf, +} from "@maple/domain/http" +import { UserId } from "@maple/primitives" +import { Array as Arr, Effect, Option, Result, Schema, String as Str } from "effect" +import { AsyncData, Command } from "foldkit" +import { failureMessage, type LoadFailure, settleTo } from "@maple/views/data/load-failure" +import * as CopyButton from "@maple/views/ui/copy-button" +import * as Dialog from "@maple/views/ui/dialog" +import * as Field from "@maple/views/ui/field" +import * as Menu from "@maple/views/ui/menu" +import * as Select from "@maple/views/ui/select" +import { MapleInternalApiClient } from "../../../platform/api-clients" +import { ClerkActionError, clerkTry, currentClerkOrganization } from "../../../platform/clerk" +import { PageOutMessage, type PageReturn } from "../../contract" +import { memberDisplayName } from "../kit/members" +import { normalizeDomain } from "../domains/update" +import { revisitData } from "../kit/revisit" +import { + type ConnectionDraft, + type DraftField, + type MappingDraft, + type MemberOption, + Message, + type Model, + type WriteAction, +} from "./model" + +type Return = PageReturn + +export { normalizeDomain } + +/** Clerk's page cap; break-glass picks from the first hundred members. */ +const MEMBERS_PAGE_SIZE = 100 + +export const PROVIDERS = SsoProvider.literals +export const MAPPED_ROLES = SsoMappedRole.literals + +// Reads + +export const FetchEnterpriseSso = Command.define("FetchEnterpriseSso", { + messages: [Message.CompletedFetchDocument], + execute: Effect.flatMap(MapleInternalApiClient, (client) => client.enterpriseSso.get()).pipe( + settleTo((result) => Message.CompletedFetchDocument({ result })), + ), +}) + +/** Every member, page by page; capped so a runaway org cannot loop the picker forever. */ +const MAX_MEMBER_PAGES = 50 + +const FetchSsoMembers = Command.define("FetchSsoMembers", { + messages: [Message.CompletedFetchMembers], + execute: currentClerkOrganization.pipe( + Effect.flatMap((organization) => { + const fetchFrom = ( + page: number, + collected: ReadonlyArray, + ): Effect.Effect, ClerkActionError> => + clerkTry("Couldn't load members", () => + organization.getMemberships({ initialPage: page, pageSize: MEMBERS_PAGE_SIZE }), + ).pipe( + Effect.flatMap((result) => { + const next = Arr.appendAll( + collected, + Arr.flatMap(result.data, (member): ReadonlyArray => { + const user = member.publicUserData + return user?.userId === undefined + ? [] + : [ + { + userId: user.userId, + name: memberDisplayName(user) ?? user.identifier, + identifier: user.identifier, + }, + ] + }), + ) + return result.data.length < MEMBERS_PAGE_SIZE || page >= MAX_MEMBER_PAGES + ? Effect.succeed(next) + : fetchFrom(page + 1, next) + }), + ) + return fetchFrom(1, []) + }), + settleTo((result) => Message.CompletedFetchMembers({ result })), + ), +}) + +// Writes: each answers with the whole document. + +const written = + (action: WriteAction) => + (effect: Effect.Effect) => + effect.pipe(settleTo((result) => Message.CompletedWrite({ action, result }))) + +const AddSsoDomain = Command.define("AddSsoDomain", { + args: { domain: Schema.String }, + messages: [Message.CompletedWrite], + execute: ({ domain }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.addDomain({ payload: new SsoAddDomainRequest({ domain }) }), + ).pipe(written("addDomain")), +}) + +const VerifySsoDomain = Command.define("VerifySsoDomain", { + args: { domain: Schema.String }, + messages: [Message.CompletedWrite], + execute: ({ domain }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.verifyDomain({ params: { domain } }), + ).pipe(written("verifyDomain")), +}) + +const RemoveSsoDomain = Command.define("RemoveSsoDomain", { + args: { domain: Schema.String }, + messages: [Message.CompletedWrite], + execute: ({ domain }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.removeDomain({ params: { domain } }), + ).pipe(written("removeDomain")), +}) + +const SaveSsoConnection = Command.define("SaveSsoConnection", { + args: { mode: Schema.Literals(["create", "edit"]), request: SsoConnectionRequest }, + messages: [Message.CompletedWrite], + execute: ({ mode, request }) => + Effect.flatMap(MapleInternalApiClient, (client) => + mode === "create" + ? client.enterpriseSso.createConnection({ payload: request }) + : client.enterpriseSso.updateConnection({ payload: request }), + ).pipe(written(mode === "create" ? "createConnection" : "updateConnection")), +}) + +const SetSsoEnforcement = Command.define("SetSsoEnforcement", { + args: { enforced: Schema.Boolean }, + messages: [Message.CompletedWrite], + execute: ({ enforced }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.setEnforcement({ payload: new SsoEnforcementRequest({ enforced }) }), + ).pipe(written(enforced ? "enforce" : "unenforce")), +}) + +const DeleteSsoConnection = Command.define("DeleteSsoConnection", { + messages: [Message.CompletedWrite], + execute: Effect.flatMap(MapleInternalApiClient, (client) => client.enterpriseSso.deleteConnection()).pipe( + written("deleteConnection"), + ), +}) + +const IssueScimToken = Command.define("IssueScimToken", { + args: { kind: Schema.Literals(["create", "rotate"]) }, + messages: [Message.CompletedIssueToken], + execute: ({ kind }) => + Effect.flatMap(MapleInternalApiClient, (client) => + kind === "create" + ? client.enterpriseSso.createDirectory() + : client.enterpriseSso.rotateDirectoryToken(), + ).pipe( + settleTo((result) => + Message.CompletedIssueToken({ + action: kind === "create" ? "createDirectory" : "rotateToken", + result, + }), + ), + ), +}) + +const SetScimDirectoryState = Command.define("SetScimDirectoryState", { + args: { paused: Schema.Boolean }, + messages: [Message.CompletedWrite], + execute: ({ paused }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.setDirectoryState({ payload: new ScimDirectoryStateRequest({ paused }) }), + ).pipe(written(paused ? "pause" : "resume")), +}) + +const DeleteScimDirectory = Command.define("DeleteScimDirectory", { + messages: [Message.CompletedWrite], + execute: Effect.flatMap(MapleInternalApiClient, (client) => client.enterpriseSso.deleteDirectory()).pipe( + written("deleteDirectory"), + ), +}) + +const SetScimRoleMappings = Command.define("SetScimRoleMappings", { + args: { mappings: Schema.Array(Schema.Struct({ groupId: Schema.String, role: SsoMappedRole })) }, + messages: [Message.CompletedWrite], + execute: ({ mappings }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.setRoleMappings({ payload: new ScimRoleMappingsRequest({ mappings }) }), + ).pipe(written("saveMappings")), +}) + +const AddSsoBypassUser = Command.define("AddSsoBypassUser", { + args: { userId: UserId }, + messages: [Message.CompletedWrite], + execute: ({ userId }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.addBypassUser({ payload: new SsoBypassRequest({ userId }) }), + ).pipe(written("addBypass")), +}) + +const RemoveSsoBypassUser = Command.define("RemoveSsoBypassUser", { + args: { userId: UserId }, + messages: [Message.CompletedWrite], + execute: ({ userId }) => + Effect.flatMap(MapleInternalApiClient, (client) => + client.enterpriseSso.removeBypassUser({ params: { userId } }), + ).pipe(written("removeBypass")), +}) + +// Init + +export const init = (canManage: boolean): Return => ({ + model: { + canManage, + document: AsyncData.Loading(), + members: canManage ? AsyncData.Loading() : AsyncData.Idle(), + pending: null, + copies: {}, + selects: {}, + domainMenus: {}, + addDomainDialog: Dialog.init("sso-domain-add", "dialog"), + domainField: Field.init(), + removingDomain: null, + removeDomainDialog: Dialog.init("sso-domain-remove", "alert-dialog"), + connectionDialog: Dialog.init("sso-connection", "dialog"), + draft: null, + enforceDialog: Dialog.init("sso-enforce", "alert-dialog"), + removeConnectionDialog: Dialog.init("sso-connection-remove", "alert-dialog"), + bypassDialog: Dialog.init("sso-bypass-add", "dialog"), + bypassPick: null, + removingBypass: null, + removeBypassDialog: Dialog.init("sso-bypass-remove", "alert-dialog"), + removeDirectoryDialog: Dialog.init("sso-directory-remove", "alert-dialog"), + rotateDialog: Dialog.init("sso-token-rotate", "alert-dialog"), + tokenDialog: Dialog.init("sso-token", "dialog"), + issuedToken: null, + mappings: null, + nextMappingKey: 0, + }, + commands: [FetchEnterpriseSso(), ...(canManage ? [FetchSsoMembers()] : [])], +}) + +export const revisit = (model: Model): Return => { + const document = revisitData(model.document, FetchEnterpriseSso) + const members = retryMembers(model) + return { + model: { ...model, document: document.data, members: members.data }, + commands: [...document.commands, ...members.commands], + } +} + +/** A failed member list is fetched again; one that loaded or is loading is left alone. */ +const retryMembers = (model: Model) => + model.canManage && AsyncData.isFailure(model.members) + ? { data: AsyncData.Loading(), commands: [FetchSsoMembers()] } + : { data: model.members, commands: [] } + +// Derived + +export const documentOf = (model: Model): EnterpriseSsoDocument | null => + AsyncData.getOrElse( + AsyncData.map(model.document, (document): EnterpriseSsoDocument | null => document), + () => null, + ) + +export const verifiedDomains = (document: EnterpriseSsoDocument): ReadonlyArray => + Arr.flatMap(document.domains, (domain) => (domain.status === "verified" ? [domain.domain] : [])) + +/** The rows on screen: the draft while editing, else the saved mappings. */ +export const mappingRows = (model: Model): ReadonlyArray => + model.mappings ?? + Arr.map(documentOf(model)?.roleMappings ?? [], (mapping, index) => ({ + key: `saved-${index}`, + groupId: mapping.groupId, + role: mapping.role, + })) + +/** Every row names a group, and no group twice. */ +export const isMappingsValid = (rows: ReadonlyArray): boolean => + Arr.every(rows, (row) => row.groupId !== "") && + Arr.dedupe(Arr.map(rows, (row) => row.groupId)).length === rows.length + +const isHttps = (value: string): boolean => Str.startsWith("https://")(Str.trim(value)) + +const draftValue = (draft: ConnectionDraft, field: DraftField): string => + Str.trim(draft.fields[field]?.value ?? "") + +/** The request a draft submits, or none while a required field is missing. */ +export const requestOf = (draft: ConnectionDraft): Option.Option => { + const value = (field: DraftField) => draftValue(draft, field) + const isCreate = draft.mode === "create" + if (value("name") === "" || draft.domains.length === 0) return Option.none() + const base = { name: value("name"), provider: draft.provider, domains: draft.domains } + const decode = Schema.decodeUnknownOption(SsoConnectionRequest) + if (ssoProtocolOf(draft.provider) === "oidc") { + if (!isHttps(value("discoveryUrl")) || value("clientId") === "") return Option.none() + if (isCreate && value("clientSecret") === "") return Option.none() + return decode({ + ...base, + oidc: { + discoveryUrl: value("discoveryUrl"), + clientId: value("clientId"), + ...(value("clientSecret") !== "" && { clientSecret: value("clientSecret") }), + }, + }) + } + if (draft.samlMode === "metadata") + return isHttps(value("metadataUrl")) + ? decode({ ...base, saml: { metadataUrl: value("metadataUrl") } }) + : Option.none() + if (!isHttps(value("ssoUrl")) || value("entityId") === "") return Option.none() + if (isCreate && value("certificate") === "") return Option.none() + return decode({ + ...base, + saml: { + ssoUrl: value("ssoUrl"), + entityId: value("entityId"), + ...(value("certificate") !== "" && { certificate: value("certificate") }), + }, + }) +} + +/** What keeps a draft from submitting, in words, or null when `requestOf` accepts it. */ +export const draftProblem = (draft: ConnectionDraft): string | null => { + const value = (field: DraftField) => draftValue(draft, field) + const isCreate = draft.mode === "create" + if (value("name") === "") return "Give the connection a name." + if (value("name").length > 120) return "Keep the name to 120 characters." + if (draft.domains.length === 0) return "Pick at least one verified domain." + if (draft.domains.length > 20) return "Pick at most 20 domains." + if (ssoProtocolOf(draft.provider) === "oidc") { + if (!isHttps(value("discoveryUrl"))) return "The discovery URL must start with https://." + if (value("clientId") === "") return "Add the client ID." + if (isCreate && value("clientSecret") === "") return "Add the client secret." + } else if (draft.samlMode === "metadata") { + if (!isHttps(value("metadataUrl"))) return "The metadata URL must start with https://." + } else { + if (!isHttps(value("ssoUrl"))) return "The SSO URL must start with https://." + if (value("entityId") === "") return "Add the IdP entity ID." + if (isCreate && value("certificate") === "") return "Add the IdP signing certificate." + } + return Option.isNone(requestOf(draft)) ? "One of the values is too long." : null +} + +const fieldsOf = (values: Partial>): ConnectionDraft["fields"] => ({ + name: Field.init(values.name ?? ""), + metadataUrl: Field.init(values.metadataUrl ?? ""), + ssoUrl: Field.init(values.ssoUrl ?? ""), + entityId: Field.init(values.entityId ?? ""), + certificate: Field.init(values.certificate ?? ""), + discoveryUrl: Field.init(values.discoveryUrl ?? ""), + clientId: Field.init(values.clientId ?? ""), + clientSecret: Field.init(values.clientSecret ?? ""), +}) + +const newDraft = (document: EnterpriseSsoDocument): ConnectionDraft => ({ + mode: "create", + provider: "saml_okta", + domains: verifiedDomains(document), + samlMode: "metadata", + fields: fieldsOf({}), +}) + +const editDraft = (connection: NonNullable): ConnectionDraft => ({ + mode: "edit", + provider: connection.provider, + domains: connection.domains, + samlMode: connection.idpMetadataUrl === null && connection.idpSsoUrl !== null ? "manual" : "metadata", + fields: fieldsOf({ + name: connection.name, + metadataUrl: connection.idpMetadataUrl ?? "", + ssoUrl: connection.idpSsoUrl ?? "", + entityId: connection.idpEntityId ?? "", + discoveryUrl: connection.oidcDiscoveryUrl ?? "", + clientId: connection.oidcClientId ?? "", + }), +}) + +// Steps + +const toast = (type: "success" | "error", title: string, description = "") => + PageOutMessage.RequestedToast({ type, title, description }) + +type DialogKey = + | "addDomainDialog" + | "removeDomainDialog" + | "connectionDialog" + | "enforceDialog" + | "removeConnectionDialog" + | "bypassDialog" + | "removeBypassDialog" + | "removeDirectoryDialog" + | "rotateDialog" + | "tokenDialog" + +const dialogMessage = (key: DialogKey, message: Dialog.Message): Message => { + switch (key) { + case "addDomainDialog": + return Message.GotAddDomainDialogMessage({ message }) + case "removeDomainDialog": + return Message.GotRemoveDomainDialogMessage({ message }) + case "connectionDialog": + return Message.GotConnectionDialogMessage({ message }) + case "enforceDialog": + return Message.GotEnforceDialogMessage({ message }) + case "removeConnectionDialog": + return Message.GotRemoveConnectionDialogMessage({ message }) + case "bypassDialog": + return Message.GotBypassDialogMessage({ message }) + case "removeBypassDialog": + return Message.GotRemoveBypassDialogMessage({ message }) + case "removeDirectoryDialog": + return Message.GotRemoveDirectoryDialogMessage({ message }) + case "rotateDialog": + return Message.GotRotateDialogMessage({ message }) + case "tokenDialog": + return Message.GotTokenDialogMessage({ message }) + } +} + +const dialogStep = (model: Model, key: DialogKey, step: ReturnType): Return => ({ + model: { ...model, [key]: step.model }, + commands: Command.mapMessages(step.commands ?? [], (message) => dialogMessage(key, message)), +}) + +const openDialog = (model: Model, key: DialogKey): Return => dialogStep(model, key, Dialog.open(model[key])) +const closeDialog = (model: Model, key: DialogKey): Return => dialogStep(model, key, Dialog.close(model[key])) + +/** A dialog's own messages; it stays put while its write is in flight. */ +const updateDialog = (model: Model, key: DialogKey, message: Dialog.Message): Return => + model.pending !== null && key !== "tokenDialog" + ? { model } + : dialogStep(model, key, Dialog.update(model[key], message)) + +const merge = (first: Return, second: Return): Return => ({ + ...second, + commands: [...(first.commands ?? []), ...(second.commands ?? [])], +}) + +/** Starts a write unless one is already running, or the viewer only reads. */ +type WriteCommand = NonNullable[number] + +const startWrite = (model: Model, action: WriteAction, command: WriteCommand): Return => + model.pending !== null || !model.canManage + ? { model } + : { model: { ...model, pending: action }, commands: [command] } + +const SUCCESS_TITLES = { + addDomain: "Domain added. Publish the TXT record, then verify it.", + verifyDomain: "Domain verified", + removeDomain: "Domain removed", + createConnection: "Identity provider connected", + updateConnection: "Identity provider saved", + enforce: "SSO is now required", + unenforce: "SSO is no longer required", + deleteConnection: "Identity provider removed", + createDirectory: "SCIM provisioning set up", + rotateToken: "SCIM token rotated", + pause: "SCIM provisioning paused", + resume: "SCIM provisioning resumed", + deleteDirectory: "SCIM provisioning removed", + saveMappings: "Role mappings saved", + addBypass: "Break-glass member added", + removeBypass: "Break-glass member removed", +} as const satisfies { readonly [A in WriteAction]: string } + +/** The dialog a successful write closes, and the state it clears. */ +const afterSuccess = (model: Model, action: WriteAction): Return => { + switch (action) { + case "addDomain": + return closeDialog({ ...model, domainField: Field.init() }, "addDomainDialog") + case "removeDomain": + return closeDialog({ ...model, removingDomain: null }, "removeDomainDialog") + case "createConnection": + case "updateConnection": + return closeDialog({ ...model, draft: null, selects: {} }, "connectionDialog") + case "enforce": + return closeDialog(model, "enforceDialog") + case "deleteConnection": + return closeDialog({ ...model, mappings: null }, "removeConnectionDialog") + case "rotateToken": + return closeDialog(model, "rotateDialog") + case "deleteDirectory": + return closeDialog({ ...model, mappings: null, selects: {} }, "removeDirectoryDialog") + case "saveMappings": + return { model: { ...model, mappings: null, selects: {} } } + case "addBypass": + return closeDialog({ ...model, bypassPick: null }, "bypassDialog") + case "removeBypass": + return closeDialog({ ...model, removingBypass: null }, "removeBypassDialog") + case "verifyDomain": + case "unenforce": + case "createDirectory": + case "pause": + case "resume": + return { model } + } +} + +const failed = (model: Model, failure: LoadFailure): Return => ({ + model: { ...model, pending: null }, + outMessage: toast("error", failure.title, failureMessage(failure)), +}) + +const settled = (model: Model, action: WriteAction, document: EnterpriseSsoDocument): Return => { + const step = afterSuccess( + { ...model, pending: null, document: AsyncData.Success({ data: document }) }, + action, + ) + return { ...step, outMessage: toast("success", SUCCESS_TITLES[action]) } +} + +const fieldStep = (model: Model, child: Field.Message): Return => { + const step = Field.update(model.domainField, child) + return { + model: { ...model, domainField: step.model }, + commands: Command.mapMessages(step.commands ?? [], (inner) => + Message.GotDomainFieldMessage({ message: inner }), + ), + } +} + +const selectModel = (model: Model, key: string): Select.Model => + model.selects[key] ?? Select.init(`sso-select-${key}`, { value: "", selectedIndex: null }) + +const withRows = (model: Model, rows: ReadonlyArray): Model => ({ ...model, mappings: rows }) + +/** A picked select value lands where its key says. */ +const applyPick = (model: Model, key: string, value: string): Model => { + const draft = model.draft + if (key === "provider") + return draft === null + ? model + : Option.match(Schema.decodeUnknownOption(SsoProvider)(value), { + onNone: () => model, + onSome: (provider) => ({ ...model, draft: { ...draft, provider } }), + }) + if (key === "bypass") return { ...model, bypassPick: value } + const rows = mappingRows(model) + if (Str.startsWith("group-")(key)) { + const rowKey = Str.slice(6)(key) + return withRows( + model, + Arr.map(rows, (row) => (row.key === rowKey ? { ...row, groupId: value } : row)), + ) + } + if (Str.startsWith("role-")(key)) { + const rowKey = Str.slice(5)(key) + return Option.match(Schema.decodeUnknownOption(SsoMappedRole)(value), { + onNone: () => model, + onSome: (role) => + withRows( + model, + Arr.map(rows, (row) => (row.key === rowKey ? { ...row, role } : row)), + ), + }) + } + return model +} + +const moveRow = (rows: ReadonlyArray, key: string, by: -1 | 1): ReadonlyArray => + Option.match( + Arr.findFirstIndex(rows, (row) => row.key === key), + { + onNone: () => rows, + onSome: (index) => { + const target = index + by + const row = rows[index] + const other = rows[target] + if (row === undefined || other === undefined) return rows + return Arr.map(rows, (current, at) => (at === index ? other : at === target ? row : current)) + }, + }, + ) + +export const update = (model: Model, message: Message): Return => + Message.match(message, { + CompletedFetchDocument: ({ result }) => ({ + model: { ...model, document: AsyncData.settle(model.document, result) }, + }), + CompletedFetchMembers: ({ result }) => ({ + model: { ...model, members: AsyncData.settle(model.members, result) }, + }), + ClickedRetry: () => { + const members = retryMembers(model) + return { + model: { ...model, document: AsyncData.Loading(), members: members.data }, + commands: [FetchEnterpriseSso(), ...members.commands], + } + }, + CompletedWrite: ({ action, result }) => + Result.match(result, { + onSuccess: (document) => settled(model, action, document), + onFailure: (failure) => failed(model, failure), + }), + CompletedIssueToken: ({ action, result }) => + Result.match(result, { + onSuccess: ({ document, token }) => { + const step = settled(model, action, document) + const revealed = openDialog( + { + ...step.model, + issuedToken: token, + copies: { ...step.model.copies, token: CopyButton.init() }, + }, + "tokenDialog", + ) + return { ...merge(step, revealed), outMessage: step.outMessage } + }, + onFailure: (failure) => failed(model, failure), + }), + GotCopyMessage: ({ key, message: child }) => { + const step = CopyButton.update(model.copies[key] ?? CopyButton.init(), child) + return { + model: { ...model, copies: { ...model.copies, [key]: step.model } }, + commands: Command.mapMessages(step.commands ?? [], (inner) => + Message.GotCopyMessage({ key, message: inner }), + ), + } + }, + GotSelectMessage: ({ key, message: child }) => { + const step = Select.update(selectModel(model, key), child) + const next = { ...model, selects: { ...model.selects, [key]: step.model } } + const commands = Command.mapMessages(step.commands ?? [], (inner) => + Message.GotSelectMessage({ key, message: inner }), + ) + return { + model: step.outMessage === undefined ? next : applyPick(next, key, step.outMessage.value), + commands, + } + }, + + // Domains + ClickedAddDomain: () => (model.canManage ? openDialog(model, "addDomainDialog") : { model }), + GotAddDomainDialogMessage: ({ message: child }) => updateDialog(model, "addDomainDialog", child), + GotDomainFieldMessage: ({ message: child }) => fieldStep(model, child), + SubmittedAddDomain: () => { + const domain = normalizeDomain(model.domainField.value) + return domain === "" ? { model } : startWrite(model, "addDomain", AddSsoDomain({ domain })) + }, + ClickedVerifyDomain: ({ domain }) => startWrite(model, "verifyDomain", VerifySsoDomain({ domain })), + GotDomainMenuMessage: ({ domain, message: child }) => { + const menuId = `sso-domain-${domain}` + const step = Menu.update(model.domainMenus[menuId] ?? Menu.init(menuId), child) + const next = { ...model, domainMenus: { ...model.domainMenus, [menuId]: step.model } } + const commands = Command.mapMessages(step.commands ?? [], (inner) => + Message.GotDomainMenuMessage({ domain, message: inner }), + ) + if (step.outMessage?._tag !== "SelectedItem") return { model: next, commands } + if (step.outMessage.value === "verify") + return merge( + { model: next, commands }, + startWrite(next, "verifyDomain", VerifySsoDomain({ domain })), + ) + return merge( + { model: next, commands }, + openDialog({ ...next, removingDomain: domain }, "removeDomainDialog"), + ) + }, + GotRemoveDomainDialogMessage: ({ message: child }) => + updateDialog(model, "removeDomainDialog", child), + ClickedConfirmRemoveDomain: () => + model.removingDomain === null + ? { model } + : startWrite(model, "removeDomain", RemoveSsoDomain({ domain: model.removingDomain })), + + // Identity provider + ClickedConnect: () => { + const document = documentOf(model) + return document === null || !model.canManage + ? { model } + : openDialog({ ...model, draft: newDraft(document), selects: {} }, "connectionDialog") + }, + ClickedEditConnection: () => { + const connection = documentOf(model)?.connection ?? null + return connection === null || !model.canManage + ? { model } + : openDialog({ ...model, draft: editDraft(connection), selects: {} }, "connectionDialog") + }, + GotConnectionDialogMessage: ({ message: child }) => { + const step = updateDialog(model, "connectionDialog", child) + return step.model.connectionDialog.isOpen + ? step + : { ...step, model: { ...step.model, draft: null } } + }, + GotDraftFieldMessage: ({ field, message: child }) => { + const draft = model.draft + if (draft === null) return { model } + const step = Field.update(draft.fields[field] ?? Field.init(), child) + return { + model: { ...model, draft: { ...draft, fields: { ...draft.fields, [field]: step.model } } }, + commands: Command.mapMessages(step.commands ?? [], (inner) => + Message.GotDraftFieldMessage({ field, message: inner }), + ), + } + }, + PickedSamlMode: ({ mode }) => + model.draft === null + ? { model } + : { model: { ...model, draft: { ...model.draft, samlMode: mode } } }, + ToggledDraftDomain: ({ domain }) => { + const draft = model.draft + if (draft === null) return { model } + const domains = draft.domains.includes(domain) + ? Arr.filter(draft.domains, (current) => current !== domain) + : [...draft.domains, domain] + return { model: { ...model, draft: { ...draft, domains } } } + }, + SubmittedConnection: () => { + const draft = model.draft + if (draft === null) return { model } + return Option.match(requestOf(draft), { + onNone: () => ({ model }), + onSome: (request) => + startWrite( + model, + draft.mode === "create" ? "createConnection" : "updateConnection", + SaveSsoConnection({ mode: draft.mode, request }), + ), + }) + }, + ToggledEnforcement: () => { + const connection = documentOf(model)?.connection ?? null + if (connection === null || !model.canManage || model.pending !== null) return { model } + return connection.enforced + ? startWrite(model, "unenforce", SetSsoEnforcement({ enforced: false })) + : openDialog(model, "enforceDialog") + }, + GotEnforceDialogMessage: ({ message: child }) => updateDialog(model, "enforceDialog", child), + ClickedConfirmEnforce: () => startWrite(model, "enforce", SetSsoEnforcement({ enforced: true })), + ClickedRemoveConnection: () => + model.canManage ? openDialog(model, "removeConnectionDialog") : { model }, + GotRemoveConnectionDialogMessage: ({ message: child }) => + updateDialog(model, "removeConnectionDialog", child), + ClickedConfirmRemoveConnection: () => startWrite(model, "deleteConnection", DeleteSsoConnection()), + + // Break-glass + ClickedAddBypass: () => { + if (!model.canManage) return { model } + const members = retryMembers(model) + const opened = openDialog({ ...model, bypassPick: null, members: members.data }, "bypassDialog") + return { ...opened, commands: [...(opened.commands ?? []), ...members.commands] } + }, + GotBypassDialogMessage: ({ message: child }) => updateDialog(model, "bypassDialog", child), + SubmittedBypass: () => + Option.match(Schema.decodeUnknownOption(UserId)(model.bypassPick), { + onNone: () => ({ model }), + onSome: (userId) => startWrite(model, "addBypass", AddSsoBypassUser({ userId })), + }), + ClickedRemoveBypass: ({ userId }) => + model.canManage + ? openDialog({ ...model, removingBypass: userId }, "removeBypassDialog") + : { model }, + GotRemoveBypassDialogMessage: ({ message: child }) => + updateDialog(model, "removeBypassDialog", child), + ClickedConfirmRemoveBypass: () => + Option.match(Schema.decodeUnknownOption(UserId)(model.removingBypass), { + onNone: () => ({ model }), + onSome: (userId) => startWrite(model, "removeBypass", RemoveSsoBypassUser({ userId })), + }), + + // SCIM + ClickedSetUpScim: () => startWrite(model, "createDirectory", IssueScimToken({ kind: "create" })), + ClickedTogglePaused: () => { + const directory = documentOf(model)?.directory ?? null + if (directory === null) return { model } + const paused = !directory.paused + return startWrite(model, paused ? "pause" : "resume", SetScimDirectoryState({ paused })) + }, + ClickedRotateToken: () => (model.canManage ? openDialog(model, "rotateDialog") : { model }), + GotRotateDialogMessage: ({ message: child }) => updateDialog(model, "rotateDialog", child), + ClickedConfirmRotate: () => startWrite(model, "rotateToken", IssueScimToken({ kind: "rotate" })), + GotTokenDialogMessage: ({ message: child }) => { + const step = updateDialog(model, "tokenDialog", child) + if (step.model.tokenDialog.isOpen) return step + // Closed: the token leaves the model for good. + const { token: _token, ...copies } = step.model.copies + return { ...step, model: { ...step.model, issuedToken: null, copies } } + }, + ClickedRemoveDirectory: () => + model.canManage ? openDialog(model, "removeDirectoryDialog") : { model }, + GotRemoveDirectoryDialogMessage: ({ message: child }) => + updateDialog(model, "removeDirectoryDialog", child), + ClickedConfirmRemoveDirectory: () => startWrite(model, "deleteDirectory", DeleteScimDirectory()), + ClickedAddMapping: () => { + const rows = mappingRows(model) + const used = Arr.map(rows, (row) => row.groupId) + const groupId = Option.match( + Arr.findFirst(documentOf(model)?.groups ?? [], (group) => !used.includes(group.groupId)), + { onNone: () => "", onSome: (group) => group.groupId }, + ) + return { + model: { + ...withRows(model, [ + ...rows, + { key: `new-${model.nextMappingKey}`, groupId, role: "org:member" }, + ]), + nextMappingKey: model.nextMappingKey + 1, + }, + } + }, + ClickedMoveMapping: ({ key, by }) => ({ + model: withRows(model, moveRow(mappingRows(model), key, by)), + }), + ClickedRemoveMapping: ({ key }) => ({ + model: withRows( + model, + Arr.filter(mappingRows(model), (row) => row.key !== key), + ), + }), + ClickedDiscardMappings: () => ({ model: { ...model, mappings: null, selects: {} } }), + ClickedSaveMappings: () => { + const rows = mappingRows(model) + if (model.mappings === null || !isMappingsValid(rows)) return { model } + return startWrite( + model, + "saveMappings", + SetScimRoleMappings({ + mappings: Arr.map(rows, (row) => ({ groupId: row.groupId, role: row.role })), + }), + ) + }, + }) diff --git a/apps/web/src/page/settings/sso/view.ts b/apps/web/src/page/settings/sso/view.ts new file mode 100644 index 0000000000..9800509a7b --- /dev/null +++ b/apps/web/src/page/settings/sso/view.ts @@ -0,0 +1,1318 @@ +import { formatDateInTimezone } from "@maple/ui/lib/timezone-format" +import type { + EnterpriseSsoDocument, + ScimDirectoryDocument, + SsoConnectionDocument, + SsoDomainDocument, + SsoMappedRole, + SsoProvider, +} from "@maple/domain/http" +import { ssoProtocolOf } from "@maple/domain/http" +import { Array as Arr, Option } from "effect" +import { AsyncData, Submodel } from "foldkit" +import type { Html, HtmlBuilder } from "foldkit/html" +import { alert, alertDescription, alertTitle } from "@maple/views/ui/alert" +import { button, linkButton } from "@maple/views/ui/button" +import { confirmDialog } from "@maple/views/ui/confirm-dialog" +import * as CopyButton from "@maple/views/ui/copy-button" +import { copyableField } from "@maple/views/ui/copyable-field" +import * as DialogView from "@maple/views/ui/dialog-view" +import { badge } from "@maple/views/ui/display" +import { + empty, + emptyContent, + emptyDescription, + emptyHeader, + emptyMedia, + emptyTitle, +} from "@maple/views/ui/empty" +import { errorState } from "@maple/views/ui/error-state" +import * as Field from "@maple/views/ui/field" +import { + field, + type FieldIds, + fieldDescription, + fieldGroupLabel, + fieldLabel, + input, +} from "@maple/views/ui/field" +import { formDialog } from "@maple/views/ui/form-dialog" +import { icon } from "@maple/views/ui/icon" +import { iconButton } from "@maple/views/ui/icon-button" +import { keyValue, keyValueList } from "@maple/views/ui/key-value" +import * as Menu from "@maple/views/ui/menu" +import { rowActionsMenu } from "@maple/views/ui/row-actions-menu" +import { dividedList, strip } from "@maple/views/ui/rule" +import { multiSegmentedSelect, segmentedSelect } from "@maple/views/ui/segmented-select" +import * as Select from "@maple/views/ui/select" +import * as SelectView from "@maple/views/ui/select-view" +import { skeleton } from "@maple/views/ui/skeleton" +import { hstack, vstack } from "@maple/views/ui/stack" +import { table, tableBody, tableCell, tableHead, tableHeader, tableRow } from "@maple/views/ui/table" +import { textarea } from "@maple/views/ui/textarea" +import { typography } from "@maple/views/ui/typography" +import { ENTERPRISE_CONTACT_URL } from "../../onboarding/pricing-cards" +import { switchRow } from "../../kit/switch-row" +import { adminOnlyNote, sectionNote, settingsSection, settingsSections } from "../../kit/settings-section" +import { type ConnectionDraft, type DraftField, type MappingDraft, Message, type Model } from "./model" +import { + documentOf, + isMappingsValid, + MAPPED_ROLES, + mappingRows, + normalizeDomain, + PROVIDERS, + requestOf, + draftProblem, + verifiedDomains, +} from "./update" + +type H = HtmlBuilder + +export const description = "Sign your team in through your identity provider and provision members over SCIM." + +export const PROVIDER_LABELS = { + saml_okta: "Okta (SAML)", + saml_microsoft: "Microsoft Entra ID (SAML)", + saml_google: "Google Workspace (SAML)", + saml_custom: "Other SAML provider", + oidc_github_enterprise: "GitHub Enterprise (OIDC)", + oidc_gitlab: "GitLab (OIDC)", + oidc_custom: "Other OIDC provider", +} as const satisfies Record + +export const ROLE_LABELS = { + "org:admin": "Admin", + "org:engineer": "Engineer", + "org:member": "Member", + "org:analyst": "Analyst", +} as const satisfies Record + +const PROVIDER_ENTRIES: ReadonlyArray = Arr.map(PROVIDERS, (provider) => ({ + _tag: "Item", + item: { value: provider, label: PROVIDER_LABELS[provider] }, +})) + +const ROLE_ENTRIES: ReadonlyArray = Arr.map(MAPPED_ROLES, (role) => ({ + _tag: "Item", + item: { value: role, label: ROLE_LABELS[role] }, +})) + +/** Set-up writes are open to admins on an entitled org. */ +const canEdit = (model: Model, document: EnterpriseSsoDocument): boolean => + model.canManage && document.entitled + +/** Turning things off or removing them stays open to admins after the plan lapses, as the API allows. */ +const canExit = (model: Model): boolean => model.canManage + +const isBusy = (model: Model): boolean => model.pending !== null + +// Shared pieces + +const copyStatus = (model: Model, key: string): CopyButton.CopyStatus => model.copies[key]?.status ?? "idle" + +const copyValue = (h: H, model: Model, key: string, label: string, value: string): Html => + keyValue( + h, + { + label, + mono: true, + copy: { + status: copyStatus(model, key), + onCopy: Message.GotCopyMessage({ + key, + message: CopyButton.Message.ClickedCopy({ text: value }), + }), + }, + }, + [value], + ) + +const plainValue = (h: H, label: string, value: string, mono = false): Html => + keyValue(h, { label, mono }, [value]) + +type SelectOptions = Readonly<{ + key: string + value: string + label: string + entries: ReadonlyArray + ariaLabel?: string + labelledBy?: string + isDisabled?: boolean +}> + +const selectControl = (h: H, model: Model, options: SelectOptions): Html => { + const id = `sso-select-${options.key}` + const base = + model.selects[options.key] ?? + Select.init(id, { + value: options.value, + selectedIndex: SelectView.selectedIndexOf(options.entries, options.value), + }) + return h.submodel({ + slotId: id, + model: { ...base, value: options.value }, + view: SelectView.view, + toParentMessage: (message) => Message.GotSelectMessage({ key: options.key, message }), + viewInputs: { + entries: options.entries, + ariaLabel: options.ariaLabel, + labelledBy: options.labelledBy, + size: "sm", + isDisabled: options.isDisabled ?? false, + className: "w-full min-w-0", + renderValue: () => [options.label], + toView: (parts) => h.div([h.Class("contents")], parts), + }, + }) +} + +// Not entitled + +const notEntitled = (h: H): Html => + alert(h, { role: "status" }, [ + icon(h, "LockIcon"), + alertTitle(h, ["SSO and SCIM are part of the Enterprise plan"]), + alertDescription(h, [ + typography(h, { size: "sm", tone: "muted", as: "p", className: "font-prose" }, [ + "Sign in through Okta, Entra ID, Google Workspace or any SAML or OIDC provider, and provision members over SCIM.", + ]), + hstack(h, { gap: "2", className: "mt-3" }, [ + linkButton( + h, + { + size: "sm", + href: ENTERPRISE_CONTACT_URL, + attributes: [h.Target("_blank"), h.Rel("noreferrer")], + }, + ["Contact sales"], + ), + ]), + ]), + ]) + +// Domains + +const domainStatus = (h: H, domain: SsoDomainDocument): Html => + domain.status === "verified" + ? badge(h, { variant: "done" }, ["Verified"]) + : badge(h, { variant: "muted" }, ["Pending"]) + +const domainRow = (h: H, model: Model, domain: SsoDomainDocument, isEditable: boolean): Html => { + const menuId = `sso-domain-${domain.domain}` + return tableRow( + h, + [ + tableCell(h, [typography(h, { size: "xs", weight: "medium", truncate: true }, [domain.domain])]), + tableCell(h, [domainStatus(h, domain)], "w-28"), + tableCell( + h, + isEditable + ? [ + rowActionsMenu(h, { + slotId: menuId, + model: model.domainMenus[menuId] ?? Menu.init(menuId), + label: `Actions for ${domain.domain}`, + entries: [ + ...(domain.status === "verified" + ? [] + : [ + { + _tag: "Item" as const, + value: "verify", + label: "Verify", + icon: "CircleCheckIcon" as const, + }, + ]), + { + _tag: "Item", + value: "remove", + label: "Remove", + icon: "TrashIcon", + variant: "destructive", + }, + ], + toParentMessage: (message) => + Message.GotDomainMenuMessage({ domain: domain.domain, message }), + }), + ] + : [], + "w-12", + ), + ], + undefined, + [h.Key(domain.domain)], + ) +} + +const pendingRecord = (h: H, model: Model, domain: SsoDomainDocument, isEditable: boolean): Html => + strip(h, { kind: "block", attributes: [h.Key(`record-${domain.domain}`)] }, [ + vstack(h, { gap: "3", align: "stretch" }, [ + hstack(h, { gap: "2", justify: "between" }, [ + typography(h, { size: "sm", weight: "medium" }, [`Verify ${domain.domain}`]), + ...(isEditable + ? [ + button( + h, + { + variant: "outline", + size: "sm", + isLoading: model.pending === "verifyDomain", + isDisabled: isBusy(model), + attributes: [ + h.OnClick(Message.ClickedVerifyDomain({ domain: domain.domain })), + ], + }, + ["Verify"], + ), + ] + : []), + ]), + typography(h, { size: "xs", tone: "muted", as: "p", className: "font-prose" }, [ + "Add this TXT record at your DNS provider. DNS changes can take a few minutes to show.", + ]), + keyValueList(h, { layout: "stacked" }, [ + copyValue(h, model, `record-name-${domain.domain}`, "Name", domain.recordName), + copyValue(h, model, `record-value-${domain.domain}`, "Value", domain.recordValue), + ]), + ]), + ]) + +const domainsSection = (h: H, model: Model, document: EnterpriseSsoDocument): Html => { + const isEditable = canEdit(model, document) + const pending = Arr.filter(document.domains, (domain) => domain.status === "pending") + return settingsSection( + h, + { + id: "settings-sso-domains", + title: "Domains", + description: [ + "The email domains your identity provider signs in. Prove you own each one with a DNS record.", + ], + padded: false, + actions: isEditable + ? button( + h, + { + size: "sm", + variant: "outline", + attributes: [h.OnClick(Message.ClickedAddDomain())], + }, + [ + icon(h, "PlusIcon", { attributes: [h.DataAttribute("icon", "inline-start")] }), + "Add domain", + ], + ) + : undefined, + }, + document.domains.length === 0 + ? [sectionNote(h, "No domains yet. Add the domain your team's email addresses use.")] + : [ + table(h, { className: "table-fixed" }, [ + tableHeader(h, [ + tableRow(h, [ + tableHead(h, ["Domain"]), + tableHead(h, ["Status"], "w-28"), + tableHead(h, [], "w-12"), + ]), + ]), + tableBody( + h, + Arr.map(document.domains, (domain) => domainRow(h, model, domain, isEditable)), + ), + ]), + ...Arr.map(pending, (domain) => pendingRecord(h, model, domain, isEditable)), + ], + ) +} + +// Identity provider + +const spValues = (h: H, model: Model, connection: SsoConnectionDocument): ReadonlyArray => + Arr.flatMap( + [ + ["acs", "ACS URL", connection.acsUrl], + ["entity", "SP entity ID", connection.spEntityId], + ["metadata", "SP metadata URL", connection.spMetadataUrl], + ] as const, + ([key, label, value]) => (value === null ? [] : [copyValue(h, model, `sp-${key}`, label, value)]), + ) + +const idpValues = (h: H, connection: SsoConnectionDocument): ReadonlyArray => + Arr.flatMap( + [ + ["Provider", PROVIDER_LABELS[connection.provider], false], + ["Domains", Arr.join(connection.domains, ", "), false], + ["Metadata URL", connection.idpMetadataUrl, true], + ["SSO URL", connection.idpSsoUrl, true], + ["Entity ID", connection.idpEntityId, true], + [ + "Certificate expires", + connection.idpCertificateExpiresAt === null + ? null + : formatDateInTimezone(connection.idpCertificateExpiresAt, { timeZone: "UTC" }), + false, + ], + ["Discovery URL", connection.oidcDiscoveryUrl, true], + ["Client ID", connection.oidcClientId, true], + ] as const, + ([label, value, mono]) => (value === null ? [] : [plainValue(h, label, value, mono)]), + ) + +const connectionPanel = ( + h: H, + model: Model, + document: EnterpriseSsoDocument, + connection: SsoConnectionDocument, +): ReadonlyArray => { + const isEditable = canEdit(model, document) + const isExitable = canExit(model) + const sp = spValues(h, model, connection) + return [ + vstack(h, { gap: "4", align: "stretch" }, [ + hstack(h, { gap: "2", justify: "between", wrap: true }, [ + hstack(h, { gap: "2" }, [ + typography(h, { size: "sm", weight: "medium" }, [connection.name]), + connection.enforced + ? badge(h, { variant: "done" }, ["Required"]) + : badge(h, { variant: "muted" }, ["Optional"]), + ]), + ...(isExitable + ? [ + hstack(h, { gap: "2" }, [ + ...(isEditable + ? [ + button( + h, + { + variant: "outline", + size: "sm", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedEditConnection())], + }, + ["Edit"], + ), + ] + : []), + button( + h, + { + variant: "destructive-outline", + size: "sm", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedRemoveConnection())], + }, + ["Remove"], + ), + ]), + ] + : []), + ]), + ...(sp.length === 0 + ? [] + : [ + typography(h, { size: "xs", tone: "muted", as: "p", className: "font-prose" }, [ + "Paste these into your identity provider.", + ]), + keyValueList(h, { layout: "stacked" }, sp), + ]), + keyValueList(h, { layout: "split", divided: true }, idpValues(h, connection)), + ]), + strip(h, { kind: "block", className: "-mx-4 -mb-4 mt-4" }, [ + switchRow(h, { + id: "sso-enforce", + label: "Require SSO", + description: `Everyone with an email on ${Arr.join(connection.domains, ", ")} must sign in through ${connection.name}. Break-glass members can still sign in with an email code.`, + isChecked: connection.enforced, + // Without the plan, an enforced connection can still be relaxed, never enforced again. + isDisabled: !(isEditable || (isExitable && connection.enforced)) || isBusy(model), + onToggle: Message.ToggledEnforcement(), + }), + ]), + ] +} + +const noConnection = (h: H, model: Model, document: EnterpriseSsoDocument): Html => { + const hasVerified = verifiedDomains(document).length > 0 + return empty(h, [ + emptyHeader(h, [ + emptyMedia(h, {}, [icon(h, "ShieldIcon", { size: 20 })]), + emptyTitle(h, ["No identity provider"]), + emptyDescription(h, [ + hasVerified + ? "Connect Okta, Entra ID, Google Workspace or any SAML or OIDC provider." + : "Verify a domain first, then connect your identity provider.", + ]), + ]), + ...(canEdit(model, document) + ? [ + emptyContent(h, [ + button( + h, + { + size: "sm", + isDisabled: !hasVerified || isBusy(model), + attributes: [h.OnClick(Message.ClickedConnect())], + }, + ["Connect identity provider"], + ), + ]), + ] + : []), + ]) +} + +const connectionSection = (h: H, model: Model, document: EnterpriseSsoDocument): Html => + settingsSection( + h, + { + id: "settings-sso-connection", + title: "Identity provider", + padded: document.connection !== null, + }, + document.connection === null + ? [noConnection(h, model, document)] + : connectionPanel(h, model, document, document.connection), + ) + +// Break-glass + +const memberLabel = (model: Model, userId: string, identifier: string | null): string => + Option.match( + Option.flatMap(AsyncData.getData(model.members), (members) => + Arr.findFirst(members, (member) => member.userId === userId), + ), + { onNone: () => identifier ?? userId, onSome: (member) => member.name }, + ) + +const bypassSection = (h: H, model: Model, document: EnterpriseSsoDocument): Html => { + const isEditable = canEdit(model, document) + return settingsSection( + h, + { + id: "settings-sso-bypass", + title: "Break-glass access", + description: [ + "These members can sign in with an email code when the identity provider is down. Only members with a verified email on the SSO domains can be added.", + ], + padded: false, + // Nobody qualifies before a connection names the SSO domains. + actions: + isEditable && document.connection !== null + ? button( + h, + { + size: "sm", + variant: "outline", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedAddBypass())], + }, + ["Add member"], + ) + : undefined, + }, + document.bypassUsers.length === 0 + ? [sectionNote(h, "No break-glass members. Add one before you require SSO.")] + : [ + dividedList( + h, + { as: "ul", bordered: false }, + Arr.map(document.bypassUsers, (user) => + h.li( + [h.Key(user.userId)], + [ + hstack(h, { gap: "2", justify: "between", className: "px-4 py-2.5" }, [ + vstack(h, { gap: "0.5", align: "start", className: "min-w-0" }, [ + typography(h, { size: "sm", weight: "medium", truncate: true }, [ + memberLabel(model, user.userId, user.identifier), + ]), + ...(user.identifier === null + ? [] + : [ + typography( + h, + { size: "xs", tone: "muted", truncate: true }, + [user.identifier], + ), + ]), + ]), + ...(canExit(model) + ? [ + iconButton( + h, + { + label: "Remove break-glass access", + isDisabled: isBusy(model), + attributes: [ + h.OnClick( + Message.ClickedRemoveBypass({ + userId: user.userId, + }), + ), + ], + }, + [icon(h, "TrashIcon")], + ), + ] + : []), + ]), + ], + ), + ), + ), + ], + ) +} + +// SCIM + +const directoryPanel = ( + h: H, + model: Model, + document: EnterpriseSsoDocument, + directory: ScimDirectoryDocument, +): ReadonlyArray => { + const isEditable = canEdit(model, document) + // Pausing and removing stay open without the plan; resuming and rotating need it. + const canTogglePause = directory.paused ? isEditable : canExit(model) + return [ + vstack(h, { gap: "4", align: "stretch" }, [ + hstack(h, { gap: "2", justify: "between", wrap: true }, [ + hstack(h, { gap: "2" }, [ + typography(h, { size: "sm", weight: "medium" }, ["SCIM 2.0"]), + directory.paused + ? badge(h, { variant: "warn" }, ["Paused"]) + : badge(h, { variant: "done" }, ["Active"]), + ]), + ...(canExit(model) + ? [ + hstack(h, { gap: "2", wrap: true }, [ + ...(canTogglePause + ? [ + button( + h, + { + variant: "outline", + size: "sm", + isLoading: + model.pending === "pause" || + model.pending === "resume", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedTogglePaused())], + }, + [directory.paused ? "Resume" : "Pause"], + ), + ] + : []), + ...(isEditable + ? [ + button( + h, + { + variant: "outline", + size: "sm", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedRotateToken())], + }, + ["Rotate token"], + ), + ] + : []), + button( + h, + { + variant: "destructive-outline", + size: "sm", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedRemoveDirectory())], + }, + ["Remove"], + ), + ]), + ] + : []), + ]), + keyValueList(h, { layout: "stacked" }, [ + copyValue(h, model, "scim-endpoint", "Endpoint URL", directory.endpointUrl), + ]), + typography(h, { size: "xs", tone: "muted", as: "p", className: "font-prose" }, [ + directory.paused + ? "Your identity provider's pushes are refused while provisioning is paused." + : "Your identity provider creates, updates and removes members through this endpoint.", + ]), + ]), + ] +} + +const noDirectory = (h: H, model: Model, document: EnterpriseSsoDocument): Html => + empty(h, [ + emptyHeader(h, [ + emptyMedia(h, {}, [icon(h, "UsersIcon", { size: 20 })]), + emptyTitle(h, ["SCIM is not set up"]), + emptyDescription(h, [ + "Let your identity provider add and remove members, and set their role from its groups.", + ]), + ]), + ...(canEdit(model, document) + ? [ + emptyContent(h, [ + button( + h, + { + size: "sm", + isLoading: model.pending === "createDirectory", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedSetUpScim())], + }, + ["Set up SCIM"], + ), + ]), + ] + : []), + ]) + +const scimSection = (h: H, model: Model, document: EnterpriseSsoDocument): Html => + settingsSection( + h, + { id: "settings-sso-scim", title: "SCIM provisioning", padded: document.directory !== null }, + document.directory === null + ? [noDirectory(h, model, document)] + : directoryPanel(h, model, document, document.directory), + ) + +const groupLabel = (document: EnterpriseSsoDocument, groupId: string): string => { + if (groupId === "") return "Pick a group" + return Option.getOrElse( + Option.orElse( + Option.map( + Arr.findFirst(document.groups, (group) => group.groupId === groupId), + (group) => group.displayName, + ), + () => + Option.flatMap( + Arr.findFirst(document.roleMappings, (mapping) => mapping.groupId === groupId), + (mapping) => Option.fromNullishOr(mapping.groupName), + ), + ), + () => groupId, + ) +} + +const groupEntries = ( + document: EnterpriseSsoDocument, + row: MappingDraft, +): ReadonlyArray => { + const known = Arr.map(document.groups, (group): SelectView.SelectEntry => ({ + _tag: "Item", + item: { value: group.groupId, label: group.displayName }, + })) + // A mapped group the IdP no longer pushes still shows, so the row reads what it holds. + const isKnown = row.groupId === "" || Arr.some(document.groups, (group) => group.groupId === row.groupId) + return isKnown + ? known + : [...known, { _tag: "Item", item: { value: row.groupId, label: groupLabel(document, row.groupId) } }] +} + +const mappingRow = ( + h: H, + model: Model, + document: EnterpriseSsoDocument, + row: MappingDraft, + index: number, + count: number, + isEditable: boolean, +): Html => + h.li( + [h.Key(row.key)], + [ + hstack(h, { gap: "2", className: "px-4 py-2.5" }, [ + typography(h, { size: "xs", tone: "muted", numeric: true, className: "w-5 shrink-0" }, [ + String(index + 1), + ]), + h.div( + [h.Class("min-w-0 flex-1")], + [ + selectControl(h, model, { + key: `group-${row.key}`, + value: row.groupId, + label: groupLabel(document, row.groupId), + entries: groupEntries(document, row), + ariaLabel: `Group for mapping ${index + 1}`, + isDisabled: !isEditable || isBusy(model), + }), + ], + ), + h.div( + [h.Class("w-36 shrink-0")], + [ + selectControl(h, model, { + key: `role-${row.key}`, + value: row.role, + label: ROLE_LABELS[row.role], + entries: ROLE_ENTRIES, + ariaLabel: `Role for mapping ${index + 1}`, + isDisabled: !isEditable || isBusy(model), + }), + ], + ), + ...(isEditable + ? [ + iconButton( + h, + { + label: "Move up", + isDisabled: index === 0 || isBusy(model), + attributes: [ + h.OnClick(Message.ClickedMoveMapping({ key: row.key, by: -1 })), + ], + }, + [icon(h, "ArrowUpIcon")], + ), + iconButton( + h, + { + label: "Move down", + isDisabled: index === count - 1 || isBusy(model), + attributes: [ + h.OnClick(Message.ClickedMoveMapping({ key: row.key, by: 1 })), + ], + }, + [icon(h, "ArrowDownIcon")], + ), + iconButton( + h, + { + label: "Remove mapping", + isDisabled: isBusy(model), + attributes: [h.OnClick(Message.ClickedRemoveMapping({ key: row.key }))], + }, + [icon(h, "TrashIcon")], + ), + ] + : []), + ]), + ], + ) + +const mappingsSection = (h: H, model: Model, document: EnterpriseSsoDocument): Html => { + const isEditable = canEdit(model, document) + const rows = mappingRows(model) + const isDirty = model.mappings !== null + const hasGroups = document.groups.length > 0 + return settingsSection( + h, + { + id: "settings-sso-mappings", + title: "Role mapping", + description: [ + "Members get the role of the first group that matches, top to bottom. Members in no mapped group join as members. A change applies the next time your identity provider pushes the group (in Okta, Push Groups then Push now).", + ], + padded: false, + }, + [ + ...(hasGroups + ? [] + : [sectionNote(h, "Groups appear here after your identity provider pushes them over SCIM.")]), + ...(rows.length === 0 + ? hasGroups + ? [sectionNote(h, "No mappings yet.")] + : [] + : [ + dividedList( + h, + { as: "ol", bordered: false }, + Arr.map(rows, (row, index) => + mappingRow(h, model, document, row, index, rows.length, isEditable), + ), + ), + ]), + ...(isEditable && (hasGroups || isDirty) + ? [ + strip(h, { kind: "foot" }, [ + hstack(h, { gap: "2", justify: "between" }, [ + button( + h, + { + variant: "ghost", + size: "sm", + isDisabled: !hasGroups || isBusy(model), + attributes: [h.OnClick(Message.ClickedAddMapping())], + }, + [ + icon(h, "PlusIcon", { + attributes: [h.DataAttribute("icon", "inline-start")], + }), + "Add mapping", + ], + ), + hstack(h, { gap: "2" }, [ + ...(isDirty + ? [ + button( + h, + { + variant: "ghost", + size: "sm", + isDisabled: isBusy(model), + attributes: [ + h.OnClick(Message.ClickedDiscardMappings()), + ], + }, + ["Discard"], + ), + ] + : []), + button( + h, + { + size: "sm", + isLoading: model.pending === "saveMappings", + isDisabled: !isDirty || !isMappingsValid(rows) || isBusy(model), + attributes: [h.OnClick(Message.ClickedSaveMappings())], + }, + ["Save"], + ), + ]), + ]), + ]), + ] + : []), + ], + ) +} + +// Dialogs + +const DOMAIN_IDS: FieldIds = { control: "sso-domain", label: "sso-domain-label", error: "sso-domain-error" } + +const addDomainDialog = (h: H, model: Model): Html => { + const state = Field.stateOf(model.domainField, false) + return formDialog(h, { + slotId: "sso-domain-add", + model: model.addDomainDialog, + toParentMessage: (message) => Message.GotAddDomainDialogMessage({ message }), + title: "Add domain", + description: "Next you'll publish a TXT record on it to prove your team owns it.", + onSubmit: Message.SubmittedAddDomain(), + submitLabel: "Add domain", + isPending: model.pending === "addDomain", + isSubmitDisabled: normalizeDomain(model.domainField.value) === "", + fields: [ + field(h, { state }, [ + fieldLabel(h, { ids: DOMAIN_IDS, state }, "Domain"), + input(h, { + ids: DOMAIN_IDS, + state, + attributes: [ + h.Placeholder("acme.com"), + h.Autocomplete("off"), + ...Field.controlAttributes(h, model.domainField, (message) => + Message.GotDomainFieldMessage({ message }), + ), + ], + }), + ]), + ], + }) +} + +const draftIds = (key: DraftField): FieldIds => ({ + control: `sso-draft-${key}`, + label: `sso-draft-${key}-label`, + error: `sso-draft-${key}-error`, + description: `sso-draft-${key}-hint`, +}) + +const draftInput = ( + h: H, + draft: ConnectionDraft, + key: DraftField, + label: string, + options: Readonly<{ placeholder?: string; hint?: string; isSecret?: boolean }> = {}, +): Html => { + const model = draft.fields[key] ?? Field.init() + const ids = draftIds(key) + const state = Field.stateOf(model, false) + return field(h, { state }, [ + fieldLabel(h, { ids, state }, label), + input(h, { + ids, + state, + attributes: [ + h.Autocomplete("off"), + ...(options.isSecret === true ? [h.Type("password")] : []), + ...(options.placeholder === undefined ? [] : [h.Placeholder(options.placeholder)]), + ...Field.controlAttributes(h, model, (message) => + Message.GotDraftFieldMessage({ field: key, message }), + ), + ], + }), + ...(options.hint === undefined ? [] : [fieldDescription(h, { ids, state }, options.hint)]), + ]) +} + +const certificateInput = (h: H, draft: ConnectionDraft): Html => { + const model = draft.fields.certificate ?? Field.init() + const ids = draftIds("certificate") + const state = Field.stateOf(model, false) + return field(h, { state }, [ + fieldLabel(h, { ids, state }, "Signing certificate"), + textarea(h, { + id: ids.control, + controlClassName: "font-mono text-xs", + attributes: [ + h.Rows(5), + h.Placeholder("-----BEGIN CERTIFICATE-----"), + h.AriaLabelledBy(ids.label), + h.Value(model.value), + h.OnInput((value) => + Message.GotDraftFieldMessage({ + field: "certificate", + message: Field.Message.ChangedValue({ value }), + }), + ), + ], + }), + ...(draft.mode === "edit" + ? [fieldDescription(h, { ids, state }, "Leave empty to keep the current certificate.")] + : []), + ]) +} + +const protocolFields = (h: H, draft: ConnectionDraft): ReadonlyArray => { + if (ssoProtocolOf(draft.provider) === "oidc") + return [ + draftInput(h, draft, "discoveryUrl", "Discovery URL", { + placeholder: "https://idp.example.com/.well-known/openid-configuration", + }), + draftInput(h, draft, "clientId", "Client ID"), + draftInput(h, draft, "clientSecret", "Client secret", { + isSecret: true, + ...(draft.mode === "edit" && { hint: "Leave empty to keep the current secret." }), + }), + ] + return [ + vstack(h, { gap: "2", align: "stretch" }, [ + fieldGroupLabel(h, {}, "SAML settings"), + segmentedSelect(h, { + options: [ + { value: "metadata", label: "Metadata URL" }, + { value: "manual", label: "Enter manually" }, + ], + value: draft.samlMode, + onChange: (mode) => Message.PickedSamlMode({ mode }), + ariaLabel: "How to configure SAML", + size: "sm", + }), + ]), + ...(draft.samlMode === "metadata" + ? [ + draftInput(h, draft, "metadataUrl", "IdP metadata URL", { + placeholder: "https://idp.example.com/metadata.xml", + }), + ] + : [ + draftInput(h, draft, "ssoUrl", "IdP SSO URL", { + placeholder: "https://idp.example.com/sso", + }), + draftInput(h, draft, "entityId", "IdP entity ID"), + certificateInput(h, draft), + ]), + ] +} + +const footerReason = (h: H, reason: string | null): { readonly footerStart?: Html } => + reason === null ? {} : { footerStart: typography(h, { size: "xs", tone: "muted" }, [reason]) } + +const connectionDialog = (h: H, model: Model, document: EnterpriseSsoDocument | null): Html => { + const draft = model.draft + const verified = document === null ? [] : verifiedDomains(document) + const isEdit = draft?.mode === "edit" + return formDialog(h, { + slotId: "sso-connection", + model: model.connectionDialog, + toParentMessage: (message) => Message.GotConnectionDialogMessage({ message }), + title: isEdit ? "Edit identity provider" : "Connect identity provider", + description: "Members on the chosen domains can sign in through this provider.", + onSubmit: Message.SubmittedConnection(), + submitLabel: isEdit ? "Save" : "Connect", + isPending: model.pending === "createConnection" || model.pending === "updateConnection", + isSubmitDisabled: draft === null || Option.isNone(requestOf(draft)), + // A disabled submit says why, so the admin knows what to fix. + ...footerReason(h, draft === null ? null : draftProblem(draft)), + fields: + draft === null + ? [] + : [ + field(h, { state: Field.stateOf(Field.init(draft.provider), false) }, [ + fieldGroupLabel(h, { attributes: [h.Id("sso-provider-label")] }, "Provider"), + selectControl(h, model, { + key: "provider", + value: draft.provider, + label: PROVIDER_LABELS[draft.provider], + entries: PROVIDER_ENTRIES, + labelledBy: "sso-provider-label", + isDisabled: isEdit, + }), + ]), + draftInput(h, draft, "name", "Name", { placeholder: "Okta" }), + vstack(h, { gap: "2", align: "stretch" }, [ + fieldGroupLabel(h, {}, "Domains"), + verified.length === 0 + ? adminOnlyNote(h, ["Verify a domain before connecting."]) + : multiSegmentedSelect(h, { + options: Arr.map(verified, (domain) => ({ + value: domain, + label: domain, + ariaLabel: domain, + })), + value: draft.domains, + onToggle: (domain) => Message.ToggledDraftDomain({ domain }), + ariaLabel: "Domains", + size: "sm", + className: "flex-wrap", + }), + ]), + ...protocolFields(h, draft), + ], + }) +} + +const tokenDialog = (h: H, model: Model): Html => { + const id = model.tokenDialog.id + const token = model.issuedToken ?? "" + return h.submodel({ + slotId: "sso-token", + model: model.tokenDialog, + view: DialogView.view, + toParentMessage: (message) => Message.GotTokenDialogMessage({ message }), + viewInputs: { + hasTrigger: false, + toView: ({ portal }) => portal ?? h.empty, + toContent: (close) => [ + DialogView.dialogHeader(h, "dialog", [ + DialogView.dialogTitle(h, "dialog", id, "SCIM token"), + DialogView.dialogDescription( + h, + "dialog", + id, + "Paste this token into your identity provider's SCIM settings with the endpoint URL.", + ), + ]), + DialogView.dialogPanel(h, "dialog", id, [ + vstack(h, { gap: "3", align: "stretch" }, [ + copyableField(h, { + id: "sso-scim-token", + label: "Token", + value: token, + copyLabel: "SCIM token", + copy: model.copies["token"] ?? CopyButton.init(), + toCopyMessage: (message) => Message.GotCopyMessage({ key: "token", message }), + }), + alert(h, { variant: "warn", size: "sm", role: "status" }, [ + icon(h, "AlertWarningIcon"), + alertDescription(h, [ + "You will not see this token again. Rotate it to get a new one if you lose it.", + ]), + ]), + ]), + ]), + DialogView.dialogFooter(h, "dialog", [button(h, { attributes: close }, ["Done"])]), + ], + }, + }) +} + +const bypassEntries = ( + model: Model, + document: EnterpriseSsoDocument, +): ReadonlyArray => + Arr.flatMap( + AsyncData.getOrElse(model.members, () => []), + (member): ReadonlyArray => + // Any verified email can qualify, not just the one shown, so the API decides and says why. + Arr.some(document.bypassUsers, (user) => user.userId === member.userId) + ? [] + : [ + { + _tag: "Item", + item: { + value: member.userId, + label: + member.name === member.identifier + ? member.name + : `${member.name} (${member.identifier})`, + }, + }, + ], + ) + +const bypassDialog = (h: H, model: Model, document: EnterpriseSsoDocument | null): Html => { + const entries = document === null ? [] : bypassEntries(model, document) + const picked = Option.getOrNull( + Arr.findFirst(SelectView.optionsOf(entries), (option) => option.value === model.bypassPick), + ) + return formDialog(h, { + slotId: "sso-bypass-add", + model: model.bypassDialog, + toParentMessage: (message) => Message.GotBypassDialogMessage({ message }), + title: "Add break-glass member", + description: + "Pick a member with an email on the SSO domains who can sign in with an email code if the identity provider is down.", + onSubmit: Message.SubmittedBypass(), + submitLabel: "Add member", + isPending: model.pending === "addBypass", + isSubmitDisabled: picked === null, + fields: [ + vstack(h, { gap: "2", align: "stretch" }, [ + fieldGroupLabel(h, { attributes: [h.Id("sso-bypass-label")] }, "Member"), + AsyncData.isFailure(model.members) + ? adminOnlyNote(h, ["Couldn't load members. Close this and try again."]) + : AsyncData.isSuccess(model.members) || AsyncData.isRefreshing(model.members) + ? entries.length === 0 + ? adminOnlyNote(h, ["Every member already has break-glass access."]) + : selectControl(h, model, { + key: "bypass", + value: model.bypassPick ?? "", + label: picked?.label ?? "Pick a member", + entries, + labelledBy: "sso-bypass-label", + }) + : skeleton(h, "h-8 w-full"), + ]), + ], + }) +} + +const dialogs = (h: H, model: Model, document: EnterpriseSsoDocument | null): ReadonlyArray => { + const connection = document?.connection ?? null + return [ + addDomainDialog(h, model), + confirmDialog(h, { + slotId: "sso-domain-remove", + model: model.removeDomainDialog, + toParentMessage: (message) => Message.GotRemoveDomainDialogMessage({ message }), + title: `Remove ${model.removingDomain ?? "domain"}?`, + description: "Members on this domain can no longer sign in through your identity provider.", + confirmLabel: "Remove domain", + isPending: model.pending === "removeDomain", + onConfirm: Message.ClickedConfirmRemoveDomain(), + }), + connectionDialog(h, model, document), + confirmDialog(h, { + slotId: "sso-enforce", + model: model.enforceDialog, + toParentMessage: (message) => Message.GotEnforceDialogMessage({ message }), + title: "Require SSO?", + description: [ + `Everyone with an email on ${Arr.join(connection?.domains ?? [], ", ")} must sign in through ${connection?.name ?? "your identity provider"}. Passwords and other sign-in methods stop working for them.`, + ...(document !== null && document.bypassUsers.length === 0 + ? [ + " Add a break-glass member first, so you keep access if the identity provider is down.", + ] + : []), + ], + confirmLabel: "Require SSO", + tone: "default", + isPending: model.pending === "enforce", + onConfirm: Message.ClickedConfirmEnforce(), + }), + confirmDialog(h, { + slotId: "sso-connection-remove", + model: model.removeConnectionDialog, + toParentMessage: (message) => Message.GotRemoveConnectionDialogMessage({ message }), + title: "Remove identity provider?", + description: + "Members go back to signing in with their own email and password. SCIM provisioning stops too.", + confirmLabel: "Remove", + isPending: model.pending === "deleteConnection", + onConfirm: Message.ClickedConfirmRemoveConnection(), + }), + bypassDialog(h, model, document), + confirmDialog(h, { + slotId: "sso-bypass-remove", + model: model.removeBypassDialog, + toParentMessage: (message) => Message.GotRemoveBypassDialogMessage({ message }), + title: "Remove break-glass access?", + description: + "This member will have to sign in through the identity provider when SSO is required.", + confirmLabel: "Remove", + isPending: model.pending === "removeBypass", + onConfirm: Message.ClickedConfirmRemoveBypass(), + }), + confirmDialog(h, { + slotId: "sso-token-rotate", + model: model.rotateDialog, + toParentMessage: (message) => Message.GotRotateDialogMessage({ message }), + title: "Rotate the SCIM token?", + description: + "The current token keeps working for a short grace period, then stops. Paste the new one into your identity provider before then.", + confirmLabel: "Rotate token", + isPending: model.pending === "rotateToken", + onConfirm: Message.ClickedConfirmRotate(), + }), + tokenDialog(h, model), + confirmDialog(h, { + slotId: "sso-directory-remove", + model: model.removeDirectoryDialog, + toParentMessage: (message) => Message.GotRemoveDirectoryDialogMessage({ message }), + title: "Remove SCIM provisioning?", + description: + "Your identity provider stops adding and removing members. Members it already added keep their access.", + confirmLabel: "Remove", + isPending: model.pending === "deleteDirectory", + onConfirm: Message.ClickedConfirmRemoveDirectory(), + }), + ] +} + +const loaded = ( + h: H, + model: Model, + document: EnterpriseSsoDocument, + isKnownMember: boolean, +): ReadonlyArray => { + const hasState = document.domains.length > 0 || document.connection !== null + if (!document.entitled && !hasState) return [notEntitled(h)] + return [ + ...(document.entitled ? [] : [notEntitled(h)]), + // While the role is unknown the page banner speaks; nothing claims the viewer is not an admin. + ...(model.canManage || !isKnownMember + ? [] + : [adminOnlyNote(h, ["Only admins can change SSO and SCIM settings."])]), + domainsSection(h, model, document), + connectionSection(h, model, document), + bypassSection(h, model, document), + ...(document.connection === null + ? [] + : [ + scimSection(h, model, document), + ...(document.directory === null ? [] : [mappingsSection(h, model, document)]), + ]), + ] +} + +const loadingSkeleton = (h: H): Html => + vstack(h, { gap: "3", align: "stretch" }, [skeleton(h, "h-32 w-full"), skeleton(h, "h-40 w-full")]) + +export const view = Submodel.defineView>( + (model, inputs, h) => + settingsSections(h, [ + ...AsyncData.match(model.document, { + onIdle: () => [loadingSkeleton(h)], + onLoading: () => [loadingSkeleton(h)], + onFailure: (failure) => [ + errorState(h, { + failure, + title: "Couldn't load SSO settings", + variant: "row", + onRetry: Message.ClickedRetry(), + }), + ], + onSuccess: (document) => loaded(h, model, document, inputs.isKnownMember), + onRefreshing: (document) => loaded(h, model, document, inputs.isKnownMember), + onStale: ({ data }) => loaded(h, model, data, inputs.isKnownMember), + }), + ...dialogs(h, model, documentOf(model)), + ]), +) diff --git a/apps/web/src/page/settings/update.ts b/apps/web/src/page/settings/update.ts index 4612751fe5..9f417aef02 100644 --- a/apps/web/src/page/settings/update.ts +++ b/apps/web/src/page/settings/update.ts @@ -25,6 +25,7 @@ import * as Billing from "./billing/update" import * as Members from "./members/update" import * as General from "./general/update" import * as Domains from "./domains/update" +import * as Sso from "./sso/update" import * as DataPlatform from "./data-platform/update" import * as DataSources from "./data-sources/update" import * as AuditLog from "./audit-log/update" @@ -103,6 +104,7 @@ const TAB_TAGS = { general: "General", members: "Members", domains: "Domains", + sso: "Sso", billing: "Billing", } as const satisfies Record const tabTag = (tab: SettingsTab): TabModel["_tag"] => TAB_TAGS[tab] @@ -285,6 +287,15 @@ const initTab = (model: Model, tab: SettingsTab, context: PageContext): Return = ), } } + case "Sso": { + const step = Sso.init(Policy.has(grantsOf(model), "sso:manage")) + return { + model: { ...model, tab: { _tag: "Sso", model: step.model } }, + commands: Command.mapMessages(step.commands ?? [], (message) => + Message.GotSsoMessage({ message }), + ), + } + } case "Billing": { const step = Billing.init( grantsOf(model), @@ -409,6 +420,15 @@ const revisitTab = (model: Model, kept: TabModel, context: PageContext): Return ), } } + case "Sso": { + const step = Sso.revisit(kept.model) + return { + model: { ...model, tab: { _tag: "Sso", model: step.model } }, + commands: Command.mapMessages(step.commands ?? [], (message) => + Message.GotSsoMessage({ message }), + ), + } + } case "Members": { const step = Members.revisit(kept.model) return { @@ -786,6 +806,18 @@ const updateMessage = (model: Model, message: Message, context: PageContext): Re outMessage: step.outMessage, } }, + GotSsoMessage: ({ message: inner }) => { + const tab = tabNamed(model, "Sso") + if (tab === undefined) return { model } + const step = Sso.update(tab.model, inner) + return { + model: putTab(model, { _tag: "Sso", model: step.model }), + commands: Command.mapMessages(step.commands ?? [], (child) => + Message.GotSsoMessage({ message: child }), + ), + outMessage: step.outMessage, + } + }, GotBillingMessage: ({ message: inner }) => { const tab = tabNamed(model, "Billing") if (tab === undefined) return { model } diff --git a/apps/web/src/page/settings/view.ts b/apps/web/src/page/settings/view.ts index 40973002b7..20cf36fdcb 100644 --- a/apps/web/src/page/settings/view.ts +++ b/apps/web/src/page/settings/view.ts @@ -28,6 +28,7 @@ import * as BillingView from "./billing/view" import * as MembersView from "./members/view" import * as GeneralView from "./general/view" import * as DomainsView from "./domains/view" +import * as SsoView from "./sso/view" import * as DataPlatformView from "./data-platform/view" import * as DataSourcesView from "./data-sources/view" import * as AuditLogView from "./audit-log/view" @@ -195,6 +196,16 @@ const tabContent = (h: H, model: Model, inputs: PageViewInputs): ReadonlyArray Message.GotSsoMessage({ message }), + viewInputs: { isKnownMember: isKnownMember(model) }, + }), + ] case "Billing": return [ h.submodel({ @@ -251,6 +262,7 @@ const ROLE_GATED_TABS: ReadonlySet = new Set([ "billing", "keys", "automation", + "sso", ]) /** The session read failed: admin tabs and controls stay hidden, and the page says so where it matters. */ @@ -319,6 +331,8 @@ const tabDescription = (model: Model): string | undefined => { return MembersView.description case "Domains": return DomainsView.description + case "Sso": + return SsoView.description case "AuditLog": return AuditLogView.description case "SetupHealth": diff --git a/apps/web/src/route/search.ts b/apps/web/src/route/search.ts index 19a16c3986..8815034e36 100644 --- a/apps/web/src/route/search.ts +++ b/apps/web/src/route/search.ts @@ -213,6 +213,7 @@ export const settingsTabValues = [ "general", "members", "domains", + "sso", "billing", "audit-log", "keys",