Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

setup-auth: multi-provider authentication and SPA flows support (#173)

Dhiresh Chawlab4c46e900357
diff --git a/evals/power-pages/setup-auth/evals.json b/evals/power-pages/setup-auth/evals.json
index 076193e86..822227857 100644
--- a/evals/power-pages/setup-auth/evals.json
+++ b/evals/power-pages/setup-auth/evals.json
@@ -9,8 +9,10 @@
"expectations": [
"Detects the site as a React framework project",
"Discovers existing web roles including Administrators and Authenticated Users",
+ "Asks which identity provider to use and user selects Microsoft Entra ID",
"Creates a powerPages.d.ts type declarations file for the shell API",
- "Creates an auth service module with login and logout functions using Microsoft Entra ID",
+ "Creates an auth service module with AUTH_PROVIDER configured for entra-id type",
+ "Auth service login function posts to /Account/Login/ExternalLogin with Entra ID provider URL",
"Creates a React-specific hook (e.g., useAuth) for consuming auth state in components",
"Creates mock data or local dev helpers so auth works in local development",
"Creates authorization utility functions for checking user roles",
@@ -80,6 +82,474 @@
"Does not create authorization utilities or role-based components without valid web roles",
"May still offer to set up basic login/logout authentication without role-based access"
]
+ },
+ {
+ "id": 5,
+ "prompt": "Set up authentication for my Power Pages React site using a generic OpenID Connect provider. Our company uses Okta as our identity provider. The authority URL is https://dev-12345.okta.com/oauth2/default.",
+ "expected_output": "Auth setup for a React site using OpenID Connect with Okta. Auth service configured with OIDC provider type, Okta authority URL, and appropriate site settings for the OpenID Connect provider. AuthButton shows 'Sign in with Okta'. OIDC site settings created for authority, client ID, and redirect URI.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks which identity provider to use and user selects OpenID Connect",
+ "Accepts the Okta authority URL from the user",
+ "Creates an auth service with AUTH_PROVIDER configured for oidc type",
+ "Auth service has providerIdentifier set to the Okta-based AuthenticationType",
+ "Auth service login function posts to /Account/Login/ExternalLogin with the OIDC provider identifier",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/Authority with Okta URL",
+ "Asks user for the Client ID from their Okta application registration",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/ClientId with the collected value",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/RedirectUri",
+ "Creates a powerPages.d.ts type declarations file",
+ "Creates AuthButton component with 'Sign in with Okta' display text",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 6,
+ "prompt": "Configure SAML2 authentication for my Power Pages Vue site. We use ADFS as our identity provider. The metadata endpoint is https://adfs.contoso.com/FederationMetadata/2007-06/FederationMetadata.xml.",
+ "expected_output": "Auth setup for a Vue site using SAML2 with ADFS. Auth service configured with SAML2 provider type, ADFS metadata URL, and site settings for MetadataAddress, AuthenticationType, and ServiceProviderRealm. Vue composable and AuthButton created. SAML2-specific site settings created.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a Vue framework project",
+ "Asks which identity provider to use and user selects SAML2",
+ "Accepts the ADFS metadata endpoint URL from the user",
+ "Creates an auth service with AUTH_PROVIDER configured for saml2 type",
+ "Auth service login function posts to /Account/Login/ExternalLogin with the SAML2 provider identifier",
+ "Creates site settings for Authentication/SAML2/{provider}/MetadataAddress with the ADFS URL",
+ "Creates site settings for Authentication/SAML2/{provider}/AuthenticationType",
+ "Creates site settings for Authentication/SAML2/{provider}/ServiceProviderRealm",
+ "Creates a Vue-specific composable (e.g., useAuth) for consuming auth state",
+ "Creates AuthButton component with SAML2-appropriate display text",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 7,
+ "prompt": "I want to set up local username and password authentication for my Power Pages React site. No external identity provider needed, just simple email/password login.",
+ "expected_output": "Auth setup for a React site using local authentication. Auth service configured with local provider type that posts credentials to /SignIn (the server-rendered login form endpoint) — NOT to /Account/Login/Login and NOT to /Account/Login/ExternalLogin. The form sends the password as the `PasswordValue` field (not `Password`). Includes a LocalLoginForm component with username and password fields. Site settings enable local login.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks which identity provider to use and user selects Local Authentication",
+ "Creates an auth service with AUTH_PROVIDER configured for local type",
+ "Auth service login function posts to /SignIn (the server-rendered login form endpoint) — NOT to /Account/Login/Login and NOT to /Account/Login/ExternalLogin",
+ "Auth service login function sends the password as the form field named PasswordValue (NOT Password) — Power Pages' /SignIn endpoint uses PasswordValue; the Password field name is only used by the separate /Account/Login/Register endpoint",
+ "Creates a LocalLoginForm component with username/email and password input fields",
+ "LocalLoginForm handles form submission and error display",
+ "Creates site settings for Authentication/Registration/LocalLoginEnabled set to true",
+ "Creates site settings for Authentication/Registration/LocalLoginByEmail set to true",
+ "Creates a powerPages.d.ts type declarations file",
+ "Creates mock data or local dev helpers so auth works in local development",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 8,
+ "prompt": "Add Google and Facebook social login to my Power Pages Angular site. I want users to be able to sign in with either provider.",
+ "expected_output": "Auth setup for an Angular site with Google and Facebook as individual providers. Auth service supports multiple social providers using AUTH_PROVIDERS array with loginWithProvider(). Site settings created for both Google and Facebook with collected client IDs and secrets via environment variables. Login UI shows both provider buttons.",
+ "files": [],
+ "expectations": [
+ "Detects the site as an Angular framework project",
+ "Recognizes user wants both Google and Facebook providers",
+ "Asks user for the Google Client ID from Google Cloud Console",
+ "Asks user for the Facebook App ID from Facebook Developer Console",
+ "Creates an auth service with AUTH_PROVIDERS array for multi-provider support",
+ "Auth service includes loginWithProvider() function for provider-specific login",
+ "Auth service supports login with provider identifiers for both Google and Facebook",
+ "Creates site settings for Authentication/OpenAuth/Google/ClientId with collected value",
+ "Creates site settings for Authentication/OpenAuth/Facebook/AppId with collected value (not ClientId)",
+ "Creates ClientSecret and AppSecret as environment variables (not in YAML files)",
+ "Warns user not to commit ClientSecret or AppSecret values to source control",
+ "Creates auth UI that presents both Google and Facebook as login buttons",
+ "Creates a powerPages.d.ts type declarations file",
+ "Creates Angular-specific injectable service for auth state",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 9,
+ "prompt": "Set up WS-Federation authentication for my Power Pages Astro site. We use an on-premises ADFS server for federation. The metadata endpoint is https://adfs.contoso.com/federationmetadata/2007-06/federationmetadata.xml.",
+ "expected_output": "Auth setup for an Astro site using WS-Federation with ADFS. Auth service configured with WS-Federation provider type, ADFS metadata URL, and site settings for MetadataAddress, Wtrealm, and AuthenticationType. Astro uses the auth service directly without a framework wrapper. WS-Federation-specific site settings created.",
+ "files": [],
+ "expectations": [
+ "Detects the site as an Astro framework project",
+ "Asks which identity provider to use and user selects WS-Federation",
+ "Accepts the ADFS metadata endpoint URL from the user",
+ "Creates an auth service with AUTH_PROVIDER configured for ws-federation type",
+ "Auth service login function posts to /Account/Login/ExternalLogin with the WS-Federation provider identifier",
+ "Creates site settings for Authentication/WsFederation/{provider}/MetadataAddress with the ADFS URL",
+ "Creates site settings for Authentication/WsFederation/{provider}/AuthenticationType with the provider identifier",
+ "Creates site settings for Authentication/WsFederation/{provider}/Wtrealm with the site URL",
+ "Astro site uses authService.ts directly without a framework-specific wrapper",
+ "Creates a powerPages.d.ts type declarations file",
+ "Creates mock data or local dev helpers so auth works in local development",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 10,
+ "prompt": "Set up Entra External ID authentication for my Power Pages React site. Our External ID tenant is contoso.ciamlogin.com and we want customer self-service sign-up.",
+ "expected_output": "Auth setup for a React site using Entra External ID. Auth service configured with entra-external-id provider type and External ID authority URL using ciamlogin.com. Site settings created for Authority, ClientId, AuthenticationType, and RedirectUri. Uses OpenID Connect site setting path.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks which identity provider to use and user selects Entra External ID",
+ "Creates an auth service with AUTH_PROVIDER configured for entra-external-id type",
+ "Auth service has providerIdentifier set to the External ID authority URL with ciamlogin.com",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/Authority with ciamlogin.com URL",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/ClientId as placeholder",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/AuthenticationType",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/RedirectUri",
+ "Creates a powerPages.d.ts type declarations file",
+ "Creates AuthButton component",
+ "Warns user not to commit ClientSecret to source control",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 11,
+ "prompt": "Set up local login with two-factor authentication for my Power Pages React site. Users should log in with email and password, then verify with a 2FA code.",
+ "expected_output": "Auth setup for a React site with local login only. Skill explains that Power Pages built-in 2FA is not supported in SPA-based code sites because the SendCode/VerifyCode pages are server-rendered and cannot be intercepted from the SPA. Recommends enabling MFA at the identity provider layer instead (or accepting that local-only 2FA is not currently scaffolded). Proceeds with the rest of local auth setup without creating any TwoFactorEnabled / RememberMeEnabled / RememberBrowserEnabled site settings.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Tells the user that Power Pages built-in 2FA is not supported in SPA-based code sites because SendCode/VerifyCode are server-rendered and cannot be intercepted",
+ "Recommends enabling MFA at the identity provider layer (Entra External ID conditional access, B2C user flow MFA, etc.) instead, OR accepting local-only sign-in without 2FA for now",
+ "Does NOT offer 2FA as an option in the Phase 2.1 optional features question",
+ "Does NOT create Authentication/Registration/TwoFactorEnabled site setting",
+ "Does NOT create Authentication/Registration/RememberMeEnabled site setting",
+ "Does NOT create Authentication/Registration/RememberBrowserEnabled site setting",
+ "Creates an auth service with AUTH_PROVIDER configured for local type with loginByEmail set to true",
+ "Auth service login function posts Email field (not Username) when loginByEmail is true",
+ "Creates LocalLoginForm component with email field and password field",
+ "Creates site settings for Authentication/Registration/LocalLoginEnabled set to true",
+ "Creates site settings for Authentication/Registration/LocalLoginByEmail set to true",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 12,
+ "prompt": "Configure invitation-based registration for my Power Pages Vue site with Microsoft Entra ID. Only users with invitation codes should be able to register.",
+ "expected_output": "Auth setup for a Vue site with Entra ID and invitation-based registration. Auth service supports passing invitation codes through the login flow. Site settings configure invitation-only registration by setting Authentication/Registration/InvitationEnabled = true AND Authentication/Registration/OpenRegistrationEnabled = false (this combination is what the server enforces; there is no RequireInvitationCode setting). Explains how invitation codes are threaded through the ExternalLogin flow.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a Vue framework project",
+ "Creates an auth service with AUTH_PROVIDER configured for entra-id type",
+ "Auth service login function accepts and passes through invitationCode parameter",
+ "Creates site settings for Authentication/Registration/InvitationEnabled set to true",
+ "Creates site settings for Authentication/Registration/OpenRegistrationEnabled set to false (this combination — InvitationEnabled=true + OpenRegistrationEnabled=false — is what enforces invitation-only registration on the server)",
+ "Does NOT create Authentication/Registration/RequireInvitationCode — this name is not a real Power Pages server setting; the server never reads it",
+ "Explains the invitation code URL format for sharing with users",
+ "Explains that invitationCode is passed as a query parameter to ExternalLogin",
+ "Creates a Vue-specific composable for consuming auth state",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 13,
+ "prompt": "Set up OpenID Connect authentication for my Power Pages React site with Okta. Authority URL is https://dev-12345.okta.com/oauth2/default. I also need custom claims mapping so that the user's department and job title are synced to the contact record on registration.",
+ "expected_output": "Auth setup for a React site using OIDC with Okta. Asks for ClientId during the flow. When user opts for advanced settings, creates RegistrationClaimsMapping site setting with a comma-separated string of `contactfield=claimtype` pairs (NOT JSON) mapping OIDC claims to Dataverse contact fields. Session timeout and other defaults left as-is.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks which identity provider to use and user selects OpenID Connect",
+ "Accepts the Okta authority URL from the user",
+ "Asks user for the Client ID from their Okta application registration",
+ "Offers advanced settings configuration and user opts in",
+ "Presents the OIDC optional settings table including RegistrationClaimsMapping and LoginClaimsMapping",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/RegistrationClaimsMapping with a comma-separated string of `contactfield=claimtype` pairs (NOT JSON) — the Power Pages server parses CSV, not JSON, for this setting",
+ "Claims mapping value maps department and job title OIDC claims to Dataverse contact fields using the comma-separated CSV format, e.g. `firstname=given_name,lastname=family_name,emailaddress1=email,department=department,jobtitle=job_title`",
+ "Creates all required OIDC site settings (Authority, ClientId, AuthenticationType, RedirectUri)",
+ "Handles ClientSecret via environment variable (not in YAML)",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 14,
+ "prompt": "Set up authentication for my Power Pages React site with both Entra External ID and local email/password login. Our External ID tenant is contoso.ciamlogin.com. Users should be able to choose between signing in with External ID or creating a local account.",
+ "expected_output": "Auth setup for a React site with both Entra External ID (OIDC) and Local Authentication. Auth service uses AUTH_PROVIDERS array with loginWithProvider() supporting both external and local flows. Login page shows External ID button and a local login form. Site settings created for both providers.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Recognizes user wants both Entra External ID and Local Authentication",
+ "Asks for Entra External ID tenant name and Client ID",
+ "Creates auth service with AUTH_PROVIDERS array containing both providers",
+ "Auth service includes loginWithProvider() that handles both external (ExternalLogin) and local (Login) endpoints",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/Authority with ciamlogin.com URL",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/ClientId with collected value",
+ "Creates site settings for Authentication/Registration/LocalLoginEnabled set to true",
+ "Creates site settings for Authentication/Registration/LocalLoginByEmail set to true",
+ "Handles Entra External ID ClientSecret via environment variable",
+ "Creates login UI with both External ID button and local email/password form",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 15,
+ "prompt": "Add Microsoft Account login to my Power Pages Vue site.",
+ "expected_output": "Auth setup for a Vue site with Microsoft Account as a standalone social provider. Auth service configured with social type and urn:microsoft:account provider identifier. Site settings created for ClientId and ClientSecret (via Key Vault).",
+ "files": [],
+ "expectations": [
+ "Detects the site as a Vue framework project",
+ "Asks for the Client ID from Microsoft app registration",
+ "Creates an auth service with AUTH_PROVIDER configured for social type with providerIdentifier urn:microsoft:account",
+ "Creates site settings for Authentication/OpenAuth/MicrosoftAccount/ClientId with collected value",
+ "Handles ClientSecret via Azure Key Vault or environment variable (not in YAML)",
+ "Creates a Vue-specific composable for consuming auth state",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 16,
+ "prompt": "Set up authentication for my Power Pages React site. It's an internal HR dashboard for employees to check leave balances and submit requests.",
+ "expected_output": "Smart inference detects this is an internal/employee portal and recommends Entra ID with invitation-only registration. Explains rationale (internal sites should restrict access to invited employees). If user accepts, proceeds with Entra ID setup and invitation-only settings.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Analyzes the site purpose (HR dashboard, internal, employee-facing)",
+ "Recommends Microsoft Entra ID as the provider (not Entra External ID)",
+ "Recommends invitation-only registration (OpenRegistrationEnabled=false, InvitationEnabled=true)",
+ "Explains the rationale for the recommendation",
+ "Asks user to confirm or override the recommendation",
+ "Does NOT recommend Local Authentication",
+ "Does NOT present Local Authentication in provider choices",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 17,
+ "prompt": "Set up Entra External ID and Google login for my Power Pages Angular site. Our External ID uses a custom domain: login.contoso.com. The tenant ID is 12345678-abcd-efgh-ijkl-123456789012. We also need a registration page for local accounts.",
+ "expected_output": "Auth setup for an Angular site with Entra External ID (custom domain, not ciamlogin.com) and Google. Creates a dedicated /login page with both provider buttons. Asks for Client IDs. Does NOT hardcode ciamlogin.com — uses the custom authority URL provided.",
+ "files": [],
+ "expectations": [
+ "Detects the site as an Angular framework project",
+ "Recognizes both Entra External ID and Google as selected providers",
+ "Accepts the custom domain authority URL (login.contoso.com, not ciamlogin.com)",
+ "Asks for Entra External ID Client ID",
+ "Asks for Google Client ID",
+ "Creates site settings for Authentication/OpenIdConnect/{provider}/Authority with the custom domain URL",
+ "Does NOT hardcode ciamlogin.com in the authority URL",
+ "Creates site settings for Authentication/OpenAuth/Google/ClientId with collected value",
+ "Creates a dedicated /login page with both External ID and Google buttons",
+ "Handles secrets via Azure Key Vault or environment variables",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 18,
+ "prompt": "Set up local login with email/password for my Power Pages React site. Users should be able to register, reset their password, and see proper error messages if login fails.",
+ "expected_output": "Auth setup for a React site with local authentication including registration page at /registration, forgot password page, and inline error display. Auth service uses fetch() for login/register to keep user in SPA. Server errors parsed via parseServerErrors() and displayed inline.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Configures local authentication (user explicitly requested it)",
+ "Creates auth service with login() using fetch() not form.submit()",
+ "Auth service includes register() function that handles Web Forms ViewState pattern",
+ "Auth service includes forgotPassword() function",
+ "Auth service includes parseServerErrors() for parsing server HTML errors",
+ "Creates LocalLoginForm component with email field, password field, remember-me checkbox",
+ "Creates a registration page at /registration route",
+ "Creates a forgot password page or links to /Account/Login/ForgotPassword",
+ "Login form displays server errors inline (not redirect to server page)",
+ "Registration form displays server errors inline",
+ "Creates site settings for LocalLoginEnabled, LocalLoginByEmail, OpenRegistrationEnabled, ResetPasswordEnabled",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 19,
+ "prompt": "Set up Entra External ID authentication for my Power Pages Vue site. Our tenant is contoso.ciamlogin.com. Client ID is a1b2c3d4-e5f6-7890-abcd-ef1234567890. Store the client secret securely using Azure Key Vault.",
+ "expected_output": "Auth setup for a Vue site with Entra External ID. Client secret stored in Azure Key Vault — lists available vaults (or creates one), instructs user to store secret via CLI or portal, creates Dataverse env var with type=secret referencing Key Vault URI, links to site setting via envVarSchema.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a Vue framework project",
+ "Configures Entra External ID with the provided authority and Client ID",
+ "Lists available Azure Key Vaults or offers to create one",
+ "Instructs user to store ClientSecret in Key Vault (never asks for the secret value)",
+ "Creates Dataverse environment variable with --type secret referencing Key Vault secret URI",
+ "Creates site setting for ClientSecret using --envVarSchema (not --value)",
+ "Site setting YAML contains envvar_schema and source: 1",
+ "Secret value never appears in conversation, YAML files, or source control",
+ "Creates a powerPages.d.ts type declarations file",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 20,
+ "prompt": "I already set up Entra External ID for my Power Pages React site but users are seeing an error page after login. The URL shows ?message=access_denied. How do I handle this?",
+ "expected_output": "The skill recognizes this is about auth error handling. The getAuthError() function in authService parses ?message= query params and maps them to user-friendly messages. The access_denied code maps to 'Access was denied by the identity provider.' The login page or AuthButton should call getAuthError() on mount and display the error inline.",
+ "files": [],
+ "expectations": [
+ "Recognizes this is about error handling for an existing auth setup",
+ "Explains that getAuthError() parses ?message= and ?error= query params",
+ "Shows the AUTH_ERROR_MESSAGES map or explains what access_denied maps to",
+ "Explains that the error should be displayed inline in the SPA (not on a server page)",
+ "Shows how to use getAuthError() in a React component (useEffect on mount)",
+ "Mentions getSessionExpiredMessage() for ?sessionExpired=true handling",
+ "Does NOT suggest redirecting to server-rendered error pages"
+ ]
+ },
+ {
+ "id": 21,
+ "prompt": "Set up local authentication for my Power Pages React site in invitation-only mode. Users should only be able to register if they have a valid invitation code emailed by an admin. Direct self-registration should be blocked.",
+ "expected_output": "Local auth setup for a React site with invitation-only registration mode. Creates registration mode site settings (Enabled=true, OpenRegistrationEnabled=false, InvitationEnabled=true), creates the SPA redeem-invitation page, extends the Code-Site-Shell-Header redirect map with /account/login/redeeminvitation, adds redeemInvitation() and fetchInvitationDetails() to auth service, updates loginLocal() to accept invitationCode, updates Login page to read invitationCode from URL and show banner, Registration page pre-fills email via fetchInvitationDetails. Does NOT create the RequireInvitationCode site setting (phantom setting that the server does not read).",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks the registration mode question and user selects Invitation-only",
+ "Creates an auth service with AUTH_PROVIDER configured for local type",
+ "Adds redeemInvitation(invitationCode, redeemByLogin, returnUrl) function to authService",
+ "redeemInvitation uses fetch() with redirect:'manual' to intercept the server 302",
+ "redeemInvitation returns { nextStep: 'register' } when response.type === 'opaqueredirect'",
+ "redeemInvitation returns { nextStep: 'login' } when the response HTML contains login form markers",
+ "redeemInvitation throws parsed errors when the response HTML contains validation summary errors",
+ "Adds fetchInvitationDetails(invitationCode) function to authService that parses email from #EmailTextBox",
+ "Updates loginLocal() to accept an invitationCode 5th parameter and append it as ?InvitationCode= on /SignIn URL",
+ "Creates a /redeem-invitation SPA page that pre-fills code from the URL and shows a 'Sign in with an existing account instead of registering' checkbox",
+ "RedeemInvitation page navigates to /registration?invitationCode= or /login?invitationCode= based on redeemInvitation result",
+ "Creates a /registration SPA page (still created in invitation-only mode — reached via redeem-invitation flow)",
+ "Registration page calls fetchInvitationDetails(invitationCode) on mount when invitationCode is in URL and pre-fills the email input",
+ "Updates Login page to read invitationCode from URL, show an info banner, and pass invitationCode through to loginLocal()",
+ "Extends Code-Site-Shell-Header template redirect map to include '/account/login/redeeminvitation': '/redeem-invitation'",
+ "Creates site setting Authentication/Registration/Enabled = true",
+ "Creates site setting Authentication/Registration/OpenRegistrationEnabled = false",
+ "Creates site setting Authentication/Registration/InvitationEnabled = true",
+ "Does NOT create the Authentication/Registration/RequireInvitationCode site setting (phantom — server never reads it)",
+ "Creates site settings for LocalLoginEnabled, LocalLoginByEmail, ResetPasswordEnabled",
+ "Creates CAPTCHA-disabled site settings (CaptchaEnabled=false, IsCaptchaEnabledForRegistration=false)",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Post-deploy notes show the correct invitation link format: {site-url}/Account/Login/RedeemInvitation?invitation={code}",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 22,
+ "prompt": "Set up local authentication for my Power Pages React site with both open registration AND invitation-based registration enabled. Users should be able to self-register OR redeem an invitation link.",
+ "expected_output": "Local auth setup for a React site with both open and invitation modes enabled. Creates registration mode site settings (Enabled=true, OpenRegistrationEnabled=true, InvitationEnabled=true). Creates both the /registration and /redeem-invitation SPA pages. Registration page accepts direct navigation AND invitation links (pre-fills email when invitationCode is present).",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks the registration mode question and user selects Both",
+ "Creates site setting Authentication/Registration/Enabled = true",
+ "Creates site setting Authentication/Registration/OpenRegistrationEnabled = true",
+ "Creates site setting Authentication/Registration/InvitationEnabled = true",
+ "Does NOT create the RequireInvitationCode site setting",
+ "Creates a /registration SPA page accessible both directly and via invitation flow",
+ "Registration page pre-fills email via fetchInvitationDetails() when invitationCode is in URL, blank otherwise",
+ "Creates a /redeem-invitation SPA page",
+ "Extends Code-Site-Shell-Header redirect map with /account/login/redeeminvitation -> /redeem-invitation",
+ "Adds redeemInvitation() and fetchInvitationDetails() to auth service",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 23,
+ "prompt": "Set up local authentication for my Power Pages React site but DISABLE new user registration entirely. Only existing users should be able to log in — no one should be able to create new accounts via the site.",
+ "expected_output": "Local auth setup for a React site with registration disabled mode. Creates the Authentication/Registration/Enabled = false site setting. Does NOT create /registration page, /redeem-invitation page, or invitation/open-registration settings. Login, forgot password, reset password pages still created for existing users.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks the registration mode question and user selects Registration disabled",
+ "Creates site setting Authentication/Registration/Enabled = false",
+ "Does NOT create site settings for OpenRegistrationEnabled or InvitationEnabled (they are moot when Enabled=false)",
+ "Does NOT create the RequireInvitationCode site setting",
+ "Does NOT create a /registration SPA page",
+ "Does NOT create a /redeem-invitation SPA page",
+ "Does NOT include /account/login/redeeminvitation in the Code-Site-Shell-Header redirects",
+ "Still creates the /login page for existing users",
+ "Still creates /forgot-password and /reset-password pages (existing users may still need password resets)",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 24,
+ "prompt": "Set up authentication for my Power Pages React site with Entra External ID, and add a profile page so signed-in users can edit their basic contact info (name, phone, address).",
+ "expected_output": "Full auth setup for a React site with Entra External ID PLUS a simple /user-profile SPA page. Skill scaffolds UserProfile.tsx (with a read-only Account Details section showing just full name + email, plus an edit form limited to firstname, lastname, mobilephone, and 5 address fields), extends authService.ts with getMyProfile and updateMyProfile, evolves AuthButton to a dropdown with My Profile + Sign Out items, adds /user-profile route, writes Webapi/contact/enabled and Webapi/contact/fields site settings (9 entries, emailaddress1 and middlename excluded), and creates a Self-scope (756150004) table permission on contact for the Authenticated Users role.",
+ "files": [],
+ "expectations": [
+ "Asks the registration mode question and user selects an option that creates contacts (Open registration / Both / Invitation-only)",
+ "Asks the new profile-page question in Phase 2.1 and user selects Yes",
+ "Captures INCLUDE_PROFILE_PAGE = true",
+ "Phase 5.1.9 creates src/pages/UserProfile.tsx at exactly that path and filename (NOT Profile.tsx, NOT /profile route)",
+ "Route is /user-profile (NOT /profile — /profile is reserved by the server)",
+ "Service functions are named getMyProfile and updateMyProfile (NOT patchOwnContact, fetchProfile, saveProfile, etc.)",
+ "UserProfile page sets document.title in a useEffect using the same `<Page> — <Site Name>` convention as other auth pages (e.g., 'My Profile — Contoso Portal'), with the actual site name substituted in",
+ "UserProfile page reads user.contactId from useAuth() and calls getMyProfile(contactId) on mount",
+ "UserProfile page has a read-only Account Details section at the top showing ONLY the user's full name (firstname + lastname combined) and email (sourced from useAuth().user.email — no Web API roundtrip needed)",
+ "Account Details section does NOT display contactId, web roles, claims, or any other metadata — only full name + email",
+ "UserProfile page renders editable form fields limited to exactly 8 fields: firstname, lastname, mobilephone, address1_line1, address1_city, address1_stateorprovince, address1_postalcode, address1_country",
+ "UserProfile page does NOT include an editable email field (emailaddress1 is read-only in Account Details, never in the form)",
+ "UserProfile page does NOT include a middlename field",
+ "UserProfile page does NOT include a Change Password / Reset Password link or any password-related UI",
+ "UserProfile page does NOT include a Sign Out button (sign-out stays in the header AuthButton dropdown)",
+ "UserProfile page uses validate-on-blur pattern matching Login.tsx / Registration.tsx (with phone format check)",
+ "UserProfile page handles user.contactId being empty by showing a friendly error pointing to RegistrationClaimsMapping",
+ "Extends src/services/authService.ts with ProfileContact interface (8 editable fields + contactid — NO emailaddress1, NO middlename), ProfileUpdate type, getMyProfile function, and updateMyProfile function",
+ "updateMyProfile PATCHes /_api/contacts({contactId}) with __RequestVerificationToken header and If-Match: * header",
+ "updateMyProfile omits undefined fields from the body so partial updates don't clear other columns",
+ "Updates src/components/AuthButton.tsx to a dropdown shape with state-based open/close, outside-click handler, Escape key handler, and ARIA attributes",
+ "Dropdown shows 'My Profile' link to /user-profile and 'Sign Out' button when INCLUDE_PROFILE_PAGE is true",
+ "Adds <Route path='/user-profile' element={<UserProfile />} /> to src/App.tsx",
+ "Adds '/signin': '/login' to the Code-Site-Shell-Header template's redirect map so that when the server bounces unauthenticated users from server-protected paths (e.g., /profile) to /SignIn?ReturnUrl=..., they land on the SPA /login page instead of the legacy server sign-in UI",
+ "Extends src/services/authService.ts with an applyContactUpdateLocally(payload) helper that mirrors saved firstname/lastname back into window.Microsoft.Dynamic365.Portal.User (mutating firstName/lastName camelCase properties on the snapshot) so the header reflects the new values without a page reload",
+ "Updates src/hooks/useAuth.ts (or framework equivalent) so refresh()/loadUser() spreads the user object into a fresh reference — e.g., setUser(current ? { ...current } : undefined) — so React detects the state change after Portal.User is mutated in place",
+ "After successful save, UserProfile calls applyContactUpdateLocally(payload) BEFORE refresh() so the header avatar/display name in AuthButton repaint immediately without a full page reload",
+ "After successful save, UserProfile calls refresh() from useAuth() and shows inline 'Profile updated.' message — does not redirect or reload the page",
+ "Phase 8.1 writes Webapi/contact/enabled = true site setting",
+ "Phase 8.1 writes Webapi/contact/fields site setting with exactly 9 lowercase logical names (contactid,firstname,lastname,mobilephone,address1_line1,address1_city,address1_stateorprovince,address1_postalcode,address1_country) — emailaddress1 and middlename are NOT in this list",
+ "Phase 8.1.x discovers the Authenticated Users web role UUID from .powerpages-site/web-roles/",
+ "Phase 8.1.x creates table permission YAML at .powerpages-site/table-permissions/My-Profile-Edit-Own-Contact.tablepermission.yml",
+ "Table permission YAML has scope: 756150004 (Self), read: true, write: true, create: false, delete: false",
+ "Table permission YAML associates the Authenticated Users role UUID via adx_entitypermission_webrole array",
+ "Does NOT use Contact scope (756150001) for the contact entity (script validates and rejects this)",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Generates an HTML setup report at <PROJECT_ROOT>/docs/auth-setup-report.html via render-auth-report.js, opens it in the browser, and tells the user the file path",
+ "Prompts the user to deploy the updated site"
+ ]
+ },
+ {
+ "id": 25,
+ "prompt": "Set up authentication for my Power Pages React site with local login and Terms and Conditions enabled.",
+ "expected_output": "Auth setup for a React site with local login + Terms and Conditions. Before asking the user about the Privacy Extensions solution prerequisite, the skill automatically runs check-solution-installed.js against the current Dataverse environment to detect whether msdynce_PortalPrivacyExtensions is installed. Based on the JSON result, the skill either confirms the prerequisite (and skips the question), or tells the user clearly that Terms & Conditions will NOT be enforced server-side and asks whether to continue scaffolding anyway or skip Terms entirely. If the auto-detection fails (no PAC env, expired token, missing permissions), the skill falls back to the manual three-option confirmation question.",
+ "files": [],
+ "expectations": [
+ "Detects the site as a React framework project",
+ "Asks the optional features question in Phase 2.1 and the user selects Terms and Conditions",
+ "Runs `node \"${CLAUDE_PLUGIN_ROOT}/scripts/check-solution-installed.js\" --solutionName \"msdynce_PortalPrivacyExtensions\"` BEFORE asking the GDPR prerequisite question",
+ "Parses the script's stdout JSON result and branches based on the `installed` boolean",
+ "When the script returns installed: true, skips the manual prerequisite confirmation entirely and tells the user the solution is detected (including the version from the JSON) before proceeding to collect Terms content",
+ "When the script returns installed: false, tells the user clearly that Terms and Conditions will NOT be enforced by the server until msdynce_PortalPrivacyExtensions is installed (Authentication/Registration/TermsAgreementEnabled is silently ignored without it), then asks via AskUserQuestion whether to continue scaffolding anyway or skip Terms entirely (two options, not three)",
+ "When the script exits non-zero (infrastructure failure: no env URL, expired Azure CLI token, missing Read permission on the solutions table, network error), tells the user we couldn't auto-detect the solution and falls back to the manual three-option question (Yes / Continue anyway / Cancel)",
+ "Sets the ProfileRedirectEnabled site setting to false",
+ "Generates an HTML setup report at <PROJECT_ROOT>/docs/auth-setup-report.html via render-auth-report.js; OPTIONAL_FEATURES_DATA.termsEnforced reflects the detected solution state (true if installed, false otherwise)",
+ "Prompts the user to deploy the updated site"
+ ]
}
]
}
diff --git a/evals/power-pages/test-site/evals.json b/evals/power-pages/test-site/evals.json
index 4a3968669..1eda08352 100644
--- a/evals/power-pages/test-site/evals.json
+++ b/evals/power-pages/test-site/evals.json
@@ -82,6 +82,68 @@
"Closes the browser session after all testing is complete",
"Provides prioritized next steps focusing on resolving the API failures"
]
+ },
+ {
+ "id": 5,
+ "prompt": "Test my Power Pages site at https://intranet.powerappsportals.com. It uses SAML2 authentication with our corporate ADFS server, so you'll need to let me log in first.",
+ "expected_output": "The agent uses the provided URL, launches a Playwright browser, resizes the viewport, and navigates to the homepage. It detects a redirect to the ADFS login page (a SAML2 identity provider on a different domain). It informs the user that the site redirected to a SAML2/ADFS login page and asks the user to complete authentication in the browser window. After the user logs in through the ADFS portal and is redirected back to the Power Pages site, the agent verifies the homepage loaded with authenticated content. It then crawls up to 25 pages, captures API requests, and generates a test report.",
+ "files": [],
+ "expectations": [
+ "Uses the user-provided URL https://intranet.powerappsportals.com directly",
+ "Resizes the browser viewport to an appropriate dimension",
+ "Navigates to the homepage and detects a redirect to a SAML2/ADFS identity provider login page",
+ "Recognizes the ADFS login page as a private site gate authentication redirect",
+ "Informs the user that the site requires SAML2/ADFS authentication and asks them to log in",
+ "Waits for the user to complete the ADFS login process before continuing",
+ "After authentication, verifies the homepage loads correctly with authenticated content",
+ "Captures browser console errors and network requests throughout testing",
+ "Crawls discoverable links up to a maximum of 25 pages in the authenticated context",
+ "Identifies /_api/ requests and analyzes their HTTP status codes",
+ "Generates a test report with per-page and per-API pass/fail results",
+ "Closes the browser session after testing is complete",
+ "Provides next steps or recommendations based on the test outcomes"
+ ]
+ },
+ {
+ "id": 6,
+ "prompt": "Test https://self-service.powerappsportals.com. This site uses local authentication with username/password login. I'll create a test account and log in.",
+ "expected_output": "The agent uses the provided URL, launches a Playwright browser, resizes the viewport, and navigates to the homepage. The homepage loads successfully as a public site. The agent detects site-level authentication indicators (a Sign in or Log in link in the navigation) and recognizes the site supports local authentication (login form with username/password fields rather than external provider redirect). It asks the user to log in through the browser's login form. After the user authenticates with their local credentials, the agent proceeds to crawl pages and test APIs, generating a comprehensive report.",
+ "files": [],
+ "expectations": [
+ "Uses the user-provided URL https://self-service.powerappsportals.com directly",
+ "Resizes the browser viewport before navigating to the site",
+ "Navigates to the homepage and verifies it loads without critical errors",
+ "Detects site-level authentication indicators such as Sign in or Log in links",
+ "Recognizes local authentication when the login page shows username/email and password fields instead of redirecting to an external identity provider",
+ "Asks the user to complete the local login through the browser window",
+ "After authentication, verifies the user is now logged in",
+ "Crawls discoverable links up to a maximum of 25 pages",
+ "Captures and analyzes /_api/ network requests",
+ "Generates a test report with per-page and per-API pass/fail results",
+ "Closes the browser session after testing is complete",
+ "Provides recommendations based on test findings"
+ ]
+ },
+ {
+ "id": 7,
+ "prompt": "Run tests on https://partner-hub.powerappsportals.com. The site uses OpenID Connect with Okta for authentication. Some pages are public and some require login.",
+ "expected_output": "The agent uses the provided URL, launches a Playwright browser, and navigates to the homepage. The homepage loads as a public site with a Sign in option visible. The agent detects site-level authentication and asks whether the user wants to log in or skip authenticated pages. If the user logs in through the Okta OIDC flow (redirect to Okta login page, then back to the site), the agent tests both public and authenticated pages. The report distinguishes between public and authenticated page results and notes any APIs returning 401/403 for unauthenticated vs authenticated contexts.",
+ "files": [],
+ "expectations": [
+ "Uses the user-provided URL https://partner-hub.powerappsportals.com directly",
+ "Resizes the browser viewport to an appropriate dimension",
+ "Navigates to the homepage and verifies it loads correctly as a public page",
+ "Detects site-level authentication indicators (Sign in link)",
+ "Asks user whether to log in or skip authenticated pages",
+ "If user logs in, recognizes the redirect to Okta as an OpenID Connect authentication flow",
+ "Waits for the user to complete the Okta login process",
+ "After authentication, verifies the user is logged in on the site",
+ "Crawls discoverable links up to a maximum of 25 pages",
+ "Captures and analyzes /_api/ network requests with status codes",
+ "Generates a test report distinguishing public and authenticated page results",
+ "Closes the browser session after testing is complete",
+ "Provides recommendations based on test findings"
+ ]
}
]
}
diff --git a/plugins/power-pages/scripts/check-solution-installed.js b/plugins/power-pages/scripts/check-solution-installed.js
new file mode 100644
index 000000000..dea857527
--- /dev/null
+++ b/plugins/power-pages/scripts/check-solution-installed.js
@@ -0,0 +1,77 @@
+#!/usr/bin/env node
+
+// Checks whether a Dataverse solution is installed in the current PAC environment.
+// Usage:
+// node check-solution-installed.js --solutionName <uniqueName> [--envUrl <url>]
+//
+// If --envUrl is omitted, the environment URL is read from `pac env who`.
+//
+// Outputs JSON to stdout on success:
+// { "installed": true, "solutionName": "...", "version": "1.0.0.5" }
+// { "installed": false, "solutionName": "..." }
+//
+// On infrastructure failure (no PAC env, no Azure CLI token, network error, 4xx/5xx),
+// writes a human-readable message to stderr and exits 1 — the caller (skill) should
+// treat this as "unknown" and fall back to asking the user manually.
+//
+// The query itself lives in lib/check-solution-installed.js so it can be unit-
+// tested without spawning a subprocess or making real network calls.
+
+const { getAuthToken, getEnvironmentUrl } = require('./lib/validation-helpers');
+const { checkSolutionInstalled, sanitizeEnvUrl } = require('./lib/check-solution-installed');
+
+function parseArgs(argv) {
+ const args = {};
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--solutionName') args.solutionName = argv[++i];
+ else if (a === '--envUrl') args.envUrl = argv[++i];
+ }
+ return args;
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ if (!args.solutionName) {
+ process.stderr.write('Usage: node check-solution-installed.js --solutionName <uniqueName> [--envUrl <url>]\n');
+ process.exit(1);
+ }
+
+ const rawEnvUrl = args.envUrl || getEnvironmentUrl();
+ if (!rawEnvUrl) {
+ process.stderr.write('No environment URL provided and `pac env who` did not return one. Run `pac auth create` and `pac env select` first.\n');
+ process.exit(1);
+ }
+
+ // Sanitize before passing anywhere that interpolates the URL into a shell
+ // command (getAuthToken builds `az account get-access-token --resource
+ // "${envUrl}"`). sanitizeEnvUrl strips everything except scheme+host+port,
+ // so a `--envUrl 'x"; rm -rf ~; echo "'` can't escape the quotes.
+ let envUrl;
+ try {
+ envUrl = sanitizeEnvUrl(rawEnvUrl);
+ } catch (err) {
+ process.stderr.write(`${err.message}\n`);
+ process.exit(1);
+ }
+
+ const token = getAuthToken(envUrl);
+ if (!token) {
+ process.stderr.write('Failed to get Azure CLI token. Run `az login` first.\n');
+ process.exit(1);
+ }
+
+ try {
+ const result = await checkSolutionInstalled({
+ envUrl,
+ token,
+ solutionName: args.solutionName,
+ });
+ console.log(JSON.stringify(result));
+ } catch (err) {
+ process.stderr.write(`${err.message}\n`);
+ process.exit(1);
+ }
+}
+
+main();
diff --git a/plugins/power-pages/scripts/create-site-setting.js b/plugins/power-pages/scripts/create-site-setting.js
index 3a130d11d..8e26089bb 100644
--- a/plugins/power-pages/scripts/create-site-setting.js
+++ b/plugins/power-pages/scripts/create-site-setting.js
@@ -85,9 +85,47 @@ try {
// --- Helpers ---
+function needsQuoting(value) {
+ if (typeof value !== 'string') return false;
+
+ // Empty string and the bareword-reserved values that YAML 1.2 reads as
+ // booleans / null instead of as strings.
+ if (value === '' || value === 'true' || value === 'false' || value === 'null') return true;
+
+ // Leading/trailing whitespace (a leading tab would also be caught by the
+ // leading-char check below — keeping this for clarity).
+ if (value !== value.trim()) return true;
+
+ // YAML-special characters anywhere in the value. Without quoting, these can
+ // start comments (#), terminate scalars (:), open flow collections ([ { , ]),
+ // start anchors/aliases/tags/directives (& * ! %), or be reserved/unsupported
+ // (` @ < > = ?). Pipe and gt are block-scalar indicators.
+ if (/[:#{}[\],&*?|<>=!%@`]/.test(value)) return true;
+
+ // Leading characters that change parser semantics even when no other special
+ // character appears in the value. These cases were missed by the
+ // character-class check above:
+ // "-foo" → ambiguous: parsers may interpret a leading "-" as a block
+ // sequence indicator or a numeric sign, depending on context.
+ // "'foo" → leading single quote opens a quoted scalar that never closes.
+ // '"foo' → leading double quote opens a quoted scalar that never closes.
+ // "\tfoo" → leading tab is not allowed by YAML 1.2 in plain scalars.
+ // Quoting the entire value sidesteps every one of these.
+ const first = value.charAt(0);
+ if (first === '-' || first === "'" || first === '"' || first === '\t') return true;
+
+ return false;
+}
+
+function yamlValue(value) {
+ if (typeof value === 'boolean' || typeof value === 'number') return String(value);
+ if (needsQuoting(value)) return `"${String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
+ return String(value);
+}
+
function writeYaml(fields) {
const keys = Object.keys(fields).sort();
- return keys.map(k => `${k}: ${fields[k]}`).join('\n') + '\n';
+ return keys.map(k => `${k}: ${yamlValue(fields[k])}`).join('\n') + '\n';
}
// --- Create site setting ---
diff --git a/plugins/power-pages/scripts/lib/check-solution-installed.js b/plugins/power-pages/scripts/lib/check-solution-installed.js
new file mode 100644
index 000000000..ec83d2b21
--- /dev/null
+++ b/plugins/power-pages/scripts/lib/check-solution-installed.js
@@ -0,0 +1,131 @@
+'use strict';
+
+// Core logic for the `check-solution-installed` CLI, exposed as a function so
+// the unit tests can mock `helpers.makeRequest` without spawning a subprocess
+// or hitting the network.
+//
+// The CLI wrapper at scripts/check-solution-installed.js just resolves env
+// URL + auth token and calls checkSolutionInstalled below.
+
+const helpers = require('./validation-helpers');
+
+const UNIQUE_NAME_RE = /^[A-Za-z0-9_]+$/;
+
+/**
+ * Validates and normalizes a Dataverse environment URL before it is passed
+ * to anything that interpolates it into a shell command (notably
+ * helpers.getAuthToken, which calls `az account get-access-token --resource
+ * "${url}"` via execSync). Returns the URL's `origin` only (scheme + host +
+ * optional port) so path, query, fragment, and userinfo are all stripped.
+ *
+ * Throws on:
+ * - non-string / empty input
+ * - input that `new URL()` can't parse
+ * - non-https protocol (Dataverse refuses http and we don't want file: etc.)
+ * - URLs with embedded userinfo (https://user:pass@host) — credentials in
+ * URLs are a smell and can confuse downstream tooling
+ *
+ * The normalized origin is safe to interpolate into a shell command because
+ * URL.origin only contains scheme, host, and port — characters that the
+ * URL spec disallows from carrying shell metacharacters.
+ *
+ * @param {unknown} envUrl
+ * @returns {string} sanitized origin, e.g. "https://contoso.crm.dynamics.com"
+ * @throws Error with a human-readable message on rejection
+ */
+function sanitizeEnvUrl(envUrl) {
+ if (typeof envUrl !== 'string' || envUrl.trim() === '') {
+ throw new Error('envUrl must be a non-empty string.');
+ }
+
+ let parsed;
+ try {
+ parsed = new URL(envUrl);
+ } catch {
+ throw new Error(`envUrl is not a valid URL: "${envUrl}".`);
+ }
+
+ if (parsed.protocol !== 'https:') {
+ throw new Error(`envUrl must use https (got "${parsed.protocol}").`);
+ }
+
+ if (parsed.username || parsed.password) {
+ throw new Error('envUrl must not contain userinfo (username/password). Authentication uses the Azure CLI token, not credentials in the URL.');
+ }
+
+ // url.origin is the scheme + host + port — no path, no query, no fragment.
+ // For "https://contoso.crm.dynamics.com:443/api/data/v9.2/?x=1#anchor"
+ // it returns "https://contoso.crm.dynamics.com:443".
+ return parsed.origin;
+}
+
+/**
+ * @typedef {Object} CheckResult
+ * @property {boolean} installed
+ * @property {string} solutionName
+ * @property {string|null} [version]
+ */
+
+/**
+ * Queries the Dataverse `solutions` table for a row matching the given
+ * uniquename. The presence of a row means the solution is installed.
+ *
+ * @param {Object} options
+ * @param {string} options.envUrl — Dataverse environment URL (no trailing slash)
+ * @param {string} options.token — Azure CLI bearer token
+ * @param {string} options.solutionName — solution unique name (alphanumeric + underscore)
+ * @returns {Promise<CheckResult>}
+ * @throws Error with a human-readable message on infrastructure failure
+ * (network error, 401/403, non-200, malformed JSON, etc.)
+ */
+async function checkSolutionInstalled({ envUrl, token, solutionName } = {}) {
+ if (!envUrl) throw new Error('envUrl is required');
+ if (!token) throw new Error('token is required');
+ if (!solutionName) throw new Error('solutionName is required');
+ if (!UNIQUE_NAME_RE.test(solutionName)) {
+ throw new Error(`Invalid solution unique name: "${solutionName}". Expected alphanumeric + underscore.`);
+ }
+
+ const filter = `uniquename eq '${solutionName}'`;
+ const url = `${envUrl}/api/data/v9.2/solutions?$filter=${encodeURIComponent(filter)}&$select=uniquename,version&$top=1`;
+
+ const res = await helpers.makeRequest({
+ url,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ 'OData-MaxVersion': '4.0',
+ 'OData-Version': '4.0',
+ },
+ });
+
+ if (res.error) {
+ throw new Error(`Solution query failed: ${res.error}`);
+ }
+
+ if (res.statusCode === 401 || res.statusCode === 403) {
+ throw new Error(
+ `Authentication / authorization failed (${res.statusCode}) querying solutions table. ` +
+ 'Either the token is expired (run `az login`) or the signed-in user lacks Read permission on the solutions table.'
+ );
+ }
+
+ if (res.statusCode !== 200) {
+ throw new Error(`Unexpected response (${res.statusCode}): ${res.body}`);
+ }
+
+ let data;
+ try {
+ data = JSON.parse(res.body);
+ } catch {
+ throw new Error(`Failed to parse Dataverse response as JSON: ${res.body}`);
+ }
+
+ const row = Array.isArray(data.value) && data.value.length > 0 ? data.value[0] : null;
+ if (row) {
+ return { installed: true, solutionName, version: row.version || null };
+ }
+ return { installed: false, solutionName };
+}
+
+module.exports = { checkSolutionInstalled, sanitizeEnvUrl, UNIQUE_NAME_RE };
diff --git a/plugins/power-pages/scripts/lib/powerpages-config.js b/plugins/power-pages/scripts/lib/powerpages-config.js
index 519b802b1..169feff0b 100644
--- a/plugins/power-pages/scripts/lib/powerpages-config.js
+++ b/plugins/power-pages/scripts/lib/powerpages-config.js
@@ -7,6 +7,25 @@ const WEB_ROLE_FILE_SUFFIX = '.webrole.yml';
function parseYamlScalar(value) {
const trimmed = value.trim();
+
+ // Unwrap quoted scalars BEFORE the bareword tests so that a value written
+ // as `"true"` (the literal 4-character string) is read back as a string,
+ // not coerced to the boolean true. Same for `"null"` / `"123"` etc. This
+ // is symmetric with the quoting strategy in create-site-setting.js, which
+ // wraps any value that would otherwise change meaning when read as YAML.
+
+ // Double-quoted: "...". YAML 1.2 supports many escape sequences; our writer
+ // only emits \\ and \", so we only unescape those.
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
+ return trimmed.slice(1, -1).replace(/\\([\\"])/g, '$1');
+ }
+
+ // Single-quoted: '...'. YAML 1.2 single-quoted strings escape '' for a
+ // literal single quote and otherwise pass through verbatim.
+ if (trimmed.length >= 2 && trimmed.startsWith("'") && trimmed.endsWith("'")) {
+ return trimmed.slice(1, -1).replace(/''/g, "'");
+ }
+
if (trimmed === 'true') {
return true;
}
diff --git a/plugins/power-pages/scripts/render-auth-report.js b/plugins/power-pages/scripts/render-auth-report.js
new file mode 100644
index 000000000..b3ce714d1
--- /dev/null
+++ b/plugins/power-pages/scripts/render-auth-report.js
@@ -0,0 +1,44 @@
+#!/usr/bin/env node
+/**
+ * render-auth-report.js — Renders the setup-auth post-execution report HTML
+ * from a JSON data file.
+ *
+ * Usage:
+ * node render-auth-report.js --output <path> --data <json-file>
+ *
+ * Required keys in the JSON data file:
+ * META_DATA — { siteName, reportDate, framework, nextStepsHtml }
+ * PROVIDERS_DATA — array of provider objects (may be empty)
+ * LOCAL_AUTH_DATA — object or null
+ * OPTIONAL_FEATURES_DATA — object (may be empty)
+ * SITE_SETTINGS_DATA — array of { name, value } (may be empty)
+ * TABLE_PERMISSIONS_DATA — array of permission objects (may be empty)
+ * FILES_DATA — array of { path, action, notes } (may be empty)
+ */
+
+const path = require('path');
+const { renderTemplate, parseArgs } = require('./lib/render-template');
+
+const args = parseArgs(process.argv);
+
+if (!args.output || !args.data) {
+ console.error(
+ 'Usage: node render-auth-report.js --output <path> --data <json-file>'
+ );
+ process.exit(1);
+}
+
+renderTemplate({
+ templatePath: path.join(__dirname, '..', 'skills', 'setup-auth', 'assets', 'auth-report.html'),
+ outputPath: path.resolve(args.output),
+ dataPath: path.resolve(args.data),
+ requiredKeys: [
+ 'META_DATA',
+ 'PROVIDERS_DATA',
+ 'LOCAL_AUTH_DATA',
+ 'OPTIONAL_FEATURES_DATA',
+ 'SITE_SETTINGS_DATA',
+ 'TABLE_PERMISSIONS_DATA',
+ 'FILES_DATA',
+ ],
+});
diff --git a/plugins/power-pages/scripts/tests/check-solution-installed.test.js b/plugins/power-pages/scripts/tests/check-solution-installed.test.js
new file mode 100644
index 000000000..c466308d2
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/check-solution-installed.test.js
@@ -0,0 +1,233 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+
+const helpers = require('../lib/validation-helpers');
+const { checkSolutionInstalled, sanitizeEnvUrl } = require('../lib/check-solution-installed');
+
+const ENV_URL = 'https://contoso.crm.dynamics.com';
+const TOKEN = 'fake-token';
+const SOLUTION = 'msdynce_PortalPrivacyExtensions';
+
+function withMockedRequests(t, handler) {
+ const orig = helpers.makeRequest;
+ const calls = [];
+ helpers.makeRequest = async (opts) => {
+ calls.push(opts);
+ return handler(opts, calls.length);
+ };
+ t.after(() => { helpers.makeRequest = orig; });
+ return calls;
+}
+
+test('rejects missing envUrl, token, solutionName', async () => {
+ await assert.rejects(
+ () => checkSolutionInstalled({ token: TOKEN, solutionName: SOLUTION }),
+ /envUrl is required/
+ );
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, solutionName: SOLUTION }),
+ /token is required/
+ );
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN }),
+ /solutionName is required/
+ );
+});
+
+test('rejects solution unique names with disallowed characters', async () => {
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: 'has space' }),
+ /Invalid solution unique name/
+ );
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: "'; DROP TABLE solutions; --" }),
+ /Invalid solution unique name/
+ );
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: 'name/with/slashes' }),
+ /Invalid solution unique name/
+ );
+});
+
+test('returns installed:true with version when the solution row exists', async (t) => {
+ const calls = withMockedRequests(t, () => ({
+ statusCode: 200,
+ body: JSON.stringify({
+ value: [
+ { uniquename: SOLUTION, version: '1.0.0.5' },
+ ],
+ }),
+ }));
+
+ const result = await checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION });
+
+ assert.deepEqual(result, { installed: true, solutionName: SOLUTION, version: '1.0.0.5' });
+ assert.equal(calls.length, 1);
+ // OData query is well-formed: targets /api/data/v9.2/solutions and filters by uniquename
+ assert.match(calls[0].url, /\/api\/data\/v9\.2\/solutions/);
+ assert.match(calls[0].url, /uniquename%20eq%20'msdynce_PortalPrivacyExtensions'/);
+ assert.match(calls[0].url, /\$top=1/);
+ assert.match(calls[0].url, /\$select=uniquename,version/);
+ // Auth header is the bearer token
+ assert.equal(calls[0].headers.Authorization, `Bearer ${TOKEN}`);
+});
+
+test('returns installed:false when the solutions table has no matching row', async (t) => {
+ withMockedRequests(t, () => ({
+ statusCode: 200,
+ body: JSON.stringify({ value: [] }),
+ }));
+
+ const result = await checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION });
+ assert.deepEqual(result, { installed: false, solutionName: SOLUTION });
+});
+
+test('version field is null when the response row omits it', async (t) => {
+ withMockedRequests(t, () => ({
+ statusCode: 200,
+ body: JSON.stringify({ value: [{ uniquename: SOLUTION }] }),
+ }));
+
+ const result = await checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION });
+ assert.equal(result.installed, true);
+ assert.equal(result.version, null);
+});
+
+test('throws with a helpful message on network error', async (t) => {
+ withMockedRequests(t, () => ({ error: 'ECONNREFUSED' }));
+
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION }),
+ /Solution query failed: ECONNREFUSED/
+ );
+});
+
+test('throws with auth-specific message on 401', async (t) => {
+ withMockedRequests(t, () => ({ statusCode: 401, body: '' }));
+
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION }),
+ /Authentication \/ authorization failed \(401\)/
+ );
+});
+
+test('throws with auth-specific message on 403 (likely missing solutions-table read permission)', async (t) => {
+ withMockedRequests(t, () => ({ statusCode: 403, body: '' }));
+
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION }),
+ /Authentication \/ authorization failed \(403\)/
+ );
+});
+
+test('throws on unexpected status code with the response body included', async (t) => {
+ withMockedRequests(t, () => ({ statusCode: 500, body: 'Internal Server Error' }));
+
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION }),
+ /Unexpected response \(500\): Internal Server Error/
+ );
+});
+
+test('throws when the response body is not valid JSON', async (t) => {
+ withMockedRequests(t, () => ({ statusCode: 200, body: '<html>not json</html>' }));
+
+ await assert.rejects(
+ () => checkSolutionInstalled({ envUrl: ENV_URL, token: TOKEN, solutionName: SOLUTION }),
+ /Failed to parse Dataverse response as JSON/
+ );
+});
+
+// --- sanitizeEnvUrl: defense against command injection via --envUrl ---
+//
+// The output of sanitizeEnvUrl is passed to helpers.getAuthToken, which
+// interpolates it into `az account get-access-token --resource "${url}"`
+// via execSync (a shell command). If we didn't sanitize, an attacker who
+// could pass a malicious --envUrl on the CLI could execute arbitrary
+// shell commands.
+
+test('sanitizeEnvUrl accepts a plain Dataverse URL and returns just the origin', () => {
+ assert.equal(
+ sanitizeEnvUrl('https://contoso.crm.dynamics.com'),
+ 'https://contoso.crm.dynamics.com'
+ );
+});
+
+test('sanitizeEnvUrl strips path, query, and fragment from the URL', () => {
+ assert.equal(
+ sanitizeEnvUrl('https://contoso.crm.dynamics.com/api/data/v9.2/solutions?$top=1#hash'),
+ 'https://contoso.crm.dynamics.com'
+ );
+});
+
+test('sanitizeEnvUrl preserves an explicit port', () => {
+ assert.equal(
+ sanitizeEnvUrl('https://contoso.crm.dynamics.com:8443/some/path'),
+ 'https://contoso.crm.dynamics.com:8443'
+ );
+});
+
+test('sanitizeEnvUrl strips a trailing slash by normalizing to origin', () => {
+ assert.equal(
+ sanitizeEnvUrl('https://contoso.crm.dynamics.com/'),
+ 'https://contoso.crm.dynamics.com'
+ );
+});
+
+test('sanitizeEnvUrl rejects shell-injection payloads embedded in the URL', () => {
+ // The whole point of using URL.origin is that these characters are stripped
+ // (in path/query/fragment) or rejected by URL parsing (in host).
+ // Verify a few representative payloads no longer make it through.
+
+ // Path-position payload: URL parses fine, but origin throws away the path.
+ assert.equal(
+ sanitizeEnvUrl('https://contoso.crm.dynamics.com/"; rm -rf ~; echo "'),
+ 'https://contoso.crm.dynamics.com'
+ );
+
+ // Query-position payload: same story.
+ assert.equal(
+ sanitizeEnvUrl('https://contoso.crm.dynamics.com?x="; rm -rf ~; echo "'),
+ 'https://contoso.crm.dynamics.com'
+ );
+
+ // Newline in the URL — WHATWG URL parsing strips ASCII tabs and newlines
+ // per spec, so a newline-laced URL gets normalized to a safe origin rather
+ // than carrying the newline downstream. This is the behavior we want — a
+ // newline in a shell command argument can be used to break out of a quoted
+ // string.
+ assert.equal(
+ sanitizeEnvUrl('https://contoso\ndynamics.com'),
+ 'https://contosodynamics.com'
+ );
+ assert.doesNotMatch(sanitizeEnvUrl('https://contoso\tdynamics.com'), /\s/);
+});
+
+test('sanitizeEnvUrl rejects non-https protocols', () => {
+ assert.throws(() => sanitizeEnvUrl('http://contoso.crm.dynamics.com'), /must use https/);
+ assert.throws(() => sanitizeEnvUrl('file:///etc/passwd'), /must use https/);
+ assert.throws(() => sanitizeEnvUrl('javascript:alert(1)'), /must use https/);
+});
+
+test('sanitizeEnvUrl rejects URLs containing userinfo (credentials)', () => {
+ assert.throws(
+ () => sanitizeEnvUrl('https://attacker:[email protected]'),
+ /must not contain userinfo/
+ );
+ assert.throws(
+ () => sanitizeEnvUrl('https://[email protected]'),
+ /must not contain userinfo/
+ );
+});
+
+test('sanitizeEnvUrl rejects garbage input', () => {
+ assert.throws(() => sanitizeEnvUrl(''), /non-empty string/);
+ assert.throws(() => sanitizeEnvUrl(' '), /non-empty string/);
+ assert.throws(() => sanitizeEnvUrl(null), /non-empty string/);
+ assert.throws(() => sanitizeEnvUrl(undefined), /non-empty string/);
+ assert.throws(() => sanitizeEnvUrl(42), /non-empty string/);
+ assert.throws(() => sanitizeEnvUrl('not a url'), /not a valid URL/);
+ assert.throws(() => sanitizeEnvUrl('://broken'), /not a valid URL/);
+});
diff --git a/plugins/power-pages/scripts/tests/create-site-setting.test.js b/plugins/power-pages/scripts/tests/create-site-setting.test.js
index 04d29cfe2..304af883f 100644
--- a/plugins/power-pages/scripts/tests/create-site-setting.test.js
+++ b/plugins/power-pages/scripts/tests/create-site-setting.test.js
@@ -66,3 +66,116 @@ test('create-site-setting rejects mixing environment-variable and value inputs',
assert.equal(result.status, 1);
assert.match(result.stderr, /cannot be combined with --value or --description/);
});
+
+// --- YAML quoting edge cases ---
+//
+// The YAML writer must quote values that would change meaning when read back
+// by a YAML 1.2 parser. The body-of-value character-class regex catches most
+// cases, but a few values look harmless but still need quoting because they
+// rely on the LEADING character.
+
+function getWrittenYaml(t, settingName, value) {
+ const projectRoot = createTempProject(t);
+ const result = runCreateSiteSetting([
+ '--projectRoot', projectRoot,
+ '--name', settingName,
+ '--value', value,
+ '--description', 'test',
+ ]);
+ assert.equal(result.status, 0, result.stderr);
+ const parsed = JSON.parse(result.stdout);
+ return fs.readFileSync(parsed.filePath, 'utf8');
+}
+
+test('quotes values starting with a hyphen (would be a YAML sequence indicator unquoted)', (t) => {
+ const yaml = getWrittenYaml(t, 'Test/HyphenLeading', '-foo');
+ assert.match(yaml, /^value: "-foo"$/m);
+});
+
+test('quotes values starting with a single quote (would open an unterminated quoted scalar)', (t) => {
+ const yaml = getWrittenYaml(t, 'Test/SQuoteLeading', "'foo");
+ assert.match(yaml, /^value: "'foo"$/m);
+});
+
+test('quotes values starting with a double quote (would open an unterminated quoted scalar)', (t) => {
+ const yaml = getWrittenYaml(t, 'Test/DQuoteLeading', '"foo');
+ // The leading literal " in the value gets backslash-escaped inside the JSON-style YAML quoted scalar
+ assert.match(yaml, /^value: "\\"foo"$/m);
+});
+
+test('quotes values starting with a tab character (not allowed by YAML 1.2 in plain scalars)', (t) => {
+ const yaml = getWrittenYaml(t, 'Test/TabLeading', '\tfoo');
+ assert.match(yaml, /^value: "\tfoo"$/m);
+});
+
+test('quotes YAML 1.2 bareword reserved values: true / false / null', (t) => {
+ // These are strings the caller passed as the --value, but YAML would read them
+ // back as boolean true/false/null. The site-setting code passes booleans
+ // through --type=boolean, so `--value true` (without --type=boolean) means
+ // the string "true". Without quoting, the YAML parser would re-coerce.
+ assert.match(getWrittenYaml(t, 'Test/StrTrue', 'true'), /^value: "true"$/m);
+ assert.match(getWrittenYaml(t, 'Test/StrFalse', 'false'), /^value: "false"$/m);
+ assert.match(getWrittenYaml(t, 'Test/StrNull', 'null'), /^value: "null"$/m);
+});
+
+test('does NOT quote ordinary values with no special characters or leading indicators', (t) => {
+ // Regression guard: the leading-character check must not over-quote plain
+ // values. A value like "Contoso Portal" or "/signin-EntraExternal" should
+ // emit as a bareword scalar.
+ const yaml1 = getWrittenYaml(t, 'Test/PlainText', 'Contoso Portal');
+ assert.match(yaml1, /^value: Contoso Portal$/m);
+ const yaml2 = getWrittenYaml(t, 'Test/PathLike', '/signin-EntraExternal');
+ assert.match(yaml2, /^value: \/signin-EntraExternal$/m);
+});
+
+// --- Writer / loader round-trip ---
+//
+// The whole point of the C5 quoting is that a value's meaning survives a
+// round-trip through the YAML file. Without a symmetric unquote in the
+// loader (powerpages-config.js#parseYamlScalar), the writer's quotes would
+// be read back as literal characters, corrupting subsequent reads. Verify
+// that loadSiteSettings() returns the ORIGINAL input string.
+
+const { loadSiteSettings } = require('../lib/powerpages-config');
+
+function roundTrip(t, settingName, value) {
+ const projectRoot = createTempProject(t);
+ const result = runCreateSiteSetting([
+ '--projectRoot', projectRoot,
+ '--name', settingName,
+ '--value', value,
+ '--description', 'round-trip test',
+ ]);
+ assert.equal(result.status, 0, result.stderr);
+ const siteSettingsDir = path.join(projectRoot, '.powerpages-site', 'site-settings');
+ const settings = loadSiteSettings(siteSettingsDir);
+ const found = settings.find(s => s.name === settingName);
+ assert.ok(found, `setting ${settingName} not found after write`);
+ return found;
+}
+
+test('round-trip preserves value with leading hyphen', (t) => {
+ const setting = roundTrip(t, 'Test/RT/Hyphen', '-foo');
+ assert.equal(setting.value, '-foo');
+});
+
+test('round-trip preserves value with embedded quotes', (t) => {
+ const setting = roundTrip(t, 'Test/RT/EmbeddedQuotes', 'He said "hi"');
+ assert.equal(setting.value, 'He said "hi"');
+});
+
+test('round-trip preserves YAML 1.2 reserved-bareword strings as strings (not coerced)', (t) => {
+ // The writer quotes these to defend against bareword coercion; the loader
+ // must unquote them back to the string. Without the C5 round-trip fix the
+ // loader would return either the boolean true/false/null OR the literal
+ // string with quote characters embedded.
+ assert.equal(roundTrip(t, 'Test/RT/StrTrue', 'true').value, 'true');
+ assert.equal(roundTrip(t, 'Test/RT/StrFalse', 'false').value, 'false');
+ assert.equal(roundTrip(t, 'Test/RT/StrNull', 'null').value, 'null');
+});
+
+test('round-trip preserves value containing a literal backslash', (t) => {
+ // \\ is the writer's escape for a literal backslash; the loader must unescape it.
+ const setting = roundTrip(t, 'Test/RT/Backslash', 'back\\slash');
+ assert.equal(setting.value, 'back\\slash');
+});
diff --git a/plugins/power-pages/scripts/tests/powerpages-config.test.js b/plugins/power-pages/scripts/tests/powerpages-config.test.js
index 37e430829..96de43396 100644
--- a/plugins/power-pages/scripts/tests/powerpages-config.test.js
+++ b/plugins/power-pages/scripts/tests/powerpages-config.test.js
@@ -20,3 +20,84 @@ test('parseSimpleYaml handles arrays and block-scalar descriptions', () => {
assert.equal(parsed.description, 'First line\n\nSecond line');
assert.deepEqual(parsed.adx_entitypermission_webrole, ['997e7996-e241-4117-9c09-28e90a1fcdbc']);
});
+
+// --- Quoted scalar unwrap (round-trip symmetry with create-site-setting writer) ---
+
+test('parseSimpleYaml unwraps double-quoted scalars and unescapes \\\\ and \\"', () => {
+ // The writer in create-site-setting.js wraps values like "-foo", "'foo",
+ // '"foo', and YAML 1.2 reserved barewords ("true", "false", "null") in
+ // double quotes. The loader must return the original UNQUOTED string so a
+ // read-modify-write cycle doesn't silently mutate the value.
+ const parsed = parseSimpleYaml(
+ [
+ 'a: "-foo"',
+ 'b: "\'foo"',
+ 'c: "\\"foo"',
+ 'd: "true"',
+ 'e: "false"',
+ 'f: "null"',
+ 'g: "back\\\\slash"',
+ ].join('\n'),
+ 'sample.yml'
+ );
+
+ assert.equal(parsed.a, '-foo');
+ assert.equal(parsed.b, "'foo");
+ assert.equal(parsed.c, '"foo');
+ // These three would be parsed as boolean / null if unwrapping happened after
+ // the bareword tests. The order in parseYamlScalar is deliberate.
+ assert.equal(parsed.d, 'true');
+ assert.equal(parsed.e, 'false');
+ assert.equal(parsed.f, 'null');
+ assert.equal(parsed.g, 'back\\slash');
+});
+
+test('parseSimpleYaml unwraps single-quoted scalars and unescapes \'\' as a literal quote', () => {
+ const parsed = parseSimpleYaml(
+ [
+ "a: '-foo'",
+ "b: 'hello ''world'''",
+ ].join('\n'),
+ 'sample.yml'
+ );
+ assert.equal(parsed.a, '-foo');
+ assert.equal(parsed.b, "hello 'world'");
+});
+
+test('parseSimpleYaml leaves plain (unquoted) scalars untouched', () => {
+ // Regression guard: the unwrap logic must only fire when both ends are the
+ // SAME quote character.
+ const parsed = parseSimpleYaml(
+ [
+ 'a: hello world',
+ 'b: contains "quote" mid-string',
+ 'c: ends with "',
+ 'd: "no matching close',
+ ].join('\n'),
+ 'sample.yml'
+ );
+ assert.equal(parsed.a, 'hello world');
+ assert.equal(parsed.b, 'contains "quote" mid-string');
+ assert.equal(parsed.c, 'ends with "');
+ assert.equal(parsed.d, '"no matching close');
+});
+
+test('parseYamlScalar bareword coercion still works for actually-bareword values', () => {
+ // Regression guard: the unwrap path is for QUOTED values. Unquoted true /
+ // false / null / digits must still coerce to JS booleans / null / number.
+ const parsed = parseSimpleYaml(
+ [
+ 'a: true',
+ 'b: false',
+ 'c: null',
+ 'd: 42',
+ 'e: -7',
+ ].join('\n'),
+ 'sample.yml'
+ );
+ assert.equal(parsed.a, true);
+ assert.equal(parsed.b, false);
+ assert.equal(parsed.c, null);
+ assert.equal(parsed.d, 42);
+ assert.equal(parsed.e, -7);
+});
diff --git a/plugins/power-pages/scripts/tests/render-auth-report.test.js b/plugins/power-pages/scripts/tests/render-auth-report.test.js
new file mode 100644
index 000000000..873ab4c2c
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/render-auth-report.test.js
@@ -0,0 +1,178 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const scriptPath = path.join(__dirname, '..', 'render-auth-report.js');
+
+const SAMPLE_DATA = {
+ META_DATA: {
+ siteName: 'Contoso Portal',
+ reportDate: '2026-05-27',
+ framework: 'React',
+ nextStepsHtml: '<ol><li>Deploy with <code>pac pages upload-code-site</code>.</li></ol>',
+ },
+ PROVIDERS_DATA: [
+ {
+ type: 'External',
+ displayName: 'Entra External ID',
+ name: 'EntraExternal',
+ identifier: 'https://contoso.ciamlogin.com/...',
+ authority: 'https://contoso.ciamlogin.com/tenant-id',
+ clientId: 'abc-123',
+ redirectUri: 'https://contoso.powerappsportals.com/signin-EntraExternal',
+ scopes: 'openid profile email',
+ registrationClaimsMapping: 'firstname=given_name,lastname=family_name,emailaddress1=email',
+ loginClaimsMapping: null,
+ contactLinking: 'Link to existing contact by email',
+ profileSync: 'First sign-in only',
+ federatedLogout: 'Disabled',
+ isPrimary: true,
+ },
+ ],
+ LOCAL_AUTH_DATA: null,
+ OPTIONAL_FEATURES_DATA: {
+ profilePage: true,
+ termsAndConditions: true,
+ termsEnforced: false,
+ federatedLogout: false,
+ sessionKeepAlive: true,
+ },
+ SITE_SETTINGS_DATA: [
+ { name: 'Authentication/Registration/ProfileRedirectEnabled', value: 'false' },
+ { name: 'Webapi/contact/enabled', value: 'true' },
+ ],
+ TABLE_PERMISSIONS_DATA: [
+ {
+ name: 'My Profile - Edit Own Contact',
+ table: 'contact',
+ scope: 'Self (756150004)',
+ read: true,
+ write: true,
+ create: false,
+ delete: false,
+ },
+ ],
+ FILES_DATA: [
+ { path: 'src/pages/UserProfile.tsx', action: 'Created', notes: '' },
+ { path: 'src/components/AuthButton.tsx', action: 'Updated', notes: 'Evolved to dropdown shape' },
+ ],
+};
+
+test('render-auth-report renders HTML from --data file', () => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'auth-report-'));
+ const dataPath = path.join(tempDir, 'data.json');
+ const outputPath = path.join(tempDir, 'auth-report.html');
+
+ fs.writeFileSync(dataPath, JSON.stringify(SAMPLE_DATA, null, 2), 'utf8');
+
+ const result = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], {
+ encoding: 'utf8',
+ });
+
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ assert.ok(fs.existsSync(outputPath));
+
+ const html = fs.readFileSync(outputPath, 'utf8');
+
+ // Title in HTML <title> is set by inline JS, so just confirm SITE_NAME made it in
+ assert.match(html, /Contoso Portal/);
+ // Provider details
+ assert.match(html, /Entra External ID/);
+ assert.match(html, /firstname=given_name/);
+ // Site settings
+ assert.match(html, /ProfileRedirectEnabled/);
+ // Table permissions
+ assert.match(html, /My Profile - Edit Own Contact/);
+ assert.match(html, /Self \(756150004\)/);
+ // Files table
+ assert.match(html, /UserProfile\.tsx/);
+ assert.match(html, /AuthButton\.tsx/);
+ // Standard AI-generated footer matches the convention used by other reports
+ assert.match(html, /AI-generated content may be incorrect/);
+ // Vertical tabs structure
+ assert.match(html, /data-tab="overview"/);
+ assert.match(html, /data-tab="next-steps"/);
+});
+
+test('render-auth-report fails with no arguments', () => {
+ const result = spawnSync(process.execPath, [scriptPath], { encoding: 'utf8' });
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /Usage:/);
+});
+
+test('render-auth-report fails when --data file is missing a required key', () => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'auth-report-'));
+ const dataPath = path.join(tempDir, 'data.json');
+ const outputPath = path.join(tempDir, 'auth-report.html');
+
+ // Omit META_DATA so the renderTemplate helper reports it as missing
+ const broken = Object.assign({}, SAMPLE_DATA);
+ delete broken.META_DATA;
+ fs.writeFileSync(dataPath, JSON.stringify(broken), 'utf8');
+
+ const result = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], {
+ encoding: 'utf8',
+ });
+
+ assert.equal(result.status, 1);
+ assert.match(result.stderr, /Missing required keys/);
+ assert.match(result.stderr, /META_DATA/);
+});
+
+test('render-auth-report refuses to overwrite an existing output file', () => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'auth-report-'));
+ const dataPath = path.join(tempDir, 'data.json');
+ const outputPath = path.join(tempDir, 'auth-report.html');
+
+ fs.writeFileSync(dataPath, JSON.stringify(SAMPLE_DATA), 'utf8');
+
+ // First run succeeds
+ const result1 = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], {
+ encoding: 'utf8',
+ });
+ assert.equal(result1.status, 0, result1.stderr || result1.stdout);
+ const original = fs.readFileSync(outputPath, 'utf8');
+
+ // Second run with the same output path must fail without modifying the file
+ const result2 = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], {
+ encoding: 'utf8',
+ });
+ assert.equal(result2.status, 1);
+ assert.match(result2.stderr, /Output file already exists/);
+ assert.equal(fs.readFileSync(outputPath, 'utf8'), original);
+});
+
+test('render-auth-report handles empty arrays and null LOCAL_AUTH_DATA cleanly', () => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'auth-report-'));
+ const dataPath = path.join(tempDir, 'data.json');
+ const outputPath = path.join(tempDir, 'auth-report.html');
+
+ const minimal = {
+ META_DATA: {
+ siteName: 'Empty Site',
+ reportDate: '2026-05-27',
+ framework: '',
+ nextStepsHtml: '',
+ },
+ PROVIDERS_DATA: [],
+ LOCAL_AUTH_DATA: null,
+ OPTIONAL_FEATURES_DATA: {},
+ SITE_SETTINGS_DATA: [],
+ TABLE_PERMISSIONS_DATA: [],
+ FILES_DATA: [],
+ };
+ fs.writeFileSync(dataPath, JSON.stringify(minimal), 'utf8');
+
+ const result = spawnSync(process.execPath, [scriptPath, '--output', outputPath, '--data', dataPath], {
+ encoding: 'utf8',
+ });
+
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ const html = fs.readFileSync(outputPath, 'utf8');
+ assert.match(html, /Empty Site/);
+ // No unreplaced template placeholders in the output
+ assert.doesNotMatch(html, /__[A-Z][A-Z0-9_]+__/);
+});
diff --git a/plugins/power-pages/scripts/tests/validate-auth.test.js b/plugins/power-pages/scripts/tests/validate-auth.test.js
new file mode 100644
index 000000000..4bfb2a8ba
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/validate-auth.test.js
@@ -0,0 +1,298 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { spawnSync } = require('child_process');
+const path = require('path');
+
+const { createTempProject, writeProjectFile } = require('./test-utils');
+
+const VALIDATOR_PATH = path.join(
+ __dirname,
+ '..',
+ '..',
+ 'skills',
+ 'setup-auth',
+ 'scripts',
+ 'validate-auth.js'
+);
+
+function runValidator(projectRoot) {
+ return spawnSync(process.execPath, [VALIDATOR_PATH], {
+ input: JSON.stringify({ cwd: projectRoot }),
+ encoding: 'utf8',
+ });
+}
+
+const TYPE_DECLARATIONS = `
+export interface PowerPagesUser {
+ userName: string;
+ firstName?: string;
+ lastName?: string;
+ email?: string;
+ contactId?: string;
+ userRoles?: string[];
+}
+`;
+
+const COMPLETE_AUTH_SERVICE = `
+import type { PowerPagesUser } from '../types/powerPages';
+
+export interface AuthProviderConfig {
+ type: 'entra-id' | 'oidc' | 'saml2' | 'ws-federation' | 'local' | 'social';
+ displayName: string;
+}
+
+export const AUTH_PROVIDERS: AuthProviderConfig[] = [
+ { type: 'entra-id', displayName: 'Sign In' },
+];
+
+export async function fetchAntiForgeryToken(): Promise<string> {
+ const r = await fetch('/_layout/tokenhtml');
+ return (await r.text()).match(/value="([^"]+)"/)![1];
+}
+
+export function login() { /* ... */ }
+export function logout() { /* ... */ }
+export function getCurrentUser() { return undefined; }
+`;
+
+const AUTH_BUTTON = `
+import { useAuth } from '../hooks/useAuth';
+export default function AuthButton() { return null; }
+`;
+
+// The skill writes docs/auth-setup-report.html at the end of Phase 8.3.5.
+// The validator gates its real work on this file existing — without it, the
+// skill is considered in-progress and the validator silent-approves to avoid
+// blocking the run before it has had a chance to finish.
+const FINISHING_MARKER = '<html>fake auth report for testing</html>';
+function withMarker(projectRoot) {
+ writeProjectFile(projectRoot, 'docs/auth-setup-report.html', FINISHING_MARKER);
+ return projectRoot;
+}
+
+// --- Skip path: no auth files at all ---
+
+test('approves when the project has no auth artifacts (not a setup-auth session)', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('approves when the cwd is outside any Power Pages project', (t) => {
+ // Use a temp dir that does NOT contain powerpages.config.json
+ const projectRoot = createTempProject(t);
+ // Don't write powerpages.config.json — findProjectRoot returns null → approve
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+// --- In-progress path: auth artifacts exist but the finishing marker doesn't ---
+//
+// Without this gate, re-running setup-auth on a project that has stale auth
+// files from a previous failed attempt would block the new run before it
+// could overwrite them. With the marker gate, the validator silent-approves
+// until Phase 8.3.5 writes docs/auth-setup-report.html.
+
+test('silent-approves when auth artifacts exist but the finishing report has not been written yet', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ // Deliberately do NOT call withMarker — the report doesn't exist.
+ // Write an INCOMPLETE auth service: missing the login function and
+ // missing AUTH_PROVIDERS/AuthProviderConfig. With the marker present this
+ // would block (two errors); without it, the validator must silent-approve
+ // so the in-progress skill can finish.
+ writeProjectFile(projectRoot, 'src/services/authService.ts', '// half-written file\nexport function logout() {}\n');
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('also silent-approves when a date-suffixed report is the only marker on disk', (t) => {
+ // The skill renames the report on subsequent runs (auth-setup-report-2026-05-28.html).
+ // The validator should treat any matching file in docs/ as a valid marker.
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ writeProjectFile(projectRoot, 'docs/auth-setup-report-2026-05-28.html', '<html></html>');
+ writeProjectFile(projectRoot, 'src/services/authService.ts', COMPLETE_AUTH_SERVICE);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+// --- Happy path: complete auth setup ---
+
+test('approves a complete auth setup with AUTH_PROVIDERS array', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/services/authService.ts', COMPLETE_AUTH_SERVICE);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('also accepts AuthProviderConfig as a fallback marker when AUTH_PROVIDERS is absent', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ // Auth service declares AuthProviderConfig interface but no AUTH_PROVIDERS array.
+ // The validator should still pass — AuthProviderConfig is the type and is a
+ // valid signal that the provider configuration is set up.
+ const svc = COMPLETE_AUTH_SERVICE.replace(/AUTH_PROVIDERS/g, 'NOT_THE_ARRAY');
+ writeProjectFile(projectRoot, 'src/services/authService.ts', svc);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+// --- Failure paths: trigger each individual error message ---
+
+test('blocks when authService exists but type declarations are missing', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/services/authService.ts', COMPLETE_AUTH_SERVICE);
+ // No types file
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /Missing Power Pages type declarations/);
+});
+
+test('blocks when type declarations exist but authService is missing', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /Missing auth service/);
+});
+
+test('blocks when authService is missing the login function', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ writeProjectFile(
+ projectRoot,
+ 'src/services/authService.ts',
+ COMPLETE_AUTH_SERVICE.replace(/export function login\(\) [^\n]+\n/, '')
+ );
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /Auth service missing login function/);
+});
+
+test('blocks when authService has no anti-forgery token handling', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ // Strip the anti-forgery references
+ const svc = COMPLETE_AUTH_SERVICE
+ .replace(/\/_layout\/tokenhtml/g, '/some/other/url')
+ .replace(/fetchAntiForgeryToken/g, 'somethingElse');
+ writeProjectFile(projectRoot, 'src/services/authService.ts', svc);
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /missing anti-forgery token handling/);
+});
+
+test('blocks when authService has neither AUTH_PROVIDERS nor AuthProviderConfig (the canonical markers)', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ // Strip BOTH AUTH_PROVIDERS and AuthProviderConfig to simulate an auth service
+ // that doesn't follow the canonical pattern.
+ const svc = COMPLETE_AUTH_SERVICE
+ .replace(/AUTH_PROVIDERS/g, 'PROVIDERS_NOT_CANONICAL')
+ .replace(/AuthProviderConfig/g, 'ProviderInterface');
+ writeProjectFile(projectRoot, 'src/services/authService.ts', svc);
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ // The error message names the canonical shape so the implementer knows
+ // what to write — guards against regressions to the singular `AUTH_PROVIDER`
+ // pattern that the C7 review comment flagged.
+ assert.match(result.stderr, /AUTH_PROVIDERS array or AuthProviderConfig type/);
+ assert.match(result.stderr, /export const AUTH_PROVIDERS/);
+});
+
+test('blocks when the auth UI component is missing', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ writeProjectFile(projectRoot, 'src/services/authService.ts', COMPLETE_AUTH_SERVICE);
+ // No AuthButton component
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /Missing auth UI component/);
+});
+
+test('accepts auth components in src/app/components/ (Angular convention)', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ writeProjectFile(projectRoot, 'src/services/authService.ts', COMPLETE_AUTH_SERVICE);
+ // Angular convention — component lives under app/components/
+ writeProjectFile(projectRoot, 'src/app/components/auth-button.component.ts', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
+
+test('blocks when authService references hasRole but authorization utils are missing', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ // Auth service references hasRole, signalling that authorization is in scope
+ const svc = COMPLETE_AUTH_SERVICE + '\nexport function hasRole(role: string) { return false; }\n';
+ writeProjectFile(projectRoot, 'src/services/authService.ts', svc);
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+ // No authorization utility file
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 2);
+ assert.match(result.stderr, /Missing authorization utilities/);
+});
+
+test('approves when authorization utils exist and authService uses them', (t) => {
+ const projectRoot = createTempProject(t);
+ writeProjectFile(projectRoot, 'powerpages.config.json', '{}');
+ withMarker(projectRoot);
+ writeProjectFile(projectRoot, 'src/types/powerPages.d.ts', TYPE_DECLARATIONS);
+ const svc = COMPLETE_AUTH_SERVICE + '\nexport function hasRole(role: string) { return false; }\n';
+ writeProjectFile(projectRoot, 'src/services/authService.ts', svc);
+ writeProjectFile(projectRoot, 'src/utils/authorization.ts', 'export function hasRole() {}');
+ writeProjectFile(projectRoot, 'src/components/AuthButton.tsx', AUTH_BUTTON);
+
+ const result = runValidator(projectRoot);
+ assert.equal(result.status, 0, result.stderr);
+});
diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.md
index fe88aa8f3..6ec8fd9b9 100644
--- a/plugins/power-pages/skills/create-site/SKILL.md
+++ b/plugins/power-pages/skills/create-site/SKILL.md
@@ -241,6 +241,8 @@ Immediately after the dev server starts, verify the scaffold is working:
> - "Partner Hub" + Internal → Document Library, Partner Directory, Deal Tracker, Notifications
>
> Always generate options that make sense for the specific site — never reuse a fixed list.
+ >
+ > **If you include an Authentication feature option**, describe it generically as "Login/signup for tracking application status" or similar. Do NOT mention a specific identity provider (e.g., "Entra ID", "SAML", "Google") in the feature description — the `/power-pages:setup-auth` skill will ask the user which provider they want.
3. Read the design aesthetics reference: `${CLAUDE_PLUGIN_ROOT}/skills/create-site/references/design-aesthetics.md`
4. **Map aesthetic + mood to design choices** using the Aesthetic x Mood Mapping table from the design reference. Record the chosen font direction, color direction, and motion direction.
diff --git a/plugins/power-pages/skills/setup-auth/SKILL.md b/plugins/power-pages/skills/setup-auth/SKILL.md
index f3be25e12..1d5d3b0ee 100644
--- a/plugins/power-pages/skills/setup-auth/SKILL.md
+++ b/plugins/power-pages/skills/setup-auth/SKILL.md
@@ -1,10 +1,19 @@
---
name: setup-auth
-description: >-
- Sets up authentication (login/logout via Microsoft Entra ID) and role-based authorization
- for a Power Pages code site. Configures identity providers, protected routes, and access
- control. Use when the user wants to add login, configure Entra ID, enable authentication,
- or add role-based access to their site.
+description: >
+ Use when the user asks to "set up authentication", "add login",
+ "add logout", "add sign in", "enable auth", "add role-based access",
+ "add authorization", "protect routes", "configure identity provider",
+ "configure Entra ID", "configure Entra External ID",
+ "configure OpenID Connect", "add OIDC", "set up SAML",
+ "set up WS-Federation", "set up local login", "add username password",
+ "add Facebook login", "add Google sign in", "add Microsoft Account",
+ "set up invitation login", or otherwise wants to set up
+ authentication (login/logout) and role-based authorization for their
+ Power Pages code site using any supported identity provider
+ (Microsoft Entra ID, Entra External ID, OpenID Connect, SAML2,
+ WS-Federation, local authentication, Microsoft Account, Facebook,
+ or Google).
user-invocable: true
allowed-tools: Read, Write, Edit, Bash, Grep, Glob, AskUserQuestion, Task, TaskCreate, TaskUpdate, TaskList, Skill
model: opus
@@ -14,7 +23,7 @@ model: opus
# Set Up Authentication & Authorization
-Configure authentication (login/logout via Microsoft Entra ID) and role-based authorization for a Power Pages code site. This skill creates an auth service, type declarations, authorization utilities, auth UI components, and role-based access control patterns appropriate to the site's framework.
+Configure authentication (login/logout) and role-based authorization for a Power Pages code site. This skill supports multiple identity providers -- Microsoft Entra ID, Entra External ID (for customer-facing apps with self-service sign-up), OpenID Connect (generic), SAML2, WS-Federation, local authentication (username/password), Microsoft Account, Facebook, and Google. It also supports optional features including invitation-based registration and Terms & Conditions acceptance. Power Pages built-in 2FA is intentionally not scaffolded because the SendCode/VerifyCode pages are server-rendered and cannot be integrated into a SPA experience — use IdP-level MFA instead. It creates an auth service, type declarations, authorization utilities, auth UI components, and role-based access control patterns appropriate to the site's framework and chosen identity provider(s).
## Core Principles
@@ -105,16 +114,97 @@ Read each file and compile a list of existing web roles (name, id, flags).
**If "Skip"**: Continue — auth service and login/logout will still work, but role-based authorization will need roles created later.
-#### 1.5 Check for Existing Auth Code
+#### 1.5 Discover Existing Auth Configuration
-Search for existing auth files to avoid duplicating work:
+**Always run this discovery step, even on a first invocation** — the site may have site settings from a prior run, or from hand-editing the YAML files, even if no SPA auth code exists yet. The goal is to make sure we never silently drop a provider that's already configured server-side.
-- `src/services/authService.ts` or `src/services/authService.js`
-- `src/types/powerPages.d.ts`
-- `src/utils/authorization.ts` or `src/utils/authorization.js`
-- Auth components (e.g., `AuthButton.tsx`, `AuthButton.vue`)
+**Step 1 — Scan `.powerpages-site/site-settings/` for already-configured providers.**
-If auth files already exist, present them to the user and ask whether to overwrite or skip.
+Detect existing providers by matching site-setting filenames against these patterns:
+
+| Pattern | Maps to provider type |
+|---|---|
+| `Authentication-OpenIdConnect-{Name}-AuthenticationType.sitesetting.yml` | OIDC (Entra External ID, Okta, Auth0, generic OIDC, B2C — all share the OIDC path) |
+| `Authentication-SAML2-{Name}-AuthenticationType.sitesetting.yml` | SAML2 |
+| `Authentication-WsFederation-{Name}-AuthenticationType.sitesetting.yml` | WS-Federation |
+| `Authentication-OpenAuth-{Microsoft\|Facebook\|Google}-{ClientId\|AppId}.sitesetting.yml` | Social OAuth |
+| `Authentication-Registration-LocalLoginEnabled.sitesetting.yml` with value `true` | Local Authentication |
+
+For each detected provider, read its full set of `.sitesetting.yml` files to extract: `Authority` / `MetadataAddress`, `ClientId` / `AppId`, `AuthenticationType` (the providerIdentifier), `Caption` or display name (if present), and the `{Name}` slug used in the keys (e.g., `OpenIdConnect_1`, `EntraExternalId`).
+
+**Distinguishing Entra ID variants from OIDC** — by Authority URL pattern:
+
+| Authority pattern | Provider type | Notes |
+|---|---|---|
+| `https://login.windows.net/{guid}/` (no `/v2.0/`) — site's parent tenant | **Microsoft Entra ID (workforce)** — `type: 'entra-id'` | Auto-populated by Power Pages on site creation. The `{Name}` slug is usually `AzureAD`. **Set `providerIdentifier` to undefined in AUTH_PROVIDERS** — runtime resolver derives it from `Portal.tenant`. |
+| `https://{subdomain}.ciamlogin.com/{tenantId}` (no trailing `/v2.0/`) | **Entra External ID** — `type: 'oidc'` | Customer tenant. Must include explicit `providerIdentifier` matching the Authority. |
+| `https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/v2.0/{policy}` | **Azure AD B2C** (legacy) — `type: 'oidc'` | Older B2C product. Must include explicit `providerIdentifier`. |
+| Any other OIDC authority (Okta, Auth0, Ping, etc.) | **OIDC (Generic)** — `type: 'oidc'` | Must include explicit `providerIdentifier`. |
+
+**The Entra ID (workforce) case is special** — when Phase 1.5 discovery detects `Authentication/OpenIdConnect/AzureAD/*` settings on the site (which Power Pages auto-creates for the parent tenant), add a single entry to `EXISTING_PROVIDERS`:
+
+```typescript
+{
+ id: 'entra-id',
+ type: 'entra-id',
+ displayName: existingCaption || 'Sign in with Microsoft',
+ // NO providerIdentifier — resolveProviderIdentifier() derives it from Portal.tenant
+}
+```
+
+Do NOT extract the tenant ID from the existing Authority site setting just to hardcode it back into AUTH_PROVIDERS — the runtime resolver handles it. This keeps the SPA code portable if the site is ever cloned to a different tenant.
+
+**Step 2 — Scan for existing SPA auth code.**
+
+Check for these files and read their key markers:
+
+- `src/services/authService.ts` or `.js` — look for `AUTH_PROVIDERS` array (current pattern) vs single `AUTH_PROVIDER` constant (legacy)
+- `src/types/powerPages.d.ts` — exists or not
+- `src/utils/authorization.ts` — exists or not
+- Auth components (`AuthButton.*`, `Login.*`, `Registration.*`, `RedeemInvitation.*`, etc.) — list which exist
+- `src/pages/Login.tsx` — extract which providers it currently renders (via `AUTH_PROVIDERS` import or inline)
+
+**Step 3 — Present findings to the user.**
+
+If providers were detected from site settings, present them with their config:
+
+```
+I found these existing auth providers on your site:
+
+ ✓ Entra External ID
+ - ProviderName: OpenIdConnect_1
+ - Tenant: ba275000-98c8-404d-a6f0-c5450f2aa668
+ - ClientId: e728d63e-1190-495a-ae29-663e9cc10877
+ - Configured in site settings: yes
+ - Surfaced in SPA UI: NO (authService.ts has no entry for this provider)
+
+ ✓ Local Authentication
+ - LoginByEmail: true
+ - Surfaced in SPA UI: yes
+```
+
+Use `AskUserQuestion`:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| I found existing auth providers on your site. What would you like to do? | Existing auth | Keep all existing providers and add a new one (Recommended) — preserves what's there, adds what you ask for next, Keep all existing providers (no new provider this run) — re-generates SPA code to surface what's already in site settings, Replace everything with a new configuration — wipes existing site settings and SPA code, starts fresh |
+
+**"Keep all existing providers and add a new one"** (default path):
+- Store the discovered providers as `EXISTING_PROVIDERS` — these will be merged into the `AUTH_PROVIDERS` array generated in Phase 3.2
+- Phase 2.1 will prompt for the NEW provider being added; the existing ones are kept untouched
+- For **local auth specifically** — if `Local Authentication` is in `EXISTING_PROVIDERS`, **always regenerate the local auth SPA code** (login flow, registration page, forgot/reset password, redeem invitation) from the user's Phase 2.1 answers. Don't try to preserve hand-edited local-auth code — the local flows are complex enough that partial updates introduce more bugs than they avoid.
+
+**"Keep all existing providers (no new provider this run)"**:
+- Skip the Phase 2.1 provider selection question entirely
+- Re-derive `AUTH_PROVIDERS` from `EXISTING_PROVIDERS` only
+- Useful for: fixing a site where the SPA UI is missing a provider that's already in site settings (the exact bug this branch was created to fix)
+
+**"Replace everything with a new configuration"**:
+- Set `EXISTING_PROVIDERS = []`
+- Delete existing OIDC/SAML2/WsFed/OpenAuth site-setting YAMLs as part of Phase 8.1
+- Run Phase 2.1 as if no providers existed
+
+> **DO NOT** offer a "skip / no changes" option. If the user invokes setup-auth, they want auth set up — silently doing nothing is worse than asking.
### Output
@@ -122,7 +212,9 @@ If auth files already exist, present them to the user and ask whether to overwri
- Framework identified (React, Vue, Angular, or Astro)
- Deployment status verified
- Web roles inventory compiled
-- Existing auth code conflicts identified (if any)
+- **`EXISTING_PROVIDERS` list compiled from site settings, with provider type, ProviderName slug, ClientId/Authority/etc. for each**
+- **`MERGE_MODE` chosen: `keep-and-add` (default) | `keep-only` | `replace-all`**
+- SPA auth file inventory recorded (which files exist, whether they use `AUTH_PROVIDERS` array or legacy single-provider pattern)
---
@@ -132,195 +224,1615 @@ If auth files already exist, present them to the user and ask whether to overwri
### Actions
+#### 2.0 Smart Auth Inference (Before Asking)
+
+Before asking the user which providers they want, analyze the site context from Phase 1 (site name, purpose, audience type) and try to infer appropriate auth settings automatically:
+
+**Inference rules:**
+
+| Site Type | Inferred Auth Settings | Rationale |
+|-----------|----------------------|-----------|
+| Internal/employee portal (HR, dashboard, admin) | Entra ID + invitation-only registration (`OpenRegistrationEnabled=false`, `InvitationEnabled=true`) | Internal sites should restrict access to invited employees only |
+| Customer-facing portal (support, self-service) | Entra External ID + open registration | Customer portals need self-service sign-up for customers |
+| Partner portal (B2B, vendor) | Entra ID + invitation-only registration | Partners are pre-vetted; open registration is a security risk |
+| Public site with protected features (e-commerce, community) | Entra External ID + open registration + optional Google/Facebook | Public sites benefit from social login for frictionless sign-up |
+| Loan/financial/banking portal | Entra External ID + invitation-only registration | Financial sites require controlled access for compliance |
+
+**If you can infer with confidence**, present the recommendation with rationale:
+
+> "Based on your site purpose ({purpose}), I recommend:
+> - **{provider}** for authentication
+> - **{registration mode}** because {rationale}
+>
+> Would you like to proceed with this configuration, or choose different providers?"
+
+| Question | Options |
+|----------|---------|
+| Would you like to proceed with this recommended configuration? | Yes, proceed with recommendation, No, let me choose providers |
+
+**If "Yes"**: Skip Phase 2.1 provider selection and proceed directly to collecting provider-specific details (ClientId, tenant name, etc.) for the recommended provider(s).
+
+**If "No"** or **if you cannot infer with confidence**: Fall back to Phase 2.1 below.
+
#### 2.1 Gather Requirements
-Use `AskUserQuestion` to determine the scope:
+**Re-run handling — when Phase 1.5 detected existing providers:**
+
+The behavior depends on the `MERGE_MODE` chosen in Phase 1.5:
+
+- **`keep-only`** (user chose "keep all existing, no new provider this run") → Skip the new-provider selection question entirely. Proceed to the "Local Authentication" follow-ups only if local was detected. Phase 3.2 will generate `AUTH_PROVIDERS` from `EXISTING_PROVIDERS` only.
+- **`keep-and-add`** (default — user wants to add one more) → Ask the user what to add. The provider selection question below should still be multi-select (the user could be adding multiple new providers in one go), but the existing providers are NOT in the list (they're already configured — the question is asking what's *new*). Common patterns:
+ - User has Entra External ID, wants to add Local Auth → user selects "Local Authentication" → ask local follow-ups → Phase 3.2 merges
+ - User has Entra External ID + Local, wants to add a *second* Entra External ID tenant → user selects "Entra External ID" → after collecting Authority/ClientId, ask: `"You already have an Entra External ID provider configured for tenant {existing-tenant}. This new one is a separate instance — give it a distinct ProviderName slug (used in site setting keys like Authentication/OpenIdConnect/{ProviderName}/* and in code as the provider id)."` Let the user pick a slug (default to the next incrementing number, e.g., `OpenIdConnect_2`) or pick a custom name (e.g., `EntraExternalId_Employee`).
+- **`replace-all`** (user chose to wipe everything) → Run the provider selection question as on a first invocation.
+
+**Do NOT proactively ask "do you want to configure multiple instances?"** at the start. Walk the user through configuring ONE provider at a time. When they finish configuring one and want another, they can re-run setup-auth → Phase 1.5 detects what's there → Phase 2.1 in `keep-and-add` mode asks "what do you want to add now?". This keeps the question count low for the common case (configure one provider) while still supporting the advanced case (multiple tenants).
+
+**IMPORTANT: Multiple providers are supported.** The user may want more than one identity provider (e.g., Entra External ID + Google). If the user's initial prompt mentions specific providers, skip the provider selection question and proceed directly to collecting details for each mentioned provider.
+
+> **IMPORTANT — Local Authentication:** NEVER set up local authentication by default. Do NOT include it in the provider selection list, do NOT recommend it in smart inference, and do NOT configure it unless the user explicitly and specifically asks for it (e.g., "I want username/password login", "set up local login", "add local auth"). External identity providers (Entra External ID, Entra ID, OIDC, etc.) are always preferred. If the user says something ambiguous like "add login", default to an external provider — never to local auth.
+
+If the user has NOT specified which provider(s) they want, use `AskUserQuestion` to determine the identity provider(s). **This is a multi-select question** — the user can choose one or more:
| Question | Options |
|----------|---------|
-| Which authentication features do you need? | Login & Logout + Role-based access control (Recommended), Login & Logout only, Role-based access control only (auth service already exists) |
+| Which identity provider(s) do you want to use? (select all that apply) | Entra External ID (Recommended) — Customer identity with self-service sign-up (CIAM), Microsoft Entra ID — Azure AD / Entra ID for internal/employee sites, OpenID Connect (Generic) — Any OIDC-compliant provider (Okta, Auth0, Ping Identity, etc.), SAML2 — SAML 2.0 identity provider (ADFS, Shibboleth, etc.), WS-Federation — WS-Federation identity provider, Microsoft Account — Sign in with Microsoft personal/work account, Facebook — Sign in with Facebook, Google — Sign in with Google |
-If web roles were found in Phase 1.4, also ask:
+**Then, for EACH selected provider, ask the mandatory follow-up questions below.** Do not skip any provider — every selected provider needs its configuration collected before proceeding.
+
+For each provider, also share the relevant Microsoft Learn documentation link so the user knows where to get the values:
+
+**For "Microsoft Account"**:
| Question | Options |
|----------|---------|
-| Which web roles should have access to protected areas of the site? | *(List discovered web role names as options)* |
+| What is the Client ID from your Microsoft app registration? (e.g., `a1b2c3d4-e5f6-7890-abcd-ef1234567890`) | *(free text)* |
-#### 2.2 Present Plan for Approval
+> Docs: https://learn.microsoft.com/en-us/power-pages/security/authentication/openid-settings
-Present the implementation plan inline:
+**For "Facebook"**:
-- Which files will be created (auth service, types, authorization utils, components)
-- How the auth UI will be integrated into the site's navigation
-- Which routes/components will be protected and with which roles
-- The site setting that needs to be configured (`Authentication/Registration/ProfileRedirectEnabled = false`)
+| Question | Options |
+|----------|---------|
+| What is the App ID from the Facebook Developer Console? (e.g., `1234567890123456`) | *(free text)* |
-Use `AskUserQuestion` to get approval:
+> Docs: https://learn.microsoft.com/en-us/power-pages/security/authentication/facebook-settings
+
+**For "Google"**:
| Question | Options |
|----------|---------|
-| Here is the implementation plan for authentication and authorization. Would you like to proceed? | Approve and proceed (Recommended), I'd like to make changes |
+| What is the Client ID from the Google Cloud Console? (e.g., `123456789-abc.apps.googleusercontent.com`) | *(free text)* |
-**If "Approve and proceed"**: Continue to Phase 3.
+> Docs: https://learn.microsoft.com/en-us/power-pages/security/authentication/openid-settings
-**If "I'd like to make changes"**: Ask the user what they want to change, revise the plan, and present it again for approval.
+**For "OpenID Connect (Generic)"**:
-### Output
+| Question | Options |
+|----------|---------|
+| What is the Authority URL for your OpenID Connect provider? (e.g., `https://dev-12345.okta.com/oauth2/default` or `https://login.microsoftonline.com/{tenant}/v2.0`) | *(free text)* |
+| What is the Client ID (Application ID) from your provider's app registration? (e.g., `0oa1bcde2fGHIJklmn3o4`) | *(free text)* |
+| What is the Metadata Address URL? (Only needed if your provider's metadata is NOT at `{authority}/.well-known/openid-configuration`). Leave blank to auto-derive. | *(free text, optional)* |
+| What display name should the login button show? (e.g., `Sign in with Okta`) | *(free text)* |
-- Authentication scope confirmed (login/logout, role-based access, or both)
-- Target web roles selected
-- Implementation plan approved by user
+> Docs: https://learn.microsoft.com/en-us/power-pages/security/authentication/openid-settings
----
+**For "Entra External ID"** — use the 4-step walkthrough below. Do NOT just ask the user for Authority/ClientId/Metadata upfront — those values come from a tenant + app registration + user flow that the user may not have set up yet. Walk them through each prerequisite before asking for the corresponding value.
-## Phase 3: Create Auth Service
+> Reference doc: https://learn.microsoft.com/en-us/power-pages/security/authentication/entra-external-id
+> See also `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/references/authentication-reference.md` for the full Entra External ID prerequisites section the steps below cross-reference.
-**Goal:** Create the authentication service, type declarations, and framework-specific auth hook/composable with local development mock support.
+**Pre-computed values for THIS site** — before starting the walkthrough, compute:
+- `SITE_URL` = the deployed site URL (e.g., `https://site-597pv.powerappsportals.com`). Read from `pac env who` + the site name, or from the site's existing settings.
+- `PROVIDER_NAME` = if this is a fresh add, default to `OpenIdConnect_1` (or the next free `OpenIdConnect_N` slug per the CallbackPath uniqueness logic in Phase 8.1). The user can override to a custom slug like `EntraExternalId_Customer` for multi-instance setups.
+- `REDIRECT_URI` = `{SITE_URL}/signin-{PROVIDER_NAME-lowercased}` — e.g., `https://site-597pv.powerappsportals.com/signin-openidconnect_1`. The user pastes this verbatim into the Entra app registration.
+- `APP_NAME_SUGGESTION` = `power-pages-{site-shortname}` — e.g., `power-pages-savoria`
+- `USER_FLOW_NAME_SUGGESTION` = `{site-shortname}-signupsignin` — e.g., `savoria-signupsignin`
-Reference: `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/references/authentication-reference.md`
+Display these to the user before Step 1 so they have them handy.
+
+##### Step 1 — Tenant
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Do you already have a Microsoft Entra External ID tenant? (This is a separate tenant type from a regular workforce Entra ID tenant — sometimes called CIAM.) | Tenant | Yes — I have an External ID tenant, No — help me create one (free 30-day trial), I'm not sure |
+
+**If "No"**, show:
+
+> Steps to create an Entra External ID tenant:
+> 1. Open https://entra.microsoft.com/
+> 2. Sign in with the account that should own the tenant
+> 3. From the top, click **Manage tenants → Create**
+> 4. Choose **External (for customers)** — NOT Workforce
+> 5. Pick a domain prefix (the **tenant subdomain**) — e.g., `contoso` becomes `contoso.ciamlogin.com`. This appears in every login URL.
+> 6. Free 30-day trial: no credit card required. You can attach a paid Azure subscription later.
+>
+> Detailed guide: https://learn.microsoft.com/en-us/entra/external-id/customers/quickstart-tenant-setup
+>
+> When you've created the tenant, switch to it (top-right tenant picker in entra.microsoft.com), then come back here.
+
+**If "I'm not sure"**, show: "At https://entra.microsoft.com/ → top-right tenant picker. Tenants for customers are labeled **External**. Workforce tenants won't work — that's a different product."
+
+Then collect the tenant identifiers:
+
+| Question | Options |
+|----------|---------|
+| What is the tenant **subdomain**? (the part before `.ciamlogin.com` — e.g., `contoso`. Find it in the External ID tenant's Overview page under "Primary domain", removing `.onmicrosoft.com`.) | *(free text)* |
+| What is the tenant **ID** (GUID)? (Find it in the External ID tenant's Overview page under "Tenant ID" — looks like `a1b2c3d4-e5f6-7890-abcd-ef1234567890`.) | *(free text)* |
+
+**Validate**: subdomain matches `^[a-z0-9-]+$` (no dots, no uppercase, no `.ciamlogin.com` suffix); tenant ID matches the UUID regex. If either fails, show the expected format and re-prompt.
+
+Store as `EXTERNAL_ID_TENANT_SUBDOMAIN` and `EXTERNAL_ID_TENANT_ID`.
+
+##### Step 2 — App registration
+
+**Confirm the Redirect URI first.** The skill pre-computes a default based on the site URL and `PROVIDER_NAME`, but the user may prefer a different URI:
+
+> The Power Pages site needs a Redirect URI registered in your app registration. Based on the site URL and provider name, the default is:
+>
+> **`{REDIRECT_URI}`**
+>
+> You can keep this default, or use a different URI — for example, `{SITE_URL}/signin-entra-customer` or `{SITE_URL}/auth/external-id`. The host must be your Power Pages site; only the path can change.
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Use this Redirect URI? | Redirect URI | Use the default (Recommended) — `{REDIRECT_URI}`, Use a different URI |
+
+**If "Use a different URI"**, ask:
+
+| Question | Options |
+|----------|---------|
+| Enter the Redirect URI (must be on `{SITE_URL}`, must start with `{SITE_URL}/`, no spaces, no query string). Example: `{SITE_URL}/signin-entra-customer`. | *(free text)* |
+
+**Validate** the custom URI:
+- Must start with `{SITE_URL}/`
+- Path portion must match `^/[a-zA-Z0-9_\-/]+$` (alphanumeric, hyphen, underscore, additional slashes allowed)
+- Path must NOT collide with any `Authentication/OpenIdConnect/*/CallbackPath` already in `.powerpages-site/site-settings/` (from Phase 1.5 discovery)
+- Path must NOT be a reserved Power Pages server path (`/Account/...`, `/SignIn`, `/Register`, `/_layout/...`, `/api/...`)
+
+Re-prompt on invalid input. Then store the value as `REDIRECT_URI` for the rest of the walkthrough and Phase 8.1.
+
+> **Note**: The skill writes two site settings derived from this single `REDIRECT_URI`: the user-facing `RedirectUri` (the full URI, sent to the IdP) and the internal `CallbackPath` (just the path portion, used by the OWIN middleware to know which incoming request to handle). The maker doesn't need to think about `CallbackPath` separately — the skill derives it automatically from `REDIRECT_URI` by extracting the path portion.
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Have you registered an app in your Entra External ID tenant for this Power Pages site? | App reg | No — walk me through it (Recommended for first time), Yes — I have the Application (client) ID |
+
+**If "No"**, show step-by-step with the confirmed Redirect URI verbatim:
+
+> Steps to register the app:
+> 1. At https://entra.microsoft.com/, make sure you're in your External ID tenant (top-right picker)
+> 2. **Applications → App registrations → New registration**
+> 3. **Name**: `{APP_NAME_SUGGESTION}` (or your own name)
+> 4. **Supported account types**: select **Accounts in this organizational directory only (single tenant)** — recommended for Power Pages. Multi-tenant configurations forcibly disable contact mapping by email for security.
+> 5. **Redirect URI**: select **Web**, paste exactly:
+>
+> ```
+> {REDIRECT_URI}
+> ```
+>
+> (Copy this verbatim. Any mismatch between this value and the `RedirectUri` site setting causes sign-in to fail with `AADSTS50011: The reply URL specified in the request does not match`.)
+> 6. Click **Register**
+> 7. Open the **Authentication** tab → under "Implicit grant and hybrid flows" check **Access tokens** AND **ID tokens** → **Save**
+> 8. Open the **API permissions** tab → click **Grant admin consent for {your tenant}** → confirm
+> 9. Go back to the **Overview** tab and copy the **Application (client) ID** (it's a GUID)
+>
+> Detailed guide: https://learn.microsoft.com/en-us/entra/external-id/customers/quickstart-register-app
+
+**If "Yes" (existing app)**, before asking for the Client ID, also confirm the user has the matching Redirect URI registered:
+
+> Before continuing, please verify that your existing app registration has the following Redirect URI registered (under **Authentication → Web** in the Entra admin center):
+>
+> **`{REDIRECT_URI}`**
+>
+> If it's missing or different, add it now. An app registration can have multiple Web Redirect URIs registered — adding ours doesn't break any existing integrations. Sign-in will fail if the value in Power Pages doesn't match a registered URI exactly.
+
+Then ask for the value:
+
+| Question | Options |
+|----------|---------|
+| Paste the **Application (client) ID** from the Overview tab. | *(free text)* |
+
+**Validate**: must match UUID v4 format (`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`). Re-prompt on mismatch.
+
+Store as `EXTERNAL_ID_CLIENT_ID`.
+
+**Do NOT ask about client secret.** Entra External ID app registrations are public clients using PKCE — no secret needed. The skill will create site settings without `ClientSecret` and skip Phase 8.1.1 (Key Vault) for this provider. If the user has a confidential-client scenario that requires a secret, they can add it manually via the Power Pages admin center after deploy — document this as an advanced override in Phase 8.5 post-deploy notes.
+
+##### Step 3 — User flow
+
+User flows define what attributes are collected from users and what claims appear in the ID token. Without one, sign-in fails after the IdP redirect.
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Have you created a sign-up/sign-in user flow in your Entra External ID tenant and attached it to your app? | User flow | No — walk me through it (Recommended for first time), Yes — I have the user flow name |
+
+**If "No"**, the walkthrough's user-flow-attribute selection must match the `PROFILE_MAPPING_CHOICE` collected later (Track B's profile mapping question). Since this step runs BEFORE that question, ask it now (just for Entra External ID):
+
+> The user flow needs to be told which attributes to collect from users and which claims to return in the token. The skill maps claims → Dataverse contact fields automatically — the attributes you select here determine what's available.
+
+| Question | Header | Options |
+|----------|--------|---------|
+| What user profile info should the sign-up form collect and return as claims? | Profile attributes | Standard (Recommended) — Email, Given Name, Surname, Standard + phone — also Phone Number, Email only — minimal sign-up form |
+
+Store as `PROFILE_ATTRIBUTES_CHOICE` (this also drives `PROFILE_MAPPING_CHOICE` in Track B — they should be consistent; default both to "Standard" unless the user explicitly differs).
+
+Then show:
+
+> Steps to create the user flow:
+> 1. At https://entra.microsoft.com/, in your External ID tenant
+> 2. **External Identities → User flows → New user flow**
+> 3. **Name**: `{USER_FLOW_NAME_SUGGESTION}` (or your own — letters, digits, hyphens, underscores only)
+> 4. **Identity providers** for sign-in: choose **Email with password** (Recommended — most familiar to customers) or **Email one-time passcode** (passwordless)
+> 5. **User attributes to collect** (the sign-up form fields): based on your choice above, select:
+> - **Standard / Standard + phone**: ☑ Email Address, ☑ Given Name, ☑ Surname{`, ☑ Phone Number` if Standard + phone}
+> - **Email only**: ☑ Email Address
+> 6. **User attributes to return as claims** (in the ID token): same selections as above — these power profile mapping into Dataverse contact fields
+> 7. Click **Create**
+> 8. Open the user flow you just created → **Applications** tab → **Add application** → select the app you registered in Step 2 → **Select**
+>
+> Detailed guide: https://learn.microsoft.com/en-us/entra/external-id/customers/how-to-user-flow-sign-up-sign-in-customers
+
+Then ask:
+
+| Question | Options |
+|----------|---------|
+| Paste the **user flow name** you created (e.g., `{USER_FLOW_NAME_SUGGESTION}`). | *(free text)* |
+
+**Validate**: matches `^[a-zA-Z0-9_-]+$` (letters, digits, hyphens, underscores). Re-prompt on mismatch.
+
+Store as `EXTERNAL_ID_USER_FLOW`.
+
+##### Step 4 — Display name + Confirmation
+
+| Question | Options |
+|----------|---------|
+| What should the login button label say? Default: **`Sign in with Entra External ID`** (shortened from "Sign in with Microsoft Entra External ID" so it fits on one line in the horizontal-row Login page layout — see note below). Do NOT use "Sign in with Microsoft" — that conflicts with the Microsoft Account social provider. | *(free text, defaulted)* |
+
+> **Display name length guidance**: keep labels around **28 characters or less** to display on a single line in the horizontal-row Login page layout (which is the default). Longer labels still work — buttons grow vertically to wrap text to two lines — but single-line buttons look more polished. For reference:
+> - "Sign in with Entra External ID" — 30 chars (wraps on narrow cards, fits on wider)
+> - "Sign in with Microsoft Entra External ID" — 40 chars (wraps to two lines in the default horizontal layout)
+> - "Customer Sign In" — 16 chars (always single line, but less descriptive)
+>
+> If the user has multiple external providers configured (e.g., Entra External ID + Google), shorter labels matter more because each button gets less width. For a single-provider site, longer labels are fine (the button spans the full row width).
+
+Store as `EXTERNAL_ID_DISPLAY_NAME`.
+
+Now derive the configuration and present a summary for confirmation:
+
+- **Authority**: `https://{EXTERNAL_ID_TENANT_SUBDOMAIN}.ciamlogin.com/{EXTERNAL_ID_TENANT_ID}` (NO trailing `/v2.0/` — Entra External ID uses the bare tenant path, NOT the B2C-style URL)
+- **MetadataAddress**: `https://{EXTERNAL_ID_TENANT_SUBDOMAIN}.ciamlogin.com/{EXTERNAL_ID_TENANT_ID}/v2.0/.well-known/openid-configuration`
+- **AuthenticationType** (provider identifier in `AUTH_PROVIDERS` array and ExternalLogin POST): same value as Authority
+- **RedirectUri**: `{REDIRECT_URI}` (computed earlier)
+- **ClientId**: `{EXTERNAL_ID_CLIENT_ID}`
+
+Present this summary inline:
+
+> About to configure:
+>
+> | Field | Value |
+> |---|---|
+> | Provider | Microsoft Entra External ID |
+> | Tenant | `{subdomain}.ciamlogin.com` (`{tenantId}`) |
+> | App (Client) ID | `{clientId}` |
+> | User flow | `{userFlowName}` |
+> | Redirect URI | `{REDIRECT_URI}` (must already be registered in your app) |
+> | Authority | `{authority}` (derived) |
+> | Metadata | `{metadataAddress}` (derived) |
+> | Display name | `{displayName}` |
+> | Login button | "{displayName}" |
+> | Client secret | None (public client / PKCE) |
+>
+> Continue to write these site settings?
+
+| Question | Options |
+|----------|---------|
+| Continue? | Yes — write the site settings, No — let me adjust |
+
+If "No", re-prompt for the specific value the user wants to change.
+
+> **Implementation note:** Power Pages server treats Entra External ID as a generic OpenID Connect provider (no special CIAM handling). All settings go under `Authentication/OpenIdConnect/{ProviderName}/`. The `provider` value posted to `/Account/Login/ExternalLogin` must match the `AuthenticationType` site setting, which by default equals the authority URL.
+
+**For "SAML2"**:
+
+| Question | Options |
+|----------|---------|
+| What is the metadata endpoint URL for your SAML2 identity provider? (e.g., `https://adfs.contoso.com/FederationMetadata/2007-06/FederationMetadata.xml`) | *(free text)* |
+| What display name should the login button show? (e.g., `Sign in with ADFS`) | *(free text)* |
+
+> Docs: https://learn.microsoft.com/en-us/power-pages/security/authentication/saml2-settings
+
+**For "WS-Federation"**:
+
+| Question | Options |
+|----------|---------|
+| What is the metadata endpoint URL for your WS-Federation provider? (e.g., `https://adfs.contoso.com/federationmetadata/2007-06/federationmetadata.xml`) | *(free text)* |
+| What is the provider realm or identifier? (e.g., `https://adfs.contoso.com/adfs/services/trust`) | *(free text)* |
+| What display name should the login button show? (e.g., `Sign in with ADFS`) | *(free text)* |
+
+> Docs: https://learn.microsoft.com/en-us/power-pages/security/authentication/ws-federation-settings
+
+**Profile mapping (for every external provider — OIDC, Entra External ID, SAML2, WS-Federation, social)**
+
+After collecting the provider's basic details, ask what user profile info should flow from the IdP to the Dataverse contact. **Don't skip this** — without it, contact records have empty `firstname`/`lastname` and the SPA falls back to displaying the email or username everywhere.
+
+| Question | Header | Options |
+|----------|--------|---------|
+| What profile info should be copied from your identity provider into the Dataverse contact record? | Profile mapping | Standard (Recommended) — copy first name, last name, and email on first sign-in, Standard + phone — also copy mobile phone, Custom — let me pick which contact fields and claims to map, None — leave contact fields empty (the server will still populate emailaddress1 from the email claim) |
+
+Store as `PROFILE_MAPPING_CHOICE`. Then ask:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Should profile info be updated on every login, or only once at first sign-in? | Sync frequency | First sign-in only (Recommended) — copy claims once when the contact is created; let users edit their own profile afterwards without it being overwritten, Both — sync on first sign-in AND every login (use only when the IdP is the authoritative source of truth and you don't want users editing their profile in Power Pages) |
+
+Store as `PROFILE_SYNC_FREQUENCY`. This determines whether to write `LoginClaimsMapping` (every login) in addition to `RegistrationClaimsMapping` (first sign-in only).
+
+> **Why "First sign-in only" is now the default**: this skill optionally scaffolds a SPA profile page (`/user-profile`) where signed-in users can edit their own contact info. If `LoginClaimsMapping` is set, the server overwrites the user's edits with IdP claims on the very next login — which is confusing and silently undoes the user's work. "First sign-in only" lets the user own their profile after the contact is created. Switch to "Both" only when the IdP is the sole authoritative source for these fields (e.g., HR-managed workforce directory) and end-user edits should NOT persist.
+
+**Claim type values** — the mapping format is comma-separated `contactfield=claimtype` (NOT JSON). For OIDC providers like Entra External ID, use OIDC short names:
+
+| Choice | Generated mapping |
+|---|---|
+| Standard | `firstname=given_name,lastname=family_name,emailaddress1=email` |
+| Standard + phone | `firstname=given_name,lastname=family_name,emailaddress1=email,mobilephone=phone_number` |
+| Custom | Loop: ask the user for each `contactfield=claimtype` pair until they say done. Suggest OIDC short names (`given_name`, `family_name`, `email`, `phone_number`, `preferred_username`, custom claim names). Validate that `contactfield` is a known Dataverse contact column. |
+| None | Don't write `RegistrationClaimsMapping` or `LoginClaimsMapping` settings. |
+
+For **SAML2 / WS-Federation**, the claim types are URIs (e.g., `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname`). Adjust the "Standard" generated mapping accordingly. For **social** providers, the claim types are provider-specific (Google: `given_name`, Facebook: `name`).
+
+**Contact linking (for every external provider)**
+
+Ask whether to auto-link external sign-ins to existing contacts by email.
+
+| Question | Header | Options |
+|----------|--------|---------|
+| If a user signs in with an external provider and their email matches an existing Dataverse contact, what should happen? | Contact linking | Link to the existing contact (Recommended) — auto-link by email match so makers don't end up with duplicate contacts when admins pre-create records (single-tenant providers only — see warning below), Create a new contact — always create a fresh contact, never auto-link (safer choice when the IdP doesn't verify emails) |
+
+Store as `CONTACT_LINKING_CHOICE`. This drives `AllowContactMappingWithEmail` (`true` for "link", `false` for "create new").
+
+> **Why "Link to the existing contact" is the default**: the common flow is that admins pre-create contact records in Dataverse (often via invitation or import) and then expect those exact contacts to be picked up when the user signs in for the first time via the configured IdP. Without linking, the server creates a brand-new contact and the pre-created record sits orphaned — confusing for makers and easy to misdiagnose. Linking by verified email is the well-known pattern for joining IdP identity to an existing CRM record.
+>
+> **⚠ Multi-tenant safety**: For **multi-tenant Entra External ID** (Authority uses `/organizations/` or `/common/`, or `IssuerFilter` is a wildcard), the Power Pages server **forcibly disables** `AllowContactMappingWithEmail` regardless of the site setting (`BlockContactMappingSettingForMultitenantApp` feature flag in `LoginController.cs:2578-2587`). Reason: email claims can't be trusted across tenants. If the user selects "Link to the existing contact" but the Authority is multi-tenant, warn them that linking won't work and recommend single-tenant Authority.
+>
+> **⚠ Security**: When `AllowContactMappingWithEmail = true`, an attacker who can sign into the configured IdP using a victim's email can take over the victim's contact. Enable only when the IdP verifies emails (Entra External ID with single tenant verifies; arbitrary OIDC may not). Switch to "Create a new contact" if you're configuring an IdP whose email-verification stance you don't control (e.g., a generic OIDC endpoint).
+
+**For "Local Authentication"** (only if user explicitly requested it): Ask the user how they want users to identify themselves when logging in:
+
+| Question | Options |
+|----------|---------|
+| How should users log in with their local account? | Login by email (Recommended) — Users sign in with their email address, Login by username — Users sign in with a chosen username |
+
+This choice determines the `Authentication/Registration/LocalLoginByEmail` site setting (`true` for email, `false` for username) and affects every form field in the login, registration, and auth service code. When **email** is chosen, the login and registration forms show an `Email` field (type `email`). When **username** is chosen, the forms show a `Username` field (type `text`) and `Email` becomes a separate required field on the registration form (the server needs it for the contact record). Store this choice — it will be used in Phase 3 (auth service), Phase 5 (sign-in and registration pages), and Phase 8.1 (site settings).
+
+**For "Local Authentication"** — also ask which registration mode the site should use:
+
+| Question | Options |
+|----------|---------|
+| How should users be able to register on your site? | Open registration only (Recommended) — Anyone can sign up freely with a username/password, Invitation-only — Only users with a valid invitation code can register; direct registration is blocked, Both — Users can self-register OR redeem an invitation link, Registration disabled — No new accounts can be created (only existing users can log in) |
+
+**Why this matters** — the server enforces the following gating rules in `RegistrationManager` (see `crm.solutions.portal/Samples/MasterPortal/Areas/Account/Models/RegistrationManager.cs`):
+
+| Mode | `Enabled` | `OpenRegistrationEnabled` | `InvitationEnabled` | Behavior |
+|---|---|---|---|---|
+| Open registration only | `true` | `true` | `false` | Direct `/registration` works. Invitation links return 404. |
+| Invitation-only | `true` | `false` | `true` | Direct `/registration` returns 404. Users must arrive via invitation link → `/redeem-invitation` → `/registration?invitationCode=...`. |
+| Both | `true` | `true` | `true` | Both paths work. Invitation pre-fills email; direct registration is fully open. |
+| Registration disabled | `false` | (moot) | (moot) | All registration endpoints return 404. Existing users can still log in. |
+
+> **Note:** The `Authentication/Registration/RequireInvitationCode` setting is NOT a real server setting — the server doesn't read it. The "require invitation" behavior is enforced solely by `OpenRegistrationEnabled = false` + `InvitationEnabled = true`. Do not create that setting.
+
+Store this choice as `REGISTRATION_MODE` — it drives:
+- Whether to create the `/registration` page (always, unless `Registration disabled`)
+- Whether to create the `/redeem-invitation` page (only when `InvitationEnabled` is true, i.e., `Invitation-only` or `Both`)
+- Whether the `/registration` page calls `fetchInvitationDetails()` to pre-fill the email (only when `InvitationEnabled` is true)
+- The deterministic set of site settings written in Phase 8.1
+- Whether to default CAPTCHA on (open / both) or off (invitation-only — invitations already filter users)
+
+**For "Microsoft Entra ID"** (workforce / employee tenant): No tenant or client info needed. Power Pages auto-configures the OIDC site settings (`Authentication/OpenIdConnect/AzureAD/*`) for the site's parent tenant when the site is created. The SPA derives the `providerIdentifier` (`https://login.windows.net/{tenantId}/`) at runtime from `window.Microsoft.Dynamic365.Portal.tenant` — no hardcoded values.
+
+**Claims mapping is also auto-configured silently** — Phase 8.1 always writes `Authentication/OpenIdConnect/AzureAD/RegistrationClaimsMapping` and `LoginClaimsMapping` with the value `firstname=given_name,lastname=family_name,emailaddress1=upn` for the workforce Entra provider. **No question is asked for this** — the answer is deterministic. Workforce Entra ID issues v1.0 tokens by default (issuer `sts.windows.net/{tid}/`) which omit the `email` claim, so `upn` is the only reliable claim to populate `emailaddress1`. Without this mapping, contacts created on first sign-in have `oid` linked but firstname/lastname/email all empty (the User object renders with `contactId` but blank profile fields).
+
+Only ask one optional question — the button display name. Provide a sensible default the user can accept:
+
+| Question | Options |
+|----------|---------|
+| What should the login button label say? (default: `Sign in with Microsoft`) | *(free text, defaulted)* |
+
+Store as `ENTRA_ID_DISPLAY_NAME` (default `"Sign in with Microsoft"`). Phase 3.2 adds an entry to `AUTH_PROVIDERS` with `type: 'entra-id'`, this display name, and **no `providerIdentifier`** (runtime-resolved).
+
+> **Why no tenant ID?** The tenant ID is essentially for SPA-button wiring (the value the SPA POSTs to `/Account/Login/ExternalLogin`). Power Pages exposes the site's parent tenant ID at runtime via `window.Microsoft.Dynamic365.Portal.tenant`, so the SPA can construct the providerIdentifier (`https://login.windows.net/{tenantId}/`) without asking the maker. The server-side OIDC settings are already in place from site creation. Compare this to **Entra External ID**, where the tenant is a SEPARATE customer tenant unrelated to the site's parent — there we DO need the maker to provide the tenant ID + subdomain because they can't be derived from `Portal.tenant`.
+
+> Docs: https://learn.microsoft.com/en-us/power-pages/security/authentication/openid-settings
+
+**Login page layout** — when more than one auth provider is configured (including local + 1 external, or 2+ providers), the Login page renders all of them. Ask the user how they want providers laid out:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| How should sign-in options be laid out on the Login page? | Layout | Horizontal row (Recommended) — provider buttons side-by-side in a wrapping row, local form below a divider, Vertical stack — provider buttons stacked full-width, local form below a divider, Primary spotlight — one provider featured as the primary CTA, others under a "More sign-in options" toggle, local form below, Tabbed — tabs to switch between provider modes (good for 3+ providers, feels heavy for 2) |
+
+Store this choice as `LOGIN_LAYOUT` — Phase 5.1.1 renders the Login page based on it. If only one provider is configured (e.g., `Entra External ID` only with no local), `LOGIN_LAYOUT` is moot: the AuthButton's "Sign In" calls `login()` directly, no Login page is needed.
+
+For the **Primary spotlight** layout, ask a follow-up:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Which provider should be featured as the primary sign-in option? | Primary provider | *(List the configured providers as options. The first external provider is a sensible default.)* |
+
+Store as `PRIMARY_PROVIDER_ID`.
+
+Then determine the scope:
+
+| Question | Options |
+|----------|---------|
+| Which authentication features do you need? | Login & Logout + Role-based access control (Recommended), Login & Logout only, Role-based access control only (auth service already exists) |
+
+Then ask about optional features:
+
+| Question | Options |
+|----------|---------|
+| Would you like to enable any of these optional features? | None (Recommended), Terms and Conditions — require users to accept terms before accessing the site |
+
+> **Note:** If they select Terms and Conditions, follow the Terms flow below.
+>
+> **Invitation-based registration is NOT in this list** — it's controlled by the registration mode question above. Setting registration mode to `Invitation-only` or `Both` is what enables invitations.
+>
+> **Two-factor authentication (2FA) is intentionally NOT offered.** Power Pages' built-in 2FA flow is server-rendered (`/Account/Login/SendCode` → `/Account/Login/VerifyCode`) and cannot be intercepted from the SPA — there's no SPA-equivalent UI for the code entry step, and bouncing the user out to a server page mid-login breaks the SPA experience. If the user explicitly asks for 2FA, tell them: "Power Pages built-in 2FA requires the legacy server-rendered SendCode/VerifyCode pages, which we don't support in SPA-based code sites yet. For external providers (Entra ID, Entra External ID, OIDC), enable MFA at the identity provider instead — it's transparent to Power Pages and stays inside the IdP's branded experience. For local accounts, 2FA on SPA sites is not currently supported." Do NOT create `TwoFactorEnabled`, `RememberMeEnabled`, or `RememberBrowserEnabled` site settings.
+
+**Profile page** — ask whether to scaffold a SPA profile page that lets signed-in users edit their own contact info via the Power Pages Web API. This is a standalone question because it has its own infrastructure implications (Web API site settings on the `contact` entity + Self-scope table permission).
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Add a profile page that lets signed-in users edit their contact info (name, mobile phone, address) via the Power Pages Web API? Email is shown read-only. | Profile page | No (default) — no profile page; users can't edit their info from the SPA, Yes — create a /user-profile SPA page with edit form, accessible from the header user menu |
+
+Store as `INCLUDE_PROFILE_PAGE` (boolean). Default `false`.
+
+> **⚠ MANDATORY route name: `/user-profile` (NOT `/profile`)**. The path `/profile` is **reserved by the Power Pages server** for the legacy server-rendered profile page — using it as a SPA route creates a conflict that breaks the page. **Always use `/user-profile`** for the SPA route. The skill executor MUST NOT rename this route. Same for the file: **`src/pages/UserProfile.tsx`** (NOT `Profile.tsx`).
+
+When `true`, Phase 5.1.9 generates `src/pages/UserProfile.tsx` (file name mandatory), extends `authService.ts` with `getMyProfile` / `updateMyProfile` (function names mandatory), evolves the `AuthButton` from inline `[Avatar Name Sign Out]` to a dropdown menu with "My Profile" and "Sign Out", and adds the `/user-profile` route (path mandatory) to `App.tsx`. Phase 8.1 writes the Web API site settings (`Webapi/contact/enabled = true` and `Webapi/contact/fields` with the COMPLETE default field list documented in Phase 8.1 — not a subset) and a Self-scope table permission on `contact` for the Authenticated Users role. The dropdown shape becomes the new default for `AuthButton` regardless of `INCLUDE_PROFILE_PAGE` so the component is ready for future menu items.
+
+**Profile page design — intentionally simple:**
+
+The page has two sections:
+
+1. **Account Details** (read-only display at the top) — shows just the user's **full name** (firstname + lastname combined) and **email**. **DO NOT** display contactId, roles, sign-in method, provider name, last-login timestamp, or any other account metadata. Keep this section minimal.
+2. **Edit form** (below) — only these editable fields. Email is intentionally **NOT** editable (changing email via Web API conflicts with auth provider claim mapping behavior and is surprising for external-auth users).
+
+**Default EDITABLE field set** (the form MUST include exactly these 8 fields — do not add email, do not add middlename, do not add a Change Password link):
+
+- First name (`firstname`)
+- Last name (`lastname`)
+- Mobile phone (`mobilephone`)
+- Address line 1 (`address1_line1`)
+- City (`address1_city`)
+- State / Province (`address1_stateorprovince`)
+- Postal code (`address1_postalcode`)
+- Country (`address1_country`)
+
+All fields are optional on submit. **DO NOT** include:
+
+- ❌ `emailaddress1` as an editable field (read-only in Account Details only)
+- ❌ `middlename` (keep the form simple)
+- ❌ A "Change password" link or button (password reset is handled by the existing `/forgot-password` flow, not the profile page)
+- ❌ A "Sign out" button on the profile page (sign-out lives in the header AuthButton dropdown only)
+- ❌ Display of contactId, userRoles, or any account metadata beyond name + email
+
+The Web API `fields` site setting MUST include `contactid` plus the 8 editable fields above (9 total entries — lowercase). Phase 8.1 specifies the exact value verbatim.
+
+> **Prerequisite for `Yes`**: an "Authenticated Users" web role must exist (or any role with `authenticatedusersrole: true` flag). Phase 1.4 inventoried web roles — if none qualifies, warn the user that profile editing won't work until a role is assigned and offer to invoke `/create-webroles` first.
+
+> **Cross-provider compatibility**: the profile page works the same regardless of auth provider (local, Entra ID, Entra External ID, OIDC, social) because it operates on the contact record after sign-in — not on IdP-specific session state. Email is read-only on the page, so there's no provider-specific caveat to surface (the IdP remains the source of truth for email).
+
+**If "Terms and Conditions" is selected**, first surface the GDPR prerequisite **before** collecting content — terms only function if the underlying solution is installed:
+
+> **GDPR prerequisite**: Terms require ALL THREE of these to be in place for the server to actually enforce them:
+> 1. `Authentication/Registration/TermsAgreementEnabled = true` (site setting we will create)
+> 2. The `msdynce_PortalPrivacyExtensions` solution must be installed in your Dataverse environment (`IsGdprEnabled` is portal-level)
+> 3. The `Account/Signin/TermsAndConditionsCopy` content snippet must have non-empty text (we will create this)
+>
+> Without the Privacy Extensions solution, the server silently ignores `TermsAgreementEnabled`. The setup-auth skill will still write all three pieces — but unless the solution is installed in Dataverse, the terms gate won't be enforced server-side.
+
+**Auto-detect the Privacy Extensions solution before asking.** Run:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/check-solution-installed.js" --solutionName "msdynce_PortalPrivacyExtensions"
+```
+
+The script prints JSON to stdout: `{ "installed": true, "version": "..." }` if found, or `{ "installed": false }` if the solution isn't in the environment. On infrastructure failure (no PAC environment, expired Azure CLI token, missing Read permission on the solutions table, network error), it exits non-zero and writes a human-readable reason to stderr.
+
+Branch on the result:
+
+| Script result | What to do |
+|---|---|
+| `installed: true` | Skip the prereq question entirely and proceed to collecting terms content (next section). Briefly tell the user: *"Confirmed `msdynce_PortalPrivacyExtensions` v{version} is installed in your environment — terms enforcement will work."* |
+| `installed: false` | **Tell the user clearly that terms and conditions will NOT work**: *"The `msdynce_PortalPrivacyExtensions` solution is NOT installed in your Dataverse environment. The Terms and Conditions feature will NOT be enforced by the server until that solution is installed — `Authentication/Registration/TermsAgreementEnabled` is silently ignored without it. The site setting, Terms page, and content snippets will still be scaffolded, but the gate is a no-op until the solution is in place."* Then ask via `AskUserQuestion`: **header** "Privacy solution", **question** "Would you still like to set up Terms and Conditions now (it can be enabled later once you install the solution), or skip it?", **options**: "Continue anyway — scaffold the Terms infrastructure; I'll install the solution later", "Cancel — skip Terms and Conditions for this site". |
+| Script exited non-zero (infrastructure failure) | Tell the user we couldn't auto-detect the solution (include the stderr message succinctly so they understand why — e.g., "couldn't reach Dataverse", "missing permissions on the solutions table"). Fall back to the manual prompt: **question** "We couldn't auto-detect whether `msdynce_PortalPrivacyExtensions` is installed. Do you have the GDPR/Privacy Extensions solution installed?", **options**: "Yes — solution is installed (or I'll install it)", "Continue anyway — set up terms; I understand they won't be enforced until I install the solution", "Cancel — I don't want terms". |
+
+**If the user picks "Cancel" (in either the not-installed or fallback path)**: skip the Terms branch entirely, do not set `TermsAgreementEnabled`, do not create the Terms page or snippets.
+
+Otherwise, collect the terms content. The server uses 4 content snippets — the skill hardcodes these values into the SPA Terms page component. Ask the user:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| What terms text should be shown to users? You can provide HTML or plain text. | Terms Content | Use default terms (Recommended) — Generic terms covering data use, account responsibility, and acceptable use, I'll provide my own terms text |
+
+If the user provides custom text, use it. Otherwise use the default terms template (see `authentication-reference.md` for the default content).
+
+Also collect optional customizations:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| Would you like to customize the terms page labels? | Labels | Use defaults (Recommended) — heading: "Terms and Conditions", checkbox: "I agree to these terms and conditions.", button: "Confirm", I'll customize the labels |
+
+Store these 4 values — they'll be hardcoded into the Terms page component in Phase 5 and created as content snippets in Phase 8.1:
+- `TERMS_HEADING` (default: "Terms and Conditions")
+- `TERMS_CONTENT` (default: generic terms HTML)
+- `TERMS_AGREEMENT_TEXT` (default: "I agree to these terms and conditions.")
+- `TERMS_BUTTON_TEXT` (default: "Confirm")
+
+Optionally ask about `TermsPublicationDate`:
+
+| Question | Header | Options |
+|----------|--------|---------|
+| When should users be re-prompted to accept terms? | Re-consent | Every login (no publication date) — users accept terms every time they sign in, Set a publication date — users re-accept only when terms are updated past this date |
+
+If "Set a publication date", collect the date. The format should be ISO: `YYYY-MM-DD` (e.g., `2026-01-01`). If "Every login", leave `TermsPublicationDate` unset.
+
+If web roles were found in Phase 1.4, also ask:
+
+| Question | Options |
+|----------|---------|
+| Which web roles should have access to protected areas of the site? | *(List discovered web role names as options)* |
+
+#### 2.1.1 Optional Advanced Settings
+
+After collecting the required provider details, ask if the user wants to configure advanced settings:
+
+| Question | Options |
+|----------|---------|
+| Would you like to configure advanced authentication settings? (logout mode, claims mapping, session timeout, scopes, etc.) | No, use defaults (Recommended), Yes, show me the options |
+
+**If "Yes, show me the options"**, present the optional settings table relevant to the selected provider. Only show settings that apply to their provider type. For each setting the user wants to configure, collect the value.
+
+##### Logout mode (external providers only — OIDC, Entra External ID, SAML2, WS-Fed, social)
+
+**Always offer this question to the user** when an external provider is being configured (it's the most common advanced setting and has visible UX consequences). For local-auth-only sites, skip this question.
+
+> **Two logout modes:**
+> - **Local logout** (server default, simpler) — Power Pages clears its session cookie and redirects the user to `returnUrl` (defaults to `/`). The user **remains signed in at the IdP**. Next time they click the external provider button, the IdP's SSO cookie is still warm and they re-sign-in silently with no credential re-entry. This is the default UX for most consumer / customer-facing sites.
+> - **Federated logout** (RP-initiated) — Power Pages additionally calls the IdP's `end_session_endpoint` with `id_token_hint` and `post_logout_redirect_uri`. The IdP signs the user out of THEIR session too, then redirects the browser back to the site. The user is fully signed out across systems. Required for: shared-device scenarios, regulated industries with hard logout requirements, sites that explicitly want users to re-enter credentials each time.
+
+| Question | Header | Options |
+|----------|--------|---------|
+| What should happen at the IdP when a user signs out? | Logout mode | Local logout only (Recommended, server default) — clear Power Pages session; user stays signed in at the IdP, Federated logout — also sign user out at the IdP so they have to re-authenticate |
+
+**If "Local logout only"**: do nothing further. Skip writing `RPInitiatedLogout` and `PostLogoutRedirectUri` site settings in Phase 8.1 — the server defaults handle it correctly (both default to `false`/unset).
+
+**If "Federated logout"**: this requires TWO pieces of configuration that MUST go together. Setting only `RPInitiatedLogout=true` without `PostLogoutRedirectUri` leaves users stranded on the IdP's "you have been signed out" page — confirmed via HAR analysis on a live Entra External ID site.
+
+Step 1 — collect the post-logout redirect URI (default to the site root):
+
+| Question | Options |
+|----------|---------|
+| Where should users land after they sign out at the IdP? (Defaults to the site home page. Use a different URL if you have a dedicated "signed out" page.) | *(free text, defaulted to `{SITE_URL}/`)* |
+
+Validate the value: must be a fully-qualified URL on the same host as `SITE_URL`. Store as `POST_LOGOUT_REDIRECT_URI`.
+
+Step 2 — for Entra External ID specifically, instruct the user to register the URL in their app registration:
+
+> **Required app registration step** (must be done in the Microsoft Entra admin center):
+>
+> 1. Go to **App registrations → {your app} → Authentication**
+> 2. Scroll to the **Front-channel logout URL** field (under "Advanced settings", just above "Implicit grant and hybrid flows")
+> 3. Enter: **`{POST_LOGOUT_REDIRECT_URI}`** — must match the value above exactly
+> 4. **Save**
+>
+> **Why this is needed**: Entra External ID rejects any `post_logout_redirect_uri` value that isn't pre-registered (same security model as Redirect URIs for sign-in). Without this registration, the IdP silently drops the parameter and the user is stranded after sign-out — even if Power Pages sends it correctly.
+>
+> For **generic OIDC providers** (Okta, Auth0, Ping, etc.), check the provider's docs for the equivalent registration. Most providers call this "Logout URL", "Post Logout Redirect URI", or "Allowed Sign-out Redirect URLs" under the app's settings.
+
+Phase 8.1 will write BOTH `RPInitiatedLogout=true` AND `PostLogoutRedirectUri={POST_LOGOUT_REDIRECT_URI}` when this option is chosen.
+
+**OpenID Connect / Entra External ID optional settings:**
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `MetadataAddress` | Explicit OIDC metadata endpoint URL (alternative to `Authority` — use when provider needs a specific metadata URL) | Derived from Authority |
+| `Scope` | Space-separated OAuth scopes (e.g., `openid profile email`) | `openid` |
+| `ResponseType` | OAuth response type (`code`, `id_token`, `code id_token`) | `code id_token` |
+| `ResponseMode` | How the IdP returns the response (`form_post`, `query`, `fragment`) | `form_post` for code flow |
+| `RedirectUri` | Override the callback URL | `{site-url}/signin-{provider}` |
+| `PostLogoutRedirectUri` | URL to redirect to after federated logout completes at the IdP. **Required when `RPInitiatedLogout=true`** — server has a fallback that derives from `RedirectUri` authority, but a separate flag (`PostLogoutRedirectUriEnabled`) requires the explicit site setting to be present before the fallback is used. Without an explicit value, the IdP logout URL omits the parameter and users get stranded. | Unset (server default — but use the Logout mode question above to write it correctly) |
+| `RPInitiatedLogout` | Use RP-initiated logout via `end_session_endpoint` with `id_token_hint`. **Mutually exclusive with `ExternalLogoutEnabled`** — when `true`, the server forces `ExternalLogoutEnabled` to `false` regardless of that setting. **Prefer the "Logout mode" question above** instead of setting this directly — that flow pairs it with `PostLogoutRedirectUri` (required) and the Entra app-registration step. | `false` |
+| `Caption` | Display name shown on the login button | Provider name |
+| `RegistrationClaimsMapping` | **Comma-separated `contactfield=claimtype` pairs** (NOT JSON). Applied **once** at first sign-in, before the contact is created. Example for Entra External ID: `firstname=given_name,lastname=family_name,emailaddress1=email`. The server silently skips malformed pairs — verify in Application Insights if claims aren't populating. | None |
+| `LoginClaimsMapping` | Same format as `RegistrationClaimsMapping`. Applied **every login** (overwrites contact fields). Use sparingly — it overwrites manual edits the user makes to their profile. | None |
+| `ExternalLogoutEnabled` | Sign out of the IdP when the user logs out (legacy OWIN sign-out, prefer `RPInitiatedLogout` for OIDC). Forced to `false` when `RPInitiatedLogout=true`. | `false` (server default) |
+| `RegistrationEnabled` | Allow new users to register via this provider | `true` |
+| `AllowContactMappingWithEmail` | **Auto-link an external sign-in to an existing Dataverse contact by matching the `email` claim against `emailaddress1`.** Default `false` (a new contact is always created). **⚠ Multi-tenant Entra External ID: the server forcibly disables this** (`BlockContactMappingSettingForMultitenantApp` feature flag in `LoginController.cs:2578-2587`) — email claims can't be trusted across tenants. If you want contact linking, use single-tenant Authority. **⚠ Security**: When `true`, anyone who can sign into this provider with a victim's email gains access to the victim's contact. Enable only when the provider is trusted to verify emails. | `false` |
+| `RequireUniqueEmail` | Enforce unique email addresses during registration | `false` |
+| `UseTokenLifetime` | Use the IdP token lifetime for the session cookie | Not set |
+| `BackchannelTimeout` | Timeout for backchannel HTTP calls to the IdP (e.g., `00:01:00`) | `00:01:00` |
+| `RefreshOnIssuerKeyNotFound` | Refresh provider metadata when issuer key not found | Default |
+| `NonceEnabled` | Enable nonce validation on OIDC tokens | `true` |
+| `NonceLifetime` | Lifetime of the OIDC nonce (e.g., `00:10:00`) | `00:10:00` |
+| `AcrValues` | Authentication Context Class Reference values to request from the IdP | None |
+| `Prompt` | OIDC prompt parameter (`login`, `consent`, `none`). Use `login` to force re-authentication on session expiry. | None |
+| `Resource` | Resource parameter for the token request | None |
+| `EmailClaimIdentifier` | Custom claim type to use as the user's email | Standard email claim |
+| `IssuerFilter` | Wildcard pattern to match issuers across tenants (e.g., `https://login.microsoftonline.com/*/v2.0`). Required for multi-tenant apps — without this, issuer validation fails for non-home tenants. | None |
+| `UseUserInfoEndpointforClaims` | Fetch additional claims from the UserInfo endpoint | `false` |
+| `UserInfoEndpoint` | Custom UserInfo endpoint URL (if not in metadata) | From metadata |
+| `PasswordResetPolicyId` | B2C/External ID password reset user flow policy name | None |
+| `ProfileEditPolicyId` | B2C/External ID profile editing user flow policy name | None |
+| `DefaultPolicyId` | B2C/External ID default sign-up/sign-in policy name | None |
+| `TokenEndPointAuthenticatedMethod` | Token endpoint auth method (`client_secret_post`, `client_secret_basic`, `private_key_jwt`). Use `private_key_jwt` for certificate-based auth in sovereign clouds. | `client_secret_post` |
+| `AllowedDynamicAuthorizationParameters` | Comma-separated OIDC parameters allowed to pass through dynamically | None |
+
+**SAML2 optional settings:**
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `AssertionConsumerServiceUrl` | ACS URL (typically `{site-url}/signin-{provider}`) | Derived from site URL |
+| `RegistrationClaimsMapping` | **Comma-separated `contactfield=claimtype` pairs**. SAML assertion types are URIs (e.g., `firstname=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname,lastname=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname`). Applied once at first sign-in. | None |
+| `LoginClaimsMapping` | Same format. Applied every login (overwrites contact fields). | None |
+| `ExternalLogoutEnabled` | Enable SAML Single Logout (SLO) | `true` |
+| `RegistrationEnabled` | Allow new users to register via this provider | `true` |
+| `AllowContactMappingWithEmail` | **Auto-link an external sign-in to an existing Dataverse contact by matching the `email` claim against `emailaddress1`.** Default `false` (a new contact is always created). **⚠ Multi-tenant Entra External ID: the server forcibly disables this** (`BlockContactMappingSettingForMultitenantApp` feature flag in `LoginController.cs:2578-2587`) — email claims can't be trusted across tenants. If you want contact linking, use single-tenant Authority. **⚠ Security**: When `true`, anyone who can sign into this provider with a victim's email gains access to the victim's contact. Enable only when the provider is trusted to verify emails. | `false` |
+| `AllowCreateNameIdPolicy` | Include AllowCreate in NameIdPolicy | `true` |
+| `DefaultSignatureAlgorithm` | Signature algorithm for SAML requests | Provider default |
+| `SigningCertificateFindType` | X509 certificate find type for signing requests | None |
+| `SigningCertificateFindValue` | Certificate find value (e.g., thumbprint) | None |
+| `ExternalLogoutCertThumbprint` | Certificate thumbprint for SLO response signing | None |
+| `SingleLogoutServiceRequestPath` | Custom path for SLO request | Default |
+| `SingleLogoutServiceResponsePath` | Custom path for SLO response | Default |
+| `Comparison` | AuthnContextComparison type (`exact`, `minimum`, `maximum`, `better`) | None |
+| `BackchannelTimeout` | Timeout for metadata retrieval | `00:01:00` |
+| `UseTokenLifetime` | Use IdP token lifetime for session | Not set |
+| `EmailClaimIdentifier` | Custom claim type for user's email | Standard email claim |
+| `IssuerFilter` | Wildcard pattern for multi-tenant issuer matching | None |
+
+**WS-Federation optional settings:**
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `Wreply` | Reply URL for the WS-Fed response | Same as Wtrealm |
+| `Whr` | Home realm discovery hint (e.g., a domain name) | None |
+| `SignOutWreply` | URL for post-logout redirect | Site root |
+| `RegistrationClaimsMapping` | **Comma-separated `contactfield=claimtype` pairs**. WS-Fed claim types are typically SAML URIs (e.g., `firstname=http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname`). Applied once at first sign-in. | None |
+| `LoginClaimsMapping` | Same format. Applied every login (overwrites contact fields). | None |
+| `ExternalLogoutEnabled` | Enable federated sign-out | `true` |
+| `RegistrationEnabled` | Allow new users to register via this provider | `true` |
+| `AllowContactMappingWithEmail` | **Auto-link an external sign-in to an existing Dataverse contact by matching the `email` claim against `emailaddress1`.** Default `false` (a new contact is always created). **⚠ Multi-tenant Entra External ID: the server forcibly disables this** (`BlockContactMappingSettingForMultitenantApp` feature flag in `LoginController.cs:2578-2587`) — email claims can't be trusted across tenants. If you want contact linking, use single-tenant Authority. **⚠ Security**: When `true`, anyone who can sign into this provider with a victim's email gains access to the victim's contact. Enable only when the provider is trusted to verify emails. | `false` |
+| `BackchannelTimeout` | Timeout for metadata retrieval | `00:01:00` |
+| `UseTokenLifetime` | Use IdP token lifetime for session | Not set |
+| `IssuerFilter` | Wildcard pattern for multi-tenant issuer matching | None |
+
+**Social OAuth optional settings** (Microsoft Account, Facebook, Google):
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `Caption` | Display name on the login button | Provider name |
+| `Scope` | OAuth scopes to request (space-separated) | Provider defaults |
+| `RegistrationClaimsMapping` | **Comma-separated `contactfield=claimtype` pairs**. Social provider claim types vary — Facebook uses `name`/`email`, Google uses `given_name`/`family_name`/`email`. Example: `firstname=given_name,emailaddress1=email`. Applied once at first sign-in. | None |
+| `LoginClaimsMapping` | Same format. Applied every login (overwrites contact fields). | None |
+| `ExternalLogoutEnabled` | Sign out of social provider on logout | `true` |
+| `RegistrationEnabled` | Allow new users to register via this provider | `true` |
+| `AllowContactMappingWithEmail` | **Auto-link an external sign-in to an existing Dataverse contact by matching the `email` claim against `emailaddress1`.** Default `false` (a new contact is always created). **⚠ Multi-tenant Entra External ID: the server forcibly disables this** (`BlockContactMappingSettingForMultitenantApp` feature flag in `LoginController.cs:2578-2587`) — email claims can't be trusted across tenants. If you want contact linking, use single-tenant Authority. **⚠ Security**: When `true`, anyone who can sign into this provider with a victim's email gains access to the victim's contact. Enable only when the provider is trusted to verify emails. | `false` |
+| `BackchannelTimeout` | Timeout for OAuth token exchange | `00:01:00` |
+
+**Local Authentication optional settings:**
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `Authentication/Registration/OpenRegistrationEnabled` | Allow self-registration | `true` |
+| `Authentication/Registration/EmailConfirmationEnabled` | Require email confirmation on registration | `false` |
+| `Authentication/Registration/RememberMeEnabled` | Show "Remember me" checkbox on login form | `false` |
+| `Authentication/Registration/ResetPasswordEnabled` | Enable forgot password flow | `true` |
+| `Authentication/Registration/ResetPasswordRequiresConfirmedEmail` | Require confirmed email before allowing password reset | `false` |
+| `Authentication/Registration/RequireUniqueEmail` | Enforce unique email addresses | `false` |
+| `Authentication/Registration/TermsAgreementEnabled` | Require terms & conditions agreement on registration. The server redirects to a Terms page before completing registration. | `false` |
+| `Authentication/Registration/IsCaptchaEnabledForRegistration` | Show CAPTCHA on registration form | `false` |
+| `Authentication/Registration/TriggerLockoutOnFailedPassword` | Lock account after too many failed login attempts | `true` |
+| `Authentication/Registration/DenyMinors` | Deny registration for users identified as minors | `false` |
+| `Authentication/Registration/DenyMinorsWithoutParentalConsent` | Deny minors without parental consent (requires GDPR to be enabled) | `false` |
+
+**Session / Cookie settings** (all providers):
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `Authentication/ApplicationCookie/ExpireTimeSpan` | Session timeout duration (e.g., `01:00:00` for 1 hour) | `01:00:00` |
+| `Authentication/ApplicationCookie/SlidingExpiration` | Renew cookie on each request | `true` |
+| `Authentication/ApplicationCookie/AbsoluteSlidingExpireTimeSpan` | Absolute maximum session lifetime regardless of activity | None |
+| `Authentication/ApplicationCookie/CookieName` | Custom session cookie name | Power Pages default |
+| `Authentication/ApplicationCookie/CookieDomain` | Cookie domain scope | Current domain |
+| `Authentication/ApplicationCookie/CookiePath` | Cookie path scope | `/` |
+| `Authentication/ApplicationCookie/CookieHttpOnly` | Prevent JavaScript access to the session cookie | `true` |
+| `Authentication/ApplicationCookie/CookieSecure` | Require HTTPS for the session cookie | `true` |
+| `Authentication/ApplicationCookie/LoginPath` | Custom login page path | `/Account/Login/Login` |
+| `Authentication/ApplicationCookie/SecurityStampValidator/ValidateInterval` | Interval to validate the user's security stamp (e.g., `00:30:00`) | Default |
+
+**Global auth toggles** (all providers):
+
+| Setting | Description | Default |
+|---------|-------------|---------|
+| `Authentication/Registration/LoginButtonAuthenticationType` | Default provider for the login button | None (shows all) |
+| `Authentication/Registration/AzureADLoginEnabled` | Enable/disable Azure AD (Entra ID) login | `true` |
+| `Authentication/Registration/ExternalLoginEnabled` | Enable/disable all external identity provider login | `true` |
+| `Authentication/Registration/SignOutEverywhereEnabled` | On logout, invalidate all sessions across all devices by updating the user's security stamp | `false` |
+
+For each setting the user wants to configure, create the site setting using `create-site-setting.js` during Phase 8.1 alongside the required settings.
+
+#### 2.2 Present Plan for Approval
+
+Present the implementation plan inline:
+
+- Which files will be created (auth service, types, authorization utils, components)
+- How the auth UI will be integrated into the site's navigation
+- Which routes/components will be protected and with which roles
+- The site setting that needs to be configured (`Authentication/Registration/ProfileRedirectEnabled = false`)
+
+Use `AskUserQuestion` to get approval:
+
+| Question | Options |
+|----------|---------|
+| Here is the implementation plan for authentication and authorization. Would you like to proceed? | Approve and proceed (Recommended), I'd like to make changes |
+
+**If "Approve and proceed"**: Continue to Phase 3.
+
+**If "I'd like to make changes"**: Ask the user what they want to change, revise the plan, and present it again for approval.
+
+### Output
+
+- Authentication scope confirmed (login/logout, role-based access, or both)
+- Target web roles selected
+- Implementation plan approved by user
+
+---
+
+## Phase 3: Create Auth Service
+
+**Goal:** Create the authentication service, type declarations, and framework-specific auth hook/composable with local development mock support.
+
+Reference: `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/references/authentication-reference.md`
+
+### Actions
+
+#### 3.1 Create Type Declarations
+
+Create `src/types/powerPages.d.ts` with type definitions for the Power Pages portal object and user:
+
+- `PowerPagesUser` interface — `userName`, `firstName`, `lastName`, `email`, `contactId`, `userRoles[]`
+- `PowerPagesPortal` interface — `User`, `version`, `type`, `id`, `geo`, `tenant`, etc.
+- Global `Window` interface extension for `Microsoft.Dynamic365.Portal`
+
+#### 3.2 Create Auth Service
+
+Create the auth service file based on the detected framework and selected identity provider(s).
+
+> **ALWAYS use the `AUTH_PROVIDERS` array pattern, even with one entry.** Never generate a single `AUTH_PROVIDER` constant. The array pattern means adding a second provider later (e.g., a second Entra External ID tenant, or local + an external provider) is just appending to the array — no restructuring needed. This avoids the bug class where a re-run silently drops previously-configured providers because the single-constant pattern can't represent more than one.
+>
+> The array MUST include:
+> - Every provider in `EXISTING_PROVIDERS` from Phase 1.5 (merged in based on the user's `MERGE_MODE` choice)
+> - Any new provider the user added via Phase 2.1
+>
+> Use a stable `id` for each provider (e.g., `entra-external-id-customer`, `entra-external-id-employee`, `local`) so React keys and switch statements remain stable across re-runs.
+
+**All frameworks**: Create `src/services/authService.ts` with these functions and types:
+
+- `AuthProviderType` — string union: `'local' | 'oidc' | 'entra-id' | 'saml2' | 'ws-federation' | 'social'`
+- `AuthProviderConfig` — interface with `id`, `type`, `displayName`, optional `providerIdentifier` (required for `'oidc'` / `'saml2'` / `'ws-federation'` / `'social'`; **OMIT for `'entra-id'`** — resolved at runtime), optional `loginByEmail` (local-only)
+- `AUTH_PROVIDERS: AuthProviderConfig[]` — the array (one entry per configured provider, in the order they should appear on the Login page)
+- `LOCAL_PROVIDER` — exported helper: `AUTH_PROVIDERS.find(p => p.type === 'local')` (`undefined` if no local)
+- `EXTERNAL_PROVIDERS` — exported helper: `AUTH_PROVIDERS.filter(p => p.type !== 'local')`
+- `getCurrentUser()` — reads from `window.Microsoft.Dynamic365.Portal.User`
+- `isAuthenticated()` — checks if user exists and has `userName`
+- `getTenantId()` — reads `window.Microsoft.Dynamic365.Portal.tenant` (the site's parent tenant GUID). Returns `undefined` if not yet populated.
+- `getAuthProvider()` — DEPRECATED. For backward compat, returns the first local provider or the first provider overall. Prefer reading `AUTH_PROVIDERS` directly.
+- `fetchAntiForgeryToken()` — fetches from `/_layout/tokenhtml` and parses HTML response
+- `resolveProviderIdentifier(provider)` — returns the value to POST as `provider` to `/Account/Login/ExternalLogin`. For `type='entra-id'`, derives `https://login.windows.net/${getTenantId()}/` at runtime. For other external types, returns `provider.providerIdentifier`. **Never hardcode tenant ID into the AUTH_PROVIDERS array for Entra ID** — this resolver handles it.
+- `loginExternal(providerIdentifier, returnUrl?, invitationCode?)` — Form POST to `/Account/Login/ExternalLogin` for external providers
+- `loginLocal(credential, password, rememberMe?, returnUrl?, invitationCode?)` — fetch POST to `/SignIn` for local
+- `loginWithProvider(provider, { returnUrl?, invitationCode?, credentials? })` — **router**: dispatches to `loginLocal()` or `loginExternal()` based on `provider.type`. Uses `resolveProviderIdentifier()` so Entra ID's runtime resolution works transparently. This is what UI components should call.
+- `logout(returnUrl?)` — redirects to `/Account/Login/LogOff`
+- `getAuthError()` — parses `?message=` or `?error=` query params from server-side auth error redirects and returns a user-friendly error message
+- `getSessionExpiredMessage()` — checks for `?sessionExpired=true` and returns a session-expired message
+- `parseServerErrors(html)` — **Required for local auth.** Parses validation errors from server HTML responses (`.validation-summary-errors li`, `.alert-danger li`, `.field-validation-error`). Used by login and register to show server errors in the SPA.
+- `register(fields, returnUrl?, invitationCode?)` — **Required when local auth is configured.** POSTs registration form to `/Account/Login/Register` with anti-forgery token, email or username (based on `LocalLoginByEmail` choice from Phase 2.1), password, confirmPassword, and optional invitationCode. When `LocalLoginByEmail` is `true`, sends `Email` field. When `false`, sends `Username` field. See `authentication-reference.md` for the full implementation.
+- `forgotPassword(email)` — **Required when local auth is configured.** MVC form POST to `/Account/Login/ForgotPassword` with `Email` + anti-forgery token. Server sends a password reset email. Uses `fetch()` like login. Returns a promise — on success (`.then()`), show a "check your email" confirmation. On failure (`.catch()`), show the error.
+- `resetPassword(userId, code, password, confirmPassword)` — **Required when local auth is configured.** MVC form POST to `/Account/Login/ResetPassword` with `UserId`, `Code`, `Password`, `ConfirmPassword`, `__RequestVerificationToken`. The `UserId` and `Code` come from the URL query params (set by the email reset link). On success, redirects to `/login?message=password_reset_success`.
+- `TermsRequiredError` — **Required when terms are enabled.** Custom error class thrown when the server redirects to the terms page after login or registration. The login/registration page catches this and navigates to the SPA `/terms` page.
+- `acceptTerms(returnUrl?)` — **Required when terms are enabled.** Fetches the server terms page (GET `/Account/Login/TermsAndConditions`) to get the anti-forgery token, then POSTs acceptance (`IsTermsAndConditionsAccepted=true`, `IsFacebook=False`, `UseExternalSignInAsync=False`, `IsInternalAADUser=False`). Uses the response URL dynamically (server may serve terms from `/Account/Login/TermsAndConditions` or `/TermsAndConditions`).
+- `getUserDisplayName()` — prefers full name, falls back to userName
+- `getUserInitials()` — for avatar display
+
+**Terms detection in login and registration:** Both `loginLocal()` and `register()` must check `response.url.includes('TermsAndConditions')` after the fetch completes. The server redirects to different URLs depending on the flow:
+- **Login**: redirects to `/Account/Login/TermsAndConditions`
+- **Registration**: redirects to `/TermsAndConditions?ReturnUrl=%2F`
+
+Both are caught by `response.url.includes('TermsAndConditions')`. When detected, throw `TermsRequiredError`. The server also sets a `DeferredLocalLoginCookie` — it defers the session creation until terms are accepted.
+
+> **CRITICAL — Use `fetch()` not `form.submit()` for local login and registration.** Using `form.submit()` causes a full-page navigation — if the server returns an error, the user leaves the SPA and sees the server-rendered error page. Using `fetch()` instead keeps the user in the SPA: on success (redirect), navigate via `window.location.href`; on failure (200 with HTML), parse errors with `parseServerErrors()` and throw them so the page component can display them inline. See `authentication-reference.md` for the full implementation.
+
+**Login flow varies by provider type:**
+
+- **Microsoft Entra ID**: Form POST to `/Account/Login/ExternalLogin` with provider `https://login.windows.net/{tenantId}/`
+- **Entra External ID**: Form POST to `/Account/Login/ExternalLogin` with provider set to the External ID `AuthenticationType` (configured via site settings `Authentication/OpenIdConnect/{provider}/AuthenticationType`). Uses OpenID Connect underneath with the External ID tenant authority URL.
+- **OpenID Connect (Generic)**: Form POST to `/Account/Login/ExternalLogin` with provider set to the OIDC `AuthenticationType` (configured via site settings `Authentication/OpenIdConnect/{provider}/AuthenticationType`)
+- **SAML2**: Form POST to `/Account/Login/ExternalLogin` with provider set to the SAML2 `AuthenticationType` (configured via site settings `Authentication/SAML2/{provider}/AuthenticationType`)
+- **WS-Federation**: Form POST to `/Account/Login/ExternalLogin` with provider set to the WS-Federation `AuthenticationType` (configured via site settings `Authentication/WsFederation/{provider}/AuthenticationType`)
+- **Local Authentication**: Form POST to `/SignIn` with `PasswordValue` (not `Password`), anti-forgery token from `/_layout/tokenhtml`, and optionally `RememberMe`. When `LocalLoginByEmail` is `true`, send the `Email` field; otherwise send the `Username` field. Note: the login endpoint uses `/SignIn` and `PasswordValue` — these differ from the registration endpoint which uses `/Account/Login/Register` and `Password`. Does NOT use the ExternalLogin endpoint.
+- **Microsoft Account**: Form POST to `/Account/Login/ExternalLogin` with provider `urn:microsoft:account`
+- **Facebook**: Form POST to `/Account/Login/ExternalLogin` with provider `Facebook`
+- **Google**: Form POST to `/Account/Login/ExternalLogin` with provider `Google`
+
+**CRITICAL**: Power Pages authentication is **server-side** (session cookies). External login flows post a form to the server which redirects to the identity provider. Local login posts credentials directly to the server. There is no client-side token management. The `fetchAntiForgeryToken()` call gets a CSRF token for the form POST, not a bearer token.
+
+**SECRET MANAGEMENT**: Never include `ClientSecret`, `AppSecret`, or any credential values in the auth service code or any file committed to source control. The `providerIdentifier` field is a public identifier (URL or name), not a secret. Actual secrets must be configured through the Power Pages admin center.
+
+**SERVER-RENDERED PAGE HANDLING**: For external login flows, the Power Pages server may redirect to server-rendered pages during certain flows (e.g., first-time registration via `ExternalLoginConfirmation`, 2FA via `SendCode`/`VerifyCode`, terms acceptance via `TermsAndConditions`). These are server-side decisions that the SPA cannot intercept. To minimize these redirects:
+
+- Ensure `Authentication/Registration/OpenRegistrationEnabled` is configured correctly — when `true`, new external users are auto-registered without the `ExternalLoginConfirmation` page
+- Ensure `TermsAgreementEnabled` is `false` unless explicitly needed — otherwise every first login shows a server-rendered terms page
+- For 2FA flows, the server renders `SendCode` and `VerifyCode` pages — these cannot be replaced by SPA code
+- When the user returns from a server-rendered page, the SPA should check for auth state changes (`getCurrentUser()`) and update the UI accordingly
+- The auth service's `useAuth` hook should call `refresh()` on mount to pick up session changes that happened outside the SPA
+
+For **local auth**, all error handling is client-side — the `login()` and `register()` functions use `fetch()` (not `form.submit()`) so the user stays in the SPA. Server errors are parsed from HTML responses via `parseServerErrors()` and thrown for the UI to display inline.
+
+#### 3.3 Create Framework-Specific Auth Hook/Composable
+
+Based on the detected framework:
+
+- **React**: Create `src/hooks/useAuth.ts` — custom hook returning `{ user, isAuthenticated, isLoading, displayName, initials, login, logout, refresh }`
+- **Vue**: Create `src/composables/useAuth.ts` — composable using `ref`, `computed`, `onMounted` returning reactive auth state
+- **Angular**: Create `src/app/services/auth.service.ts` — injectable service with `BehaviorSubject` for user state
+- **Astro**: Create `src/services/authService.ts` only (no framework-specific wrapper needed — use the service directly in components)
+
+#### 3.4 Add Mock Data for Local Development
+
+Auth only works when served from Power Pages (not during local `npm run dev`). Add a development mock pattern in the auth service:
+
+```typescript
+// In development (localhost), return mock user data for testing
+const isDevelopment = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
+```
+
+The mock should return a fake user with configurable roles so developers can test role-based UI locally.
+
+#### 3.5 Create Session KeepAlive Hook
+
+> **SPA session expiry problem:** In SPAs, page navigation is client-side — no server requests are made. The session cookie's `SlidingExpiration` only renews when the browser sends a request to the server. Without a keepalive, the session silently expires even while the user is actively using the SPA. The default `ExpireTimeSpan` is 24 hours with renewal at the halfway point (12 hours), but this can be configured shorter.
+
+> **Provider-agnostic — works for local AND external auth.** Power Pages issues the same `ApplicationCookie` session cookie regardless of how the user signed in (local password, Entra External ID, generic OIDC, SAML2, social). The keepalive operates on that cookie, so the same hook covers every provider. `isAuthenticated()` reads from `window.Microsoft.Dynamic365.Portal.User` which is populated for any authenticated user. No provider-specific branches are needed.
+
+> **External providers — two independent clocks.** For external auth, the Power Pages session cookie and the IdP token (e.g., Entra External ID's ID token / refresh token) have separate lifetimes. The Power Pages session is what the SPA needs to keep alive; the IdP token is invisible to the SPA. When the Power Pages session does expire and the user is redirected to `/login?sessionExpired=true`, clicking the external provider button kicks off the IdP round-trip — but if the IdP's SSO cookie is still valid (typical), the round-trip is silent (no credential re-entry). The user lands back in the site signed in. This is the expected UX and requires no extra handling.
+
+Create a session keepalive hook that periodically pings `/_layout/tokenhtml` to renew the session cookie:
+
+- **React**: Create `src/hooks/useSessionKeepAlive.ts`
+- **Vue**: Create `src/composables/useSessionKeepAlive.ts`
+- **Angular**: Create `src/app/services/session-keepalive.service.ts`
+
+The hook must:
+
+- Define a `SESSION_EXPIRE_MS` constant based on the session timeout:
+ - If the user configured a custom `ApplicationCookie/ExpireTimeSpan` in Phase 2.1.1, convert that timespan to milliseconds
+ - If using defaults, use `24 * 60 * 60 * 1000` (24 hours)
+- Derive timing from the session timeout — do NOT hardcode intervals:
+ - `intervalMs` = `min(SESSION_EXPIRE_MS / 3, 15 * 60 * 1000)` — ping at 1/3 of the session timeout, capped at 15min. This ensures the ping happens well before the SlidingExpiration halfway renewal point.
+ - `idleTimeoutMs` = `min(SESSION_EXPIRE_MS * 0.9, 30 * 60 * 1000)` — stop pinging when idle for 90% of the session timeout, capped at 30min.
+ - Example: 10min session → intervalMs=3.3min, idleTimeoutMs=9min. 24h session → intervalMs=15min, idleTimeoutMs=30min.
+- Ping `/_layout/tokenhtml` via `fetchAntiForgeryToken()` at the calculated interval
+- Only ping when the user is authenticated (`isAuthenticated()`)
+- Only ping when the browser tab is visible (`document.visibilityState !== 'hidden'`)
+- Track user activity (mouse, keyboard, touch, scroll) and stop pinging after `idleTimeoutMs` of idle — let the session expire naturally for security
+- Detect session expiry: if the ping fails, call `onSessionExpired` callback so the app can redirect to login with `?sessionExpired=true`
+- Skip entirely in development mode (no real session to keep alive)
+
+Integrate the hook into the Layout component so it runs on every page. Pass an `onSessionExpired` callback that navigates to `/login?sessionExpired=true`. The login page already handles `?sessionExpired=true` via `getSessionExpiredMessage()`.
+
+### Output
+
+- `src/types/powerPages.d.ts` created with Power Pages type definitions
+- `src/services/authService.ts` created with login/logout functions
+- Framework-specific auth hook/composable created
+- Session keepalive hook created and integrated into Layout
+- Local development mock data included
+
+---
+
+## Phase 4: Create Authorization Utils
+
+**Goal:** Create role-checking utilities and framework-specific authorization components (guards, directives, wrapper components).
+
+Reference: `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/references/authorization-reference.md`
+
+### Actions
+
+#### 4.1 Create Core Authorization Utilities
+
+Create `src/utils/authorization.ts` with:
+
+- `getUserRoles()` — returns array of role names from current user
+- `hasRole(roleName)` — case-insensitive single role check
+- `hasAnyRole(roleNames)` — OR check across multiple roles
+- `hasAllRoles(roleNames)` — AND check across multiple roles
+- `isAuthenticated()` — re-exports from auth service
+- `isAdmin()` — checks for "Administrators" role
+- `hasElevatedAccess(additionalRoles)` — checks admin or specified roles
+
+#### 4.2 Create Framework-Specific Authorization Components
+
+Based on the detected framework:
+
+**React:**
+
+- `src/components/RequireAuth.tsx` — renders children only for authenticated users, optional login prompt fallback
+- `src/components/RequireRole.tsx` — renders children only for users with specified roles, supports `requireAll` mode
+- `src/hooks/useAuthorization.ts` — hook returning `{ roles, hasRole, hasAnyRole, hasAllRoles, isAuthenticated, isAdmin }`
+
+**Vue:**
+
+- `src/composables/useAuthorization.ts` — composable with computed roles and role-checking functions
+- `src/directives/vRole.ts` — `v-role` directive for declarative role-based visibility
+
+**Angular:**
+
+- `src/app/guards/auth.guard.ts` — `CanActivateFn` with route data for required roles
+- `src/app/directives/has-role.directive.ts` — structural directive `*appHasRole="'RoleName'"`
+
+**Astro:**
+
+- `src/utils/authorization.ts` only (use directly in component scripts)
+
+#### 4.3 Security Reminder
+
+Add a comment at the top of the authorization utilities:
+
+```typescript
+// IMPORTANT: Client-side authorization is for UX only, not security.
+// Server-side table permissions enforce actual access control.
+// Always configure table permissions via /integrate-webapi.
+```
+
+### Output
+
+- `src/utils/authorization.ts` created with role-checking functions
+- Framework-specific authorization components created (guards, directives, or wrapper components)
+- Security reminder comments included
+
+---
+
+## Phase 5: Create Auth UI
+
+**Goal:** Create the login/logout button component and integrate it into the site's navigation.
+
+### Actions
+
+#### 5.1 Create Auth Button Component
+
+Based on the detected framework, create a login/logout button component:
+
+- **React**: `src/components/AuthButton.tsx` + `src/components/AuthButton.css`
+- **Vue**: `src/components/AuthButton.vue`
+- **Angular**: `src/app/components/auth-button/auth-button.component.ts` + template + styles
+- **Astro**: `src/components/AuthButton.astro`
+
+The component should:
+
+- Show a "Sign In" button when the user is not authenticated
+- Show the user's display name, avatar (initials-based), and a "Sign Out" button when authenticated
+- Include a loading state while checking auth status
+- Be styled to match the site's existing design (read existing CSS variables/theme)
+
+#### 5.1.1 Create Sign-In Page
+
+> **Route naming — avoid server conflicts:** Power Pages reserves `/SignIn`, `/Register`, and all `/Account/Login/*` paths for server-rendered auth pages. SPA routes MUST NOT collide with these. Use `/login` for the sign-in page and `/registration` for the registration page.
+
+**Always create the `/login` page when `AUTH_PROVIDERS.length > 1`.** When only one provider is configured (single external OR single local), the AuthButton's "Sign In" can call `login()` directly and no Login page is strictly needed — but creating one is still recommended since it gives a stable place to surface auth errors, the password reset link, the invitation banner, etc.
+
+The Login page must:
+
+- Import `AUTH_PROVIDERS`, `LOCAL_PROVIDER`, `EXTERNAL_PROVIDERS`, and `loginWithProvider` from authService
+- Render every external provider as a button (loop `EXTERNAL_PROVIDERS`) — each button calls `loginWithProvider(provider, { returnUrl, invitationCode })`
+- Render the local email/password form when `LOCAL_PROVIDER` exists. On submit, call `loginWithProvider(LOCAL_PROVIDER, { returnUrl, invitationCode, credentials: { credential, password, rememberMe } })`
+- Use the credential field based on `LOCAL_PROVIDER.loginByEmail` — `Email` (type `email`) when `true`, `Username` (type `text`) when `false`
+- Disable all buttons while any submission is in flight (an `isSubmitting` flag for local + `externalSubmittingId` for external)
+- Catch `TermsRequiredError` from `loginWithProvider` and navigate to `/terms`
+- Show the invitation banner when `invitationCode` is in the URL: "Sign in to redeem invitation {code}. The invitation will be linked to your account after you sign in."
+- Show server-side auth errors parsed from `?message=` query params (via `getAuthError()`) and session-expired messages from `?sessionExpired=true` (via `getSessionExpiredMessage()`)
+- Include a "Forgot password?" link to `/forgot-password` (SPA route) when `LOCAL_PROVIDER` exists and `ResetPasswordEnabled` is true
+- Include a "Create an account" link to `/registration` when `REGISTRATION_MODE` is `Open registration only` or `Both` (omit for `Invitation-only` and `Registration disabled`)
+
+**Render layout based on `LOGIN_LAYOUT` from Phase 2.1:**
+
+| `LOGIN_LAYOUT` | Layout structure |
+|---|---|
+| `horizontal-row` (default) | External providers in a `flex-wrap` row at top, "OR SIGN IN WITH EMAIL" divider, local form below. Each external button has `flex: 1 1 0; min-width: 0` and ellipsis-truncates long labels. |
+| `vertical-stack` | External providers stacked full-width vertically, "OR SIGN IN WITH EMAIL" divider, local form below. Each external button is full card width. |
+| `primary-spotlight` | The provider matching `PRIMARY_PROVIDER_ID` rendered as a large primary CTA. Other external providers tucked under a `<details>` disclosure labeled "More sign-in options" or "Other ways to sign in". Then divider + local form. |
+| `tabbed` | A tab bar with one tab per provider (`displayName`). The selected tab's UI renders below. For external providers, the tab content is just the "Sign in with X" button; for local, it's the email/password form. |
+
+See `authentication-reference.md` for full code examples of each layout pattern in React.
+
+When the `/login` page exists, the AuthButton's "Sign In" must navigate to `/login` (use `<Link to="/login">`) instead of calling any login function directly.
+
+#### 5.1.2 Create Registration Page
+
+**Always create the `/registration` page when `REGISTRATION_MODE` is not `Registration disabled`** — regardless of whether the mode is `Open registration only`, `Invitation-only`, or `Both`, and regardless of whether local or external providers (or both) are configured. The page mirrors the Login page layout when both local and external providers exist: external provider buttons in a horizontal row at the top, an "or sign up with email" divider, and the local registration form below (when local auth is configured). In invitation-only mode the page is reached via the `/redeem-invitation` flow (Phase 5.1.7) or via the server-bouncing flow (Code-Site-Shell-Header catches `/account/login/register`), not direct navigation — but the SPA route must still exist so React Router can render it.
+
+> **Important architectural note:** The server-side registration page (`/Account/Login/Register`) is an ASP.NET Web Forms page, NOT an MVC action. The local `register()` function in authService handles this by first fetching the server page (GET), parsing the ViewState and control names, then POSTing with the correct payload. This only applies when the user submits the local registration form — external provider buttons skip this entirely and go through `loginExternal()`.
+
+**External provider buttons (when `EXTERNAL_PROVIDERS.length > 0`):**
+
+Render external provider sign-up buttons in a horizontal row at the top of the page — same layout pattern as the Login page (Phase 5.1.1). Each button calls `loginExternal(providerIdentifier, returnUrl, invitationCode)` from authService — when the user clicks "Sign up with Entra External ID" the SPA initiates external auth with the invitation code (if present) in the URL. The server's `ExternalLoginCallback` then either auto-links via `AllowContactMappingWithEmail`, or surfaces the SPA-ified ExternalLoginConfirmation page (Phase 5.1.8), or redeems the invitation if one was provided. **This is the same code path as the Login page external buttons** — `loginExternal()` doesn't care whether the user came from `/login` or `/registration`; the server creates the contact on first sign-in if one doesn't exist.
+
+If `EXTERNAL_PROVIDERS.length > 0` AND `LOCAL_PROVIDER` exists, show the divider ("or sign up with email") between the external buttons and the local form. If only external providers (no local), show ONLY the external buttons with no divider and no local form — the page becomes effectively "pick a provider to sign up with".
+
+**Local form (when `LOCAL_PROVIDER` exists):**
+
+The local registration form must:
+
+- Call the `register()` function from authService, which handles the Web Forms ViewState pattern (fetch server page → parse → POST with correct control names)
+- Show the correct credential field based on the `LocalLoginByEmail` choice from Phase 2.1:
+ - **Email mode** (`LocalLoginByEmail = true`): Show an `Email` field (type `email`). This is both the login identifier and email address.
+ - **Username mode** (`LocalLoginByEmail = false`): Show a `Username` field (type `text`) AND a separate `Email` field (type `email`). Both are required — Username is the login identifier, Email is needed for the contact record.
+- Include `Password` and `Confirm Password` fields (both type `password`)
+- Validate that passwords match client-side before submitting
+- Display server-side registration errors parsed from `?message=` query params (via `getAuthError()`)
+- Parse and pass through `invitationCode` from the URL query string (for invitation-based registration flows where the user arrives via `?invitationCode=...`)
+- Include an "Already have an account? Sign in" link back to `/login`
+- **Skip the auth redirect in development mode** — in dev mode the mock user is always "authenticated", which would block testing the registration form. Add: `const isDev = window.location.hostname === 'localhost'` and only redirect if `isAuthenticated && !isDev`.
+- Be styled to match the site's existing sign-in page design (centered card layout)
+
+**Layout** — matches the Login page (Phase 5.1.1). When the user picks `LOGIN_LAYOUT` in Phase 2.1, that layout choice (horizontal row / vertical stack / primary spotlight / tabbed) applies to both `/login` AND `/registration` so users get a consistent experience across the two pages.
+
+**Pre-fill email from invitation (when `InvitationEnabled` is true — i.e., Invitation-only or Both modes):**
+
+When the user arrives at `/registration?invitationCode=X`, the email field should pre-fill with the invited contact's email (matching the server-rendered page's behavior). Implement by calling `fetchInvitationDetails(invitationCode)` on mount:
+
+```typescript
+useEffect(() => {
+ if (!invitationCode) return
+ fetchInvitationDetails(invitationCode).then(details => {
+ if (details.email) setEmail(details.email)
+ }).catch(() => { /* silent — user can enter email manually */ })
+}, [invitationCode])
+```
+
+The `fetchInvitationDetails()` function (in `authService.ts`) GETs `/Account/Login/Register?invitationCode={code}` and parses the email from the rendered HTML's `#EmailTextBox` input value attribute. See `authentication-reference.md` for the implementation.
+
+The email input must be **controlled** (`value={email}`) and editable — the user can change it if needed (this matches server behavior).
+
+**Framework-specific implementation:**
+
+- **React**: Create `src/pages/Registration.tsx` and add `<Route path="/registration" element={<Registration />} />` to the router. See the `RegisterForm` component in `authentication-reference.md` for the implementation pattern — adapt it to match the site's existing styling patterns (inline styles, CSS variables, etc.)
+- **Vue**: Create `src/pages/Registration.vue` and add the route to `src/router/index.ts`
+- **Angular**: Create `src/app/pages/registration/registration.component.ts` and add the route to the router config
+- **Astro**: Create `src/pages/registration.astro`
+
+**If `REGISTRATION_MODE` is `Registration disabled`**, skip creating the `/registration` page entirely — there's no flow that should land users there.
+
+#### 5.1.3 Create Forgot Password Page (Local Auth Only)
+
+**If local authentication is configured AND `ResetPasswordEnabled` is `true`**, create a `/forgot-password` page. This is a simple form that collects the user's email and POSTs to the server, which sends a password reset link via email.
+
+> **Note:** The forgot password endpoint (`/Account/Login/ForgotPassword`) is an MVC form (like login), NOT a Web Forms page (like registration). A simple `fetch()` POST with `Email` + `__RequestVerificationToken` works. The `forgotPassword()` function in authService handles this.
+
+The forgot password page must:
+
+- Show an email input field
+- Call `forgotPassword(email)` from authService on submit
+- **Handle both success and error**: Use `.then()` for success (show "Check your email" confirmation with green checkmark, hide the form) and `.catch()` for errors (show error inline, reset button). Do NOT only handle `.catch()` — the button will get stuck in "Sending..." state if `.then()` is not handled.
+- Track `emailSent` state — when true, replace the form with a success message: "We've sent a password reset link to your email address. Please check your inbox and follow the instructions." with a "Back to sign in" link
+- Display server errors inline (the `forgotPassword()` function uses fetch and throws parsed errors)
+- Include a "Back to sign in" link to `/login`
+- Use the same validate-on-blur pattern as login and registration (validate email format on blur, clear on change)
+
+The login page's "Forgot password?" link should point to `/forgot-password` (SPA route), NOT `/Account/Login/ForgotPassword` (server URL).
+
+After the server processes the request, it sends a reset email. The reset link in the email points to the server's `/Account/Login/ResetPassword?UserId=...&Code=...` — but this gets intercepted by the Header template redirect script (see Phase 5.1.6) and redirected to the SPA `/reset-password` page.
+
+#### 5.1.4 Validation Pattern for All Auth Pages (Local Auth Only)
+
+All local auth pages (login, registration, forgot password) must implement **validate-on-blur, clear-on-change** for real-time field validation. This is the modern UX pattern — errors appear when the user leaves a field and disappear as they correct it.
+
+**Implementation pattern:**
+
+1. Track `touched` state per field (which fields the user has interacted with)
+2. **On blur** (`onBlur`): mark field as touched, run validation, show error immediately
+3. **On change** (`onChange`): if the field was already touched, re-validate and clear the error as soon as the value becomes valid. Also clear server errors on any change.
+4. **On submit**: mark ALL fields as touched, validate everything, show all errors at once
+5. `showError(field)` helper: only return the error if the field has been touched
+
+**Validation rules:**
+
+| Page | Field | Validation |
+|------|-------|-----------|
+| Login | Email | Required + valid email format |
+| Login | Password | Required |
+| Registration | Email | Required + valid email format |
+| Registration | Password | Required + min 8 chars + characters from at least 3 of 4 categories (lowercase, uppercase, digit, special character) |
+| Registration | Confirm Password | Required + must match Password |
+| Forgot Password | Email | Required + valid email format |
+
+The password strength validation matches the default Power Pages password policy (`EnforcePasswordPolicy`). If the site creator customizes the password policy via `Authentication/UserManager/PasswordValidator/*` site settings, the client-side validation should match.
+
+#### 5.1.5 Create Terms and Conditions Page (When Terms Enabled)
+
+**If the user enabled Terms and Conditions in Phase 2**, create a `/terms` SPA page. **This page works for ALL auth flows** — local sign-in, local registration, AND external providers (Entra External ID, OIDC, social) — via two complementary mechanisms:
+
+1. **Local auth flows** (`loginLocal`, `register`): use `fetch()` so the SPA stays in-page. The auth service detects the server's `TermsAndConditions` redirect from `response.url` and throws `TermsRequiredError`. The login/registration page catches it and navigates to `/terms`.
+2. **External auth flows** (`loginExternal`, `loginWithProvider` external branch): use `form.submit()` so the browser leaves the SPA during the IdP round-trip. After IdP callback, the server may redirect to `/Account/Login/TermsAndConditions?ReturnUrl=/&UseExternalSignInAsync=True&IsFacebook=False&IsInternalAADUser=False`. The Code-Site-Shell-Header script (Phase 5.1.6) catches this URL and redirects to the SPA `/terms` route, preserving the query string so `acceptTerms()` knows which sign-in completion path the server expects.
+
+The terms page must:
+
+- Hardcode the 4 snippet values collected in Phase 2 as constants at the top of the component:
+ ```typescript
+ const TERMS_HEADING = '<value from Phase 2 or default>'
+ const TERMS_CONTENT = '<HTML content from Phase 2 or default>'
+ const TERMS_AGREEMENT_TEXT = '<value from Phase 2 or default>'
+ const TERMS_BUTTON_TEXT = '<value from Phase 2 or default>'
+ ```
+- Display the heading, terms content (rendered as HTML via `dangerouslySetInnerHTML`), checkbox with agreement text, and confirm button
+- The confirm button calls `acceptTerms('/')` from authService — this reads the query string from `window.location.search`, fetches the server terms page (with the same query string preserved) to get the anti-forgery token, then POSTs the acceptance back to the same URL with the flags from the query string in the body
+- The confirm button is disabled until the checkbox is checked
+- Display server errors inline if `acceptTerms()` throws
+- Include a "Back to sign in" link to `/login`
+
+**Login and Registration pages must catch `TermsRequiredError` (local auth path):**
+- In the Login page's `loginLocal()` catch block: if `err instanceof TermsRequiredError`, navigate to `/terms`
+- In the Registration page's `register()` catch block: if `err instanceof TermsRequiredError`, navigate to `/terms`
+
+**No SPA code changes needed in `loginExternal` for the external auth path** — the header-template redirect (Phase 5.1.6) handles it transparently. The external user lands at `/terms?ReturnUrl=/&UseExternalSignInAsync=True&...` after the IdP round-trip; the SPA renders the Terms page; `acceptTerms()` uses the query string to POST back with the correct `UseExternalSignInAsync` / `IsFacebook` / `IsInternalAADUser` flags.
+
+**How the server triggers terms (for reference):**
+- **Local login flow**: Server redirects to `/Account/Login/TermsAndConditions` after auth — caught via `response.url.includes('TermsAndConditions')` in `loginLocal()`
+- **Local registration flow**: Server redirects to `/TermsAndConditions?ReturnUrl=%2F` after registration — caught via `response.url.includes('TermsAndConditions')` in `register()`
+- **External login flow**: Server redirects from `/Account/Login/ExternalLoginCallback` to `/Account/Login/TermsAndConditions?ReturnUrl=/&UseExternalSignInAsync=True&IsFacebook=False&IsInternalAADUser=False` — caught via header-template redirect
+
+**`acceptTerms()` must be query-string-aware** (required when external providers are configured alongside terms):
+
+```typescript
+export async function acceptTerms(returnUrl?: string): Promise<void> {
+ // Parse the flags from window.location.search — set by the server's redirect URL.
+ // For local-auth users (no query string), defaults apply.
+ const params = new URLSearchParams(window.location.search);
+ const useExternalSignInAsync = params.get('UseExternalSignInAsync') || 'False';
+ const isFacebook = params.get('IsFacebook') || 'False';
+ const isInternalAADUser = params.get('IsInternalAADUser') || 'False';
+
+ // Fetch the server terms page WITH the original query string preserved
+ const serverTermsUrl = `/Account/Login/TermsAndConditions${window.location.search}`;
+ const pageResponse = await fetch(serverTermsUrl, { credentials: 'same-origin', redirect: 'follow' });
+
+ // ... extract anti-forgery token from rendered HTML ...
+
+ // POST back to the same URL with body flags matching the query-string flags.
+ // DO NOT hardcode UseExternalSignInAsync=False — external users need True.
+ const body = new URLSearchParams();
+ body.set('__RequestVerificationToken', antiForgeryToken);
+ body.set('IsTermsAndConditionsAccepted', 'true');
+ body.set('UseExternalSignInAsync', useExternalSignInAsync);
+ body.set('IsFacebook', isFacebook);
+ body.set('IsInternalAADUser', isInternalAADUser);
+ body.set('InvitationCode', '');
+ // ... POST and handle response ...
+}
+```
+
+See `authentication-reference.md` for the full implementation.
+
+**Framework-specific implementation:**
+- **React**: Create `src/pages/Terms.tsx` and add `<Route path="/terms" element={<Terms />} />` to the router
+
+> **Content updates**: When the site creator wants to change the terms text, they update the constants in the Terms page component and redeploy. The content snippets in Dataverse (`Account/Signin/TermsAndConditionsCopy` etc.) must also be updated to match — the server-rendered terms page reads from snippets, and the SPA reads from the hardcoded constants. Both must stay in sync.
+
+#### 5.1.6 Create Reset Password Page + Header Template Redirect (Local Auth Only)
+
+**If local authentication is configured AND `ResetPasswordEnabled` is `true`**, create a full SPA reset password experience. This involves two pieces:
+
+**1. Code-Site-Shell-Header Template**
+
+The password reset email sends the user to `/Account/Login/ResetPassword?UserId=...&Code=...` — a server-rendered page. To keep the user in the SPA, we need a client-side redirect script that runs on server-rendered pages.
+
+> **Why a new template?** The `pac pages upload-code-site` command intentionally replaces the original "Header" and "Footer" web template content with `<div/>` on every upload. Any script added to the Header template gets wiped. The workaround is to create a **separate** web template (`Code-Site-Shell-Header`) and point the website record to it instead.
+
+Create a new web template in `.powerpages-site/web-templates/code-site-shell-header/`:
+
+**`Code-Site-Shell-Header.webtemplate.yml`:**
+```yaml
+id: <generate-a-new-uuid>
+name: Code-Site-Shell-Header
+```
+
+**`Code-Site-Shell-Header.webtemplate.source.html`:**
+```html
+<div/>
+<script>
+ // Code Site Shell Header — Server-to-SPA redirect for auth pages.
+ // This template runs on server-rendered pages and redirects to SPA equivalents.
+ // Uses a separate template because pac pages upload-code-site wipes the original Header.
+ (function () {
+ var path = window.location.pathname.toLowerCase();
+ var search = window.location.search;
+ var spaBase = window.location.origin;
+ // Add an entry here for each server-rendered auth page that has a SPA equivalent.
+ // Only include entries the site actually needs (e.g., omit /redeeminvitation when
+ // InvitationEnabled is false).
+ var redirects = {
+ '/account/login/resetpassword': '/reset-password',
+ '/account/login/redeeminvitation': '/redeem-invitation',
+ '/register': '/redeem-invitation',
+ '/account/login/register': '/registration',
+ '/account/login/externallogincallback': '/external-login-confirmation',
+ '/account/login/termsandconditions': '/terms',
+ '/account/login/externalauthenticationfailed': '/login',
+ '/signin': '/login'
+ };
+ // Special case: ExternalAuthenticationFailed may arrive with no query string
+ // (generic failure) or with ?message=access_denied (user-denied at IdP).
+ // Ensure the Login page always shows SOME error indication.
+ if (path === '/account/login/externalauthenticationfailed' && !search) {
+ window.location.replace(spaBase + '/login?message=external_auth_failed');
+ return;
+ }
+ for (var serverPath in redirects) {
+ if (path === serverPath) {
+ window.location.replace(spaBase + redirects[serverPath] + search);
+ return;
+ }
+ }
+ })();
+</script>
+```
+
+**Conditional entries** — only include redirect entries for pages that exist in the SPA:
+
+| Redirect | Include when |
+|---|---|
+| `'/account/login/resetpassword': '/reset-password'` | Local auth + `ResetPasswordEnabled = true` (Phase 5.1.6) |
+| `'/account/login/redeeminvitation': '/redeem-invitation'` | `REGISTRATION_MODE` is `Invitation-only` or `Both` (Phase 5.1.7) |
+| `'/register': '/redeem-invitation'` | `REGISTRATION_MODE` is `Invitation-only` or `Both` (Phase 5.1.7). `/Register` is the **alias route for `LoginController.RedeemInvitation`** — the server redirects external users here from `ExternalLoginCallback` when they have no contact AND no invitation context (per `RegistrationManager.cs` gating logic). Catching this preserves the SPA UX for external users who initiated sign-in without an invitation link. |
+| `'/account/login/register': '/registration'` | `REGISTRATION_MODE` is not `Registration disabled` (Phase 5.1.2). This is the **local Register Web Forms page**. The server redirects here after the RedeemInvitation form is submitted (from `/Register` → `/Account/Login/Register?invitationCode=...`). Catching this keeps the user in the SPA `/registration` page, which itself mirrors the Login page layout — external provider buttons above a divider, local form below — so the user can complete sign-up either way (Phase 5.1.2). |
+| `'/account/login/externallogincallback': '/external-login-confirmation'` | Any external provider is configured (Phase 5.1.8) — captures first-time external sign-in into the SPA |
+| `'/account/login/termsandconditions': '/terms'` | Terms & Conditions are enabled (any auth flow — see Phase 5.1.5) — captures the server's post-auth Terms redirect for external providers |
+| `'/account/login/externalauthenticationfailed': '/login'` | Any external provider is configured. **The server redirects here when external auth fails** — invalid token, issuer mismatch, user-denied at IdP, IdP outage, etc. This path is hardcoded in OWIN startup and cannot be overridden via site settings (per `authentication-reference.md`). The redirect script special-cases this URL: when the server appends `?message=access_denied` (user-denied case), it carries through and `getAuthError()` shows "Access was denied." When the server appends no query string (generic failure), the script injects `?message=external_auth_failed` so the Login page shows "Sign-in with the external provider failed. Please try again." (add this code to `AUTH_ERROR_MESSAGES` in authService). |
+| `'/signin': '/login'` | **Always include** (any auth flow). `/SignIn` is the server's legacy sign-in page — the server bounces unauthenticated users there whenever they hit a protected server-rendered path (e.g., `/profile`, `/Account/Manage`, any server page gated by web roles). Without this entry, the user gets dropped out of the SPA into the server-rendered sign-in UI. Any `?ReturnUrl=...` query param the server appends is carried through unchanged — the SPA `/login` page currently ignores it (always returns to `/` after sign-in), which is acceptable behavior. |
+
+> **About the two new entries (`/register` and `/account/login/register`):** these handle a specific external-auth flow that's hard to discover otherwise. When an external user (Entra External ID, OIDC, SAML2, social) clicks the "Sign in" button WITHOUT first clicking an invitation email link, and they don't have an existing contact in Dataverse, the server forces them through a server-rendered invitation flow:
+>
+> 1. `POST /Account/Login/ExternalLogin` → IdP → `/signin-{provider}` → `/Account/Login/ExternalLoginCallback`
+> 2. `ExternalLoginCallback` finds no contact + no invitation → redirects to `/Register?ReturnUrl=/` (the RedeemInvitation form, server-rendered)
+> 3. User enters invitation code → server validates → redirects to `/Account/Login/Register?invitationCode=...` (the local Register Web Forms page, which has external provider buttons rendered on it)
+> 4. User clicks an external provider button on the Register page → `/Account/Login/ExternalLogin?InvitationCode=...` → external auth round 2 with invitation in URL → contact created + invitation redeemed
+>
+> Without the `/register` and `/account/login/register` redirects, the user sees the server-rendered RedeemInvitation form and the Web Forms Register page — both break the SPA UX. **These redirects apply to ALL external providers, not just Entra External ID, because the server's bouncing logic is provider-agnostic.**
+
+Then update **`website.yml`** to point `headerwebtemplateid` to the new template's ID:
+
+```yaml
+headerwebtemplateid: <new-template-uuid>
+```
+
+The original "Header" template stays as `<div/>` (the upload command will keep wiping it, which is fine). The `Code-Site-Shell-Header` template survives uploads because the command only targets the templates named "Header" and "Footer".
+
+This is extensible — additional server-to-SPA redirects can be added to the `redirects` object (e.g., for email confirmation pages).
+
+**2. SPA Reset Password Page**
+
+Create a `/reset-password` page that:
+
+- Reads `UserId` and `Code` from the URL query params (preserved by the header redirect)
+- Shows "Invalid Reset Link" with a link to `/forgot-password` if either param is missing
+- Shows new password + confirm password fields with validate-on-blur (password strength validation same as registration)
+- Calls `resetPassword(userId, code, password, confirmPassword)` from authService on submit
+- On success, redirects to `/login?message=password_reset_success`
+- On error, shows server errors inline
+
+The `resetPassword()` function is an MVC form POST (no ViewState) to `/Account/Login/ResetPassword` with fields: `__RequestVerificationToken`, `UserId`, `Code`, `Password`, `ConfirmPassword`. Note: the password field is `Password` here (NOT `PasswordValue` like login — different endpoints use different field names).
+
+**Login page must handle the success message**: Check for `?message=password_reset_success` in the URL on mount and display a green success banner: "Your password has been reset. Please sign in with your new password."
+
+**Framework-specific implementation:**
+- **React**: Create `src/pages/ResetPassword.tsx` and add `<Route path="/reset-password" element={<ResetPassword />} />` to the router
+
+#### 5.1.7 Create Redeem Invitation Page (Invitation Modes Only)
+
+**If `REGISTRATION_MODE` is `Invitation-only` or `Both`**, create a `/redeem-invitation` SPA page. This is the landing page users hit when they click an invitation email link. The link format is `{site-url}/Account/Login/RedeemInvitation?invitation={code}` — the Code-Site-Shell-Header redirect (Phase 5.1.6) catches it and forwards to the SPA route.
+
+**Two paths land users on `/redeem-invitation`:**
+
+1. **Direct invitation link**: User clicks the email link `/Account/Login/RedeemInvitation?invitation={code}` → header script redirects to `/redeem-invitation?invitation={code}`. Clean SPA entry — invitation code in URL from the start.
+
+2. **Server-bounce path (external auth, no contact, no invitation)**: User clicks "Sign in with [external provider]" on the Login page WITHOUT first clicking an invitation link. They complete external auth, the server's `ExternalLoginCallback` finds no contact + no invitation, and redirects them to `/Register?ReturnUrl=...` (the alias for `LoginController.RedeemInvitation`). The header script catches `/register` and redirects to `/redeem-invitation` — same SPA page, no invitation code pre-filled, user types it in. This path applies to **all external providers**, not just Entra External ID — the server-side bouncing logic is provider-agnostic. **Confirmed via HAR analysis on a live site with Entra External ID + Terms.**
+
+**Server flow this replaces:** The server's `LoginController.RedeemInvitation` action (`crm.solutions.portal/Samples/MasterPortal/Areas/Account/Controllers/LoginController.cs` lines 3232-3310) validates the invitation code and branches:
+
+- **RedeemByLogin = false** (new user) → 302 redirect to `/Account/Login/Register?invitationCode={code}` — server expects registration with the code
+- **RedeemByLogin = true** (existing user) → 200 OK with Login view, invitation code embedded in the form action URL — server expects sign-in, then redeems invitation in `RedirectOnPostAuthenticate` after auth
+- **Invalid / expired / already-redeemed code** → 200 OK with form re-rendered, error in `#redeemInvitation-validation-summary` (all three conditions surface the same `Invalid_Invitation_Code_Exception`)
+
+**SPA design — fully replaces the server-rendered page:**
+
+The SPA page calls `redeemInvitation(code, redeemByLogin)` from authService, which uses `fetch()` with `redirect: 'manual'` to intercept the server's 302 redirect. Based on the response:
+
+- `response.type === 'opaqueredirect'` → server validated code + would have redirected to Register → SPA navigates to `/registration?invitationCode={code}` (existing page from Phase 5.1.2)
+- 200 OK with Login form markers in HTML → user wanted login flow → SPA navigates to `/login?invitationCode={code}` (existing page — must also be updated, see below)
+- 200 OK with validation summary in HTML → invalid code → throw parsed server error (use existing `parseServerErrors()` helper)
+
+> **DevTools artifact**: After the POST, the browser's network panel will show the 302 Location target (e.g., `/Account/Login/Register`) as an aborted (`net::ERR_ABORTED`) request. This is expected — it's the redirect we intentionally chose not to follow via `redirect: 'manual'`. The flow uses `response.type === 'opaqueredirect'` to detect the redirect occurred without actually following it.
+
+The redeem invitation page must:
+
+- Read `invitation` or `InvitationCode` from the URL query (handle both casings — emails may use either)
+- Pre-fill the invitation code input but keep it editable (in case user types it in manually with no email link)
+- Show a checkbox: **"Sign in with an existing account instead of registering"** (this controls `RedeemByLogin`)
+- Validate-on-blur: invitation code required and non-empty
+- On submit, call `redeemInvitation()` and navigate based on the returned `nextStep`
+- Display server errors inline (parsed via existing `parseServerErrors`)
+- Include a "Back to sign in" link to `/login`
+- Be styled to match the rest of the auth pages
+
+**Login page update (required):**
+
+The Login page (Phase 5.1.1) must also be updated when invitation mode is enabled:
+
+1. Read `invitationCode` from URL query params on mount
+2. If present, show an info banner: `"Sign in to redeem invitation {code}. The invitation will be linked to your account after you sign in."`
+3. Pass `invitationCode` to `loginLocal()` as the new 5th parameter — the auth service appends it as `?InvitationCode={code}` on the `/SignIn` POST URL. The server's `Login(model, returnUrl, invitationCode)` handler reads this and redeems the invitation in `RedirectOnPostAuthenticate` after successful authentication.
+
+**Framework-specific implementation:**
+
+- **React**: Create `src/pages/RedeemInvitation.tsx` and add `<Route path="/redeem-invitation" element={<RedeemInvitation />} />` to the router. See the `RedeemInvitation` component in `authentication-reference.md` for the implementation pattern.
+- **Vue / Angular / Astro**: Mirror the React pattern in the framework's idioms.
+
+**Auth service additions** (required when invitation mode is enabled):
+
+- `redeemInvitation(invitationCode, redeemByLogin, returnUrl)` — see Phase 3.2 for the function inventory; full code in `authentication-reference.md`
+- `fetchInvitationDetails(invitationCode)` — already covered in Phase 5.1.2 for email pre-fill
+- `loginLocal()` updated to accept optional `invitationCode` parameter (5th arg) — appends `?InvitationCode={code}` to the `/SignIn` URL
+
+#### 5.1.8 Create External Login Confirmation Page (External Providers Only)
+
+**If any external provider is configured** (OIDC, Entra External ID, SAML2, WS-Federation, social), create a `/external-login-confirmation` SPA page. This captures the first-time external sign-in flow that the server would otherwise render as `ExternalLoginConfirmation.aspx`.
+
+**Server flow this replaces:** When a user signs in externally for the first time and no Dataverse contact exists, the server's `LoginController.ExternalLoginCallback` action (`crm.solutions.portal/Samples/MasterPortal/Areas/Account/Controllers/LoginController.cs` ~line 761) renders the `ExternalLoginConfirmation` view AT the callback URL (`/Account/Login/ExternalLoginCallback`). The view shows an editable email field plus hidden firstName/lastName/username from claims, and POSTs to `/Account/Login/ExternalLoginConfirmation`.
+
+**Why this can be SPA-ified (same pattern as Reset Password and Redeem Invitation):**
+
+- The `__External` cookie (5-minute TTL, `AuthenticationMode = Passive`, `Secure = Always`) stores the claims between the IdP callback and the form POST. It's auto-sent on `same-origin` fetches.
+- The SPA fetches the server URL, parses the rendered HTML to extract pre-fill values + anti-forgery token, shows its own form, and POSTs back. The server processes the form unchanged.
+
+**Skip conditions** — server skips this page entirely when:
+- The user's email claim matches an existing contact AND `AllowContactMappingWithEmail = true` → server auto-signs in
+- The user has an invitation code AND it resolves to an existing contact in the ESS system → server auto-signs in
+- Registration is disabled or the user isn't allowed to register
+
+In those cases the user goes straight to home after IdP callback — the SPA page never mounts.
+
+### Redirect chain
+
+```
+Email link / "Sign in with Entra External ID" button
+ ↓
+POST /Account/Login/ExternalLogin → server redirects to IdP
+ ↓
+User authenticates at IdP → IdP callback to /signin-{providername}
+ ↓
+OIDC middleware processes callback (sets __External cookie with claims)
+ ↓
+Forward to /Account/Login/ExternalLoginCallback
+ ↓
+ExternalLoginCallback action: new user, no existing contact
+ → returns ExternalLoginConfirmation view at the callback URL
+ ↓
+┌─ Code-Site-Shell-Header script catches /account/login/externallogincallback ─┐
+│ → window.location.replace('/external-login-confirmation' + query) │
+└────────────────────────────────────────────────────────────────────────────────┘
+ ↓
+SPA /external-login-confirmation page mounts
+ → calls fetchExternalLoginDetails()
+ → GET /Account/Login/ExternalLoginCallback (__External cookie auto-sent)
+ → server returns the same rendered HTML
+ → SPA parses #Email, #FirstName, #LastName, #Username, #InvitationCode,
+ __RequestVerificationToken, and the form's action URL for ReturnUrl
+ ↓
+SPA renders own form, email pre-filled and editable
+ ↓
+User clicks "Create my account"
+ → confirmExternalLogin() POST /Account/Login/ExternalLoginConfirmation
+ (form fields + anti-forgery token, redirect:'manual')
+ ↓
+ ├── response.type === 'opaqueredirect' → window.location.href = returnUrl
+ │ (server sets ApplicationCookie BEFORE returning 302 — user is signed in)
+ ├── 200 OK with validation-summary → throw parsed error (e.g., duplicate email
+ │ when RequireUniqueEmail is true and user typed an existing email)
+ └── 200 OK with TermsAndConditions markers → throw TermsRequiredError →
+ SPA navigates to /terms
+```
+
+### Auth service additions (when any external provider is configured)
+
+Add three things to `src/services/authService.ts` — full code in `authentication-reference.md`:
+
+- `ExternalLoginCookieExpiredError` class — thrown when the `__External` cookie has expired (5-minute TTL exceeded). The page navigates to `/login` with an expired-session message.
+- `fetchExternalLoginDetails()` — fetches `/Account/Login/ExternalLoginCallback`, parses HTML for pre-fill values and anti-forgery token. Throws `ExternalLoginCookieExpiredError` if the form isn't present.
+- `confirmExternalLogin(details)` — POSTs to `/Account/Login/ExternalLoginConfirmation` with `redirect:'manual'`. Branches on response type to navigate or throw.
-### Actions
+### SPA page
-#### 3.1 Create Type Declarations
+Create `src/pages/ExternalLoginConfirmation.tsx`:
-Create `src/types/powerPages.d.ts` with type definitions for the Power Pages portal object and user:
+- On mount, calls `fetchExternalLoginDetails()`. Three states: loading, cookie-expired, ready.
+- When cookie expired: shows "Sign-in session expired" with a "Back to sign in" link to `/login`.
+- When ready: shows the user's full name read-only (from claims), an editable email input (default = email claim), and an "invitation banner" if `invitationCode` is non-empty.
+- On submit, calls `confirmExternalLogin(details)`. Handles `TermsRequiredError` → navigate to `/terms`. Handles `ExternalLoginCookieExpiredError` (mid-session expiry) → switch UI to the expired state.
+- Server-side validation errors shown inline via `parseServerErrors`.
-- `PowerPagesUser` interface — `userName`, `firstName`, `lastName`, `email`, `contactId`, `userRoles[]`
-- `PowerPagesPortal` interface — `User`, `version`, `type`, `id`, `geo`, `tenant`, etc.
-- Global `Window` interface extension for `Microsoft.Dynamic365.Portal`
+### Routing
-#### 3.2 Create Auth Service
+Add `<Route path="/external-login-confirmation" element={<ExternalLoginConfirmation />} />`.
-Create the auth service file based on the detected framework:
+### DevTools artifact
-**All frameworks**: Create `src/services/authService.ts` with these functions:
+After the POST, the network panel may show the 302 Location target (e.g., the returnUrl path) as an aborted (`net::ERR_ABORTED`) request — same as the RedeemInvitation pattern. Expected behavior from `redirect:'manual'`, not an error.
-- `getCurrentUser()` — reads from `window.Microsoft.Dynamic365.Portal.User`
-- `isAuthenticated()` — checks if user exists and has `userName`
-- `getTenantId()` — reads from portal config (`window.Microsoft.Dynamic365.Portal.tenant`)
-- `fetchAntiForgeryToken()` — fetches from `/_layout/tokenhtml` and parses HTML response
-- `login(returnUrl?)` — creates a form POST to `/Account/Login/ExternalLogin` with:
- - Anti-forgery token from `/_layout/tokenhtml`
- - Provider URL: `https://login.windows.net/{tenantId}/`
- - Return URL (defaults to current page)
-- `logout(returnUrl?)` — redirects to `/Account/Login/LogOff`
-- `getUserDisplayName()` — prefers full name, falls back to userName
-- `getUserInitials()` — for avatar display
+### Edge cases
-**CRITICAL**: Power Pages authentication is **server-side** (session cookies). The login flow posts a form to the server which redirects to Entra ID. There is no client-side token management. The `fetchAntiForgeryToken()` call gets a CSRF token for the form POST, not a bearer token.
+- **2FA**: If the user has 2FA enabled, the challenge happens AFTER `SignInAsync` completes (during the 302 redirect). The SPA-ified flow doesn't interfere — the 2FA challenge (`SendCode`/`VerifyCode`) is its own server-rendered flow that cannot be intercepted.
+- **`SameSite=Strict`**: If the `__External` cookie is configured with `SameSite=Strict`, the SPA's fetch won't include it and `fetchExternalLoginDetails` throws `ExternalLoginCookieExpiredError` immediately. Default is `Lax` (set via `SameSiteCookieHelper.GetOwinSameSiteFromSiteSettings`) — works fine.
+- **Invited user via external login**: Invitation code is captured from the form action URL by `fetchExternalLoginDetails` and re-sent on the POST. The server redeems the invitation as part of contact creation.
-#### 3.3 Create Framework-Specific Auth Hook/Composable
+#### 5.1.9 Create Profile Page (When INCLUDE_PROFILE_PAGE = true)
-Based on the detected framework:
+**Conditional on `INCLUDE_PROFILE_PAGE = true`** (Phase 2.1). Skip this entire phase otherwise.
-- **React**: Create `src/hooks/useAuth.ts` — custom hook returning `{ user, isAuthenticated, isLoading, displayName, initials, login, logout, refresh }`
-- **Vue**: Create `src/composables/useAuth.ts` — composable using `ref`, `computed`, `onMounted` returning reactive auth state
-- **Angular**: Create `src/app/services/auth.service.ts` — injectable service with `BehaviorSubject` for user state
-- **Astro**: Create `src/services/authService.ts` only (no framework-specific wrapper needed — use the service directly in components)
+Creates a `/user-profile` SPA page where signed-in users edit their contact record via the Power Pages Web API. Provider-agnostic — works for local + all external providers because it operates on the contact record after sign-in.
-#### 3.4 Add Mock Data for Local Development
+> **⚠ MANDATORY NAMING — do not deviate:**
+>
+> | Item | Required name | Wrong examples to AVOID |
+> |---|---|---|
+> | SPA route | `/user-profile` | ❌ `/profile` (server-reserved), `/my-profile`, `/account/profile` |
+> | Page component file | `src/pages/UserProfile.tsx` | ❌ `Profile.tsx`, `MyProfile.tsx`, `UserProfilePage.tsx` |
+> | Component export name | `UserProfile` (default export) | ❌ `Profile`, `ProfilePage` |
+> | Service function — read | `getMyProfile(contactId)` | ❌ `getOwnContact`, `getProfile`, `fetchProfile` |
+> | Service function — write | `updateMyProfile(contactId, payload)` | ❌ `patchOwnContact`, `updateProfile`, `saveProfile` |
+> | Type — contact shape | `ProfileContact` | ❌ `Contact`, `UserContact` |
+> | Type — patch payload | `ProfileUpdate` | ❌ `ContactUpdate`, `ProfilePatch` |
+>
+> Why naming matters: the file/route names are referenced by other parts of this skill (Phase 7.1 verification, Phase 8.3 summary), the auth-reference.md, and the eval scenarios. Renaming creates a broken-cross-reference cascade. The route `/profile` specifically MUST NOT be used because the Power Pages server reserves it for the legacy server-rendered profile page (`Authentication/Registration/ProfileRedirectEnabled` redirects users to `/profile` after sign-in by default — we set this to `false` to prevent the redirect, but creating a SPA route at the same path would cause conflicts).
-Auth only works when served from Power Pages (not during local `npm run dev`). Add a development mock pattern in the auth service:
+##### 5.1.9.a Extend authService with profile functions
-```typescript
-// In development (localhost), return mock user data for testing
-const isDevelopment = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
-```
+Add to `src/services/authService.ts` (keep all related auth/profile logic in one place; reuse the existing `fetchAntiForgeryToken()` helper for the PATCH anti-forgery token).
-The mock should return a fake user with configurable roles so developers can test role-based UI locally.
+**Use these EXACT names** — the executor MUST NOT invent shorter or differently-styled names like `patchOwnContact`, `getOwnContact`, `updateProfile`:
-### Output
+| Required name | Kind | Description |
+|---|---|---|
+| `ProfileContact` | exported interface | Typed contact shape with `contactid` + the 8 editable fields (firstname, lastname, mobilephone, address1_line1, address1_city, address1_stateorprovince, address1_postalcode, address1_country) all typed `string \| null`. **DO NOT include emailaddress1 or middlename** — email is displayed read-only from `useAuth().user.email` (no Web API roundtrip needed for it), and middlename is intentionally excluded from the simple form. |
+| `ProfileUpdate` | exported type alias | `Partial<Omit<ProfileContact, 'contactid'>>` for the PATCH payload |
+| `getMyProfile` | exported async function | Signature: `(contactId: string): Promise<ProfileContact>`. GETs `/_api/contacts({contactId})?$select=contactid,firstname,lastname,mobilephone,address1_line1,address1_city,address1_stateorprovince,address1_postalcode,address1_country` (the `$select` value MUST exactly match the 9-entry list in Phase 8.1's `Webapi/contact/fields` site setting) with `credentials: 'same-origin'`. Throws on non-OK. Returns the parsed JSON. Dev-mode returns a mock object. |
+| `updateMyProfile` | exported async function | Signature: `(contactId: string, payload: ProfileUpdate): Promise<void>`. PATCHes `/_api/contacts({contactId})` with body containing only DEFINED fields (skip `undefined` so partial updates don't blank-out unaffected columns — but DO send `null` for fields the user explicitly cleared). Headers: `Content-Type: application/json`, `If-Match: *`, `__RequestVerificationToken` from `fetchAntiForgeryToken()`. Throws on non-OK with parsed error message. Dev-mode is a no-op success. |
+| `applyContactUpdateLocally` | exported function | Signature: `(payload: ProfileUpdate): void`. Mirrors the saved `firstname` / `lastname` from `payload` back into `window.Microsoft.Dynamic365.Portal.User` (mutating `firstName` / `lastName` properties in place — note the camelCase on the snapshot, lowercase on the payload). Returns early if `window` or `Portal.User` is unavailable. Only mirrors `firstname` and `lastname` — the other fields aren't used by the header. **Without this helper, the header keeps showing the old name after a save until the next full page reload — see the "header refresh after save" requirement in 5.1.9.b.** |
-- `src/types/powerPages.d.ts` created with Power Pages type definitions
-- `src/services/authService.ts` created with login/logout functions
-- Framework-specific auth hook/composable created
-- Local development mock data included
+Full reference code in `authentication-reference.md` "User Profile Page" section. **Copy that code as-is** — do not rename functions or change signatures.
----
+> **Also update `useAuth()` (`src/hooks/useAuth.ts`)** to spread the user object inside `refresh()` / `loadUser()` — `setUser(current ? { ...current } : undefined)` instead of `setUser(getCurrentUser())`. Reason: after `applyContactUpdateLocally` mutates `Portal.User` in place, the returned reference from `getCurrentUser()` is the same object instance. React's `setState` skips re-renders when the new state ref is identical to the current ref. Spreading into a new object forces React to see a fresh ref and re-run consumers, so `AuthButton` repaints with the new name. (Framework-equivalent change for Vue/Angular: ensure the user ref/Subject emits a fresh value, not the same instance.)
-## Phase 4: Create Authorization Utils
+##### 5.1.9.b Create UserProfile.tsx
-**Goal:** Create role-checking utilities and framework-specific authorization components (guards, directives, wrapper components).
+Create `src/pages/UserProfile.tsx` (filename mandatory, do NOT rename to `Profile.tsx`).
-Reference: `${CLAUDE_PLUGIN_ROOT}/skills/setup-auth/references/authorization-reference.md`
+**Two sections — Account Details (read-only) at the top, then the edit form. Nothing else.**
-### Actions
+### Account Details section (read-only, at top)
-#### 4.1 Create Core Authorization Utilities
+A simple display block showing exactly two pieces of info from `useAuth().user`:
-Create `src/utils/authorization.ts` with:
+| Label | Value source |
+|---|---|
+| Full name | `user.firstName` + ' ' + `user.lastName` (combined; show "—" if both empty) |
+| Email | `user.email` |
-- `getUserRoles()` — returns array of role names from current user
-- `hasRole(roleName)` — case-insensitive single role check
-- `hasAnyRole(roleNames)` — OR check across multiple roles
-- `hasAllRoles(roleNames)` — AND check across multiple roles
-- `isAuthenticated()` — re-exports from auth service
-- `isAdmin()` — checks for "Administrators" role
-- `hasElevatedAccess(additionalRoles)` — checks admin or specified roles
+**DO NOT** display contactId, userRoles, sign-in provider, username, last-login date, or any other field. The Account Details section's entire purpose is to remind the user which account they're signed in as — name and email suffice.
-#### 4.2 Create Framework-Specific Authorization Components
+Rendering: a small card / heading "Account details" with two label-value rows. Use existing CSS variables. No edit affordance. No "edit email" button. No "edit account" link.
-Based on the detected framework:
+### Page logic
-**React:**
+- Read `user`, `isAuthenticated`, `refresh` from `useAuth()`. If `!isAuthenticated`, redirect to `/login?returnUrl=/user-profile`.
+- If `user.contactId` is empty or missing, show "Profile unavailable for this account. Your admin needs to set up the `RegistrationClaimsMapping` site setting for your auth provider so contacts get created with a valid ID." (handles the Entra workforce broken-claims-mapping edge case documented earlier in this skill)
+- On mount, call `getMyProfile(user.contactId)` to fetch current values for the editable form. Show loading state.
-- `src/components/RequireAuth.tsx` — renders children only for authenticated users, optional login prompt fallback
-- `src/components/RequireRole.tsx` — renders children only for users with specified roles, supports `requireAll` mode
-- `src/hooks/useAuthorization.ts` — hook returning `{ roles, hasRole, hasAnyRole, hasAllRoles, isAuthenticated, isAdmin }`
+### MANDATORY editable field set (exactly 8 fields)
-**Vue:**
+The form MUST include exactly these 8 fields — no more, no less. Do NOT add email (it's read-only in Account Details). Do NOT add middlename. Do NOT add a "Change password" link. Do NOT add a "Sign out" button.
-- `src/composables/useAuthorization.ts` — composable with computed roles and role-checking functions
-- `src/directives/vRole.ts` — `v-role` directive for declarative role-based visibility
+| Form label | Form field `name` attr / contact column | Type | Required on submit? |
+|---|---|---|---|
+| First name | `firstname` | text | No (all optional) |
+| Last name | `lastname` | text | No |
+| Mobile phone | `mobilephone` | tel | No |
+| Address line 1 | `address1_line1` | text | No |
+| City | `address1_city` | text | No |
+| State / Province | `address1_stateorprovince` | text | No |
+| Postal code | `address1_postalcode` | text | No |
+| Country | `address1_country` | text | No |
-**Angular:**
+All fields are optional. An empty string in the form is sent as `null` to the Web API (so users can clear values). The page layout groups Name fields (firstname/lastname), then Contact (mobile), then Address (all `address1_*` fields). Use a CSS grid with `grid-template-columns: repeat(auto-fit, minmax(220px, 1fr))` for responsive 1-2 column layout.
-- `src/app/guards/auth.guard.ts` — `CanActivateFn` with route data for required roles
-- `src/app/directives/has-role.directive.ts` — structural directive `*appHasRole="'RoleName'"`
+### Things NOT to include on the profile page
-**Astro:**
+The executor MUST NOT add any of these — they're either redundant with existing UI or out of scope:
-- `src/utils/authorization.ts` only (use directly in component scripts)
+- ❌ "Change password" link or button — password reset goes through the existing `/forgot-password` flow (link is on the Login page)
+- ❌ "Sign out" button on the profile page — sign-out lives in the header AuthButton dropdown only
+- ❌ Editable email field — email is displayed read-only in the Account Details section above
+- ❌ Middle name field
+- ❌ ContactId, userRoles, sign-in method, provider name, last-login timestamp, or any other account metadata
+- ❌ Email caveat note (the note about LoginClaimsMapping overwriting email edits is no longer relevant since email isn't editable)
+- ❌ Account deletion or "Close account" button — out of scope
-#### 4.3 Security Reminder
+### Logic details
-Add a comment at the top of the authorization utilities:
+- Validate-on-blur using the existing pattern from `Login.tsx` / `Registration.tsx` (`touched` state, `validateField`, `show()` helper)
+- Field-level validation: mobile phone min 6 chars if non-empty. Other 7 fields have no format validation. All fields optional — empty strings allowed and sent as `null`.
+- Submit calls `updateMyProfile(contactId, payload)`. On success, in this exact order:
+ 1. Set `successMessage` state to "Profile updated."
+ 2. Update the local `profile` snapshot (so the form's diff calculation on the next save is correct)
+ 3. **Call `applyContactUpdateLocally(payload)`** — mirrors the saved name fields back into `window.Microsoft.Dynamic365.Portal.User`. **This is REQUIRED for the header to repaint** — without it, the header keeps showing the pre-save name until the user navigates to a route that triggers a full page load.
+ 4. **Call `refresh()` from `useAuth()`** — re-reads `Portal.User` (now mutated) into React state with a spread (the useAuth update above), which triggers a re-render of `AuthButton`. Without the spread, this is a no-op because `setState` with an identical reference is skipped by React.
-```typescript
-// IMPORTANT: Client-side authorization is for UX only, not security.
-// Server-side table permissions enforce actual access control.
-// Always configure table permissions via /integrate-webapi.
-```
+ On error: show server error inline.
+- **Set the browser tab title** — add a `useEffect` near the top of the component (matching the convention used on `Login.tsx`, `Registration.tsx`, `ForgotPassword.tsx`, `ResetPassword.tsx`, `RedeemInvitation.tsx`, `ExternalLoginConfirmation.tsx`, `Terms.tsx`, etc.):
-### Output
+ ```tsx
+ useEffect(() => { document.title = 'My Profile — <SITE_NAME>' }, [])
+ ```
-- `src/utils/authorization.ts` created with role-checking functions
-- Framework-specific authorization components created (guards, directives, or wrapper components)
-- Security reminder comments included
+ Substitute `<SITE_NAME>` with the actual site display name discovered in Phase 1 (the same value used in the other auth pages — e.g., `Contoso Portal`). Format MUST match the existing pages exactly: `<Page Title> — <Site Name>` (em-dash `—`, space on each side). Do NOT use `|`, `:`, or a hyphen.
+- Use existing styles convention (CSS variables, card layout, max-width ~580)
+- See `authentication-reference.md` "User Profile Page" section for the complete reference implementation
----
+##### 5.1.9.c Evolve AuthButton to dropdown
-## Phase 5: Create Auth UI
+Update `src/components/AuthButton.tsx`. **Make the dropdown shape the default for the authenticated state regardless of `INCLUDE_PROFILE_PAGE`** so the component is consistent and ready for future menu items:
-**Goal:** Create the login/logout button component and integrate it into the site's navigation.
+- Anonymous state: unchanged — `<Link to="/login" className="btn-primary">Sign In</Link>`
+- Authenticated state (NEW):
+ - Trigger: `[Avatar] {displayName} ▾` — clickable
+ - Menu (state-based, opened via `useState<boolean>`): renders when open
+ - Menu items when `INCLUDE_PROFILE_PAGE = true`: "My Profile" (Link to `/user-profile`) + "Sign Out" (calls `logout('/')`)
+ - Menu items when `INCLUDE_PROFILE_PAGE = false`: just "Sign Out"
+ - `useEffect` listens for `mousedown` outside the dropdown container → close. Listens for `Escape` key → close. Cleanup on unmount.
+ - "My Profile" link's `onClick` also closes the dropdown
+ - ARIA: trigger has `aria-haspopup="menu"`, `aria-expanded={open}`; menu has `role="menu"`; items have `role="menuitem"`
+ - Styling: menu uses existing CSS variables (`var(--color-surface)`, `var(--color-border)`, `var(--shadow-md)`, `var(--radius-sm)`)
-### Actions
+##### 5.1.9.d Add route
-#### 5.1 Create Auth Button Component
+Add to `src/App.tsx` — use **exactly this path** (`/user-profile`, NOT `/profile`):
-Based on the detected framework, create a login/logout button component:
+```tsx
+import UserProfile from './pages/UserProfile'
+// ...inside <Routes>:
+<Route path="/user-profile" element={<UserProfile />} />
+```
-- **React**: `src/components/AuthButton.tsx` + `src/components/AuthButton.css`
-- **Vue**: `src/components/AuthButton.vue`
-- **Angular**: `src/app/components/auth-button/auth-button.component.ts` + template + styles
-- **Astro**: `src/components/AuthButton.astro`
+> **⚠ DO NOT use `<Route path="/profile" ... />`.** The server reserves `/profile` for its legacy server-rendered page. Even though `ProfileRedirectEnabled` is set to `false` by this skill (which prevents the server from auto-redirecting users there after sign-in), creating a SPA route at the same path causes conflicts. Always use `/user-profile`.
+>
+> **Authentication gate**: the page itself handles the `!isAuthenticated` redirect to `/login?returnUrl=/user-profile` (see 5.1.9.b). If you have a `RequireAuth` wrapper component you prefer, you MAY use `<Route path="/user-profile" element={<RequireAuth><UserProfile /></RequireAuth>} />` — but only if the wrapper exists in the project already. Do not introduce a new `RequireAuth` component just for this page.
-The component should:
+##### After save behavior
-- Show a "Sign In" button when the user is not authenticated
-- Show the user's display name, avatar (initials-based), and a "Sign Out" button when authenticated
-- Include a loading state while checking auth status
-- Be styled to match the site's existing design (read existing CSS variables/theme)
+When `updateMyProfile` resolves successfully:
+1. Set inline `successMessage` state ("Profile updated.") — green banner at top of form, dismissable
+2. Call `useAuth().refresh()` — re-reads `window.Microsoft.Dynamic365.Portal.User`. Note that `Portal.User` is a snapshot from initial page load and won't have the new values until full page reload. So the right pattern is to also update local UI state (form fields stay as the user typed; header avatar may briefly show old initials until refresh propagates). Document this caveat in the reference.
+3. Stay on the page — no auto-redirect.
#### 5.2 Integrate into Navigation
@@ -328,9 +1840,10 @@ Find the site's navigation component and integrate the auth button:
1. Search for the nav/header component in the site's source code
2. Import the AuthButton component
-3. Add it to the navigation bar (typically in the top-right area)
-
-**Do NOT replace the existing navigation** — add the auth button alongside existing nav items.
+3. **Replace any existing hardcoded sign-in link** (e.g., `<Link to="/login">Sign In</Link>` or `<a href="/signin">`) with the AuthButton component. The AuthButton reads `window.Microsoft.Dynamic365.Portal.User` to dynamically show either "Sign In" (when not authenticated) or the user's name + avatar + "Sign Out" button (when authenticated). A hardcoded link does not react to auth state.
+4. **If multiple providers are configured**: The AuthButton's "Sign In" action should navigate to `/login` page
+5. **If single provider**: The AuthButton's "Sign In" action should call `login()` directly
+6. **Verify** after integration that the Navbar does NOT have both a hardcoded sign-in link AND the AuthButton — there must be exactly one auth entry point in the navigation.
#### 5.3 Git Commit
@@ -345,6 +1858,7 @@ git commit -m "Add authentication service and auth UI component"
- Auth button component created for the detected framework
- Auth button integrated into the site's navigation
+- Registration page created (when local auth with open registration is configured)
- Changes committed to git
---
@@ -428,11 +1942,25 @@ Confirm the following files were created:
- `src/utils/authorization.ts` — Role-checking utilities
- Framework-specific authorization components (e.g., `RequireAuth.tsx`, `RequireRole.tsx` for React)
- Auth button component (e.g., `src/components/AuthButton.tsx` for React)
+- Registration page (e.g., `src/pages/Registration.tsx` for React) — when local auth AND `REGISTRATION_MODE` is not `Registration disabled` (always created in Open, Invitation-only, and Both modes)
+- Forgot password page (e.g., `src/pages/ForgotPassword.tsx` for React) — only when local auth with reset password is configured
+- Session keepalive hook (e.g., `src/hooks/useSessionKeepAlive.ts` for React) — integrated into Layout
+- Terms page (e.g., `src/pages/Terms.tsx` for React) — only when terms are enabled
+- Reset password page (e.g., `src/pages/ResetPassword.tsx` for React) — only when local auth with reset password is configured
+- **Redeem invitation page (e.g., `src/pages/RedeemInvitation.tsx` for React) — only when `REGISTRATION_MODE` is `Invitation-only` or `Both`**
+- **User profile page (e.g., `src/pages/UserProfile.tsx` for React) — only when `INCLUDE_PROFILE_PAGE = true`. Plus `getMyProfile` + `updateMyProfile` functions in `authService.ts`, AuthButton evolved to dropdown shape, `/user-profile` route in `App.tsx`.**
+- Code-Site-Shell-Header template (`.powerpages-site/web-templates/code-site-shell-header/`) with redirect script — entries depend on enabled features (resetpassword, redeeminvitation)
+- `website.yml` updated to point `headerwebtemplateid` to Code-Site-Shell-Header
+- **Web API site settings (`Webapi/contact/enabled`, `Webapi/contact/fields`) — only when `INCLUDE_PROFILE_PAGE = true`**
+- **Table permission `.powerpages-site/table-permissions/My-Profile-Edit-Own-Contact.tablepermission.yml` with `scope: 756150004` (Self) — only when `INCLUDE_PROFILE_PAGE = true`**
Read each file and verify it contains the expected exports and functions:
-- Auth service: `login`, `logout`, `getCurrentUser`, `isAuthenticated`, `fetchAntiForgeryToken`
+- Auth service: `login`, `logout`, `getCurrentUser`, `isAuthenticated`, `fetchAntiForgeryToken`, `parseServerErrors`, `register`, `forgotPassword` (when local auth), `TermsRequiredError`, `acceptTerms` (when terms enabled), `redeemInvitation` and `fetchInvitationDetails` (when invitation modes), `loginLocal` accepts `invitationCode` parameter (when invitation modes)
- Authorization utils: `hasRole`, `hasAnyRole`, `hasAllRoles`, `getUserRoles`
+- Login and registration pages: validate-on-blur pattern with `touched` state, `handleBlur`, `handleChange`, `showError` helper. Both must catch `TermsRequiredError` and navigate to `/terms` (when terms enabled). Login page must read `invitationCode` from URL and show info banner + pass through (when invitation modes). Registration page must call `fetchInvitationDetails()` to pre-fill email (when invitation modes).
+- Redeem invitation page (when invitation modes): pre-fills code from URL, has "Sign in with an existing account instead of registering" checkbox, branches to `/registration` or `/login` based on `redeemInvitation()` result
+- Session keepalive: integrated in Layout, pings `/_layout/tokenhtml`, tracks activity, detects expiry
#### 7.2 Verify Build
@@ -474,24 +2002,729 @@ If the auth button is not visible or the page has rendering errors, fix the issu
### Actions
-#### 8.1 Create Site Setting
-
-The site needs the `Authentication/Registration/ProfileRedirectEnabled` setting set to `false` to prevent Power Pages from redirecting users to a profile page after login (which doesn't exist in code sites).
+#### 8.1 Create Site Settings
-Check if `.powerpages-site/site-settings/` exists. If it does, create the site setting file:
+The site needs provider-specific site settings. Check if `.powerpages-site/site-settings/` exists. Use the `create-site-setting.js` script for all site settings:
```bash
-node "${CLAUDE_PLUGIN_ROOT}/scripts/generate-uuid.js"
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "<Setting/Name>" \
+ --value "<value>" \
+ --description "<description>"
+```
+
+**`{ProviderName}` naming convention:** Replace `{ProviderName}` with the protocol followed by an incrementing number:
+- OpenID Connect: `OpenIdConnect_1`, `OpenIdConnect_2`, etc.
+- Entra External ID: `OpenIdConnect_1` (uses OIDC path)
+- SAML2: `SAML2_1`, `SAML2_2`, etc.
+- WS-Federation: `WsFederation_1`, `WsFederation_2`, etc.
+
+**Handling re-runs:** If `create-site-setting.js` exits with code 1 because a setting already exists, skip that setting and continue. The existing setting is already configured from a previous run. Do not treat this as a fatal error. The script checks for duplicates by both setting name and filename (case-insensitive) — no overwrites happen.
+
+**CRITICAL — Redirect URI / CallbackPath uniqueness when multiple OIDC providers are configured:**
+
+The OWIN OpenID Connect middleware defaults `CallbackPath` to `/signin-oidc` for **every** OIDC provider. If you configure two OIDC providers (e.g., Entra External ID + Okta) without setting unique CallbackPath values, they will both claim `/signin-oidc` and authentication will silently fail for one.
+
+**Use the ProviderName directly as the CallbackPath suffix** — this is deterministic and guarantees uniqueness because ProviderName is already unique (per the `{ProviderName}` naming convention: `OpenIdConnect_1`, `OpenIdConnect_2`, `EntraExternalId`, etc.).
+
+**For every OIDC provider** (including Entra External ID), use this exact pattern:
+
+- `CallbackPath` = `/signin-{ProviderName-lowercased}` (e.g., `/signin-entraexternalid`, `/signin-openidconnect_1`)
+- `RedirectUri` = `{site-url}/signin-{ProviderName-lowercased}` (must match CallbackPath exactly)
+
+Example for two OIDC providers:
+
+| ProviderName | CallbackPath | RedirectUri |
+|--------------|--------------|-------------|
+| `EntraExternalId` | `/signin-entraexternalid` | `https://contoso.powerappsportals.com/signin-entraexternalid` |
+| `OpenIdConnect_1` (Okta) | `/signin-openidconnect_1` | `https://contoso.powerappsportals.com/signin-openidconnect_1` |
+
+**Before creating** site settings, read existing `.powerpages-site/site-settings/` and verify no other `Authentication/OpenIdConnect/*/CallbackPath` or `RedirectUri` setting has the same value. If a collision exists (because the same ProviderName was reused), increment the numeric suffix on the ProviderName (e.g., `OpenIdConnect_1` → `OpenIdConnect_2`) and re-derive the CallbackPath.
+
+**Tell the user to register the exact RedirectUri** in their identity provider's app registration (Microsoft Entra admin center → App registrations → Redirect URIs).
+
+**How values are sourced:**
+- **Non-secret values** (authority URL, site URL, redirect URIs, AuthenticationType) → filled automatically from information gathered during the flow. The user should NOT need to edit any files.
+- **ClientId / AppId** → collected from the user in Phase 2.1 (each provider's follow-up question). Use the collected value when creating the site setting.
+- **Secrets** (`ClientSecret`, `AppSecret`) → use environment variables via `create-environment-variable.js`. Never ask for or store secret values directly. See Phase 8.1.1 below.
+
+**Always create** — these settings are required for all provider types:
+
+> **ProfileRedirectEnabled MUST be `false` for code sites.** If `create-site-setting.js` reports this setting already exists, read the YAML file and check its value. If it is `true`, edit the file to set `value: false`. When this is `true`, the server redirects users to `/profile` after login/registration instead of respecting the `ReturnUrl` — which breaks the SPA flow.
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/ProfileRedirectEnabled" \
+ --value "false" \
+ --description "Disable profile redirect for code sites" \
+ --type boolean
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/Enabled" \
+ --value "true" \
+ --description "Enable user registration (global toggle)" \
+ --type boolean
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/ExternalLoginEnabled" \
+ --value "true" \
+ --description "Enable external identity provider login" \
+ --type boolean
+```
+
+**Profile mapping settings** — for **every** external provider (OIDC, SAML2, WS-Federation, social), write `RegistrationClaimsMapping` based on `PROFILE_MAPPING_CHOICE` from Phase 2.1, and `LoginClaimsMapping` when `PROFILE_SYNC_FREQUENCY = "Both"`:
+
+```powershell
+# Skip if PROFILE_MAPPING_CHOICE = "None"
+# Generate the value based on PROFILE_MAPPING_CHOICE:
+# "Standard" → firstname=given_name,lastname=family_name,emailaddress1=email
+# "Standard + phone" → firstname=given_name,lastname=family_name,emailaddress1=email,mobilephone=phone_number
+# "Custom" → user-provided comma-separated pairs
+# For SAML2/WsFed, use the claim URI form instead of OIDC short names.
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/{Type}/{ProviderName}/RegistrationClaimsMapping" \
+ --value "firstname=given_name,lastname=family_name,emailaddress1=email" \
+ --description "Map IdP claims to contact fields on first sign-in"
+
+# Only write if PROFILE_SYNC_FREQUENCY = "Both"
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/{Type}/{ProviderName}/LoginClaimsMapping" \
+ --value "firstname=given_name,lastname=family_name,emailaddress1=email" \
+ --description "Map IdP claims to contact fields on every login"
+```
+
+**Contact linking setting** — write `AllowContactMappingWithEmail` based on `CONTACT_LINKING_CHOICE`:
+
+```powershell
+# CONTACT_LINKING_CHOICE = "Link to existing" → value "true"
+# CONTACT_LINKING_CHOICE = "Create new" → value "false" (or skip — false is the server default)
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/{Type}/{ProviderName}/AllowContactMappingWithEmail" \
+ --value "<true-or-false-from-choice>" \
+ --description "Auto-link external sign-in to existing contact by email match" \
+ --type boolean
+```
+
+> **Multi-tenant guard**: Before writing `AllowContactMappingWithEmail=true` for an OIDC provider, check the Authority URL. If it contains `/organizations/`, `/common/`, or if `IssuerFilter` is set to a wildcard pattern, **override the user's choice to `false`** and tell the user: "Multi-tenant Entra External ID configurations cannot use contact mapping for security reasons (the server forcibly disables it). To enable contact mapping, use a single-tenant Authority URL with a specific tenant GUID."
+
+**Per-provider `RegistrationEnabled` setting** — for **every** external provider (OIDC, SAML2, WS-Federation, social), also write:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/{Type}/{ProviderName}/RegistrationEnabled" \
+ --value "true" \
+ --description "Allow new users to register via this specific provider" \
+ --type boolean
+```
+
+Where `{Type}` is `OpenIdConnect`, `SAML2`, `WsFederation`, or `OpenAuth`. This is a **per-provider toggle** that's distinct from the global `Authentication/Registration/ExternalLoginEnabled` — set both to `true` for registration to work. Use case for setting one provider's `RegistrationEnabled=false`: temporarily block new users from a given IdP while still letting existing users sign in.
+
+**Logout settings — conditional on Phase 2.1.1 logout mode choice**
+
+For external providers, write logout settings only when the user picked **"Federated logout"** in Phase 2.1.1. If they picked "Local logout only" (the default), write neither setting — the server defaults (`RPInitiatedLogout=false`, `ExternalLogoutEnabled=false`) handle this correctly.
+
+```powershell
+# Only when LOGOUT_MODE = "Federated logout"
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/RPInitiatedLogout" \
+ --value "true" \
+ --description "Federated logout — call IdP end_session_endpoint with id_token_hint" \
+ --type boolean
+
+# REQUIRED when RPInitiatedLogout=true — must be paired
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/PostLogoutRedirectUri" \
+ --value "<POST_LOGOUT_REDIRECT_URI from Phase 2.1.1>" \
+ --description "URL the IdP redirects to after federated logout completes"
+```
+
+For SAML2 / WS-Federation / social providers, the equivalent settings names differ — `Authentication/{Type}/{ProviderName}/RPInitiatedLogout` and `/PostLogoutRedirectUri` follow the same naming pattern. For social providers (Microsoft Account / Facebook / Google), federated logout is usually not supported by the provider, so the question is moot — skip the logout-mode question for social and don't write either setting.
+
+> **Server behavior reminder**: Without these settings (i.e., "Local logout only" mode), `/Account/Login/LogOff` clears the Power Pages session and redirects to the `returnUrl` query parameter (or site root if missing/invalid). The IdP session stays warm — next sign-in is silent SSO. **No app-registration changes needed in this mode.**
+>
+> With these settings ("Federated logout"), `/Account/Login/LogOff` 302s to the IdP's `end_session_endpoint` with `id_token_hint` and `post_logout_redirect_uri`. The IdP signs the user out and redirects to the registered post-logout URI. **The maker MUST also register that URI in the IdP app registration** (see Phase 2.1.1) — confirmed via HAR analysis that without app-registration of the front-channel logout URL, the IdP silently drops the parameter and users get stranded.
+
+**Provider-specific settings** — create site settings for **EACH** provider selected in Phase 2.1. If the user selected multiple providers (e.g., Entra External ID + Local Authentication), create settings for ALL of them:
+
+**Microsoft Entra ID** — Authority, ClientId, Metadata, etc. are auto-configured by Power Pages on site creation (provider name `AzureAD`). However, **always write claims mapping settings** so first-time-sign-in contacts get firstname/lastname/email populated. The auto-configured AzureAD provider does NOT have claims mapping by default — without these settings, new contacts are created with the user's `oid` linked but every other field empty (verified empirically: workforce Entra ID v1.0 tokens don't include the `email` claim, and the server doesn't auto-derive contact fields from `given_name`/`family_name` claims unless an explicit mapping is configured).
+
+```powershell
+# RegistrationClaimsMapping — applied once at first sign-in, before contact is created.
+# Uses `upn` for email because workforce Entra ID v1.0 tokens don't include the `email`
+# claim by default. UPN (user principal name, e.g. [email protected]) is the standard
+# substitute and matches what the user expects in their profile.
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/AzureAD/RegistrationClaimsMapping" \
+ --value "firstname=given_name,lastname=family_name,emailaddress1=upn" \
+ --description "Map AzureAD claims to contact fields on first sign-in (UPN as email — workforce v1.0 tokens lack email claim)"
+
+# LoginClaimsMapping — applied every sign-in. Updates contact fields if user info
+# changes in Entra (e.g., name change). Same mapping as Registration; safe to write
+# both for consistency.
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/AzureAD/LoginClaimsMapping" \
+ --value "firstname=given_name,lastname=family_name,emailaddress1=upn" \
+ --description "Re-apply claim mapping on every sign-in so contact fields stay in sync with Entra"
```
-Create `.powerpages-site/site-settings/authentication-registration-profileredirectenabled.yml`:
+> **Why `upn` and not `email`?** Workforce Entra ID's OIDC endpoint defaults to v1.0 tokens (issuer `sts.windows.net/{tid}/`) which do NOT include the `email` claim by default. To get the `email` claim, the app registration would need to be configured for v2.0 tokens AND request the `email` scope AND the user must have a verified email address in their Entra profile (none of which is the default). The `upn` claim, however, is always emitted for workforce users — it's the user principal name (e.g., `[email protected]`) which functions as the email for most workforce scenarios. This applies ONLY to workforce Entra ID (the auto-configured `AzureAD` provider). **Entra External ID uses v2.0 tokens with proper `email` claim — its mapping should be `emailaddress1=email`, NOT `emailaddress1=upn`** (see the Profile mapping question in Phase 2.1 for External ID).
+
+> **No question is asked for this.** Unlike other external providers where the Profile mapping question (Track B) is part of Phase 2.1, the Entra ID mapping is written silently because (a) workforce Entra IS deterministic on which claim is the right substitute for email (always `upn`), and (b) without this mapping the contact is created broken, so opting out doesn't make sense.
+
+**OpenID Connect (Generic)** — create settings for the provider (ClientId was collected in Phase 2.1):
+
+```powershell
+# Authority (required — or use MetadataAddress as alternative)
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/Authority" \
+ --value "<authority-url-from-user>" \
+ --description "OIDC authority URL"
+
+# MetadataAddress (optional — alternative to Authority for providers that need explicit metadata URL)
+# Create this if the user provides a metadata URL distinct from the authority
+# node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+# --projectRoot "<PROJECT_ROOT>" \
+# --name "Authentication/OpenIdConnect/{ProviderName}/MetadataAddress" \
+# --value "<metadata-url>" \
+# --description "OIDC metadata endpoint URL"
+
+# ClientId — use value collected in Phase 2.1
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/ClientId" \
+ --value "<client-id-from-user>" \
+ --description "Application client ID"
+
+# AuthenticationType
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/AuthenticationType" \
+ --value "<authority-url-from-user>" \
+ --description "Provider identifier for ExternalLogin"
+
+# RedirectUri — use /signin-{ProviderName-lowercased} for guaranteed uniqueness
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/RedirectUri" \
+ --value "<site-url>/signin-{ProviderName-lowercased}" \
+ --description "OAuth callback URL — unique per provider (matches CallbackPath)"
+
+# CallbackPath — required to prevent collision when multiple OIDC providers exist
+# OWIN defaults ALL OIDC providers to /signin-oidc
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/CallbackPath" \
+ --value "/signin-{ProviderName-lowercased}" \
+ --description "Unique callback path derived from ProviderName"
+
+```
+
+> **Note:** The `AuthenticationType` value is the unique provider identifier used in the `ExternalLogin` form POST. This value must match what `resolveProviderIdentifier()` returns in the auth service.
+
+> **Logout settings** — do NOT auto-write `RPInitiatedLogout` or `ExternalLogoutEnabled` here. Both default to `false` server-side (per `StartupSettingsManager.cs:418,425`), which means logout clears only the Power Pages session and leaves the IdP session intact (user can silently SSO back in). This is the simpler default and what most sites want. If the user wants **federated logout** (sign out at the IdP too, with `post_logout_redirect_uri` redirecting back to the site), they configure it via the advanced settings flow in Phase 2.1.1 — which writes BOTH `RPInitiatedLogout=true` AND `PostLogoutRedirectUri={SITE_URL}/` together (one without the other leaves users stranded on the IdP's signed-out page — see Phase 2.1.1 for the full walkthrough).
+
+**Entra External ID** — uses values from the 4-step walkthrough in Phase 2.1. Derive `Authority` and `MetadataAddress` from the tenant subdomain + tenant ID — do not ask the user to paste them:
+
+- `Authority` = `https://{EXTERNAL_ID_TENANT_SUBDOMAIN}.ciamlogin.com/{EXTERNAL_ID_TENANT_ID}` — **NO trailing `/v2.0/`**. Entra External ID uses the bare tenant path (different from classic B2C and from generic OIDC providers like Okta which often need `/v2.0/`).
+- `MetadataAddress` = `https://{EXTERNAL_ID_TENANT_SUBDOMAIN}.ciamlogin.com/{EXTERNAL_ID_TENANT_ID}/v2.0/.well-known/openid-configuration`
+- `AuthenticationType` = same as `Authority` (provider identifier in ExternalLogin POST must match)
+- `ClientId` = `EXTERNAL_ID_CLIENT_ID` from Step 2 of walkthrough
+- `RedirectUri` = `{SITE_URL}/signin-{ProviderName-lowercased}` — same Redirect URI shown to user in Step 2
+
+```powershell
+# Authority — derived: https://{subdomain}.ciamlogin.com/{tenantId}
+# (do NOT append /v2.0/ — that breaks Entra External ID)
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/Authority" \
+ --value "https://<EXTERNAL_ID_TENANT_SUBDOMAIN>.ciamlogin.com/<EXTERNAL_ID_TENANT_ID>" \
+ --description "Entra External ID authority URL (derived)"
+
+# MetadataAddress — derived: Authority + /v2.0/.well-known/openid-configuration
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/MetadataAddress" \
+ --value "https://<EXTERNAL_ID_TENANT_SUBDOMAIN>.ciamlogin.com/<EXTERNAL_ID_TENANT_ID>/v2.0/.well-known/openid-configuration" \
+ --description "OIDC metadata document URL (derived)"
+
+# ClientId — from walkthrough Step 2
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/ClientId" \
+ --value "<EXTERNAL_ID_CLIENT_ID>" \
+ --description "Application client ID"
+
+# AuthenticationType — must match Authority exactly (used as the 'provider' form value in ExternalLogin POST)
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/AuthenticationType" \
+ --value "https://<EXTERNAL_ID_TENANT_SUBDOMAIN>.ciamlogin.com/<EXTERNAL_ID_TENANT_ID>" \
+ --description "Provider identifier for ExternalLogin — must match Authority exactly"
+
+# RedirectUri — the full URI the maker registered in their Entra app.
+# Confirmed/customized by user in Step 2 of walkthrough (stored as REDIRECT_URI).
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/RedirectUri" \
+ --value "<REDIRECT_URI>" \
+ --description "OAuth callback URL (must match the URI registered in the app registration)"
+
+# CallbackPath — derived from RedirectUri (just the path portion, extracted via
+# new URL(REDIRECT_URI).pathname). Required to prevent CallbackPath collision when
+# multiple OIDC providers exist (OWIN defaults all OIDC to /signin-oidc otherwise).
+# The maker doesn't see this separately — the skill writes it automatically.
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/CallbackPath" \
+ --value "<path-portion-of-REDIRECT_URI>" \
+ --description "OWIN callback path (derived from RedirectUri)"
+
+```
+
+> **Logout settings for Entra External ID** — do NOT auto-write `RPInitiatedLogout` or `ExternalLogoutEnabled` here. Both default to `false` server-side. Default behavior: logout clears the Power Pages session only; user stays signed in at the Entra External ID tenant. Next sign-in is silent SSO via the IdP's cookie. This is the simpler default and matches what most customer-facing sites want. **If the user wants federated logout** (sign out at Entra External ID too), they enable it via the advanced settings flow in Phase 2.1.1 — which writes BOTH `RPInitiatedLogout=true` AND `PostLogoutRedirectUri={SITE_URL}/` together AND adds an app-registration step for the Front-channel logout URL.
+
+> **Custom domains**: If the user is using a custom domain for their Entra External ID tenant (e.g., `https://login.contoso.com/{tenantId}/v2.0/`) instead of `*.ciamlogin.com`, replace the derived values above with the custom domain values. The walkthrough in Phase 2.1 doesn't currently ask about custom domains — when re-running with a custom-domain Authority in existing site settings (Phase 1.5 discovery), preserve those values rather than rebuilding from `EXTERNAL_ID_TENANT_SUBDOMAIN`.
+
+> **NO ClientSecret block for Entra External ID by default.** Public clients using PKCE don't need a client secret — the walkthrough explicitly does not ask for one. **Skip Phase 8.1.1 (Key Vault) entirely for this provider.** If a confidential-client scenario requires a secret post-deploy, document it as an advanced manual step in Phase 8.5 (add via Power Pages admin center → Authentication settings).
+
+> **User flow name (`EXTERNAL_ID_USER_FLOW`) is NOT written as a site setting.** Entra External ID attaches the user flow to the app registration itself, so the user flow runs automatically on sign-in without Power Pages needing to reference it by name in URL/metadata (unlike classic B2C). The walkthrough captures it only to confirm the user has created one. If the user later configures separate password-reset or profile-edit user flows, they can add `PasswordResetPolicyId` / `ProfileEditPolicyId` site settings manually as advanced overrides.
+
+**SAML2** — create settings for the provider:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/SAML2/{ProviderName}/MetadataAddress" \
+ --value "<metadata-url-from-user>" \
+ --description "SAML IdP metadata URL"
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/SAML2/{ProviderName}/AuthenticationType" \
+ --value "<site-url>" \
+ --description "Provider identifier for ExternalLogin — MUST match providerIdentifier in authService exactly"
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/SAML2/{ProviderName}/ServiceProviderRealm" \
+ --value "<site-url>" \
+ --description "SP entity ID"
+```
+
+> **CRITICAL for SAML2:** The `AuthenticationType` site setting value and the `providerIdentifier` in the auth service code MUST be character-for-character identical — including protocol (`https://` vs `http://`), trailing slashes, and casing. A mismatch causes login to silently fail. Use the exact same `<site-url>` value in both places.
+
+**WS-Federation** — create settings for the provider:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/WsFederation/{ProviderName}/MetadataAddress" \
+ --value "<metadata-url-from-user>" \
+ --description "WS-Fed metadata URL"
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/WsFederation/{ProviderName}/AuthenticationType" \
+ --value "<provider-realm-or-identifier>" \
+ --description "Provider identifier for ExternalLogin"
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/WsFederation/{ProviderName}/Wtrealm" \
+ --value "<site-url>" \
+ --description "Relying party realm"
+```
+
+> **Note:** The `AuthenticationType` value must match what `resolveProviderIdentifier()` returns in the auth service.
+
+**Local Authentication** — write these settings based on the user's choices from Phase 2.1.
+
+**Settings always written (regardless of registration mode):**
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/LocalLoginEnabled" \
+ --value "true" \
+ --description "Enable local username/password login" \
+ --type boolean
+
+# Set to "true" if the user chose email login, "false" if they chose username login (Phase 2.1)
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/LocalLoginByEmail" \
+ --value "<true-or-false-from-user-choice>" \
+ --description "Login by email (true) or username (false)" \
+ --type boolean
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/ResetPasswordEnabled" \
+ --value "true" \
+ --description "Enable forgot password flow for local accounts" \
+ --type boolean
+```
+
+**Registration mode settings** — deterministic mapping from `REGISTRATION_MODE`:
+
+| `REGISTRATION_MODE` | `Authentication/Registration/Enabled` | `Authentication/Registration/OpenRegistrationEnabled` | `Authentication/Registration/InvitationEnabled` |
+|---|---|---|---|
+| Open registration only | `true` | `true` | `false` |
+| Invitation-only | `true` | `false` | `true` |
+| Both | `true` | `true` | `true` |
+| Registration disabled | `false` | (skip — moot) | (skip — moot) |
+
+> **Do NOT create the `Authentication/Registration/RequireInvitationCode` setting.** It does not exist on the server (the server never reads it). The invitation-only behavior is enforced entirely by `OpenRegistrationEnabled = false` + `InvitationEnabled = true`. Earlier versions of this skill wrote this setting — if you find it in the project's site settings (`.powerpages-site/site-settings/Authentication-Registration-RequireInvitationCode.sitesetting.yml`), **delete the file** as part of the setup.
+
+Example (write each setting that applies — skip Enabled/OpenReg/Invitation when mode is `Registration disabled` except `Enabled=false`):
+
+```powershell
+# For all modes EXCEPT "Registration disabled":
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/Enabled" \
+ --value "true" \
+ --description "Master switch: registration is enabled" \
+ --type boolean
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/OpenRegistrationEnabled" \
+ --value "<true-or-false-from-mode>" \
+ --description "Allow self-registration without an invitation" \
+ --type boolean
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/InvitationEnabled" \
+ --value "<true-or-false-from-mode>" \
+ --description "Enable invitation-based registration" \
+ --type boolean
+
+# For "Registration disabled" mode ONLY:
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/Enabled" \
+ --value "false" \
+ --description "Disable all registration (only existing users can sign in)" \
+ --type boolean
+```
+
+**CAPTCHA settings** — conditional on mode:
+
+| `REGISTRATION_MODE` | `CaptchaEnabled` / `IsCaptchaEnabledForRegistration` | Reason |
+|---|---|---|
+| Open registration only / Both | `false` (with note) | The SPA registration form cannot render the server-side CAPTCHA widget — leaving it on causes registration to silently fail. For production, the site owner should add their own client-side CAPTCHA solution and re-enable the server setting. |
+| Invitation-only | `false` | Invitations already filter users — CAPTCHA adds friction without security value. |
+| Registration disabled | (skip — registration is off) | — |
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/CaptchaEnabled" \
+ --value "false" \
+ --description "Disable server-rendered CAPTCHA — SPA cannot render the widget" \
+ --type boolean
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/IsCaptchaEnabledForRegistration" \
+ --value "false" \
+ --description "Disable server-rendered CAPTCHA on registration form" \
+ --type boolean
+```
+
+**Web API for contact entity — conditional on `INCLUDE_PROFILE_PAGE = true`**
+
+When the maker opted into the profile page (Phase 2.1), enable Web API on the `contact` entity. These settings tell the Power Pages server which entity + fields are reachable via `/_api/{entity}` so the SPA's `getMyProfile` and `updateMyProfile` can read and write the user's contact record.
+
+> **⚠ MANDATORY value for `Webapi/contact/fields`** — use this complete string verbatim. The executor MUST NOT trim it. All 9 entries must be present so the profile form can read AND write every editable field:
+>
+> ```
+> contactid,firstname,lastname,mobilephone,address1_line1,address1_city,address1_stateorprovince,address1_postalcode,address1_country
+> ```
+>
+> This is `contactid` (for record identification) + the 8 editable fields listed in Phase 2.1 / Phase 5.1.9.b. **`emailaddress1` is NOT in this list** because email is displayed read-only in the Account Details section, sourced from `useAuth().user.email` — no Web API roundtrip needed for it. **`middlename` is NOT in this list** because it's intentionally excluded from the simple form. Skipping any entry from the list above causes the corresponding form input to silently fail with a 403 from the Web API.
+
+```powershell
+# Enable Web API on the contact table
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Webapi/contact/enabled" \
+ --value "true" \
+ --description "Enable Web API access for contact table (profile page)" \
+ --type boolean
+
+# Allowed fields — USE THE EXACT VALUE BELOW (9 entries, all lowercase)
+# Case-sensitive: PascalCase or Title Case produces 403 even if the column exists
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Webapi/contact/fields" \
+ --value "contactid,firstname,lastname,mobilephone,address1_line1,address1_city,address1_stateorprovince,address1_postalcode,address1_country" \
+ --description "Fields allowed via Web API for profile page (read + write)"
+```
+
+> **Field name format**: all entries in the `fields` value MUST be lowercase Dataverse LogicalNames. The Web API does case-sensitive literal matching — `FirstName` or `Firstname` will produce a 403 Forbidden response from the server even though the column exists. The list above is correct.
+>
+> **Customizing the field list LATER**: if the maker has custom contact columns they want to expose on the profile page (e.g., `cr123_jobtitle`), they can extend this `fields` value AND add the matching field to the `ProfileContact` interface + form in `UserProfile.tsx` AFTER the skill finishes. The skill itself MUST ship with exactly the 9 entries above — do not add or remove entries during scaffolding.
+
+#### 8.1.x Create Table Permission for Contact (When INCLUDE_PROFILE_PAGE = true)
+
+**Conditional on `INCLUDE_PROFILE_PAGE = true`.** Skip otherwise.
+
+Enabling Web API for the contact table is NOT sufficient — the Power Pages server also requires a matching `adx_entitypermission` record granting the signed-in user read/write access. Without it, all `/_api/contacts(...)` calls return 403 even when the site settings allow the entity.
+
+For the profile-page use case, **Self scope (`756150004`)** is the correct choice — it grants access only to the user's own contact record. The `create-table-permission.js` script validates this and rejects Contact scope for the contact table itself.
+
+**Step 1 — Discover the Authenticated Users web role UUID.**
+
+Phase 1.4 already inventoried web roles. Find the role with `authenticatedusersrole: true` in `.powerpages-site/web-roles/*.yml`. Typical filename: `Authenticated-Users.webrole.yml`. Extract its `id` field.
+
+If no such role exists, warn the user:
+
+> "No 'Authenticated Users' web role found on this site. Profile editing won't work for any user until a role with `authenticatedusersrole: true` exists and is assigned to users. Run `/create-webroles` to add one, then re-run this skill."
+
+Skip the rest of this phase if no role found.
+
+**Step 2 — Create the table permission.**
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-table-permission.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --permissionName "My Profile - Edit Own Contact" \
+ --tableName "contact" \
+ --webRoleIds "<authenticated-users-role-uuid>" \
+ --scope "Self" \
+ --read \
+ --write
+```
+
+The script will create `.powerpages-site/table-permissions/My-Profile-Edit-Own-Contact.tablepermission.yml`:
```yaml
-id: <UUID from generate-uuid.js>
-name: Authentication/Registration/ProfileRedirectEnabled
-value: false
+adx_entitypermission_webrole:
+- <authenticated-users-role-uuid>
+append: false
+appendto: false
+create: false
+delete: false
+entitylogicalname: contact
+entityname: My Profile - Edit Own Contact
+id: <generated-uuid>
+read: true
+scope: 756150004
+write: true
+```
+
+Note: `create: false` + `delete: false` — users can read and update their own contact but NOT create new contacts or delete existing ones. This is the principle-of-least-privilege default for profile editing.
+
+**Permission boundary verification**: with Self scope, even if a user crafts a malicious request like `PATCH /_api/contacts({someone-elses-contact-id})` from DevTools, the server returns 403. Self scope enforces row-level security based on the signed-in user's `contactid` from the session cookie.
+
+**Facebook** — uses `AppId` (not `ClientId`). The App ID was collected in Phase 2.1:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenAuth/Facebook/AppId" \
+ --value "<app-id-from-user>" \
+ --description "Facebook App ID"
+```
+
+**Google** — the Client ID was collected in Phase 2.1:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenAuth/Google/ClientId" \
+ --value "<client-id-from-user>" \
+ --description "Google Client ID"
+```
+
+**Microsoft Account** — the Client ID was collected in Phase 2.1:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenAuth/MicrosoftAccount/ClientId" \
+ --value "<client-id-from-user>" \
+ --description "Microsoft Account Client ID"
+```
+
+#### 8.1.1 Handle Secrets via Azure Key Vault
+
+**Only run this phase if a provider requires a secret.** Skip entirely when none of the configured providers need one.
+
+Providers that **may** require a secret:
+- **OpenID Connect (Generic)** — usually yes (confidential client)
+- **Entra External ID** — **NO by default.** The Phase 2.1 walkthrough configures Entra External ID as a public client using PKCE (no client secret). **Always skip this section for Entra External ID.** If a user later needs a confidential-client setup with a secret, they add `ClientSecret` manually via the Power Pages admin center — covered in Phase 8.5 post-deploy notes.
+- **Microsoft Account / Facebook / Google** — yes (social OAuth requires app secret)
+- **SAML2 / WS-Federation** — no (certificate-based, not secrets)
+- **Local Authentication** — no
+- **Microsoft Entra ID** — no (configured via Power Pages admin center)
+
+**If no provider requires a secret, skip this entire phase 8.1.1 and proceed to the invitation block.**
+
+For secrets (`ClientSecret`, `AppSecret`), **never store them in site setting YAML files or as plain-text environment variables**. Use Azure Key Vault to store secrets, then reference them via Dataverse environment variables with `--type secret`.
+
+**Step 1 — List available Key Vaults:**
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/list-azure-keyvaults.js"
+```
+
+**Step 2 — Select or create a Key Vault:**
+
+If Key Vaults were found, ask which one to use:
+
+| Question | Context |
+|----------|---------|
+| Which Azure Key Vault would you like to use for storing auth secrets? | Present the names from the script output |
+
+If **no Key Vaults are found**:
+
+| Question | Options |
+|----------|---------|
+| No Azure Key Vaults were found. Would you like to create one? | Create a new Key Vault (Recommended), Skip Key Vault — I'll configure secrets later |
+
+**If "Create a new Key Vault"**: Ask for vault name, resource group, and location:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-azure-keyvault.js" \
+ --name "<vault-name>" \
+ --resourceGroup "<resource-group>" \
+ --location "<location>"
+```
+
+**If "Skip Key Vault"**: Skip to "Fallback" below.
+
+**Step 3 — Instruct the user to store each secret in Key Vault:**
+
+Do **not** ask for secret values — they must never pass through the conversation. Present **both** options:
+
+**Option A — Azure CLI (recommended):**
+
+```
+For each secret, run the following command (replacing <YOUR_SECRET_VALUE> with the actual value):
+
+1. <Provider> Client Secret:
+ printf '%s' '<YOUR_SECRET_VALUE>' | node "${CLAUDE_PLUGIN_ROOT}/scripts/store-keyvault-secret.js" \
+ --vaultName "<selected-vault>" \
+ --secretName "<provider>-client-secret"
+```
+
+Tell the user each command outputs a JSON object with a `secretUri` and to share the output so the workflow can continue.
+
+**Option B — Azure Portal:**
+
+```
+1. Go to https://portal.azure.com → Key vaults → <selected-vault> → Secrets
+2. Click "+ Generate/Import"
+3. Name: <provider>-client-secret, Value: paste your secret
+4. Click "Create", then click the secret → current version → copy "Secret Identifier" URI
+5. Share the URI here so the workflow can continue
+```
+
+**Step 4 — Create environment variable in Dataverse (type: secret):**
+
+After the user shares the `secretUri`, create an environment variable that references the Key Vault secret:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-environment-variable.js" "<ENV_URL>" \
+ --schemaName "<prefix_ProviderClientSecret>" \
+ --displayName "<Provider> Client Secret" \
+ --type "secret" \
+ --value "<secretUri-from-step-3>"
+```
+
+**Step 5 — Create site setting for the environment variable:**
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/OpenIdConnect/{ProviderName}/ClientSecret" \
+ --envVarSchema "<prefix_ProviderClientSecret>"
+```
+
+This creates a site setting with `envvar_schema` and `source: 1`, which tells Power Pages to resolve the value from the Dataverse environment variable (backed by Key Vault).
+
+**Repeat Steps 3-5 for each secret required by the selected providers:**
+
+| Provider | Secret Name | Site Setting | Env Var Schema |
+|----------|-------------|--------------|----------------|
+| OIDC / Entra External ID | `{provider}-client-secret` | `Authentication/OpenIdConnect/{ProviderName}/ClientSecret` | `{prefix}_ProviderClientSecret` |
+| Facebook | `facebook-app-secret` | `Authentication/OpenAuth/Facebook/AppSecret` | `{prefix}_FacebookAppSecret` |
+| Google | `google-client-secret` | `Authentication/OpenAuth/Google/ClientSecret` | `{prefix}_GoogleClientSecret` |
+| Microsoft Account | `microsoft-client-secret` | `Authentication/OpenAuth/MicrosoftAccount/ClientSecret` | `{prefix}_MicrosoftClientSecret` |
+
+**Fallback — if user skipped Key Vault:**
+
+If the user chose not to use Key Vault, create environment variables with placeholder values (plain string type, not secret type). The user updates them later via the Power Apps maker portal:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-environment-variable.js" "<ENV_URL>" \
+ --schemaName "<prefix_ProviderClientSecret>" \
+ --displayName "<Provider> Client Secret" \
+ --value "PLACEHOLDER_SET_ACTUAL_VALUE"
+
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "<site-setting-name-from-table-above>" \
+ --envVarSchema "<prefix_ProviderClientSecret>"
+```
+
+Tell the user to update each placeholder via:
+- **Power Apps maker portal** ([make.powerapps.com](https://make.powerapps.com)) → **Solutions** → **Default Solution** → **Environment variables** → find by display name → update the value
+
+Present the list of environment variables that need updating (display name and schema name for each).
+
+**Two-Factor Authentication** — **NOT supported.** The skill must NOT create `Authentication/Registration/TwoFactorEnabled`, `Authentication/Registration/RememberMeEnabled`, or `Authentication/Registration/RememberBrowserEnabled` site settings. Power Pages' built-in 2FA flow uses server-rendered `/Account/Login/SendCode` and `/Account/Login/VerifyCode` pages — the 2FA token state lives in server-side cookies between the credential POST and the code-verification POST, and there's no SPA-equivalent UI we can ship. If 2FA is needed, recommend the user enable it at the identity provider layer (Entra External ID conditional access, B2C user flow MFA, Auth0 Guardian, Okta Verify, etc.) — IdP-level 2FA is transparent to Power Pages and keeps the entire UX inside the IdP's branded experience.
+
+**Terms and Conditions** — when terms are enabled:
+
+> **Prerequisite**: The GDPR/Privacy Extensions solution (`msdynce_PortalPrivacyExtensions`) must be installed in the Dataverse environment. Without it, the server ignores `TermsAgreementEnabled` entirely. Remind the user of this requirement.
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/TermsAgreementEnabled" \
+ --value "true" \
+ --description "Require terms acceptance before accessing the site" \
+ --type boolean
```
+If the user provided a `TermsPublicationDate`:
+
+```powershell
+node "${CLAUDE_PLUGIN_ROOT}/scripts/create-site-setting.js" \
+ --projectRoot "<PROJECT_ROOT>" \
+ --name "Authentication/Registration/TermsPublicationDate" \
+ --value "<ISO-date-from-user>" \
+ --description "Users who accepted before this date will be re-prompted"
+```
+
+**Create the required content snippet** `Account/Signin/TermsAndConditionsCopy` in `.powerpages-site/content-snippets/`. This snippet MUST exist with non-empty content — without it, the server disables terms even if the setting is `true`. The snippet content should match the `TERMS_CONTENT` constant hardcoded in the SPA Terms page.
+
+Check if the content snippet directory exists and create the snippet YAML file. The format follows the existing snippet pattern in `.powerpages-site/content-snippets/`. If a script exists for creating content snippets, use it. Otherwise, create the YAML file manually following the pattern of existing snippets.
+
+Optionally create the other 3 snippets for the server-rendered terms page (used when the SPA isn't loaded, e.g., deep links):
+- `Account/Signin/TermsAndConditionsHeading`
+- `Account/Signin/TermsAndConditionsAgreementText`
+- `Account/Signin/TermsAndConditionsButtonText`
+
#### 8.2 Record Skill Usage
> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
@@ -510,7 +2743,100 @@ Present a summary of everything created:
| Authorization Utils | `src/utils/authorization.ts` | Created |
| Auth Components | `RequireAuth`, `RequireRole` (or framework equivalent) | Created |
| Auth Button | `src/components/AuthButton.tsx` (or framework equivalent) | Created |
-| Site Setting | `ProfileRedirectEnabled = false` | Created |
+| Registration Page | `src/pages/Registration.tsx` (or framework equivalent) — local auth, not disabled | Created (if applicable) |
+| Redeem Invitation Page | `src/pages/RedeemInvitation.tsx` (or framework equivalent) — `Invitation-only` or `Both` modes | Created (if applicable) |
+| Forgot Password Page | `src/pages/ForgotPassword.tsx` (or framework equivalent) — local auth only | Created (if applicable) |
+| Session KeepAlive | `src/hooks/useSessionKeepAlive.ts` (or framework equivalent) — integrated in Layout | Created |
+| Terms Page | `src/pages/Terms.tsx` (or framework equivalent) — when terms enabled | Created (if applicable) |
+| Terms Snippet | `Account/Signin/TermsAndConditionsCopy` content snippet | Created (if applicable) |
+| Reset Password Page | `src/pages/ResetPassword.tsx` (or framework equivalent) — local auth only | Created (if applicable) |
+| User Profile Page | `src/pages/UserProfile.tsx` (or framework equivalent) — when `INCLUDE_PROFILE_PAGE = true`. Plus AuthButton dropdown, `getMyProfile`/`updateMyProfile` in authService, `/user-profile` route | Created (if applicable) |
+| Shell Header | `Code-Site-Shell-Header` web template — redirects server auth pages to SPA | Created (survives uploads) |
+| Site Setting | `ProfileRedirectEnabled = false`, `Enabled`, `OpenRegistrationEnabled`, `InvitationEnabled` per registration mode | Created |
+| Web API Site Settings | `Webapi/contact/enabled = true`, `Webapi/contact/fields = ...` — when `INCLUDE_PROFILE_PAGE = true` | Created (if applicable) |
+| Table Permission | `My Profile - Edit Own Contact` (contact, Self scope, read+write, Authenticated Users role) — when `INCLUDE_PROFILE_PAGE = true` | Created (if applicable) |
+
+#### 8.3.5 Generate HTML Setup Report
+
+After the summary, generate an HTML setup report at `<PROJECT_ROOT>/docs/auth-setup-report.html` that captures every decision and artifact from this run. The report is opened in the user's browser as a durable, shareable record they can review later.
+
+**Why**: This skill makes many composing decisions (provider choice, registration mode, profile mapping, contact linking, profile page, terms, federated logout, etc.). A side-by-side HTML report makes it easy for the maker to audit the full configuration in one place — much more scannable than the chat summary above. It also gives reviewers and teammates a single artifact to look at without re-running the skill.
+
+**1. Build the data payload.** Construct a JSON object with the following keys and write it to a temp file:
+
+```json
+{
+ "META_DATA": {
+ "siteName": "<SITE_NAME>",
+ "reportDate": "<YYYY-MM-DD>",
+ "framework": "<React|Vue|Angular|Astro>",
+ "nextStepsHtml": "<HTML string — the same provider-specific guidance from 8.5, formatted as an <ol>>"
+ },
+ "PROVIDERS_DATA": [
+ {
+ "type": "Entra ID | Entra External ID | OIDC | SAML2 | WS-Federation | Local | Social (Microsoft|Facebook|Google)",
+ "displayName": "<friendly name shown in the login UI>",
+ "name": "<ProviderName used in site setting keys>",
+ "identifier": "<providerIdentifier / authority URL / issuer URI>",
+ "authority": "<Authority site-setting value, if applicable>",
+ "clientId": "<ClientId site-setting value, if applicable>",
+ "redirectUri": "<Computed redirect URI, if applicable>",
+ "scopes": "<Scopes site-setting value, if applicable>",
+ "registrationClaimsMapping": "<RegistrationClaimsMapping value, if applicable>",
+ "loginClaimsMapping": "<LoginClaimsMapping value, or null when sync = First sign-in only>",
+ "contactLinking": "Link to existing contact by email | Create a new contact",
+ "profileSync": "First sign-in only | Both",
+ "federatedLogout": "Enabled | Disabled",
+ "isPrimary": true | false
+ }
+ ],
+ "LOCAL_AUTH_DATA": {
+ "loginBy": "Email | Username",
+ "registrationMode": "Open | Invitation-only | Both | Disabled",
+ "resetPasswordEnabled": true | false,
+ "emailConfirmationEnabled": true | false
+ },
+ "OPTIONAL_FEATURES_DATA": {
+ "profilePage": true | false,
+ "termsAndConditions": true | false,
+ "termsEnforced": true | false,
+ "federatedLogout": true | false,
+ "sessionKeepAlive": true | false
+ },
+ "SITE_SETTINGS_DATA": [
+ { "name": "Authentication/Registration/ProfileRedirectEnabled", "value": "false" }
+ ],
+ "TABLE_PERMISSIONS_DATA": [
+ { "name": "My Profile - Edit Own Contact", "table": "contact", "scope": "Self (756150004)", "read": true, "write": true, "create": false, "delete": false }
+ ],
+ "FILES_DATA": [
+ { "path": "src/services/authService.ts", "action": "Created | Updated", "notes": "<short description>" }
+ ]
+}
+```
+
+- Set `LOCAL_AUTH_DATA` to `null` if local auth was not configured.
+- Include ALL site settings the skill created in `SITE_SETTINGS_DATA` (Phase 8.1) — `ProfileRedirectEnabled`, every `Authentication/{Type}/{Name}/...` block, `Webapi/contact/*` when applicable, etc. Mask any settings whose name contains `Secret` (replace value with `***` — secrets must not appear in the report).
+- Include every YAML/code file the skill created or updated in `FILES_DATA`. Use action `"Created"` for new files, `"Updated"` for edits.
+- `nextStepsHtml` should mirror the guidance in section 8.5 below, formatted as an `<ol>...</ol>` with `<code>` tags around commands. Only include the steps relevant to the providers actually configured.
+
+**2. Render the report.** Run:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/scripts/render-auth-report.js" \
+ --output "<PROJECT_ROOT>/docs/auth-setup-report.html" \
+ --data "<path-to-temp-data.json>"
+```
+
+The renderer refuses to overwrite an existing file. If a previous report already exists at that path, append a date suffix: `auth-setup-report-2026-05-27.html`.
+
+**3. Open the report in the browser** (best-effort — never block the skill flow on this):
+
+- Windows: `start "" "<PROJECT_ROOT>/docs/auth-setup-report.html"`
+- macOS: `open "<PROJECT_ROOT>/docs/auth-setup-report.html"`
+- Linux: `xdg-open "<PROJECT_ROOT>/docs/auth-setup-report.html"`
+
+**4. Tell the user** the absolute path of the report file so they can open it manually if the browser launch failed. Phrasing example: *"I've written a full setup report to `<path>` and opened it in your browser. You can revisit this file any time to see every decision and artifact from this run."*
#### 8.4 Ask to Deploy
@@ -528,10 +2854,23 @@ Use `AskUserQuestion`:
#### 8.5 Post-Deploy Notes
-After deployment (or if skipped), remind the user:
+After deployment (or if skipped), remind the user with provider-specific guidance:
- **Test on deployed site**: Auth only works on the deployed Power Pages site, not on `localhost`
-- **Entra ID configuration**: The site's identity provider must be configured in the Power Pages admin center to use Microsoft Entra ID
+- **Identity provider configuration**: Provider-specific setup is required:
+ - **Entra ID**: Configure the identity provider in the Power Pages admin center
+ - **OpenID Connect**: Register a client application with the OIDC provider and update the `ClientId` site setting. Set the redirect URI in the provider to `{site-url}/signin-{provider}`
+ - **SAML2**: Register the site as a service provider (SP) with the SAML IdP. The `ServiceProviderRealm` and `AssertionConsumerServiceUrl` must match the site URL
+ - **WS-Federation**: Register the site as a relying party with the WS-Fed provider
+ - **Local Authentication**: No external provider needed — users register and log in with username/password directly on the site
+ - **Microsoft Account**: Register an application in the Azure portal and update the `ClientSecret` environment variable via the Power Apps maker portal -- do not commit secrets to source control
+ - **Facebook**: Register an application in the Facebook Developer Console and update the `AppSecret` environment variable via the Power Apps maker portal -- do not commit secrets to source control
+ - **Google**: Register an application in the Google Cloud Console and update the `ClientSecret` environment variable via the Power Apps maker portal -- do not commit secrets to source control
+ - **Entra External ID**: Register the application in the Entra External ID tenant. Update the `ClientId` site setting. Set the redirect URI to `{site-url}/signin-{provider}`. The authority URL may use `{tenant}.ciamlogin.com` or a custom domain.
+- **Auth failure handling (keep users in SPA)**: When OIDC/SAML2/WS-Fed auth fails, the server redirects to `/Account/Login/ExternalAuthenticationFailed` — a server-rendered page that breaks the SPA. To keep users in the SPA on failure, edit the Dataverse content snippets `Account/Register/ExternalAuthenticationFailed` and `Account/Register/ExternalAuthenticationFailed/AccessDenied` in the Power Pages admin center to inject a `<script>` that redirects to `/login?message={error-code}`. The SPA's `getAuthError()` will then display the error inline. See authentication-reference.md for the exact script.
+- **User profile display**: After login, the auth service's `getUserDisplayName()` falls back through `firstName + lastName` → `firstName` → `lastName` → `email` → `userName` → `'User'`. **Email beats userName** because for external providers (Entra External ID, OIDC) the `userName` field is the OIDC subject identifier — a long opaque string like `vs25QwNe1ZAHqlWK1Naw9dVEBe-TbF5tZEpb0XjAEZQ` that's ugly and meaningless in a navigation bar. Power Pages populates `firstName`/`lastName`/`email` from standard OIDC claims (`given_name`, `family_name`, `email`). Entra External ID user flows often don't include `given_name`/`family_name` in the returned claims by default — if you want names populated, ensure the user flow has both attributes selected under "User attributes to collect" AND "Application claims" / "User attributes to return as claims" (see Phase 2.1 Entra External ID Step 3). The `email` claim is almost always emitted, so emails reliably populate even when names don't. `getUserInitials()` follows the same priority chain using the first character of each fallback source.
+- **Two-Factor Authentication**: This skill does NOT scaffold Power Pages built-in 2FA — the `SendCode`/`VerifyCode` flow is server-rendered and cannot be integrated into the SPA experience. For MFA needs, configure it at the identity provider layer (Entra External ID conditional access, B2C user flow MFA, Auth0 Guardian, Okta Verify, etc.) — IdP-level MFA is transparent to Power Pages and stays inside the IdP's branded experience.
+- **Invitation-based registration**: If invitations are enabled (`REGISTRATION_MODE` is `Invitation-only` or `Both`), generate invitation codes by creating Invitation records in Dataverse (`adx_invitation` table) — the `adx_invitationcode` field is the value to use in the URL. Share invitation links in the format `{site-url}/Account/Login/RedeemInvitation?invitation={code}` — the Code-Site-Shell-Header script redirects this to the SPA `/redeem-invitation?invitation={code}` route automatically. After redemption, the invitation is linked to the user's contact (single-redemption invitations are marked redeemed; group invitations track redeemed contacts in a collection). Terms acceptance and external login flows preserve the invitation code through the auth flow.
- **Assign web roles**: Users must be assigned appropriate web roles in the Power Pages admin center
- **Table permissions**: Client-side auth checks are for UX only — configure server-side table permissions via `/integrate-webapi` for actual data security
- **Local development**: The auth service includes mock data for testing on localhost — remove or disable before production
diff --git a/plugins/power-pages/skills/setup-auth/assets/auth-report.html b/plugins/power-pages/skills/setup-auth/assets/auth-report.html
new file mode 100644
index 000000000..1857fb04f
--- /dev/null
+++ b/plugins/power-pages/skills/setup-auth/assets/auth-report.html
@@ -0,0 +1,485 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8"/>
+<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
+<title>Authentication Setup Report</title>
+<style>
+:root {
+ --bg:#faf9f8; --surface:#ffffff; --surface2:#f3f2f1; --surface3:#edebe9;
+ --border:#e1dfdd; --border-light:#c8c6c4;
+ --text:#323130; --text-dim:#605e5c; --text-bright:#201f1e;
+ --accent:#0078d4; --accent-bg:#0078d40a; --accent-border:#0078d425;
+ --pass:#107c10; --pass-bg:#107c100a; --pass-border:#107c1025;
+ --warning:#ca5010; --warning-bg:#ca50100a; --warning-border:#ca501025;
+ --purple:#8764b8; --purple-bg:#8764b80a; --purple-border:#8764b825;
+ --mono:'Cascadia Code','Consolas',monospace;
+ --sans:'Segoe UI','Segoe UI Web (West European)',-apple-system,system-ui,sans-serif;
+ --radius:8px; --radius-sm:4px;
+ --shadow-4:0 1.6px 3.6px 0 rgba(0,0,0,0.132),0 0.3px 0.9px 0 rgba(0,0,0,0.108);
+ --shadow-8:0 3.2px 7.2px 0 rgba(0,0,0,0.132),0 0.6px 1.8px 0 rgba(0,0,0,0.108);
+}
+*{margin:0;padding:0;box-sizing:border-box;}
+html{scroll-behavior:smooth;}
+body{font-family:var(--sans);background:var(--bg);color:var(--text);font-size:14px;line-height:1.6;}
+
+/* Top bar */
+.topbar{z-index:100;background:var(--surface);box-shadow:var(--shadow-4);padding:14px 28px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;}
+.topbar-left{display:flex;align-items:center;gap:14px;}
+.logo{width:36px;height:36px;object-fit:contain;display:block;flex-shrink:0;}
+.topbar-title{font-size:16px;font-weight:700;color:var(--text-bright);}
+.topbar-sub{font-size:11px;color:var(--text-dim);margin-top:1px;}
+.topbar-right{font-size:11px;color:var(--text-dim);font-family:var(--mono);}
+
+/* Layout: sidebar + content */
+.layout{display:flex;min-height:calc(100vh - 65px);}
+
+/* Sidebar */
+.sidebar{width:220px;background:var(--surface);border-right:1px solid var(--border);padding:20px 0;flex-shrink:0;position:sticky;top:0;align-self:flex-start;}
+.sidebar-heading{font-size:10px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;padding:0 22px;margin-bottom:8px;}
+.nav-btn{display:flex;align-items:center;gap:10px;width:100%;padding:11px 22px;background:none;border:none;border-left:2px solid transparent;color:var(--text-dim);font-size:13px;font-weight:500;cursor:pointer;font-family:var(--sans);text-align:left;transition:all 0.15s;position:relative;}
+.nav-btn:hover{color:var(--text);background:var(--surface2);}
+.nav-btn.active{color:var(--accent);font-weight:600;border-left-color:var(--accent);background:var(--accent-bg);}
+.nav-btn .nav-icon{font-size:15px;width:18px;text-align:center;opacity:0.6;}
+.nav-btn.active .nav-icon{opacity:1;}
+.nav-badge{margin-left:auto;font-size:10px;font-family:var(--mono);padding:1px 7px;border-radius:8px;font-weight:700;color:var(--text-dim);background:var(--surface2);border:1px solid var(--border);}
+.nav-btn.active .nav-badge{color:var(--accent);background:var(--accent-bg);border-color:var(--accent-border);}
+
+/* Content */
+.content{flex:1;padding:32px 40px 60px;max-width:1100px;min-width:0;}
+.section{display:none;}
+.section.active{display:block;animation:fadeIn 0.2s ease;}
+@keyframes fadeIn{from{opacity:0;transform:translateY(6px);}to{opacity:1;transform:translateY(0);}}
+
+h1{font-size:24px;font-weight:800;color:var(--text-bright);letter-spacing:-0.4px;margin-bottom:6px;}
+.page-sub{font-size:13px;color:var(--text-dim);margin-bottom:24px;}
+h2{font-size:18px;font-weight:700;color:var(--text-bright);margin-bottom:6px;letter-spacing:-0.2px;}
+.section-desc{font-size:13px;color:var(--text-dim);margin-bottom:18px;}
+h3{font-size:14px;font-weight:700;color:var(--text-bright);margin-bottom:8px;}
+p{margin-bottom:10px;}
+
+.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin-bottom:24px;}
+.stat-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 16px;text-align:center;box-shadow:var(--shadow-4);}
+.stat-num{font-size:28px;font-weight:800;font-family:var(--mono);line-height:1;color:var(--accent);}
+.stat-label{font-size:10px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-top:6px;}
+
+.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 20px;margin-bottom:12px;}
+.card.muted{background:var(--surface2);}
+.empty{color:var(--text-dim);font-style:italic;font-size:13px;}
+
+.kv{display:grid;grid-template-columns:170px 1fr;gap:8px 16px;font-size:13px;align-items:baseline;}
+.kv .k{font-size:11px;font-weight:700;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;}
+.kv .v{color:var(--text);word-break:break-word;}
+.kv .v code{font-family:var(--mono);font-size:12px;background:var(--surface2);padding:1px 6px;border-radius:3px;border:1px solid var(--border);}
+
+.tag{display:inline-block;font-size:10px;font-weight:700;padding:2px 8px;border-radius:3px;font-family:var(--mono);text-transform:uppercase;letter-spacing:0.5px;margin-right:6px;}
+.tag-accent{color:var(--accent);background:var(--accent-bg);border:1px solid var(--accent-border);}
+.tag-pass{color:var(--pass);background:var(--pass-bg);border:1px solid var(--pass-border);}
+.tag-warning{color:var(--warning);background:var(--warning-bg);border:1px solid var(--warning-border);}
+.tag-purple{color:var(--purple);background:var(--purple-bg);border:1px solid var(--purple-border);}
+.tag-dim{color:var(--text-dim);background:var(--surface2);border:1px solid var(--border);}
+
+table{width:100%;border-collapse:collapse;font-size:13px;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;}
+th{text-align:left;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:0.8px;color:var(--text-dim);padding:10px 14px;background:var(--surface2);border-bottom:1px solid var(--border);}
+td{padding:10px 14px;border-bottom:1px solid var(--border);vertical-align:top;}
+tr:last-child td{border-bottom:none;}
+td code{font-family:var(--mono);font-size:12px;background:var(--surface2);padding:1px 6px;border-radius:3px;border:1px solid var(--border);}
+td.col-fixed{width:38%;white-space:nowrap;}
+
+.next-steps{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:18px 22px;}
+.next-steps ol{margin-left:18px;}
+.next-steps li{margin-bottom:8px;line-height:1.6;}
+.next-steps code{font-family:var(--mono);font-size:12px;background:var(--surface2);padding:1px 6px;border-radius:3px;border:1px solid var(--border);}
+
+@media (max-width: 760px) {
+ .layout{flex-direction:column;}
+ .sidebar{width:100%;border-right:none;border-bottom:1px solid var(--border);position:static;display:flex;flex-wrap:wrap;padding:8px;gap:4px;}
+ .sidebar-heading{display:none;}
+ .nav-btn{width:auto;flex:1 1 auto;padding:8px 12px;border-left:none;border-bottom:2px solid transparent;}
+ .nav-btn.active{border-left-color:transparent;border-bottom-color:var(--accent);}
+ .stats-grid{grid-template-columns:repeat(2,1fr);}
+}
+</style>
+</head>
+<body>
+<div class="topbar">
+ <div class="topbar-left">
+ <img class="logo" src="./power-pages-icon.png" alt="" onerror="this.style.display='none'"/>
+ <div>
+ <div class="topbar-title">Authentication Setup Report</div>
+ <div class="topbar-sub">setup-auth · Power Pages</div>
+ </div>
+ </div>
+ <div class="topbar-right" id="topbar-date"></div>
+</div>
+
+<div class="layout">
+ <nav class="sidebar" role="navigation" aria-label="Report sections">
+ <div class="sidebar-heading">Sections</div>
+ <button type="button" class="nav-btn active" data-tab="overview">
+ <span class="nav-icon" aria-hidden="true">▣</span><span>Overview</span>
+ </button>
+ <button type="button" class="nav-btn" data-tab="providers">
+ <span class="nav-icon" aria-hidden="true">⌬</span><span>Providers</span>
+ <span class="nav-badge" id="badge-providers">0</span>
+ </button>
+ <button type="button" class="nav-btn" data-tab="local-auth">
+ <span class="nav-icon" aria-hidden="true">⛛</span><span>Local Auth</span>
+ </button>
+ <button type="button" class="nav-btn" data-tab="features">
+ <span class="nav-icon" aria-hidden="true">✦</span><span>Features</span>
+ </button>
+ <button type="button" class="nav-btn" data-tab="settings">
+ <span class="nav-icon" aria-hidden="true">⚙</span><span>Site Settings</span>
+ <span class="nav-badge" id="badge-settings">0</span>
+ </button>
+ <button type="button" class="nav-btn" data-tab="permissions">
+ <span class="nav-icon" aria-hidden="true">⌭</span><span>Permissions</span>
+ <span class="nav-badge" id="badge-permissions">0</span>
+ </button>
+ <button type="button" class="nav-btn" data-tab="files">
+ <span class="nav-icon" aria-hidden="true">⌹</span><span>Files</span>
+ <span class="nav-badge" id="badge-files">0</span>
+ </button>
+ <button type="button" class="nav-btn" data-tab="next-steps">
+ <span class="nav-icon" aria-hidden="true">→</span><span>Next Steps</span>
+ </button>
+ </nav>
+
+ <main class="content">
+ <section class="section active" id="tab-overview">
+ <h1 id="hdr-site"></h1>
+ <div class="page-sub" id="hdr-sub"></div>
+ <div class="stats-grid" id="stats"></div>
+ <div id="overview-detail"></div>
+ </section>
+
+ <section class="section" id="tab-providers">
+ <h2>Identity Providers</h2>
+ <div class="section-desc">Each card shows the provider's identifier, claims mapping, and contact-linking behavior.</div>
+ <div id="providers"></div>
+ </section>
+
+ <section class="section" id="tab-local-auth">
+ <h2>Local Authentication</h2>
+ <div class="section-desc">Username/password sign-in configured directly on the site (no external IdP).</div>
+ <div id="local-auth"></div>
+ </section>
+
+ <section class="section" id="tab-features">
+ <h2>Optional Features</h2>
+ <div class="section-desc">Feature flags chosen during setup: profile page, Terms & Conditions, federated logout, and session keep-alive.</div>
+ <div id="optional-features"></div>
+ </section>
+
+ <section class="section" id="tab-settings">
+ <h2>Site Settings Created</h2>
+ <div class="section-desc">Every Power Pages site setting written by this run. Values whose name contains "Secret" are masked.</div>
+ <div id="site-settings"></div>
+ </section>
+
+ <section class="section" id="tab-permissions">
+ <h2>Table Permissions</h2>
+ <div class="section-desc">Server-side Dataverse table permissions provisioned for SPA Web API access.</div>
+ <div id="table-permissions"></div>
+ </section>
+
+ <section class="section" id="tab-files">
+ <h2>Files Created or Updated</h2>
+ <div class="section-desc">Every SPA / Power Pages site file the skill created or modified during this run.</div>
+ <div id="files"></div>
+ </section>
+
+ <section class="section" id="tab-next-steps">
+ <h2>Next Steps</h2>
+ <div class="section-desc">Follow these steps to finish wiring up the configured authentication on your deployed site.</div>
+ <div class="next-steps" id="next-steps"></div>
+ </section>
+ </main>
+</div>
+
+<footer style="position:fixed;bottom:0;left:0;right:0;text-align:center;padding:10px;font-size:12px;color:#605e5c;border-top:1px solid #c8c6c4;background:#ffffff;z-index:100;">AI-generated content may be incorrect</footer>
+
+<script>
+// All user-controlled data goes through .textContent — never innerHTML with
+// unsanitized values. META.nextStepsHtml is the one exception: it's authored by
+// the skill (not the user) and intentionally renders as HTML.
+
+const META = __META_DATA__;
+const PROVIDERS = __PROVIDERS_DATA__;
+const LOCAL_AUTH = __LOCAL_AUTH_DATA__;
+const OPTIONAL_FEATURES = __OPTIONAL_FEATURES_DATA__;
+const SITE_SETTINGS = __SITE_SETTINGS_DATA__;
+const TABLE_PERMISSIONS = __TABLE_PERMISSIONS_DATA__;
+const FILES = __FILES_DATA__;
+
+const SITE_NAME = META.siteName || '';
+const REPORT_DATE = META.reportDate || '';
+const FRAMEWORK = META.framework || '';
+const NEXT_STEPS_HTML = META.nextStepsHtml || '';
+
+document.title = 'Authentication Setup Report — ' + (SITE_NAME || 'Power Pages');
+document.getElementById('topbar-date').textContent = REPORT_DATE;
+
+function el(tag, props, ...children) {
+ const e = document.createElement(tag);
+ if (props) for (const k in props) {
+ if (k === 'class') e.className = props[k];
+ else if (k === 'text') e.textContent = props[k];
+ else e.setAttribute(k, props[k]);
+ }
+ for (const c of children) {
+ if (c == null) continue;
+ if (typeof c === 'string') e.appendChild(document.createTextNode(c));
+ else e.appendChild(c);
+ }
+ return e;
+}
+
+function kv(label, value, isCode) {
+ if (value == null || value === '') return null;
+ const v = el('div', { class: 'v' });
+ if (isCode) v.appendChild(el('code', { text: String(value) }));
+ else v.textContent = String(value);
+ return [el('div', { class: 'k', text: label }), v];
+}
+
+function emptyCard(msg) {
+ return el('div', { class: 'card muted' }, el('div', { class: 'empty', text: msg }));
+}
+
+// --- Header / Overview ---
+document.getElementById('hdr-site').textContent = SITE_NAME || '(site)';
+document.getElementById('hdr-sub').textContent =
+ 'Configured ' + (PROVIDERS.length === 1 ? '1 identity provider' : PROVIDERS.length + ' identity providers')
+ + (FRAMEWORK ? ' · ' + FRAMEWORK : '');
+
+// --- Stats grid ---
+const stats = [
+ { num: PROVIDERS.length, label: 'Providers' },
+ { num: SITE_SETTINGS.length, label: 'Site Settings' },
+ { num: TABLE_PERMISSIONS.length, label: 'Table Permissions' },
+ { num: FILES.length, label: 'Files' },
+];
+const statsEl = document.getElementById('stats');
+for (const s of stats) {
+ statsEl.appendChild(el('div', { class: 'stat-card' },
+ el('div', { class: 'stat-num', text: String(s.num) }),
+ el('div', { class: 'stat-label', text: s.label }),
+ ));
+}
+
+// --- Sidebar badges ---
+document.getElementById('badge-providers').textContent = String(PROVIDERS.length);
+document.getElementById('badge-settings').textContent = String(SITE_SETTINGS.length);
+document.getElementById('badge-permissions').textContent = String(TABLE_PERMISSIONS.length);
+document.getElementById('badge-files').textContent = String(FILES.length);
+
+// --- Overview detail (highlights jump to other tabs) ---
+const overviewDetail = document.getElementById('overview-detail');
+const overviewCard = el('div', { class: 'card' });
+overviewCard.appendChild(el('h3', { text: 'Highlights' }));
+const ul = el('ul');
+ul.style.cssText = 'margin-left:18px;font-size:13px;color:var(--text);';
+function addHighlight(text) { ul.appendChild(el('li', { text: text })); }
+if (PROVIDERS.length) addHighlight(`${PROVIDERS.length} identity provider${PROVIDERS.length === 1 ? '' : 's'} configured.`);
+if (LOCAL_AUTH) addHighlight(`Local authentication enabled (login by ${LOCAL_AUTH.loginBy || 'username'}, registration: ${LOCAL_AUTH.registrationMode || 'unspecified'}).`);
+if (OPTIONAL_FEATURES) {
+ if (OPTIONAL_FEATURES.profilePage) addHighlight('Profile page (/user-profile) was scaffolded.');
+ if (OPTIONAL_FEATURES.termsAndConditions) {
+ addHighlight(OPTIONAL_FEATURES.termsEnforced
+ ? 'Terms & Conditions enabled — Privacy Extensions solution detected, enforcement will work.'
+ : 'Terms & Conditions scaffolded — Privacy Extensions solution NOT detected, enforcement will be silently ignored until the solution is installed.');
+ }
+ if (OPTIONAL_FEATURES.federatedLogout) addHighlight('Federated (RP-initiated) logout enabled — users will be signed out of the identity provider on sign-out.');
+}
+if (!ul.children.length) addHighlight('No optional features enabled. Identity provider scaffolding is the only output of this run.');
+overviewCard.appendChild(ul);
+overviewDetail.appendChild(overviewCard);
+
+// --- Providers ---
+const provEl = document.getElementById('providers');
+if (PROVIDERS.length === 0) {
+ provEl.appendChild(emptyCard('No identity providers were configured.'));
+} else {
+ for (const p of PROVIDERS) {
+ const tags = [];
+ if (p.type) tags.push(el('span', { class: 'tag tag-accent', text: p.type }));
+ if (p.isPrimary) tags.push(el('span', { class: 'tag tag-purple', text: 'Primary' }));
+ const card = el('div', { class: 'card' });
+ card.appendChild(el('h3', { text: p.displayName || p.name || '(provider)' }));
+ if (tags.length) {
+ const tagRow = el('div');
+ tagRow.style.marginBottom = '10px';
+ for (const t of tags) tagRow.appendChild(t);
+ card.appendChild(tagRow);
+ }
+ const grid = el('div', { class: 'kv' });
+ const rows = [
+ kv('Identifier', p.identifier, true),
+ kv('Authority', p.authority, true),
+ kv('Client ID', p.clientId, true),
+ kv('Redirect URI', p.redirectUri, true),
+ kv('Scopes', p.scopes),
+ kv('Registration mapping', p.registrationClaimsMapping, true),
+ kv('Login mapping', p.loginClaimsMapping, true),
+ kv('Contact linking', p.contactLinking),
+ kv('Profile sync', p.profileSync),
+ kv('Federated logout', p.federatedLogout),
+ ].filter(Boolean);
+ for (const [k, v] of rows) { grid.appendChild(k); grid.appendChild(v); }
+ card.appendChild(grid);
+ provEl.appendChild(card);
+ }
+}
+
+// --- Local auth ---
+const localEl = document.getElementById('local-auth');
+if (!LOCAL_AUTH) {
+ localEl.appendChild(emptyCard('Local authentication was not configured for this site.'));
+} else {
+ const card = el('div', { class: 'card' });
+ const grid = el('div', { class: 'kv' });
+ const rows = [
+ kv('Login by', LOCAL_AUTH.loginBy),
+ kv('Registration mode', LOCAL_AUTH.registrationMode),
+ kv('Reset password', LOCAL_AUTH.resetPasswordEnabled ? 'Enabled' : 'Disabled'),
+ kv('Email confirmation', LOCAL_AUTH.emailConfirmationEnabled ? 'Enabled' : 'Disabled'),
+ ].filter(Boolean);
+ for (const [k, v] of rows) { grid.appendChild(k); grid.appendChild(v); }
+ card.appendChild(grid);
+ localEl.appendChild(card);
+}
+
+// --- Optional features ---
+const featEl = document.getElementById('optional-features');
+if (!OPTIONAL_FEATURES || Object.keys(OPTIONAL_FEATURES).length === 0) {
+ featEl.appendChild(emptyCard('No optional features were enabled.'));
+} else {
+ const card = el('div', { class: 'card' });
+ const grid = el('div', { class: 'kv' });
+ const featureRows = [
+ ['Profile page', OPTIONAL_FEATURES.profilePage, '/user-profile SPA page with edit form'],
+ ['Terms & Conditions', OPTIONAL_FEATURES.termsAndConditions, OPTIONAL_FEATURES.termsEnforced ? 'Enabled — solution detected' : 'Scaffolded but NOT enforced (Privacy Extensions solution missing)'],
+ ['Federated logout', OPTIONAL_FEATURES.federatedLogout, 'Signs the user out of the identity provider as well'],
+ ['Session keep-alive', OPTIONAL_FEATURES.sessionKeepAlive, 'Pings the server periodically to extend the session'],
+ ];
+ for (const [label, enabled, note] of featureRows) {
+ if (enabled == null) continue;
+ grid.appendChild(el('div', { class: 'k', text: label }));
+ const v = el('div', { class: 'v' });
+ v.appendChild(el('span', {
+ class: 'tag ' + (enabled ? 'tag-pass' : 'tag-dim'),
+ text: enabled ? 'Enabled' : 'Disabled',
+ }));
+ if (enabled && note) v.appendChild(document.createTextNode(' ' + note));
+ grid.appendChild(v);
+ }
+ card.appendChild(grid);
+ featEl.appendChild(card);
+}
+
+// --- Site settings table ---
+const settingsEl = document.getElementById('site-settings');
+if (SITE_SETTINGS.length === 0) {
+ settingsEl.appendChild(emptyCard('No site settings were created.'));
+} else {
+ const t = el('table');
+ t.appendChild(el('thead', null, el('tr', null,
+ el('th', { text: 'Setting' }),
+ el('th', { text: 'Value' }),
+ )));
+ const tbody = el('tbody');
+ for (const s of SITE_SETTINGS) {
+ tbody.appendChild(el('tr', null,
+ el('td', { class: 'col-fixed' }, el('code', { text: s.name })),
+ el('td', null, s.value === '' ? el('span', { class: 'empty', text: '(empty)' }) : el('code', { text: String(s.value) })),
+ ));
+ }
+ t.appendChild(tbody);
+ settingsEl.appendChild(t);
+}
+
+// --- Table permissions table ---
+const permsEl = document.getElementById('table-permissions');
+if (TABLE_PERMISSIONS.length === 0) {
+ permsEl.appendChild(emptyCard('No table permissions were created.'));
+} else {
+ const t = el('table');
+ t.appendChild(el('thead', null, el('tr', null,
+ el('th', { text: 'Name' }),
+ el('th', { text: 'Table' }),
+ el('th', { text: 'Scope' }),
+ el('th', { text: 'Privileges' }),
+ )));
+ const tbody = el('tbody');
+ for (const p of TABLE_PERMISSIONS) {
+ const privs = ['read', 'write', 'create', 'delete', 'append', 'appendto']
+ .filter(k => p[k]).join(', ') || '(none)';
+ tbody.appendChild(el('tr', null,
+ el('td', { text: p.name || '' }),
+ el('td', null, el('code', { text: p.table || '' })),
+ el('td', { text: p.scope || '' }),
+ el('td', { text: privs }),
+ ));
+ }
+ t.appendChild(tbody);
+ permsEl.appendChild(t);
+}
+
+// --- Files table ---
+const filesEl = document.getElementById('files');
+if (FILES.length === 0) {
+ filesEl.appendChild(emptyCard('No SPA files were created or updated.'));
+} else {
+ const t = el('table');
+ t.appendChild(el('thead', null, el('tr', null,
+ el('th', { text: 'Path' }),
+ el('th', { text: 'Action' }),
+ el('th', { text: 'Notes' }),
+ )));
+ const tbody = el('tbody');
+ for (const f of FILES) {
+ const actionClass = f.action === 'Created' ? 'tag-pass'
+ : f.action === 'Updated' ? 'tag-accent'
+ : 'tag-dim';
+ tbody.appendChild(el('tr', null,
+ el('td', null, el('code', { text: f.path || '' })),
+ el('td', null, el('span', { class: 'tag ' + actionClass, text: f.action || '' })),
+ el('td', { text: f.notes || '' }),
+ ));
+ }
+ t.appendChild(tbody);
+ filesEl.appendChild(t);
+}
+
+// --- Next steps (HTML, skill-authored) ---
+document.getElementById('next-steps').innerHTML = NEXT_STEPS_HTML || '<p class="empty">No follow-up actions recorded.</p>';
+
+// --- Tab switching ---
+const navButtons = document.querySelectorAll('.nav-btn');
+const sections = document.querySelectorAll('.section');
+
+function activateTab(tabId) {
+ for (const btn of navButtons) {
+ btn.classList.toggle('active', btn.dataset.tab === tabId);
+ }
+ for (const sec of sections) {
+ sec.classList.toggle('active', sec.id === 'tab-' + tabId);
+ }
+ // Update the URL hash so users can deep-link to a tab, but don't push a
+ // history entry (replaceState) so the back button stays useful.
+ if (history.replaceState) history.replaceState(null, '', '#' + tabId);
+}
+
+for (const btn of navButtons) {
+ btn.addEventListener('click', () => activateTab(btn.dataset.tab));
+}
+
+// Honor deep-link hash on load (e.g., file://.../auth-setup-report.html#settings)
+const initialHash = (location.hash || '').replace(/^#/, '');
+const validTabs = new Set(['overview','providers','local-auth','features','settings','permissions','files','next-steps']);
+if (initialHash && validTabs.has(initialHash)) activateTab(initialHash);
+</script>
+</body>
+</html>
diff --git a/plugins/power-pages/skills/setup-auth/references/authentication-reference.md b/plugins/power-pages/skills/setup-auth/references/authentication-reference.md
index 25e5ca599..6928539c0 100644
--- a/plugins/power-pages/skills/setup-auth/references/authentication-reference.md
+++ b/plugins/power-pages/skills/setup-auth/references/authentication-reference.md
@@ -1,24 +1,237 @@
# Authentication Reference
-This document provides the complete implementation patterns for Power Pages authentication using Microsoft Entra ID.
+This document provides the complete implementation patterns for Power Pages authentication across all supported identity providers.
+
+## Supported Identity Providers
+
+Power Pages supports the following authentication mechanisms:
+
+| Provider Type | Description | Login Endpoint | Provider Identifier |
+|---------------|-------------|----------------|---------------------|
+| **Microsoft Entra ID** | Azure AD / Entra ID via OpenID Connect | `/Account/Login/ExternalLogin` | `https://login.windows.net/{tenantId}/` |
+| **Entra External ID** | Customer identity (CIAM) with self-service sign-up. Uses OIDC — authority may be `ciamlogin.com` or a custom domain. **This is NOT Microsoft Account** — it is a separate OIDC provider for customer-facing apps. | `/Account/Login/ExternalLogin` | Site setting `Authentication/OpenIdConnect/{name}/AuthenticationType` |
+| **OpenID Connect (Generic)** | Any OIDC-compliant provider (Okta, Auth0, Ping, etc.) | `/Account/Login/ExternalLogin` | Site setting `Authentication/OpenIdConnect/{name}/AuthenticationType` |
+| **SAML2** | SAML 2.0 identity providers (ADFS, Shibboleth, etc.) | `/Account/Login/ExternalLogin` | Site setting `Authentication/SAML2/{name}/AuthenticationType` |
+| **WS-Federation** | WS-Federation identity providers | `/Account/Login/ExternalLogin` | Site setting `Authentication/WsFederation/{name}/AuthenticationType` |
+| **Local Authentication** | Username/password login without external provider | `/Account/Login/Login` | N/A (direct credential POST) |
+| **Microsoft Account** | Microsoft personal/work account (social OAuth). **Not the same as Entra External ID.** | `/Account/Login/ExternalLogin` | `urn:microsoft:account` |
+| **Facebook** | Facebook social login | `/Account/Login/ExternalLogin` | `Facebook` |
+| **Google** | Google social login | `/Account/Login/ExternalLogin` | `Google` |
## How Power Pages Authentication Works
Power Pages authentication is **server-side** using session cookies. There is no client-side token management.
-### Login Flow
+### External Login Flow (Entra ID, OIDC, SAML2, WS-Federation, Social OAuth)
1. Fetch an anti-forgery token from `/_layout/tokenhtml`
-2. POST a form to `/Account/Login/ExternalLogin` with the token, provider URL, and return URL
-3. Power Pages redirects the user to Microsoft Entra ID for authentication
+2. POST a form to `/Account/Login/ExternalLogin` with the token, provider identifier, and return URL
+3. Power Pages redirects the user to the identity provider for authentication
4. After successful authentication, the session is established via cookies
5. User information becomes available in `window.Microsoft.Dynamic365.Portal.User`
-### Logout Flow
+### Local Login Flow
+
+> **Important:** The login form field names differ from other auth endpoints. The password field is `PasswordValue` (not `Password`), and the form posts to `/SignIn` (not `/Account/Login/Login`). These names match the server-rendered login form.
+
+1. Fetch an anti-forgery token from `/_layout/tokenhtml`
+2. POST a form to `/SignIn` with the token, credentials, and password:
+ - When `Authentication/Registration/LocalLoginByEmail` is `true`: send the `Email` field
+ - When `Authentication/Registration/LocalLoginByEmail` is `false`: send the `Username` field
+ - Password field name is `PasswordValue` (NOT `Password`)
+ - Optionally include `RememberMe` field (when `Authentication/Registration/RememberMeEnabled` is `true`)
+ - Include `ReturnUrl` field with the SPA path to redirect back to (e.g., `/`)
+3. Power Pages validates credentials against the contact record in Dataverse
+4. If 2FA is enabled and required for the user, the server redirects to `SendCode` action instead of completing sign-in
+5. On success, the session is established via cookies and the server redirects to `ReturnUrl`
+6. User information becomes available in `window.Microsoft.Dynamic365.Portal.User`
+
+### Local Registration Flow
+
+> **Important:** The registration page (`/Account/Login/Register`) is an ASP.NET Web Forms page, NOT an MVC action like login. It requires `__VIEWSTATE` and uses fully-qualified control names (e.g., `ctl00$...$EmailTextBox`). A simple form POST with flat field names will silently fail.
+
+1. Fetch the server-rendered registration page: GET `/Account/Login/Register`
+2. Parse the HTML response with `DOMParser` to extract:
+ - `__VIEWSTATE`, `__VIEWSTATEGENERATOR`, `__VIEWSTATEENCRYPTED` hidden fields
+ - `__RequestVerificationToken` hidden field
+ - The form `action` URL (includes correlation IDs as query params)
+ - Input control names by their IDs: `EmailTextBox`, `UsernameTextBox`, `PasswordTextBox`, `ConfirmPasswordTextBox`, `SubmitButton`
+3. Resolve the form action URL relative to `/Account/Login/` (not relative to the SPA's current path)
+4. POST a form with the parsed ViewState, anti-forgery token, and user values mapped to the correct control names
+5. On success, the server creates a contact in Dataverse and either:
+ - Redirects to `ReturnUrl` (if `EmailConfirmationEnabled` is `false`)
+ - Redirects to email confirmation page (if `EmailConfirmationEnabled` is `true`)
+6. On failure, the server returns a 200 with the registration page HTML containing validation errors
+
+### Registration Flow (External Providers)
+
+After external authentication, if the user does not already exist in Dataverse:
+
+1. The server shows the `ExternalLoginConfirmation` view for the user to complete registration
+2. Registration is controlled by multiple site settings: `RegistrationEnabled` (per-provider), `OpenRegistrationEnabled` (global), `InvitationEnabled`
+3. Claims from the external provider are mapped to the contact record using `RegistrationClaimsMapping`
+4. Email is auto-confirmed for external providers (no manual verification needed)
+5. If an invitation code is present, the user is linked to the pre-created contact
+
+No client-side code is needed — the server handles the entire registration flow.
+
+### Password Reset Flow (Local Authentication)
+
+Power Pages provides a server-side password reset flow for local authentication:
+
+1. User navigates to `/Account/Login/ForgotPassword` (server-rendered form)
+2. User enters their email address
+3. Server generates a reset token and sends an email via the `adx_SendPasswordResetToContact` process
+4. User clicks the email link → navigates to `/Account/Login/ResetPassword` with the token
+5. User enters a new password → server validates the token and updates the password
+
+This flow is entirely server-rendered — no client-side code is needed. It is controlled by:
+- `Authentication/Registration/ResetPasswordEnabled` — enable/disable password reset (`true`/`false`)
+- `Authentication/Registration/ResetPasswordRequiresConfirmedEmail` — require confirmed email before allowing reset
+
+When local authentication is configured, add a "Forgot password?" link in the `LocalLoginForm` component pointing to `/Account/Login/ForgotPassword`.
+
+### Logout Flow (All Providers)
1. Redirect the user to `/Account/Login/LogOff`
-2. Power Pages clears the session cookies
+2. Power Pages server:
+ - Clears session cookies (`ApplicationCookie`, `ExternalCookie`, `TwoFactorCookie`)
+ - If `SignOutEverywhereEnabled` is true, updates the security stamp to invalidate all sessions across devices
+ - Clears the `DeferredLocalLoginCookie` if present
+ - Sends `Clear-Site-Data: "cache"` header
3. `window.Microsoft.Dynamic365.Portal.User` becomes `undefined`
+4. **If federated logout is enabled** (see modes below), the server redirects to the IdP's `end_session_endpoint`. **Otherwise**, the server redirects to the `returnUrl` query parameter (or site root if missing/invalid).
+
+### Two logout modes for external providers
+
+| Mode | Site settings | Behavior | When to use |
+|---|---|---|---|
+| **Local logout** (server default) | `RPInitiatedLogout` unset/false, `PostLogoutRedirectUri` unset | Clears Power Pages session; user stays signed in at the IdP. Next sign-in is silent SSO via the IdP's still-warm cookie. Server redirects to `returnUrl` or `/`. | Default for most customer-facing sites. Smooth UX, no app-registration changes needed. |
+| **Federated logout** (RP-initiated) | `RPInitiatedLogout=true` AND `PostLogoutRedirectUri={site-url}/` | Server 302s to IdP's `end_session_endpoint` with `id_token_hint` and `post_logout_redirect_uri`. IdP signs the user out of THEIR session and redirects back to the registered post-logout URI. | Shared-device scenarios, regulated industries, sites that need users to re-enter credentials each time. **Requires app-registration step** (register the URL as "Front-channel logout URL" in the Entra app — IdP rejects unregistered values). |
+
+> **Both settings must be paired**: setting `RPInitiatedLogout=true` without an explicit `PostLogoutRedirectUri` leaves users stranded on the IdP's signed-out page. The server has an internal fallback that derives a URL from `RedirectUri`'s authority — but a separate flag (`PostLogoutRedirectUriEnabled`) only treats it as enabled when the EXPLICIT site setting is present. So in practice the explicit setting is required.
+>
+> Verified via HAR analysis on a live Entra External ID site: with `RPInitiatedLogout=true` and no explicit `PostLogoutRedirectUri`, the server's logout URL was `https://{tenant}.ciamlogin.com/.../v2.0/logout?id_token_hint=...` with NO `post_logout_redirect_uri` parameter, and the user was stranded.
+
+> **`ExternalLogoutEnabled`**: this is a separate, legacy setting (server default `false`). It triggers OWIN's `AuthenticationManager.SignOut` for the IdP's auth type, but doesn't construct an explicit redirect URL. When `RPInitiatedLogout=true`, the server forces `ExternalLogoutEnabled=false` regardless of its setting. Prefer `RPInitiatedLogout` over `ExternalLogoutEnabled` for modern OIDC providers; `ExternalLogoutEnabled` is mainly useful for WS-Federation and older providers without an `end_session_endpoint`.
+
+### Terms & Conditions Flow
+
+If `Authentication/Registration/TermsAgreementEnabled` is `true`, after successful authentication (before the session is fully established), the server redirects new users to `/Account/Login/TermsAndConditions`. The user must accept the terms before proceeding. This is a server-rendered page — no client-side code is needed.
+
+### External Authentication Failure (ExternalAuthenticationFailed page)
+
+When an OIDC/SAML2/WS-Fed authentication fails (invalid token, issuer mismatch, IdX errors, user access denied, IdP outage, etc.), the server redirects to a hardcoded path: `/Account/Login/ExternalAuthenticationFailed`. **This path cannot be overridden via site settings or site markers** — it is baked into OWIN startup. The only query parameter ever appended is `?message=access_denied` (for user-denied errors); all other error details are logged to server telemetry only.
+
+**SPA handling — Code-Site-Shell-Header redirect (recommended):**
+
+Add this entry to the `Code-Site-Shell-Header` redirect map (Phase 5.1.6):
+
+```js
+'/account/login/externalauthenticationfailed': '/login'
+```
+
+And add this special-case block right after the redirect map (handles the no-query-string case):
+
+```js
+if (path === '/account/login/externalauthenticationfailed' && !search) {
+ window.location.replace(spaBase + '/login?message=external_auth_failed');
+ return;
+}
+```
+
+Then add the error code to `AUTH_ERROR_MESSAGES` in `authService.ts`:
+
+```typescript
+external_auth_failed: 'Sign-in with the external provider failed. Please try again.',
+```
+
+With this in place:
+- **User-denied at IdP** (server appends `?message=access_denied`) → SPA `/login?message=access_denied` → "Access was denied."
+- **Generic failure** (no query string) → SPA `/login?message=external_auth_failed` → "Sign-in with the external provider failed. Please try again."
+
+Either way the user lands on the SPA Login page with an inline error, can retry, and stays in the SPA UX. No content snippet editing required.
+
+**Legacy workaround — content snippet edit (use only if you can't deploy the header template):**
+
+If for some reason you can't ship the header template redirect (e.g., on a site that doesn't use Code-Site-Shell-Header), you can edit content snippets in the Power Pages admin center to inject a redirect script. This is the older approach; prefer the header-template redirect above:
+
+1. Edit content snippets `Account/Register/ExternalAuthenticationFailed` and `Account/Register/ExternalAuthenticationFailed/AccessDenied`
+2. Add `<script>` that reads `window.location.search` and redirects to `/login?message=...`
+
+**Limitations (apply to both approaches):**
+- Only `access_denied` vs. generic `external_auth_failed` distinction is preserved — rich error codes (`AADSTS*`, `IDX*`) are not available client-side
+- The server-rendered error page briefly flashes before the script redirects (1-2 frames typically)
+- Operators must still use Kusto/telemetry to investigate actual error causes
+
+### External Password Reset Flow (OIDC Providers with PasswordResetPolicyId)
+
+For OIDC providers that have a `PasswordResetPolicyId` configured (e.g., Azure AD B2C):
+
+1. User clicks "Forgot password?" on the IdP's sign-in page
+2. The IdP returns an error (e.g., `AADB2C90118` for B2C)
+3. Server catches the error and redirects to `/Account/Login/ExternalPasswordReset?passwordResetPolicyId={policy}&provider={provider}`
+4. The server challenges the provider with the password reset policy
+5. After reset, user is redirected back to the login page
+
+This is entirely server-managed — no client-side code is needed.
+
+### External Profile Edit Flow (OIDC Providers with ProfileEditPolicyId)
+
+For OIDC providers that have a `ProfileEditPolicyId` configured:
+
+1. User navigates to `/Account/Login/ExternalProfileEdit`
+2. Server challenges the provider with the profile edit policy
+3. Provider shows the profile edit form (e.g., B2C profile edit flow)
+4. After edit completes, `LoginClaimsMapping` is applied to sync updated claims back to the contact record
+
+This is entirely server-managed. The client can link to `/Account/Login/ExternalProfileEdit` to trigger it.
+
+### Invitation Redemption Flow
+
+For invitation-based registration:
+
+1. Admin creates an invitation in the Power Pages admin center and shares the invitation link
+2. Invitation link format: `{site-url}/Account/Login/RedeemInvitation?InvitationCode={code}&returnUrl=/`
+3. Server validates the invitation code and redirects to the login page with the code threaded through
+4. After authentication (local or external), the server links the user to the pre-created contact associated with the invitation
+
+The client-side `login()` and `register()` functions already support passing `invitationCode` through the auth flow.
+
+### Session Expiry Re-Authentication
+
+When a user's session expires while they are on a page:
+
+1. The server redirects to the login page with `?sessionExpired=true`
+2. The login action clears all authentication cookies
+3. For OIDC providers, the server can pass `prompt=login` to force re-authentication at the IdP (bypassing SSO)
+
+To support this in the client-side auth service, check for `sessionExpired` in the URL and show a session-expired message:
+
+```typescript
+export function getSessionExpiredMessage(): string | undefined {
+ if (typeof window === 'undefined') return undefined;
+ const params = new URLSearchParams(window.location.search);
+ return params.get('sessionExpired') === 'true' ? 'Your session has expired. Please sign in again.' : undefined;
+}
+```
+
+### Account Management Endpoints (Server-Side)
+
+Power Pages provides server-rendered account management pages. These are NOT part of the client-side auth service — they are server-side ASP.NET views. The client can link to these URLs:
+
+| Endpoint | Purpose | When to use |
+|----------|---------|-------------|
+| `/Account/Login/ChangePassword` | Change password (local auth users) | User wants to update their password |
+| `/Account/Login/SetPassword` | Add password to external-only account | External user wants to add local login |
+| `/Account/Login/ChangeEmail` | Change email address | User wants to update their email |
+| `/Account/Login/LinkLogin` | Link additional external login | User wants to add Google to their Entra account |
+| `/Account/Login/RemoveLogin` | Remove a linked external login | User wants to unlink a social provider |
+| `/Account/Login/ConfirmEmail` | Email confirmation page | After registration with `EmailConfirmationEnabled` |
+| `/Account/Login/ChangeTwoFactor` | Manage 2FA settings | User wants to enable/disable 2FA |
+| `/Account/Login/ForgotPassword` | Password reset request | User forgot their password |
+
+These endpoints are available on deployed Power Pages sites. Add links to relevant pages in the site's user profile area as needed.
---
@@ -84,6 +297,48 @@ Create `src/services/authService.ts`:
```typescript
import type { PowerPagesUser } from '../types/powerPages';
+// --- Provider Configuration ---
+// Change this to match the identity provider configured for your Power Pages site.
+// See the comments above each provider type for the correct providerIdentifier.
+
+export type AuthProviderType =
+ | 'entra-id'
+ | 'oidc'
+ | 'saml2'
+ | 'ws-federation'
+ | 'local'
+ | 'social'
+ | 'entra-external-id';
+
+export interface AuthProviderConfig {
+ type: AuthProviderType;
+ providerIdentifier?: string;
+ displayName?: string;
+ /** For local login: when true, sends Email field instead of Username */
+ loginByEmail?: boolean;
+}
+
+// --- Canonical: always declare AUTH_PROVIDERS as an array, even with one entry ---
+// This is the single source of truth for which providers the site offers. The
+// array shape is the canonical pattern (see the "Multiple Providers — Canonical
+// AUTH_PROVIDERS Array Pattern" section below) — single-provider sites use a
+// one-element array so they can grow without restructuring the code.
+// Replace the entries here with the providers configured in Power Pages.
+export const AUTH_PROVIDERS: AuthProviderConfig[] = [
+ {
+ type: 'entra-id',
+ displayName: 'Sign In',
+ },
+];
+
+// Derived alias used by the helper functions later in this file. For a single-
+// provider site this is just the only entry. For multi-provider sites it's the
+// local provider when present, otherwise the first external one — the helpers
+// that reference AUTH_PROVIDER were written for the single-provider walkthrough
+// and continue to work via this alias.
+const AUTH_PROVIDER: AuthProviderConfig =
+ AUTH_PROVIDERS.find(p => p.type === 'local') ?? AUTH_PROVIDERS[0];
+
const isDevelopment =
typeof window !== 'undefined' &&
(window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
@@ -98,11 +353,26 @@ const MOCK_USER: PowerPagesUser = {
userRoles: ['Authenticated Users', 'Administrators'],
};
+// Track mock sign-out state in dev mode (persists across page reloads via sessionStorage)
+const DEV_SIGNEDOUT_KEY = '__pp_dev_signedout__';
+
+/**
+ * Returns the configured authentication provider.
+ */
+export function getAuthProvider(): AuthProviderConfig {
+ return AUTH_PROVIDER;
+}
+
/**
* Returns the currently logged-in user, or undefined if not authenticated.
*/
export function getCurrentUser(): PowerPagesUser | undefined {
- if (isDevelopment) return MOCK_USER;
+ if (typeof window === 'undefined') return undefined; // SSR guard (Astro)
+ if (isDevelopment) {
+ // In dev mode, respect mock sign-out state
+ if (sessionStorage.getItem(DEV_SIGNEDOUT_KEY)) return undefined;
+ return MOCK_USER;
+ }
return window.Microsoft?.Dynamic365?.Portal?.User;
}
@@ -116,6 +386,7 @@ export function isAuthenticated(): boolean {
/**
* Returns the Entra ID tenant ID from the portal configuration.
+ * Only applicable for Entra ID provider type.
*/
export function getTenantId(): string | undefined {
if (isDevelopment) return '00000000-0000-0000-0000-000000000000';
@@ -123,11 +394,17 @@ export function getTenantId(): string | undefined {
}
/**
- * Fetches the anti-forgery token required for the login form POST.
+ * Fetches the anti-forgery token required for login form POSTs.
* The token is embedded in an HTML response from /_layout/tokenhtml.
*/
export async function fetchAntiForgeryToken(): Promise<string> {
const response = await fetch('/_layout/tokenhtml');
+ if (!response.ok) {
+ throw new Error(
+ `Failed to fetch anti-forgery token: ${response.status} ${response.statusText}. ` +
+ 'Ensure the site is deployed and accessible.'
+ );
+ }
const html = await response.text();
const match = html.match(/value="([^"]+)"/);
if (!match) {
@@ -137,28 +414,118 @@ export async function fetchAntiForgeryToken(): Promise<string> {
}
/**
- * Initiates login by posting a form to the Power Pages external login endpoint.
- * The browser will redirect to Microsoft Entra ID for authentication.
+ * Resolves the provider identifier for the external login form POST.
+ * Different provider types use different identifiers.
+ */
+function resolveProviderIdentifier(): string {
+ if (AUTH_PROVIDER.providerIdentifier) {
+ return AUTH_PROVIDER.providerIdentifier;
+ }
+
+ switch (AUTH_PROVIDER.type) {
+ case 'entra-id': {
+ const tenantId = getTenantId();
+ if (!tenantId) {
+ throw new Error(
+ 'Tenant ID not found in portal configuration. ' +
+ 'Ensure the site is properly deployed and window.Microsoft.Dynamic365.Portal.tenant is set.'
+ );
+ }
+ return `https://login.windows.net/${tenantId}/`;
+ }
+ case 'entra-external-id':
+ throw new Error(
+ 'providerIdentifier must be set in AUTH_PROVIDER config for Entra External ID. ' +
+ 'Use the AuthenticationType value from your External ID site settings.'
+ );
+ default:
+ throw new Error(
+ `providerIdentifier must be set in AUTH_PROVIDER config for type "${AUTH_PROVIDER.type}"`
+ );
+ }
+}
+
+/**
+ * Initiates login based on the configured provider type.
+ *
+ * - External providers (Entra ID, OIDC, SAML2, WS-Federation, Social):
+ * Posts a form to /Account/Login/ExternalLogin which redirects to the identity provider.
+ *
+ * - Local authentication: Posts credentials to /Account/Login/Login.
+ * Requires username/email and password parameters.
*
* @param returnUrl - URL to return to after successful login (defaults to current page)
+ * @param credentials - For local login only: { username, password, rememberMe }
+ * @param invitationCode - Optional invitation code for invitation-based registration
*/
-export async function login(returnUrl?: string): Promise<void> {
+export async function login(
+ returnUrl?: string,
+ credentials?: { username: string; password: string; rememberMe?: boolean },
+ invitationCode?: string
+): Promise<void> {
if (isDevelopment) {
- console.warn('[Auth] Login is not available in local development. Using mock user.');
+ // Clear sign-out state so mock user comes back
+ sessionStorage.removeItem(DEV_SIGNEDOUT_KEY);
window.location.reload();
return;
}
const token = await fetchAntiForgeryToken();
- const tenantId = getTenantId();
+
+ if (AUTH_PROVIDER.type === 'local') {
+ // Local login: use fetch() to POST credentials so we can parse server errors
+ // and keep the user in the SPA. Do NOT use form.submit() — it navigates away.
+ if (!credentials) {
+ throw new Error('Local login requires username and password credentials.');
+ }
+
+ const credentialFieldName = AUTH_PROVIDER.loginByEmail ? 'Email' : 'Username';
+
+ const body = new URLSearchParams();
+ body.set('__RequestVerificationToken', token);
+ body.set(credentialFieldName, credentials.username);
+ body.set('PasswordValue', credentials.password); // Server uses PasswordValue, not Password
+ body.set('ReturnUrl', returnUrl || '/');
+ if (credentials.rememberMe) body.set('RememberMe', 'true');
+ if (invitationCode) body.set('InvitationCode', invitationCode);
+
+ const response = await fetch('/SignIn', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: body.toString(),
+ credentials: 'same-origin',
+ redirect: 'follow',
+ });
+
+ // If the fetch followed a redirect to our ReturnUrl, login succeeded — reload to pick up session
+ if (response.redirected || response.url.endsWith(returnUrl || '/')) {
+ window.location.href = returnUrl || '/';
+ return;
+ }
+
+ // If we got a 200, the server returned the login page with errors — parse them
+ const html = await response.text();
+ const errors = parseServerErrors(html);
+ if (errors.length > 0) {
+ throw new Error(errors.join(' '));
+ }
+
+ throw new Error('Invalid email or password. Please try again.');
+ }
+
+ // External login: POST to ExternalLogin endpoint with provider identifier
+ const provider = resolveProviderIdentifier();
const form = document.createElement('form');
form.method = 'POST';
- form.action = '/Account/Login/ExternalLogin';
+ // Append invitation code as query parameter for external login if present
+ form.action = invitationCode
+ ? `/Account/Login/ExternalLogin?InvitationCode=${encodeURIComponent(invitationCode)}`
+ : '/Account/Login/ExternalLogin';
const fields: Record<string, string> = {
__RequestVerificationToken: token,
- provider: `https://login.windows.net/${tenantId}/`,
+ provider,
returnUrl: returnUrl || window.location.pathname,
};
@@ -181,7 +548,7 @@ export async function login(returnUrl?: string): Promise<void> {
*/
export function logout(returnUrl?: string): void {
if (isDevelopment) {
- console.warn('[Auth] Logout is not available in local development.');
+ sessionStorage.setItem(DEV_SIGNEDOUT_KEY, '1');
window.location.reload();
return;
}
@@ -190,18 +557,323 @@ export function logout(returnUrl?: string): void {
window.location.href = `/Account/Login/LogOff?returnUrl=${encodeURIComponent(target)}`;
}
+// --- Auth Error Handling ---
+
+/**
+ * Error codes returned by the Power Pages server via query string parameters.
+ * The server redirects back to the login page with ?message=<code> or ?error=<code>.
+ */
+const AUTH_ERROR_MESSAGES: Record<string, string> = {
+ access_denied: 'Access was denied by the identity provider.',
+ missing_license: 'Your account does not have the required license.',
+ invalid_login: 'Invalid login. Please try again.',
+ invalid_username_or_password: 'Invalid username or password.',
+ user_locked: 'Your account has been locked due to too many failed attempts. Please try again later.',
+ too_many_attempts: 'Too many failed login attempts. Please try again later.',
+ invalid_invitation: 'The invitation code is invalid or has expired.',
+ duplicate_login: 'This external identity is already linked to another account.',
+ registration_blocked: 'Registration is not available for this provider.',
+ signin_failed: 'Sign-in failed. Please try again.',
+ email_required: 'An email address is required.',
+ username_required: 'A username is required.',
+ password_required: 'A password is required.',
+ password_confirmation_failure: 'Passwords do not match.',
+ invalid_two_factor_code: 'The verification code is invalid.',
+ duplicate_email: 'This email address is already in use.',
+ duplicate_username: 'This username is already taken.',
+ deny_minors: 'Registration is not available for users under the minimum age.',
+};
+
+/**
+ * Parses authentication error from the current page URL.
+ * The Power Pages server passes errors via ?message= or ?error= query parameters
+ * when redirecting back to the login page after a failed authentication attempt.
+ *
+ * @returns The user-friendly error message, or undefined if no error.
+ */
+export function getAuthError(): string | undefined {
+ if (typeof window === 'undefined') return undefined;
+ const params = new URLSearchParams(window.location.search);
+ const message = params.get('message') || params.get('error');
+ if (!message) return undefined;
+ return AUTH_ERROR_MESSAGES[message] || 'An authentication error occurred. Please try again.';
+}
+
+// --- Server Error Parsing ---
+// When the server rejects a login/registration POST, it returns 200 with HTML containing
+// validation errors. This helper parses those errors from the response HTML so they can
+// be shown inline in the SPA instead of the user seeing the server-rendered error page.
+
+function parseServerErrors(html: string): string[] {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+ const errors: string[] = [];
+
+ // MVC validation summary (login, forgot password)
+ doc.querySelectorAll('.validation-summary-errors li').forEach(li => {
+ const text = li.textContent?.trim();
+ if (text) errors.push(text);
+ });
+
+ // Web Forms validation summary (registration)
+ doc.querySelectorAll('.alert-danger li').forEach(li => {
+ const text = li.textContent?.trim();
+ if (text && !errors.includes(text)) errors.push(text);
+ });
+
+ // Individual field errors
+ doc.querySelectorAll('.field-validation-error').forEach(el => {
+ const text = el.textContent?.trim();
+ if (text && !errors.includes(text)) errors.push(text);
+ });
+
+ return errors;
+}
+
+// --- Local Registration ---
+
+/**
+ * Registers a new local user via the server-rendered /Account/Login/Register page.
+ *
+ * IMPORTANT: The registration page is an ASP.NET Web Forms page (not MVC like login).
+ * It requires __VIEWSTATE and uses fully-qualified control names (e.g., ctl00$...$EmailTextBox).
+ * This function fetches the server page first, parses the ViewState and control names,
+ * then POSTs back with the user's data — the same flow a browser performs when submitting the form.
+ *
+ * This differs from login, which is an MVC action accepting simple field names.
+ */
+export async function register(
+ fields: { email?: string; username?: string; password: string; confirmPassword: string },
+ returnUrl?: string,
+ invitationCode?: string
+): Promise<void> {
+ if (!fields.email && !fields.username) {
+ throw new Error('Registration requires either an email or username.');
+ }
+
+ if (isDevelopment) {
+ sessionStorage.removeItem(DEV_SIGNEDOUT_KEY);
+ window.location.reload();
+ return;
+ }
+
+ // Step 1: Fetch the server-rendered registration page to get ViewState and field names
+ const params = new URLSearchParams();
+ if (returnUrl) params.set('returnUrl', returnUrl);
+ if (invitationCode) params.set('invitationCode', invitationCode);
+ const qs = params.toString();
+ const regUrl = `/Account/Login/Register${qs ? `?${qs}` : ''}`;
+
+ const pageResponse = await fetch(regUrl, { credentials: 'same-origin' });
+ if (!pageResponse.ok) {
+ throw new Error(`Failed to load registration page: ${pageResponse.status}`);
+ }
+
+ const pageHtml = await pageResponse.text();
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(pageHtml, 'text/html');
+
+ // Step 2: Extract the form element and resolve the action URL
+ const serverForm = doc.getElementById('Register') as HTMLFormElement | null;
+ if (!serverForm) {
+ throw new Error('Registration form not found on the server page.');
+ }
+
+ // The server form has a relative action like "./Register?msCorrelationId=..."
+ // Resolve it relative to /Account/Login/ (the server page's path), NOT the SPA's current URL.
+ const rawAction = serverForm.getAttribute('action') || '';
+ let formAction: string;
+ if (rawAction.startsWith('http') || rawAction.startsWith('/')) {
+ formAction = rawAction;
+ } else {
+ const base = new URL('/Account/Login/', window.location.origin);
+ formAction = new URL(rawAction, base).pathname + new URL(rawAction, base).search;
+ }
+
+ // Step 3: Extract ViewState, anti-forgery token, and other hidden fields
+ const viewState = (doc.getElementById('__VIEWSTATE') as HTMLInputElement)?.value || '';
+ const viewStateGenerator = (doc.getElementById('__VIEWSTATEGENERATOR') as HTMLInputElement)?.value || '';
+ const eventValidation = (doc.querySelector('input[name="__EVENTVALIDATION"]') as HTMLInputElement)?.value || '';
+ const antiForgeryToken = (doc.querySelector('input[name="__RequestVerificationToken"]') as HTMLInputElement)?.value || '';
+
+ // Step 4: Find the correct Web Forms control names by their IDs
+ const emailInput = doc.getElementById('EmailTextBox') as HTMLInputElement | null;
+ const usernameInput = doc.getElementById('UsernameTextBox') as HTMLInputElement | null;
+ const passwordInput = doc.getElementById('PasswordTextBox') as HTMLInputElement | null;
+ const confirmInput = doc.getElementById('ConfirmPasswordTextBox') as HTMLInputElement | null;
+ const submitBtn = doc.getElementById('SubmitButton') as HTMLInputElement | null;
+
+ // Step 5: Build the POST body with Web Forms field names
+ const body = new URLSearchParams();
+ body.set('__VIEWSTATE', viewState);
+ body.set('__VIEWSTATEGENERATOR', viewStateGenerator);
+ body.set('__EVENTTARGET', '');
+ body.set('__EVENTARGUMENT', '');
+ body.set('__VIEWSTATEENCRYPTED', '');
+
+ if (eventValidation) body.set('__EVENTVALIDATION', eventValidation);
+ if (antiForgeryToken) body.set('__RequestVerificationToken', antiForgeryToken);
+
+ if (fields.email && emailInput) body.set(emailInput.name, fields.email);
+ if (fields.username && usernameInput) body.set(usernameInput.name, fields.username);
+ if (passwordInput) body.set(passwordInput.name, fields.password);
+ if (confirmInput) body.set(confirmInput.name, fields.confirmPassword);
+ if (submitBtn) body.set(submitBtn.name, submitBtn.value || 'Register');
+
+ // Step 6: POST via fetch() to stay in the SPA and parse server errors
+ const response = await fetch(formAction, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: body.toString(),
+ credentials: 'same-origin',
+ redirect: 'follow',
+ });
+
+ // If the fetch followed a redirect, registration succeeded
+ if (response.redirected) {
+ window.location.href = response.url;
+ return;
+ }
+
+ // If we got a 200, the server returned the page with errors — parse them
+ const responseHtml = await response.text();
+ const errors = parseServerErrors(responseHtml);
+ if (errors.length > 0) {
+ throw new Error(errors.join(' '));
+ }
+
+ if (response.url !== window.location.href) {
+ window.location.href = response.url;
+ return;
+ }
+
+ throw new Error('Registration failed. Please try again.');
+}
+
+// --- Forgot Password ---
+// MVC form POST (like login, not Web Forms like registration).
+// Posts Email + anti-forgery token to /Account/Login/ForgotPassword.
+// Server sends a reset email. The reset link goes to the server-rendered
+// /Account/Login/ResetPassword page (stays server-side since user arrives from email).
+
+export async function forgotPassword(email: string): Promise<void> {
+ if (isDevelopment) {
+ alert('Dev mode: Password reset email would be sent to ' + email);
+ return;
+ }
+
+ const token = await fetchAntiForgeryToken();
+
+ const body = new URLSearchParams();
+ body.set('__RequestVerificationToken', token);
+ body.set('Email', email);
+
+ const response = await fetch('/Account/Login/ForgotPassword', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: body.toString(),
+ credentials: 'same-origin',
+ redirect: 'follow',
+ });
+
+ // The server always returns 200 with a confirmation page (even if the email doesn't exist,
+ // for security — it doesn't reveal whether an account exists). Parse for errors just in case.
+ const html = await response.text();
+ const errors = parseServerErrors(html);
+ if (errors.length > 0) {
+ throw new Error(errors.join(' '));
+ }
+
+ // No errors = success. The server sent the email.
+ // The calling component should handle .then() to show a "check your email" confirmation.
+}
+
+// --- Reset Password ---
+// MVC form POST. The user arrives at the SPA /reset-password page via the header template
+// redirect (server's /Account/Login/ResetPassword → SPA /reset-password).
+// UserId and Code come from the URL query params set by the email reset link.
+
+export async function resetPassword(
+ userId: string,
+ code: string,
+ password: string,
+ confirmPassword: string
+): Promise<void> {
+ if (isDevelopment) {
+ alert('Dev mode: Password would be reset.');
+ window.location.href = '/login';
+ return;
+ }
+
+ const token = await fetchAntiForgeryToken();
+
+ const body = new URLSearchParams();
+ body.set('__RequestVerificationToken', token);
+ body.set('UserId', userId);
+ body.set('Code', code);
+ body.set('Password', password); // Note: Password here, NOT PasswordValue (different from login)
+ body.set('ConfirmPassword', confirmPassword);
+
+ const response = await fetch('/Account/Login/ResetPassword', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: body.toString(),
+ credentials: 'same-origin',
+ redirect: 'follow',
+ });
+
+ if (response.redirected) {
+ window.location.href = '/login?message=password_reset_success';
+ return;
+ }
+
+ const html = await response.text();
+ const errors = parseServerErrors(html);
+ if (errors.length > 0) {
+ throw new Error(errors.join(' '));
+ }
+
+ // If no errors and not redirected, assume success
+ window.location.href = '/login?message=password_reset_success';
+}
+
/**
- * Returns the user's display name (full name if available, otherwise userName).
+ * Returns the user's display name, using the following fallback order:
+ * 1. firstName + lastName (if both present)
+ * 2. firstName alone (if only first name present)
+ * 3. userName (NameIdentifier/sub claim — always populated after login)
+ * 4. email (fallback if userName is empty for some reason)
+ * 5. 'User' (final fallback)
+ *
+ * Why the fallbacks: Power Pages populates `firstName`, `lastName`, and `email` from standard
+ * OIDC claims (`given_name`, `family_name`, `email`) by default — no explicit RegistrationClaimsMapping
+ * is needed for these standard claims. However, a field can still be empty if the IdP didn't emit
+ * the claim. For external providers like Entra External ID where the user flow may not include
+ * `given_name`/`family_name` attributes, firstName and lastName come back empty.
+ *
+ * Priority order: full name → first or last alone → email → userName → 'User'.
+ *
+ * **Why email beats userName**: for external providers, the `userName` field is the OIDC subject
+ * identifier (a long opaque string like `vs25QwNe1ZAHqlWK1Naw9dVEBe-TbF5tZEpb0XjAEZQ`) — showing
+ * that in a navigation bar is ugly and meaningless to the user. Email is human-readable and
+ * almost always populated from the OIDC `email` claim. So when names aren't available, prefer
+ * email; fall back to userName only as a last resort.
*/
export function getUserDisplayName(): string {
const user = getCurrentUser();
if (!user) return '';
const fullName = [user.firstName, user.lastName].filter(Boolean).join(' ');
- return fullName || user.userName;
+ if (fullName) return fullName;
+ if (user.firstName) return user.firstName;
+ if (user.lastName) return user.lastName;
+ if (user.email) return user.email;
+ if (user.userName) return user.userName;
+ return 'User';
}
/**
* Returns the user's initials for avatar display.
+ * Same fallback priority as getUserDisplayName but uses the first character of each source.
*/
export function getUserInitials(): string {
const user = getCurrentUser();
@@ -209,95 +881,584 @@ export function getUserInitials(): string {
if (user.firstName && user.lastName) {
return `${user.firstName[0]}${user.lastName[0]}`.toUpperCase();
}
- return (user.userName?.[0] || '').toUpperCase();
+ if (user.firstName) return user.firstName[0].toUpperCase();
+ if (user.lastName) return user.lastName[0].toUpperCase();
+ if (user.email) return user.email[0].toUpperCase();
+ if (user.userName) return user.userName[0].toUpperCase();
+ return '?';
}
```
---
-## Framework-Specific Patterns
+## Provider-Specific Configuration Entries
-### React: useAuth Hook
+Each snippet below is a single **entry** that goes inside the `AUTH_PROVIDERS` array shown earlier in this file. For a single-provider site, the array has one entry; for a multi-provider site, list several entries (see "Multiple Providers — Canonical `AUTH_PROVIDERS` Array Pattern" further down). The legacy `const AUTH_PROVIDER = { ... }` form shown below is illustrative for readability — in the actual generated `authService.ts` it appears as an element of `AUTH_PROVIDERS`, not as a standalone constant.
-Create `src/hooks/useAuth.ts`:
+### Microsoft Entra ID (Default)
```typescript
-import { useState, useEffect, useCallback } from 'react';
-import type { PowerPagesUser } from '../types/powerPages';
-import {
- getCurrentUser,
- isAuthenticated as checkAuth,
- getUserDisplayName,
- getUserInitials,
- login as authLogin,
- logout as authLogout,
-} from '../services/authService';
-
-interface UseAuthReturn {
- user: PowerPagesUser | undefined;
- isAuthenticated: boolean;
- isLoading: boolean;
- displayName: string;
- initials: string;
- login: (returnUrl?: string) => Promise<void>;
- logout: (returnUrl?: string) => void;
- refresh: () => void;
-}
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'entra-id',
+ displayName: 'Sign in with Microsoft',
+};
+```
-export function useAuth(): UseAuthReturn {
- const [user, setUser] = useState<PowerPagesUser | undefined>(undefined);
- const [isLoading, setIsLoading] = useState(true);
+### OpenID Connect (Generic)
- const refresh = useCallback(() => {
- setUser(getCurrentUser());
- setIsLoading(false);
- }, []);
+```typescript
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'oidc',
+ providerIdentifier: 'https://your-oidc-provider.com/', // Must match AuthenticationType site setting
+ displayName: 'Sign in with Okta',
+};
+```
- useEffect(() => {
- refresh();
- }, [refresh]);
+### SAML2
- return {
- user,
- isAuthenticated: checkAuth(),
- isLoading,
- displayName: getUserDisplayName(),
- initials: getUserInitials(),
- login: authLogin,
- logout: authLogout,
- refresh,
- };
-}
+```typescript
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'saml2',
+ providerIdentifier: 'https://contoso.powerappsportals.com/', // Must match AuthenticationType site setting EXACTLY
+ displayName: 'Sign in with ADFS',
+};
```
-### React: AuthButton Component
+> **IMPORTANT:** The `providerIdentifier` value MUST be character-for-character identical to the `Authentication/SAML2/{name}/AuthenticationType` site setting value, including the protocol (`https://` vs `http://`), trailing slashes, and casing. A mismatch causes the ExternalLogin POST to silently fail because the server cannot match the provider.
-Create `src/components/AuthButton.tsx`:
+### WS-Federation
-```tsx
-import { useAuth } from '../hooks/useAuth';
-import './AuthButton.css';
+```typescript
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'ws-federation',
+ providerIdentifier: 'https://adfs.contoso.com/adfs/services/trust', // Must match AuthenticationType site setting
+ displayName: 'Sign in with WS-Federation',
+};
+```
-export function AuthButton() {
- const { isAuthenticated, isLoading, displayName, initials, login, logout } = useAuth();
+### Local Authentication
- if (isLoading) {
- return <div className="auth-button auth-loading"><span className="auth-spinner" /></div>;
- }
+```typescript
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'local',
+ displayName: 'Sign In',
+ loginByEmail: true, // Set to true when Authentication/Registration/LocalLoginByEmail is true
+};
+```
- if (!isAuthenticated) {
- return (
- <button className="auth-button auth-sign-in" onClick={() => login()}>
- Sign In
- </button>
- );
- }
+### Social OAuth Providers (Single Provider)
- return (
- <div className="auth-button auth-signed-in">
- <span className="auth-avatar">{initials}</span>
- <span className="auth-name">{displayName}</span>
- <button className="auth-sign-out" onClick={() => logout()}>
+```typescript
+// Microsoft Account
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'social',
+ providerIdentifier: 'urn:microsoft:account',
+ displayName: 'Sign in with Microsoft',
+};
+
+// Facebook
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'social',
+ providerIdentifier: 'Facebook',
+ displayName: 'Sign in with Facebook',
+};
+
+// Google
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'social',
+ providerIdentifier: 'Google',
+ displayName: 'Sign in with Google',
+};
+```
+
+### Multiple Providers — Canonical `AUTH_PROVIDERS` Array Pattern
+
+**Always use the array pattern, even with one entry.** This is the canonical shape — single-provider sites can grow to multi-provider without restructuring.
+
+```typescript
+export type AuthProviderType =
+ | 'local'
+ | 'oidc'
+ | 'entra-id'
+ | 'saml2'
+ | 'ws-federation'
+ | 'social';
+
+export interface AuthProviderConfig {
+ /** Stable identifier — used as React key and to distinguish multiple instances of same type */
+ id: string;
+ type: AuthProviderType;
+ /** Button label shown on the Login page */
+ displayName: string;
+ /**
+ * Provider identifier the server expects in the ExternalLogin form POST.
+ * For OIDC: the Authority URL (matches the AuthenticationType site setting).
+ * For SAML2/WS-Fed/social: the provider identifier from the site settings.
+ * For Entra ID (workforce): OMIT this — resolveProviderIdentifier() derives it
+ * at runtime from window.Microsoft.Dynamic365.Portal.tenant.
+ * Not used for local.
+ */
+ providerIdentifier?: string;
+ /** Local-only: send Email field (true) or Username field (false) */
+ loginByEmail?: boolean;
+}
+
+export const AUTH_PROVIDERS: AuthProviderConfig[] = [
+ // Each provider gets a stable id. For multiple instances of the same type
+ // (e.g., 2 Entra External ID tenants), use distinct ids.
+ {
+ // Entra ID (workforce) — providerIdentifier is OMITTED. The runtime resolver
+ // computes https://login.windows.net/{site-tenant-id}/ from Portal.tenant.
+ // No tenant ID hardcoded; site can move between tenants without code changes.
+ id: 'entra-id',
+ type: 'entra-id',
+ displayName: 'Sign in with Microsoft',
+ },
+ {
+ // Entra External ID — providerIdentifier IS required. External ID is a
+ // separate tenant from the site's parent, so we can't derive from Portal.tenant.
+ id: 'entra-external-id',
+ type: 'oidc',
+ displayName: 'Sign in with Entra External ID',
+ providerIdentifier: 'https://contoso.ciamlogin.com/contoso.onmicrosoft.com/v2.0/',
+ },
+ {
+ id: 'local',
+ type: 'local',
+ displayName: 'Sign in with email',
+ loginByEmail: true,
+ },
+];
+
+if (AUTH_PROVIDERS.length === 0) {
+ throw new Error('AUTH_PROVIDERS array is empty. Configure at least one authentication provider.');
+}
+
+// Exported helpers for the Login page to filter providers cleanly:
+export const LOCAL_PROVIDER = AUTH_PROVIDERS.find(p => p.type === 'local');
+export const EXTERNAL_PROVIDERS = AUTH_PROVIDERS.filter(p => p.type !== 'local');
+
+// Backward-compat for any code that still imports AUTH_PROVIDER:
+const AUTH_PROVIDER: AuthProviderConfig =
+ AUTH_PROVIDERS.find(p => p.type === 'local') ?? AUTH_PROVIDERS[0];
+```
+
+### `loginExternal()` — external provider form POST
+
+```typescript
+export async function loginExternal(
+ providerIdentifier: string,
+ returnUrl?: string,
+ invitationCode?: string
+): Promise<void> {
+ if (isDevelopment) {
+ sessionStorage.removeItem(DEV_SIGNEDOUT_KEY);
+ window.location.reload();
+ return;
+ }
+
+ const token = await fetchAntiForgeryToken();
+
+ const form = document.createElement('form');
+ form.method = 'POST';
+ form.action = invitationCode
+ ? `/Account/Login/ExternalLogin?InvitationCode=${encodeURIComponent(invitationCode)}`
+ : '/Account/Login/ExternalLogin';
+
+ const fields: Record<string, string> = {
+ __RequestVerificationToken: token,
+ provider: providerIdentifier,
+ returnUrl: returnUrl || '/',
+ };
+
+ for (const [name, value] of Object.entries(fields)) {
+ const input = document.createElement('input');
+ input.type = 'hidden';
+ input.name = name;
+ input.value = value;
+ form.appendChild(input);
+ }
+
+ document.body.appendChild(form);
+ form.submit();
+}
+```
+
+### `resolveProviderIdentifier()` — runtime-resolves Entra ID, returns hardcoded value for others
+
+The `providerIdentifier` field on `AuthProviderConfig` is **optional** for external providers. For type `'entra-id'`, it's resolved at runtime from the site's parent tenant (exposed via `window.Microsoft.Dynamic365.Portal.tenant`). For other types (`'oidc'`, `'saml2'`, `'ws-federation'`, `'social'`), it must be explicitly configured in the AUTH_PROVIDERS entry because those providers point at external resources unrelated to the Power Pages tenant.
+
+```typescript
+/**
+ * Resolves the providerIdentifier the server expects in /Account/Login/ExternalLogin's
+ * `provider` form field. For Entra ID, derives from the site's parent tenant at runtime
+ * — no need to hardcode the tenant ID in the AUTH_PROVIDERS array. For other external
+ * providers, returns the explicitly-configured providerIdentifier.
+ */
+export function resolveProviderIdentifier(provider: AuthProviderConfig): string {
+ if (provider.type === 'local') {
+ throw new Error(`resolveProviderIdentifier called for local provider ${provider.id}`);
+ }
+
+ if (provider.type === 'entra-id') {
+ const tenantId = getTenantId();
+ if (!tenantId) {
+ throw new Error(
+ `Cannot resolve Entra ID provider identifier — tenant ID not available. ` +
+ `Ensure the site is properly deployed and window.Microsoft.Dynamic365.Portal.tenant is set.`
+ );
+ }
+ return `https://login.windows.net/${tenantId}/`;
+ }
+
+ if (!provider.providerIdentifier) {
+ throw new Error(
+ `Provider ${provider.id} (type ${provider.type}) is missing providerIdentifier.`
+ );
+ }
+ return provider.providerIdentifier;
+}
+```
+
+**Why Entra ID is special-cased**: when Power Pages creates a site in a workforce Entra tenant, it auto-writes `Authentication/OpenIdConnect/AzureAD/AuthenticationType = https://login.windows.net/{site-tenant-id}/` — the server already knows the correct value. The SPA's `providerIdentifier` needs to match this exactly. By computing it at runtime from `Portal.tenant`, we avoid hardcoding the tenant ID into the AUTH_PROVIDERS array (which would break if the site moved between tenants, and required the maker to look up + paste the value during setup-auth).
+
+For non-workforce providers (External ID, generic OIDC, SAML2, etc.), the providerIdentifier points at the THIRD-PARTY tenant or resource — not the Power Pages tenant — so we can't derive it. It must be explicit.
+
+### `loginWithProvider()` — router that dispatches to local or external
+
+This is the **only function the Login UI should call**. It takes a provider config object and routes correctly based on `type`. Uses `resolveProviderIdentifier()` so Entra ID's runtime resolution works transparently.
+
+```typescript
+export async function loginWithProvider(
+ provider: AuthProviderConfig,
+ options: {
+ returnUrl?: string;
+ invitationCode?: string;
+ /** Local-only: credentials are required when provider.type === 'local' */
+ credentials?: { credential: string; password: string; rememberMe?: boolean };
+ } = {}
+): Promise<void> {
+ if (provider.type === 'local') {
+ if (!options.credentials) {
+ throw new Error('Local login requires credentials.');
+ }
+ return loginLocal(
+ options.credentials.credential,
+ options.credentials.password,
+ options.credentials.rememberMe ?? false,
+ options.returnUrl,
+ options.invitationCode
+ );
+ }
+
+ const providerIdentifier = resolveProviderIdentifier(provider);
+ return loginExternal(providerIdentifier, options.returnUrl, options.invitationCode);
+}
+```
+
+`loginLocal()` retains its existing signature (`credential, password, rememberMe, returnUrl, invitationCode`) — see "Local Login" section above. The router just delegates.
+
+### Login Page — Layout Patterns
+
+The Login page renders providers from `EXTERNAL_PROVIDERS` and (optionally) the local form. The structural skeleton is shared across all 4 layouts; only the provider section differs.
+
+**Shared skeleton (all layouts):**
+
+```tsx
+import { useEffect, useState, type FormEvent } from 'react'
+import { Link, useNavigate } from 'react-router-dom'
+import {
+ loginWithProvider,
+ AUTH_PROVIDERS,
+ LOCAL_PROVIDER,
+ EXTERNAL_PROVIDERS,
+ getAuthError,
+ getSessionExpiredMessage,
+ TermsRequiredError,
+} from '../services/authService'
+
+export default function Login() {
+ const navigate = useNavigate()
+ // ... state: errors, touched, serverError, successMessage, infoMessage,
+ // isSubmitting, externalSubmittingId, plus invitationCode parsing ...
+
+ function handleExternalSignIn(providerId: string) {
+ const provider = AUTH_PROVIDERS.find(p => p.id === providerId)
+ if (!provider) return
+ setExternalSubmittingId(providerId)
+ loginWithProvider(provider, { returnUrl: '/', invitationCode })
+ .catch(err => { setServerError(err.message); setExternalSubmittingId(undefined) })
+ }
+
+ function handleLocalSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ if (!LOCAL_PROVIDER) return
+ // validate, then:
+ loginWithProvider(LOCAL_PROVIDER, {
+ returnUrl: '/',
+ invitationCode,
+ credentials: { credential: email, password, rememberMe: false },
+ }).catch(err => {
+ if (err instanceof TermsRequiredError) return navigate('/terms')
+ setServerError(err.message)
+ })
+ }
+
+ // ...render based on LOGIN_LAYOUT (see patterns below)...
+}
+```
+
+#### Layout 1: Horizontal row (default)
+
+External provider buttons in a wrapping flex row at the top. Local form below an "OR SIGN IN WITH EMAIL" divider.
+
+**Text handling**: long display names wrap to two lines inside the button (buttons grow vertically to fit). This is preferred over single-line truncation with ellipsis — when text is center-aligned, ellipsis truncates from BOTH sides leaving the unreadable middle of the string visible (e.g., `WITH MICROSOFT ENTRA EXTER`). Allowing wrap gives a clean two-line button instead. The full label is also exposed via `title={p.displayName}` for hover tooltip and screen-reader accessibility.
+
+```tsx
+{EXTERNAL_PROVIDERS.length > 0 && (
+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginBottom: 24 }}>
+ {EXTERNAL_PROVIDERS.map(p => (
+ <button key={p.id} type="button"
+ title={p.displayName}
+ style={{
+ flex: '1 1 0',
+ minWidth: 0,
+ padding: '12px 16px',
+ lineHeight: 1.3,
+ textAlign: 'center',
+ // No whiteSpace:nowrap — allow text to wrap to two lines for long labels
+ }}
+ disabled={!!externalSubmittingId || isSubmitting}
+ onClick={() => handleExternalSignIn(p.id)}>
+ {externalSubmittingId === p.id ? 'Redirecting...' : p.displayName}
+ </button>
+ ))}
+ </div>
+)}
+{EXTERNAL_PROVIDERS.length > 0 && LOCAL_PROVIDER && <Divider label="OR SIGN IN WITH EMAIL" />}
+{LOCAL_PROVIDER && <LocalForm onSubmit={handleLocalSubmit} loginByEmail={LOCAL_PROVIDER.loginByEmail} />}
+```
+
+> **Why allow wrapping instead of truncating**: with center-aligned text in a flex button, `text-overflow: ellipsis` doesn't behave as expected — the overflow clips both sides of the string, showing the middle of the label without any ellipsis marker. Allowing wrap (removing `whiteSpace: 'nowrap'`) keeps the label fully readable on two lines. The button height auto-adjusts. If you need uniform button heights, set `minHeight: 56` (or similar) on the button style; rows with short labels still look fine, and rows with long labels match the wrapped height.
+
+#### Layout 2: Vertical stack
+
+External provider buttons stacked full-width vertically. Same divider + local form below.
+
+```tsx
+{EXTERNAL_PROVIDERS.length > 0 && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginBottom: 24 }}>
+ {EXTERNAL_PROVIDERS.map(p => (
+ <button key={p.id} type="button"
+ style={{ width: '100%', padding: '12px 16px' }}
+ disabled={!!externalSubmittingId || isSubmitting}
+ onClick={() => handleExternalSignIn(p.id)}>
+ {externalSubmittingId === p.id ? 'Redirecting...' : p.displayName}
+ </button>
+ ))}
+ </div>
+)}
+{/* divider + LocalForm — same as horizontal layout */}
+```
+
+#### Layout 3: Primary spotlight
+
+One featured provider (matching `PRIMARY_PROVIDER_ID`) shown as a large primary CTA. Other external providers tucked under a `<details>` disclosure. Local form below.
+
+```tsx
+const primary = EXTERNAL_PROVIDERS.find(p => p.id === PRIMARY_PROVIDER_ID) ?? EXTERNAL_PROVIDERS[0]
+const others = EXTERNAL_PROVIDERS.filter(p => p.id !== primary?.id)
+
+{primary && (
+ <button type="button" className="btn-primary"
+ style={{ width: '100%', padding: '14px 20px', fontSize: '1rem', marginBottom: 12 }}
+ disabled={!!externalSubmittingId || isSubmitting}
+ onClick={() => handleExternalSignIn(primary.id)}>
+ {externalSubmittingId === primary.id ? 'Redirecting...' : primary.displayName}
+ </button>
+)}
+{others.length > 0 && (
+ <details style={{ marginBottom: 24 }}>
+ <summary style={{ cursor: 'pointer', fontSize: '0.875rem', color: 'var(--color-text-muted)' }}>
+ More sign-in options
+ </summary>
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
+ {others.map(p => (
+ <button key={p.id} type="button"
+ style={{ width: '100%', padding: '10px 16px' }}
+ onClick={() => handleExternalSignIn(p.id)}>
+ {p.displayName}
+ </button>
+ ))}
+ </div>
+ </details>
+)}
+{/* divider + LocalForm — same as horizontal layout */}
+```
+
+#### Layout 4: Tabbed
+
+Tabs across the top — one tab per external provider, plus a "Email & password" tab when local exists. The selected tab's UI renders below.
+
+```tsx
+const [activeTab, setActiveTab] = useState<string>(
+ EXTERNAL_PROVIDERS[0]?.id ?? LOCAL_PROVIDER?.id ?? ''
+)
+
+const allTabs: { id: string; label: string }[] = [
+ ...EXTERNAL_PROVIDERS.map(p => ({ id: p.id, label: p.displayName })),
+ ...(LOCAL_PROVIDER ? [{ id: LOCAL_PROVIDER.id, label: 'Email & password' }] : []),
+]
+
+return (
+ <>
+ <div role="tablist" style={{
+ display: 'flex',
+ gap: 4,
+ borderBottom: '1px solid var(--color-border)',
+ marginBottom: 24,
+ overflowX: 'auto', // long tab labels can scroll horizontally if they exceed the card width
+ }}>
+ {allTabs.map(tab => (
+ <button key={tab.id} role="tab" aria-selected={activeTab === tab.id}
+ title={tab.label}
+ style={{
+ padding: '10px 16px', border: 'none', background: 'none',
+ borderBottom: activeTab === tab.id ? '2px solid var(--color-primary)' : '2px solid transparent',
+ cursor: 'pointer', fontWeight: activeTab === tab.id ? 600 : 400,
+ whiteSpace: 'nowrap', // tab labels stay single-line; container scrolls if needed
+ flexShrink: 0,
+ }}
+ onClick={() => setActiveTab(tab.id)}>
+ {tab.label}
+ </button>
+ ))}
+ </div>
+
+ {/* Render the active tab's UI */}
+ {(() => {
+ const external = EXTERNAL_PROVIDERS.find(p => p.id === activeTab)
+ if (external) {
+ return (
+ <button type="button" className="btn-primary"
+ style={{ width: '100%' }}
+ disabled={!!externalSubmittingId}
+ onClick={() => handleExternalSignIn(external.id)}>
+ {externalSubmittingId === external.id ? 'Redirecting...' : external.displayName}
+ </button>
+ )
+ }
+ if (LOCAL_PROVIDER && activeTab === LOCAL_PROVIDER.id) {
+ return <LocalForm onSubmit={handleLocalSubmit} loginByEmail={LOCAL_PROVIDER.loginByEmail} />
+ }
+ return null
+ })()}
+ </>
+)
+```
+
+#### Single-provider sites
+
+When `AUTH_PROVIDERS.length === 1`, all layouts collapse to a single button (external) or a single form (local). The layout choice doesn't visually matter — pick `horizontal-row` as the no-op default.
+
+---
+
+## Framework-Specific Patterns
+
+### React: useAuth Hook
+
+Create `src/hooks/useAuth.ts`:
+
+```typescript
+import { useState, useEffect, useCallback } from 'react';
+import type { PowerPagesUser } from '../types/powerPages';
+import {
+ getCurrentUser,
+ isAuthenticated as checkAuth,
+ getUserDisplayName,
+ getUserInitials,
+ getAuthProvider,
+ login as authLogin,
+ logout as authLogout,
+} from '../services/authService';
+
+interface UseAuthReturn {
+ user: PowerPagesUser | undefined;
+ isAuthenticated: boolean;
+ isLoading: boolean;
+ displayName: string;
+ initials: string;
+ providerType: string;
+ providerDisplayName: string;
+ login: (returnUrl?: string, credentials?: { username: string; password: string; rememberMe?: boolean }, invitationCode?: string) => Promise<void>;
+ logout: (returnUrl?: string) => void;
+ refresh: () => void;
+}
+
+export function useAuth(): UseAuthReturn {
+ const [user, setUser] = useState<PowerPagesUser | undefined>(undefined);
+ const [isLoading, setIsLoading] = useState(true);
+
+ const refresh = useCallback(() => {
+ // Spread `getCurrentUser()` into a new object so React sees a fresh
+ // reference. Otherwise refresh() after an in-place mutation of
+ // `window.Microsoft.Dynamic365.Portal.User` (used by the profile page
+ // to reflect saves without a full reload) would be a no-op: setState
+ // with the same reference is skipped by React.
+ const current = getCurrentUser();
+ setUser(current ? { ...current } : undefined);
+ setIsLoading(false);
+ }, []);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const provider = getAuthProvider();
+
+ return {
+ user,
+ isAuthenticated: checkAuth(),
+ isLoading,
+ displayName: getUserDisplayName(),
+ initials: getUserInitials(),
+ providerType: provider.type,
+ providerDisplayName: provider.displayName || 'Sign In',
+ login: authLogin,
+ logout: authLogout,
+ refresh,
+ };
+}
+```
+
+### React: AuthButton Component
+
+Create `src/components/AuthButton.tsx`:
+
+```tsx
+import { useAuth } from '../hooks/useAuth';
+import './AuthButton.css';
+
+export function AuthButton() {
+ const { isAuthenticated, isLoading, displayName, initials, providerDisplayName, login, logout } = useAuth();
+
+ if (isLoading) {
+ return <div className="auth-button auth-loading"><span className="auth-spinner" /></div>;
+ }
+
+ if (!isAuthenticated) {
+ return (
+ <button className="auth-button auth-sign-in" onClick={() => login()}>
+ {providerDisplayName}
+ </button>
+ );
+ }
+
+ return (
+ <div className="auth-button auth-signed-in">
+ <span className="auth-avatar">{initials}</span>
+ <span className="auth-name">{displayName}</span>
+ <button className="auth-sign-out" onClick={() => logout()}>
Sign Out
</button>
</div>
@@ -305,6 +1466,200 @@ export function AuthButton() {
}
```
+### React: LocalLoginForm Component (Local Auth Only)
+
+When the provider type is `local`, also create `src/components/LocalLoginForm.tsx`. This component handles:
+- Login with email or username (based on `loginByEmail` setting)
+- Server-side auth error display (parsed from `?message=` query params)
+- Link to forgot password page
+- Link to registration page (when `OpenRegistrationEnabled` is true)
+
+```tsx
+import { useState, useEffect } from 'react';
+import { login, getAuthProvider, getAuthError } from '../services/authService';
+import './LocalLoginForm.css';
+
+export function LocalLoginForm() {
+ const [credential, setCredential] = useState('');
+ const [password, setPassword] = useState('');
+ const [rememberMe, setRememberMe] = useState(false);
+ const [error, setError] = useState('');
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const provider = getAuthProvider();
+ const isEmailMode = provider.loginByEmail ?? true;
+
+ // Check for server-side auth errors passed via URL query params
+ useEffect(() => {
+ const serverError = getAuthError();
+ if (serverError) setError(serverError);
+ }, []);
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setError('');
+ setIsSubmitting(true);
+ try {
+ await login(undefined, { username: credential, password, rememberMe });
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Login failed. Please check your credentials.');
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <form className="local-login-form" onSubmit={handleSubmit}>
+ {error && <div className="form-error" role="alert">{error}</div>}
+ <div className="form-field">
+ <label htmlFor="credential">{isEmailMode ? 'Email' : 'Username'}</label>
+ <input
+ id="credential"
+ type={isEmailMode ? 'email' : 'text'}
+ value={credential}
+ onChange={(e) => setCredential(e.target.value)}
+ required
+ autoComplete={isEmailMode ? 'email' : 'username'}
+ />
+ </div>
+ <div className="form-field">
+ <label htmlFor="password">Password</label>
+ <input
+ id="password"
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ required
+ autoComplete="current-password"
+ />
+ </div>
+ <div className="form-field form-checkbox">
+ <label>
+ <input
+ type="checkbox"
+ checked={rememberMe}
+ onChange={(e) => setRememberMe(e.target.checked)}
+ />
+ Remember me
+ </label>
+ </div>
+ <button type="submit" disabled={isSubmitting}>
+ {isSubmitting ? 'Signing in...' : 'Sign In'}
+ </button>
+ <div className="form-links">
+ <a href="/Account/Login/ForgotPassword">Forgot password?</a>
+ </div>
+ </form>
+ );
+}
+```
+
+> **Note on "Create an account" link:** Only add a registration link (`<a href="/registration">Create an account</a>`) to the login form when `OpenRegistrationEnabled` is `true`. Since this is a server-side setting, the skill should include the link when it creates the `LocalLoginForm` and the `OpenRegistrationEnabled` site setting is being set to `true`. If the user chose invitation-only registration (where `OpenRegistrationEnabled` is `false`), omit the link — users register via invitation links instead.
+
+### React: RegisterForm Component (Local Auth Only)
+
+When local authentication is configured, create `src/pages/Registration.tsx` and a `/registration` route (NOT `/register` — that path conflicts with the server's `/Register` route). This component handles new user registration with email/username and password. It calls the `register()` function from authService, which handles the Web Forms ViewState pattern internally.
+
+> **Dev mode:** The registration page should skip the auth redirect when running on localhost, because the mock user is always "authenticated" and would prevent testing the form. Add: `const isDev = window.location.hostname === 'localhost'` and only redirect if `isAuthenticated && !isDev`.
+
+```tsx
+import { useState, useEffect } from 'react';
+import { register, getAuthProvider, getAuthError } from '../services/authService';
+import './LocalLoginForm.css';
+
+export function RegisterForm() {
+ const [credential, setCredential] = useState('');
+ const [password, setPassword] = useState('');
+ const [confirmPassword, setConfirmPassword] = useState('');
+ const [error, setError] = useState('');
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const provider = getAuthProvider();
+ const isEmailMode = provider.loginByEmail ?? true;
+
+ // Check for server-side registration errors passed via URL query params
+ useEffect(() => {
+ const serverError = getAuthError();
+ if (serverError) setError(serverError);
+ }, []);
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ setError('');
+
+ if (password !== confirmPassword) {
+ setError('Passwords do not match.');
+ return;
+ }
+
+ setIsSubmitting(true);
+ try {
+ // Parse invitation code from URL if present
+ const params = new URLSearchParams(window.location.search);
+ const invitationCode = params.get('invitationCode') || undefined;
+
+ await register(
+ isEmailMode
+ ? { email: credential, password, confirmPassword }
+ : { username: credential, password, confirmPassword },
+ '/',
+ invitationCode
+ );
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <form className="local-login-form" onSubmit={handleSubmit}>
+ <h2>Create an Account</h2>
+ {error && <div className="form-error" role="alert">{error}</div>}
+ <div className="form-field">
+ <label htmlFor="credential">{isEmailMode ? 'Email' : 'Username'}</label>
+ <input
+ id="credential"
+ type={isEmailMode ? 'email' : 'text'}
+ value={credential}
+ onChange={(e) => setCredential(e.target.value)}
+ required
+ autoComplete={isEmailMode ? 'email' : 'username'}
+ />
+ </div>
+ <div className="form-field">
+ <label htmlFor="password">Password</label>
+ <input
+ id="password"
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ required
+ autoComplete="new-password"
+ />
+ </div>
+ <div className="form-field">
+ <label htmlFor="confirmPassword">Confirm Password</label>
+ <input
+ id="confirmPassword"
+ type="password"
+ value={confirmPassword}
+ onChange={(e) => setConfirmPassword(e.target.value)}
+ required
+ autoComplete="new-password"
+ />
+ </div>
+ <button type="submit" disabled={isSubmitting}>
+ {isSubmitting ? 'Creating account...' : 'Create Account'}
+ </button>
+ <div className="form-links">
+ <a href="/login">Already have an account? Sign in</a>
+ </div>
+ </form>
+ );
+}
+```
+
Create `src/components/AuthButton.css`:
```css
@@ -394,6 +1749,7 @@ import {
isAuthenticated as checkAuth,
getUserDisplayName,
getUserInitials,
+ getAuthProvider,
login as authLogin,
logout as authLogout,
} from '../services/authService';
@@ -405,6 +1761,9 @@ export function useAuth() {
const isAuthenticated = computed(() => checkAuth());
const displayName = computed(() => getUserDisplayName());
const initials = computed(() => getUserInitials());
+ const provider = getAuthProvider();
+ const providerType = computed(() => provider.type);
+ const providerDisplayName = computed(() => provider.displayName || 'Sign In');
function refresh() {
user.value = getCurrentUser();
@@ -421,6 +1780,8 @@ export function useAuth() {
isLoading,
displayName,
initials,
+ providerType,
+ providerDisplayName,
login: authLogin,
logout: authLogout,
refresh,
@@ -441,8 +1802,10 @@ import {
isAuthenticated as checkAuth,
getUserDisplayName,
getUserInitials,
+ getAuthProvider,
login as authLogin,
logout as authLogout,
+ type AuthProviderConfig,
} from '../../services/authService';
@Injectable({ providedIn: 'root' })
@@ -469,8 +1832,12 @@ export class AuthService {
return getUserInitials();
}
- login(returnUrl?: string): Promise<void> {
- return authLogin(returnUrl);
+ get provider(): AuthProviderConfig {
+ return getAuthProvider();
+ }
+
+ login(returnUrl?: string, credentials?: { username: string; password: string; rememberMe?: boolean }, invitationCode?: string): Promise<void> {
+ return authLogin(returnUrl, credentials, invitationCode);
}
logout(returnUrl?: string): void {
@@ -490,39 +1857,1985 @@ For Astro projects, use `src/services/authService.ts` directly in component scri
---
-## Site Settings
+## Site Settings Reference
-### Required: Disable Profile Redirect
+### Required: Disable Profile Redirect (All Providers)
Power Pages code sites do not have a built-in profile page. After login, Power Pages attempts to redirect to `/profile`, which returns a 404 on code sites. Disable this with a site setting:
**Site setting name:** `Authentication/Registration/ProfileRedirectEnabled`
**Value:** `false`
-Create as a YAML file in `.powerpages-site/site-settings/`:
-
-```yaml
-id: <generated-uuid>
-name: Authentication/Registration/ProfileRedirectEnabled
-value: false
-```
-
-### Other Useful Settings
+### General Registration Settings
| Setting | Value | Description |
|---------|-------|-------------|
| `Authentication/Registration/Enabled` | `true` | Enable user registration |
+| `Authentication/Registration/ExternalLoginEnabled` | `true` | Enable external identity provider login |
| `Authentication/Registration/OpenRegistrationEnabled` | `true`/`false` | Allow self-registration |
| `Authentication/Registration/InvitationEnabled` | `true`/`false` | Allow invitation-based registration |
-| `Authentication/Registration/LocalLoginEnabled` | `false` | Disable local (username/password) login when using Entra ID only |
+| `Authentication/Registration/LocalLoginEnabled` | `true`/`false` | Enable local username/password login |
+| `Authentication/Registration/LocalLoginByEmail` | `true`/`false` | Allow login by email instead of username |
+| `Authentication/Registration/RememberMeEnabled` | `true`/`false` | Show "Remember me" checkbox on login |
+| `Authentication/Registration/TwoFactorEnabled` | `true`/`false` | Enable two-factor authentication |
+| `Authentication/Registration/LoginButtonAuthenticationType` | `(provider)` | Default login button provider type |
-These can be configured via the Power Pages admin center, PAC CLI, or Dataverse Web API as needed.
+### OpenID Connect Provider Settings
----
+Pattern: `Authentication/OpenIdConnect/{ProviderName}/{SettingName}`
-## Important Notes
+| Setting | Description |
+|---------|-------------|
+| `Authority` | The OIDC authority URL (metadata endpoint base) |
+| `ClientId` | The registered application's client ID |
+| `ClientSecret` | The registered application's client secret -- **never commit to source control** |
+| `RedirectUri` | The callback URL (typically `{site-url}/signin-{provider}`) |
+| `AuthenticationType` | Unique identifier for this provider (used as the `provider` value in ExternalLogin) |
+| `Caption` | Display name shown on the login button |
+| `ExternalLogoutEnabled` | `true` to sign out of the IdP on logout |
+| `PostLogoutRedirectUri` | URL to redirect to after external logout |
+| `RegistrationClaimsMapping` | **Comma-separated `contactfield=claimtype` pairs** (NOT JSON). Applied once at first sign-in. Example: `firstname=given_name,lastname=family_name,emailaddress1=email`. |
+| `LoginClaimsMapping` | Same format. Applied every login (overwrites contact fields). Use sparingly to avoid overwriting manual edits. |
-- **Auth only works on deployed sites**: The `/_layout/tokenhtml` endpoint and `window.Microsoft.Dynamic365.Portal` object are only available when the site is served from Power Pages, not during local `npm run dev`.
-- **Mock data for development**: The auth service includes a mock user pattern for local development. The mock user has configurable roles so developers can test role-based UI locally.
-- **Security**: Always validate permissions server-side via table permissions. Client-side auth checks are for UX only — a direct API call bypasses all client-side checks.
-- **Entra ID configuration**: The identity provider must be configured in the Power Pages admin center. This skill creates the client-side code but does not configure the identity provider itself.
+> **Workforce Entra ID (AzureAD provider) — different claim mapping needed.** The Power-Pages-auto-configured AzureAD provider uses v1.0 tokens by default (issuer `sts.windows.net/{tid}/`). **v1.0 workforce tokens do NOT include the `email` claim** by default. To populate `emailaddress1` for workforce users, use `upn` instead — it's the user's principal name (`[email protected]`) and is always emitted for workforce accounts. The correct mapping for workforce Entra ID is:
+>
+> ```
+> firstname=given_name,lastname=family_name,emailaddress1=upn
+> ```
+>
+> The setup-auth skill writes these settings silently in Phase 8.1 when Microsoft Entra ID is configured — no question is asked because the mapping is deterministic for workforce. Without it, contacts created on first sign-in have the `oid` link but empty firstname/lastname/email (`window.Microsoft.Dynamic365.Portal.User` renders with `contactId` but all profile fields empty).
+
+### v1.0 vs v2.0 tokens — claim availability by Entra product
+
+Different Entra products issue different token versions with different claim defaults. **This matters for the `RegistrationClaimsMapping` value** because some claim types don't exist in v1.0 tokens.
+
+| Entra product | Default token version | Issuer pattern | `email` claim | `upn` claim | `preferred_username` claim | `given_name` / `family_name` |
+|---|---|---|---|---|---|---|
+| **Microsoft Entra ID (workforce, AzureAD)** | v1.0 | `sts.windows.net/{tid}/` | ❌ Not by default (requires v2.0 + email scope + verified email) | ✅ Yes (`[email protected]` or custom domain) | ❌ v2.0-only | ✅ Yes |
+| **Microsoft Entra External ID (OpenIdConnect)** | v2.0 | `{subdomain}.ciamlogin.com/{tid}/v2.0` | ✅ Yes (with email user flow attribute) | ❌ Not typically emitted | ✅ Yes | ✅ Yes (with user flow attributes) |
+| **Azure AD B2C (legacy)** | v2.0 | `{tenant}.b2clogin.com/{policy}/v2.0/` | ✅ Yes (if email user flow attribute selected) | ❌ Not typically | ✅ Yes | ✅ Yes (with user flow attributes) |
+
+**Implication for `RegistrationClaimsMapping`**:
+- **AzureAD (workforce)**: `emailaddress1=upn` (skill writes this silently)
+- **Entra External ID**: `emailaddress1=email` (skill asks via Profile mapping question; default uses `email`)
+- **Other v2.0 OIDC providers**: depends on provider — Okta, Auth0, etc. mostly emit `email`. User can choose.
+
+If you need workforce Entra ID to emit the `email` claim instead of relying on UPN (e.g., for organizations where UPN ≠ email):
+
+1. Edit the app registration in Entra admin center → **Token configuration** → **Add optional claim** → `email`
+2. Verify the user has a verified email in their Entra profile (`mail` attribute)
+3. The token will then include `email` and you can switch the mapping to `emailaddress1=email`
+
+But for the default config that Power Pages auto-creates, `upn` is the reliable choice.
+
+### Entra External ID Provider Settings
+
+Entra External ID uses the same `Authentication/OpenIdConnect/{ProviderName}/{SettingName}` path as generic OIDC. The authority URL may use `ciamlogin.com` (default) or a custom domain configured for the tenant.
+
+All settings from the OpenID Connect section above apply to Entra External ID providers.
+
+### SAML2 Provider Settings
+
+Pattern: `Authentication/SAML2/{ProviderName}/{SettingName}`
+
+| Setting | Description |
+|---------|-------------|
+| `MetadataAddress` | URL of the SAML IdP metadata XML |
+| `AuthenticationType` | Unique identifier for this provider |
+| `ServiceProviderRealm` | The SP entity ID (typically the site URL) |
+| `AssertionConsumerServiceUrl` | The ACS URL (typically `{site-url}/signin-{provider}`) |
+| `Caption` | Display name shown on the login button |
+| `SignAuthenticationRequests` | `true` to sign SAML authn requests |
+| `ExternalLogoutEnabled` | `true` to enable SAML Single Logout (SLO) |
+| `NameIdPolicy` | Format of the NameID claim (e.g., `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`) |
+| `AuthnContextClassRef` | Authentication context class (e.g., `urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport`) |
+| `ForceAuthn` | `true` to force re-authentication even if session exists at IdP |
+
+### WS-Federation Provider Settings
+
+Pattern: `Authentication/WsFederation/{ProviderName}/{SettingName}`
+
+| Setting | Description |
+|---------|-------------|
+| `MetadataAddress` | URL of the WS-Fed metadata XML |
+| `AuthenticationType` | Unique identifier for this provider |
+| `Wtrealm` | The relying party realm (typically the site URL) |
+| `Caption` | Display name shown on the login button |
+| `ExternalLogoutEnabled` | `true` to enable federated logout |
+
+### Local Authentication Settings
+
+| Setting | Value | Description |
+|---------|-------|-------------|
+| `Authentication/Registration/LocalLoginEnabled` | `true` | Enable local login |
+| `Authentication/Registration/LocalLoginByEmail` | `true` | Allow login by email instead of username |
+| `Authentication/Registration/LocalLoginDeprecated` | `false` | Set to `true` to deprecate local login |
+| `Authentication/Registration/RememberMeEnabled` | `true`/`false` | Show "Remember me" checkbox on login form |
+
+### Social OAuth Provider Settings
+
+Social providers use the `Authentication/OpenAuth/{ProviderName}/` site setting path:
+
+| Setting Pattern | Description |
+|-----------------|-------------|
+| `Authentication/OpenAuth/{SocialProvider}/ClientId` | App ID from the social provider (generic) |
+| `Authentication/OpenAuth/{SocialProvider}/ClientSecret` | App secret from the social provider (generic) |
+| `Authentication/OpenAuth/{SocialProvider}/Caption` | Button label (e.g., "Sign in with Facebook") |
+
+**Facebook-specific settings** -- Facebook uses `AppId` and `AppSecret` (not `ClientId`/`ClientSecret`). The server falls back to `ClientId`/`ClientSecret` if `AppId`/`AppSecret` are not set, but the canonical setting names are:
+
+| Setting | Description |
+|---------|-------------|
+| `Authentication/OpenAuth/Facebook/AppId` | Facebook App ID from the Facebook Developer Console |
+| `Authentication/OpenAuth/Facebook/AppSecret` | Facebook App Secret from the Facebook Developer Console |
+
+**Google-specific settings:**
+
+| Setting | Description |
+|---------|-------------|
+| `Authentication/OpenAuth/Google/ClientId` | Google Client ID from the Google Cloud Console |
+| `Authentication/OpenAuth/Google/ClientSecret` | Google Client Secret from the Google Cloud Console |
+
+> **Security Warning:** Never commit `ClientSecret` or `AppSecret` values to source control. Secrets must be stored as Dataverse environment variables using `create-environment-variable.js`, then linked to site settings via `create-site-setting.js --envVarSchema`. Do NOT create site setting YAML files with placeholder secret values — use the environment variable pattern exclusively. The user updates actual secret values through the Power Apps maker portal (make.powerapps.com).
+
+### Two-Factor Cookie Settings
+
+| Setting | Description |
+|---------|-------------|
+| `Authentication/TwoFactorCookie/AuthenticationType` | Custom authentication type for 2FA cookie (defaults to `TwoFactorCookie`) |
+| `Authentication/TwoFactorCookie/ExpireTimeSpan` | 2FA cookie expiry (defaults to `00:05:00` / 5 minutes) |
+
+### Application Cookie Settings
+
+| Setting | Description |
+|---------|-------------|
+| `Authentication/ApplicationCookie/CookieName` | Custom cookie name |
+| `Authentication/ApplicationCookie/CookieDomain` | Cookie domain scope |
+| `Authentication/ApplicationCookie/ExpireTimeSpan` | Session timeout (e.g., `01:00:00` for 1 hour) |
+| `Authentication/ApplicationCookie/SlidingExpiration` | `true` to renew cookie on each request |
+
+---
+
+## Entra External ID Provider
+
+Entra External ID is Microsoft's customer identity and access management (CIAM) solution for customer-facing applications. It is a separate product from Azure AD B2C — do not conflate the two. It uses OpenID Connect underneath. The authority URL defaults to `{tenant}.ciamlogin.com` but may use a custom domain (e.g., `login.contoso.com`).
+
+### External ID Provider Type
+
+```typescript
+export type AuthProviderType =
+ | 'entra-id'
+ | 'oidc'
+ | 'saml2'
+ | 'ws-federation'
+ | 'local'
+ | 'social'
+ | 'entra-external-id';
+```
+
+### External ID AUTH_PROVIDER Configuration
+
+```typescript
+const AUTH_PROVIDER: AuthProviderConfig = {
+ type: 'entra-external-id',
+ providerIdentifier: 'https://{tenant}.ciamlogin.com/{tenant}.onmicrosoft.com/v2.0/', // Must match AuthenticationType site setting
+ displayName: 'Sign in with External ID',
+};
+```
+
+### External ID Site Settings
+
+Pattern: `Authentication/OpenIdConnect/{ProviderName}/{SettingName}`
+
+Entra External ID uses the same OpenID Connect site setting path:
+
+| Setting | Description |
+|---------|-------------|
+| `Authority` | External ID authority URL (e.g., `https://{tenant}.ciamlogin.com/{tenant}.onmicrosoft.com/v2.0/` or custom domain like `https://login.contoso.com/{tenant-id}/v2.0/`) |
+| `ClientId` | Application (client) ID from the External ID app registration |
+| `AuthenticationType` | Unique identifier for this provider (typically the authority URL) |
+| `RedirectUri` | Callback URL (e.g., `{site-url}/signin-{provider}`) |
+| `ExternalLogoutEnabled` | `true` to sign out of External ID on logout |
+| `Caption` | Display name shown on the login button |
+
+---
+
+## Two-Factor Authentication (2FA)
+
+> **NOT scaffolded by this skill.** Power Pages built-in 2FA uses server-rendered `SendCode` and `VerifyCode` pages between the credential POST and successful sign-in. These pages cannot be SPA-ified — the 2FA token state lives in server-side cookies (`TwoFactorCookie`), the code-entry view is an ASP.NET MVC page rendered by the server, and there's no client-side hook to replace it. Bouncing the user out to a server-rendered page mid-login breaks the SPA experience. The skill therefore does NOT create `TwoFactorEnabled`, `RememberMeEnabled`, or `RememberBrowserEnabled` site settings. For MFA needs, recommend enabling it at the identity provider layer (Entra External ID conditional access, B2C user flow MFA, Auth0 Guardian, Okta Verify, etc.) — IdP-level MFA is transparent to Power Pages and keeps the entire UX inside the IdP's branded experience. The rest of this section documents Power Pages' server-side 2FA behavior for reference (so the executor can recognize and explain it if a maker has it enabled manually) but does NOT instruct the skill to create the settings.
+
+Two-factor authentication is an optional follow-on step that occurs after primary authentication (either local login or external login). It is controlled by the `Authentication/Registration/TwoFactorEnabled` site setting.
+
+### 2FA Site Settings
+
+| Setting | Value | Description |
+|---------|-------|-------------|
+| `Authentication/Registration/TwoFactorEnabled` | `true`/`false` | Enable two-factor authentication |
+| `Authentication/Registration/RememberBrowserEnabled` | `true`/`false` | Allow "remember this browser" option to skip 2FA on subsequent logins |
+| `Authentication/TwoFactorCookie/AuthenticationType` | `(string)` | Custom authentication type for the 2FA cookie (defaults to `TwoFactorCookie`) |
+| `Authentication/TwoFactorCookie/ExpireTimeSpan` | `(timespan)` | 2FA cookie expiry (defaults to 5 minutes) |
+
+### 2FA Flow (Server-Side)
+
+The 2FA flow is entirely server-side. The client-side auth service does not need to implement 2FA logic directly -- the server handles the redirect chain:
+
+1. User completes primary authentication (local login or external login)
+2. `SignInManager.PasswordSignInAsync` (local) or `SignInManager.ExternalSignInAsync` (external) returns `SignInStatus.RequiresVerification`
+3. Server redirects to `/Account/Login/SendCode` with `ReturnUrl`, `InvitationCode`, and `RememberMe` parameters
+4. The `SendCode` action retrieves valid 2FA providers for the user via `UserManager.GetValidTwoFactorProvidersAsync`
+5. If only one provider exists, the code is sent automatically; otherwise, the user selects a provider
+6. Server sends the verification code via `SignInManager.SendTwoFactorCodeAsync`
+7. Server redirects to `/Account/Login/VerifyCode` with the selected provider, return URL, and remember preferences
+8. User enters the verification code
+9. `SignInManager.TwoFactorSignInAsync` validates the code
+10. On success, the session is fully established
+
+### 2FA Client-Side Considerations
+
+Since 2FA is server-managed, the client-side auth service needs only to be aware that:
+- After calling `login()`, the page may redirect to a 2FA verification form instead of completing immediately
+- The `window.Microsoft.Dynamic365.Portal.User` object will only be populated after 2FA is complete
+- The `RememberMe` flag from the login form is threaded through the 2FA flow
+
+No additional client-side components are needed for 2FA -- the server renders the SendCode and VerifyCode pages using its own ASP.NET views.
+
+---
+
+## Invitation-Based Registration
+
+Power Pages supports invitation code-based registration where users receive an invitation code (typically via email) that grants them access to register on the site.
+
+### Invitation Site Settings
+
+| Setting | Value | Description |
+|---------|-------|-------------|
+| `Authentication/Registration/Enabled` | `true` | Master switch; must be true for any registration path |
+| `Authentication/Registration/OpenRegistrationEnabled` | `true`/`false` | `false` for invitation-only, `true` for open or both |
+| `Authentication/Registration/InvitationEnabled` | `true` | Required for invitation flow |
+
+> **`Authentication/Registration/RequireInvitationCode` is NOT a real server setting.** The Power Pages server (`crm.solutions.portal/Samples/MasterPortal/Areas/Account/Models/RegistrationManager.cs`) never reads this name. The "require invitation" behavior is enforced entirely by the combination `OpenRegistrationEnabled = false` + `InvitationEnabled = true` (the server's gating rule: if `OpenRegistrationEnabled=false` AND no invitation code is provided on the registration POST, return 404).
+
+### Invitation Flow (SPA)
+
+The full SPA invitation flow is documented in the **"Redeem Invitation Flow for SPA Sites"** section above. Summary:
+
+1. User receives an invitation link: `{site-url}/Account/Login/RedeemInvitation?invitation={code}`
+2. Code-Site-Shell-Header script redirects to SPA `/redeem-invitation?invitation={code}`
+3. SPA RedeemInvitation page calls `redeemInvitation(code, redeemByLogin)`:
+ - Server returns 302 (caught as `opaqueredirect`) → SPA navigates to `/registration?invitationCode={code}`
+ - Server returns 200 with Login view → SPA navigates to `/login?invitationCode={code}`
+ - Server returns 200 with validation summary → throw parsed error
+4. The destination page (Registration or Login) accepts `invitationCode` from URL and passes it through to the final POST
+5. Server's `InvitationManager.RedeemAsync()` links the invitation to the user's contact during registration or in `RedirectOnPostAuthenticate` after login
+
+To pass an invitation code from a URL (e.g., `?invitationCode=abc123`):
+
+```typescript
+const params = new URLSearchParams(window.location.search);
+const invitationCode = params.get('invitationCode') || undefined;
+
+// For external login with invitation
+await login('/dashboard', undefined, invitationCode);
+
+// For local login with invitation
+await login('/dashboard', { username: email, password, rememberMe: true }, invitationCode);
+```
+
+---
+
+## Secret Management
+
+> **Security Warning:** Never commit `ClientSecret`, `AppSecret`, or any other credential values to source control.
+
+### Best Practices
+
+- **Use Azure Key Vault (recommended)** — store secrets in Key Vault, then create a Dataverse environment variable with `--type secret` referencing the Key Vault secret URI. Link the env var to a site setting via `create-site-setting.js --envVarSchema`. This ensures secrets are never stored in YAML files, conversation history, or Dataverse as plain text.
+- **Fallback: plain environment variables** — if Key Vault is not available, create Dataverse environment variables with placeholder values and update them via the Power Apps maker portal ([make.powerapps.com](https://make.powerapps.com)) → Solutions → Default Solution → Environment variables.
+- **Never ask for secret values** in the conversation — secret values must never pass through the chat. Instruct the user to store secrets via Azure CLI or the Azure Portal, then share only the Key Vault secret URI.
+- **Never store secrets** in `authService.ts`, environment files (`.env`), site setting YAML files, or any file tracked by version control.
+- **Review before committing**: Always verify that no actual `ClientSecret`, `AppSecret`, API key, or certificate values are included in your commits.
+- **The `providerIdentifier` field** in `AUTH_PROVIDER` is NOT a secret -- it is a public identifier (like a URL or provider name) that identifies which identity provider to use.
+
+---
+
+## Terms and Conditions for SPA Sites
+
+### Prerequisites
+
+The Terms feature requires three things to work:
+
+1. **GDPR solution installed** (`msdynce_PortalPrivacyExtensions`) — without this, `IsGdprEnabled()` returns false and terms are disabled
+2. **Site setting** `Authentication/Registration/TermsAgreementEnabled = true`
+3. **Content snippet** `Account/Signin/TermsAndConditionsCopy` must exist with non-empty content — if blank, terms are disabled even with the setting enabled
+
+### How it works
+
+After login or registration, the server checks terms (in the `LoginController` and `RegistrationManager`):
+
+```
+IsTermsAndConditionsEnabled():
+ if (!TermsConsentEnabled || !IsGdprEnabled) return false
+ if (snippet "Account/Signin/TermsAndConditionsCopy" is empty) return false
+ return true
+```
+
+If enabled, the server redirects to the terms page instead of the ReturnUrl:
+- **Local login**: redirects to `/Account/Login/TermsAndConditions` (no query string for the local-auth case)
+- **Local registration**: redirects to `/TermsAndConditions?ReturnUrl=%2F`
+- **External login (Entra External ID, OIDC, social)**: redirects from `/Account/Login/ExternalLoginCallback` to `/Account/Login/TermsAndConditions?ReturnUrl=/&UseExternalSignInAsync=True&IsFacebook=False&IsInternalAADUser=False`. The query-string flags tell the server which sign-in completion path to take after acceptance — `UseExternalSignInAsync=True` is the critical one for external users.
+
+The server also sets a deferred sign-in cookie (`DeferredLocalLoginCookie` for local, external sign-in deferred cookie for external) — sign-in completes only after terms are accepted.
+
+### SPA coverage
+
+| Auth flow | SPA detection mechanism |
+|---|---|
+| Local login / registration | `fetch()` response URL check → throw `TermsRequiredError` → page navigates to `/terms` |
+| External login (Entra External ID, OIDC, social) | Browser navigates to `/Account/Login/TermsAndConditions` after IdP callback → Code-Site-Shell-Header redirect script catches it → forwards to `/terms` with query string preserved |
+
+### Auth Service: TermsRequiredError and acceptTerms
+
+Add to `authService.ts`:
+
+```typescript
+// Thrown when the server redirects to the terms page after login/registration.
+export class TermsRequiredError extends Error {
+ constructor() {
+ super('Terms and conditions acceptance required.');
+ this.name = 'TermsRequiredError';
+ }
+}
+```
+
+**Detection in `loginLocal()` and `register()`** — add before the redirect handling:
+
+```typescript
+// Check if the server redirected to terms (catches both URL patterns)
+if (response.url.includes('TermsAndConditions')) {
+ throw new TermsRequiredError();
+}
+```
+
+**`acceptTerms()` function — query-string-aware:**
+
+The function must read flags from `window.location.search` (set by the server's redirect URL for external auth) instead of hardcoding them. Without this, external users' POST to `/Account/Login/TermsAndConditions` sends `UseExternalSignInAsync=False` and the server won't complete their sign-in.
+
+```typescript
+export async function acceptTerms(returnUrl?: string): Promise<void> {
+ if (isDevelopment) {
+ window.location.href = returnUrl || '/';
+ return;
+ }
+
+ // Read flags from the URL the user landed at. For external auth, the server's
+ // redirect URL is /Account/Login/TermsAndConditions?ReturnUrl=/&UseExternalSignInAsync=True&...
+ // For local auth, the SPA navigates here directly with no query string — defaults apply.
+ const params = new URLSearchParams(window.location.search);
+ const useExternalSignInAsync = params.get('UseExternalSignInAsync') || 'False';
+ const isFacebook = params.get('IsFacebook') || 'False';
+ const isInternalAADUser = params.get('IsInternalAADUser') || 'False';
+ const queryReturnUrl = params.get('ReturnUrl') || returnUrl || '/';
+
+ // Preserve the original query string when fetching / POSTing to the server terms page.
+ // The server reads the flags from the URL too, not just the body.
+ const queryString = window.location.search;
+ const serverTermsUrl = `/Account/Login/TermsAndConditions${queryString}`;
+
+ const pageResponse = await fetch(serverTermsUrl, {
+ credentials: 'same-origin',
+ redirect: 'follow',
+ });
+
+ // Use the final URL the server responded from (may differ between login/registration flows).
+ const finalTermsUrl = new URL(pageResponse.url).pathname + new URL(pageResponse.url).search;
+
+ const pageHtml = await pageResponse.text();
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(pageHtml, 'text/html');
+
+ const antiForgeryToken = (doc.querySelector('input[name="__RequestVerificationToken"]') as HTMLInputElement)?.value || '';
+
+ // Body flags match query-string flags so the server treats this as the correct sign-in flow type.
+ // DO NOT hardcode UseExternalSignInAsync=False — that breaks external auth completion.
+ const body = new URLSearchParams();
+ body.set('__RequestVerificationToken', antiForgeryToken);
+ body.set('InvitationCode', '');
+ body.set('IsFacebook', isFacebook);
+ body.set('UseExternalSignInAsync', useExternalSignInAsync);
+ body.set('IsInternalAADUser', isInternalAADUser);
+ body.set('IsTermsAndConditionsAccepted', 'true');
+
+ const response = await fetch(finalTermsUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: body.toString(),
+ credentials: 'same-origin',
+ redirect: 'follow',
+ });
+
+ // Default to the ReturnUrl from the query string if no explicit one was passed —
+ // that's where the server originally wanted to send the user.
+ returnUrl = returnUrl ?? queryReturnUrl;
+
+ if (response.redirected || response.ok) {
+ window.location.href = returnUrl || '/';
+ return;
+ }
+
+ const responseHtml = await response.text();
+ const errors = parseServerErrors(responseHtml);
+ if (errors.length > 0) throw new Error(errors.join(' '));
+ throw new Error('Failed to accept terms. Please try again.');
+}
+```
+
+### React: Terms Page Component
+
+Create `src/pages/Terms.tsx`. The terms content is hardcoded from the snippet values collected during skill setup:
+
+```tsx
+import { useEffect, useState } from 'react'
+import { Link } from 'react-router-dom'
+import { acceptTerms } from '../services/authService'
+
+// Content from Power Pages content snippets — hardcoded during skill setup.
+// Update these values and redeploy when the site creator changes the terms.
+const TERMS_HEADING = 'Terms and Conditions'
+const TERMS_CONTENT = `
+ <p>By using this portal, you agree to the following terms of service.</p>
+ <h3>1. Acceptance of Terms</h3>
+ <p>By accessing and using this portal, you accept and agree to be bound by these terms.</p>
+ <h3>2. Privacy & Data</h3>
+ <p>We collect and process your personal data in accordance with our privacy policy.</p>
+ <h3>3. Account Responsibility</h3>
+ <p>You are responsible for maintaining the confidentiality of your account credentials.</p>
+ <h3>4. Changes to Terms</h3>
+ <p>We reserve the right to update these terms at any time.</p>
+`
+const TERMS_AGREEMENT_TEXT = 'I agree to these terms and conditions.'
+const TERMS_BUTTON_TEXT = 'Confirm'
+
+export default function Terms() {
+ const [accepted, setAccepted] = useState(false)
+ const [isSubmitting, setIsSubmitting] = useState(false)
+ const [serverError, setServerError] = useState<string | undefined>()
+
+ useEffect(() => { document.title = `${TERMS_HEADING} — Site Name` }, [])
+
+ function handleConfirm() {
+ if (!accepted) return
+ setIsSubmitting(true)
+ setServerError(undefined)
+ acceptTerms('/').catch(err => {
+ setServerError(err instanceof Error ? err.message : 'Failed to accept terms.')
+ setIsSubmitting(false)
+ })
+ }
+
+ return (
+ <section>
+ <h1>{TERMS_HEADING}</h1>
+ {serverError && <div role="alert">{serverError}</div>}
+ <div dangerouslySetInnerHTML={{ __html: TERMS_CONTENT }} />
+ <label>
+ <input type="checkbox" checked={accepted} onChange={e => setAccepted(e.target.checked)} />
+ {TERMS_AGREEMENT_TEXT}
+ </label>
+ <button onClick={handleConfirm} disabled={!accepted || isSubmitting}>
+ {isSubmitting ? 'Confirming...' : TERMS_BUTTON_TEXT}
+ </button>
+ <p><Link to="/login">Back to sign in</Link></p>
+ </section>
+ )
+}
+```
+
+Style the component to match the site's existing auth page design (card layout, CSS variables, etc.).
+
+### Login and Registration: Catching TermsRequiredError
+
+Both pages must catch `TermsRequiredError` in their submit handlers:
+
+```typescript
+// In Login.tsx
+loginLocal(email, password, false, '/').catch(err => {
+ if (err instanceof TermsRequiredError) {
+ navigate('/terms')
+ return
+ }
+ // ... existing error handling
+})
+
+// In Registration.tsx
+register({ email, password, confirmPassword }, '/', invitationCode).catch(err => {
+ if (err instanceof TermsRequiredError) {
+ navigate('/terms')
+ return
+ }
+ // ... existing error handling
+})
+```
+
+### Content Snippets Used by the Server
+
+The server-rendered terms page uses these snippets. Create the required one and optionally the others:
+
+| Snippet | Required | Default |
+|---------|----------|---------|
+| `Account/Signin/TermsAndConditionsCopy` | **Yes** (feature disabled without it) | The terms HTML content |
+| `Account/Signin/TermsAndConditionsHeading` | No | "Terms and Conditions" |
+| `Account/Signin/TermsAndConditionsAgreementText` | No | "I agree to these terms and conditions." |
+| `Account/Signin/TermsAndConditionsButtonText` | No | "Confirm" |
+
+### Re-consent via TermsPublicationDate
+
+The `TermsPublicationDate` site setting controls re-acceptance:
+- **Not set**: users are prompted every login
+- **Set to a date**: users who accepted after that date are not re-prompted. Bump the date to force everyone to re-accept when terms are updated.
+
+The server stores acceptance on the contact record's `msdyn_portaltermsagreementdate` field.
+
+---
+
+## Reset Password Flow for SPA Sites
+
+### The Problem
+
+The password reset email sends the user to `/Account/Login/ResetPassword?UserId=...&Code=...` — a server-rendered page outside the SPA. The user leaves the SPA experience.
+
+### The Solution: Code-Site-Shell-Header Template
+
+> **Why not use the original Header template?** The `pac pages upload-code-site` command intentionally replaces the "Header" and "Footer" web template content with `<div/>` on every upload. Any redirect script added to the Header template gets wiped. The solution is to create a separate web template and point the website record to it.
+
+Create a new web template `Code-Site-Shell-Header` in `.powerpages-site/web-templates/code-site-shell-header/`:
+
+**`Code-Site-Shell-Header.webtemplate.yml`:**
+```yaml
+id: <generate-a-new-uuid>
+name: Code-Site-Shell-Header
+```
+
+**`Code-Site-Shell-Header.webtemplate.source.html`:**
+```html
+<div/>
+<script>
+ // Code Site Shell Header — Server-to-SPA redirect for auth pages.
+ // Uses a separate template because pac pages upload-code-site wipes the original Header.
+ (function () {
+ var path = window.location.pathname.toLowerCase();
+ var search = window.location.search;
+ var spaBase = window.location.origin;
+ var redirects = {
+ '/account/login/resetpassword': '/reset-password'
+ };
+ for (var serverPath in redirects) {
+ if (path === serverPath) {
+ window.location.replace(spaBase + redirects[serverPath] + search);
+ return;
+ }
+ }
+ })();
+</script>
+```
+
+Then update **`website.yml`** to point `headerwebtemplateid` to the new template's UUID:
+
+```yaml
+headerwebtemplateid: <new-template-uuid-from-yml>
+```
+
+The original "Header" template stays as `<div/>` — the upload command keeps wiping it, which is fine. The `Code-Site-Shell-Header` survives uploads because the command only targets templates named "Header" and "Footer".
+
+The `redirects` object is extensible — add more server-to-SPA mappings as needed (e.g., email confirmation pages).
+
+### React: ResetPassword Page Component
+
+Create `src/pages/ResetPassword.tsx`:
+
+- Read `UserId` and `Code` from URL query params
+- If either is missing, show "Invalid Reset Link" with a link to `/forgot-password`
+- Show new password + confirm password with validate-on-blur (same password strength rules as registration)
+- Call `resetPassword(userId, code, password, confirmPassword)` on submit
+- On success → redirect to `/login?message=password_reset_success`
+
+### Login Page: Password Reset Success Message
+
+The Login page must check for `?message=password_reset_success` on mount:
+
+```typescript
+const params = new URLSearchParams(window.location.search)
+if (params.get('message') === 'password_reset_success') {
+ setSuccessMessage('Your password has been reset. Please sign in with your new password.')
+}
+```
+
+Display it as a green success banner above the form (distinct from the red error banner).
+
+### Forgot Password Page: Success State
+
+The ForgotPassword page must handle both `.then()` and `.catch()` from `forgotPassword()`:
+
+```typescript
+forgotPassword(email).then(() => {
+ setIsSubmitting(false)
+ setEmailSent(true) // triggers success UI
+}).catch(err => {
+ setServerError(err.message)
+ setIsSubmitting(false)
+})
+```
+
+When `emailSent` is true, replace the form with a success confirmation: green checkmark icon, "Check your email" heading, and a "Back to sign in" link. Do NOT only handle `.catch()` — the button gets stuck in "Sending..." if `.then()` is not handled.
+
+### Complete Password Reset Flow
+
+1. User clicks "Forgot password?" on login → SPA `/forgot-password`
+2. Enters email → `forgotPassword()` POSTs to server → success message "Check your email"
+3. User opens email → clicks reset link → browser goes to `/Account/Login/ResetPassword?UserId=...&Code=...`
+4. **Header template script fires** → `window.location.replace` to `/reset-password?UserId=...&Code=...`
+5. SPA loads → ResetPassword page reads params → shows new password form
+6. User submits → `resetPassword()` POSTs to server → redirect to `/login?message=password_reset_success`
+7. Login page shows green "Password has been reset" banner
+
+---
+
+## Redeem Invitation Flow for SPA Sites
+
+When `Authentication/Registration/InvitationEnabled = true`, invitation emails contain a link to `{site-url}/Account/Login/RedeemInvitation?invitation={code}`. To keep users in the SPA, we follow the same pattern as Reset Password: a header-template redirect + a dedicated SPA page + a service function that intercepts the server's 302 redirect.
+
+### The redirect chain
+
+```
+Email link → /Account/Login/RedeemInvitation?invitation=ABC
+ ↓ (Code-Site-Shell-Header script catches this URL)
+/redeem-invitation?invitation=ABC ← SPA page mounts
+ ↓ (User clicks Continue)
+POST /Account/Login/RedeemInvitation ← fetch with redirect:'manual'
+ ↓ (server validates, returns 302 OR 200)
+ ├── 302 Location:/Account/Login/Register → response.type === 'opaqueredirect'
+ │ ↓ (SPA detects redirect, navigates)
+ │ /registration?invitationCode=ABC ← existing page (Phase 5.1.2)
+ │
+ ├── 200 OK with Login view markers → server expects sign-in
+ │ ↓ (SPA detects login HTML, navigates)
+ │ /login?invitationCode=ABC ← existing page (Phase 5.1.1)
+ │
+ └── 200 OK with validation-summary errors → throw parsed error
+ (invalid / expired / already-redeemed code)
+```
+
+### Header template entry
+
+Extend the existing `Code-Site-Shell-Header` template's redirect map:
+
+```js
+var redirects = {
+ '/account/login/resetpassword': '/reset-password',
+ '/account/login/redeeminvitation': '/redeem-invitation' // ← add this
+};
+```
+
+Only include the redeeminvitation entry when `REGISTRATION_MODE` is `Invitation-only` or `Both`. The path comparison is lowercased, so the script catches both `/Account/Login/RedeemInvitation` (server URL casing) and `/account/login/redeeminvitation`.
+
+### Auth service additions
+
+#### `redeemInvitation()` — the core function
+
+Add to `src/services/authService.ts`:
+
+```typescript
+export interface RedeemInvitationResult {
+ nextStep: 'register' | 'login';
+}
+
+export async function redeemInvitation(
+ invitationCode: string,
+ redeemByLogin: boolean,
+ returnUrl: string = '/'
+): Promise<RedeemInvitationResult> {
+ if (!invitationCode) {
+ throw new Error('Invitation code is required.');
+ }
+
+ if (isDevelopment) {
+ return { nextStep: redeemByLogin ? 'login' : 'register' };
+ }
+
+ const token = await fetchAntiForgeryToken();
+
+ const body = new URLSearchParams();
+ body.set('__RequestVerificationToken', token);
+ body.set('InvitationCode', invitationCode);
+ body.set('RedeemByLogin', redeemByLogin ? 'true' : 'false');
+ body.set('returnUrl', returnUrl);
+
+ const response = await fetch('/Account/Login/RedeemInvitation', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: body.toString(),
+ credentials: 'same-origin',
+ redirect: 'manual',
+ });
+
+ // Branch 1: server returned a 302 redirect (caught by redirect:'manual').
+ // Code is valid AND RedeemByLogin was false → server would have sent us to
+ // /Account/Login/Register. We don't follow it — we navigate to our SPA /registration.
+ if (response.type === 'opaqueredirect') {
+ return { nextStep: 'register' };
+ }
+
+ // Branch 2: 200 OK — could be Login view (RedeemByLogin=true) or validation error.
+ if (response.ok) {
+ const html = await response.text();
+
+ // 2a: Validation error (invalid/expired/already-redeemed code)
+ const errors = parseServerErrors(html);
+ if (errors.length > 0) {
+ throw new Error(errors.join(' '));
+ }
+
+ // 2b: Login view returned — server expects user to sign in with existing account
+ if (html.includes('name="PasswordValue"') || html.includes('LoginLocal')) {
+ return { nextStep: 'login' };
+ }
+
+ throw new Error('Unable to process invitation. Please try again.');
+ }
+
+ throw new Error(`Failed to redeem invitation (status ${response.status}).`);
+}
+```
+
+> **DevTools note**: After the POST resolves with `opaqueredirect`, Chrome's network panel will show the 302 Location target (e.g., `/Account/Login/Register`) as an aborted request with `net::ERR_ABORTED`. This is **expected** and not an actual error — it's the redirect we intentionally chose not to follow. The fast (~0.3ms) timing and the matching URL confirm it's the redirect target, not a network failure.
+
+#### `fetchInvitationDetails()` — for email pre-fill on Registration page
+
+Add to `src/services/authService.ts`:
+
+```typescript
+export interface InvitationDetails {
+ email: string;
+}
+
+export async function fetchInvitationDetails(invitationCode: string): Promise<InvitationDetails> {
+ if (!invitationCode) return { email: '' };
+
+ if (isDevelopment) {
+ return { email: '[email protected]' };
+ }
+
+ const regUrl = `/Account/Login/Register?invitationCode=${encodeURIComponent(invitationCode)}`;
+ const response = await fetch(regUrl, { credentials: 'same-origin' });
+ if (!response.ok) return { email: '' };
+
+ const html = await response.text();
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+
+ const emailInput = doc.getElementById('EmailTextBox') as HTMLInputElement | null;
+ const email = emailInput?.getAttribute('value') || '';
+
+ return { email };
+}
+```
+
+#### `loginLocal()` update — accept invitationCode
+
+Update the existing `loginLocal()` signature to accept an optional invitation code as the 5th parameter. Append it as `?InvitationCode={code}` on the `/SignIn` POST URL — the server's `Login(model, returnUrl, invitationCode)` reads it from the URL, not the body.
+
+```typescript
+export async function loginLocal(
+ credential: string,
+ password: string,
+ rememberMe = false,
+ returnUrl?: string,
+ invitationCode?: string // ← new
+): Promise<void> {
+ // ... existing dev/token setup ...
+
+ const signInUrl = invitationCode
+ ? `/SignIn?InvitationCode=${encodeURIComponent(invitationCode)}`
+ : '/SignIn';
+
+ const response = await fetch(signInUrl, {
+ method: 'POST',
+ // ... rest unchanged ...
+ });
+ // ... rest unchanged ...
+}
+```
+
+After successful authentication, the server's `RedirectOnPostAuthenticate` (LoginController.cs line 3665) calls `InvitationManager.RedeemAsync(invitation, user, ...)` to link the invitation to the now-signed-in user's contact.
+
+### React: RedeemInvitation page
+
+Create `src/pages/RedeemInvitation.tsx`:
+
+```typescript
+import { useEffect, useState, type FormEvent } from 'react'
+import { Link, useNavigate } from 'react-router-dom'
+import { redeemInvitation } from '../services/authService'
+
+const validateCode = (v: string) => {
+ if (!v || !v.trim()) return 'Invitation code is required'
+ return ''
+}
+
+export default function RedeemInvitation() {
+ const navigate = useNavigate()
+
+ const initialCode = (() => {
+ const params = new URLSearchParams(window.location.search)
+ return params.get('invitation') || params.get('InvitationCode') || params.get('code') || ''
+ })()
+
+ const [code, setCode] = useState(initialCode)
+ const [redeemByLogin, setRedeemByLogin] = useState(false)
+ const [errors, setErrors] = useState<Record<string, string>>({})
+ const [touched, setTouched] = useState<Record<string, boolean>>({})
+ const [serverError, setServerError] = useState<string | undefined>()
+ const [isSubmitting, setIsSubmitting] = useState(false)
+
+ useEffect(() => { document.title = 'Redeem Invitation' }, [])
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ setTouched({ code: true })
+ const error = validateCode(code)
+ setErrors(error ? { code: error } : {})
+ if (error) return
+
+ setIsSubmitting(true)
+ setServerError(undefined)
+
+ redeemInvitation(code.trim(), redeemByLogin).then(result => {
+ const target = result.nextStep === 'register' ? '/registration' : '/login'
+ navigate(`${target}?invitationCode=${encodeURIComponent(code.trim())}`)
+ }).catch(err => {
+ setServerError(err instanceof Error ? err.message : 'Unable to verify invitation.')
+ setIsSubmitting(false)
+ })
+ }
+
+ // ... render form with invitation code input + "Sign in with an existing account
+ // instead of registering" checkbox + Continue button (see contoso-portal site for
+ // a complete styled example) ...
+}
+```
+
+### Login page update
+
+When `REGISTRATION_MODE` is `Invitation-only` or `Both`, update Login.tsx to:
+
+1. Read `invitationCode` from URL on mount:
+ ```typescript
+ const invitationCode = new URLSearchParams(window.location.search)
+ .get('invitationCode') || undefined
+ ```
+2. Show an info banner when present: `"Sign in to redeem invitation {code}. The invitation will be linked to your account after you sign in."`
+3. Pass `invitationCode` to `loginLocal(email, password, rememberMe, '/', invitationCode)` on submit.
+
+### Registration page update — email pre-fill + external provider buttons
+
+When `REGISTRATION_MODE` is `Invitation-only` or `Both`, update Registration.tsx to call `fetchInvitationDetails(invitationCode)` on mount and pre-fill the email input. The input must be controlled (`value={email}`) and editable.
+
+```typescript
+useEffect(() => {
+ if (!invitationCode) return
+ fetchInvitationDetails(invitationCode).then(details => {
+ if (details.email) setEmail(details.email)
+ }).catch(() => { /* silent — user can enter email manually */ })
+}, [invitationCode])
+```
+
+**Also when `EXTERNAL_PROVIDERS.length > 0`**, render external provider buttons above the local form (same layout as Login page). Each button calls `loginExternal(providerIdentifier, '/', invitationCode)` — the invitation code threads through to the IdP round-trip via `/Account/Login/ExternalLogin?InvitationCode={code}`, and the server's `ExternalLoginCallback` redeems the invitation as part of contact creation.
+
+```tsx
+{EXTERNAL_PROVIDERS.length > 0 && (
+ <div style={styles.externalRow}>
+ {EXTERNAL_PROVIDERS.map(provider => (
+ <button key={provider.id} type="button"
+ onClick={() => loginExternal(provider.providerIdentifier!, '/', invitationCode)}>
+ {`Sign up with ${provider.displayName.replace(/^Sign in with /, '')}`}
+ </button>
+ ))}
+ </div>
+)}
+{EXTERNAL_PROVIDERS.length > 0 && LOCAL_PROVIDER && <Divider label="OR SIGN UP WITH EMAIL" />}
+{LOCAL_PROVIDER && <LocalRegistrationForm ... />}
+```
+
+### End-to-end flow summary
+
+**Path A — User clicks invitation email link first (clean SPA entry):**
+1. Admin creates an Invitation record in Dataverse (`adx_invitation` table) for an invited contact → captures `adx_invitationcode`
+2. Admin sends user a link: `{site-url}/Account/Login/RedeemInvitation?invitation={code}`
+3. User clicks → browser loads server page → header template script redirects to SPA `/redeem-invitation?invitation={code}`
+4. SPA RedeemInvitation page mounts → code pre-filled → user picks register vs. login → submits
+5. `redeemInvitation()` POSTs → server validates code → returns 302 (register) or 200 (login)
+6. SPA detects branch and navigates to `/registration?invitationCode={code}` or `/login?invitationCode={code}`
+7. **Register path with local auth**: Registration page pre-fills email via `fetchInvitationDetails()` → user completes form → POST creates account AND redeems invitation in one server call
+8. **Register path with external auth**: User clicks external provider button on `/registration` → `loginExternal()` POSTs to `/Account/Login/ExternalLogin?InvitationCode={code}` → IdP → ExternalLoginCallback creates contact + redeems invitation
+9. **Login path**: Login page shows info banner → user signs in (local or external — both thread `invitationCode` through) → server redeems invitation in `RedirectOnPostAuthenticate` after auth
+
+**Path B — User clicks "Sign in with external provider" without invitation context (server-bounce path):**
+1. User clicks external provider button on `/login` (or directly via `loginExternal()` from the Nav) — **no invitation code in URL**
+2. `POST /Account/Login/ExternalLogin?Provider=...` → IdP → `/signin-{providername}` → 302 → `/Account/Login/ExternalLoginCallback?ReturnUrl=/`
+3. **`GET /Account/Login/ExternalLoginCallback`**: server detects no contact + no invitation → 302 → `/Register?ReturnUrl=/` (the alias route for `LoginController.RedeemInvitation`, NOT the local Register page)
+4. Code-Site-Shell-Header script catches `/register` → redirects to SPA `/redeem-invitation`
+5. User enters invitation code → SPA `redeemInvitation()` → server returns 302 → `/Account/Login/Register?returnUrl=/&invitationCode={code}` (the local Register Web Forms page)
+6. Header script catches `/account/login/register` → redirects to SPA `/registration?invitationCode={code}`
+7. SPA Registration page mounts. External provider buttons visible at top. User clicks "Sign up with [external provider]" → `loginExternal(providerIdentifier, '/', invitationCode)`
+8. `POST /Account/Login/ExternalLogin?InvitationCode={code}&Provider=...` → IdP (silent — cookies still valid from step 2) → `/signin-{providername}` → `/Account/Login/ExternalLoginCallback?InvitationCode={code}`
+9. ExternalLoginCallback now has BOTH external auth + invitation → creates contact + redeems → 302 to ReturnUrl (or Terms if enabled)
+
+> **Why the bounce?** The server's `RegistrationManager` enforces that external-authenticated users without a contact MUST either (a) have an invitation, or (b) be in a configuration where `OpenRegistrationEnabled = true` AND `AllowContactMappingWithEmail = true`. Without those, the server forces the invitation flow via the alias `/Register` route. The header redirect catches the bounce and keeps the user in the SPA throughout.
+
+> **Verified via HAR analysis** on a live Power Pages site (smoking-burgers-inc) with Entra External ID + Terms enabled. The two new redirects (`/register` and `/account/login/register`) are critical for any site with external providers AND invitations enabled — without them, users see two server-rendered pages (RedeemInvitation form + local Register Web Forms page) in the middle of the flow.
+
+---
+
+## Entra External ID — Tenant and App Registration Prerequisites
+
+Entra External ID requires three things to be set up in the Microsoft Entra admin center before Power Pages can use it: a tenant, an app registration, and a user flow. The setup-auth skill walks users through these in Phase 2.1, but here's the complete reference for the four-step process.
+
+> Microsoft Learn: https://learn.microsoft.com/en-us/power-pages/security/authentication/entra-external-id
+
+### Step 1 — Tenant
+
+Entra External ID tenants are a distinct tenant type from regular workforce Entra ID tenants. **A workforce tenant cannot be used in place of an External ID tenant** — they're different products that share underlying technology.
+
+To create an External ID tenant:
+
+1. Open https://entra.microsoft.com/
+2. Top of left navigation → **Manage tenants** → **Create**
+3. Choose **External (for customers)** — not Workforce
+4. Pick a domain prefix (the "tenant subdomain") — e.g., `contoso` becomes `contoso.ciamlogin.com`
+5. The tenant has a 30-day free trial; attach an Azure subscription later
+
+To verify whether an existing tenant is External or Workforce: tenant picker (top-right of entra.microsoft.com) shows an **External** badge next to External ID tenants.
+
+**Values to capture for the skill:**
+- **Tenant subdomain** — the part before `.ciamlogin.com` (e.g., `contoso`). Validate `^[a-z0-9-]+$`.
+- **Tenant ID** (GUID) — from the tenant's Overview page. Validate UUID v4 regex.
+
+### Step 2 — App registration
+
+Register an app inside the External ID tenant:
+
+1. **Applications → App registrations → New registration**
+2. **Name** — typically `power-pages-{sitename}`
+3. **Supported account types** — **single-tenant** is the recommended default. Multi-tenant configurations cause the Power Pages server to forcibly disable `AllowContactMappingWithEmail` (`BlockContactMappingSettingForMultitenantApp` feature flag in `LoginController.cs:2578-2587`).
+4. **Redirect URI**:
+ - Platform: **Web**
+ - URI: `{SITE_URL}/signin-{ProviderName-lowercased}` — exact string matters, including the `signin-` prefix and the lowercased provider name suffix
+5. **Register**
+6. **Authentication** tab → check **Access tokens** + **ID tokens** under "Implicit grant and hybrid flows" → **Save**
+7. **API permissions** tab → **Grant admin consent for {tenant}**
+
+**Value to capture for the skill:**
+- **Application (client) ID** — from the Overview tab. Validate UUID v4 regex.
+
+**Do NOT create a client secret.** Entra External ID app registrations are public clients using PKCE — the OWIN OpenID Connect middleware in Power Pages performs the auth code exchange with PKCE, no secret needed. Adding one creates a confidential-client scenario that requires Azure Key Vault storage (advanced override; document but don't auto-configure).
+
+### Step 3 — User flow
+
+Without a user flow, sign-in fails after the IdP redirect.
+
+1. **External Identities → User flows → New user flow**
+2. **Name** — typically `{sitename}-signupsignin`. Validate `^[a-zA-Z0-9_-]+$`.
+3. **Identity providers** for sign-in — **Email with password** (most common) or **Email one-time passcode** (passwordless)
+4. **User attributes to collect** — these become the sign-up form fields. The skill should align this with the user's profile mapping choice from Track B:
+ - "Standard" mapping → ☑ Email Address, ☑ Given Name, ☑ Surname
+ - "Standard + phone" → also ☑ Phone Number
+ - "Email only" → just ☑ Email Address
+5. **User attributes to return as claims** — these are the values in the ID token. **Select the same attributes as in step 4** — these power the `RegistrationClaimsMapping` → Dataverse contact field flow. If a user selects an attribute to collect but NOT to return as a claim, the contact field stays empty even though the user provided the value.
+6. **Create**
+7. Open the user flow → **Applications** tab → **Add application** → select the app registered in Step 2
+
+**Value to capture for the skill:**
+- **User flow name** — used to confirm the user has one. Not written to a Power Pages site setting (the user flow is attached to the app, not referenced by name from Power Pages).
+
+### Step 4 — Derived configuration
+
+After collecting tenant subdomain, tenant ID, client ID, and user flow name, derive:
+
+| Field | Value |
+|---|---|
+| Authority | `https://{subdomain}.ciamlogin.com/{tenantId}` — **no trailing `/v2.0/`** |
+| MetadataAddress | `https://{subdomain}.ciamlogin.com/{tenantId}/v2.0/.well-known/openid-configuration` |
+| AuthenticationType | Same as Authority (provider identifier for ExternalLogin POST must match) |
+| RedirectUri | `{SITE_URL}/signin-{ProviderName-lowercased}` (same as Step 2) |
+
+**Authority URL format quirk** — Entra External ID's Authority is the bare tenant path `https://{subdomain}.ciamlogin.com/{tenantId}`, NOT the `/v2.0/` variant. This differs from:
+- **Classic Azure AD B2C** (`https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/v2.0/{policy}` with policy in the path)
+- **Generic OIDC** (often `{authority}/v2.0` or `{authority}/oauth2/default`)
+- **Workforce Entra ID** (`https://login.microsoftonline.com/{tenantId}/v2.0/`)
+
+The MetadataAddress, however, DOES include `/v2.0/` before `.well-known/openid-configuration`.
+
+### Common pitfalls
+
+| Pitfall | Symptom | Fix |
+|---|---|---|
+| Wrong tenant type (workforce instead of External ID) | Sign-in works but no External ID-specific features (sign-up, user flows) | Create a separate External ID tenant |
+| Multi-tenant app registration | Contact mapping silently disabled on server | Use single-tenant; or accept new contacts always (the safer default) |
+| Redirect URI mismatch (casing, suffix typo) | "AADSTS50011: The reply URL specified in the request does not match" | Copy the Redirect URI from the skill output verbatim, including lowercase |
+| Missing user flow / not attached to app | After IdP redirect, user sees error or nothing happens | Create user flow + add app to it |
+| Selected attribute to collect but not to return as claim | Contact created with empty `firstname`/`lastname` | Re-edit user flow → check claim boxes for same attributes |
+| Authority URL includes `/v2.0/` for External ID | Sign-in returns "AADSTS900144: The request body must contain..." or metadata loading fails | Remove `/v2.0/` from Authority (keep it in MetadataAddress) |
+
+### Custom domains
+
+External ID supports custom domains (e.g., `login.contoso.com` instead of `contoso.ciamlogin.com`). To use one:
+
+1. Configure the custom domain in the External ID tenant (see Microsoft Learn)
+2. The Authority becomes `https://{custom-domain}/{tenantId}` (same structure, custom hostname)
+3. MetadataAddress becomes `https://{custom-domain}/{tenantId}/v2.0/.well-known/openid-configuration`
+4. The Redirect URI in the app registration must also use the site's custom domain
+
+The setup-auth skill walkthrough doesn't ask about custom domains in the initial flow — those configurations should be edited manually post-setup, or imported via Phase 1.5 discovery if pre-existing.
+
+---
+
+## External Login Confirmation Flow for SPA Sites
+
+When a user signs in with an external provider (Entra External ID, OIDC, SAML2, etc.) for the first time and no Dataverse contact exists, the server renders `ExternalLoginConfirmation.aspx` at the OIDC callback URL (`/Account/Login/ExternalLoginCallback`). The user confirms/edits their email and the server creates the contact + signs them in. We SPA-ify this with the same pattern as Reset Password and Redeem Invitation.
+
+### State storage that makes this work
+
+The IdP's claims are stored in the `__External` cookie set by the OIDC middleware (see `Samples/MasterPortal/App_Start/Startup.Auth.cs:50-59`):
+
+- `AuthenticationType = DefaultAuthenticationTypes.ExternalCookie` (`__External`)
+- `ExpireTimeSpan = TimeSpan.FromMinutes(5)`
+- `CookieSecure = CookieSecureOption.Always`
+- `AuthenticationMode = AuthenticationMode.Passive` — auto-sent on same-origin requests
+- `CookieSameSite` derived from site settings (typically `Lax`)
+
+The SPA's fetch with `credentials: 'same-origin'` includes this cookie automatically, so the server returns the claim-populated form.
+
+### Header template entry
+
+Extend the `Code-Site-Shell-Header` redirect map:
+
+```js
+var redirects = {
+ '/account/login/resetpassword': '/reset-password',
+ '/account/login/redeeminvitation': '/redeem-invitation',
+ '/account/login/externallogincallback': '/external-login-confirmation' // ← add this
+};
+```
+
+### Auth service additions
+
+#### Types and error class
+
+```typescript
+export interface ExternalLoginDetails {
+ email: string;
+ firstName: string;
+ lastName: string;
+ username: string;
+ invitationCode: string;
+ returnUrl: string;
+ antiForgeryToken: string;
+}
+
+export class ExternalLoginCookieExpiredError extends Error {
+ constructor() {
+ super('External login session expired. Please sign in again.');
+ this.name = 'ExternalLoginCookieExpiredError';
+ }
+}
+```
+
+#### `fetchExternalLoginDetails()` — pre-fetch claim-populated form
+
+```typescript
+export async function fetchExternalLoginDetails(): Promise<ExternalLoginDetails> {
+ if (isDevelopment) {
+ return {
+ email: '[email protected]',
+ firstName: 'Invited',
+ lastName: 'User',
+ username: 'invited.user',
+ invitationCode: '',
+ returnUrl: '/',
+ antiForgeryToken: 'dev-token',
+ };
+ }
+
+ const response = await fetch('/Account/Login/ExternalLoginCallback', {
+ credentials: 'same-origin',
+ });
+
+ if (!response.ok) {
+ throw new Error(`Failed to fetch external login details (status ${response.status}).`);
+ }
+
+ const html = await response.text();
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, 'text/html');
+
+ // ExternalLoginFailure.aspx is returned when the __External cookie has expired.
+ // Detect by the absence of the confirmation form.
+ if (!doc.querySelector('input[name="Email"]')) {
+ throw new ExternalLoginCookieExpiredError();
+ }
+
+ const getValue = (selector: string): string =>
+ (doc.querySelector(selector) as HTMLInputElement | null)?.value || '';
+
+ const formAction = doc.querySelector('form')?.getAttribute('action') || '';
+ const actionParams = new URLSearchParams(formAction.split('?')[1] || '');
+
+ return {
+ email: getValue('input[name="Email"]'),
+ firstName: getValue('input[name="FirstName"]'),
+ lastName: getValue('input[name="LastName"]'),
+ username: getValue('input[name="Username"]'),
+ invitationCode: getValue('input[name="InvitationCode"]') || actionParams.get('InvitationCode') || '',
+ returnUrl: actionParams.get('ReturnUrl') || '/',
+ antiForgeryToken: getValue('input[name="__RequestVerificationToken"]'),
+ };
+}
+```
+
+#### `confirmExternalLogin()` — POST with redirect detection
+
+```typescript
+export async function confirmExternalLogin(details: ExternalLoginDetails): Promise<void> {
+ if (isDevelopment) {
+ window.location.href = details.returnUrl || '/';
+ return;
+ }
+
+ const body = new URLSearchParams();
+ body.set('__RequestVerificationToken', details.antiForgeryToken);
+ body.set('Email', details.email);
+ body.set('FirstName', details.firstName);
+ body.set('LastName', details.lastName);
+ body.set('Username', details.username);
+
+ // Server reads ReturnUrl and InvitationCode from the form action URL query string.
+ const params = new URLSearchParams();
+ if (details.returnUrl) params.set('ReturnUrl', details.returnUrl);
+ if (details.invitationCode) params.set('InvitationCode', details.invitationCode);
+ const qs = params.toString();
+ const postUrl = `/Account/Login/ExternalLoginConfirmation${qs ? `?${qs}` : ''}`;
+
+ const response = await fetch(postUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+ body: body.toString(),
+ credentials: 'same-origin',
+ redirect: 'manual',
+ });
+
+ // Server sets ApplicationCookie BEFORE returning the 302 — user is signed in.
+ if (response.type === 'opaqueredirect') {
+ window.location.href = details.returnUrl || '/';
+ return;
+ }
+
+ if (response.ok) {
+ const html = await response.text();
+ const errors = parseServerErrors(html);
+ if (errors.length > 0) throw new Error(errors.join(' '));
+
+ // Server may render TermsAndConditions instead of redirecting to it.
+ if (html.includes('TermsAndConditions') || html.includes('IsTermsAndConditionsAccepted')) {
+ throw new TermsRequiredError();
+ }
+
+ throw new Error('Unable to complete external login. Please try again.');
+ }
+
+ throw new Error(`Failed to confirm external login (status ${response.status}).`);
+}
+```
+
+### Page component (React)
+
+```tsx
+import { useEffect, useState, type FormEvent } from 'react'
+import { useNavigate, Link } from 'react-router-dom'
+import {
+ fetchExternalLoginDetails,
+ confirmExternalLogin,
+ ExternalLoginCookieExpiredError,
+ TermsRequiredError,
+ type ExternalLoginDetails,
+} from '../services/authService'
+
+export default function ExternalLoginConfirmation() {
+ const navigate = useNavigate()
+ const [details, setDetails] = useState<ExternalLoginDetails | null>(null)
+ const [email, setEmail] = useState('')
+ const [cookieExpired, setCookieExpired] = useState(false)
+ // ... isLoading, isSubmitting, serverError state, validation, etc.
+
+ useEffect(() => {
+ fetchExternalLoginDetails()
+ .then(d => { setDetails(d); setEmail(d.email) })
+ .catch(err => {
+ if (err instanceof ExternalLoginCookieExpiredError) setCookieExpired(true)
+ // else show serverError
+ })
+ }, [])
+
+ function handleSubmit(e: FormEvent) {
+ e.preventDefault()
+ if (!details) return
+ confirmExternalLogin({ ...details, email }).catch(err => {
+ if (err instanceof TermsRequiredError) return navigate('/terms')
+ if (err instanceof ExternalLoginCookieExpiredError) return setCookieExpired(true)
+ // else show serverError
+ })
+ }
+
+ if (cookieExpired) return <ExpiredCard />
+ if (!details) return <LoadingCard />
+
+ return (
+ <form onSubmit={handleSubmit}>
+ <h1>Almost done!</h1>
+ {details.invitationCode && <Banner>Redeeming invitation {details.invitationCode}</Banner>}
+ <ReadOnlyRow label="Name" value={`${details.firstName} ${details.lastName}`} />
+ <input type="email" value={email} onChange={e => setEmail(e.target.value)} />
+ <button type="submit">Create my account</button>
+ </form>
+ )
+}
+```
+
+### Routing
+
+Add `<Route path="/external-login-confirmation" element={<ExternalLoginConfirmation />} />` to the React Router config.
+
+### Cookie expiry handling
+
+The `__External` cookie has a **5-minute TTL**. If the user lingers between IdP callback and form submission, the cookie expires and the server returns `ExternalLoginFailure.aspx` instead of the confirmation form. The SPA detects this (no `input[name="Email"]` in the HTML) and shows an "expired" state with a link back to `/login`.
+
+### Edge cases summary
+
+| Case | Behavior |
+|---|---|
+| User has 2FA enabled | 2FA challenge happens AFTER `SignInAsync` completes (during the 302 navigation). SPA-ified confirmation doesn't interfere — 2FA challenge pages are server-rendered, separate flow. |
+| `SameSite=Strict` cookie config | Fetch won't send `__External` cookie → `fetchExternalLoginDetails` throws `ExternalLoginCookieExpiredError` immediately. Default is `Lax` — works. |
+| Invited user via external login | Invitation code captured from form action URL → preserved through POST → server redeems as part of contact creation. |
+| Email mismatch with existing contact + `RequireUniqueEmail=true` | Server returns 200 with validation summary; SPA shows error inline. User can edit email and retry. |
+| `AllowContactMappingWithEmail=true` and email matches existing contact | Server SKIPS the ExternalLoginConfirmation page entirely — user is signed in via the existing contact and lands at the return URL. The SPA page never mounts. |
+
+---
+
+## Session KeepAlive for SPA Sites
+
+In SPAs, page navigation is client-side — no server requests are made. The session cookie's `SlidingExpiration` only renews when the browser sends a request to the server. Without a keepalive, the session silently expires even while the user is actively using the SPA.
+
+### Provider-agnostic by design
+
+The keepalive operates on the **Power Pages `ApplicationCookie`** — the same session cookie that's issued for every authenticated user regardless of provider (local password, Entra External ID, generic OIDC, SAML2, social). The hook calls `isAuthenticated()` which reads from `window.Microsoft.Dynamic365.Portal.User`, populated for any signed-in user. No provider-specific branches are needed.
+
+| Layer | Local auth | External auth (Entra External ID, OIDC, SAML2, social) |
+|---|---|---|
+| Session cookie | `ApplicationCookie` set by server on `/SignIn` POST | `ApplicationCookie` set by server on `/Account/Login/ExternalLoginCallback` |
+| Ping endpoint | `/_layout/tokenhtml` (refreshes the cookie via OWIN middleware) | Same |
+| Activity tracking | Mouse / keyboard / touch / scroll | Same |
+| On expiry | Redirect to `/login?sessionExpired=true` → user re-enters email/password | Redirect to `/login?sessionExpired=true` → user clicks external provider button → IdP round-trip (silent if IdP SSO is still valid) → back in |
+
+### Two independent clocks for external providers
+
+External providers add a second token lifetime to be aware of:
+
+1. **Power Pages `ApplicationCookie`** — what this keepalive touches. Controlled by `Authentication/ApplicationCookie/ExpireTimeSpan` site setting.
+2. **IdP token** (Entra External ID ID token / refresh token, etc.) — controlled entirely by the IdP. Power Pages does NOT re-verify with the IdP on every request; once the session cookie is issued post-callback, it's independent of the IdP token.
+
+What this means in practice:
+- **Power Pages session expires, IdP token still valid** (common): user redirected to `/login?sessionExpired=true` → clicks external provider button → IdP responds silently (SSO cookie still valid in browser) → new Power Pages session issued. No credential re-entry. Smooth UX.
+- **IdP token expires, Power Pages session still valid**: user keeps using the site fine — Power Pages doesn't care about the IdP token after the initial sign-in.
+
+The keepalive is responsible for the first clock only. The IdP's own session management handles the second.
+
+### Detection limitation
+
+`/_layout/tokenhtml` is **anonymous-accessible** by design — it's the endpoint the unauthenticated login form uses to fetch an anti-forgery token. When the Power Pages session expires server-side, the next `fetchAntiForgeryToken()` call **may still succeed** (returns an anonymous-context token), and the hook's catch block won't fire. `onSessionExpired` won't run.
+
+In practice, this means the keepalive is **highly effective at PREVENTING expiry** (by touching the cookie before it expires) but **less reliable at DETECTING expiry** once it has happened.
+
+Robust expiry detection in the field typically happens when:
+- The user attempts a protected action (e.g., data fetch via the WebAPI client from `/integrate-webapi`) → server returns 401 → SPA catches and redirects to `/login?sessionExpired=true`
+- The user reloads the page → SPA reads `window.Microsoft.Dynamic365.Portal.User` → empty → effectively logged out
+
+If your site uses the WebAPI client from the `/integrate-webapi` skill, that client treats 401 as a session-expired signal and triggers the same redirect. The two mechanisms together (keepalive prevention + WebAPI 401 detection) give the best practical coverage.
+
+This limitation applies equally to local and external auth — it's a property of the cookie-based session model + the choice of `/_layout/tokenhtml` as the ping endpoint, not a provider issue. Switching to an authenticated-only ping endpoint would catch expiry reliably but Power Pages doesn't expose a built-in "is my session valid?" endpoint; building one would require server-side custom code (out of scope for this skill).
+
+### React: useSessionKeepAlive Hook
+
+Create `src/hooks/useSessionKeepAlive.ts`:
+
+```typescript
+import { useEffect, useRef } from 'react';
+import { isAuthenticated, fetchAntiForgeryToken } from '../services/authService';
+
+// Set this to match your Authentication/ApplicationCookie/ExpireTimeSpan site setting.
+// Default Power Pages session is 24 hours. For a 10-minute session, use 10 * 60 * 1000.
+const SESSION_EXPIRE_MS = 24 * 60 * 60 * 1000;
+
+export function useSessionKeepAlive({
+ // Ping at 1/3 of session timeout, capped at 15min.
+ // Must be well before the halfway point where SlidingExpiration renews.
+ intervalMs = Math.min(SESSION_EXPIRE_MS / 3, 15 * 60 * 1000),
+ // Stop pinging after 90% of session timeout idle, capped at 30min.
+ idleTimeoutMs = Math.min(SESSION_EXPIRE_MS * 0.9, 30 * 60 * 1000),
+ onSessionExpired,
+}: {
+ intervalMs?: number;
+ idleTimeoutMs?: number;
+ onSessionExpired?: () => void;
+} = {}) {
+ const lastActivityRef = useRef(Date.now());
+
+ useEffect(() => {
+ const isDev = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
+ if (isDev) return;
+
+ function onActivity() { lastActivityRef.current = Date.now(); }
+
+ window.addEventListener('mousemove', onActivity, { passive: true });
+ window.addEventListener('keydown', onActivity, { passive: true });
+ window.addEventListener('touchstart', onActivity, { passive: true });
+ window.addEventListener('scroll', onActivity, { passive: true });
+
+ const timer = setInterval(async () => {
+ if (!isAuthenticated()) return;
+ if (document.visibilityState === 'hidden') return;
+ if (Date.now() - lastActivityRef.current > idleTimeoutMs) return;
+
+ try {
+ await fetchAntiForgeryToken();
+ } catch {
+ if (onSessionExpired) onSessionExpired();
+ }
+ }, intervalMs);
+
+ return () => {
+ clearInterval(timer);
+ window.removeEventListener('mousemove', onActivity);
+ window.removeEventListener('keydown', onActivity);
+ window.removeEventListener('touchstart', onActivity);
+ window.removeEventListener('scroll', onActivity);
+ };
+ }, [intervalMs, idleTimeoutMs, onSessionExpired]);
+}
+```
+
+### Integration
+
+Add to the Layout component so it runs on every page:
+
+```typescript
+import { useSessionKeepAlive } from '../hooks/useSessionKeepAlive';
+import { useNavigate } from 'react-router-dom';
+import { useCallback } from 'react';
+
+export default function Layout({ children }) {
+ const navigate = useNavigate();
+ const handleSessionExpired = useCallback(() => {
+ navigate('/login?sessionExpired=true');
+ }, [navigate]);
+
+ useSessionKeepAlive({ onSessionExpired: handleSessionExpired });
+
+ return (/* ... */);
+}
+```
+
+The login page already handles `?sessionExpired=true` via `getSessionExpiredMessage()`.
+
+### Why `/_layout/tokenhtml`?
+
+This is the best endpoint for keepalive because:
+- Smallest response (~200-300 bytes — just an anti-forgery token `<input>` tag)
+- Low server cost (no Dataverse queries, no template rendering)
+- Renews the session cookie via OWIN middleware
+- Already used by the auth service for CSRF tokens
+- No dedicated health/ping endpoint exists in Power Pages
+
+---
+
+## Important Notes
+
+- **Auth only works on deployed sites**: The `/_layout/tokenhtml` endpoint and `window.Microsoft.Dynamic365.Portal` object are only available when the site is served from Power Pages, not during local `npm run dev`.
+- **Mock data for development**: The auth service includes a mock user pattern for local development. The mock user has configurable roles so developers can test role-based UI locally.
+- **Security**: Always validate permissions server-side via table permissions. Client-side auth checks are for UX only -- a direct API call bypasses all client-side checks. Never commit secrets (`ClientSecret`, `AppSecret`) to source control -- use the Power Pages admin center for sensitive values.
+- **Provider configuration**: The identity provider must be configured in the Power Pages admin center (for Entra ID) or via site settings (for OIDC, SAML2, WS-Fed, Social, Entra External ID). This skill creates the client-side code and site settings but does not configure the external identity provider itself.
+- **Multiple providers**: Power Pages supports multiple identity providers simultaneously. Users see all configured providers on the login page. To configure multiple providers, create separate site settings for each and update the auth service to support provider selection.
+
+---
+
+## User Profile Page
+
+A `/user-profile` SPA page where signed-in users edit their own contact record via the Power Pages Web API. Created only when the maker opts in via the Phase 2.1 `INCLUDE_PROFILE_PAGE` question. Provider-agnostic — works the same for local + all external providers because it operates on the contact record after sign-in (not on IdP-specific session state).
+
+The page is intentionally **simple by default**:
+- An **Account Details** section at the top shows the user's **full name** (firstname + lastname) and **email** as read-only — sourced from `useAuth()` so no extra Web API roundtrip is needed.
+- An **edit form** below lets the user update only: firstname, lastname, mobile phone, and the five address fields. **Email is not editable** (avoids cross-provider claim-mapping headaches), and **password reset is not exposed here** (it stays under `/forgot-password` for local accounts).
+- Makers can extend the form post-generation if they need additional contact columns; the skill ships with this minimal field set.
+
+### Server-side requirements (set by the skill in Phase 8.1)
+
+- `Webapi/contact/enabled = true`
+- `Webapi/contact/fields = contactid,firstname,lastname,mobilephone,address1_line1,address1_city,address1_stateorprovince,address1_postalcode,address1_country` (9 entries, all lowercase Dataverse LogicalNames; mixed casing causes 403). `emailaddress1` is intentionally omitted because email is read-only in the UI; `middlename` is omitted to keep the form simple.
+- Table permission `My Profile - Edit Own Contact`: `entitylogicalname: contact`, `scope: 756150004` (Self), `read: true`, `write: true`, associated with the Authenticated Users web role
+
+Self scope ensures a user can read and update ONLY their own contact record. Even a crafted `PATCH /_api/contacts({someone-elses-id})` request from DevTools returns 403.
+
+### Auth service additions
+
+Add to `src/services/authService.ts` (reuses the existing `fetchAntiForgeryToken()` helper for the PATCH anti-forgery token — no need for a separate Web API client):
+
+```typescript
+export interface ProfileContact {
+ contactid: string;
+ firstname: string | null;
+ lastname: string | null;
+ mobilephone: string | null;
+ address1_line1: string | null;
+ address1_city: string | null;
+ address1_stateorprovince: string | null;
+ address1_postalcode: string | null;
+ address1_country: string | null;
+}
+
+export type ProfileUpdate = Partial<Omit<ProfileContact, 'contactid'>>;
+
+const PROFILE_FIELDS = [
+ 'contactid', 'firstname', 'lastname',
+ 'mobilephone', 'address1_line1', 'address1_city', 'address1_stateorprovince',
+ 'address1_postalcode', 'address1_country',
+].join(',');
+
+export async function getMyProfile(contactId: string): Promise<ProfileContact> {
+ if (isDevelopment) {
+ return {
+ contactid: contactId,
+ firstname: 'Dev', lastname: 'User',
+ mobilephone: null,
+ address1_line1: null, address1_city: null,
+ address1_stateorprovince: null, address1_postalcode: null, address1_country: null,
+ };
+ }
+
+ const url = `/_api/contacts(${encodeURIComponent(contactId)})?$select=${PROFILE_FIELDS}`;
+ const response = await fetch(url, { credentials: 'same-origin' });
+ if (!response.ok) {
+ throw new Error(`Failed to load profile (status ${response.status}).`);
+ }
+ return response.json();
+}
+
+export async function updateMyProfile(
+ contactId: string,
+ payload: ProfileUpdate
+): Promise<void> {
+ if (isDevelopment) {
+ return;
+ }
+
+ const token = await fetchAntiForgeryToken();
+
+ // Only include defined fields — undefined means "don't touch this column".
+ // Explicit null clears the column.
+ const body: Record<string, string | null> = {};
+ for (const [key, value] of Object.entries(payload)) {
+ if (value !== undefined) body[key] = value;
+ }
+
+ const response = await fetch(`/_api/contacts(${encodeURIComponent(contactId)})`, {
+ method: 'PATCH',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'If-Match': '*',
+ '__RequestVerificationToken': token,
+ },
+ body: JSON.stringify(body),
+ credentials: 'same-origin',
+ });
+
+ if (!response.ok) {
+ // Try to parse OData error envelope
+ try {
+ const errorBody = await response.json();
+ const message = errorBody?.error?.message
+ ?? `Failed to update profile (status ${response.status}).`;
+ throw new Error(message);
+ } catch {
+ throw new Error(`Failed to update profile (status ${response.status}).`);
+ }
+ }
+}
+
+/**
+ * After a successful contact PATCH, mirror the saved name fields into the
+ * in-memory `window.Microsoft.Dynamic365.Portal.User` snapshot so the
+ * header avatar / display name reflect the new values without a full
+ * page reload.
+ *
+ * Why this is needed: `Portal.User` is set ONCE by the server when the
+ * page is rendered. Our Web API PATCH updates Dataverse but does NOT
+ * touch this client-side object. `useAuth()` reads from it via
+ * `getCurrentUser()`, so without this helper the header keeps showing
+ * the pre-save name until the next full page navigation.
+ *
+ * Only the fields the header actually uses are mirrored (firstName,
+ * lastName). Other contact fields stay untouched. Call this AFTER the
+ * PATCH has succeeded, then call `refresh()` from useAuth to trigger a
+ * re-render.
+ */
+export function applyContactUpdateLocally(payload: ProfileUpdate): void {
+ if (typeof window === 'undefined') return;
+ const portalUser = window.Microsoft?.Dynamic365?.Portal?.User;
+ if (!portalUser) return;
+ if (payload.firstname !== undefined) {
+ portalUser.firstName = payload.firstname ?? '';
+ }
+ if (payload.lastname !== undefined) {
+ portalUser.lastName = payload.lastname ?? '';
+ }
+}
+```
+
+### React: UserProfile page
+
+Create `src/pages/UserProfile.tsx`:
+
+```tsx
+import { useEffect, useState, type FormEvent } from 'react'
+import { useNavigate, Link } from 'react-router-dom'
+import { useAuth } from '../hooks/useAuth'
+import {
+ getMyProfile,
+ updateMyProfile,
+ applyContactUpdateLocally,
+ type ProfileContact,
+} from '../services/authService'
+
+const validatePhone = (v: string) => {
+ if (!v) return '' // optional
+ if (v.length < 6) return 'Enter a valid phone number'
+ return ''
+}
+
+export default function UserProfile() {
+ const { user, isAuthenticated, refresh } = useAuth()
+ const navigate = useNavigate()
+ const [profile, setProfile] = useState<ProfileContact | null>(null)
+ const [isLoading, setIsLoading] = useState(true)
+ const [loadError, setLoadError] = useState<string | undefined>()
+ const [serverError, setServerError] = useState<string | undefined>()
+ const [successMessage, setSuccessMessage] = useState<string | undefined>()
+ const [errors, setErrors] = useState<Record<string, string>>({})
+ const [touched, setTouched] = useState<Record<string, boolean>>({})
+ const [isSubmitting, setIsSubmitting] = useState(false)
+
+ // Form state mirrors the editable profile values; empty string = clear column.
+ // Note: email is NOT in this form — it's shown read-only in Account Details.
+ const [form, setForm] = useState<Record<string, string>>({
+ firstname: '', lastname: '',
+ mobilephone: '', address1_line1: '', address1_city: '',
+ address1_stateorprovince: '', address1_postalcode: '', address1_country: '',
+ })
+
+ // Document title — same `<Page> — <Site Name>` convention as other auth pages
+ useEffect(() => { document.title = 'My Profile — Site Name' }, [])
+
+ useEffect(() => {
+ if (!isAuthenticated) {
+ navigate('/login?returnUrl=' + encodeURIComponent('/user-profile'))
+ return
+ }
+ if (!user?.contactId) {
+ setLoadError(
+ 'Profile unavailable for this account. Your contact record is missing or has no ID. ' +
+ 'If you signed in with workforce Entra ID, your admin needs to ensure RegistrationClaimsMapping ' +
+ 'is configured so contacts are created with the correct fields.'
+ )
+ setIsLoading(false)
+ return
+ }
+ getMyProfile(user.contactId)
+ .then(p => {
+ setProfile(p)
+ setForm({
+ firstname: p.firstname ?? '',
+ lastname: p.lastname ?? '',
+ mobilephone: p.mobilephone ?? '',
+ address1_line1: p.address1_line1 ?? '',
+ address1_city: p.address1_city ?? '',
+ address1_stateorprovince: p.address1_stateorprovince ?? '',
+ address1_postalcode: p.address1_postalcode ?? '',
+ address1_country: p.address1_country ?? '',
+ })
+ setIsLoading(false)
+ })
+ .catch(err => {
+ setLoadError(err instanceof Error ? err.message : 'Failed to load profile.')
+ setIsLoading(false)
+ })
+ }, [isAuthenticated, user?.contactId, navigate])
+
+ function validateField(name: string, value: string) {
+ let error = ''
+ if (name === 'mobilephone') error = validatePhone(value)
+ setErrors(prev => {
+ if (error) return { ...prev, [name]: error }
+ const next = { ...prev }; delete next[name]; return next
+ })
+ return error
+ }
+
+ function handleBlur(e: React.FocusEvent<HTMLInputElement>) {
+ setTouched(prev => ({ ...prev, [e.target.name]: true }))
+ validateField(e.target.name, e.target.value)
+ }
+
+ function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
+ setForm(prev => ({ ...prev, [e.target.name]: e.target.value }))
+ if (serverError) setServerError(undefined)
+ if (successMessage) setSuccessMessage(undefined)
+ if (touched[e.target.name]) validateField(e.target.name, e.target.value)
+ }
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ if (!profile) return
+
+ // Validate phone format (only field with a format check)
+ const phoneErr = validatePhone(form.mobilephone)
+ const errs: Record<string, string> = {}
+ if (phoneErr) errs.mobilephone = phoneErr
+ setErrors(errs)
+ setTouched(prev => ({ ...prev, mobilephone: true }))
+ if (Object.keys(errs).length > 0) return
+
+ // Build payload: convert empty strings to null (clear column);
+ // skip unchanged fields by comparing to loaded profile values
+ const payload: Record<string, string | null> = {}
+ for (const key of Object.keys(form)) {
+ const newValue = form[key] === '' ? null : form[key]
+ const oldValue = (profile as Record<string, string | null>)[key] ?? null
+ if (newValue !== oldValue) payload[key] = newValue
+ }
+ if (Object.keys(payload).length === 0) {
+ setSuccessMessage('No changes to save.')
+ return
+ }
+
+ setIsSubmitting(true)
+ setServerError(undefined)
+ updateMyProfile(profile.contactid, payload).then(() => {
+ setSuccessMessage('Profile updated.')
+ // Update local profile snapshot so the next save's diff is correct
+ setProfile(prev => prev ? { ...prev, ...payload } as ProfileContact : prev)
+ // Mirror the saved name fields into window.Microsoft.Dynamic365.Portal.User
+ // so the header avatar / display name picks up the new values immediately.
+ // Without this, refresh() below re-reads the unchanged Portal.User snapshot
+ // and the header keeps showing the old name until the next full page load.
+ applyContactUpdateLocally(payload)
+ // refresh() re-reads getCurrentUser() and (because useAuth's refresh spreads
+ // the result into a fresh object) triggers a re-render so AuthButton repaints.
+ refresh()
+ setIsSubmitting(false)
+ }).catch(err => {
+ setServerError(err instanceof Error ? err.message : 'Failed to save profile.')
+ setIsSubmitting(false)
+ })
+ }
+
+ const show = (f: string) => touched[f] ? errors[f] : undefined
+
+ // Compose the read-only "full name" displayed in Account Details.
+ // Prefer form values (so it reflects unsaved edits live), fall back to
+ // profile-loaded values, then to a placeholder.
+ const accountFullName = [form.firstname, form.lastname]
+ .map(s => s.trim()).filter(Boolean).join(' ') || '—'
+ const accountEmail = user?.email || '—'
+
+ if (isLoading) {
+ return (
+ <section style={styles.page}>
+ <div style={styles.card}>
+ <p style={{ textAlign: 'center', color: 'var(--color-text-muted)' }}>Loading profile...</p>
+ </div>
+ </section>
+ )
+ }
+
+ if (loadError) {
+ return (
+ <section style={styles.page}>
+ <div style={styles.card}>
+ <h1 style={styles.title}>Profile unavailable</h1>
+ <p style={{ color: 'var(--color-text-muted)', marginBottom: 24 }}>{loadError}</p>
+ <Link to="/" style={{ color: 'var(--color-primary)' }}>Back to home</Link>
+ </div>
+ </section>
+ )
+ }
+
+ return (
+ <section style={styles.page}>
+ <div className="animate-in" style={styles.card}>
+ <h1 style={styles.title}>My Profile</h1>
+ <p style={styles.subtitle}>Update your contact information. All fields are optional.</p>
+
+ {/* Read-only Account Details: just full name + email. No contactId, no roles. */}
+ <section aria-label="Account details" style={styles.accountDetails}>
+ <h2 style={styles.sectionHeading}>Account details</h2>
+ <dl style={styles.dl}>
+ <div style={styles.dlRow}>
+ <dt style={styles.dt}>Name</dt>
+ <dd style={styles.dd}>{accountFullName}</dd>
+ </div>
+ <div style={styles.dlRow}>
+ <dt style={styles.dt}>Email</dt>
+ <dd style={styles.dd}>{accountEmail}</dd>
+ </div>
+ </dl>
+ </section>
+
+ {successMessage && <div style={styles.successMessage} role="status">{successMessage}</div>}
+ {serverError && <div style={styles.serverError} role="alert">{serverError}</div>}
+
+ <form onSubmit={handleSubmit} noValidate style={styles.form}>
+ <h2 style={styles.sectionHeading}>Edit details</h2>
+ <div style={styles.grid}>
+ <Field name="firstname" label="First name" value={form.firstname} onBlur={handleBlur} onChange={handleChange} error={show('firstname')} />
+ <Field name="lastname" label="Last name" value={form.lastname} onBlur={handleBlur} onChange={handleChange} error={show('lastname')} />
+ <Field name="mobilephone" label="Mobile phone" type="tel" value={form.mobilephone} onBlur={handleBlur} onChange={handleChange} error={show('mobilephone')} />
+ </div>
+
+ <h2 style={styles.sectionHeading}>Address</h2>
+ <div style={styles.grid}>
+ <Field name="address1_line1" label="Street" value={form.address1_line1} onBlur={handleBlur} onChange={handleChange} />
+ <Field name="address1_city" label="City" value={form.address1_city} onBlur={handleBlur} onChange={handleChange} />
+ <Field name="address1_stateorprovince" label="State / Province" value={form.address1_stateorprovince} onBlur={handleBlur} onChange={handleChange} />
+ <Field name="address1_postalcode" label="Postal code" value={form.address1_postalcode} onBlur={handleBlur} onChange={handleChange} />
+ <Field name="address1_country" label="Country" value={form.address1_country} onBlur={handleBlur} onChange={handleChange} />
+ </div>
+
+ <button type="submit" className="btn-primary" disabled={isSubmitting}
+ style={{ marginTop: 24, justifyContent: 'center' }}>
+ {isSubmitting ? 'Saving...' : 'Save changes'}
+ </button>
+ </form>
+ </div>
+ </section>
+ )
+}
+
+function Field({ name, label, value, onChange, onBlur, error, type = 'text' }: {
+ name: string; label: string; value: string; type?: string;
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ onBlur: (e: React.FocusEvent<HTMLInputElement>) => void;
+ error?: string;
+}) {
+ return (
+ <div style={styles.field}>
+ <label htmlFor={`p-${name}`} style={styles.label}>{label}</label>
+ <input id={`p-${name}`} name={name} type={type} value={value} onChange={onChange} onBlur={onBlur}
+ style={{ ...styles.input, ...(error ? styles.inputError : {}) }}
+ aria-invalid={!!error} />
+ {error && <span style={styles.error} role="alert">{error}</span>}
+ </div>
+ )
+}
+
+const styles: Record<string, React.CSSProperties> = {
+ page: { minHeight: 'calc(100vh - 64px)', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '48px 24px', background: 'var(--color-bg)' },
+ card: { width: '100%', maxWidth: 580, background: 'var(--color-surface)', borderRadius: 'var(--radius-lg)', padding: 40, boxShadow: 'var(--shadow-md)', border: '1px solid var(--color-border)' },
+ title: { fontSize: '1.5rem', fontWeight: 600, marginBottom: 8 },
+ subtitle: { fontSize: '0.875rem', color: 'var(--color-text-muted)', marginBottom: 24 },
+ sectionHeading: { fontSize: '1rem', fontWeight: 600, marginTop: 24, marginBottom: 12 },
+ accountDetails: { padding: '16px 20px', background: 'var(--color-bg)', border: '1px solid var(--color-border)', borderRadius: 'var(--radius-sm)', marginBottom: 24 },
+ dl: { margin: 0, display: 'flex', flexDirection: 'column', gap: 8 },
+ dlRow: { display: 'flex', gap: 16, alignItems: 'baseline' },
+ dt: { fontSize: '0.75rem', textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--color-text-muted)', fontWeight: 600, minWidth: 60 },
+ dd: { margin: 0, fontSize: '0.875rem', color: 'var(--color-text)' },
+ form: { display: 'flex', flexDirection: 'column' },
+ grid: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 16 },
+ field: { display: 'flex', flexDirection: 'column', gap: 6 },
+ label: { fontSize: '0.875rem', fontWeight: 500 },
+ input: { fontFamily: 'var(--font-body)', fontSize: '0.875rem', padding: '10px 14px', borderRadius: 'var(--radius-sm)', border: '1px solid var(--color-border)', background: 'var(--color-surface)', color: 'var(--color-text)', outline: 'none' },
+ inputError: { borderColor: '#DA1E28' },
+ error: { fontSize: '0.75rem', color: '#DA1E28' },
+ successMessage: { padding: '12px 16px', background: '#DEFBE6', border: '1px solid #24A148', borderRadius: 'var(--radius-sm)', color: '#0E6027', fontSize: '0.875rem', marginBottom: 20 },
+ serverError: { padding: '12px 16px', background: '#FFF1F1', border: '1px solid #DA1E28', borderRadius: 'var(--radius-sm)', color: '#DA1E28', fontSize: '0.875rem', marginBottom: 20 },
+}
+```
+
+> **Intentionally NOT included in this page** (the executor must NOT add these even if they seem like obvious enhancements):
+> - **No editable email field** — email is read-only in Account Details. Across providers, email is often re-derived from claims on every login, so an SPA edit would be silently reverted and confuse the user.
+> - **No middle-name field** — keeps the form simple. Makers can extend post-generation if needed.
+> - **No Change Password / Reset Password link** — password management stays under `/forgot-password` for local accounts; surfacing it on the profile page muddles the UX for external-provider users who don't have a password at all.
+> - **No Sign Out button** — sign-out lives in the header `AuthButton` dropdown; duplicating it here is redundant.
+> - **No display of `contactId`, web roles, claims, or other metadata in Account Details** — those are debugging affordances, not user-facing info. Just full name + email.
+
+### Updated AuthButton with dropdown
+
+`src/components/AuthButton.tsx`:
+
+```tsx
+import { useEffect, useRef, useState } from 'react'
+import { Link } from 'react-router-dom'
+import { useAuth } from '../hooks/useAuth'
+
+const INCLUDE_PROFILE_PAGE = true // set by skill based on Phase 2.1 answer
+
+export default function AuthButton() {
+ const { isAuthenticated, isLoading, displayName, initials, logout } = useAuth()
+ const [open, setOpen] = useState(false)
+ const containerRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (!open) return
+ function onMouseDown(e: MouseEvent) {
+ if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
+ setOpen(false)
+ }
+ }
+ function onKeyDown(e: KeyboardEvent) {
+ if (e.key === 'Escape') setOpen(false)
+ }
+ document.addEventListener('mousedown', onMouseDown)
+ document.addEventListener('keydown', onKeyDown)
+ return () => {
+ document.removeEventListener('mousedown', onMouseDown)
+ document.removeEventListener('keydown', onKeyDown)
+ }
+ }, [open])
+
+ if (isLoading) return null
+
+ if (!isAuthenticated) {
+ return (
+ <Link to="/login" className="btn-primary" style={{ padding: '8px 20px', fontSize: '0.875rem', textDecoration: 'none' }}>
+ Sign In
+ </Link>
+ )
+ }
+
+ return (
+ <div ref={containerRef} style={{ position: 'relative' }}>
+ <button type="button"
+ onClick={() => setOpen(o => !o)}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ style={{
+ display: 'flex', alignItems: 'center', gap: 10,
+ background: 'none', border: 'none', cursor: 'pointer', padding: 4,
+ }}>
+ <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'var(--color-primary)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '0.75rem', fontWeight: 600 }} aria-hidden="true">{initials}</div>
+ <span style={{ fontSize: '0.875rem', fontWeight: 500 }}>{displayName}</span>
+ <span aria-hidden="true" style={{ fontSize: '0.65rem', color: 'var(--color-text-muted)' }}>▾</span>
+ </button>
+
+ {open && (
+ <div role="menu"
+ style={{
+ position: 'absolute', top: 'calc(100% + 8px)', right: 0,
+ minWidth: 180,
+ background: 'var(--color-surface)',
+ border: '1px solid var(--color-border)',
+ borderRadius: 'var(--radius-sm)',
+ boxShadow: 'var(--shadow-md)',
+ padding: 4,
+ zIndex: 100,
+ }}>
+ {INCLUDE_PROFILE_PAGE && (
+ <Link to="/user-profile" role="menuitem"
+ onClick={() => setOpen(false)}
+ style={menuItemStyle}>
+ My Profile
+ </Link>
+ )}
+ <button type="button" role="menuitem"
+ onClick={() => { setOpen(false); logout('/'); }}
+ style={{ ...menuItemStyle, background: 'none', border: 'none', textAlign: 'left', cursor: 'pointer', width: '100%' }}>
+ Sign Out
+ </button>
+ </div>
+ )}
+ </div>
+ )
+}
+
+const menuItemStyle: React.CSSProperties = {
+ display: 'block',
+ padding: '10px 14px',
+ fontSize: '0.875rem',
+ color: 'var(--color-text)',
+ textDecoration: 'none',
+ borderRadius: 'var(--radius-sm)',
+}
+```
+
+### Routing
+
+In `src/App.tsx`:
+
+```tsx
+import UserProfile from './pages/UserProfile'
+// ...
+<Route path="/user-profile" element={<UserProfile />} />
+```
+
+### `useAuth().refresh()` mechanics — why the header updates immediately
+
+`useAuth()` derives `displayName` and `initials` by reading from `window.Microsoft.Dynamic365.Portal.User` — a global snapshot the Power Pages server sets when the page is first rendered. Two things have to be true for the header to repaint after a successful profile save:
+
+1. **`Portal.User` itself must reflect the new values.** The Web API PATCH only updates Dataverse, not this in-memory object. The `applyContactUpdateLocally(payload)` helper in `authService.ts` mirrors the saved `firstname` / `lastname` back into `Portal.User` after the PATCH succeeds.
+
+2. **`refresh()` must trigger a re-render.** The hook's `loadUser`/`refresh` function calls `setUser(getCurrentUser())` — but `getCurrentUser()` returns the same `Portal.User` reference every time, so a naive `setUser(getCurrentUser())` is a no-op (React skips re-renders when the state reference is identical). The reference impl above spreads the user into a fresh object: `setUser(current ? { ...current } : undefined)`. That forces React to see a new ref and re-run `AuthButton`, which re-reads `getUserDisplayName()` / `getUserInitials()` — now returning the new values because `Portal.User` was mutated in step 1.
+
+Both pieces are required. Drop either one and the header stays stale until a full page navigation.
+
+Email is intentionally NOT mirrored by `applyContactUpdateLocally`, since the profile page makes email read-only and never PATCHes it.
+
+### Empty contactId edge case
+
+If `user.contactId` is empty or missing, the page shows a friendly error pointing the user to the `RegistrationClaimsMapping` site setting (see the workforce Entra ID empty-contact issue documented elsewhere in this reference). The user can't edit a contact that doesn't exist or has no ID.
+
+### Unauthenticated `/SignIn` bounce — keep the SPA experience
+
+The SPA `UserProfile` component handles `!isAuthenticated` by navigating to `/login?returnUrl=/user-profile`. **But the legacy server-rendered `/profile` path is a different story**: if a user types `/profile` (or follows an old link) while unauthenticated, the server short-circuits its own auth check and 302s the user to `/SignIn?ReturnUrl=/profile` — the legacy ASP.NET sign-in page, which drops them out of the SPA UI entirely.
+
+This is solved at the `Code-Site-Shell-Header` redirect-map layer (the same template that already handles `/Account/Login/ResetPassword`, `/Account/Login/ExternalAuthenticationFailed`, etc.). Add `/signin` to the redirect map:
+
+```js
+var redirects = {
+ // ...other entries...
+ '/signin': '/login' // ← catches the server's "you need to sign in" bounce
+};
+```
+
+The existing template already appends `window.location.search` to the SPA URL, so `?ReturnUrl=/profile` (server casing) is carried through unchanged. The SPA `Login` page currently ignores `ReturnUrl` and always navigates to `/` after sign-in, which is fine — no further wiring is needed. If you later want the SPA to honor it, mirror the `invitationCode` / `InvitationCode` dual-casing pattern in `Login.tsx`.
+
+This redirect should be added regardless of which auth flow is configured — `/SignIn` is the server's universal sign-in entry point, and any server-protected route (`/profile`, `/Account/Manage`, anything gated by web roles) bounces through it.
+
+### Permission boundary verification
+
+To verify Self-scope is enforcing row-level security:
+1. Sign in as user A → note their contactId (e.g., visible in `window.Microsoft.Dynamic365.Portal.User.contactId`)
+2. In DevTools console, try to PATCH a different user's contact:
+ ```javascript
+ fetch('/_api/contacts(SOMEONE-ELSES-GUID)', {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', 'If-Match': '*' },
+ body: JSON.stringify({ firstname: 'Hacked' }),
+ credentials: 'same-origin',
+ }).then(r => console.log(r.status))
+ ```
+3. Expect 403. If you get 200, the table permission is misconfigured (wrong scope or wrong role assignment).
diff --git a/plugins/power-pages/skills/setup-auth/scripts/validate-auth.js b/plugins/power-pages/skills/setup-auth/scripts/validate-auth.js
index 409bc5e26..6d0be769c 100644
--- a/plugins/power-pages/skills/setup-auth/scripts/validate-auth.js
+++ b/plugins/power-pages/skills/setup-auth/scripts/validate-auth.js
@@ -1,7 +1,15 @@
#!/usr/bin/env node
-// Validates that authentication and authorization code was created for a Power Pages code site.
-// Runs as a Stop hook to verify the setup-auth skill produced output.
+// Validates that authentication and authorization code was created for a
+// Power Pages code site. Runs as a PostToolUse:Skill hook (configured in
+// hooks/hooks.json) after the `Skill` tool fires for /power-pages:setup-auth.
+//
+// Because PostToolUse fires when the Skill tool LOADS (instructions are read
+// into context) rather than when the skill has FINISHED its work, this
+// validator gates on a finishing marker: the auth setup report HTML written
+// by the skill's final Phase 8.3.5. Until that report exists, the skill is
+// considered in-progress and validation silent-approves. This follows the
+// marker-file recommendation in plugins/power-pages/PLUGIN_DEVELOPMENT_GUIDE.md.
const fs = require('fs');
const path = require('path');
@@ -9,13 +17,19 @@ const { approve, block, runValidation, findProjectRoot } = require('../../../scr
runValidation((cwd) => {
const projectRoot = findProjectRoot(cwd);
- if (!projectRoot) approve(); // Not a Power Pages project, skip
+ if (!projectRoot) return approve(); // Not a Power Pages project, skip
// Check if any auth files exist — if none, this wasn't an auth session
const authServiceExists = findAuthService(projectRoot);
const typeDeclarationsExist = findTypeDeclarations(projectRoot);
- if (!authServiceExists && !typeDeclarationsExist) approve();
+ if (!authServiceExists && !typeDeclarationsExist) return approve();
+
+ // Marker gate: silent-approve until the skill writes its finishing report.
+ // Without this gate, re-running setup-auth on a project that has stale auth
+ // files from a previous attempt would block the new run before it could
+ // overwrite them.
+ if (!hasFinishingMarker(projectRoot)) return approve();
const errors = [];
@@ -42,12 +56,26 @@ runValidation((cwd) => {
if (!content.includes('/_layout/tokenhtml') && !content.includes('fetchAntiForgeryToken')) {
errors.push('Auth service missing anti-forgery token handling');
}
+ // Verify provider configuration exists. The canonical pattern in
+ // authentication-reference.md is the AUTH_PROVIDERS array (even single-
+ // provider sites use a one-element array — see SKILL.md and the
+ // "Multiple Providers — Canonical AUTH_PROVIDERS Array Pattern" section
+ // of authentication-reference.md). AuthProviderConfig is the interface
+ // name and is also a valid marker (auth service must declare the type).
+ if (!content.includes('AUTH_PROVIDERS') && !content.includes('AuthProviderConfig')) {
+ errors.push('Auth service missing provider configuration — expected the AUTH_PROVIDERS array or AuthProviderConfig type. The canonical pattern is `export const AUTH_PROVIDERS: AuthProviderConfig[] = [...]` even when only one provider is configured.');
+ }
}
- // Check for authorization utilities
+ // Check for authorization utilities — only if auth service references role-checking
+ // (skip for "Login & Logout only" scope where authorization utils are not created)
const authzUtils = findAuthorizationUtils(projectRoot);
- if (!authzUtils) {
- errors.push('Missing authorization utilities (src/utils/authorization.ts or equivalent)');
+ if (!authzUtils && authServiceExists) {
+ const authContent = fs.readFileSync(authServiceExists, 'utf8');
+ // Only flag missing authz utils if the auth service imports or references them
+ if (authContent.includes('authorization') || authContent.includes('hasRole') || authContent.includes('getUserRoles')) {
+ errors.push('Missing authorization utilities (src/utils/authorization.ts or equivalent)');
+ }
}
// Check for auth UI component
@@ -63,6 +91,22 @@ runValidation((cwd) => {
approve();
});
+function hasFinishingMarker(projectRoot) {
+ // The skill writes `docs/auth-setup-report.html` at the end of Phase 8.3.5.
+ // If the user already had a previous report there, the renderer date-suffixes
+ // the new one (auth-setup-report-2026-05-27.html). Treat any matching file
+ // in docs/ as evidence that the skill has completed at least one run.
+ const docsDir = path.join(projectRoot, 'docs');
+ if (!fs.existsSync(docsDir)) return false;
+ try {
+ return fs.readdirSync(docsDir).some((name) =>
+ /^auth-setup-report.*\.html$/.test(name)
+ );
+ } catch {
+ return false;
+ }
+}
+
function findAuthService(projectRoot) {
const candidates = [
path.join(projectRoot, 'src', 'services', 'authService.ts'),