progmaweb
The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.
Clonegit clone https://git.progmasoft.com/progmaweb
Move the OAuth pages to Next.js and split the authorize host and the console
- Commit
9099e9fbb50d27b622362b0c2f0dda5085d1fa03- Author
- Leitwolf11 ·
- Parents
3481b5fe411f
Changes
apps/api-tests/AccountApiFactory.cs | 41 +- apps/api-tests/OAuthFlowTests.cs | 95 ++- apps/api-tests/OAuthPolicyTests.cs | 320 ++++++-- apps/api-tests/OAuthTestClient.cs | 171 ++-- apps/api/Accounts/AccountEndpoints.cs | 10 +- apps/api/Accounts/SessionService.cs | 31 +- apps/api/OAuth/Api/AllowedApplicationEndpoints.cs | 99 +++ apps/api/OAuth/Api/ApplicationEndpoints.cs | 240 ++++++ apps/api/OAuth/Api/ConsentEndpoints.cs | 108 +++ apps/api/OAuth/Api/OAuthAccount.cs | 82 ++ apps/api/OAuth/Api/OAuthCors.cs | 128 +++ apps/api/OAuth/Api/SessionEndpoints.cs | 78 ++ apps/api/OAuth/Developers/ApplicationKind.cs | 104 +++ apps/api/OAuth/Developers/ApplicationPolicy.cs | 96 ++- apps/api/OAuth/Developers/ApplicationRegistry.cs | 80 +- apps/api/OAuth/Developers/DeveloperEndpoints.cs | 300 ------- apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs | 55 +- apps/api/OAuth/OAuthEndpoints.cs | 19 +- apps/api/OAuth/OAuthHostFilter.cs | 76 +- apps/api/OAuth/OAuthOptions.cs | 17 +- apps/api/OAuth/OAuthRegistration.cs | 15 +- .../OAuth/Pages/AllowedApplicationsEndpoints.cs | 95 --- apps/api/OAuth/Pages/HtmlPage.cs | 95 --- apps/api/OAuth/Pages/SignInEndpoints.cs | 167 ---- apps/api/Program.cs | 2 + apps/api/appsettings.Development.json | 12 +- apps/api/appsettings.json | 5 +- apps/web/app/authorize/applications/page.tsx | 28 + apps/web/app/authorize/consent/page.tsx | 43 + apps/web/app/authorize/layout.tsx | 18 + apps/web/app/authorize/oauth.css | 259 ++++++ apps/web/app/authorize/page.tsx | 32 + apps/web/app/authorize/signin/page.tsx | 41 + .../app/console/credentials/[clientId]/page.tsx | 42 + .../app/console/credentials/new/[kind]/page.tsx | 44 + apps/web/app/console/credentials/new/page.tsx | 42 + apps/web/app/console/credentials/page.tsx | 28 + apps/web/app/console/layout.tsx | 18 + apps/web/app/console/page.tsx | 52 ++ apps/web/app/issuer/layout.tsx | 18 + apps/web/app/issuer/page.tsx | 54 ++ apps/web/app/robots.ts | 9 + apps/web/components/Brand.tsx | 9 +- .../components/credentials/AccountSignInNotice.tsx | 34 + .../components/credentials/AllowedApplications.tsx | 113 +++ .../components/credentials/ApplicationDetails.tsx | 193 +++++ .../web/components/credentials/ApplicationForm.tsx | 178 +++++ apps/web/components/credentials/ConsentPanel.tsx | 131 +++ .../web/components/credentials/CredentialsCard.tsx | 58 ++ .../web/components/credentials/CredentialsHome.tsx | 95 +++ .../components/credentials/CredentialsShell.tsx | 89 +++ apps/web/components/credentials/NewToken.tsx | 87 ++ apps/web/components/credentials/SignInForm.tsx | 124 +++ apps/web/components/credentials/TokenList.tsx | 106 +++ apps/web/lib/credentials-messages.ts | 887 +++++++++++++++++++++ apps/web/lib/credentials.ts | 258 ++++++ apps/web/lib/hosts.server.ts | 35 + apps/web/proxy.ts | 40 + apps/web/tests/credentials.test.mjs | 124 +++ docs/ACCOUNT-API.md | 10 +- docs/OAUTH.md | 85 +- docs/README.md | 2 +- docs/api/namespaces/Progmasoft.OAuth.Api.md | 9 + docs/api/namespaces/Progmasoft.OAuth.Developers.md | 2 +- docs/api/namespaces/Progmasoft.OAuth.Pages.md | 9 - ops/README.md | 22 +- ops/nginx/progmaweb.conf | 149 +++- 67 files changed, 5078 insertions(+), 1040 deletions(-) diff --git a/apps/api-tests/AccountApiFactory.cs b/apps/api-tests/AccountApiFactory.cs index 926de65..bbe2d64 100644 --- a/apps/api-tests/AccountApiFactory.cs +++ b/apps/api-tests/AccountApiFactory.cs @@ -49,8 +49,10 @@ internal sealed class AccountApiFactory( // Progmasoft OAuth reads its host while services are registered, like the Google client above. Its own host // keeps the host filter honest: the account API answers on localhost, OAuth on oauth.localhost. builder.UseSetting("OAuth:Host", OAuthHost); + builder.UseSetting("OAuth:AuthorizeHost", AuthorizeHost); + builder.UseSetting("OAuth:ConsoleHost", ConsoleHost); builder.UseSetting("AllowedHosts", - $"localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;{OAuthHost}"); + $"localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;{OAuthHost};{AuthorizeHost};{ConsoleHost}"); if (oauthKeys && environment == "Production") { Directory.CreateDirectory(keyDirectory); @@ -74,7 +76,9 @@ internal sealed class AccountApiFactory( configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["AccountSessions:LifetimeHours"] = "2", - ["AccountSessions:CookieName"] = "__Host-ProgmasoftSession" + ["AccountSessions:CookieName"] = "__Host-ProgmasoftSession", + // A host-only cookie: the console tests send the account session themselves. + ["AccountSessions:CookieDomain"] = string.Empty }); }); } @@ -82,6 +86,10 @@ internal sealed class AccountApiFactory( /// <summary>The host Progmasoft OAuth answers on in the tests.</summary> public const string OAuthHost = "oauth.localhost"; + public const string AuthorizeHost = "authorize.localhost"; + + public const string ConsoleHost = "console.localhost"; + /// <summary>A client of the OAuth host that keeps its cookies and does not follow redirections.</summary> public HttpClient CreateOAuthClient() => CreateClient( new WebApplicationFactoryClientOptions @@ -91,6 +99,35 @@ internal sealed class AccountApiFactory( HandleCookies = true }); + /// <summary>A browser on the authorize host: sign-in, consent and the allowed applications.</summary> + public HttpClient CreateAuthorizeClient() => CreateClient( + new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri($"https://{AuthorizeHost}"), + HandleCookies = true + }); + + /// <summary> + /// A browser on the Progmasoft Console. Production shares the account session cookie with progmasoft.com; the + /// test hosts are not under one domain, so a test sends the session cookie of an account itself. + /// </summary> + public HttpClient CreateConsoleClient(string? sessionCookie = null) + { + HttpClient client = CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + BaseAddress = new Uri($"https://{ConsoleHost}"), + HandleCookies = false + }); + if (sessionCookie is not null) + { + client.DefaultRequestHeaders.Add("Cookie", sessionCookie); + } + + return client; + } + protected override void Dispose(bool disposing) { base.Dispose(disposing); diff --git a/apps/api-tests/OAuthFlowTests.cs b/apps/api-tests/OAuthFlowTests.cs index dcd94de..b550e0e 100644 --- a/apps/api-tests/OAuthFlowTests.cs +++ b/apps/api-tests/OAuthFlowTests.cs @@ -152,12 +152,17 @@ public sealed class OAuthFlowTests Assert.Equal(HttpStatusCode.Redirect, again.StatusCode); Assert.NotNull(OAuthTestClient.Query(again.Headers.Location!, "code")); - string allowed = await browser.Browser.GetStringAsync("/account/applications", Cancel); - Assert.Contains("Example Client", allowed, StringComparison.Ordinal); - string action = System.Text.RegularExpressions.Regex.Match(allowed, - "action=\"(/account/applications/[^\"]+/revoke)\"").Groups[1].Value; - HttpResponseMessage withdrawn = await browser.SubmitAsync("/account/applications", action, []); - Assert.Equal(HttpStatusCode.Redirect, withdrawn.StatusCode); + JsonElement allowed = await (await browser.SendAsync(HttpMethod.Get, "/api/v1/oauth/allowed")) + .Content.ReadFromJsonAsync<JsonElement>(Cancel); + JsonElement entry = Assert.Single(allowed.EnumerateArray()); + Assert.Equal("Example Client", entry.GetProperty("displayName").GetString()); + string authorizationId = entry.GetProperty("authorizationId").GetString()!; + HttpResponseMessage foreign = await browser.SendAsync(HttpMethod.Delete, + $"/api/v1/oauth/allowed/{authorizationId}", origin: "https://attacker.example"); + Assert.Equal(HttpStatusCode.Forbidden, foreign.StatusCode); + HttpResponseMessage withdrawn = await browser.SendAsync(HttpMethod.Delete, + $"/api/v1/oauth/allowed/{authorizationId}"); + Assert.Equal(HttpStatusCode.NoContent, withdrawn.StatusCode); (HttpStatusCode refreshed, _) = await browser.TokenAsync(new Dictionary<string, string> { @@ -191,16 +196,60 @@ public sealed class OAuthFlowTests (string clientId, _) = await browser.RegisterApplicationAsync( "profile email viget.packages.read viget.packages.publish viget.packages.yank"); - HttpResponseMessage page = await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, + HttpResponseMessage authorize = await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, "openid profile email viget.packages.read viget.packages.publish viget.packages.yank", OAuthTestClient.Pkce().Challenge), Cancel); - string html = await page.Content.ReadAsStringAsync(Cancel); - Assert.Contains("Read your Progmasoft account name.", html, StringComparison.Ordinal); - Assert.Contains("Read the email address you sign in and registered with.", html, StringComparison.Ordinal); - Assert.Contains("Read the packages you have published on ViGet.", html, StringComparison.Ordinal); - Assert.Contains("Publish packages to ViGet under your account.", html, StringComparison.Ordinal); - Assert.Contains("Yank packages you have published on ViGet.", html, StringComparison.Ordinal); - Assert.Contains("registered by <strong>OAuthHolder6</strong>", html, StringComparison.Ordinal); + Uri consentPage = authorize.Headers.Location!; + Assert.True(OAuthTestClient.IsConsentPage(consentPage), consentPage.OriginalString); + + JsonElement consent = await browser.Browser.GetFromJsonAsync<JsonElement>( + "/api/v1/oauth/consent" + consentPage.OriginalString["/consent".Length..], Cancel); + Assert.Equal(["profile", "email", "viget.packages.read", "viget.packages.publish", "viget.packages.yank"], + consent.GetProperty("scopes").EnumerateArray().Select(scope => scope.GetString())); + Assert.Equal("Example Client", consent.GetProperty("displayName").GetString()); + Assert.Equal("OAuthHolder6", consent.GetProperty("owner").GetString()); + Assert.Equal("OAuthHolder6", consent.GetProperty("accountName").GetString()); + Assert.Equal("https://client.example", consent.GetProperty("returnTo").GetString()); + Assert.Equal("https://client.example", consent.GetProperty("homepage").GetString()); + } + + [Fact] + public async Task TheConsentPageDescribesOnlyRequestsTheApplicationCouldMake() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder10", "holder10@example.com"); + (string clientId, _) = await browser.RegisterApplicationAsync("profile"); + + string Query(string redirectUri, string scope) => + $"/api/v1/oauth/consent?client_id={clientId}&redirect_uri={Uri.EscapeDataString(redirectUri)}" + + $"&scope={Uri.EscapeDataString(scope)}"; + Assert.Equal(HttpStatusCode.OK, + (await browser.Browser.GetAsync(Query(OAuthTestClient.RedirectUri, "openid profile"), Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, + (await browser.Browser.GetAsync(Query("https://attacker.example/callback", "openid"), Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, + (await browser.Browser.GetAsync(Query(OAuthTestClient.RedirectUri, "openid email"), Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.BadRequest, (await browser.Browser.GetAsync( + "/api/v1/oauth/consent?client_id=pmo_missing&redirect_uri=https%3A%2F%2Fclient.example%2Fcallback", + Cancel)).StatusCode); + } + + [Fact] + public async Task AConsentDecisionFromAnotherSiteIsRefused() + { + await using AccountApiFactory factory = new(); + OAuthTestClient browser = new(factory); + await browser.RegisterAndSignInAsync("OAuthHolder11", "holder11@example.com"); + (string clientId, _) = await browser.RegisterApplicationAsync("profile"); + + HttpResponseMessage authorize = await browser.Browser.GetAsync( + OAuthTestClient.AuthorizePath(clientId, "openid profile", OAuthTestClient.Pkce().Challenge), Cancel); + Uri consentPage = authorize.Headers.Location!; + HttpResponseMessage forged = await browser.DecideAsync(consentPage, "allow", "https://attacker.example"); + Assert.Equal(HttpStatusCode.Forbidden, forged.StatusCode); + HttpResponseMessage blind = await browser.DecideAsync(consentPage, "allow", origin: null); + Assert.Equal(HttpStatusCode.Forbidden, blind.StatusCode); } [Fact] @@ -244,19 +293,13 @@ public sealed class OAuthFlowTests await using AccountApiFactory factory = new(); OAuthTestClient browser = new(factory); await browser.RegisterAndSignInAsync("OAuthHolder8", "holder8@example.com"); - (string clientId, string? secret) = await browser.RegisterApplicationAsync("profile", isPublic: true, + (string clientId, string? secret) = await browser.RegisterApplicationAsync("profile", kind: "desktop", redirectUris: "com.example.app:/callback"); Assert.Null(secret); (string verifier, string challenge) = OAuthTestClient.Pkce(); - HttpResponseMessage page = await browser.Browser.GetAsync(OAuthTestClient.AuthorizePath(clientId, - "openid profile", challenge, "com.example.app:/callback"), Cancel); - string html = await page.Content.ReadAsStringAsync(Cancel); - List<KeyValuePair<string, string>> fields = OAuthTestClient.HiddenFields(html); - fields.Add(new("decision", "allow")); - HttpResponseMessage decided = await browser.Browser.PostAsync("/connect/authorize", - new FormUrlEncodedContent(fields), Cancel); - Uri redirect = decided.Headers.Location!; + Uri redirect = await browser.AuthorizeAsync(clientId, "openid profile", challenge, + redirectUri: "com.example.app:/callback"); Assert.Equal("com.example.app", redirect.Scheme); (HttpStatusCode status, _) = await browser.TokenAsync(new Dictionary<string, string> @@ -320,7 +363,7 @@ public sealed class OAuthFlowTests await using AccountApiFactory factory = new(); OAuthTestClient browser = new(factory); await browser.RegisterAndSignInAsync("OAuthHolder9", "holder9@example.com"); - (string clientId, string? secret) = await browser.RegisterApplicationAsync("profile", clientCredentials: true); + (string clientId, string? secret) = await browser.RegisterServiceAsync(); (HttpStatusCode status, JsonElement token) = await browser.TokenAsync(new Dictionary<string, string> { @@ -337,8 +380,10 @@ public sealed class OAuthFlowTests ["client_secret"] = secret!, ["scope"] = "profile" }); + // A service has no scope permission at all, so OpenIddict refuses the scope before the handler sees it. Assert.Equal(HttpStatusCode.BadRequest, scoped); - Assert.Equal("invalid_scope", error.GetProperty("error").GetString()); + Assert.Equal("invalid_request", error.GetProperty("error").GetString()); + Assert.Contains("scope", error.GetProperty("error_description").GetString(), StringComparison.Ordinal); (HttpStatusCode wrongSecret, _) = await browser.TokenAsync(new Dictionary<string, string> { diff --git a/apps/api-tests/OAuthPolicyTests.cs b/apps/api-tests/OAuthPolicyTests.cs index 1f84c77..2c95656 100644 --- a/apps/api-tests/OAuthPolicyTests.cs +++ b/apps/api-tests/OAuthPolicyTests.cs @@ -8,7 +8,6 @@ using System.Text; using System.Text.Json; using Microsoft.EntityFrameworkCore; using Progmasoft.OAuth.Developers; -using Progmasoft.OAuth.Pages; using Progmasoft.OAuth.Storage; namespace Progmasoft.Progmaweb.Api.Tests; @@ -18,32 +17,64 @@ public sealed class OAuthPolicyTests private static CancellationToken Cancel => TestContext.Current.CancellationToken; [Theory] - [InlineData("https://client.example/callback", false, true)] - [InlineData("http://127.0.0.1:8400/callback", false, true)] - [InlineData("http://[::1]:8400/callback", false, true)] - [InlineData("http://localhost:3000/callback", false, true)] - [InlineData("http://client.example/callback", false, false)] - [InlineData("https://client.example/callback#fragment", false, false)] - [InlineData("https://user:password@client.example/callback", false, false)] - [InlineData("https://*.client.example/callback", false, false)] - [InlineData("com.example.app:/callback", true, true)] - [InlineData("com.example.app:/callback", false, false)] - [InlineData("javascript:alert(1)", true, false)] - [InlineData("data:text/html,x", true, false)] - [InlineData("myapp:/callback", true, false)] - [InlineData("/relative/callback", false, false)] - public void RedirectionAddressesFollowRfc8252(string address, bool isPublic, bool accepted) => - Assert.Equal(accepted, ApplicationPolicy.IsRedirectionAddress(address, isPublic)); + [InlineData("https://client.example/callback", "web", true)] + [InlineData("http://127.0.0.1:8400/callback", "web", true)] + [InlineData("http://[::1]:8400/callback", "web", true)] + [InlineData("http://localhost:3000/callback", "web", true)] + [InlineData("http://client.example/callback", "web", false)] + [InlineData("https://client.example/callback#fragment", "web", false)] + [InlineData("https://user:password@client.example/callback", "web", false)] + [InlineData("https://*.client.example/callback", "web", false)] + [InlineData("com.example.app:/callback", "web", false)] + [InlineData("/relative/callback", "web", false)] + [InlineData("https://app.example/callback", "spa", true)] + [InlineData("http://localhost:5173/callback", "spa", true)] + [InlineData("com.example.app:/callback", "spa", false)] + [InlineData("http://127.0.0.1:8400/callback", "desktop", true)] + [InlineData("com.example.app:/callback", "desktop", true)] + [InlineData("https://client.example/callback", "desktop", false)] + [InlineData("myapp:/callback", "desktop", false)] + [InlineData("javascript:alert(1)", "desktop", false)] + [InlineData("data:text/html,x", "mobile", false)] + [InlineData("com.example.app:/callback", "mobile", true)] + [InlineData("https://app.example/open", "mobile", true)] + [InlineData("http://127.0.0.1:8400/callback", "mobile", false)] + [InlineData("https://client.example/callback", "service", false)] + public void RedirectionAddressesFollowRfc8252ForEachType(string address, string kind, bool accepted) => + Assert.Equal(accepted, ApplicationPolicy.IsRedirectionAddress(address, ApplicationKinds.Parse(kind)!.Value)); [Fact] public void ARegistrationIsCheckedFieldByField() { Dictionary<string, string> errors = ApplicationPolicy.Validate(new ApplicationInput( - "x", "http://plain.example", true, [], [], ["profile", "not-a-scope"], true)); - Assert.Equal(["allowClientCredentials", "displayName", "homepage", "redirectUris", "scopes"], - errors.Keys.Order(StringComparer.Ordinal)); + "x", "http://plain.example", ApplicationKind.Desktop, [], [], ["profile", "not-a-scope"])); + Assert.Equal(["displayName", "homepage", "redirectUris", "scopes"], errors.Keys.Order(StringComparer.Ordinal)); Assert.Empty(ApplicationPolicy.Validate(new ApplicationInput( - "Example", string.Empty, false, ["https://client.example/callback"], [], ["profile"], true))); + "Example", string.Empty, ApplicationKind.Web, ["https://client.example/callback"], [], ["profile"]))); + } + + [Fact] + public void AServiceRegistersNeitherAddressesNorAccountScopes() + { + Assert.Empty(ApplicationPolicy.Validate(new ApplicationInput( + "Build robot", string.Empty, ApplicationKind.Service, [], [], []))); + Dictionary<string, string> errors = ApplicationPolicy.Validate(new ApplicationInput( + "Build robot", string.Empty, ApplicationKind.Service, ["https://client.example/callback"], [], ["profile"])); + Assert.Equal(["redirectUris", "scopes"], errors.Keys.Order(StringComparer.Ordinal)); + } + + [Fact] + public void EveryTypeHasANameThatParsesBack() + { + Assert.Equal(["web", "spa", "desktop", "mobile", "service"], ApplicationKinds.All.Select(kind => kind.Slug())); + foreach (ApplicationKind kind in ApplicationKinds.All) + { + Assert.Equal(kind, ApplicationKinds.Parse(kind.Slug())); + } + + Assert.Null(ApplicationKinds.Parse("confidential")); + Assert.Equal([ApplicationKind.SinglePage, ApplicationKind.Desktop, ApplicationKind.Mobile], + ApplicationKinds.All.Where(kind => kind.IsPublic())); } [Fact] @@ -54,6 +85,13 @@ public sealed class OAuthPolicyTests JsonElement document = await client.GetFromJsonAsync<JsonElement>("/.well-known/openid-configuration", Cancel); Assert.Equal($"https://{AccountApiFactory.OAuthHost}/", document.GetProperty("issuer").GetString()); + // People visit the authorize host; clients call the issuer. + Assert.Equal($"https://{AccountApiFactory.AuthorizeHost}/connect/authorize", + document.GetProperty("authorization_endpoint").GetString()); + Assert.Equal($"https://{AccountApiFactory.AuthorizeHost}/connect/logout", + document.GetProperty("end_session_endpoint").GetString()); + Assert.Equal($"https://{AccountApiFactory.OAuthHost}/connect/token", + document.GetProperty("token_endpoint").GetString()); string grants = document.GetProperty("grant_types_supported").ToString(); Assert.Contains("authorization_code", grants, StringComparison.Ordinal); Assert.Contains("refresh_token", grants, StringComparison.Ordinal); @@ -83,7 +121,42 @@ public sealed class OAuthPolicyTests Assert.Equal(HttpStatusCode.NotFound, (await accounts.GetAsync("/.well-known/openid-configuration", Cancel)).StatusCode); - Assert.Equal(HttpStatusCode.NotFound, (await accounts.GetAsync("/signin", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await accounts.GetAsync("/api/v1/oauth/session", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/api/v1/accounts/me", Cancel)).StatusCode); + // The pages of the OAuth host belong to the Next.js site; the API answers none of them. + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/signin", Cancel)).StatusCode); + + // People sign in and decide on the authorize host; clients call the issuer. + using HttpClient authorize = factory.CreateAuthorizeClient(); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/connect/authorize", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/connect/logout", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/api/v1/oauth/session", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/api/v1/oauth/allowed", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await authorize.GetAsync("/.well-known/openid-configuration", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await authorize.PostAsync("/connect/token", null, Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await authorize.GetAsync("/connect/userinfo", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await authorize.GetAsync("/api/v1/oauth/applications", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, + (await authorize.GetAsync("/api/v1/oauth/session", Cancel)).StatusCode); + + // Applications are managed in the Progmasoft Console only, and the console issues no tokens. + using HttpClient console = factory.CreateConsoleClient(); + Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/api/v1/oauth/applications", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await accounts.GetAsync("/api/v1/oauth/applications", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, + (await console.GetAsync("/api/v1/oauth/applications", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, (await console.GetAsync("/api/v1/oauth/session", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await console.GetAsync("/.well-known/openid-configuration", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await console.GetAsync("/api/v1/oauth/allowed", Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await console.PostAsync("/connect/token", null, Cancel)).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, (await console.GetAsync("/api/v1/accounts/me", Cancel)).StatusCode); + // The console has no sign-in of its own. + Assert.Equal(HttpStatusCode.NotFound, (await console.PostAsync("/api/v1/oauth/signin", null, Cancel)).StatusCode); Assert.Equal(HttpStatusCode.NotFound, (await accounts.PostAsync("/connect/token", null, Cancel)).StatusCode); Assert.Equal(HttpStatusCode.NotFound, (await oauth.GetAsync("/api/v1/status", Cancel)).StatusCode); Assert.Equal(HttpStatusCode.OK, (await oauth.GetAsync("/health", Cancel)).StatusCode); @@ -135,7 +208,7 @@ public sealed class OAuthPolicyTests await developer.RegisterAndSignInAsync("PolicyHolder2", "policy2@example.com"); (string clientId, _) = await developer.RegisterApplicationAsync("profile"); - using HttpClient anonymous = factory.CreateOAuthClient(); + using HttpClient anonymous = factory.CreateAuthorizeClient(); string path = OAuthTestClient.AuthorizePath(clientId, "openid", OAuthTestClient.Pkce().Challenge, prompt: "login"); HttpResponseMessage response = await anonymous.GetAsync(path, Cancel); Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); @@ -150,28 +223,29 @@ public sealed class OAuthPolicyTests } [Fact] - public async Task TheSignInPageGivesOneMessageForEveryFailureAndKeepsReturnAddressesLocal() + public async Task SignInGivesOneMessageForEveryFailureAndOnlyFromThisSite() { await using AccountApiFactory factory = new(); OAuthTestClient browser = new(factory); - HttpResponseMessage failed = await browser.SubmitAsync("/signin", "/signin", new Dictionary<string, string> - { - ["email"] = "nobody@example.com", - ["password"] = "wrong password here", - ["returnUrl"] = "https://attacker.example/" - }); + HttpResponseMessage failed = await browser.SendAsync(HttpMethod.Post, "/api/v1/oauth/signin", + new { email = "nobody@example.com", password = "wrong password here" }); Assert.Equal(HttpStatusCode.Unauthorized, failed.StatusCode); - string html = await failed.Content.ReadAsStringAsync(Cancel); - Assert.Contains("The email address or the password is not right.", html, StringComparison.Ordinal); - Assert.Contains("name=\"returnUrl\" value=\"/\"", html, StringComparison.Ordinal); + Assert.Contains("The email address or the password is not right.", + await failed.Content.ReadAsStringAsync(Cancel), StringComparison.Ordinal); - HttpResponseMessage forged = await browser.Browser.PostAsync("/signin", new FormUrlEncodedContent( - new Dictionary<string, string> { ["email"] = "a@example.com", ["password"] = "x" }), Cancel); - Assert.Equal(HttpStatusCode.BadRequest, forged.StatusCode); + HttpResponseMessage forged = await browser.SendAsync(HttpMethod.Post, "/api/v1/oauth/signin", + new { email = "a@example.com", password = "x" }, origin: "https://attacker.example"); + Assert.Equal(HttpStatusCode.Forbidden, forged.StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, + (await browser.SendAsync(HttpMethod.Get, "/api/v1/oauth/session")).StatusCode); - Assert.Equal("/", OAuthAccount.LocalReturnUrl("//attacker.example")); - Assert.Equal("/", OAuthAccount.LocalReturnUrl("/\\attacker.example")); - Assert.Equal("/developers", OAuthAccount.LocalReturnUrl("/developers")); + await browser.RegisterAndSignInAsync("PolicyHolder3", "policy3@example.com"); + JsonElement session = await browser.Browser.GetFromJsonAsync<JsonElement>("/api/v1/oauth/session", Cancel); + Assert.Equal("PolicyHolder3", session.GetProperty("accountName").GetString()); + Assert.Equal(HttpStatusCode.NoContent, + (await browser.SendAsync(HttpMethod.Post, "/api/v1/oauth/signout")).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, + (await browser.SendAsync(HttpMethod.Get, "/api/v1/oauth/session")).StatusCode); } [Fact] @@ -182,30 +256,90 @@ public sealed class OAuthPolicyTests await owner.RegisterAndSignInAsync("PolicyOwner1", "owner1@example.com"); (string clientId, _) = await owner.RegisterApplicationAsync("profile"); - HttpResponseMessage refused = await owner.SubmitAsync("/developers/new", "/developers/new", - new Dictionary<string, string> - { - ["displayName"] = "Plain HTTP", - ["clientType"] = "confidential", - ["redirectUris"] = "http://plain.example/callback" - }); + HttpResponseMessage refused = await owner.SendAsync(HttpMethod.Post, "/api/v1/oauth/applications", new + { + kind = "web", + displayName = "Plain HTTP", + redirectUris = new List<string> { "http://plain.example/callback" } + }); Assert.Equal(HttpStatusCode.BadRequest, refused.StatusCode); Assert.Contains("cannot be registered", await refused.Content.ReadAsStringAsync(Cancel), StringComparison.Ordinal); + HttpResponseMessage noKind = await owner.SendAsync(HttpMethod.Post, "/api/v1/oauth/applications", new + { + kind = "confidential", + displayName = "Old form", + redirectUris = new[] { OAuthTestClient.RedirectUri } + }); + Assert.Equal(HttpStatusCode.BadRequest, noKind.StatusCode); + HttpResponseMessage foreign = await owner.SendAsync(HttpMethod.Post, "/api/v1/oauth/applications", new + { + kind = "web", + displayName = "From elsewhere", + redirectUris = new[] { OAuthTestClient.RedirectUri } + }, origin: "https://attacker.example"); + Assert.Equal(HttpStatusCode.Forbidden, foreign.StatusCode); OAuthTestClient stranger = new(factory); await stranger.RegisterAndSignInAsync("PolicyStranger1", "stranger1@example.com"); Assert.Equal(HttpStatusCode.NotFound, - (await stranger.Browser.GetAsync($"/developers/{clientId}", Cancel)).StatusCode); - HttpResponseMessage deleted = await stranger.SubmitAsync("/", $"/developers/{clientId}/delete", []); - Assert.Equal(HttpStatusCode.NotFound, deleted.StatusCode); - Assert.Equal(HttpStatusCode.OK, (await owner.Browser.GetAsync($"/developers/{clientId}", Cancel)).StatusCode); - - HttpResponseMessage ownDelete = await owner.SubmitAsync($"/developers/{clientId}", - $"/developers/{clientId}/delete", []); - Assert.Equal(HttpStatusCode.Redirect, ownDelete.StatusCode); + (await stranger.SendAsync(HttpMethod.Get, $"/api/v1/oauth/applications/{clientId}")).StatusCode); Assert.Equal(HttpStatusCode.NotFound, - (await owner.Browser.GetAsync($"/developers/{clientId}", Cancel)).StatusCode); + (await stranger.SendAsync(HttpMethod.Delete, $"/api/v1/oauth/applications/{clientId}")).StatusCode); + JsonElement listed = await owner.Console.GetFromJsonAsync<JsonElement>("/api/v1/oauth/applications", Cancel); + JsonElement only = Assert.Single(listed.GetProperty("applications").EnumerateArray()); + Assert.Equal("web", only.GetProperty("kind").GetString()); + Assert.Equal(10, listed.GetProperty("maximum").GetInt32()); + + HttpResponseMessage saved = await owner.SendAsync(HttpMethod.Put, $"/api/v1/oauth/applications/{clientId}", new + { + kind = "desktop", + displayName = "Renamed Client", + redirectUris = new[] { OAuthTestClient.RedirectUri }, + scopes = new List<string> { "profile", "email" } + }); + JsonElement view = await saved.Content.ReadFromJsonAsync<JsonElement>(Cancel); + Assert.True(saved.StatusCode == HttpStatusCode.OK, view.ToString()); + Assert.Equal("Renamed Client", view.GetProperty("displayName").GetString()); + // The type is chosen once, when the token is made. + Assert.Equal("web", view.GetProperty("kind").GetString()); + Assert.Equal(["profile", "email"], view.GetProperty("scopes").EnumerateArray().Select(scope => scope.GetString())); + + Assert.Equal(HttpStatusCode.NoContent, + (await owner.SendAsync(HttpMethod.Delete, $"/api/v1/oauth/applications/{clientId}")).StatusCode); + Assert.Equal(HttpStatusCode.NotFound, + (await owner.SendAsync(HttpMethod.Get, $"/api/v1/oauth/applications/{clientId}")).StatusCode); + } + + [Fact] + public async Task EachTypeGetsItsSecretAndGrants() + { + await using AccountApiFactory factory = new(); + OAuthTestClient owner = new(factory); + await owner.RegisterAndSignInAsync("PolicyOwner3", "owner3@example.com"); + (_, string? web) = await owner.RegisterApplicationAsync("profile"); + (_, string? spa) = await owner.RegisterApplicationAsync("profile", kind: "spa", + redirectUris: "https://app.example/callback"); + (_, string? mobile) = await owner.RegisterApplicationAsync("profile", kind: "mobile", + redirectUris: "com.example.app:/callback"); + (string serviceId, string? service) = await owner.RegisterServiceAsync(); + Assert.NotNull(web); + Assert.Null(spa); + Assert.Null(mobile); + Assert.NotNull(service); + + // A service never reaches the sign-in or consent page. + HttpResponseMessage authorize = await owner.Browser.GetAsync(OAuthTestClient.AuthorizePath(serviceId, "openid", + OAuthTestClient.Pkce().Challenge), Cancel); + Assert.Equal(HttpStatusCode.BadRequest, authorize.StatusCode); + // A web application does not use the client credentials grant; that is what a service token is for. + (string webId, string? webSecret) = await owner.RegisterApplicationAsync("profile"); + (HttpStatusCode status, JsonElement error) = await owner.TokenAsync(new Dictionary<string, string> + { + ["grant_type"] = "client_credentials", ["client_id"] = webId, ["client_secret"] = webSecret! + }); + Assert.Equal(HttpStatusCode.BadRequest, status); + Assert.Equal("unauthorized_client", error.GetProperty("error").GetString()); } [Fact] @@ -214,13 +348,12 @@ public sealed class OAuthPolicyTests await using AccountApiFactory factory = new(); OAuthTestClient owner = new(factory); await owner.RegisterAndSignInAsync("PolicyOwner2", "owner2@example.com"); - (string clientId, string? secret) = await owner.RegisterApplicationAsync("profile", clientCredentials: true); + (string clientId, string? secret) = await owner.RegisterServiceAsync(); - HttpResponseMessage rotated = await owner.SubmitAsync($"/developers/{clientId}", - $"/developers/{clientId}/secret", []); - string html = await rotated.Content.ReadAsStringAsync(Cancel); - string newSecret = System.Web.HttpUtility.HtmlDecode( - System.Text.RegularExpressions.Regex.Matches(html, "<code>([^<]*)</code>")[1].Groups[1].Value); + HttpResponseMessage rotated = await owner.SendAsync(HttpMethod.Post, + $"/api/v1/oauth/applications/{clientId}/secret"); + JsonElement credentials = await rotated.Content.ReadFromJsonAsync<JsonElement>(Cancel); + string newSecret = credentials.GetProperty("clientSecret").GetString()!; Assert.NotEqual(secret, newSecret); (HttpStatusCode old, _) = await owner.TokenAsync(new Dictionary<string, string> @@ -236,17 +369,66 @@ public sealed class OAuthPolicyTests } [Fact] - public async Task PagesAllowTheirStylesheetByDigestAndNoScript() + public async Task TheTokenEndpointAnswersOnlyTheOriginsOfSinglePageApplications() { await using AccountApiFactory factory = new(); + OAuthTestClient owner = new(factory); + await owner.RegisterAndSignInAsync("PolicyOwner4", "owner4@example.com"); + await owner.RegisterApplicationAsync("profile", kind: "spa", redirectUris: "https://app.example/callback"); + // A web application on another origin does not open that origin to the browser. + await owner.RegisterApplicationAsync("profile", redirectUris: "https://server.example/callback"); using HttpClient client = factory.CreateOAuthClient(); - HttpResponseMessage response = await client.GetAsync("/signin", Cancel); - string policy = string.Join(";", response.Headers.GetValues("Content-Security-Policy")); - string digest = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(HtmlPage.Stylesheet))); - Assert.Contains($"style-src 'sha256-{digest}'", policy, StringComparison.Ordinal); - Assert.Contains("default-src 'none'", policy, StringComparison.Ordinal); - Assert.Contains("frame-ancestors 'none'", policy, StringComparison.Ordinal); - Assert.DoesNotContain("script-src", policy, StringComparison.Ordinal); + + async Task<HttpResponseMessage> PreflightAsync(string path, string origin) + { + HttpRequestMessage request = new(HttpMethod.Options, path); + request.Headers.Add("Origin", origin); + request.Headers.Add("Access-Control-Request-Method", "POST"); + return await client.SendAsync(request, Cancel); + } + + HttpResponseMessage allowed = await PreflightAsync("/connect/token", "https://app.example"); + Assert.Equal(HttpStatusCode.NoContent, allowed.StatusCode); + Assert.Equal("https://app.example", allowed.Headers.GetValues("Access-Control-Allow-Origin").Single()); + Assert.False(allowed.Headers.Contains("Access-Control-Allow-Credentials")); + foreach (string origin in new[] + { + "https://server.example", "https://attacker.example", "https://app.example.attacker.example", + "https://app.example/callback", "null" + }) + { + HttpResponseMessage refused = await PreflightAsync("/connect/token", origin); + Assert.False(refused.Headers.Contains("Access-Control-Allow-Origin"), origin); + } + + HttpRequestMessage discovery = new(HttpMethod.Get, "/.well-known/openid-configuration"); + discovery.Headers.Add("Origin", "https://anyone.example"); + HttpResponseMessage document = await client.SendAsync(discovery, Cancel); + Assert.Equal("*", document.Headers.GetValues("Access-Control-Allow-Origin").Single()); + } + + [Fact] + public void ProductionSharesTheAccountSessionWithTheConsoleUnderProgmasoftCom() + { + // The console has no sign-in of its own: it reads the account session, so production shares that cookie with + // progmasoft.com. A cookie with a domain cannot keep the __Host- prefix; it takes __Secure-. + using JsonDocument settings = JsonDocument.Parse(File.ReadAllText( + Path.Combine(AppContext.BaseDirectory, "appsettings.json"))); + JsonElement sessions = settings.RootElement.GetProperty("AccountSessions"); + Assert.Equal("__Secure-ProgmasoftSession", sessions.GetProperty("CookieName").GetString()); + Assert.Equal("progmasoft.com", sessions.GetProperty("CookieDomain").GetString()); + + Progmasoft.Progmaweb.Api.Accounts.SessionService service = new(null!, TimeProvider.System, + Microsoft.Extensions.Options.Options.Create(new Progmasoft.Progmaweb.Api.Accounts.AccountSessionOptions + { + CookieName = "__Secure-ProgmasoftSession", + CookieDomain = "progmasoft.com" + })); + Microsoft.AspNetCore.Http.CookieOptions cookie = service.CreateCookieOptions(DateTimeOffset.UnixEpoch); + Assert.Equal("progmasoft.com", cookie.Domain); + Assert.True(cookie.Secure); + Assert.True(cookie.HttpOnly); + Assert.Equal(Microsoft.AspNetCore.Http.SameSiteMode.Lax, cookie.SameSite); } [Fact] diff --git a/apps/api-tests/OAuthTestClient.cs b/apps/api-tests/OAuthTestClient.cs index 5453027..a176c04 100644 --- a/apps/api-tests/OAuthTestClient.cs +++ b/apps/api-tests/OAuthTestClient.cs @@ -6,18 +6,29 @@ using System.Net.Http.Json; using System.Security.Cryptography; using System.Text; using System.Text.Json; -using System.Text.RegularExpressions; using System.Web; namespace Progmasoft.Progmaweb.Api.Tests; /// <summary>An account holder in a browser on the OAuth host, and a developer's client application.</summary> -/// <remarks>The pages are plain HTML forms; this fills them the way a browser would.</remarks> -internal sealed partial class OAuthTestClient(AccountApiFactory factory) +/// <remarks> +/// The pages of the OAuth host are Next.js pages that call the JSON endpoints under <c>/api/v1/oauth</c> and post +/// the consent decision to <c>/connect/authorize</c>; this makes the same requests, with the <c>Origin</c> header a +/// browser sends. +/// </remarks> +internal sealed class OAuthTestClient(AccountApiFactory factory) { public const string RedirectUri = "https://client.example/callback"; - public HttpClient Browser { get; } = factory.CreateOAuthClient(); + public const string Origin = $"https://{AccountApiFactory.AuthorizeHost}"; + + public const string ConsoleOrigin = $"https://{AccountApiFactory.ConsoleHost}"; + + /// <summary>The browser on the authorize host, where people sign in and decide.</summary> + public HttpClient Browser { get; } = factory.CreateAuthorizeClient(); + + /// <summary>The same browser on the Progmasoft Console, signed in with the Progmasoft account session.</summary> + public HttpClient Console { get; private set; } = factory.CreateConsoleClient(); private static CancellationToken Cancel => TestContext.Current.CancellationToken; @@ -28,68 +39,67 @@ internal sealed partial class OAuthTestClient(AccountApiFactory factory) HttpResponseMessage registered = await accounts.PostAsJsonAsync("/api/v1/accounts/register", new { accountName, email, password = "correct horse battery staple" }, Cancel); Assert.Equal(HttpStatusCode.Created, registered.StatusCode); - - HttpResponseMessage signedIn = await SubmitAsync("/signin", "/signin", new Dictionary<string, string> - { - ["email"] = email, - ["password"] = "correct horse battery staple", - ["returnUrl"] = "/" - }); - Assert.Equal(HttpStatusCode.Redirect, signedIn.StatusCode); + // The console knows the account of the Progmasoft account session; it has no sign-in of its own. + string session = registered.Headers.GetValues("Set-Cookie") + .Single(cookie => cookie.StartsWith("__Host-ProgmasoftSession=", StringComparison.Ordinal)) + .Split(';')[0]; + Console = factory.CreateConsoleClient(session); + + HttpResponseMessage signedIn = await SendAsync(HttpMethod.Post, "/api/v1/oauth/signin", + new { email, password = "correct horse battery staple" }); + Assert.Equal(HttpStatusCode.OK, signedIn.StatusCode); return accountName; } - /// <summary>Registers an application in the developer portal and returns its identifier and secret.</summary> + /// <summary>Makes a token in the developer portal and returns its identifier and secret.</summary> public async Task<(string ClientId, string? Secret)> RegisterApplicationAsync( string scopes = "profile email offline_access viget.packages.read", - bool isPublic = false, - bool clientCredentials = false, + string kind = "web", string redirectUris = RedirectUri) { - List<KeyValuePair<string, string>> fields = - [ - new("displayName", "Example Client"), - new("homepage", "https://client.example"), - new("clientType", isPublic ? "public" : "confidential"), - new("redirectUris", redirectUris), - new("postLogoutRedirectUris", "https://client.example/signed-out") - ]; - fields.AddRange(scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries) - .Select(scope => new KeyValuePair<string, string>("scope", scope))); - if (clientCredentials) + HttpResponseMessage response = await SendAsync(HttpMethod.Post, "/api/v1/oauth/applications", new { - fields.Add(new("allowClientCredentials", "on")); - } - - HttpResponseMessage response = await SubmitAsync("/developers/new", "/developers/new", fields); - string html = await response.Content.ReadAsStringAsync(Cancel); - Assert.True(response.StatusCode == HttpStatusCode.OK, html); - MatchCollection codes = CodePattern().Matches(html); - string clientId = codes[0].Groups[1].Value; + kind, + displayName = "Example Client", + homepage = "https://client.example", + redirectUris = redirectUris.Split('\n', StringSplitOptions.RemoveEmptyEntries), + postLogoutRedirectUris = kind is "web" or "spa" ? new List<string> { "https://client.example/signed-out" } : [], + scopes = scopes.Split(' ', StringSplitOptions.RemoveEmptyEntries) + }); + JsonElement body = await response.Content.ReadFromJsonAsync<JsonElement>(Cancel); + Assert.True(response.StatusCode == HttpStatusCode.Created, body.ToString()); + string clientId = body.GetProperty("application").GetProperty("clientId").GetString()!; Assert.StartsWith("pmo_", clientId, StringComparison.Ordinal); - return (clientId, isPublic ? null : HttpUtility.HtmlDecode(codes[1].Groups[1].Value)); + JsonElement secret = body.GetProperty("clientSecret"); + return (clientId, secret.ValueKind == JsonValueKind.Null ? null : secret.GetString()); } - /// <summary>Loads a page with a form, then posts the form with the given fields and its token.</summary> - public async Task<HttpResponseMessage> SubmitAsync( - string page, - string action, - IEnumerable<KeyValuePair<string, string>> fields) + /// <summary>Makes a service token, which acts as itself with the client credentials grant.</summary> + public Task<(string ClientId, string? Secret)> RegisterServiceAsync() => + RegisterApplicationAsync(scopes: string.Empty, kind: "service", redirectUris: string.Empty); + + /// <summary> + /// Sends a request of a page, with a JSON body when one is given. Applications are managed in the console; every + /// other path belongs to the OAuth host. The origin is the page's own unless another one is given. + /// </summary> + public Task<HttpResponseMessage> SendAsync(HttpMethod method, string path, object? body = null, + string? origin = "", HttpClient? host = null) { - string html = await (await Browser.GetAsync(page, Cancel)).Content.ReadAsStringAsync(Cancel); - return await Browser.PostAsync(action, new FormUrlEncodedContent( - fields.Append(new("form-token", FormToken(html)))), Cancel); - } + host ??= path.StartsWith("/api/v1/oauth/applications", StringComparison.Ordinal) ? Console : Browser; + HttpRequestMessage request = new(method, path); + origin = origin == "" ? (host == Console ? ConsoleOrigin : Origin) : origin; + if (origin is not null) + { + request.Headers.Add("Origin", origin); + } - /// <summary>The token of the first form of a page.</summary> - public static string FormToken(string html) => - HttpUtility.HtmlDecode(TokenPattern().Match(html).Groups[1].Value); + if (body is not null) + { + request.Content = JsonContent.Create(body); + } - /// <summary>Every hidden field of the first form of a page, the token included.</summary> - public static List<KeyValuePair<string, string>> HiddenFields(string html) => HiddenPattern().Matches(html) - .Select(match => new KeyValuePair<string, string>( - HttpUtility.HtmlDecode(match.Groups[1].Value), HttpUtility.HtmlDecode(match.Groups[2].Value))) - .ToList(); + return host.SendAsync(request, Cancel); + } /// <summary>A PKCE verifier and its S256 challenge.</summary> public static (string Verifier, string Challenge) Pkce() @@ -118,24 +128,52 @@ internal sealed partial class OAuthTestClient(AccountApiFactory factory) .Select(pair => $"{pair.Key}={Uri.EscapeDataString(pair.Value!)}")); } - /// <summary>Asks for an authorization and allows it on the consent page; returns the redirection.</summary> - public async Task<Uri> AuthorizeAsync(string clientId, string scope, string challenge, string decision = "allow") + /// <summary> + /// Asks for an authorization and decides on the consent page; returns where the browser is sent at the end. + /// </summary> + public async Task<Uri> AuthorizeAsync(string clientId, string scope, string challenge, string decision = "allow", + string redirectUri = RedirectUri) { - HttpResponseMessage consent = await Browser.GetAsync(AuthorizePath(clientId, scope, challenge), Cancel); - if (consent.StatusCode == HttpStatusCode.Redirect) + HttpResponseMessage response = await Browser.GetAsync( + AuthorizePath(clientId, scope, challenge, redirectUri), Cancel); + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Uri location = response.Headers.Location!; + if (!IsConsentPage(location)) { - return consent.Headers.Location!; + return location; } - string html = await consent.Content.ReadAsStringAsync(Cancel); - Assert.True(consent.StatusCode == HttpStatusCode.OK, html); - List<KeyValuePair<string, string>> fields = HiddenFields(html); - fields.Add(new("decision", decision)); - HttpResponseMessage decided = await Browser.PostAsync("/connect/authorize", new FormUrlEncodedContent(fields), Cancel); + HttpResponseMessage described = await Browser.GetAsync("/api/v1/oauth/consent" + location.OriginalString[ + "/consent".Length..], Cancel); + Assert.True(described.StatusCode == HttpStatusCode.OK, await described.Content.ReadAsStringAsync(Cancel)); + HttpResponseMessage decided = await DecideAsync(location, decision); Assert.Equal(HttpStatusCode.Redirect, decided.StatusCode); return decided.Headers.Location!; } + /// <summary>Whether an address is the consent page of the OAuth host.</summary> + public static bool IsConsentPage(Uri location) => + !location.IsAbsoluteUri && location.OriginalString.StartsWith("/consent?", StringComparison.Ordinal); + + /// <summary>Posts the decision of the consent page back to the authorization endpoint, as its form does.</summary> + public Task<HttpResponseMessage> DecideAsync(Uri consentPage, string decision, string? origin = Origin) + { + var query = HttpUtility.ParseQueryString(consentPage.OriginalString["/consent".Length..]); + List<KeyValuePair<string, string>> fields = + query.AllKeys.Select(key => new KeyValuePair<string, string>(key!, query[key]!)).ToList(); + fields.Add(new("decision", decision)); + HttpRequestMessage request = new(HttpMethod.Post, "/connect/authorize") + { + Content = new FormUrlEncodedContent(fields) + }; + if (origin is not null) + { + request.Headers.Add("Origin", origin); + } + + return Browser.SendAsync(request, Cancel); + } + /// <summary>Posts to the token endpoint as a client would, from outside the browser.</summary> public async Task<(HttpStatusCode Status, JsonElement Body)> TokenAsync(Dictionary<string, string> fields) { @@ -157,13 +195,4 @@ internal sealed partial class OAuthTestClient(AccountApiFactory factory) private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); - - [GeneratedRegex("name=\"form-token\" value=\"([^\"]*)\"")] - private static partial Regex TokenPattern(); - - [GeneratedRegex("<input type=\"hidden\" name=\"([^\"]*)\" value=\"([^\"]*)\">")] - private static partial Regex HiddenPattern(); - - [GeneratedRegex("<code>([^<]*)</code>")] - private static partial Regex CodePattern(); } diff --git a/apps/api/Accounts/AccountEndpoints.cs b/apps/api/Accounts/AccountEndpoints.cs index c5be51c..f15b1be 100644 --- a/apps/api/Accounts/AccountEndpoints.cs +++ b/apps/api/Accounts/AccountEndpoints.cs @@ -192,13 +192,7 @@ internal static class AccountEndpoints { context.Request.Cookies.TryGetValue(sessions.CookieName, out string? token); await sessions.RevokeAsync(token, cancellationToken); - context.Response.Cookies.Delete(sessions.CookieName, new CookieOptions - { - HttpOnly = true, - Path = "/", - SameSite = SameSiteMode.Lax, - Secure = true - }); + context.Response.Cookies.Delete(sessions.CookieName, sessions.CreateCookieOptions(null)); return Results.NoContent(); } @@ -228,7 +222,7 @@ internal static class AccountEndpoints context.Response.Cookies.Append( sessions.CookieName, authentication.SessionToken, - SessionService.CreateCookieOptions(authentication.ExpiresAt)); + sessions.CreateCookieOptions(authentication.ExpiresAt)); /// <summary>Projects a stored account to its public view.</summary> /// <param name="account">The stored account.</param> diff --git a/apps/api/Accounts/SessionService.cs b/apps/api/Accounts/SessionService.cs index 24a81d0..3c20755 100644 --- a/apps/api/Accounts/SessionService.cs +++ b/apps/api/Accounts/SessionService.cs @@ -18,8 +18,18 @@ internal sealed class AccountSessionOptions /// <see cref="MaximumLifetimeHours"/> are clamped to that range. /// </summary> public int LifetimeHours { get; init; } = MaximumLifetimeHours; - /// <summary>Name of the session cookie. The <c>__Host-</c> prefix binds it to this host over HTTPS.</summary> + /// <summary> + /// Name of the session cookie. The <c>__Host-</c> prefix binds it to this host over HTTPS; a cookie shared with + /// <see cref="CookieDomain"/> takes the <c>__Secure-</c> prefix instead, which browsers allow with a domain. + /// </summary> public string CookieName { get; init; } = "__Host-ProgmasoftSession"; + + /// <summary> + /// The domain the session cookie is shared with, such as <c>progmasoft.com</c>, or <see langword="null"/> for a + /// cookie of the account host alone. Production shares it so that the Progmasoft Console on + /// <c>console.progmasoft.com</c> knows the signed-in account without a sign-in of its own. + /// </summary> + public string? CookieDomain { get; init; } } /// <summary>Opens, checks and revokes account sessions.</summary> @@ -99,10 +109,14 @@ internal sealed class SessionService( } /// <summary>Creates the attributes of the session cookie.</summary> - /// <param name="expiresAt">Moment the session expires; the cookie expires with it.</param> - /// <returns>Options for a secure, HTTP-only, same-site cookie on the root path.</returns> - public static CookieOptions CreateCookieOptions(DateTimeOffset expiresAt) => new() + /// <param name="expiresAt"> + /// Moment the session expires; the cookie expires with it. <see langword="null"/> describes the cookie for its + /// deletion. + /// </param> + /// <returns>Options for a secure, HTTP-only, same-site cookie on the root path of the configured domain.</returns> + public CookieOptions CreateCookieOptions(DateTimeOffset? expiresAt) => new() { + Domain = string.IsNullOrEmpty(settings.CookieDomain) ? null : settings.CookieDomain, Expires = expiresAt, HttpOnly = true, IsEssential = true, @@ -111,6 +125,15 @@ internal sealed class SessionService( Secure = true }; + /// <summary>Finds the account of the session cookie of a request.</summary> + /// <param name="context">The request.</param> + /// <returns>The account, or <see langword="null"/> without a valid session.</returns> + public ValueTask<AccountRecord?> AuthenticateAsync(HttpContext context) + { + context.Request.Cookies.TryGetValue(CookieName, out string? token); + return AuthenticateAsync(token, context.RequestAborted); + } + /// <summary>Name of the session cookie.</summary> public string CookieName => settings.CookieName; diff --git a/apps/api/OAuth/Api/AllowedApplicationEndpoints.cs b/apps/api/OAuth/Api/AllowedApplicationEndpoints.cs new file mode 100644 index 0000000..3939c9a --- /dev/null +++ b/apps/api/OAuth/Api/AllowedApplicationEndpoints.cs @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Collections.Immutable; +using OpenIddict.Abstractions; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Api; + +/// <summary>An application the account has allowed.</summary> +/// <param name="AuthorizationId">The identifier of the allowance, used to withdraw it.</param> +/// <param name="DisplayName">The name of the application, or <see langword="null"/> when it was deleted.</param> +/// <param name="Scopes">The scopes the account allowed.</param> +/// <param name="CreatedAt">When the account allowed it.</param> +internal sealed record AllowedApplicationView( + string AuthorizationId, + string? DisplayName, + IReadOnlyList<string> Scopes, + DateTimeOffset? CreatedAt); + +/// <summary>The applications an account has allowed, and withdrawing an allowance.</summary> +internal static class AllowedApplicationEndpoints +{ + /// <summary>Maps the endpoints.</summary> + /// <param name="api">The <c>/api/v1/oauth</c> group.</param> + public static void MapAllowedApplicationEndpoints(this RouteGroupBuilder api) + { + api.MapGet("/allowed", ListAsync); + api.MapDelete("/allowed/{authorizationId}", RevokeAsync).RequireRateLimiting("oauth"); + } + + /// <summary>Lists the applications the signed-in account has allowed.</summary> + private static async Task<IResult> ListAsync( + HttpContext context, + IOpenIddictAuthorizationManager authorizations, + IOpenIddictApplicationManager applications) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + List<AllowedApplicationView> allowed = []; + await foreach (object authorization in authorizations.FindBySubjectAsync(account.Id.ToString(), + context.RequestAborted)) + { + if (!await authorizations.HasStatusAsync(authorization, Statuses.Valid, context.RequestAborted) + || !await authorizations.HasTypeAsync(authorization, AuthorizationTypes.Permanent, context.RequestAborted)) + { + continue; + } + + string? applicationId = await authorizations.GetApplicationIdAsync(authorization, context.RequestAborted); + object? application = applicationId is null + ? null + : await applications.FindByIdAsync(applicationId, context.RequestAborted); + ImmutableArray<string> scopes = await authorizations.GetScopesAsync(authorization, context.RequestAborted); + allowed.Add(new AllowedApplicationView( + (await authorizations.GetIdAsync(authorization, context.RequestAborted))!, + application is null + ? null + : await applications.GetDisplayNameAsync(application, context.RequestAborted), + scopes, + await authorizations.GetCreationDateAsync(authorization, context.RequestAborted))); + } + + return Results.Ok(allowed.OrderByDescending(entry => entry.CreatedAt).ToList()); + } + + /// <summary>Withdraws an allowance and revokes the tokens issued under it.</summary> + private static async Task<IResult> RevokeAsync( + HttpContext context, + IOpenIddictAuthorizationManager authorizations, + IOpenIddictTokenManager tokens, + string authorizationId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + if (!OAuthAccount.IsSameOrigin(context)) + { + return OAuthAccount.ForeignOrigin(); + } + + object? authorization = await authorizations.FindByIdAsync(authorizationId, context.RequestAborted); + // Another account's authorization is treated as absent. + if (authorization is null + || await authorizations.GetSubjectAsync(authorization, context.RequestAborted) != account.Id.ToString()) + { + return Results.NotFound(); + } + + await authorizations.TryRevokeAsync(authorization, context.RequestAborted); + await tokens.RevokeByAuthorizationIdAsync(authorizationId, context.RequestAborted); + return Results.NoContent(); + } +} diff --git a/apps/api/OAuth/Api/ApplicationEndpoints.cs b/apps/api/OAuth/Api/ApplicationEndpoints.cs new file mode 100644 index 0000000..e917554 --- /dev/null +++ b/apps/api/OAuth/Api/ApplicationEndpoints.cs @@ -0,0 +1,240 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Microsoft.Extensions.Options; +using Progmasoft.OAuth.Developers; + +namespace Progmasoft.OAuth.Api; + +/// <summary>What the developer portal submits to make or change a token.</summary> +/// <param name="Kind">The type, as <see cref="ApplicationKinds.Slug"/> writes it; read only when a token is made.</param> +/// <param name="DisplayName">The name the consent page shows.</param> +/// <param name="Homepage">The address of the application's site, or empty.</param> +/// <param name="RedirectUris">The redirection addresses.</param> +/// <param name="PostLogoutRedirectUris">The addresses after sign-out.</param> +/// <param name="Scopes">The scopes the application may request.</param> +internal sealed record ApplicationRequest( + string? Kind, + string? DisplayName, + string? Homepage, + string[]? RedirectUris, + string[]? PostLogoutRedirectUris, + string[]? Scopes) +{ + /// <summary>The submission of an application of a type.</summary> + /// <param name="kind">The type.</param> + /// <returns>The submission, with blank and repeated addresses and scopes left out.</returns> + public ApplicationInput ToInput(ApplicationKind kind) => new( + DisplayName ?? string.Empty, + (Homepage ?? string.Empty).Trim(), + kind, + Clean(RedirectUris), + Clean(PostLogoutRedirectUris), + Clean(Scopes)); + + /// <summary>Each non-blank entry once, trimmed, in the submitted order.</summary> + private static List<string> Clean(string[]? values) => (values ?? []) + .Select(value => value?.Trim() ?? string.Empty) + .Where(value => value.Length != 0) + .Distinct(StringComparer.Ordinal) + .ToList(); +} + +/// <summary>An application as the developer portal shows it.</summary> +/// <param name="ClientId">The client identifier.</param> +/// <param name="DisplayName">The name the consent page shows.</param> +/// <param name="Homepage">The address of the application's site, or empty.</param> +/// <param name="Kind">The type, as <see cref="ApplicationKinds.Slug"/> writes it.</param> +/// <param name="IsPublic">Whether the application has no secret.</param> +/// <param name="RedirectUris">The redirection addresses.</param> +/// <param name="PostLogoutRedirectUris">The addresses after sign-out.</param> +/// <param name="Scopes">The scopes the application may request.</param> +/// <param name="CreatedAt">When the token was made.</param> +internal sealed record ApplicationView( + string ClientId, + string DisplayName, + string Homepage, + string Kind, + bool IsPublic, + IReadOnlyList<string> RedirectUris, + IReadOnlyList<string> PostLogoutRedirectUris, + IReadOnlyList<string> Scopes, + DateTimeOffset CreatedAt) +{ + /// <summary>The view of a registered application.</summary> + public static ApplicationView Of(RegisteredApplication application) => new( + application.ClientId, + application.DisplayName, + application.Homepage, + application.Kind.Slug(), + application.IsPublic, + application.RedirectUris, + application.PostLogoutRedirectUris, + application.Scopes, + application.CreatedAt); +} + +/// <summary>The applications of an account, with how many it may have.</summary> +/// <param name="Applications">The applications, newest first.</param> +/// <param name="Maximum">How many applications an account may have.</param> +internal sealed record ApplicationList(IReadOnlyList<ApplicationView> Applications, int Maximum); + +/// <summary>A token that was just made, or a secret that was just replaced.</summary> +/// <param name="Application">The application.</param> +/// <param name="ClientSecret">The secret, shown this once; <see langword="null"/> for a type without one.</param> +internal sealed record ApplicationCredentials(ApplicationView Application, string? ClientSecret); + +/// <summary> +/// The Progmasoft Cloud Console: any account makes and manages the tokens of its own applications there. +/// </summary> +/// <remarks> +/// Every endpoint acts only on applications the signed-in account owns. An application of another account answers +/// 404, so that client identifiers cannot be probed. +/// </remarks> +internal static class ApplicationEndpoints +{ + /// <summary>Maps the endpoints.</summary> + /// <param name="api">The <c>/api/v1/oauth</c> group.</param> + public static void MapApplicationEndpoints(this RouteGroupBuilder api) + { + api.MapGet("/applications", ListAsync); + api.MapPost("/applications", CreateAsync).RequireRateLimiting("oauth"); + api.MapGet("/applications/{clientId}", ShowAsync); + api.MapPut("/applications/{clientId}", UpdateAsync).RequireRateLimiting("oauth"); + api.MapPost("/applications/{clientId}/secret", RotateAsync).RequireRateLimiting("oauth"); + api.MapDelete("/applications/{clientId}", DeleteAsync).RequireRateLimiting("oauth"); + } + + /// <summary>Lists the applications of the signed-in account.</summary> + private static async Task<IResult> ListAsync( + HttpContext context, + ApplicationRegistry registry, + IOptions<OAuthOptions> options) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + IReadOnlyList<RegisteredApplication> owned = await registry.ListAsync(account.Id, context.RequestAborted); + return Results.Ok(new ApplicationList(owned.Select(ApplicationView.Of).ToList(), + options.Value.MaximumApplicationsPerAccount)); + } + + /// <summary>Makes a token of the submitted type.</summary> + private static async Task<IResult> CreateAsync( + HttpContext context, + ApplicationRequest request, + ApplicationRegistry registry) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + if (!OAuthAccount.IsSameOrigin(context)) + { + return OAuthAccount.ForeignOrigin(); + } + + if (ApplicationKinds.Parse(request.Kind) is not { } kind) + { + return OAuthAccount.Refused(new Dictionary<string, string> { ["kind"] = "Choose an application type." }); + } + + RegistrationResult result = await registry.CreateAsync(account.Id, request.ToInput(kind), context.RequestAborted); + return result.Application is null + ? OAuthAccount.Refused(result.Errors) + : Results.Created($"/api/v1/oauth/applications/{Uri.EscapeDataString(result.Application.ClientId)}", + new ApplicationCredentials(ApplicationView.Of(result.Application), result.ClientSecret)); + } + + /// <summary>Shows an application of the signed-in account.</summary> + private static async Task<IResult> ShowAsync(HttpContext context, ApplicationRegistry registry, string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + return await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted) is { } application + ? Results.Ok(ApplicationView.Of(application)) + : Results.NotFound(); + } + + /// <summary>Saves the settings of an application. Its type, identifier and secret stay.</summary> + private static async Task<IResult> UpdateAsync( + HttpContext context, + ApplicationRequest request, + ApplicationRegistry registry, + string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + if (!OAuthAccount.IsSameOrigin(context)) + { + return OAuthAccount.ForeignOrigin(); + } + + if (await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted) is not { } current) + { + return Results.NotFound(); + } + + IReadOnlyDictionary<string, string>? errors = await registry.UpdateAsync(account.Id, clientId, + request.ToInput(current.Kind), context.RequestAborted); + if (errors is null) + { + return Results.NotFound(); + } + + if (errors.Count != 0) + { + return OAuthAccount.Refused(errors); + } + + RegisteredApplication? saved = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); + return saved is null ? Results.NotFound() : Results.Ok(ApplicationView.Of(saved)); + } + + /// <summary>Replaces the secret of an application and answers the new one once.</summary> + private static async Task<IResult> RotateAsync(HttpContext context, ApplicationRegistry registry, string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + if (!OAuthAccount.IsSameOrigin(context)) + { + return OAuthAccount.ForeignOrigin(); + } + + string? secret = await registry.RotateSecretAsync(account.Id, clientId, context.RequestAborted); + RegisteredApplication? application = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); + return secret is null || application is null + ? Results.NotFound() + : Results.Ok(new ApplicationCredentials(ApplicationView.Of(application), secret)); + } + + /// <summary>Deletes an application with its authorizations and tokens.</summary> + private static async Task<IResult> DeleteAsync(HttpContext context, ApplicationRegistry registry, string clientId) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + if (!OAuthAccount.IsSameOrigin(context)) + { + return OAuthAccount.ForeignOrigin(); + } + + return await registry.DeleteAsync(account.Id, clientId, context.RequestAborted) + ? Results.NoContent() + : Results.NotFound(); + } +} diff --git a/apps/api/OAuth/Api/ConsentEndpoints.cs b/apps/api/OAuth/Api/ConsentEndpoints.cs new file mode 100644 index 0000000..cc3bfb4 --- /dev/null +++ b/apps/api/OAuth/Api/ConsentEndpoints.cs @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using OpenIddict.Abstractions; +using Progmasoft.OAuth.Developers; +using Progmasoft.Progmaweb.Api.Accounts; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Api; + +/// <summary>What the consent page shows about an authorization request.</summary> +/// <param name="ClientId">The client identifier.</param> +/// <param name="DisplayName">The name of the application.</param> +/// <param name="Homepage">The address of the application's site, or empty.</param> +/// <param name="Owner">The account that registered the application, or <see langword="null"/>.</param> +/// <param name="ReturnTo">The origin, or for a native application the scheme, that the account holder returns to.</param> +/// <param name="Scopes">The requested scopes the consent page lists, <c>openid</c> left out.</param> +/// <param name="AccountName">The account that is signed in.</param> +internal sealed record ConsentView( + string ClientId, + string DisplayName, + string Homepage, + string? Owner, + string ReturnTo, + IReadOnlyList<string> Scopes, + string AccountName); + +/// <summary>The data of the consent page.</summary> +/// <remarks> +/// <c>/connect/authorize</c> sends an account holder who has not allowed the request yet to the consent page with +/// the parameters of the request. The page reads what to show here and posts the decision back to +/// <c>/connect/authorize</c>, where OpenIddict checks the whole request again. The checks here only keep the page +/// from showing an application, an address or a scope that the request could not use. +/// </remarks> +internal static class ConsentEndpoints +{ + /// <summary>Maps the endpoint.</summary> + /// <param name="api">The <c>/api/v1/oauth</c> group.</param> + public static void MapConsentEndpoints(this RouteGroupBuilder api) => api.MapGet("/consent", DescribeAsync); + + /// <summary>Describes an authorization request for the consent page.</summary> + private static async Task<IResult> DescribeAsync( + HttpContext context, + IOpenIddictApplicationManager applications, + ApplicationRegistry registry, + AccountService accounts, + string? client_id, + string? redirect_uri, + string? scope) + { + if (await OAuthAccount.CurrentAsync(context) is not { } account) + { + return OAuthAccount.SignInRequired(); + } + + object? application = string.IsNullOrEmpty(client_id) + ? null + : await applications.FindByClientIdAsync(client_id, context.RequestAborted); + if (application is null + || !await applications.HasPermissionAsync(application, Permissions.Endpoints.Authorization, + context.RequestAborted) + || string.IsNullOrEmpty(redirect_uri) + || !Uri.TryCreate(redirect_uri, UriKind.Absolute, out Uri? redirect) + || !await applications.ValidateRedirectUriAsync(application, redirect_uri, context.RequestAborted)) + { + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, + title: "This request does not name a registered application and address."); + } + + List<string> scopes = []; + foreach (string requested in (scope ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries) + .Distinct(StringComparer.Ordinal)) + { + if (requested == Scopes.OpenId) + { + continue; + } + + if (OAuthScopes.Find(requested) is null + || !await applications.HasPermissionAsync(application, Permissions.Prefixes.Scope + requested, + context.RequestAborted)) + { + return Results.Problem(statusCode: StatusCodes.Status400BadRequest, + title: "The application may not request this scope.", detail: requested); + } + + scopes.Add(requested); + } + + string applicationId = (await applications.GetIdAsync(application, context.RequestAborted))!; + Guid? ownerId = await registry.FindOwnerAsync(applicationId, context.RequestAborted); + AccountRecord? owner = ownerId is { } id ? await accounts.FindAsync(id, context.RequestAborted) : null; + RegisteredApplication? registered = ownerId is { } ownerAccount + ? await registry.FindOwnedAsync(ownerAccount, client_id!, context.RequestAborted) + : null; + string returnTo = redirect.Scheme is "http" or "https" + ? redirect.GetLeftPart(UriPartial.Authority) + : redirect.Scheme + ":"; + return Results.Ok(new ConsentView( + client_id!, + await applications.GetDisplayNameAsync(application, context.RequestAborted) ?? client_id!, + registered?.Homepage ?? string.Empty, + owner?.AccountName, + returnTo, + scopes, + account.AccountName)); + } +} diff --git a/apps/api/OAuth/Api/OAuthAccount.cs b/apps/api/OAuth/Api/OAuthAccount.cs new file mode 100644 index 0000000..8a7940c --- /dev/null +++ b/apps/api/OAuth/Api/OAuthAccount.cs @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Options; +using Progmasoft.Progmaweb.Api.Accounts; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Api; + +/// <summary>The account signed in to Progmasoft OAuth, and the origin check of its requests.</summary> +internal static class OAuthAccount +{ + /// <summary>Finds the signed-in account of a request.</summary> + /// <remarks> + /// The Progmasoft Console has no sign-in of its own: it knows the account of the Progmasoft account session, whose + /// cookie production shares with <c>progmasoft.com</c>. The authorize host keeps its own sign-in cookie, so that an + /// authorization never depends on the account site. An account that no longer exists ends that sign-in. + /// </remarks> + /// <param name="context">The request.</param> + /// <returns>The account, or <see langword="null"/> when nobody is signed in.</returns> + public static async Task<AccountRecord?> CurrentAsync(HttpContext context) + { + OAuthOptions options = context.RequestServices.GetRequiredService<IOptions<OAuthOptions>>().Value; + if (string.Equals(context.Request.Host.Host, options.ConsoleHost, StringComparison.OrdinalIgnoreCase)) + { + return await context.RequestServices.GetRequiredService<SessionService>().AuthenticateAsync(context); + } + + AuthenticateResult result = await context.AuthenticateAsync(OAuthRegistration.CookieScheme); + string? subject = result.Principal?.FindFirst(Claims.Subject)?.Value; + if (!result.Succeeded || !Guid.TryParse(subject, out Guid id)) + { + return null; + } + + AccountService accounts = context.RequestServices.GetRequiredService<AccountService>(); + AccountRecord? account = await accounts.FindAsync(id, context.RequestAborted); + if (account is null) + { + await context.SignOutAsync(OAuthRegistration.CookieScheme); + } + + return account; + } + + /// <summary>Whether a request that changes something comes from a page of this host.</summary> + /// <remarks> + /// The pages of the OAuth host are served by the Progmasoft site on the same origin, so every request they make + /// that changes state carries an <c>Origin</c> header naming this host. A request from another site is refused + /// even before the <c>SameSite=Lax</c> cookie would keep it from acting as the account. + /// </remarks> + /// <param name="context">The request.</param> + /// <returns><see langword="true"/> when the request may change state.</returns> + public static bool IsSameOrigin(HttpContext context) + { + string? origin = context.Request.Headers.Origin; + if (string.IsNullOrEmpty(origin)) + { + return context.Request.Headers["Sec-Fetch-Site"] == "same-origin"; + } + + string expected = $"{context.Request.Scheme}://{context.Request.Host.Value}"; + return Uri.TryCreate(origin, UriKind.Absolute, out Uri? uri) + && string.Equals(uri.GetLeftPart(UriPartial.Authority), expected, StringComparison.OrdinalIgnoreCase); + } + + /// <summary>The answer for a request that needs a signed-in account.</summary> + /// <returns>401 with a problem that names the remedy.</returns> + public static IResult SignInRequired() => Results.Problem( + statusCode: StatusCodes.Status401Unauthorized, title: "Sign in to Progmasoft first."); + + /// <summary>The answer for a request from another origin.</summary> + public static IResult ForeignOrigin() => Results.Problem( + statusCode: StatusCodes.Status403Forbidden, title: "The request did not come from this site."); + + /// <summary>A validation problem from the messages of each refused field.</summary> + /// <param name="errors">The messages, keyed by field.</param> + /// <returns>The problem.</returns> + public static IResult Refused(IReadOnlyDictionary<string, string> errors) => Results.ValidationProblem( + errors.ToDictionary(error => error.Key, error => new[] { error.Value })); +} diff --git a/apps/api/OAuth/Api/OAuthCors.cs b/apps/api/OAuth/Api/OAuthCors.cs new file mode 100644 index 0000000..7a6c8b5 --- /dev/null +++ b/apps/api/OAuth/Api/OAuthCors.cs @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using OpenIddict.EntityFrameworkCore.Models; +using Progmasoft.OAuth.Developers; +using Progmasoft.OAuth.Storage; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Api; + +/// <summary>Lets single-page applications call the token endpoints from the browser.</summary> +/// <remarks> +/// <para> +/// A single-page application has no server, so it exchanges its code and refreshes its tokens from the browser, on +/// another origin. The token, revocation and user information endpoints answer an origin only when a single-page +/// application registered a redirection address on it; every other origin gets no CORS header and the browser keeps +/// the response from the page. +/// </para> +/// <para> +/// The discovery documents and the signing keys are public and answer every origin. No response allows credentials: +/// the endpoints authenticate with PKCE and bearer tokens, never with a cookie. +/// </para> +/// </remarks> +/// <param name="next">The next middleware.</param> +internal sealed class OAuthCors(RequestDelegate next) +{ + /// <summary>The endpoints a single-page application calls from the browser.</summary> + private static readonly string[] TokenPaths = ["/connect/token", "/connect/revoke", "/connect/userinfo"]; + + /// <summary>The public documents of the server.</summary> + private static readonly string[] PublicPaths = + ["/.well-known/openid-configuration", "/.well-known/oauth-authorization-server", "/.well-known/jwks"]; + + /// <summary>Adds the CORS headers a request may have, and answers its preflight.</summary> + /// <param name="context">The request.</param> + /// <param name="database">The OAuth tables.</param> + /// <returns>A task that completes when the request has been answered.</returns> + public async Task InvokeAsync(HttpContext context, OAuthDbContext database) + { + string? origin = context.Request.Headers.Origin; + PathString path = context.Request.Path; + bool isPublic = PublicPaths.Any(entry => path.Equals(entry, StringComparison.OrdinalIgnoreCase)); + bool isToken = TokenPaths.Any(entry => path.Equals(entry, StringComparison.OrdinalIgnoreCase)); + if (string.IsNullOrEmpty(origin) || !(isPublic || isToken)) + { + await next(context); + return; + } + + IHeaderDictionary headers = context.Response.Headers; + headers.Vary = "Origin"; + bool allowed = isPublic || await IsSinglePageOriginAsync(database, origin, context.RequestAborted); + if (allowed) + { + headers.AccessControlAllowOrigin = isPublic ? "*" : origin; + } + + if (HttpMethods.IsOptions(context.Request.Method) + && context.Request.Headers.ContainsKey("Access-Control-Request-Method")) + { + if (allowed) + { + headers.AccessControlAllowMethods = "GET, POST"; + headers.AccessControlAllowHeaders = "Authorization, Content-Type"; + headers.AccessControlMaxAge = "600"; + } + + context.Response.StatusCode = StatusCodes.Status204NoContent; + return; + } + + await next(context); + } + + /// <summary>Whether a single-page application registered a redirection address on an origin.</summary> + /// <param name="database">The OAuth tables.</param> + /// <param name="origin">The <c>Origin</c> header of the request.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns><see langword="true"/> when the origin belongs to a single-page application.</returns> + internal static async Task<bool> IsSinglePageOriginAsync( + OAuthDbContext database, + string origin, + CancellationToken cancellationToken) + { + // Only an origin that is exactly scheme, host and port is looked up; anything else is no origin of a page. + if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? uri) || uri.Scheme is not ("https" or "http") + || !string.Equals(uri.GetLeftPart(UriPartial.Authority), origin, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + // The stored addresses are a JSON array of strings, so every address on the origin contains it followed by + // a slash. The candidates are then checked exactly. + string prefix = $"\"{uri.GetLeftPart(UriPartial.Authority)}/"; + List<OpenIddictEntityFrameworkCoreApplication> candidates = await database + .Set<OpenIddictEntityFrameworkCoreApplication>() + .Where(application => application.ClientType == ClientTypes.Public && application.RedirectUris != null + && application.RedirectUris.Contains(prefix)) + .Take(50) + .ToListAsync(cancellationToken); + return candidates.Any(application => IsSinglePage(application) && RedirectsTo(application, uri)); + } + + /// <summary>Whether a stored application is a single-page application.</summary> + private static bool IsSinglePage(OpenIddictEntityFrameworkCoreApplication application) + { + if (string.IsNullOrEmpty(application.Properties)) + { + return false; + } + + using JsonDocument properties = JsonDocument.Parse(application.Properties); + return properties.RootElement.TryGetProperty(ApplicationRegistry.KindProperty, out JsonElement kind) + && kind.ValueKind is JsonValueKind.String + && kind.GetString() == ApplicationKind.SinglePage.Slug(); + } + + /// <summary>Whether a stored application registered a redirection address on an origin.</summary> + private static bool RedirectsTo(OpenIddictEntityFrameworkCoreApplication application, Uri origin) + { + string[] addresses = JsonSerializer.Deserialize<string[]>(application.RedirectUris!) ?? []; + return addresses.Any(address => Uri.TryCreate(address, UriKind.Absolute, out Uri? uri) + && Uri.Compare(uri, origin, UriComponents.SchemeAndServer, + UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0); + } +} diff --git a/apps/api/OAuth/Api/SessionEndpoints.cs b/apps/api/OAuth/Api/SessionEndpoints.cs new file mode 100644 index 0000000..ec574cf --- /dev/null +++ b/apps/api/OAuth/Api/SessionEndpoints.cs @@ -0,0 +1,78 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using System.Security.Claims; +using Microsoft.AspNetCore.Authentication; +using Progmasoft.Progmaweb.Api.Accounts; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Progmasoft.OAuth.Api; + +/// <summary>The email address and password of a sign-in to Progmasoft OAuth.</summary> +/// <param name="Email">The email address as entered.</param> +/// <param name="Password">The password as entered.</param> +internal sealed record SignInRequest(string? Email, string? Password); + +/// <summary>The signed-in account, as the pages of the OAuth host show it.</summary> +/// <param name="AccountName">The account name.</param> +internal sealed record SessionView(string AccountName); + +/// <summary>Signing in to and out of Progmasoft OAuth.</summary> +/// <remarks> +/// The sign-in has its own cookie on the OAuth host and opens no session of the account site: an application that +/// signs people in with Progmasoft never shares a cookie with progmasoft.com. +/// </remarks> +internal static class SessionEndpoints +{ + /// <summary>Maps the endpoints.</summary> + /// <param name="api">The <c>/api/v1/oauth</c> group.</param> + public static void MapSessionEndpoints(this RouteGroupBuilder api) + { + api.MapGet("/session", (Delegate)SessionAsync); + api.MapPost("/signin", SignInAsync).RequireRateLimiting("account-auth"); + api.MapPost("/signout", (Delegate)SignOutAsync); + } + + /// <summary>Answers who is signed in.</summary> + private static async Task<IResult> SessionAsync(HttpContext context) => + await OAuthAccount.CurrentAsync(context) is { } account + ? Results.Ok(new SessionView(account.AccountName)) + : OAuthAccount.SignInRequired(); + + /// <summary>Checks the email address and password and signs the account in.</summary> + private static async Task<IResult> SignInAsync(HttpContext context, SignInRequest request, AccountService accounts) + { + if (!OAuthAccount.IsSameOrigin(context)) + { + return OAuthAccount.ForeignOrigin(); + } + + AccountRecord? account = + await accounts.VerifyPasswordAsync(request.Email, request.Password, context.RequestAborted); + if (account is null) + { + // One message for every failure, as the account API gives: it does not tell registered addresses apart. + return Results.Problem(statusCode: StatusCodes.Status401Unauthorized, + title: "The email address or the password is not right."); + } + + ClaimsIdentity identity = new(OAuthRegistration.CookieScheme, Claims.Name, Claims.Role); + identity.AddClaim(new Claim(Claims.Subject, account.Id.ToString())); + identity.AddClaim(new Claim(Claims.Name, account.AccountName)); + await context.SignInAsync(OAuthRegistration.CookieScheme, new ClaimsPrincipal(identity), + new AuthenticationProperties { IsPersistent = false }); + return Results.Ok(new SessionView(account.AccountName)); + } + + /// <summary>Ends the sign-in.</summary> + private static async Task<IResult> SignOutAsync(HttpContext context) + { + if (!OAuthAccount.IsSameOrigin(context)) + { + return OAuthAccount.ForeignOrigin(); + } + + await context.SignOutAsync(OAuthRegistration.CookieScheme); + return Results.NoContent(); + } +} diff --git a/apps/api/OAuth/Developers/ApplicationKind.cs b/apps/api/OAuth/Developers/ApplicationKind.cs new file mode 100644 index 0000000..8696674 --- /dev/null +++ b/apps/api/OAuth/Developers/ApplicationKind.cs @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +namespace Progmasoft.OAuth.Developers; + +/// <summary>The type of an OAuth 2.1 application, chosen when its token is made.</summary> +/// <remarks> +/// The type decides whether the application keeps a secret, which grants it may use and which redirection addresses +/// it may register. It cannot change later: an application that changes its nature registers a new token. +/// </remarks> +internal enum ApplicationKind +{ + /// <summary>A web application with a server that keeps a client secret.</summary> + Web, + + /// <summary>A browser application without a server; it cannot keep a secret.</summary> + SinglePage, + + /// <summary>A desktop or command-line application on the user's machine; it cannot keep a secret.</summary> + Desktop, + + /// <summary>An iOS or Android application; it cannot keep a secret.</summary> + Mobile, + + /// <summary>A server that acts as itself, not for an account, with the client credentials grant.</summary> + Service +} + +/// <summary>The names, descriptions and rules of each <see cref="ApplicationKind"/>.</summary> +internal static class ApplicationKinds +{ + /// <summary>Every type in the order the portal offers them.</summary> + public static IReadOnlyList<ApplicationKind> All { get; } = + [ + ApplicationKind.Web, + ApplicationKind.SinglePage, + ApplicationKind.Desktop, + ApplicationKind.Mobile, + ApplicationKind.Service + ]; + + /// <summary>The name of a type in addresses and in the stored application.</summary> + /// <param name="kind">The type.</param> + /// <returns>The name, such as <c>web</c> or <c>spa</c>.</returns> + public static string Slug(this ApplicationKind kind) => kind switch + { + ApplicationKind.Web => "web", + ApplicationKind.SinglePage => "spa", + ApplicationKind.Desktop => "desktop", + ApplicationKind.Mobile => "mobile", + _ => "service" + }; + + /// <summary>Finds a type by its name.</summary> + /// <param name="slug">The name, as <see cref="Slug"/> writes it.</param> + /// <returns>The type, or <see langword="null"/> for an unknown name.</returns> + public static ApplicationKind? Parse(string? slug) => + All.Cast<ApplicationKind?>().FirstOrDefault(kind => kind!.Value.Slug() == slug); + + /// <summary>The title of a type in the portal.</summary> + /// <param name="kind">The type.</param> + /// <returns>The title.</returns> + public static string Title(this ApplicationKind kind) => kind switch + { + ApplicationKind.Web => "Web application", + ApplicationKind.SinglePage => "Single-page application", + ApplicationKind.Desktop => "Desktop application", + ApplicationKind.Mobile => "Mobile application", + _ => "Service" + }; + + /// <summary>What a type is for and how it signs in, as the portal explains it.</summary> + /// <param name="kind">The type.</param> + /// <returns>The description.</returns> + public static string Description(this ApplicationKind kind) => kind switch + { + ApplicationKind.Web => + "A site with a server. Signs people in with the authorization code flow and PKCE, and authenticates with " + + "a client secret.", + ApplicationKind.SinglePage => + "A browser application without a server, such as React or Vue. Authorization code flow with PKCE, no " + + "secret; the token endpoint answers its origin.", + ApplicationKind.Desktop => + "A desktop or command-line program. Authorization code flow with PKCE, no secret; returns through a " + + "loopback address or a private-use scheme (RFC 8252).", + ApplicationKind.Mobile => + "An iOS or Android application. Authorization code flow with PKCE, no secret; returns through a " + + "private-use scheme or a claimed https:// address.", + _ => + "A server that acts as itself, not for a person. Client credentials grant with a client secret; no " + + "account scope and no sign-in page." + }; + + /// <summary>Whether a type cannot keep a secret and proves itself with PKCE only.</summary> + /// <param name="kind">The type.</param> + /// <returns><see langword="true"/> for single-page, desktop and mobile applications.</returns> + public static bool IsPublic(this ApplicationKind kind) => + kind is ApplicationKind.SinglePage or ApplicationKind.Desktop or ApplicationKind.Mobile; + + /// <summary>Whether a type signs people in and so registers redirection addresses and scopes.</summary> + /// <param name="kind">The type.</param> + /// <returns><see langword="false"/> for a service only.</returns> + public static bool SignsPeopleIn(this ApplicationKind kind) => kind is not ApplicationKind.Service; +} diff --git a/apps/api/OAuth/Developers/ApplicationPolicy.cs b/apps/api/OAuth/Developers/ApplicationPolicy.cs index 6c5cb1e..09b7605 100644 --- a/apps/api/OAuth/Developers/ApplicationPolicy.cs +++ b/apps/api/OAuth/Developers/ApplicationPolicy.cs @@ -8,29 +8,25 @@ namespace Progmasoft.OAuth.Developers; /// <summary>What a developer submits to register or change an application.</summary> /// <param name="DisplayName">The name the consent page shows.</param> /// <param name="Homepage">The address of the application's site, or empty.</param> -/// <param name="IsPublic"> -/// Whether the application cannot keep a secret: a browser or native application. Such a client has no secret and -/// may not use the client credentials grant. -/// </param> +/// <param name="Kind">The type of the application; it decides the secret, the grants and the address rules.</param> /// <param name="RedirectUris">The addresses the authorization endpoint may send the account holder back to.</param> /// <param name="PostLogoutRedirectUris">The addresses the end-session endpoint may send the account holder back to.</param> /// <param name="Scopes">The scopes the application may request.</param> -/// <param name="AllowClientCredentials">Whether the application may act as itself with the client credentials grant.</param> internal sealed record ApplicationInput( string DisplayName, string Homepage, - bool IsPublic, + ApplicationKind Kind, IReadOnlyList<string> RedirectUris, IReadOnlyList<string> PostLogoutRedirectUris, - IReadOnlyList<string> Scopes, - bool AllowClientCredentials); + IReadOnlyList<string> Scopes); /// <summary>The rules an application registration must follow.</summary> /// <remarks> /// Redirection addresses are compared exactly by the authorization server, so the rules here only decide which -/// addresses may be registered: HTTPS, an <c>http</c> loopback address for software on the developer's own -/// machine, or, for public clients, a private-use scheme of a native application as RFC 8252 describes. A -/// fragment, user information or a wildcard is never accepted. +/// addresses each type may register: web and single-page applications use HTTPS, or an <c>http</c> loopback address +/// during development; desktop applications a loopback address or a private-use scheme, mobile applications a +/// private-use scheme or a claimed HTTPS address, as RFC 8252 describes. A service signs nobody in and registers +/// none. A fragment, user information or a wildcard is never accepted. /// </remarks> internal static class ApplicationPolicy { @@ -61,23 +57,39 @@ internal static class ApplicationPolicy errors["homepage"] = "The homepage must be an https:// address."; } + if (!input.Kind.SignsPeopleIn()) + { + // A service acts as itself: nobody is sent to it after signing in, and no account consents to it. + if (input.RedirectUris.Count != 0 || input.PostLogoutRedirectUris.Count != 0) + { + errors["redirectUris"] = "A service signs nobody in and registers no redirection address."; + } + + if (input.Scopes.Count != 0) + { + errors["scopes"] = "A service acts as itself and requests no account scope."; + } + + return errors; + } + if (input.RedirectUris.Count is 0 or > MaximumRedirectUris) { errors["redirectUris"] = $"Register 1 to {MaximumRedirectUris} redirection addresses, one per line."; } - else if (input.RedirectUris.FirstOrDefault(uri => !IsRedirectionAddress(uri, input.IsPublic)) is { } wrong) + else if (input.RedirectUris.FirstOrDefault(uri => !IsRedirectionAddress(uri, input.Kind)) is { } wrong) { - errors["redirectUris"] = $"{wrong} cannot be registered. {AddressRule(input.IsPublic)}"; + errors["redirectUris"] = $"{wrong} cannot be registered. {AddressRule(input.Kind)}"; } if (input.PostLogoutRedirectUris.Count > MaximumRedirectUris) { errors["postLogoutRedirectUris"] = $"Register at most {MaximumRedirectUris} addresses."; } - else if (input.PostLogoutRedirectUris.FirstOrDefault(uri => !IsRedirectionAddress(uri, input.IsPublic)) is + else if (input.PostLogoutRedirectUris.FirstOrDefault(uri => !IsRedirectionAddress(uri, input.Kind)) is { } wrongLogout) { - errors["postLogoutRedirectUris"] = $"{wrongLogout} cannot be registered. {AddressRule(input.IsPublic)}"; + errors["postLogoutRedirectUris"] = $"{wrongLogout} cannot be registered. {AddressRule(input.Kind)}"; } if (input.Scopes.Any(scope => OAuthScopes.Find(scope) is null)) @@ -85,12 +97,6 @@ internal static class ApplicationPolicy errors["scopes"] = "Choose scopes from the list."; } - if (input.IsPublic && input.AllowClientCredentials) - { - errors["allowClientCredentials"] = - "A public client has no secret and cannot use the client credentials grant."; - } - return errors; } @@ -105,9 +111,14 @@ internal static class ApplicationPolicy .ToList(); /// <summary>The rule for redirection addresses, as the refusal message states it.</summary> - private static string AddressRule(bool isPublic) => isPublic - ? "Use https://, http:// with a loopback address, or a private-use scheme such as com.example.app:/callback." - : "Use https://, or http:// with a loopback address for development."; + private static string AddressRule(ApplicationKind kind) => kind switch + { + ApplicationKind.Desktop => + "Use http:// with a loopback address, or a private-use scheme such as com.example.app:/callback.", + ApplicationKind.Mobile => + "Use a private-use scheme such as com.example.app:/callback, or an https:// address the app claims.", + _ => "Use https://, or http:// with a loopback address for development." + }; /// <summary>Whether text is an absolute <c>https://</c> address without fragment or user information.</summary> private static bool IsHttpsAddress(string text) => @@ -116,11 +127,11 @@ internal static class ApplicationPolicy && uri.Scheme == Uri.UriSchemeHttps && IsClean(uri); - /// <summary>Whether an address may be registered for redirection.</summary> + /// <summary>Whether an address may be registered for redirection by an application of a type.</summary> /// <param name="text">The address.</param> - /// <param name="isPublic">Whether the application is a public client.</param> + /// <param name="kind">The type of the application.</param> /// <returns><see langword="true"/> when the address follows the rules above.</returns> - internal static bool IsRedirectionAddress(string text, bool isPublic) + internal static bool IsRedirectionAddress(string text, ApplicationKind kind) { if (text.Length > MaximumUriLength || text.Contains('*', StringComparison.Ordinal) || !Uri.TryCreate(text, UriKind.Absolute, out Uri? uri) || !IsClean(uri)) @@ -128,23 +139,26 @@ internal static class ApplicationPolicy return false; } - if (uri.Scheme == Uri.UriSchemeHttps) - { - return true; - } - - if (uri.Scheme == Uri.UriSchemeHttp) - { - // RFC 8252 section 7.3: loopback, never a host name that DNS could point elsewhere, except localhost - // during development. - return uri.Host == "localhost" || (IPAddress.TryParse(uri.Host.Trim('[', ']'), out IPAddress? address) - && IPAddress.IsLoopback(address)); - } - + bool https = uri.Scheme == Uri.UriSchemeHttps; + // RFC 8252 section 7.3: loopback, never a host name that DNS could point elsewhere, except localhost + // during development. + bool loopback = uri.Scheme == Uri.UriSchemeHttp + && (uri.Host == "localhost" + || (IPAddress.TryParse(uri.Host.Trim('[', ']'), out IPAddress? address) + && IPAddress.IsLoopback(address))); // RFC 8252 section 7.1: a private-use scheme names the application in reverse DNS order, so it contains a // dot; javascript:, data: and the like are refused by that rule as well as by the explicit list. string[] refused = ["javascript", "data", "file", "vbscript", "about", "blob"]; - return isPublic && uri.Scheme.Contains('.', StringComparison.Ordinal) && !refused.Contains(uri.Scheme); + bool privateUse = !https && uri.Scheme != Uri.UriSchemeHttp + && uri.Scheme.Contains('.', StringComparison.Ordinal) && !refused.Contains(uri.Scheme); + return kind switch + { + ApplicationKind.Web or ApplicationKind.SinglePage => https || loopback, + ApplicationKind.Desktop => loopback || privateUse, + // RFC 8252 section 7.2: a claimed https:// address (Universal Links, App Links) or a private-use scheme. + ApplicationKind.Mobile => https || privateUse, + _ => false + }; } /// <summary>Whether an address has neither a fragment nor user information.</summary> diff --git a/apps/api/OAuth/Developers/ApplicationRegistry.cs b/apps/api/OAuth/Developers/ApplicationRegistry.cs index f768b52..d289113 100644 --- a/apps/api/OAuth/Developers/ApplicationRegistry.cs +++ b/apps/api/OAuth/Developers/ApplicationRegistry.cs @@ -15,22 +15,24 @@ namespace Progmasoft.OAuth.Developers; /// <param name="ClientId">The public identifier of the client.</param> /// <param name="DisplayName">The name the consent page shows.</param> /// <param name="Homepage">The address of the application's site, or empty.</param> -/// <param name="IsPublic">Whether the client has no secret.</param> +/// <param name="Kind">The type chosen when the token was made.</param> /// <param name="RedirectUris">The registered redirection addresses.</param> /// <param name="PostLogoutRedirectUris">The registered end-session addresses.</param> /// <param name="Scopes">The scopes the application may request.</param> -/// <param name="AllowClientCredentials">Whether the client credentials grant is allowed.</param> /// <param name="CreatedAt">When the application was registered.</param> internal sealed record RegisteredApplication( string ClientId, string DisplayName, string Homepage, - bool IsPublic, + ApplicationKind Kind, IReadOnlyList<string> RedirectUris, IReadOnlyList<string> PostLogoutRedirectUris, IReadOnlyList<string> Scopes, - bool AllowClientCredentials, - DateTimeOffset CreatedAt); + DateTimeOffset CreatedAt) +{ + /// <summary>Whether the client has no secret.</summary> + public bool IsPublic => Kind.IsPublic(); +} /// <summary>What registering an application produced.</summary> /// <param name="Application">The application, or <see langword="null"/> when it was refused.</param> @@ -59,6 +61,9 @@ internal sealed class ApplicationRegistry( /// <summary>The property of the application that keeps its homepage.</summary> private const string HomepageProperty = "homepage"; + /// <summary>The property of the application that keeps its <see cref="ApplicationKind"/>.</summary> + internal const string KindProperty = "kind"; + /// <summary>Lists the applications of an account, newest first.</summary> /// <param name="accountId">The owner.</param> /// <param name="cancellationToken">Cancels the operation.</param> @@ -67,10 +72,10 @@ internal sealed class ApplicationRegistry( { List<ApplicationOwner> owned = await database.ApplicationOwners .Where(owner => owner.AccountId == accountId) - .OrderByDescending(owner => owner.CreatedAt) .ToListAsync(cancellationToken); List<RegisteredApplication> result = []; - foreach (ApplicationOwner owner in owned) + // At most MaximumApplicationsPerAccount rows: ordered here, as SQLite cannot order by DateTimeOffset. + foreach (ApplicationOwner owner in owned.OrderByDescending(owner => owner.CreatedAt)) { if (await applications.FindByIdAsync(owner.ApplicationId, cancellationToken) is { } application) { @@ -127,7 +132,7 @@ internal sealed class ApplicationRegistry( } string clientId = "pmo_" + RandomText(15); - string? secret = input.IsPublic ? null : RandomText(32); + string? secret = input.Kind.IsPublic() ? null : RandomText(32); OpenIddictApplicationDescriptor descriptor = new() { ClientId = clientId, @@ -151,7 +156,7 @@ internal sealed class ApplicationRegistry( /// <summary>Changes an application of an account. The client identifier, type and secret stay.</summary> /// <param name="accountId">The account that asks.</param> /// <param name="clientId">The client identifier.</param> - /// <param name="input">The new settings; <see cref="ApplicationInput.IsPublic"/> is ignored.</param> + /// <param name="input">The new settings; <see cref="ApplicationInput.Kind"/> is ignored.</param> /// <param name="cancellationToken">Cancels the operation.</param> /// <returns>The refused fields, empty on success, or <see langword="null"/> when the application is absent.</returns> public async Task<IReadOnlyDictionary<string, string>?> UpdateAsync( @@ -165,8 +170,8 @@ internal sealed class ApplicationRegistry( return null; } - bool isPublic = await applications.HasClientTypeAsync(found.application, ClientTypes.Public, cancellationToken); - ApplicationInput effective = input with { IsPublic = isPublic }; + ApplicationKind kind = await KindOfAsync(found.application, cancellationToken); + ApplicationInput effective = input with { Kind = kind }; Dictionary<string, string> errors = ApplicationPolicy.Validate(effective); if (errors.Count != 0) { @@ -241,12 +246,16 @@ internal sealed class ApplicationRegistry( /// <param name="input">The validated submission.</param> private static void Describe(OpenIddictApplicationDescriptor descriptor, ApplicationInput input) { + ApplicationKind kind = input.Kind; descriptor.DisplayName = input.DisplayName.Trim(); - descriptor.ApplicationType = input.IsPublic ? ApplicationTypes.Native : ApplicationTypes.Web; - descriptor.ClientType = input.IsPublic ? ClientTypes.Public : ClientTypes.Confidential; + descriptor.ApplicationType = kind is ApplicationKind.Desktop or ApplicationKind.Mobile + ? ApplicationTypes.Native + : ApplicationTypes.Web; + descriptor.ClientType = kind.IsPublic() ? ClientTypes.Public : ClientTypes.Confidential; // Every client of Progmasoft OAuth shows the consent page: none is trusted by default. descriptor.ConsentType = ConsentTypes.Explicit; descriptor.Properties[HomepageProperty] = JsonSerializer.SerializeToElement(input.Homepage.Trim()); + descriptor.Properties[KindProperty] = JsonSerializer.SerializeToElement(kind.Slug()); descriptor.RedirectUris.Clear(); foreach (string uri in input.RedirectUris) @@ -261,6 +270,20 @@ internal sealed class ApplicationRegistry( } descriptor.Permissions.Clear(); + descriptor.Requirements.Clear(); + if (!kind.SignsPeopleIn()) + { + // A service only asks the token endpoint for tokens that name itself; it never reaches the sign-in page. + descriptor.Permissions.UnionWith( + [ + Permissions.Endpoints.Token, + Permissions.Endpoints.Revocation, + Permissions.Endpoints.Introspection, + Permissions.GrantTypes.ClientCredentials + ]); + return; + } + descriptor.Permissions.UnionWith( [ Permissions.Endpoints.Authorization, @@ -270,7 +293,7 @@ internal sealed class ApplicationRegistry( Permissions.GrantTypes.AuthorizationCode, Permissions.ResponseTypes.Code ]); - if (!input.IsPublic) + if (!kind.IsPublic()) { descriptor.Permissions.Add(Permissions.Endpoints.Introspection); } @@ -280,20 +303,34 @@ internal sealed class ApplicationRegistry( descriptor.Permissions.Add(Permissions.GrantTypes.RefreshToken); } - if (input.AllowClientCredentials) - { - descriptor.Permissions.Add(Permissions.GrantTypes.ClientCredentials); - } - foreach (string scope in input.Scopes) { descriptor.Permissions.Add(Permissions.Prefixes.Scope + scope); } - descriptor.Requirements.Clear(); descriptor.Requirements.Add(Requirements.Features.ProofKeyForCodeExchange); } + /// <summary>Reads the type of a stored application.</summary> + /// <param name="application">The application.</param> + /// <param name="cancellationToken">Cancels the operation.</param> + /// <returns>The type it was registered with.</returns> + internal async Task<ApplicationKind> KindOfAsync(object application, CancellationToken cancellationToken) + { + var properties = await applications.GetPropertiesAsync(application, cancellationToken); + if (properties.TryGetValue(KindProperty, out JsonElement value) && value.ValueKind is JsonValueKind.String + && ApplicationKinds.Parse(value.GetString()) is { } kind) + { + return kind; + } + + // An application stored before types existed: a public client was a native application, a confidential one + // a web application. + return await applications.HasClientTypeAsync(application, ClientTypes.Public, cancellationToken) + ? ApplicationKind.Desktop + : ApplicationKind.Web; + } + /// <summary>Reads an application into the view of the developer portal.</summary> private async Task<RegisteredApplication> DescribeAsync( object application, @@ -310,7 +347,7 @@ internal sealed class ApplicationRegistry( (await applications.GetClientIdAsync(application, cancellationToken))!, await applications.GetDisplayNameAsync(application, cancellationToken) ?? string.Empty, homepage, - await applications.HasClientTypeAsync(application, ClientTypes.Public, cancellationToken), + await KindOfAsync(application, cancellationToken), (await applications.GetRedirectUrisAsync(application, cancellationToken)).Order(StringComparer.Ordinal).ToList(), (await applications.GetPostLogoutRedirectUrisAsync(application, cancellationToken)) .Order(StringComparer.Ordinal).ToList(), @@ -318,7 +355,6 @@ internal sealed class ApplicationRegistry( .Where(scope => permissions.Contains(Permissions.Prefixes.Scope + scope.Name)) .Select(scope => scope.Name) .ToList(), - permissions.Contains(Permissions.GrantTypes.ClientCredentials), createdAt); } diff --git a/apps/api/OAuth/Developers/DeveloperEndpoints.cs b/apps/api/OAuth/Developers/DeveloperEndpoints.cs deleted file mode 100644 index 460d17b..0000000 --- a/apps/api/OAuth/Developers/DeveloperEndpoints.cs +++ /dev/null @@ -1,300 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> -// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 - -using Microsoft.Extensions.Options; -using Progmasoft.OAuth.Pages; -using Progmasoft.Progmaweb.Api.Accounts; -using static OpenIddict.Abstractions.OpenIddictConstants; - -namespace Progmasoft.OAuth.Developers; - -/// <summary>The developer portal: any account registers and manages its own applications here.</summary> -internal static class DeveloperEndpoints -{ - /// <summary>Maps the portal.</summary> - /// <param name="app">The application.</param> - public static void MapDeveloperPortal(this WebApplication app) - { - app.MapGet("/developers", ListAsync); - app.MapGet("/developers/new", (Delegate)NewAsync); - app.MapPost("/developers/new", CreateAsync).RequireRateLimiting("oauth"); - app.MapGet("/developers/{clientId}", ShowAsync); - app.MapPost("/developers/{clientId}", UpdateAsync).RequireRateLimiting("oauth"); - app.MapPost("/developers/{clientId}/secret", RotateAsync).RequireRateLimiting("oauth"); - app.MapPost("/developers/{clientId}/delete", DeleteAsync).RequireRateLimiting("oauth"); - } - - /// <summary>Lists the applications of the signed-in account.</summary> - private static async Task<IResult> ListAsync( - HttpContext context, - ApplicationRegistry registry, - IOptions<OAuthOptions> options) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - IReadOnlyList<RegisteredApplication> owned = await registry.ListAsync(account.Id, context.RequestAborted); - string list = owned.Count == 0 - ? "<p>You have not registered an application yet.</p>" - : "<ul>" + string.Concat(owned.Select(application => - $"<li><a href=\"/developers/{Uri.EscapeDataString(application.ClientId)}\">" + - $"{HtmlPage.Encode(application.DisplayName)}</a> " + - $"<span class=\"note\">{(application.IsPublic ? "public" : "confidential")} · " + - $"<code>{HtmlPage.Encode(application.ClientId)}</code></span></li>")) + "</ul>"; - string body = - "<h1>Your applications</h1>" + list + - (owned.Count < options.Value.MaximumApplicationsPerAccount - ? "<p><a href=\"/developers/new\">Register an application</a></p>" - : $"<p class=\"note\">An account can register {options.Value.MaximumApplicationsPerAccount} applications.</p>") + - "<h2>Endpoints</h2>" + - "<p class=\"note\">Read the discovery document at <a href=\"/.well-known/openid-configuration\">" + - "/.well-known/openid-configuration</a>. Every client uses the authorization code flow with PKCE (S256); " + - "confidential clients authenticate at the token endpoint with their secret.</p>" + - "<p><a href=\"/\">Back</a></p>"; - return HtmlPage.Render(context, "Your applications", body); - } - - /// <summary>Shows the empty registration form.</summary> - private static async Task<IResult> NewAsync(HttpContext context) - { - if (await OAuthAccount.CurrentAsync(context) is null) - { - return OAuthAccount.SignInFirst(context); - } - - return RenderForm(context, "Register an application", "/developers/new", - new ApplicationInput(string.Empty, string.Empty, false, [], [], [Scopes.Profile], false), - isNew: true, new Dictionary<string, string>()); - } - - /// <summary>Registers an application from the submitted form.</summary> - private static async Task<IResult> CreateAsync(HttpContext context, ApplicationRegistry registry) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - if (!await OAuthAccount.IsGenuineFormAsync(context)) - { - return Results.BadRequest(); - } - - ApplicationInput input = await ReadAsync(context); - RegistrationResult result = await registry.CreateAsync(account.Id, input, context.RequestAborted); - if (result.Application is null) - { - return RenderForm(context, "Register an application", "/developers/new", input, isNew: true, - result.Errors, StatusCodes.Status400BadRequest); - } - - return RenderCredentials(context, "Application registered", result.Application, result.ClientSecret); - } - - /// <summary>Shows an application of the signed-in account with its settings.</summary> - private static async Task<IResult> ShowAsync(HttpContext context, ApplicationRegistry registry, string clientId) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - RegisteredApplication? application = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); - return application is null - ? NotFound(context) - : RenderDetails(context, application, new Dictionary<string, string>(), null); - } - - /// <summary>Saves the submitted settings of an application.</summary> - private static async Task<IResult> UpdateAsync(HttpContext context, ApplicationRegistry registry, string clientId) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - if (!await OAuthAccount.IsGenuineFormAsync(context)) - { - return Results.BadRequest(); - } - - ApplicationInput input = await ReadAsync(context); - IReadOnlyDictionary<string, string>? errors = - await registry.UpdateAsync(account.Id, clientId, input, context.RequestAborted); - RegisteredApplication? application = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); - if (errors is null || application is null) - { - return NotFound(context); - } - - return errors.Count == 0 - ? RenderDetails(context, application, errors, "The application was saved.") - : RenderForm(context, application.DisplayName, $"/developers/{Uri.EscapeDataString(clientId)}", - input with { IsPublic = application.IsPublic }, isNew: false, errors, - StatusCodes.Status400BadRequest); - } - - /// <summary>Replaces the secret of an application and shows the new one once.</summary> - private static async Task<IResult> RotateAsync(HttpContext context, ApplicationRegistry registry, string clientId) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - if (!await OAuthAccount.IsGenuineFormAsync(context)) - { - return Results.BadRequest(); - } - - string? secret = await registry.RotateSecretAsync(account.Id, clientId, context.RequestAborted); - RegisteredApplication? application = await registry.FindOwnedAsync(account.Id, clientId, context.RequestAborted); - return secret is null || application is null - ? NotFound(context) - : RenderCredentials(context, "New client secret", application, secret); - } - - /// <summary>Deletes an application of the signed-in account.</summary> - private static async Task<IResult> DeleteAsync(HttpContext context, ApplicationRegistry registry, string clientId) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - if (!await OAuthAccount.IsGenuineFormAsync(context)) - { - return Results.BadRequest(); - } - - return await registry.DeleteAsync(account.Id, clientId, context.RequestAborted) - ? Results.Redirect("/developers") - : NotFound(context); - } - - /// <summary>Reads the registration form into a submission.</summary> - private static async Task<ApplicationInput> ReadAsync(HttpContext context) - { - IFormCollection form = await context.Request.ReadFormAsync(context.RequestAborted); - return new ApplicationInput( - form["displayName"].ToString(), - form["homepage"].ToString().Trim(), - form["clientType"] == "public", - ApplicationPolicy.Lines(form["redirectUris"]), - ApplicationPolicy.Lines(form["postLogoutRedirectUris"]), - form["scope"].Where(scope => scope is not null).Select(scope => scope!).Distinct(StringComparer.Ordinal).ToList(), - form["allowClientCredentials"] == "on"); - } - - /// <summary>Shows the client identifier and, once, the client secret.</summary> - private static IResult RenderCredentials( - HttpContext context, - string title, - RegisteredApplication application, - string? secret) - { - string body = - $"<h1>{HtmlPage.Encode(title)}</h1>" + - $"<p><strong>{HtmlPage.Encode(application.DisplayName)}</strong></p>" + - $"<label>Client identifier</label><p><code>{HtmlPage.Encode(application.ClientId)}</code></p>" + - (secret is null - ? "<p class=\"note\">A public client has no secret: it proves itself with PKCE only.</p>" - : $"<label>Client secret</label><p><code>{HtmlPage.Encode(secret)}</code></p>" + - "<p class=\"error\">Copy the secret now. It is stored only as a hash and is never shown again; " + - "if it is lost, make a new one.</p>") + - $"<p><a href=\"/developers/{Uri.EscapeDataString(application.ClientId)}\">Go to the application</a></p>"; - return HtmlPage.Render(context, title, body); - } - - /// <summary>Shows an application: its settings form, its secret and its deletion.</summary> - private static IResult RenderDetails( - HttpContext context, - RegisteredApplication application, - IReadOnlyDictionary<string, string> errors, - string? saved) - { - string path = $"/developers/{Uri.EscapeDataString(application.ClientId)}"; - string secretForm = application.IsPublic - ? string.Empty - : HtmlPage.Form(context, path + "/secret", - "<button class=\"secondary\" type=\"submit\">Make a new client secret</button>") + - "<p class=\"note\">The old secret stops working at once.</p>"; - string body = - (saved is null ? string.Empty : $"<p role=\"status\">{HtmlPage.Encode(saved)}</p>") + - FormContent(context, application.DisplayName, path, - new ApplicationInput(application.DisplayName, application.Homepage, application.IsPublic, - application.RedirectUris, application.PostLogoutRedirectUris, application.Scopes, - application.AllowClientCredentials), - isNew: false, errors, application.ClientId) + - "<h2>Secret</h2>" + secretForm + - "<h2>Delete</h2>" + - HtmlPage.Form(context, path + "/delete", - "<p class=\"note\">Deleting the application ends every authorization and token it holds.</p>" + - "<button class=\"danger\" type=\"submit\">Delete the application</button>") + - "<p><a href=\"/developers\">Back</a></p>"; - return HtmlPage.Render(context, application.DisplayName, body); - } - - /// <summary>Shows the settings form as a page.</summary> - private static IResult RenderForm( - HttpContext context, - string title, - string action, - ApplicationInput input, - bool isNew, - IReadOnlyDictionary<string, string> errors, - int statusCode = StatusCodes.Status200OK) => - HtmlPage.Render(context, title, - FormContent(context, title, action, input, isNew, errors, null) + "<p><a href=\"/developers\">Back</a></p>", - statusCode); - - /// <summary>Builds the settings form with the messages of refused fields.</summary> - private static string FormContent( - HttpContext context, - string title, - string action, - ApplicationInput input, - bool isNew, - IReadOnlyDictionary<string, string> errors, - string? clientId) - { - string Error(string field) => HtmlPage.Error(errors.TryGetValue(field, out string? message) ? message : null); - string type = isNew - ? "<label>Type</label>" + - $"<label class=\"check\"><input type=\"radio\" name=\"clientType\" value=\"confidential\"{(input.IsPublic ? "" : " checked")}> " + - "Confidential: a server that keeps a client secret</label>" + - $"<label class=\"check\"><input type=\"radio\" name=\"clientType\" value=\"public\"{(input.IsPublic ? " checked" : "")}> " + - "Public: a browser or native application without a secret</label>" - : $"<p class=\"note\">{(input.IsPublic ? "Public" : "Confidential")} client · " + - $"<code>{HtmlPage.Encode(clientId)}</code></p>"; - string scopes = string.Concat(OAuthScopes.All.Select(scope => - $"<label class=\"check\"><input type=\"checkbox\" name=\"scope\" value=\"{HtmlPage.Encode(scope.Name)}\"" + - $"{(input.Scopes.Contains(scope.Name) ? " checked" : "")}> <code>{HtmlPage.Encode(scope.Name)}</code> " + - $"{HtmlPage.Encode(scope.Consent)}</label>")); - string fields = - type + - "<label for=\"displayName\">Name</label>" + Error("displayName") + - $"<input id=\"displayName\" name=\"displayName\" type=\"text\" required maxlength=\"{ApplicationPolicy.MaximumDisplayNameLength}\" value=\"{HtmlPage.Encode(input.DisplayName)}\">" + - "<label for=\"homepage\">Homepage (optional)</label>" + Error("homepage") + - $"<input id=\"homepage\" name=\"homepage\" type=\"url\" value=\"{HtmlPage.Encode(input.Homepage)}\">" + - "<label for=\"redirectUris\">Redirection addresses, one per line</label>" + Error("redirectUris") + - $"<textarea id=\"redirectUris\" name=\"redirectUris\" required>{HtmlPage.Encode(string.Join('\n', input.RedirectUris))}</textarea>" + - "<label for=\"postLogoutRedirectUris\">Addresses after sign-out (optional)</label>" + - Error("postLogoutRedirectUris") + - $"<textarea id=\"postLogoutRedirectUris\" name=\"postLogoutRedirectUris\">{HtmlPage.Encode(string.Join('\n', input.PostLogoutRedirectUris))}</textarea>" + - "<label>Scopes the application may request</label>" + Error("scopes") + scopes + - "<p class=\"note\"><code>openid</code> is always available.</p>" + - "<label>Service access</label>" + Error("allowClientCredentials") + - $"<label class=\"check\"><input type=\"checkbox\" name=\"allowClientCredentials\"{(input.AllowClientCredentials ? " checked" : "")}> " + - "Allow the client credentials grant (confidential clients only)</label>" + - $"<button type=\"submit\">{(isNew ? "Register" : "Save")}</button>"; - return $"<h1>{HtmlPage.Encode(title)}</h1>" + HtmlPage.Form(context, action, fields); - } - - /// <summary>Answers for an application that is absent or belongs to another account.</summary> - private static IResult NotFound(HttpContext context) => HtmlPage.Render(context, "Not found", - "<h1>Not found</h1><p>No application of yours has this client identifier.</p>" + - "<p><a href=\"/developers\">Back</a></p>", StatusCodes.Status404NotFound); -} diff --git a/apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs b/apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs index 54dd29a..a16a14c 100644 --- a/apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs +++ b/apps/api/OAuth/Endpoints/AuthorizationEndpoints.cs @@ -11,7 +11,7 @@ using OpenIddict.Abstractions; using OpenIddict.Server.AspNetCore; using OpenIddict.Validation.AspNetCore; using Progmasoft.OAuth.Developers; -using Progmasoft.OAuth.Pages; +using Progmasoft.OAuth.Api; using Progmasoft.Progmaweb.Api.Accounts; using static OpenIddict.Abstractions.OpenIddictConstants; @@ -42,9 +42,7 @@ internal static class AuthorizationEndpoints private static async Task<IResult> AuthorizeAsync( HttpContext context, IOpenIddictApplicationManager applications, - IOpenIddictAuthorizationManager authorizations, - ApplicationRegistry registry, - AccountService accounts) + IOpenIddictAuthorizationManager authorizations) { OpenIddictRequest request = context.GetOpenIddictServerRequest() ?? throw new InvalidOperationException("OpenIddict did not pass a request."); @@ -91,9 +89,10 @@ internal static class AuthorizationEndpoints : null; if (!string.IsNullOrEmpty(decision)) { - if (!await OAuthAccount.IsGenuineFormAsync(context)) + // The decision comes from the consent page of this host; a form on another site cannot decide. + if (!OAuthAccount.IsSameOrigin(context)) { - return Results.BadRequest(); + return OAuthAccount.ForeignOrigin(); } if (decision != "allow") @@ -119,47 +118,11 @@ internal static class AuthorizationEndpoints return Forbid(Errors.ConsentRequired, "The account holder has not allowed these scopes yet."); } - return await ConsentPageAsync(context, request, application, applicationId, account, applications, registry, - accounts); - } - - /// <summary>Shows the consent page for an authorization request.</summary> - private static async Task<IResult> ConsentPageAsync( - HttpContext context, - OpenIddictRequest request, - object application, - string applicationId, - AccountRecord account, - IOpenIddictApplicationManager applications, - ApplicationRegistry registry, - AccountService accounts) - { - string name = await applications.GetDisplayNameAsync(application, context.RequestAborted) ?? request.ClientId!; - Guid? ownerId = await registry.FindOwnerAsync(applicationId, context.RequestAborted); - AccountRecord? owner = ownerId is { } id ? await accounts.FindAsync(id, context.RequestAborted) : null; - Uri redirect = new(request.RedirectUri!); - - string grants = "<li>Know which Progmasoft account you use.</li>" + string.Concat(request.GetScopes() - .Select(OAuthScopes.Find) - .Where(scope => scope is not null) - .Select(scope => $"<li>{HtmlPage.Encode(scope!.Consent)}</li>")); - string hidden = string.Concat(request.GetParameters() + // The consent page is a page of the Progmasoft site on this host. It reads what to show from + // /api/v1/oauth/consent and posts the parameters back here with the decision. + return Results.Redirect("/consent" + QueryString.Create(request.GetParameters() .Where(parameter => parameter.Key != Parameters.Prompt) - .Select(parameter => HtmlPage.Hidden(parameter.Key, parameter.Value.ToString()))); - string buttons = - "<div class=\"row\"><button type=\"submit\" name=\"decision\" value=\"allow\">Allow</button>" + - "<button class=\"secondary\" type=\"submit\" name=\"decision\" value=\"deny\">Deny</button></div>"; - string body = - $"<h1>Allow {HtmlPage.Encode(name)}?</h1>" + - $"<p><strong>{HtmlPage.Encode(name)}</strong>" + - (owner is null ? string.Empty : $", registered by <strong>{HtmlPage.Encode(owner.AccountName)}</strong>,") + - " wants to:</p>" + - $"<ul>{grants}</ul>" + - $"<p class=\"note\">You will be sent back to <code>{HtmlPage.Encode(redirect.GetLeftPart(UriPartial.Authority))}</code>. " + - $"Signed in as {HtmlPage.Encode(account.AccountName)}. You can withdraw this at any time under " + - "<a href=\"/account/applications\">Applications you have allowed</a>.</p>" + - HtmlPage.Form(context, "/connect/authorize", hidden + buttons); - return HtmlPage.Render(context, "Allow access", body); + .Select(parameter => new KeyValuePair<string, string?>(parameter.Key, parameter.Value.ToString())))); } /// <summary>Answers the token endpoint for the authorization code, refresh token and client credentials grants.</summary> diff --git a/apps/api/OAuth/OAuthEndpoints.cs b/apps/api/OAuth/OAuthEndpoints.cs index fa6409c..c4419b1 100644 --- a/apps/api/OAuth/OAuthEndpoints.cs +++ b/apps/api/OAuth/OAuthEndpoints.cs @@ -1,22 +1,27 @@ // SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> // SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 -using Progmasoft.OAuth.Developers; +using Progmasoft.OAuth.Api; using Progmasoft.OAuth.Endpoints; -using Progmasoft.OAuth.Pages; namespace Progmasoft.OAuth; -/// <summary>Maps every page and endpoint of Progmasoft OAuth.</summary> +/// <summary>Maps every endpoint of Progmasoft OAuth.</summary> +/// <remarks> +/// The pages of the OAuth host (sign-in, consent, the developer portal and the allowed applications) belong to the +/// Progmasoft site, which runs on Next.js; they call the JSON endpoints under <c>/api/v1/oauth</c>. +/// </remarks> internal static class OAuthEndpoints { - /// <summary>Maps the pages and endpoints. <see cref="OAuthHostFilter"/> keeps them on the OAuth host.</summary> + /// <summary>Maps the endpoints. <see cref="OAuthHostFilter"/> keeps them on the OAuth host.</summary> /// <param name="app">The application.</param> public static void MapProgmasoftOAuth(this WebApplication app) { - app.MapSignInPages(); app.MapAuthorizationEndpoints(); - app.MapDeveloperPortal(); - app.MapAllowedApplications(); + RouteGroupBuilder api = app.MapGroup("/api/v1/oauth"); + api.MapSessionEndpoints(); + api.MapApplicationEndpoints(); + api.MapAllowedApplicationEndpoints(); + api.MapConsentEndpoints(); } } diff --git a/apps/api/OAuth/OAuthHostFilter.cs b/apps/api/OAuth/OAuthHostFilter.cs index ce9cbfc..280de94 100644 --- a/apps/api/OAuth/OAuthHostFilter.cs +++ b/apps/api/OAuth/OAuthHostFilter.cs @@ -5,44 +5,74 @@ using Microsoft.Extensions.Options; namespace Progmasoft.OAuth; -/// <summary>Keeps Progmasoft OAuth on its own host, and the account API off it.</summary> +/// <summary>Keeps Progmasoft OAuth and the Progmasoft Console on their own hosts, and the account API off them.</summary> /// <remarks> /// <para> -/// The account API and the OAuth provider run in one process. OpenIddict answers its endpoints on any host, so this -/// filter, placed before authentication, answers 404 for an OAuth path on another host: tokens are only ever issued -/// under the issuer's own name. On the OAuth host it answers 404 for everything but the OAuth paths and -/// <c>/health</c>, so that the account API, whose cookies belong to the account site, is not reachable there. +/// The account API, the OAuth provider and the console run in one process. OpenIddict answers its endpoints on any +/// host, so this filter, placed before authentication, answers 404 for a path on the wrong host: tokens are only ever +/// issued under the issuer's own name, and applications are only managed in the console. +/// </para> +/// <para> +/// The issuer host serves the discovery documents, the key set and the endpoints clients call directly. The authorize +/// host serves the authorization and end session endpoints, sign-in, consent and the allowed applications. The +/// console host serves the applications and the account of the Progmasoft account session. All three serve +/// <c>/health</c> and nothing of the account API, whose cookies belong to the account site. Nginx routes the hosts +/// the same way; this keeps the rule when a request reaches the process directly. /// </para> -/// <para>Nginx routes the hosts the same way; this keeps the rule when a request reaches the process directly.</para> /// </remarks> /// <param name="next">The next middleware.</param> -/// <param name="options">The settings that name the OAuth host.</param> +/// <param name="options">The settings that name the hosts.</param> internal sealed class OAuthHostFilter(RequestDelegate next, IOptions<OAuthOptions> options) { - /// <summary>Paths that only the OAuth host serves; a path is matched with its sub-paths.</summary> - private static readonly string[] OAuthPaths = + /// <summary>Paths only the authorize host serves; a path is matched with its sub-paths.</summary> + private static readonly string[] AuthorizePaths = + [ + "/connect/authorize", + "/connect/logout", + "/api/v1/oauth/consent", + "/api/v1/oauth/allowed", + "/api/v1/oauth/signin", + "/api/v1/oauth/signout" + ]; + + /// <summary>Paths only the issuer host serves, the authorize paths under <c>/connect</c> excepted.</summary> + private static readonly string[] IssuerPaths = [ "/connect", "/.well-known/openid-configuration", "/.well-known/oauth-authorization-server", - "/.well-known/jwks", - "/signin", - "/signout", - "/developers", - "/account/applications" + "/.well-known/jwks" ]; + /// <summary>Paths only the console host serves.</summary> + private static readonly string[] ConsolePaths = ["/api/v1/oauth/applications"]; + + /// <summary> + /// Paths the authorize and console hosts serve. The authorize host answers with its own sign-in, the console + /// with the Progmasoft account session; the console has no sign-in of its own. + /// </summary> + private static readonly string[] SharedPaths = ["/api/v1/oauth/session"]; + /// <summary>Answers 404 for a request on the wrong host, and passes the others on.</summary> /// <param name="context">The request.</param> /// <returns>A task that completes when the request has been answered.</returns> public Task InvokeAsync(HttpContext context) { PathString path = context.Request.Path; - bool onOAuthHost = string.Equals(context.Request.Host.Host, options.Value.Host, StringComparison.OrdinalIgnoreCase); - bool isOAuthPath = OAuthPaths.Any(prefix => path.StartsWithSegments(prefix, StringComparison.OrdinalIgnoreCase)); - bool allowed = onOAuthHost - ? isOAuthPath || path == "/" || path.StartsWithSegments("/health", StringComparison.OrdinalIgnoreCase) - : !isOAuthPath; + string host = context.Request.Host.Host; + OAuthOptions settings = options.Value; + bool isAuthorizePath = Matches(path, AuthorizePaths); + bool isIssuerPath = !isAuthorizePath && Matches(path, IssuerPaths); + bool isConsolePath = Matches(path, ConsolePaths); + bool isSharedPath = Matches(path, SharedPaths); + bool isHealth = path.StartsWithSegments("/health", StringComparison.OrdinalIgnoreCase); + bool allowed = Is(host, settings.Host) + ? isIssuerPath || isHealth + : Is(host, settings.AuthorizeHost) + ? isAuthorizePath || isSharedPath || isHealth + : Is(host, settings.ConsoleHost) + ? isConsolePath || isSharedPath || isHealth + : !(isAuthorizePath || isIssuerPath || isConsolePath || isSharedPath); if (allowed) { return next(context); @@ -51,4 +81,12 @@ internal sealed class OAuthHostFilter(RequestDelegate next, IOptions<OAuthOption context.Response.StatusCode = StatusCodes.Status404NotFound; return Task.CompletedTask; } + + /// <summary>Whether a host name is the given one.</summary> + private static bool Is(string host, string expected) => + string.Equals(host, expected, StringComparison.OrdinalIgnoreCase); + + /// <summary>Whether a path is one of the given paths or below one.</summary> + private static bool Matches(PathString path, string[] prefixes) => + prefixes.Any(prefix => path.StartsWithSegments(prefix, StringComparison.OrdinalIgnoreCase)); } diff --git a/apps/api/OAuth/OAuthOptions.cs b/apps/api/OAuth/OAuthOptions.cs index 7e32712..f5b000a 100644 --- a/apps/api/OAuth/OAuthOptions.cs +++ b/apps/api/OAuth/OAuthOptions.cs @@ -9,9 +9,24 @@ internal sealed class OAuthOptions /// <summary>The configuration section of these settings.</summary> public const string SectionName = "OAuth"; - /// <summary>The host name Progmasoft OAuth answers on; the issuer is <c>https://{Host}/</c>.</summary> + /// <summary> + /// The host name of the issuer, <c>https://{Host}/</c>: the discovery documents, the key set and the endpoints + /// clients call directly (token, user information, revocation, introspection). + /// </summary> public string Host { get; set; } = "credentials.progmasoft.com"; + /// <summary> + /// The host name of the pages people see: the authorization endpoint with its sign-in and consent screen, the end + /// session endpoint, and the applications an account has allowed. + /// </summary> + public string AuthorizeHost { get; set; } = "authorize.progmasoft.com"; + + /// <summary> + /// The host name of the Progmasoft Cloud Console, where developers make and manage the tokens of their + /// applications. It has its own sign-in; the protocol endpoints stay on <see cref="Host"/>. + /// </summary> + public string ConsoleHost { get; set; } = "console.progmasoft.com"; + /// <summary> /// PEM file with the RSA private key that signs identity and access tokens. Required in production; other /// environments use a key that lives as long as the process. diff --git a/apps/api/OAuth/OAuthRegistration.cs b/apps/api/OAuth/OAuthRegistration.cs index 4d2ac65..ead8739 100644 --- a/apps/api/OAuth/OAuthRegistration.cs +++ b/apps/api/OAuth/OAuthRegistration.cs @@ -78,10 +78,12 @@ internal static class OAuthRegistration .AddServer(server => { server.SetIssuer(settings.Issuer); - server.SetAuthorizationEndpointUris("connect/authorize") + // The endpoints a browser visits live on the authorize host, with the sign-in and consent pages; + // the discovery document names them with that host. The others stay under the issuer. + server.SetAuthorizationEndpointUris($"https://{settings.AuthorizeHost}/connect/authorize") .SetTokenEndpointUris("connect/token") .SetUserInfoEndpointUris("connect/userinfo") - .SetEndSessionEndpointUris("connect/logout") + .SetEndSessionEndpointUris($"https://{settings.AuthorizeHost}/connect/logout") .SetRevocationEndpointUris("connect/revoke") .SetIntrospectionEndpointUris("connect/introspect"); @@ -133,17 +135,10 @@ internal static class OAuthRegistration options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.ExpireTimeSpan = SignInLifetime; options.SlidingExpiration = false; + // The sign-in page is a page of the Progmasoft site (Next.js) on the same host. options.LoginPath = "/signin"; - options.LogoutPath = "/signout"; options.AccessDeniedPath = "/signin"; }); - services.AddAntiforgery(options => - { - options.Cookie.Name = "__Host-ProgmasoftOAuthForm"; - options.Cookie.SecurePolicy = CookieSecurePolicy.Always; - options.Cookie.SameSite = SameSiteMode.Strict; - options.FormFieldName = "form-token"; - }); services.AddScoped<ApplicationRegistry>(); return settings; } diff --git a/apps/api/OAuth/Pages/AllowedApplicationsEndpoints.cs b/apps/api/OAuth/Pages/AllowedApplicationsEndpoints.cs deleted file mode 100644 index 19dec69..0000000 --- a/apps/api/OAuth/Pages/AllowedApplicationsEndpoints.cs +++ /dev/null @@ -1,95 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> -// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 - -using System.Collections.Immutable; -using OpenIddict.Abstractions; -using static OpenIddict.Abstractions.OpenIddictConstants; - -namespace Progmasoft.OAuth.Pages; - -/// <summary>The applications an account has allowed, and withdrawing an allowance.</summary> -internal static class AllowedApplicationsEndpoints -{ - /// <summary>Maps the pages.</summary> - /// <param name="app">The application.</param> - public static void MapAllowedApplications(this WebApplication app) - { - app.MapGet("/account/applications", ListAsync); - app.MapPost("/account/applications/{authorizationId}/revoke", RevokeAsync); - } - - /// <summary>Lists the applications the signed-in account has allowed.</summary> - private static async Task<IResult> ListAsync( - HttpContext context, - IOpenIddictAuthorizationManager authorizations, - IOpenIddictApplicationManager applications) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - List<string> rows = []; - await foreach (object authorization in authorizations.FindBySubjectAsync(account.Id.ToString(), - context.RequestAborted)) - { - if (!await authorizations.HasStatusAsync(authorization, Statuses.Valid, context.RequestAborted) - || !await authorizations.HasTypeAsync(authorization, AuthorizationTypes.Permanent, context.RequestAborted)) - { - continue; - } - - string? applicationId = await authorizations.GetApplicationIdAsync(authorization, context.RequestAborted); - object? application = applicationId is null - ? null - : await applications.FindByIdAsync(applicationId, context.RequestAborted); - string name = application is null - ? "A deleted application" - : await applications.GetDisplayNameAsync(application, context.RequestAborted) ?? "An application"; - ImmutableArray<string> scopes = await authorizations.GetScopesAsync(authorization, context.RequestAborted); - string id = (await authorizations.GetIdAsync(authorization, context.RequestAborted))!; - DateTimeOffset? created = await authorizations.GetCreationDateAsync(authorization, context.RequestAborted); - string grants = string.Join(", ", scopes.Select(scope => $"<code>{HtmlPage.Encode(scope)}</code>")); - rows.Add( - $"<li><strong>{HtmlPage.Encode(name)}</strong> " + - $"<span class=\"note\">since {created:yyyy-MM-dd}</span><br>{grants}" + - HtmlPage.Form(context, $"/account/applications/{Uri.EscapeDataString(id)}/revoke", - "<button class=\"secondary\" type=\"submit\">Withdraw</button>") + "</li>"); - } - - string body = "<h1>Applications you have allowed</h1>" + - (rows.Count == 0 ? "<p>You have not allowed any application.</p>" : $"<ul>{string.Concat(rows)}</ul>") + - "<p class=\"note\">Withdrawing ends the application's access tokens and refresh tokens at once; " + - "it will have to ask you again.</p><p><a href=\"/\">Back</a></p>"; - return HtmlPage.Render(context, "Allowed applications", body); - } - - /// <summary>Withdraws an allowance and revokes the tokens issued under it.</summary> - private static async Task<IResult> RevokeAsync( - HttpContext context, - IOpenIddictAuthorizationManager authorizations, - IOpenIddictTokenManager tokens, - string authorizationId) - { - if (await OAuthAccount.CurrentAsync(context) is not { } account) - { - return OAuthAccount.SignInFirst(context); - } - - if (!await OAuthAccount.IsGenuineFormAsync(context)) - { - return Results.BadRequest(); - } - - object? authorization = await authorizations.FindByIdAsync(authorizationId, context.RequestAborted); - // Another account's authorization is treated as absent. - if (authorization is not null - && await authorizations.GetSubjectAsync(authorization, context.RequestAborted) == account.Id.ToString()) - { - await authorizations.TryRevokeAsync(authorization, context.RequestAborted); - await tokens.RevokeByAuthorizationIdAsync(authorizationId, context.RequestAborted); - } - - return Results.Redirect("/account/applications"); - } -} diff --git a/apps/api/OAuth/Pages/HtmlPage.cs b/apps/api/OAuth/Pages/HtmlPage.cs deleted file mode 100644 index a471f80..0000000 --- a/apps/api/OAuth/Pages/HtmlPage.cs +++ /dev/null @@ -1,95 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> -// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 - -using System.Security.Cryptography; -using System.Text; -using System.Text.Encodings.Web; -using Microsoft.AspNetCore.Antiforgery; - -namespace Progmasoft.OAuth.Pages; - -/// <summary>Renders the pages of Progmasoft OAuth: plain HTML forms, no script.</summary> -/// <remarks> -/// The pages need no JavaScript, so the content security policy allows none. The one stylesheet is inline and -/// allowed by its digest. The policy has no <c>form-action</c>: a form here posts to this host, and the -/// redirection that follows a consent goes to the address the application registered, which browsers would check -/// against <c>form-action</c> as well. -/// </remarks> -internal static class HtmlPage -{ - /// <summary>The stylesheet of every page.</summary> - internal const string Stylesheet = - "body{margin:0;font:16px/1.5 system-ui,-apple-system,'Segoe UI',sans-serif;color:#1d1d1f;background:#f6f7f9}" + - "main{max-width:34rem;margin:3rem auto;padding:2rem;background:#fff;border:1px solid #dcdfe4;border-radius:12px}" + - "h1{font-size:1.5rem;margin:0 0 1rem}h2{font-size:1.1rem;margin:1.5rem 0 .5rem}" + - "label{display:block;margin:.75rem 0 .25rem;font-weight:600}" + - "input[type=text],input[type=email],input[type=password],input[type=url],textarea{box-sizing:border-box;" + - "width:100%;padding:.55rem .65rem;border:1px solid #b8bec8;border-radius:8px;font:inherit}" + - "textarea{min-height:5rem}button{margin-top:1rem;padding:.55rem 1rem;border:0;border-radius:8px;" + - "background:#1f4fd6;color:#fff;font:inherit;cursor:pointer}button.secondary{background:#e5e8ee;color:#1d1d1f}" + - "button.danger{background:#b3261e}.error{color:#b3261e}.note{color:#5b6270;font-size:.9rem}" + - "code{font:14px ui-monospace,SFMono-Regular,Consolas,monospace;background:#eef0f4;padding:.1rem .3rem;" + - "border-radius:4px;word-break:break-all}ul{padding-left:1.2rem}a{color:#1f4fd6}" + - ".row{display:flex;gap:.5rem;flex-wrap:wrap}.check{font-weight:400}" + - "@media(prefers-color-scheme:dark){body{background:#121316;color:#e8e9ec}main{background:#1b1d22;" + - "border-color:#30343c}input[type=text],input[type=email],input[type=password],input[type=url],textarea" + - "{background:#121316;color:#e8e9ec;border-color:#454a54}code{background:#262a31}a{color:#8fb0ff}" + - "button.secondary{background:#30343c;color:#e8e9ec}.note{color:#a3a9b5}}"; - - /// <summary>The content security policy source that allows <see cref="Stylesheet"/>.</summary> - internal static readonly string StylesheetSource = - "'sha256-" + Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Stylesheet))) + "'"; - - /// <summary>Encodes text for an HTML element or attribute.</summary> - /// <param name="text">The text.</param> - /// <returns>The encoded text.</returns> - public static string Encode(string? text) => HtmlEncoder.Default.Encode(text ?? string.Empty); - - /// <summary>Answers with a page.</summary> - /// <param name="context">The request.</param> - /// <param name="title">The title of the page.</param> - /// <param name="body">The content of the page, already encoded.</param> - /// <param name="statusCode">The status of the response.</param> - /// <returns>The result.</returns> - public static IResult Render(HttpContext context, string title, string body, int statusCode = 200) - { - IHeaderDictionary headers = context.Response.Headers; - headers.ContentSecurityPolicy = - $"default-src 'none'; style-src {StylesheetSource}; img-src 'self'; frame-ancestors 'none'; base-uri 'none'"; - headers.CacheControl = "no-store"; - string html = - "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">" + - "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" + - "<meta name=\"robots\" content=\"noindex\">" + - $"<title>{Encode(title)} · Progmasoft</title><style>{Stylesheet}</style></head>" + - $"<body><main>{body}</main></body></html>"; - return Results.Content(html, "text/html; charset=utf-8", Encoding.UTF8, statusCode); - } - - /// <summary>A form that posts to this host, with the token that proves it was served here.</summary> - /// <param name="context">The request that renders the form.</param> - /// <param name="action">The path the form posts to.</param> - /// <param name="content">The fields and buttons, already encoded.</param> - /// <returns>The form.</returns> - public static string Form(HttpContext context, string action, string content) - { - IAntiforgery antiforgery = context.RequestServices.GetRequiredService<IAntiforgery>(); - AntiforgeryTokenSet tokens = antiforgery.GetAndStoreTokens(context); - return $"<form method=\"post\" action=\"{Encode(action)}\">" + - $"<input type=\"hidden\" name=\"{Encode(tokens.FormFieldName)}\" value=\"{Encode(tokens.RequestToken)}\">" + - content + "</form>"; - } - - /// <summary>A hidden field.</summary> - /// <param name="name">The name of the field.</param> - /// <param name="value">The value of the field.</param> - /// <returns>The field.</returns> - public static string Hidden(string name, string? value) => - $"<input type=\"hidden\" name=\"{Encode(name)}\" value=\"{Encode(value)}\">"; - - /// <summary>A paragraph that reports an error, or nothing.</summary> - /// <param name="message">The message, or <see langword="null"/>.</param> - /// <returns>The paragraph.</returns> - public static string Error(string? message) => - string.IsNullOrEmpty(message) ? string.Empty : $"<p class=\"error\" role=\"alert\">{Encode(message)}</p>"; -} diff --git a/apps/api/OAuth/Pages/SignInEndpoints.cs b/apps/api/OAuth/Pages/SignInEndpoints.cs deleted file mode 100644 index 3a6ea14..0000000 --- a/apps/api/OAuth/Pages/SignInEndpoints.cs +++ /dev/null @@ -1,167 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> -// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 - -using System.Security.Claims; -using Microsoft.AspNetCore.Antiforgery; -using Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.Options; -using Progmasoft.Progmaweb.Api.Accounts; -using static OpenIddict.Abstractions.OpenIddictConstants; - -namespace Progmasoft.OAuth.Pages; - -/// <summary>The account signed in to Progmasoft OAuth.</summary> -internal static class OAuthAccount -{ - /// <summary>Finds the account of the sign-in cookie.</summary> - /// <remarks>An account that no longer exists ends the sign-in.</remarks> - /// <param name="context">The request.</param> - /// <returns>The account, or <see langword="null"/> when nobody is signed in.</returns> - public static async Task<AccountRecord?> CurrentAsync(HttpContext context) - { - AuthenticateResult result = await context.AuthenticateAsync(OAuthRegistration.CookieScheme); - string? subject = result.Principal?.FindFirst(Claims.Subject)?.Value; - if (!result.Succeeded || !Guid.TryParse(subject, out Guid id)) - { - return null; - } - - AccountService accounts = context.RequestServices.GetRequiredService<AccountService>(); - AccountRecord? account = await accounts.FindAsync(id, context.RequestAborted); - if (account is null) - { - await context.SignOutAsync(OAuthRegistration.CookieScheme); - } - - return account; - } - - /// <summary>Sends a visitor to the sign-in page and back to where they were.</summary> - /// <param name="context">The request.</param> - /// <returns>The redirection.</returns> - public static IResult SignInFirst(HttpContext context) => Results.Redirect( - "/signin?ReturnUrl=" + Uri.EscapeDataString(context.Request.Path + context.Request.QueryString)); - - /// <summary>Whether a form carries the token this host served with it.</summary> - /// <param name="context">The request.</param> - /// <returns><see langword="true"/> when the form is genuine.</returns> - public static Task<bool> IsGenuineFormAsync(HttpContext context) => - context.RequestServices.GetRequiredService<IAntiforgery>().IsRequestValidAsync(context); - - /// <summary>A return address that stays on this host.</summary> - /// <param name="returnUrl">The requested address.</param> - /// <returns>The address, or <c>/</c> when it would leave the host.</returns> - public static string LocalReturnUrl(string? returnUrl) => - !string.IsNullOrEmpty(returnUrl) && returnUrl[0] == '/' && (returnUrl.Length == 1 || - (returnUrl[1] != '/' && returnUrl[1] != '\\')) - ? returnUrl - : "/"; -} - -/// <summary>The home page, the sign-in page and signing out.</summary> -internal static class SignInEndpoints -{ - /// <summary>Maps the pages.</summary> - /// <param name="app">The application.</param> - public static void MapSignInPages(this WebApplication app) - { - app.MapGet("/", (Delegate)HomeAsync); - app.MapGet("/signin", SignInPage); - app.MapPost("/signin", SignInAsync).RequireRateLimiting("account-auth"); - app.MapPost("/signout", (Delegate)SignOutAsync); - } - - /// <summary>Shows the home page of the OAuth host.</summary> - private static async Task<IResult> HomeAsync(HttpContext context) - { - AccountRecord? account = await OAuthAccount.CurrentAsync(context); - string body = "<h1>Progmasoft OAuth</h1>" + - "<p>Sign in with Progmasoft: an OAuth 2.1 and OpenID Connect provider for Progmasoft accounts. " + - "Any developer can register an application.</p>"; - if (account is null) - { - body += "<p><a href=\"/signin\">Sign in</a> to register applications or to review the applications you " + - "have allowed.</p>"; - } - else - { - body += $"<p>Signed in as <strong>{HtmlPage.Encode(account.AccountName)}</strong>.</p>" + - "<ul><li><a href=\"/developers\">Your applications</a></li>" + - "<li><a href=\"/account/applications\">Applications you have allowed</a></li></ul>" + - HtmlPage.Form(context, "/signout", "<button class=\"secondary\" type=\"submit\">Sign out</button>"); - } - - body += "<p class=\"note\">Discovery document: <a href=\"/.well-known/openid-configuration\">" + - "/.well-known/openid-configuration</a></p>"; - return HtmlPage.Render(context, "Progmasoft OAuth", body); - } - - /// <summary>Shows the sign-in form.</summary> - private static IResult SignInPage(HttpContext context, IOptions<OAuthOptions> options, string? returnUrl) => - RenderSignIn(context, options.Value, OAuthAccount.LocalReturnUrl(returnUrl), null, null); - - /// <summary>Checks the submitted email address and password and signs the account in.</summary> - private static async Task<IResult> SignInAsync( - HttpContext context, - AccountService accounts, - IOptions<OAuthOptions> options) - { - if (!await OAuthAccount.IsGenuineFormAsync(context)) - { - return Results.BadRequest(); - } - - IFormCollection form = await context.Request.ReadFormAsync(context.RequestAborted); - string returnUrl = OAuthAccount.LocalReturnUrl(form["returnUrl"]); - string? email = form["email"]; - AccountRecord? account = await accounts.VerifyPasswordAsync(email, form["password"], context.RequestAborted); - if (account is null) - { - // One message for every failure, as the account API gives: it does not tell registered addresses apart. - return RenderSignIn(context, options.Value, returnUrl, email, - "The email address or the password is not right.", StatusCodes.Status401Unauthorized); - } - - ClaimsIdentity identity = new(OAuthRegistration.CookieScheme, Claims.Name, Claims.Role); - identity.AddClaim(new Claim(Claims.Subject, account.Id.ToString())); - identity.AddClaim(new Claim(Claims.Name, account.AccountName)); - await context.SignInAsync(OAuthRegistration.CookieScheme, new ClaimsPrincipal(identity), - new AuthenticationProperties { IsPersistent = false }); - return Results.Redirect(returnUrl); - } - - /// <summary>Ends the sign-in.</summary> - private static async Task<IResult> SignOutAsync(HttpContext context) - { - if (!await OAuthAccount.IsGenuineFormAsync(context)) - { - return Results.BadRequest(); - } - - await context.SignOutAsync(OAuthRegistration.CookieScheme); - return Results.Redirect("/"); - } - - /// <summary>Shows the sign-in form with an optional message.</summary> - private static IResult RenderSignIn( - HttpContext context, - OAuthOptions options, - string returnUrl, - string? email, - string? error, - int statusCode = StatusCodes.Status200OK) - { - string fields = - HtmlPage.Hidden("returnUrl", returnUrl) + - "<label for=\"email\">Email address</label>" + - $"<input id=\"email\" name=\"email\" type=\"email\" autocomplete=\"username\" required value=\"{HtmlPage.Encode(email)}\">" + - "<label for=\"password\">Password</label>" + - "<input id=\"password\" name=\"password\" type=\"password\" autocomplete=\"current-password\" required>" + - "<button type=\"submit\">Sign in</button>"; - string body = "<h1>Sign in to Progmasoft</h1>" + HtmlPage.Error(error) + - HtmlPage.Form(context, "/signin", fields) + - $"<p class=\"note\">No account yet? <a href=\"{HtmlPage.Encode(options.RegistrationUrl)}\">" + - "Create a Progmasoft account</a>.</p>"; - return HtmlPage.Render(context, "Sign in", body, statusCode); - } -} diff --git a/apps/api/Program.cs b/apps/api/Program.cs index aeeff29..476cbdb 100644 --- a/apps/api/Program.cs +++ b/apps/api/Program.cs @@ -118,6 +118,8 @@ app.UseHttpsRedirection(); app.UseMiddleware<SecurityHeadersMiddleware>(); // Before authentication, where OpenIddict answers its own endpoints: OAuth only on its host, and nothing else there. app.UseMiddleware<OAuthHostFilter>(); +// Single-page applications call the token endpoints from the browser; see OAuth/Api/OAuthCors.cs. +app.UseMiddleware<Progmasoft.OAuth.Api.OAuthCors>(); app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter(); diff --git a/apps/api/appsettings.Development.json b/apps/api/appsettings.Development.json index b91cc83..2267743 100644 --- a/apps/api/appsettings.Development.json +++ b/apps/api/appsettings.Development.json @@ -5,6 +5,14 @@ "Microsoft.AspNetCore": "Information" } }, - "AllowedHosts": "localhost;127.0.0.1;account.localhost;credentials.localhost" + "AllowedHosts": "localhost;127.0.0.1;account.localhost;credentials.localhost;authorize.localhost;console.localhost", + "AccountSessions": { + "CookieName": "__Host-ProgmasoftSession", + "CookieDomain": "" + }, + "OAuth": { + "Host": "credentials.localhost", + "AuthorizeHost": "authorize.localhost", + "ConsoleHost": "console.localhost" + } } - diff --git a/apps/api/appsettings.json b/apps/api/appsettings.json index 1bbeb26..4ddc9e9 100644 --- a/apps/api/appsettings.json +++ b/apps/api/appsettings.json @@ -5,9 +5,10 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;credentials.progmasoft.com", + "AllowedHosts": "localhost;127.0.0.1;progmasoft.com;account.progmasoft.com;www.progmasoft.com;credentials.progmasoft.com;authorize.progmasoft.com;console.progmasoft.com", "AccountSessions": { "LifetimeHours": 720, - "CookieName": "__Host-ProgmasoftSession" + "CookieName": "__Secure-ProgmasoftSession", + "CookieDomain": "progmasoft.com" } } diff --git a/apps/web/app/authorize/applications/page.tsx b/apps/web/app/authorize/applications/page.tsx new file mode 100644 index 0000000..988771e --- /dev/null +++ b/apps/web/app/authorize/applications/page.tsx @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { AllowedApplications } from "@/components/credentials/AllowedApplications"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.allowed }; +} + +export default async function AllowedApplicationsPage() { + const locale = await getLocale(); + const { allowed } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={allowed.eyebrow} + title={allowed.title} + description={allowed.description} + locale={locale} + site="authorize" + > + <AllowedApplications locale={locale} /> + </CredentialsShell> + ); +} diff --git a/apps/web/app/authorize/consent/page.tsx b/apps/web/app/authorize/consent/page.tsx new file mode 100644 index 0000000..0a2bb51 --- /dev/null +++ b/apps/web/app/authorize/consent/page.tsx @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { ConsentPanel } from "@/components/credentials/ConsentPanel"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.consent }; +} + +interface ConsentPageProps { + searchParams: Promise<Record<string, string | string[] | undefined>>; +} + +export default async function CredentialsConsentPage({ + searchParams, +}: ConsentPageProps) { + const query = await searchParams; + // Every parameter of the authorization request goes back to + // /connect/authorize with the decision, where OpenIddict checks it again. + const parameters: [string, string][] = Object.entries(query).flatMap( + ([name, value]) => + (Array.isArray(value) ? value : value === undefined ? [] : [value]).map( + (entry): [string, string] => [name, entry], + ), + ); + const locale = await getLocale(); + const { consent } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={consent.eyebrow} + title={getCredentialsMessages(locale).metadata.consent} + locale={locale} + site="authorize" + layout="split" + > + <ConsentPanel locale={locale} parameters={parameters} /> + </CredentialsShell> + ); +} diff --git a/apps/web/app/authorize/layout.tsx b/apps/web/app/authorize/layout.tsx new file mode 100644 index 0000000..7d39427 --- /dev/null +++ b/apps/web/app/authorize/layout.tsx @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import type { ReactNode } from "react"; +import "./oauth.css"; + +// credentials.progmasoft.com: sign-in, consent and developer pages are never +// search documents. +export const metadata: Metadata = { + robots: { index: false, follow: false }, +}; + +export default function CredentialsLayout({ + children, +}: Readonly<{ children: ReactNode }>) { + return children; +} diff --git a/apps/web/app/authorize/oauth.css b/apps/web/app/authorize/oauth.css new file mode 100644 index 0000000..f36e5ad --- /dev/null +++ b/apps/web/app/authorize/oauth.css @@ -0,0 +1,259 @@ +/* SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> */ +/* SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 */ + +/* Progmasoft OAuth at credentials.progmasoft.com. The sign-in and consent + pages reuse the account layout; the developer pages are one column. */ + +.credentials-main { + width: min(calc(100% - 40px), 880px); + min-height: calc(100vh - 69px); + margin-inline: auto; + padding-block: 56px 72px; +} + +.credentials-heading h1 { + margin: 0; + font-size: clamp(32px, 4vw, 44px); + letter-spacing: -0.035em; + line-height: 1.1; +} + +.credentials-heading > p:not(.eyebrow) { + max-width: 640px; + margin: 14px 0 0; + color: var(--ink-650); + font-size: 17px; +} + +.credentials-heading + * { + margin-top: 32px; +} + +.credentials-panel { + display: grid; + gap: 21px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + padding: 32px; + background: var(--surface); + box-shadow: var(--shadow-sm); +} + +.credentials-panel + .credentials-panel { + margin-top: 24px; +} + +.credentials-panel h2 { + margin: 0; + font-size: 21px; + letter-spacing: -0.02em; +} + +.credentials-panel p { + margin: 0; +} + +.credentials-note { + color: var(--ink-650); + font-size: 14px; +} + +.credentials-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 12px; +} + +.credentials-list { + display: grid; + gap: 0; + margin: 0; + padding: 0; + list-style: none; +} + +.credentials-list li { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px 16px; + border-top: 1px solid var(--line); + padding-block: 16px; +} + +.credentials-list li:first-child { + border-top: 0; + padding-top: 0; +} + +.credentials-list a { + color: var(--ink-950); + font-weight: 650; +} + +.credentials-meta { + display: flex; + flex-wrap: wrap; + gap: 6px 12px; + color: var(--ink-650); + font-size: 14px; +} + +.credentials-code { + overflow-wrap: anywhere; + border-radius: var(--radius-sm); + padding: 2px 6px; + background: var(--surface-muted); + font-family: ui-monospace, SFMono-Regular, Consolas, monospace; + font-size: 13px; +} + +.credentials-secret { + display: block; + border: 1px solid var(--line-strong); + padding: 12px 14px; + font-size: 14px; +} + +.kind-list { + display: grid; + gap: 12px; + margin: 0; + padding: 0; + list-style: none; +} + +.kind-list a { + display: grid; + gap: 6px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + padding: 18px 20px; + background: var(--surface); + color: var(--ink-800); + text-decoration: none; + transition: + border-color 120ms ease, + box-shadow 120ms ease; +} + +.kind-list a:hover, +.kind-list a:focus-visible { + border-color: var(--blue-500); + box-shadow: var(--shadow-sm); +} + +.kind-list strong { + color: var(--blue-600); + font-size: 17px; +} + +.kind-list span { + color: var(--ink-650); + font-size: 14px; +} + +.field-group textarea { + width: 100%; + min-height: 92px; + border: 1px solid #89939e; + border-radius: var(--radius-sm); + padding: 9px 11px; + background: var(--surface); + color: var(--ink-950); + font-family: ui-monospace, SFMono-Regular, Consolas, monospace; + font-size: 14px; + resize: vertical; +} + +.field-group textarea:focus { + outline: 2px solid var(--blue-500); + outline-offset: 1px; +} + +.field-error { + color: var(--danger); + font-size: 14px; +} + +.scope-checks { + display: grid; + gap: 10px; + margin: 0; + border: 0; + padding: 0; +} + +.scope-checks legend { + margin-bottom: 4px; + color: var(--ink-800); + font-size: 14px; + font-weight: 650; +} + +.scope-checks label { + display: grid; + grid-template-columns: auto 1fr; + gap: 2px 10px; + align-items: start; + font-size: 14px; +} + +.scope-checks input { + margin-top: 3px; +} + +.scope-checks small { + grid-column: 2; + color: var(--ink-650); +} + +.consent-scopes { + display: grid; + gap: 10px; + margin: 0; + padding: 0; + list-style: none; +} + +.consent-scopes li { + display: flex; + gap: 10px; +} + +.consent-scopes li::before { + flex: none; + width: 18px; + height: 18px; + display: grid; + place-items: center; + margin-top: 3px; + border-radius: 50%; + background: var(--blue-100); + color: var(--blue-600); + content: "✓"; + font-size: 11px; + font-weight: 800; +} + +.form-message-success { + border: 1px solid #9ad8bf; + background: #effaf5; + color: var(--green-600); +} + +.button-danger { + background: var(--danger); +} + +@media (max-width: 760px) { + .credentials-panel { + padding: 22px; + } +} + +.credentials-footnote { + margin-top: 20px; +} diff --git a/apps/web/app/authorize/page.tsx b/apps/web/app/authorize/page.tsx new file mode 100644 index 0000000..d6fc6dc --- /dev/null +++ b/apps/web/app/authorize/page.tsx @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { CredentialsHome } from "@/components/credentials/CredentialsHome"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { siteOrigin } from "@/lib/hosts.server"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.home }; +} + +export default async function CredentialsHomePage() { + const locale = await getLocale(); + const { home } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={home.eyebrow} + title={home.title} + description={home.description} + locale={locale} + site="authorize" + > + <CredentialsHome + locale={locale} + consoleOrigin={await siteOrigin("console")} + /> + </CredentialsShell> + ); +} diff --git a/apps/web/app/authorize/signin/page.tsx b/apps/web/app/authorize/signin/page.tsx new file mode 100644 index 0000000..bdfcf3a --- /dev/null +++ b/apps/web/app/authorize/signin/page.tsx @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { SignInForm } from "@/components/credentials/SignInForm"; +import { localReturnUrl } from "@/lib/credentials"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.signIn }; +} + +interface SignInPageProps { + // The cookie handler of the API names the parameter ReturnUrl. + searchParams: Promise<{ ReturnUrl?: string; returnUrl?: string }>; +} + +export default async function CredentialsSignInPage({ + searchParams, +}: SignInPageProps) { + const { ReturnUrl, returnUrl } = await searchParams; + const locale = await getLocale(); + const { signIn } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={signIn.eyebrow} + title={signIn.title} + description={signIn.description} + locale={locale} + site="authorize" + layout="split" + > + <SignInForm + locale={locale} + returnUrl={localReturnUrl(ReturnUrl ?? returnUrl)} + /> + </CredentialsShell> + ); +} diff --git a/apps/web/app/console/credentials/[clientId]/page.tsx b/apps/web/app/console/credentials/[clientId]/page.tsx new file mode 100644 index 0000000..6d780cd --- /dev/null +++ b/apps/web/app/console/credentials/[clientId]/page.tsx @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { ApplicationDetails } from "@/components/credentials/ApplicationDetails"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { + title: getCredentialsMessages(await getLocale()).metadata.application, + }; +} + +interface ApplicationPageProps { + params: Promise<{ clientId: string }>; +} + +export default async function ApplicationPage({ + params, +}: ApplicationPageProps) { + const { clientId } = await params; + const locale = await getLocale(); + const { portal, metadata, common } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={portal.title} + title={metadata.application} + locale={locale} + site="console" + > + <ApplicationDetails + locale={locale} + clientId={decodeURIComponent(clientId)} + /> + <p className="credentials-footnote"> + <a href="/credentials">{common.back}</a> + </p> + </CredentialsShell> + ); +} diff --git a/apps/web/app/console/credentials/new/[kind]/page.tsx b/apps/web/app/console/credentials/new/[kind]/page.tsx new file mode 100644 index 0000000..7fa35e7 --- /dev/null +++ b/apps/web/app/console/credentials/new/[kind]/page.tsx @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { NewToken } from "@/components/credentials/NewToken"; +import { isApplicationKind } from "@/lib/credentials"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.newToken }; +} + +interface NewTokenFormPageProps { + params: Promise<{ kind: string }>; +} + +/** The second step of a new token: the form of the chosen type. */ +export default async function NewTokenFormPage({ + params, +}: NewTokenFormPageProps) { + const { kind } = await params; + if (!isApplicationKind(kind)) { + notFound(); + } + const locale = await getLocale(); + const { kinds, portal, common } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={`${portal.newToken} · ${kinds[kind].title}`} + title={kinds[kind].title} + description={kinds[kind].description} + locale={locale} + site="console" + > + <NewToken locale={locale} kind={kind} /> + <p className="credentials-footnote"> + <a href="/credentials/new">{common.back}</a> + </p> + </CredentialsShell> + ); +} diff --git a/apps/web/app/console/credentials/new/page.tsx b/apps/web/app/console/credentials/new/page.tsx new file mode 100644 index 0000000..aeecfbe --- /dev/null +++ b/apps/web/app/console/credentials/new/page.tsx @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { applicationKinds } from "@/lib/credentials"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.newToken }; +} + +/** The first step of a new token: the type of the application. */ +export default async function NewTokenPage() { + const locale = await getLocale(); + const { kinds, portal, common } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={portal.eyebrow} + title={kinds.chooseTitle} + description={kinds.chooseDescription} + locale={locale} + site="console" + > + <h2 className="credentials-note">{kinds.label}</h2> + <ul className="kind-list"> + {applicationKinds.map((kind) => ( + <li key={kind}> + <a href={`/credentials/new/${kind}`}> + <strong>{kinds[kind].title}</strong> + <span>{kinds[kind].description}</span> + </a> + </li> + ))} + </ul> + <p className="credentials-footnote"> + <a href="/credentials">{common.back}</a> + </p> + </CredentialsShell> + ); +} diff --git a/apps/web/app/console/credentials/page.tsx b/apps/web/app/console/credentials/page.tsx new file mode 100644 index 0000000..76a569d --- /dev/null +++ b/apps/web/app/console/credentials/page.tsx @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { TokenList } from "@/components/credentials/TokenList"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.portal }; +} + +export default async function DevelopersPage() { + const locale = await getLocale(); + const { portal } = getCredentialsMessages(locale); + return ( + <CredentialsShell + eyebrow={portal.eyebrow} + title={portal.title} + description={portal.description} + locale={locale} + site="console" + > + <TokenList locale={locale} /> + </CredentialsShell> + ); +} diff --git a/apps/web/app/console/layout.tsx b/apps/web/app/console/layout.tsx new file mode 100644 index 0000000..e0ec969 --- /dev/null +++ b/apps/web/app/console/layout.tsx @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import type { ReactNode } from "react"; +import "../authorize/oauth.css"; + +// console.progmasoft.com: the pages of a signed-in developer are never search +// documents. +export const metadata: Metadata = { + robots: { index: false, follow: false }, +}; + +export default function ConsoleLayout({ + children, +}: Readonly<{ children: ReactNode }>) { + return children; +} diff --git a/apps/web/app/console/page.tsx b/apps/web/app/console/page.tsx new file mode 100644 index 0000000..1c16df4 --- /dev/null +++ b/apps/web/app/console/page.tsx @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { siteOrigin } from "@/lib/hosts.server"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).overview.eyebrow }; +} + +/** + * The overview of the Progmasoft Console. OAuth 2.1 credentials are one area + * of it, under /credentials; later Progmasoft services get areas of their own. + */ +export default async function ConsoleOverviewPage() { + const locale = await getLocale(); + const { overview, common } = getCredentialsMessages(locale); + const authorize = await siteOrigin("authorize"); + return ( + <CredentialsShell + eyebrow={overview.eyebrow} + title={overview.title} + description={overview.description} + locale={locale} + site="console" + > + <ul className="kind-list"> + <li> + <a href="/credentials"> + <strong>{common.developers}</strong> + <span>{overview.credentialsText}</span> + </a> + </li> + <li> + <a href={`${authorize}/account/applications`}> + <strong>{common.allowedApplications}</strong> + <span>{overview.allowedText}</span> + </a> + </li> + <li> + <a href="https://github.com/Progmasoft/progmaweb/blob/main/docs/OAUTH.md"> + <strong>{overview.docs}</strong> + <span>{overview.docsText}</span> + </a> + </li> + </ul> + </CredentialsShell> + ); +} diff --git a/apps/web/app/issuer/layout.tsx b/apps/web/app/issuer/layout.tsx new file mode 100644 index 0000000..087a362 --- /dev/null +++ b/apps/web/app/issuer/layout.tsx @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import type { ReactNode } from "react"; +import "../authorize/oauth.css"; + +// credentials.progmasoft.com is the issuer of Progmasoft OAuth; its one page +// is not a search document. +export const metadata: Metadata = { + robots: { index: false, follow: false }, +}; + +export default function IssuerLayout({ + children, +}: Readonly<{ children: ReactNode }>) { + return children; +} diff --git a/apps/web/app/issuer/page.tsx b/apps/web/app/issuer/page.tsx new file mode 100644 index 0000000..542ec4c --- /dev/null +++ b/apps/web/app/issuer/page.tsx @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Metadata } from "next"; +import { CredentialsShell } from "@/components/credentials/CredentialsShell"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { siteOrigin } from "@/lib/hosts.server"; +import { getLocale } from "@/lib/locale.server"; + +export async function generateMetadata(): Promise<Metadata> { + return { title: getCredentialsMessages(await getLocale()).metadata.home }; +} + +/** + * credentials.progmasoft.com: the issuer, whose discovery document names every + * endpoint. People sign in on authorize.progmasoft.com and developers make + * tokens on console.progmasoft.com. + */ +export default async function IssuerPage() { + const locale = await getLocale(); + const { home, common } = getCredentialsMessages(locale); + const consoleOrigin = await siteOrigin("console"); + const authorizeOrigin = await siteOrigin("authorize"); + return ( + <CredentialsShell + eyebrow={home.eyebrow} + title={home.title} + description={home.description} + locale={locale} + site="authorize" + > + <ul className="kind-list"> + <li> + <a href="/.well-known/openid-configuration"> + <strong>{home.discovery}</strong> + <span>/.well-known/openid-configuration</span> + </a> + </li> + <li> + <a href={`${consoleOrigin}/credentials`}> + <strong>{common.developers}</strong> + <span>{home.developersText}</span> + </a> + </li> + <li> + <a href={`${authorizeOrigin}/account/applications`}> + <strong>{common.allowedApplications}</strong> + <span>{home.allowedText}</span> + </a> + </li> + </ul> + </CredentialsShell> + ); +} diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts index 1bce9a0..ddf41bc 100644 --- a/apps/web/app/robots.ts +++ b/apps/web/app/robots.ts @@ -9,6 +9,15 @@ export default async function robots(): Promise<MetadataRoute.Robots> { const host = requestHeaders.get("x-forwarded-host") ?? requestHeaders.get("host") ?? ""; const canonicalHost = host.split(":", 1)[0]?.toLowerCase(); + // Progmasoft OAuth and the Progmasoft Console have sign-in, consent and + // developer pages only; none of them is a search document. + if ( + canonicalHost === "credentials.progmasoft.com" || + canonicalHost === "authorize.progmasoft.com" || + canonicalHost === "console.progmasoft.com" + ) { + return { rules: [{ userAgent: "*", disallow: "/" }] }; + } const sitemap = canonicalHost === "viget.progmasoft.com" ? "https://viget.progmasoft.com/sitemap.xml" diff --git a/apps/web/components/Brand.tsx b/apps/web/components/Brand.tsx index 925ef61..621d192 100644 --- a/apps/web/components/Brand.tsx +++ b/apps/web/components/Brand.tsx @@ -1,22 +1,29 @@ // SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> // SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 +import type { Route } from "next"; import Link from "next/link"; interface BrandProps { account?: boolean; accountLabel?: string; + /** Where the mark leads; by default the account site or the organization site. */ + home?: Route; } export function Brand({ account = false, accountLabel = "Account", + home, }: BrandProps) { return ( <Link className="brand" href={ - account ? "https://account.progmasoft.com/" : "https://progmasoft.com/" + home ?? + (account + ? "https://account.progmasoft.com/" + : "https://progmasoft.com/") } > <span className="brand-mark" aria-hidden="true"> diff --git a/apps/web/components/credentials/AccountSignInNotice.tsx b/apps/web/components/credentials/AccountSignInNotice.tsx new file mode 100644 index 0000000..ebd96c1 --- /dev/null +++ b/apps/web/components/credentials/AccountSignInNotice.tsx @@ -0,0 +1,34 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; + +/** + * The sign-in page of the Progmasoft account site. The console has no sign-in + * of its own and never redirects: it shows this link instead. On a development + * host (console.localhost:3010) the account site is account.localhost. + */ +function accountSignInUrl(): string { + const { protocol, hostname, port } = window.location; + return hostname.endsWith(".localhost") + ? `${protocol}//account.localhost${port ? `:${port}` : ""}/login` + : "https://account.progmasoft.com/login"; +} + +/** Shown by a console page whose visitor has no Progmasoft account session. */ +export function AccountSignInNotice({ locale }: { locale: Locale }) { + const { common } = getCredentialsMessages(locale); + return ( + <div className="credentials-panel"> + <p>{common.signInRequired}</p> + <div className="credentials-actions"> + <a className="button" href={accountSignInUrl()}> + {common.signInAccount} + </a> + </div> + </div> + ); +} diff --git a/apps/web/components/credentials/AllowedApplications.tsx b/apps/web/components/credentials/AllowedApplications.tsx new file mode 100644 index 0000000..ec7b857 --- /dev/null +++ b/apps/web/components/credentials/AllowedApplications.tsx @@ -0,0 +1,113 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { useEffect, useState } from "react"; +import { + callOAuthApi, + signInPath, + type AllowedApplication, +} from "@/lib/credentials"; +import { format, getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; + +type AllowedState = + | { kind: "loading" } + | { kind: "failed" } + | { kind: "ready"; allowed: AllowedApplication[] }; + +/** The applications the signed-in account has allowed, each with a Withdraw button. */ +export function AllowedApplications({ locale }: { locale: Locale }) { + const { allowed: text, common } = getCredentialsMessages(locale); + const [state, setState] = useState<AllowedState>({ kind: "loading" }); + + useEffect(() => { + const controller = new AbortController(); + void callOAuthApi<AllowedApplication[]>("/allowed", { + signal: controller.signal, + }).then((result) => { + if (result.kind === "signedOut") { + window.location.replace(signInPath("/account/applications")); + } else if (result.kind === "ok") { + setState({ kind: "ready", allowed: result.value }); + } else { + setState({ kind: "failed" }); + } + }); + return () => controller.abort(); + }, []); + + async function withdraw(authorizationId: string) { + const result = await callOAuthApi( + `/allowed/${encodeURIComponent(authorizationId)}`, + { method: "DELETE" }, + ); + if (result.kind === "ok" || result.kind === "notFound") { + setState((current) => + current.kind === "ready" + ? { + kind: "ready", + allowed: current.allowed.filter( + (entry) => entry.authorizationId !== authorizationId, + ), + } + : current, + ); + } else if (result.kind === "signedOut") { + window.location.assign(signInPath("/account/applications")); + } + } + + if (state.kind === "loading") { + return <p className="credentials-note">{common.loading}</p>; + } + if (state.kind === "failed") { + return ( + <div className="form-message form-message-error" role="alert"> + {common.unreachable} + </div> + ); + } + + return ( + <div className="credentials-panel"> + {state.allowed.length === 0 ? ( + <p>{text.empty}</p> + ) : ( + <ul className="credentials-list"> + {state.allowed.map((entry) => ( + <li key={entry.authorizationId}> + <div> + <strong>{entry.displayName ?? text.deleted}</strong> + <span className="credentials-meta"> + {entry.createdAt && ( + <span> + {format(text.since, { + date: new Date(entry.createdAt).toLocaleDateString( + locale, + ), + })} + </span> + )} + {entry.scopes.map((scope) => ( + <code className="credentials-code" key={scope}> + {scope} + </code> + ))} + </span> + </div> + <button + className="button button-secondary button-small" + type="button" + onClick={() => withdraw(entry.authorizationId)} + > + {text.withdraw} + </button> + </li> + ))} + </ul> + )} + </div> + ); +} diff --git a/apps/web/components/credentials/ApplicationDetails.tsx b/apps/web/components/credentials/ApplicationDetails.tsx new file mode 100644 index 0000000..68bfd84 --- /dev/null +++ b/apps/web/components/credentials/ApplicationDetails.tsx @@ -0,0 +1,193 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { useEffect, useState } from "react"; +import { + callOAuthApi, + type ApplicationCredentials, + type ApplicationView, +} from "@/lib/credentials"; +import { format, getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; +import { AccountSignInNotice } from "./AccountSignInNotice"; +import { ApplicationForm } from "./ApplicationForm"; +import { CredentialsCard } from "./CredentialsCard"; + +type DetailsState = + | { kind: "loading" } + | { kind: "signedOut" } + | { kind: "notFound" } + | { kind: "failed" } + | { kind: "ready"; application: ApplicationView }; + +/** One application of the signed-in account: its settings, its secret and its deletion. */ +export function ApplicationDetails({ + locale, + clientId, +}: { + locale: Locale; + clientId: string; +}) { + const { common, details, form, kinds } = getCredentialsMessages(locale); + const [state, setState] = useState<DetailsState>({ kind: "loading" }); + const [saved, setSaved] = useState(false); + const [secret, setSecret] = useState<ApplicationCredentials | null>(null); + const path = `/applications/${encodeURIComponent(clientId)}`; + + useEffect(() => { + const controller = new AbortController(); + void callOAuthApi<ApplicationView>( + `/applications/${encodeURIComponent(clientId)}`, + { signal: controller.signal }, + ).then((result) => { + if (result.kind === "signedOut") { + setState({ kind: "signedOut" }); + } else if (result.kind === "ok") { + setState({ kind: "ready", application: result.value }); + } else { + setState({ kind: result.kind === "notFound" ? "notFound" : "failed" }); + } + }); + return () => controller.abort(); + }, [clientId]); + + if (state.kind === "loading") { + return <p className="credentials-note">{common.loading}</p>; + } + if (state.kind === "signedOut") { + return <AccountSignInNotice locale={locale} />; + } + if (state.kind !== "ready") { + return ( + <div className="credentials-panel"> + <p> + {state.kind === "notFound" ? common.notFound : common.unreachable} + </p> + <div className="credentials-actions"> + <a className="button button-secondary" href="/credentials"> + {common.back} + </a> + </div> + </div> + ); + } + + const { application } = state; + + async function rotate() { + const result = await callOAuthApi<ApplicationCredentials>( + `${path}/secret`, + { method: "POST" }, + ); + if (result.kind === "ok") { + setSecret(result.value); + } else if (result.kind === "signedOut") { + setState({ kind: "signedOut" }); + } + } + + async function remove() { + if (!window.confirm(details.confirmDelete)) { + return; + } + const result = await callOAuthApi(path, { method: "DELETE" }); + if (result.kind === "ok" || result.kind === "notFound") { + window.location.replace("/credentials"); + } else if (result.kind === "signedOut") { + setState({ kind: "signedOut" }); + } + } + + return ( + <> + <div className="credentials-panel"> + <p className="credentials-meta"> + <span>{kinds[application.kind].title}</span> + <code className="credentials-code">{application.clientId}</code> + <span> + {format(details.created, { + date: new Date(application.createdAt).toLocaleDateString(locale), + })} + </span> + </p> + {saved && ( + <div className="form-message form-message-success" role="status"> + {form.saved} + </div> + )} + </div> + + <ApplicationForm + key={application.clientId} + locale={locale} + kind={application.kind} + initial={application} + submitLabel={form.save} + onSubmit={async (submission) => { + setSaved(false); + const result = await callOAuthApi<ApplicationView>(path, { + method: "PUT", + body: submission, + }); + switch (result.kind) { + case "ok": + setState({ kind: "ready", application: result.value }); + setSaved(true); + return null; + case "signedOut": + setState({ kind: "signedOut" }); + return null; + case "refused": + return result.errors; + default: + return { form: common.unreachable }; + } + }} + /> + + {secret ? ( + <CredentialsCard + locale={locale} + title={details.newSecret} + credentials={secret} + /> + ) : ( + <div className="credentials-panel"> + <h2>{details.secretHeading}</h2> + {application.isPublic ? ( + <p className="credentials-note">{details.noSecret}</p> + ) : ( + <> + <p className="credentials-note">{details.rotateNote}</p> + <div className="credentials-actions"> + <button + className="button button-secondary" + type="button" + onClick={rotate} + > + {details.rotate} + </button> + </div> + </> + )} + </div> + )} + + <div className="credentials-panel"> + <h2>{details.deleteHeading}</h2> + <p className="credentials-note">{details.deleteNote}</p> + <div className="credentials-actions"> + <button + className="button button-danger" + type="button" + onClick={remove} + > + {details.delete} + </button> + </div> + </div> + </> + ); +} diff --git a/apps/web/components/credentials/ApplicationForm.tsx b/apps/web/components/credentials/ApplicationForm.tsx new file mode 100644 index 0000000..6285a12 --- /dev/null +++ b/apps/web/components/credentials/ApplicationForm.tsx @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { type FormEvent, useId, useState } from "react"; +import { + lines, + oauthScopes, + signsPeopleIn, + type ApplicationKind, + type ApplicationSubmission, +} from "@/lib/credentials"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; + +export interface ApplicationFormValues { + displayName: string; + homepage: string; + redirectUris: string[]; + postLogoutRedirectUris: string[]; + scopes: string[]; +} + +interface ApplicationFormProps { + locale: Locale; + kind: ApplicationKind; + initial: ApplicationFormValues; + submitLabel: string; + /** Sends the submission; answers the messages of refused fields, or none. */ + onSubmit: ( + submission: ApplicationSubmission, + ) => Promise<Record<string, string> | null>; +} + +/** + * The settings of an application of one type. A service has neither addresses + * nor scopes; the other types list the scopes the application may request, + * which every person still decides on the consent page. + */ +export function ApplicationForm({ + locale, + kind, + initial, + submitLabel, + onSubmit, +}: ApplicationFormProps) { + const { form, scopes } = getCredentialsMessages(locale); + const formId = useId(); + const [pending, setPending] = useState(false); + const [errors, setErrors] = useState<Record<string, string>>({}); + + async function submit(event: FormEvent<HTMLFormElement>) { + event.preventDefault(); + const data = new FormData(event.currentTarget); + const peopleSignIn = signsPeopleIn(kind); + setPending(true); + const refused = await onSubmit({ + kind, + displayName: String(data.get("displayName") ?? ""), + homepage: String(data.get("homepage") ?? "").trim(), + redirectUris: peopleSignIn + ? lines(String(data.get("redirectUris") ?? "")) + : [], + postLogoutRedirectUris: peopleSignIn + ? lines(String(data.get("postLogoutRedirectUris") ?? "")) + : [], + scopes: peopleSignIn ? data.getAll("scope").map(String) : [], + }); + setErrors(refused ?? {}); + setPending(false); + } + + function fieldError(field: string) { + return errors[field] ? ( + <p className="field-error" role="alert"> + {errors[field]} + </p> + ) : null; + } + + return ( + <form className="credentials-panel" onSubmit={submit}> + {errors.form && ( + <div className="form-message form-message-error" role="alert"> + {errors.form} + </div> + )} + {fieldError("kind")} + + <div className="field-group"> + <label htmlFor={`${formId}-name`}>{form.name}</label> + {fieldError("displayName")} + <input + id={`${formId}-name`} + name="displayName" + type="text" + minLength={3} + maxLength={64} + defaultValue={initial.displayName} + required + /> + </div> + + <div className="field-group"> + <label htmlFor={`${formId}-homepage`}>{form.homepage}</label> + {fieldError("homepage")} + <input + id={`${formId}-homepage`} + name="homepage" + type="url" + placeholder="https://" + defaultValue={initial.homepage} + /> + </div> + + {signsPeopleIn(kind) ? ( + <> + <div className="field-group"> + <label htmlFor={`${formId}-redirects`}>{form.redirectUris}</label> + <small>{form.hints[kind]}</small> + {fieldError("redirectUris")} + <textarea + id={`${formId}-redirects`} + name="redirectUris" + defaultValue={initial.redirectUris.join("\n")} + spellCheck={false} + required + /> + </div> + + <div className="field-group"> + <label htmlFor={`${formId}-logout`}> + {form.postLogoutRedirectUris} + </label> + {fieldError("postLogoutRedirectUris")} + <textarea + id={`${formId}-logout`} + name="postLogoutRedirectUris" + defaultValue={initial.postLogoutRedirectUris.join("\n")} + spellCheck={false} + /> + </div> + + <fieldset className="scope-checks"> + <legend>{form.scopes}</legend> + {fieldError("scopes")} + {oauthScopes.map((scope) => ( + <label key={scope}> + <input + type="checkbox" + name="scope" + value={scope} + defaultChecked={initial.scopes.includes(scope)} + /> + <code className="credentials-code">{scope}</code> + <small>{scopes[scope]}</small> + </label> + ))} + <p className="credentials-note">{form.scopesNote}</p> + </fieldset> + </> + ) : ( + <> + {fieldError("redirectUris")} + {fieldError("scopes")} + <p className="credentials-note">{form.serviceNote}</p> + </> + )} + + <div className="credentials-actions"> + <button className="button" type="submit" disabled={pending}> + {pending ? form.working : submitLabel} + </button> + </div> + </form> + ); +} diff --git a/apps/web/components/credentials/ConsentPanel.tsx b/apps/web/components/credentials/ConsentPanel.tsx new file mode 100644 index 0000000..0a264fe --- /dev/null +++ b/apps/web/components/credentials/ConsentPanel.tsx @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { useEffect, useState } from "react"; +import { + callOAuthApi, + oauthScopes, + signInPath, + type ConsentView, + type OAuthScope, +} from "@/lib/credentials"; +import { format, getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; + +type ConsentState = + | { kind: "loading" } + | { kind: "invalid" } + | { kind: "failed" } + | { kind: "ready"; consent: ConsentView }; + +/** + * The consent page. `/connect/authorize` sends the account holder here with + * the parameters of the request; the decision is posted back there as a plain + * form, so the browser follows the redirection to the application. + */ +export function ConsentPanel({ + locale, + parameters, +}: { + locale: Locale; + parameters: [string, string][]; +}) { + const { consent: text, scopes, common } = getCredentialsMessages(locale); + const [state, setState] = useState<ConsentState>({ kind: "loading" }); + const query = new URLSearchParams(parameters).toString(); + + useEffect(() => { + const controller = new AbortController(); + void callOAuthApi<ConsentView>(`/consent?${query}`, { + signal: controller.signal, + }).then((result) => { + if (result.kind === "signedOut") { + window.location.replace(signInPath(`/connect/authorize?${query}`)); + } else if (result.kind === "ok") { + setState({ kind: "ready", consent: result.value }); + } else { + setState({ kind: result.kind === "refused" ? "invalid" : "failed" }); + } + }); + return () => controller.abort(); + }, [query]); + + if (state.kind === "loading") { + return <p className="auth-form credentials-note">{common.loading}</p>; + } + if (state.kind !== "ready") { + return ( + <div className="auth-form"> + <div className="form-message form-message-error" role="alert"> + {state.kind === "invalid" ? text.invalid : common.unreachable} + </div> + </div> + ); + } + + const { consent } = state; + const granted = consent.scopes.filter((scope): scope is OAuthScope => + oauthScopes.includes(scope as OAuthScope), + ); + return ( + <form className="auth-form" method="post" action="/connect/authorize"> + {parameters.map(([name, value], index) => ( + <input + key={`${name}-${index}`} + type="hidden" + name={name} + value={value} + /> + ))} + <div className="form-heading"> + <h2>{format(text.title, { name: consent.displayName })}</h2> + <p> + {consent.homepage ? ( + <a + href={consent.homepage} + rel="noreferrer noopener" + target="_blank" + > + {consent.homepage} + </a> + ) : ( + <code className="credentials-code">{consent.clientId}</code> + )} + {consent.owner && ( + <> · {format(text.registeredBy, { owner: consent.owner })}</> + )} + </p> + </div> + + <p>{format(text.wants, { name: consent.displayName })}</p> + <ul className="consent-scopes"> + <li>{scopes.account}</li> + {granted.map((scope) => ( + <li key={scope}>{scopes[scope]}</li> + ))} + </ul> + + <p className="credentials-note"> + {format(text.returnTo, { origin: consent.returnTo })}{" "} + {format(text.signedInAs, { name: consent.accountName })}{" "} + {text.withdrawLater} + </p> + + <div className="credentials-actions"> + <button className="button" type="submit" name="decision" value="allow"> + {text.allow} + </button> + <button + className="button button-secondary" + type="submit" + name="decision" + value="deny" + > + {text.deny} + </button> + </div> + </form> + ); +} diff --git a/apps/web/components/credentials/CredentialsCard.tsx b/apps/web/components/credentials/CredentialsCard.tsx new file mode 100644 index 0000000..2f7665e --- /dev/null +++ b/apps/web/components/credentials/CredentialsCard.tsx @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { ApplicationCredentials } from "@/lib/credentials"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; + +/** The client identifier and, this once, the client secret of an application. */ +export function CredentialsCard({ + locale, + title, + credentials, +}: { + locale: Locale; + title: string; + credentials: ApplicationCredentials; +}) { + const { details, kinds } = getCredentialsMessages(locale); + const { application, clientSecret } = credentials; + return ( + <div className="credentials-panel"> + <h2>{title}</h2> + <p> + <strong>{application.displayName}</strong>{" "} + <span className="credentials-note"> + {kinds[application.kind].title} + </span> + </p> + <div className="field-group"> + <label>{details.clientId}</label> + <code className="credentials-code credentials-secret"> + {application.clientId} + </code> + </div> + {clientSecret ? ( + <div className="field-group"> + <label>{details.clientSecret}</label> + <code className="credentials-code credentials-secret"> + {clientSecret} + </code> + <div className="form-message form-message-error" role="alert"> + {details.copyNow} + </div> + </div> + ) : ( + <p className="credentials-note">{details.noSecret}</p> + )} + <div className="credentials-actions"> + <a + className="button" + href={`/credentials/${encodeURIComponent(application.clientId)}`} + > + {application.displayName} + </a> + </div> + </div> + ); +} diff --git a/apps/web/components/credentials/CredentialsHome.tsx b/apps/web/components/credentials/CredentialsHome.tsx new file mode 100644 index 0000000..6ffc42d --- /dev/null +++ b/apps/web/components/credentials/CredentialsHome.tsx @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { useEffect, useState } from "react"; +import { callOAuthApi, type SessionView } from "@/lib/credentials"; +import { format, getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; + +type HomeState = + | { kind: "loading" } + | { kind: "signedOut" } + | { kind: "signedIn"; accountName: string }; + +/** The home page of credentials.progmasoft.com: where to go, signed in or not. */ +export function CredentialsHome({ + locale, + consoleOrigin, +}: { + locale: Locale; + consoleOrigin: string; +}) { + const { home, common } = getCredentialsMessages(locale); + const [state, setState] = useState<HomeState>({ kind: "loading" }); + + useEffect(() => { + const controller = new AbortController(); + void callOAuthApi<SessionView>("/session", { + signal: controller.signal, + }).then((result) => { + setState( + result.kind === "ok" + ? { kind: "signedIn", accountName: result.value.accountName } + : { kind: "signedOut" }, + ); + }); + return () => controller.abort(); + }, []); + + async function signOut() { + await callOAuthApi("/signout", { method: "POST" }); + setState({ kind: "signedOut" }); + } + + return ( + <> + <div className="credentials-panel"> + {state.kind === "loading" && ( + <p className="credentials-note">{common.loading}</p> + )} + {state.kind === "signedOut" && ( + <> + <p>{home.signedOut}</p> + <div className="credentials-actions"> + <a className="button" href="/signin"> + {common.signIn} + </a> + </div> + </> + )} + {state.kind === "signedIn" && ( + <> + <p>{format(common.signedInAs, { name: state.accountName })}</p> + <ul className="credentials-list"> + <li> + <a href={`${consoleOrigin}/credentials`}>{common.developers}</a> + <span className="credentials-meta">{home.developersText}</span> + </li> + <li> + <a href="/account/applications">{common.allowedApplications}</a> + <span className="credentials-meta">{home.allowedText}</span> + </li> + </ul> + <div className="credentials-actions"> + <button + className="button button-secondary" + type="button" + onClick={signOut} + > + {common.signOut} + </button> + </div> + </> + )} + </div> + <p className="credentials-note credentials-footnote"> + {home.discovery}:{" "} + <a href="/.well-known/openid-configuration"> + /.well-known/openid-configuration + </a> + </p> + </> + ); +} diff --git a/apps/web/components/credentials/CredentialsShell.tsx b/apps/web/components/credentials/CredentialsShell.tsx new file mode 100644 index 0000000..5cd8aa8 --- /dev/null +++ b/apps/web/components/credentials/CredentialsShell.tsx @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { ReactNode } from "react"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { siteOrigin, type OAuthSite } from "@/lib/hosts.server"; +import { getMessages, type Locale } from "@/lib/localization"; +import { Brand } from "../Brand"; +import { PreferenceControls } from "../PreferenceControls"; + +interface CredentialsShellProps { + children: ReactNode; + eyebrow: string; + title: string; + description?: string; + locale: Locale; + /** authorize.progmasoft.com (sign-in, consent) or console.progmasoft.com (tokens). */ + site: OAuthSite; + /** + * `split` puts the introduction beside a panel, as the account sign-in + * does; `column` stacks a heading above the content of a console page. + */ + layout?: "split" | "column"; +} + +/** + * The frame of every page of Progmasoft OAuth and the Progmasoft Console. Its + * addresses are the public ones of each host; the proxy maps them to the + * internal `/authorize`, `/issuer` and `/console` trees. + */ +export async function CredentialsShell({ + children, + eyebrow, + title, + description, + locale, + site, + layout = "column", +}: CredentialsShellProps) { + const { navigation } = getMessages(locale); + const { common } = getCredentialsMessages(locale); + const authorizeOrigin = + site === "authorize" ? "" : await siteOrigin("authorize"); + const consoleOrigin = site === "console" ? "" : await siteOrigin("console"); + const heading = ( + <> + <p className="eyebrow">{eyebrow}</p> + <h1>{title}</h1> + {description && <p>{description}</p>} + </> + ); + return ( + <div className="account-page"> + <header className="site-header"> + <div className="shell header-inner"> + <Brand + account + accountLabel={site === "console" ? common.console : "OAuth"} + home="/" + /> + <nav className="primary-nav" aria-label={navigation.primary}> + <a href="https://progmasoft.com/">{common.organization}</a> + <a href={`${authorizeOrigin}/account/applications`}> + {common.allowedApplications} + </a> + <a + className="button button-small" + href={`${consoleOrigin}/credentials`} + > + {common.developers} + </a> + <PreferenceControls locale={locale} labels={navigation} /> + </nav> + </div> + </header> + {layout === "split" ? ( + <main className="account-main"> + <section className="account-intro">{heading}</section> + <section className="account-panel">{children}</section> + </main> + ) : ( + <main className="credentials-main"> + <section className="credentials-heading">{heading}</section> + <div>{children}</div> + </main> + )} + </div> + ); +} diff --git a/apps/web/components/credentials/NewToken.tsx b/apps/web/components/credentials/NewToken.tsx new file mode 100644 index 0000000..80640ac --- /dev/null +++ b/apps/web/components/credentials/NewToken.tsx @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { useEffect, useState } from "react"; +import { + callOAuthApi, + signsPeopleIn, + type ApplicationCredentials, + type ApplicationKind, + type SessionView, +} from "@/lib/credentials"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import type { Locale } from "@/lib/localization"; +import { AccountSignInNotice } from "./AccountSignInNotice"; +import { ApplicationForm } from "./ApplicationForm"; +import { CredentialsCard } from "./CredentialsCard"; + +/** + * The second step of a new token: the form of the chosen type, and then the + * client identifier and the secret, shown once. + */ +export function NewToken({ + locale, + kind, +}: { + locale: Locale; + kind: ApplicationKind; +}) { + const { form, common, details } = getCredentialsMessages(locale); + const [created, setCreated] = useState<ApplicationCredentials | null>(null); + const [signedOut, setSignedOut] = useState(false); + + // Nobody signed in to the Progmasoft account: show where to sign in. + useEffect(() => { + void callOAuthApi<SessionView>("/session").then((result) => { + setSignedOut(result.kind === "signedOut"); + }); + }, []); + + if (signedOut) { + return <AccountSignInNotice locale={locale} />; + } + if (created) { + return ( + <CredentialsCard + locale={locale} + title={details.tokenCreated} + credentials={created} + /> + ); + } + + return ( + <ApplicationForm + locale={locale} + kind={kind} + initial={{ + displayName: "", + homepage: "", + redirectUris: [], + postLogoutRedirectUris: [], + scopes: signsPeopleIn(kind) ? ["profile"] : [], + }} + submitLabel={form.create} + onSubmit={async (submission) => { + const result = await callOAuthApi<ApplicationCredentials>( + "/applications", + { method: "POST", body: submission }, + ); + switch (result.kind) { + case "ok": + setCreated(result.value); + return null; + case "signedOut": + setSignedOut(true); + return null; + case "refused": + return result.errors; + default: + return { form: common.unreachable }; + } + }} + /> + ); +} diff --git a/apps/web/components/credentials/SignInForm.tsx b/apps/web/components/credentials/SignInForm.tsx new file mode 100644 index 0000000..a64f777 --- /dev/null +++ b/apps/web/components/credentials/SignInForm.tsx @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { type FormEvent, useId, useState } from "react"; +import { localReturnUrl } from "@/lib/credentials"; +import { getCredentialsMessages } from "@/lib/credentials-messages"; +import { getMessages, type Locale } from "@/lib/localization"; + +interface SignInFormProps { + locale: Locale; + returnUrl: string; +} + +/** + * Signs in to Progmasoft OAuth. The cookie belongs to the OAuth host only; the + * account holder then goes back to the authorization request that sent them. + */ +export function SignInForm({ locale, returnUrl }: SignInFormProps) { + const { signIn, common } = getCredentialsMessages(locale); + const { auth } = getMessages(locale); + const formId = useId(); + const [pending, setPending] = useState(false); + const [message, setMessage] = useState<string | null>(null); + const [showPassword, setShowPassword] = useState(false); + + async function submit(event: FormEvent<HTMLFormElement>) { + event.preventDefault(); + setMessage(null); + setPending(true); + const form = new FormData(event.currentTarget); + const response = await fetch("/api/v1/oauth/signin", { + method: "POST", + credentials: "same-origin", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + email: String(form.get("email") ?? ""), + password: String(form.get("password") ?? ""), + }), + }).catch(() => null); + + if (response?.ok) { + // A full navigation, so that /connect/authorize on the API receives the new cookie. + window.location.assign(localReturnUrl(returnUrl)); + return; + } + + setPending(false); + if (response?.status === 401) { + // One message for every refusal: it does not tell registered addresses apart. + setMessage(signIn.failed); + } else { + setMessage(common.unreachable); + } + } + + return ( + <form + className="auth-form" + onSubmit={submit} + aria-describedby={message ? `${formId}-message` : undefined} + > + <div className="form-heading"> + <h2>{signIn.title}</h2> + </div> + + {message && ( + <div + className="form-message form-message-error" + id={`${formId}-message`} + role="alert" + > + {message} + </div> + )} + + <div className="field-group"> + <label htmlFor={`${formId}-email`}>{signIn.email}</label> + <input + id={`${formId}-email`} + name="email" + type="email" + autoComplete="username" + inputMode="email" + maxLength={254} + required + /> + </div> + + <div className="field-group"> + <label htmlFor={`${formId}-password`}>{signIn.password}</label> + <div className="password-field"> + <input + id={`${formId}-password`} + name="password" + type={showPassword ? "text" : "password"} + autoComplete="current-password" + maxLength={256} + required + /> + <button + type="button" + className="password-toggle" + onClick={() => setShowPassword((visible) => !visible)} + > + {showPassword ? auth.hide : auth.show} + </button> + </div> + </div> + + <button className="button auth-submit" type="submit" disabled={pending}> + {pending ? signIn.working : signIn.submit} + </button> + + <p className="form-switch"> + {signIn.noAccount}{" "} + <a href="https://account.progmasoft.com/register"> + {signIn.createAccount} + </a> + </p> + </form> + ); +} diff --git a/apps/web/components/credentials/TokenList.tsx b/apps/web/components/credentials/TokenList.tsx new file mode 100644 index 0000000..97b2b7b --- /dev/null +++ b/apps/web/components/credentials/TokenList.tsx @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +"use client"; + +import { useEffect, useState } from "react"; +import { callOAuthApi, type ApplicationList } from "@/lib/credentials"; +import { format, getCredentialsMessages } from "@/lib/credentials-messages"; +import { AccountSignInNotice } from "./AccountSignInNotice"; +import type { Locale } from "@/lib/localization"; + +type ListState = + | { kind: "loading" } + | { kind: "signedOut" } + | { kind: "failed" } + | { kind: "ready"; list: ApplicationList }; + +/** The OAuth 2.1 tokens of the signed-in account, with the New token button. */ +export function TokenList({ locale }: { locale: Locale }) { + const messages = getCredentialsMessages(locale); + const { portal, common, kinds, details } = messages; + const [state, setState] = useState<ListState>({ kind: "loading" }); + + useEffect(() => { + const controller = new AbortController(); + void callOAuthApi<ApplicationList>("/applications", { + signal: controller.signal, + }).then((result) => { + if (result.kind === "signedOut") { + setState({ kind: "signedOut" }); + } else if (result.kind === "ok") { + setState({ kind: "ready", list: result.value }); + } else { + setState({ kind: "failed" }); + } + }); + return () => controller.abort(); + }, []); + + if (state.kind === "loading") { + return <p className="credentials-note">{common.loading}</p>; + } + if (state.kind === "signedOut") { + return <AccountSignInNotice locale={locale} />; + } + if (state.kind === "failed") { + return ( + <div className="form-message form-message-error" role="alert"> + {common.unreachable} + </div> + ); + } + + const { applications, maximum } = state.list; + return ( + <> + <div className="credentials-panel"> + <div className="credentials-actions"> + {applications.length < maximum ? ( + <a className="button" href="/credentials/new"> + {portal.newToken} + </a> + ) : ( + <p className="credentials-note"> + {format(portal.limit, { count: maximum })} + </p> + )} + </div> + {applications.length === 0 ? ( + <p>{portal.empty}</p> + ) : ( + <ul className="credentials-list"> + {applications.map((application) => ( + <li key={application.clientId}> + <a + href={`/credentials/${encodeURIComponent(application.clientId)}`} + > + {application.displayName} + </a> + <span className="credentials-meta"> + <span>{kinds[application.kind].title}</span> + <code className="credentials-code"> + {application.clientId} + </code> + <span> + {format(details.created, { + date: new Date(application.createdAt).toLocaleDateString( + locale, + ), + })} + </span> + </span> + </li> + ))} + </ul> + )} + </div> + <p className="credentials-note credentials-footnote"> + {portal.endpoints}{" "} + <a href="/.well-known/openid-configuration"> + /.well-known/openid-configuration + </a> + </p> + </> + ); +} diff --git a/apps/web/lib/credentials-messages.ts b/apps/web/lib/credentials-messages.ts new file mode 100644 index 0000000..03f9843 --- /dev/null +++ b/apps/web/lib/credentials-messages.ts @@ -0,0 +1,887 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import type { Locale } from "./localization"; +import type { ApplicationKind, OAuthScope } from "./credentials"; + +/** + * The text of the Progmasoft OAuth pages at credentials.progmasoft.com, in + * every published language. Placeholders in braces are filled by + * {@link format}. + */ +interface CredentialsMessages { + metadata: { + home: string; + signIn: string; + portal: string; + newToken: string; + application: string; + consent: string; + allowed: string; + }; + common: { + product: string; + developers: string; + console: string; + allowedApplications: string; + organization: string; + back: string; + signIn: string; + signOut: string; + signedInAs: string; + signInRequired: string; + signInAccount: string; + loading: string; + unreachable: string; + notFound: string; + }; + home: { + eyebrow: string; + title: string; + description: string; + signedOut: string; + developersText: string; + allowedText: string; + discovery: string; + }; + signIn: { + eyebrow: string; + title: string; + description: string; + email: string; + password: string; + submit: string; + working: string; + failed: string; + noAccount: string; + createAccount: string; + }; + overview: { + eyebrow: string; + title: string; + description: string; + credentialsText: string; + allowedText: string; + docs: string; + docsText: string; + }; + portal: { + eyebrow: string; + title: string; + description: string; + newToken: string; + empty: string; + limit: string; + endpoints: string; + }; + kinds: Record<ApplicationKind, { title: string; description: string }> & { + chooseTitle: string; + chooseDescription: string; + label: string; + }; + form: { + name: string; + homepage: string; + redirectUris: string; + postLogoutRedirectUris: string; + scopes: string; + scopesNote: string; + serviceNote: string; + create: string; + save: string; + saved: string; + working: string; + hints: Record<ApplicationKind, string>; + }; + details: { + clientId: string; + clientSecret: string; + created: string; + copyNow: string; + noSecret: string; + secretHeading: string; + rotate: string; + rotateNote: string; + deleteHeading: string; + deleteNote: string; + delete: string; + confirmDelete: string; + tokenCreated: string; + newSecret: string; + }; + scopes: Record<OAuthScope, string> & { account: string }; + consent: { + eyebrow: string; + title: string; + wants: string; + registeredBy: string; + returnTo: string; + signedInAs: string; + withdrawLater: string; + allow: string; + deny: string; + invalid: string; + }; + allowed: { + eyebrow: string; + title: string; + description: string; + empty: string; + since: string; + deleted: string; + withdraw: string; + }; +} + +export const credentialsMessages: Record<Locale, CredentialsMessages> = { + "en-US": { + metadata: { + home: "Progmasoft OAuth", + signIn: "Sign in to Progmasoft OAuth", + portal: "OAuth 2.1 tokens", + newToken: "New token", + application: "Application", + consent: "Allow access", + allowed: "Allowed applications", + }, + common: { + product: "Progmasoft OAuth", + developers: "OAuth 2.1 tokens", + console: "Console", + allowedApplications: "Allowed applications", + organization: "Progmasoft", + back: "Back", + signIn: "Sign in", + signOut: "Sign out", + signedInAs: "Signed in as {name}.", + signInRequired: + "Sign in to your Progmasoft account to manage the tokens of your applications.", + signInAccount: "Sign in to Progmasoft", + loading: "Loading…", + unreachable: "Progmasoft OAuth could not be reached. Try again.", + notFound: "No application of yours has this client identifier.", + }, + home: { + eyebrow: "OAuth 2.1 · OpenID Connect", + title: "Sign in with Progmasoft", + description: + "Let people sign in to your application with their Progmasoft account and, with their consent, act on ViGet for them. Any developer can make a token.", + signedOut: + "Sign in to make OAuth 2.1 tokens for your applications or to review the applications you have allowed.", + developersText: "Make and manage the tokens of your applications.", + allowedText: "See and withdraw what applications may do for you.", + discovery: "Discovery document", + }, + signIn: { + eyebrow: "Progmasoft OAuth", + title: "Sign in to Progmasoft", + description: + "Use your Progmasoft account. This sign-in stays on credentials.progmasoft.com; applications never see your password.", + email: "Email address", + password: "Password", + submit: "Sign in", + working: "Signing in…", + failed: "The email address or the password is not right.", + noAccount: "No account yet?", + createAccount: "Create a Progmasoft account", + }, + overview: { + eyebrow: "Progmasoft Console", + title: "Build on Progmasoft", + description: + "Manage how your applications use Progmasoft: sign-in with Progmasoft accounts today, more Progmasoft services as they open.", + credentialsText: + "Tokens of your applications: web, single-page, desktop, mobile and service.", + allowedText: "Applications that may act for your own account.", + docs: "Developer guide", + docsText: "Flows, scopes, consent and limits of Progmasoft OAuth.", + }, + portal: { + eyebrow: "Developers", + title: "OAuth 2.1 tokens", + description: + "Each token is one application: its client identifier, its secret if its type has one, and where people return after signing in.", + newToken: "New token", + empty: "You have no token yet.", + limit: "An account can have {count} tokens.", + endpoints: + "Applications that sign people in use the authorization code flow with PKCE (S256). The discovery document lists every endpoint.", + }, + kinds: { + chooseTitle: "New token", + chooseDescription: + "The type decides how the application proves itself and where Progmasoft OAuth may send people back. It cannot change later.", + label: "Application type", + web: { + title: "Web application", + description: + "A site with a server. Authorization code flow with PKCE, and a client secret the server keeps.", + }, + spa: { + title: "Single-page application", + description: + "A browser application without a server, such as React or Vue. Authorization code flow with PKCE, no secret; the token endpoint answers its origin.", + }, + desktop: { + title: "Desktop application", + description: + "A desktop or command-line program. Authorization code flow with PKCE, no secret; returns through a loopback address or a private-use scheme.", + }, + mobile: { + title: "Mobile application", + description: + "An iOS or Android application. Authorization code flow with PKCE, no secret; returns through a private-use scheme or a claimed https:// address.", + }, + service: { + title: "Service", + description: + "A server that acts as itself, not for a person. Client credentials grant with a client secret; no account scope and no sign-in page.", + }, + }, + form: { + name: "Name", + homepage: "Homepage (optional)", + redirectUris: "Redirection addresses, one per line", + postLogoutRedirectUris: + "Addresses after sign-out (optional), one per line", + scopes: "Scopes the application may request", + scopesNote: + "openid is always available. Each person still decides on the consent page.", + serviceNote: + "A service asks /connect/token with grant_type=client_credentials and its secret. The token names the application itself and carries no account scope.", + create: "Create", + save: "Save", + saved: "The application was saved.", + working: "Saving…", + hints: { + web: "https:// addresses; http:// only for a loopback address during development.", + spa: "https:// addresses of the application; http:// only for a loopback address during development. The token endpoint answers the origins of these addresses.", + desktop: + "http:// with a loopback address (http://127.0.0.1:8400/callback), or a private-use scheme (com.example.app:/callback).", + mobile: + "A private-use scheme (com.example.app:/callback), or an https:// address the app claims.", + service: "", + }, + }, + details: { + clientId: "Client identifier", + clientSecret: "Client secret", + created: "Created {date}", + copyNow: + "Copy the secret now. It is stored only as a hash and is never shown again; if it is lost, make a new one.", + noSecret: "This type has no secret: it proves itself with PKCE only.", + secretHeading: "Secret", + rotate: "Make a new client secret", + rotateNote: "The old secret stops working at once.", + deleteHeading: "Delete", + deleteNote: + "Deleting the application ends every authorization and token it holds.", + delete: "Delete the application", + confirmDelete: "Delete this application and end all of its tokens?", + tokenCreated: "Token created", + newSecret: "New client secret", + }, + scopes: { + account: "Know which Progmasoft account you use.", + profile: "Read your Progmasoft account name.", + email: "Read the email address you sign in and registered with.", + "viget.packages.read": "Read the packages you have published on ViGet.", + "viget.packages.publish": "Publish packages to ViGet under your account.", + "viget.packages.yank": "Yank packages you have published on ViGet.", + offline_access: + "Keep this access when you are not using the application.", + }, + consent: { + eyebrow: "Progmasoft OAuth", + title: "Allow {name}?", + wants: "{name} wants to:", + registeredBy: "Registered by {owner}.", + returnTo: "You will be sent back to {origin}.", + signedInAs: "Signed in as {name}.", + withdrawLater: + "You can withdraw this at any time under Allowed applications.", + allow: "Allow", + deny: "Deny", + invalid: + "This request does not name a registered application, address and scopes. Go back to the application and try again.", + }, + allowed: { + eyebrow: "Your account", + title: "Allowed applications", + description: + "Withdrawing ends the application's access and refresh tokens at once; it will have to ask you again.", + empty: "You have not allowed any application.", + since: "Since {date}", + deleted: "A deleted application", + withdraw: "Withdraw", + }, + }, + "de-DE": { + metadata: { + home: "Progmasoft OAuth", + signIn: "Bei Progmasoft OAuth anmelden", + portal: "OAuth-2.1-Tokens", + newToken: "Neues Token", + application: "Anwendung", + consent: "Zugriff erlauben", + allowed: "Erlaubte Anwendungen", + }, + common: { + product: "Progmasoft OAuth", + developers: "OAuth-2.1-Tokens", + console: "Console", + allowedApplications: "Erlaubte Anwendungen", + organization: "Progmasoft", + back: "Zurück", + signIn: "Anmelden", + signOut: "Abmelden", + signedInAs: "Angemeldet als {name}.", + signInRequired: + "Melden Sie sich bei Ihrem Progmasoft-Konto an, um die Tokens Ihrer Anwendungen zu verwalten.", + signInAccount: "Bei Progmasoft anmelden", + loading: "Wird geladen …", + unreachable: + "Progmasoft OAuth ist nicht erreichbar. Versuchen Sie es erneut.", + notFound: "Keine Ihrer Anwendungen hat diese Client-ID.", + }, + home: { + eyebrow: "OAuth 2.1 · OpenID Connect", + title: "Mit Progmasoft anmelden", + description: + "Lassen Sie Menschen sich mit ihrem Progmasoft-Konto bei Ihrer Anwendung anmelden und mit ihrer Zustimmung auf ViGet für sie handeln. Jede Entwicklerin und jeder Entwickler kann ein Token erstellen.", + signedOut: + "Melden Sie sich an, um OAuth-2.1-Tokens für Ihre Anwendungen zu erstellen oder die Anwendungen zu prüfen, denen Sie Zugriff erlaubt haben.", + developersText: "Tokens Ihrer Anwendungen erstellen und verwalten.", + allowedText: "Sehen und widerrufen, was Anwendungen für Sie tun dürfen.", + discovery: "Discovery-Dokument", + }, + signIn: { + eyebrow: "Progmasoft OAuth", + title: "Bei Progmasoft anmelden", + description: + "Verwenden Sie Ihr Progmasoft-Konto. Diese Anmeldung bleibt auf credentials.progmasoft.com; Anwendungen sehen Ihr Passwort nie.", + email: "E-Mail-Adresse", + password: "Passwort", + submit: "Anmelden", + working: "Anmeldung läuft …", + failed: "Die E-Mail-Adresse oder das Passwort ist nicht richtig.", + noAccount: "Noch kein Konto?", + createAccount: "Progmasoft-Konto erstellen", + }, + overview: { + eyebrow: "Progmasoft Console", + title: "Mit Progmasoft entwickeln", + description: + "Verwalten Sie, wie Ihre Anwendungen Progmasoft nutzen: heute die Anmeldung mit Progmasoft-Konten, weitere Progmasoft-Dienste, sobald sie öffnen.", + credentialsText: + "Tokens Ihrer Anwendungen: Web, Single-Page, Desktop, Mobil und Dienst.", + allowedText: "Anwendungen, die für Ihr eigenes Konto handeln dürfen.", + docs: "Entwicklerhandbuch", + docsText: + "Flows, Berechtigungen, Zustimmung und Grenzen von Progmasoft OAuth.", + }, + portal: { + eyebrow: "Entwickler", + title: "OAuth-2.1-Tokens", + description: + "Jedes Token ist eine Anwendung: ihre Client-ID, ihr Secret, falls ihr Typ eines hat, und wohin Menschen nach der Anmeldung zurückkehren.", + newToken: "Neues Token", + empty: "Sie haben noch kein Token.", + limit: "Ein Konto kann {count} Tokens haben.", + endpoints: + "Anwendungen, die Menschen anmelden, verwenden den Authorization-Code-Flow mit PKCE (S256). Das Discovery-Dokument nennt jeden Endpunkt.", + }, + kinds: { + chooseTitle: "Neues Token", + chooseDescription: + "Der Typ bestimmt, wie sich die Anwendung ausweist und wohin Progmasoft OAuth Menschen zurückschicken darf. Er lässt sich später nicht ändern.", + label: "Anwendungstyp", + web: { + title: "Webanwendung", + description: + "Eine Website mit Server. Authorization-Code-Flow mit PKCE und ein Client-Secret, das der Server aufbewahrt.", + }, + spa: { + title: "Single-Page-Anwendung", + description: + "Eine Browser-Anwendung ohne Server, etwa mit React oder Vue. Authorization-Code-Flow mit PKCE, kein Secret; der Token-Endpunkt antwortet ihrem Origin.", + }, + desktop: { + title: "Desktop-Anwendung", + description: + "Ein Desktop- oder Kommandozeilenprogramm. Authorization-Code-Flow mit PKCE, kein Secret; Rückkehr über eine Loopback-Adresse oder ein privates Schema.", + }, + mobile: { + title: "Mobile Anwendung", + description: + "Eine iOS- oder Android-App. Authorization-Code-Flow mit PKCE, kein Secret; Rückkehr über ein privates Schema oder eine beanspruchte https://-Adresse.", + }, + service: { + title: "Dienst", + description: + "Ein Server, der für sich selbst handelt, nicht für eine Person. Client-Credentials-Grant mit Client-Secret; keine Kontoberechtigung und keine Anmeldeseite.", + }, + }, + form: { + name: "Name", + homepage: "Startseite (optional)", + redirectUris: "Weiterleitungsadressen, eine pro Zeile", + postLogoutRedirectUris: + "Adressen nach der Abmeldung (optional), eine pro Zeile", + scopes: "Berechtigungen, die die Anwendung anfragen darf", + scopesNote: + "openid ist immer verfügbar. Jede Person entscheidet weiterhin auf der Zustimmungsseite.", + serviceNote: + "Ein Dienst fragt /connect/token mit grant_type=client_credentials und seinem Secret an. Das Token nennt die Anwendung selbst und trägt keine Kontoberechtigung.", + create: "Erstellen", + save: "Speichern", + saved: "Die Anwendung wurde gespeichert.", + working: "Wird gespeichert …", + hints: { + web: "https://-Adressen; http:// nur für eine Loopback-Adresse während der Entwicklung.", + spa: "https://-Adressen der Anwendung; http:// nur für eine Loopback-Adresse während der Entwicklung. Der Token-Endpunkt antwortet den Origins dieser Adressen.", + desktop: + "http:// mit einer Loopback-Adresse (http://127.0.0.1:8400/callback) oder ein privates Schema (com.example.app:/callback).", + mobile: + "Ein privates Schema (com.example.app:/callback) oder eine https://-Adresse, die die App beansprucht.", + service: "", + }, + }, + details: { + clientId: "Client-ID", + clientSecret: "Client-Secret", + created: "Erstellt am {date}", + copyNow: + "Kopieren Sie das Secret jetzt. Es wird nur als Hash gespeichert und nie wieder angezeigt; erstellen Sie ein neues, wenn es verloren geht.", + noSecret: "Dieser Typ hat kein Secret: Er weist sich nur mit PKCE aus.", + secretHeading: "Secret", + rotate: "Neues Client-Secret erstellen", + rotateNote: "Das alte Secret funktioniert sofort nicht mehr.", + deleteHeading: "Löschen", + deleteNote: + "Das Löschen beendet jede Autorisierung und jedes Token der Anwendung.", + delete: "Anwendung löschen", + confirmDelete: "Diese Anwendung löschen und alle ihre Tokens beenden?", + tokenCreated: "Token erstellt", + newSecret: "Neues Client-Secret", + }, + scopes: { + account: "Wissen, welches Progmasoft-Konto Sie verwenden.", + profile: "Ihren Progmasoft-Kontonamen lesen.", + email: + "Die E-Mail-Adresse lesen, mit der Sie sich angemeldet und registriert haben.", + "viget.packages.read": + "Die Pakete lesen, die Sie auf ViGet veröffentlicht haben.", + "viget.packages.publish": + "Pakete unter Ihrem Konto auf ViGet veröffentlichen.", + "viget.packages.yank": + "Pakete zurückziehen, die Sie auf ViGet veröffentlicht haben.", + offline_access: + "Diesen Zugriff behalten, wenn Sie die Anwendung nicht verwenden.", + }, + consent: { + eyebrow: "Progmasoft OAuth", + title: "{name} erlauben?", + wants: "{name} möchte:", + registeredBy: "Registriert von {owner}.", + returnTo: "Sie werden zu {origin} zurückgeschickt.", + signedInAs: "Angemeldet als {name}.", + withdrawLater: + "Sie können dies jederzeit unter „Erlaubte Anwendungen“ widerrufen.", + allow: "Erlauben", + deny: "Ablehnen", + invalid: + "Diese Anfrage nennt keine registrierte Anwendung, Adresse und Berechtigungen. Kehren Sie zur Anwendung zurück und versuchen Sie es erneut.", + }, + allowed: { + eyebrow: "Ihr Konto", + title: "Erlaubte Anwendungen", + description: + "Der Widerruf beendet die Zugriffs- und Aktualisierungstokens der Anwendung sofort; sie muss Sie erneut fragen.", + empty: "Sie haben noch keiner Anwendung Zugriff erlaubt.", + since: "Seit {date}", + deleted: "Eine gelöschte Anwendung", + withdraw: "Widerrufen", + }, + }, + "ru-RU": { + metadata: { + home: "Progmasoft OAuth", + signIn: "Вход в Progmasoft OAuth", + portal: "Токены OAuth 2.1", + newToken: "Новый токен", + application: "Приложение", + consent: "Разрешить доступ", + allowed: "Разрешённые приложения", + }, + common: { + product: "Progmasoft OAuth", + developers: "Токены OAuth 2.1", + console: "Консоль", + allowedApplications: "Разрешённые приложения", + organization: "Progmasoft", + back: "Назад", + signIn: "Войти", + signOut: "Выйти", + signedInAs: "Вы вошли как {name}.", + signInRequired: + "Войдите в аккаунт Progmasoft, чтобы управлять токенами своих приложений.", + signInAccount: "Войти в Progmasoft", + loading: "Загрузка…", + unreachable: "Progmasoft OAuth недоступен. Попробуйте ещё раз.", + notFound: + "Ни у одного из ваших приложений нет такого идентификатора клиента.", + }, + home: { + eyebrow: "OAuth 2.1 · OpenID Connect", + title: "Вход через Progmasoft", + description: + "Позвольте людям входить в ваше приложение с аккаунтом Progmasoft и с их согласия действовать от их имени в ViGet. Создать токен может любой разработчик.", + signedOut: + "Войдите, чтобы создавать токены OAuth 2.1 для своих приложений или просмотреть приложения, которым вы дали доступ.", + developersText: "Создавайте токены своих приложений и управляйте ими.", + allowedText: + "Смотрите и отзывайте то, что приложениям разрешено делать от вашего имени.", + discovery: "Документ обнаружения", + }, + signIn: { + eyebrow: "Progmasoft OAuth", + title: "Вход в Progmasoft", + description: + "Используйте аккаунт Progmasoft. Этот вход остаётся на credentials.progmasoft.com; приложения никогда не видят ваш пароль.", + email: "Адрес электронной почты", + password: "Пароль", + submit: "Войти", + working: "Выполняется вход…", + failed: "Неверный адрес электронной почты или пароль.", + noAccount: "Ещё нет аккаунта?", + createAccount: "Создать аккаунт Progmasoft", + }, + overview: { + eyebrow: "Progmasoft Console", + title: "Разработка на Progmasoft", + description: + "Управляйте тем, как ваши приложения используют Progmasoft: сегодня вход с аккаунтами Progmasoft, другие сервисы Progmasoft — по мере их открытия.", + credentialsText: + "Токены ваших приложений: веб, одностраничных, настольных, мобильных и сервисов.", + allowedText: + "Приложения, которые могут действовать от имени вашего аккаунта.", + docs: "Руководство разработчика", + docsText: "Потоки, разрешения, согласие и ограничения Progmasoft OAuth.", + }, + portal: { + eyebrow: "Разработчикам", + title: "Токены OAuth 2.1", + description: + "Каждый токен — это одно приложение: его идентификатор клиента, секрет, если он есть у этого типа, и адреса, куда люди возвращаются после входа.", + newToken: "Новый токен", + empty: "У вас ещё нет токенов.", + limit: "У аккаунта может быть не более {count} токенов.", + endpoints: + "Приложения, через которые люди входят, используют поток authorization code с PKCE (S256). Все конечные точки перечислены в документе обнаружения.", + }, + kinds: { + chooseTitle: "Новый токен", + chooseDescription: + "Тип определяет, как приложение подтверждает себя и куда Progmasoft OAuth может возвращать людей. Позже его изменить нельзя.", + label: "Тип приложения", + web: { + title: "Веб-приложение", + description: + "Сайт с сервером. Поток authorization code с PKCE и секрет клиента, который хранит сервер.", + }, + spa: { + title: "Одностраничное приложение", + description: + "Браузерное приложение без сервера, например на React или Vue. Поток authorization code с PKCE, без секрета; конечная точка токенов отвечает его origin.", + }, + desktop: { + title: "Настольное приложение", + description: + "Настольная или консольная программа. Поток authorization code с PKCE, без секрета; возврат через loopback-адрес или собственную схему.", + }, + mobile: { + title: "Мобильное приложение", + description: + "Приложение для iOS или Android. Поток authorization code с PKCE, без секрета; возврат через собственную схему или закреплённый адрес https://.", + }, + service: { + title: "Сервис", + description: + "Сервер, который действует от своего имени, а не от имени человека. Грант client credentials с секретом клиента; без разрешений аккаунта и без страницы входа.", + }, + }, + form: { + name: "Название", + homepage: "Домашняя страница (необязательно)", + redirectUris: "Адреса перенаправления, по одному на строку", + postLogoutRedirectUris: + "Адреса после выхода (необязательно), по одному на строку", + scopes: "Разрешения, которые приложение может запрашивать", + scopesNote: + "openid доступен всегда. Каждый человек всё равно решает сам на странице согласия.", + serviceNote: + "Сервис обращается к /connect/token с grant_type=client_credentials и своим секретом. Токен называет само приложение и не содержит разрешений аккаунта.", + create: "Создать", + save: "Сохранить", + saved: "Приложение сохранено.", + working: "Сохранение…", + hints: { + web: "Адреса https://; http:// только для loopback-адреса во время разработки.", + spa: "Адреса https:// приложения; http:// только для loopback-адреса во время разработки. Конечная точка токенов отвечает origin этих адресов.", + desktop: + "http:// с loopback-адресом (http://127.0.0.1:8400/callback) или собственная схема (com.example.app:/callback).", + mobile: + "Собственная схема (com.example.app:/callback) или адрес https://, закреплённый за приложением.", + service: "", + }, + }, + details: { + clientId: "Идентификатор клиента", + clientSecret: "Секрет клиента", + created: "Создан {date}", + copyNow: + "Скопируйте секрет сейчас. Он хранится только в виде хеша и больше не будет показан; если он потерян, создайте новый.", + noSecret: + "У этого типа нет секрета: приложение подтверждает себя только через PKCE.", + secretHeading: "Секрет", + rotate: "Создать новый секрет клиента", + rotateNote: "Старый секрет сразу перестаёт работать.", + deleteHeading: "Удаление", + deleteNote: + "Удаление приложения прекращает все его авторизации и токены.", + delete: "Удалить приложение", + confirmDelete: "Удалить это приложение и прекратить все его токены?", + tokenCreated: "Токен создан", + newSecret: "Новый секрет клиента", + }, + scopes: { + account: "Знать, каким аккаунтом Progmasoft вы пользуетесь.", + profile: "Видеть имя вашего аккаунта Progmasoft.", + email: + "Видеть адрес электронной почты, с которым вы входите и регистрировались.", + "viget.packages.read": "Видеть пакеты, которые вы опубликовали в ViGet.", + "viget.packages.publish": + "Публиковать пакеты в ViGet от имени вашего аккаунта.", + "viget.packages.yank": + "Отзывать (yank) пакеты, которые вы опубликовали в ViGet.", + offline_access: + "Сохранять этот доступ, когда вы не пользуетесь приложением.", + }, + consent: { + eyebrow: "Progmasoft OAuth", + title: "Разрешить {name}?", + wants: "{name} запрашивает:", + registeredBy: "Зарегистрировано пользователем {owner}.", + returnTo: "Вы вернётесь на {origin}.", + signedInAs: "Вы вошли как {name}.", + withdrawLater: + "Вы можете отозвать это в любое время в разделе «Разрешённые приложения».", + allow: "Разрешить", + deny: "Отклонить", + invalid: + "В этом запросе нет зарегистрированного приложения, адреса и разрешений. Вернитесь в приложение и попробуйте ещё раз.", + }, + allowed: { + eyebrow: "Ваш аккаунт", + title: "Разрешённые приложения", + description: + "Отзыв сразу прекращает токены доступа и обновления приложения; ему придётся спросить вас снова.", + empty: "Вы ещё не дали доступ ни одному приложению.", + since: "С {date}", + deleted: "Удалённое приложение", + withdraw: "Отозвать", + }, + }, + "he-IL": { + metadata: { + home: "Progmasoft OAuth", + signIn: "כניסה ל־Progmasoft OAuth", + portal: "אסימוני OAuth 2.1", + newToken: "אסימון חדש", + application: "אפליקציה", + consent: "מתן גישה", + allowed: "אפליקציות מורשות", + }, + common: { + product: "Progmasoft OAuth", + developers: "אסימוני OAuth 2.1", + console: "קונסולה", + allowedApplications: "אפליקציות מורשות", + organization: "Progmasoft", + back: "חזרה", + signIn: "כניסה", + signOut: "יציאה", + signedInAs: "מחובר/ת בתור {name}.", + signInRequired: + "היכנסו לחשבון Progmasoft שלכם כדי לנהל את אסימוני האפליקציות.", + signInAccount: "כניסה ל־Progmasoft", + loading: "בטעינה…", + unreachable: "אין גישה ל־Progmasoft OAuth. נסו שוב.", + notFound: "לאף אחת מהאפליקציות שלך אין מזהה לקוח כזה.", + }, + home: { + eyebrow: "OAuth 2.1 · OpenID Connect", + title: "כניסה עם Progmasoft", + description: + "אפשרו לאנשים להיכנס לאפליקציה שלכם עם חשבון Progmasoft, ובהסכמתם לפעול עבורם ב־ViGet. כל מפתח/ת יכול/ה ליצור אסימון.", + signedOut: + "היכנסו כדי ליצור אסימוני OAuth 2.1 לאפליקציות שלכם או לעיין באפליקציות שנתתם להן גישה.", + developersText: "יצירה וניהול של אסימוני האפליקציות שלכם.", + allowedText: "צפייה וביטול של מה שאפליקציות רשאיות לעשות עבורכם.", + discovery: "מסמך הגילוי", + }, + signIn: { + eyebrow: "Progmasoft OAuth", + title: "כניסה ל־Progmasoft", + description: + "השתמשו בחשבון Progmasoft. הכניסה הזו נשארת ב־credentials.progmasoft.com; אפליקציות לעולם לא רואות את הסיסמה שלכם.", + email: "כתובת דוא״ל", + password: "סיסמה", + submit: "כניסה", + working: "מתבצעת כניסה…", + failed: "כתובת הדוא״ל או הסיסמה שגויות.", + noAccount: "עדיין אין חשבון?", + createAccount: "יצירת חשבון Progmasoft", + }, + overview: { + eyebrow: "Progmasoft Console", + title: "לבנות על Progmasoft", + description: + "נהלו איך האפליקציות שלכם משתמשות ב־Progmasoft: היום כניסה עם חשבונות Progmasoft, ושירותי Progmasoft נוספים כשייפתחו.", + credentialsText: + "אסימוני האפליקציות שלכם: ווב, עמוד יחיד, שולחן עבודה, נייד ושירות.", + allowedText: "אפליקציות שרשאיות לפעול בשם החשבון שלכם.", + docs: "מדריך למפתחים", + docsText: "זרימות, הרשאות, הסכמה ומגבלות של Progmasoft OAuth.", + }, + portal: { + eyebrow: "מפתחים", + title: "אסימוני OAuth 2.1", + description: + "כל אסימון הוא אפליקציה אחת: מזהה הלקוח שלה, הסוד שלה אם לסוג שלה יש סוד, והכתובות שאליהן אנשים חוזרים אחרי הכניסה.", + newToken: "אסימון חדש", + empty: "עדיין אין לך אסימונים.", + limit: "לחשבון יכולים להיות עד {count} אסימונים.", + endpoints: + "אפליקציות שמכניסות אנשים משתמשות בזרימת authorization code עם PKCE (S256). מסמך הגילוי מפרט כל נקודת קצה.", + }, + kinds: { + chooseTitle: "אסימון חדש", + chooseDescription: + "הסוג קובע איך האפליקציה מזדהה ולאן Progmasoft OAuth רשאי להחזיר אנשים. אי אפשר לשנות אותו אחר כך.", + label: "סוג האפליקציה", + web: { + title: "אפליקציית ווב", + description: + "אתר עם שרת. זרימת authorization code עם PKCE, וסוד לקוח שהשרת שומר.", + }, + spa: { + title: "אפליקציית עמוד יחיד", + description: + "אפליקציית דפדפן בלי שרת, למשל ב־React או Vue. זרימת authorization code עם PKCE, בלי סוד; נקודת הקצה של האסימונים עונה למקור שלה.", + }, + desktop: { + title: "אפליקציית שולחן עבודה", + description: + "תוכנה לשולחן העבודה או לשורת הפקודה. זרימת authorization code עם PKCE, בלי סוד; חזרה דרך כתובת loopback או סכמה פרטית.", + }, + mobile: { + title: "אפליקציה לנייד", + description: + "אפליקציית iOS או Android. זרימת authorization code עם PKCE, בלי סוד; חזרה דרך סכמה פרטית או כתובת https:// שהאפליקציה תובעת.", + }, + service: { + title: "שירות", + description: + "שרת שפועל בשם עצמו, לא בשם אדם. הענקת client credentials עם סוד לקוח; בלי הרשאות חשבון ובלי עמוד כניסה.", + }, + }, + form: { + name: "שם", + homepage: "דף הבית (רשות)", + redirectUris: "כתובות הפניה, אחת בכל שורה", + postLogoutRedirectUris: "כתובות אחרי יציאה (רשות), אחת בכל שורה", + scopes: "הרשאות שהאפליקציה רשאית לבקש", + scopesNote: "openid זמין תמיד. כל אדם עדיין מחליט בעצמו בעמוד ההסכמה.", + serviceNote: + "שירות פונה ל־/connect/token עם grant_type=client_credentials ועם הסוד שלו. האסימון מציין את האפליקציה עצמה ואינו נושא הרשאות חשבון.", + create: "יצירה", + save: "שמירה", + saved: "האפליקציה נשמרה.", + working: "בשמירה…", + hints: { + web: "כתובות https://; http:// רק לכתובת loopback בזמן פיתוח.", + spa: "כתובות https:// של האפליקציה; http:// רק לכתובת loopback בזמן פיתוח. נקודת הקצה של האסימונים עונה למקורות של הכתובות האלה.", + desktop: + "http:// עם כתובת loopback (http://127.0.0.1:8400/callback), או סכמה פרטית (com.example.app:/callback).", + mobile: + "סכמה פרטית (com.example.app:/callback), או כתובת https:// שהאפליקציה תובעת.", + service: "", + }, + }, + details: { + clientId: "מזהה לקוח", + clientSecret: "סוד לקוח", + created: "נוצר ב־{date}", + copyNow: + "העתיקו את הסוד עכשיו. הוא נשמר רק כגיבוב ולא יוצג שוב; אם הוא אבד, צרו סוד חדש.", + noSecret: "לסוג הזה אין סוד: הוא מזדהה רק באמצעות PKCE.", + secretHeading: "סוד", + rotate: "יצירת סוד לקוח חדש", + rotateNote: "הסוד הישן מפסיק לעבוד מיד.", + deleteHeading: "מחיקה", + deleteNote: "מחיקת האפליקציה מסיימת כל הרשאה וכל אסימון שלה.", + delete: "מחיקת האפליקציה", + confirmDelete: "למחוק את האפליקציה הזו ולסיים את כל האסימונים שלה?", + tokenCreated: "האסימון נוצר", + newSecret: "סוד לקוח חדש", + }, + scopes: { + account: "לדעת באיזה חשבון Progmasoft אתם משתמשים.", + profile: "לקרוא את שם חשבון ה־Progmasoft שלכם.", + email: "לקרוא את כתובת הדוא״ל שבה נכנסתם ונרשמתם.", + "viget.packages.read": "לקרוא את החבילות שפרסמתם ב־ViGet.", + "viget.packages.publish": "לפרסם חבילות ב־ViGet בשם החשבון שלכם.", + "viget.packages.yank": "למשוך (yank) חבילות שפרסמתם ב־ViGet.", + offline_access: "לשמור על הגישה הזו גם כשאינכם משתמשים באפליקציה.", + }, + consent: { + eyebrow: "Progmasoft OAuth", + title: "לאשר את {name}?", + wants: "{name} מבקשת:", + registeredBy: "נרשמה על ידי {owner}.", + returnTo: "תוחזרו אל {origin}.", + signedInAs: "מחובר/ת בתור {name}.", + withdrawLater: "אפשר לבטל זאת בכל עת בעמוד „אפליקציות מורשות”.", + allow: "אישור", + deny: "דחייה", + invalid: + "הבקשה הזו אינה מציינת אפליקציה, כתובת והרשאות רשומות. חזרו לאפליקציה ונסו שוב.", + }, + allowed: { + eyebrow: "החשבון שלך", + title: "אפליקציות מורשות", + description: + "ביטול מסיים מיד את אסימוני הגישה והרענון של האפליקציה; היא תצטרך לבקש מכם שוב.", + empty: "עדיין לא נתתם גישה לאף אפליקציה.", + since: "מאז {date}", + deleted: "אפליקציה שנמחקה", + withdraw: "ביטול", + }, + }, +}; + +export function getCredentialsMessages(locale: Locale): CredentialsMessages { + return credentialsMessages[locale]; +} + +/** Fills the `{name}` placeholders of a message. */ +export function format( + message: string, + values: Record<string, string | number>, +): string { + return message.replace(/\{(\w+)\}/g, (placeholder, key: string) => + key in values ? String(values[key]) : placeholder, + ); +} diff --git a/apps/web/lib/credentials.ts b/apps/web/lib/credentials.ts new file mode 100644 index 0000000..f0dab9a --- /dev/null +++ b/apps/web/lib/credentials.ts @@ -0,0 +1,258 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +/** + * Progmasoft OAuth at credentials.progmasoft.com: the types of its JSON + * endpoints and the requests the pages make. + * + * The protocol endpoints (`/connect/*`, `/.well-known/*`) and the JSON + * endpoints (`/api/v1/oauth/*`) belong to the account API on the same host; + * these pages only call them. + */ + +/** The types an application may have, in the order the portal offers them. */ +export const applicationKinds = [ + "web", + "spa", + "desktop", + "mobile", + "service", +] as const; +export type ApplicationKind = (typeof applicationKinds)[number]; + +export function isApplicationKind(value: string): value is ApplicationKind { + return applicationKinds.includes(value as ApplicationKind); +} + +/** Whether applications of a type sign people in, and so register redirection addresses and scopes. */ +export function signsPeopleIn(kind: ApplicationKind): boolean { + return kind !== "service"; +} + +/** The scopes an application may request, in the order the pages list them. */ +export const oauthScopes = [ + "profile", + "email", + "viget.packages.read", + "viget.packages.publish", + "viget.packages.yank", + "offline_access", +] as const; +export type OAuthScope = (typeof oauthScopes)[number]; + +export interface ApplicationView { + clientId: string; + displayName: string; + homepage: string; + kind: ApplicationKind; + isPublic: boolean; + redirectUris: string[]; + postLogoutRedirectUris: string[]; + scopes: string[]; + createdAt: string; +} + +export interface ApplicationList { + applications: ApplicationView[]; + maximum: number; +} + +export interface ApplicationCredentials { + application: ApplicationView; + clientSecret: string | null; +} + +export interface ApplicationSubmission { + kind: ApplicationKind; + displayName: string; + homepage: string; + redirectUris: string[]; + postLogoutRedirectUris: string[]; + scopes: string[]; +} + +export interface AllowedApplication { + authorizationId: string; + displayName: string | null; + scopes: string[]; + createdAt: string | null; +} + +export interface ConsentView { + clientId: string; + displayName: string; + homepage: string; + owner: string | null; + returnTo: string; + scopes: string[]; + accountName: string; +} + +export interface SessionView { + accountName: string; +} + +/** What a request to the JSON endpoints produced. */ +export type ApiResult<T> = + | { kind: "ok"; value: T } + | { kind: "signedOut" } + | { kind: "notFound" } + | { kind: "refused"; errors: Record<string, string>; title?: string } + | { kind: "failed" }; + +interface ProblemDetails { + title?: string; + detail?: string; + errors?: Record<string, string[]>; +} + +/** + * Calls a JSON endpoint of Progmasoft OAuth on this host. + * + * The sign-in cookie of the OAuth host goes with the request; the browser adds + * the `Origin` header the API checks for every request that changes state. + */ +export async function callOAuthApi<T>( + path: string, + init: { method?: string; body?: unknown; signal?: AbortSignal } = {}, +): Promise<ApiResult<T>> { + let response: Response; + try { + response = await fetch(`/api/v1/oauth${path}`, { + method: init.method ?? "GET", + credentials: "same-origin", + headers: + init.body === undefined + ? undefined + : { "Content-Type": "application/json" }, + body: init.body === undefined ? undefined : JSON.stringify(init.body), + signal: init.signal, + }); + } catch { + return { kind: "failed" }; + } + + if (response.status === 401) { + return { kind: "signedOut" }; + } + if (response.status === 404) { + return { kind: "notFound" }; + } + if (response.status === 204) { + return { kind: "ok", value: undefined as T }; + } + if (response.ok) { + return { kind: "ok", value: (await response.json()) as T }; + } + if (response.status === 400) { + const problem = (await response.json().catch(() => ({}))) as ProblemDetails; + const errors: Record<string, string> = {}; + for (const [field, messages] of Object.entries(problem.errors ?? {})) { + if (messages[0]) { + errors[field] = messages[0]; + } + } + return { + kind: "refused", + errors, + title: problem.detail ?? problem.title, + }; + } + return { kind: "failed" }; +} + +/** + * A return address that stays on this host. + * + * The sign-in page sends the account holder back to where they came from, + * usually `/connect/authorize`; anything that would leave the host goes to `/`. + */ +export function localReturnUrl(value: string | null | undefined): string { + if (!value || value[0] !== "/" || value.startsWith("//")) { + return "/"; + } + if (value.startsWith("/\\") || /[\u0000-\u001f]/.test(value)) { + return "/"; + } + return value; +} + +/** The address of the sign-in page that returns to the current page. */ +export function signInPath(returnTo: string): string { + return `/signin?ReturnUrl=${encodeURIComponent(localReturnUrl(returnTo))}`; +} + +/** Splits a text area into its non-empty lines, each once. */ +export function lines(text: string): string[] { + return [ + ...new Set( + text + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0), + ), + ]; +} + +/** Drops the trailing slash of every path but the root. */ +function trimmed(pathname: string): string { + return pathname.length > 1 && pathname.endsWith("/") + ? pathname.slice(0, -1) + : pathname; +} + +/** + * The public pages of authorize.progmasoft.com and the internal routes that + * render them: the home page, sign-in, the consent screen and the allowed + * applications. Nginx sends `/connect` and `/api` of the host to the account + * API; every other path reaches the proxy. + */ +export function authorizeRoute(pathname: string): string | null { + const path = trimmed(pathname); + if (path === "/") { + return "/authorize"; + } + if (path === "/signin" || path === "/consent") { + return `/authorize${path}`; + } + if (path === "/account/applications") { + return "/authorize/applications"; + } + return null; +} + +/** + * The public pages of credentials.progmasoft.com, the issuer: only its home + * page. Its endpoints and discovery documents belong to the account API. + */ +export function issuerRoute(pathname: string): string | null { + return trimmed(pathname) === "/" ? "/issuer" : null; +} + +/** + * The public pages of console.progmasoft.com, the Progmasoft Console, and the + * internal routes that render them: the overview and the OAuth 2.1 + * credentials under `/credentials` (the list, a new token in two steps, one + * application). The console has no sign-in page: it uses the Progmasoft + * account session. + */ +export function consoleRoute(pathname: string): string | null { + const path = trimmed(pathname); + if (path === "/") { + return "/console"; + } + if (path === "/credentials" || path === "/credentials/new") { + return `/console${path}`; + } + const segments = path.split("/"); + if (segments[1] !== "credentials") { + return null; + } + if (segments.length === 4 && segments[2] === "new" && segments[3]) { + return `/console${path}`; + } + if (segments.length === 3 && segments[2]) { + return `/console${path}`; + } + return null; +} diff --git a/apps/web/lib/hosts.server.ts b/apps/web/lib/hosts.server.ts new file mode 100644 index 0000000..758f834 --- /dev/null +++ b/apps/web/lib/hosts.server.ts @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import "server-only"; +import { headers } from "next/headers"; + +/** The hosts of Progmasoft OAuth and the account site they link to. */ +export type ProgmasoftSite = + | "authorize" + | "credentials" + | "console" + | "account"; + +/** The two sites whose pages share the OAuth frame. */ +export type OAuthSite = "authorize" | "console"; + +/** + * The origin of a sibling host of the current request. + * + * authorize.progmasoft.com, credentials.progmasoft.com and + * console.progmasoft.com link to each other. On a development host + * (authorize.localhost:3010) the sibling keeps the scheme and the port, so the + * sites work side by side locally. + */ +export async function siteOrigin(site: ProgmasoftSite): Promise<string> { + const requestHeaders = await headers(); + const host = + requestHeaders.get("x-forwarded-host") ?? requestHeaders.get("host") ?? ""; + const [name = "", port] = host.toLowerCase().split(":", 2); + if (name.endsWith(".localhost")) { + const protocol = requestHeaders.get("x-forwarded-proto") ?? "http"; + return `${protocol}://${site}.localhost${port ? `:${port}` : ""}`; + } + return `https://${site}.progmasoft.com`; +} diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index a9ee327..2aa7e95 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -9,9 +9,19 @@ import { localeCookieOptions, requestHost, } from "@/lib/localization"; +import { authorizeRoute, consoleRoute, issuerRoute } from "@/lib/credentials"; const accountHosts = new Set(["account.progmasoft.com", "account.localhost"]); const vigetHosts = new Set(["viget.progmasoft.com", "viget.localhost"]); +const issuerHosts = new Set([ + "credentials.progmasoft.com", + "credentials.localhost", +]); +const authorizeHosts = new Set([ + "authorize.progmasoft.com", + "authorize.localhost", +]); +const consoleHosts = new Set(["console.progmasoft.com", "console.localhost"]); export function proxy(request: NextRequest) { const host = requestHost( @@ -47,6 +57,36 @@ export function proxy(request: NextRequest) { return response; } + // Progmasoft OAuth serves its own pages and nothing else of the site: the + // account pages keep their own host and cookies. + // Progmasoft OAuth and the Progmasoft Console serve their own pages and + // nothing else of the site: the account pages keep their own host and cookies. + const oauthSite = authorizeHosts.has(host) + ? { route: authorizeRoute, root: "/authorize" } + : issuerHosts.has(host) + ? { route: issuerRoute, root: "/issuer" } + : consoleHosts.has(host) + ? { route: consoleRoute, root: "/console" } + : null; + if (oauthSite) { + if (pathname.startsWith("/api/")) { + return NextResponse.next(); + } + const destination = internalRoute( + request, + oauthSite.route(pathname) ?? `${oauthSite.root}/not-found`, + ); + // The sign-in page reads ReturnUrl and the consent page every parameter + // of the authorization request. + destination.search = request.nextUrl.search; + return NextResponse.rewrite(destination); + } + for (const internal of ["/authorize", "/issuer", "/console"]) { + if (pathname === internal || pathname.startsWith(`${internal}/`)) { + return NextResponse.rewrite(internalRoute(request, "/not-found")); + } + } + // The account root has its own landing page, but authentication and dashboard URLs remain stable and readable. if (accountHosts.has(host) && pathname === "/") { const destination = new URL("/account", request.url); diff --git a/apps/web/tests/credentials.test.mjs b/apps/web/tests/credentials.test.mjs new file mode 100644 index 0000000..70c9318 --- /dev/null +++ b/apps/web/tests/credentials.test.mjs @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + applicationKinds, + authorizeRoute, + consoleRoute, + issuerRoute, + lines, + localReturnUrl, + oauthScopes, + signInPath, +} from "../lib/credentials.ts"; +import { credentialsMessages, format } from "../lib/credentials-messages.ts"; +import { supportedLocales } from "../lib/localization.ts"; + +function shape(value) { + if (typeof value !== "object" || value === null) { + return typeof value; + } + return Object.fromEntries( + Object.keys(value) + .sort() + .map((key) => [key, shape(value[key])]), + ); +} + +test("every language has every message of the OAuth pages", () => { + const english = shape(credentialsMessages["en-US"]); + for (const locale of supportedLocales) { + assert.deepEqual(shape(credentialsMessages[locale]), english, locale); + } +}); + +test("every type and scope has its text in every language", () => { + for (const locale of supportedLocales) { + const messages = credentialsMessages[locale]; + for (const kind of applicationKinds) { + assert.ok(messages.kinds[kind].title, `${locale} ${kind}`); + assert.ok(messages.kinds[kind].description, `${locale} ${kind}`); + } + for (const scope of oauthScopes) { + assert.ok(messages.scopes[scope], `${locale} ${scope}`); + } + } +}); + +test("the pages people see map to the authorize host's routes", () => { + assert.equal(authorizeRoute("/"), "/authorize"); + assert.equal(authorizeRoute("/signin"), "/authorize/signin"); + assert.equal(authorizeRoute("/consent/"), "/authorize/consent"); + assert.equal( + authorizeRoute("/account/applications"), + "/authorize/applications", + ); + for (const path of ["/login", "/register", "/credentials", "/new", "/x"]) { + assert.equal(authorizeRoute(path), null, path); + } +}); + +test("the issuer has its home page only", () => { + assert.equal(issuerRoute("/"), "/issuer"); + for (const path of ["/signin", "/consent", "/account/applications"]) { + assert.equal(issuerRoute(path), null, path); + } +}); + +test("the public pages of the console map to the internal routes", () => { + assert.equal(consoleRoute("/"), "/console"); + assert.equal(consoleRoute("/credentials/"), "/console/credentials"); + assert.equal(consoleRoute("/credentials/new"), "/console/credentials/new"); + assert.equal( + consoleRoute("/credentials/new/spa"), + "/console/credentials/new/spa", + ); + assert.equal( + consoleRoute("/credentials/pmo_abc"), + "/console/credentials/pmo_abc", + ); + for (const path of [ + "/signin", + "/consent", + "/account/applications", + "/new", + "/clients/pmo_abc", + "/credentials/new/spa/x", + "/login", + ]) { + assert.equal(consoleRoute(path), null, path); + } +}); + +test("the sign-in page only returns to this host", () => { + assert.equal( + localReturnUrl("/connect/authorize?client_id=x"), + "/connect/authorize?client_id=x", + ); + for (const value of [ + "//attacker.example", + "/\\attacker.example", + "https://attacker.example/", + "javascript:alert(1)", + "", + null, + undefined, + ]) { + assert.equal(localReturnUrl(value), "/", String(value)); + } + assert.equal( + signInPath("/credentials/new/web"), + "/signin?ReturnUrl=%2Fcredentials%2Fnew%2Fweb", + ); +}); + +test("text areas become distinct addresses and messages fill their placeholders", () => { + assert.deepEqual( + lines(" https://a.example/cb \n\nhttps://a.example/cb\nb "), + ["https://a.example/cb", "b"], + ); + assert.equal(format("Allow {name}?", { name: "Example" }), "Allow Example?"); + assert.equal(format("{count} tokens", { count: 10 }), "10 tokens"); +}); diff --git a/docs/ACCOUNT-API.md b/docs/ACCOUNT-API.md index 68186b5..51648a3 100644 --- a/docs/ACCOUNT-API.md +++ b/docs/ACCOUNT-API.md @@ -120,9 +120,14 @@ to `/login?google=failed`, and the callback path is not a route. | Cookie | Purpose | Attributes | | --- | --- | --- | -| `__Host-ProgmasoftSession` | the account session | `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/`, expires with the session | +| `__Secure-ProgmasoftSession` | the account session | `HttpOnly`, `Secure`, `SameSite=Lax`, `Path=/`, `Domain=progmasoft.com`, expires with the session | | `__Host-ProgmasoftExternal` | carries the Google identity between callback and completion | `HttpOnly`, `Secure`, `SameSite=Lax`, ten minutes | +In production the session cookie is shared with `progmasoft.com`, so that the Progmasoft Console on +`console.progmasoft.com` knows the signed-in account without a sign-in of its own; a cookie with a domain takes the +`__Secure-` prefix instead of `__Host-`. Without `AccountSessions:CookieDomain` the cookie belongs to the account host +alone and keeps the `__Host-` name. + A session token is 256 random bits. The service stores only its SHA-256 digest, so a copy of the store does not contain a usable token. A session lasts 30 days (720 hours) from the sign-in, whether the account signed in with a password or with Google; `AccountSessions:LifetimeHours` changes that, within 1 to 720 hours. @@ -143,7 +148,8 @@ The client address comes from `X-Forwarded-For`, which the service accepts from | Setting | Meaning | Default | | --- | --- | --- | | `AccountSessions:LifetimeHours` | hours a session stays valid, clamped to 1–720 | `720` | -| `AccountSessions:CookieName` | name of the session cookie | `__Host-ProgmasoftSession` | +| `AccountSessions:CookieName` | name of the session cookie | `__Host-ProgmasoftSession`; production `__Secure-ProgmasoftSession` | +| `AccountSessions:CookieDomain` | domain the session cookie is shared with | none; production `progmasoft.com` | | `Authentication:Google:ClientId` | Google OAuth client identifier | empty; Google sign-in is off | | `Authentication:Google:ClientSecret` | Google OAuth client secret | empty; Google sign-in is off | | `AllowedHosts` | host names the service answers | see `appsettings.json` | diff --git a/docs/OAUTH.md b/docs/OAUTH.md index 3b14fde..31a88ac 100644 --- a/docs/OAUTH.md +++ b/docs/OAUTH.md @@ -4,50 +4,71 @@ # Progmasoft OAuth Progmasoft OAuth lets any application sign people in with their Progmasoft account and, with their consent, act on -their behalf. It is an OAuth 2.1 authorization server and an OpenID Connect provider at -`https://credentials.progmasoft.com/`. Any developer with a Progmasoft account can register applications. +their behalf. It is an OAuth 2.1 authorization server and an OpenID Connect provider on three hosts: -## Register an application +| Host | Serves | +| --- | --- | +| `credentials.progmasoft.com` | The issuer (`https://credentials.progmasoft.com/`): discovery documents, key set, and the endpoints clients call directly | +| `authorize.progmasoft.com` | The pages people see: the authorization endpoint with sign-in and the consent screen, the end session endpoint, and the applications an account has allowed | +| `console.progmasoft.com` | The Progmasoft Console, where developers make tokens for their applications | -Sign in at `https://credentials.progmasoft.com/developers` and register the application: +The console has no sign-in of its own: it uses the Progmasoft account session of `account.progmasoft.com`, so any +developer signed in to their Progmasoft account can make tokens there. -| Field | Meaning | -| --- | --- | -| Type | **Confidential** for a server that keeps a client secret; **public** for a browser or native application, which has no secret. The type cannot change later. | -| Name | What the consent page shows, 3 to 64 characters. | -| Homepage | Optional, `https://` only. | -| Redirection addresses | Up to 10, compared exactly. `https://` addresses; `http://` only for a loopback address (`127.0.0.1`, `[::1]`, `localhost`); for public clients also a private-use scheme in reverse DNS order, such as `com.example.app:/callback` (RFC 8252). No fragments, user information or wildcards. | -| Addresses after sign-out | Optional, the same rules; where `/connect/logout` may send the account holder. | -| Scopes | The scopes the application may request; see below. | -| Service access | Allows the client credentials grant; confidential clients only. | - -The portal shows the client identifier (`pmo_…`) and, for a confidential client, the client secret. The secret is -shown once and stored only as a hash; make a new one in the portal if it is lost. An account can register 10 -applications. Deleting an application ends every authorization and token it holds. +## Make a token + +Open **OAuth 2.1 tokens** in the console (`/credentials`), choose **New token**, then the type of the application. The type decides how the application +proves itself, which grants it may use and where people may return; it cannot change later. + +| Type | For | Secret | Grants | Redirection addresses | +| --- | --- | --- | --- | --- | +| Web application | A site with a server | Yes | Authorization code + PKCE, refresh | `https://`; `http://` loopback during development | +| Single-page application | A browser application without a server | No | Authorization code + PKCE, refresh | `https://`; `http://` loopback during development | +| Desktop application | A desktop or command-line program | No | Authorization code + PKCE, refresh | `http://` loopback (`127.0.0.1`, `[::1]`, `localhost`) or a private-use scheme | +| Mobile application | An iOS or Android application | No | Authorization code + PKCE, refresh | A private-use scheme or a claimed `https://` address | +| Service | A server that acts as itself | Yes | Client credentials | None | + +A private-use scheme names the application in reverse DNS order, such as `com.example.app:/callback` (RFC 8252). +Addresses are compared exactly; fragments, user information and wildcards are refused. Up to 10 redirection addresses +and 10 addresses after sign-out (where `/connect/logout` may send the account holder) are registered per application. + +Every type but a service also lists the scopes the application may request (see below); each person still decides on +the consent page. The name (3 to 64 characters) is what the consent page shows; the homepage is optional and +`https://` only. + +The console shows the client identifier (`pmo_…`) and, for a type with a secret, the client secret. The secret is +shown once and stored only as a hash; make a new one in the console if it is lost. An account can have 10 tokens. +Deleting an application ends every authorization and token it holds. + +### Single-page applications + +The token, revocation and user information endpoints answer CORS requests from the origins of the redirection +addresses that single-page applications registered, without credentials. The discovery documents and the key set +answer every origin. ## Endpoints The discovery documents list everything: `/.well-known/openid-configuration` and `/.well-known/oauth-authorization-server`. -| Endpoint | Path | +| Endpoint | Address | | --- | --- | -| Authorization | `/connect/authorize` | -| Token | `/connect/token` | -| User information | `/connect/userinfo` | -| End session | `/connect/logout` | -| Revocation | `/connect/revoke` | -| Introspection | `/connect/introspect` (confidential clients) | -| Key set | `/.well-known/jwks` | +| Authorization | `https://authorize.progmasoft.com/connect/authorize` | +| End session | `https://authorize.progmasoft.com/connect/logout` | +| Token | `https://credentials.progmasoft.com/connect/token` | +| User information | `https://credentials.progmasoft.com/connect/userinfo` | +| Revocation | `https://credentials.progmasoft.com/connect/revoke` | +| Introspection | `https://credentials.progmasoft.com/connect/introspect` (web applications and services) | +| Key set | `https://credentials.progmasoft.com/.well-known/jwks` | ## Flows -- **Authorization code with PKCE**, for every client. `code_challenge_method` must be `S256`; requests without a - challenge, and `plain` challenges, are refused. Confidential clients also authenticate at the token endpoint with - their secret (`client_secret_post` or `client_secret_basic`). +- **Authorization code with PKCE**, for every type but a service. `code_challenge_method` must be `S256`; requests + without a challenge, and `plain` challenges, are refused. Web applications also authenticate at the token endpoint + with their secret (`client_secret_post` or `client_secret_basic`). - **Refresh tokens**, with `offline_access`. Each refresh returns a new refresh token and retires the old one. A retired refresh token that is presented again is treated as stolen: the whole chain of tokens is revoked. -- **Client credentials**, when allowed. The token names the application itself (`sub` is the client identifier) and +- **Client credentials**, for services. The token names the application itself (`sub` is the client identifier) and carries no account scope. The implicit grant, the resource owner password grant and the device flow are not offered. @@ -77,7 +98,7 @@ the application's name, the account that registered it, and the host the account that already holds consent for the requested scopes gets its code without the page, unless it sends `prompt=consent`. `prompt=none` returns `login_required` or `consent_required` instead of showing a page. -Account holders review and withdraw consent at `https://credentials.progmasoft.com/account/applications`. +Account holders review and withdraw consent at `https://authorize.progmasoft.com/account/applications`. Withdrawing ends the application's tokens at once. ## Tokens @@ -95,5 +116,5 @@ their content. ## Limits -The token endpoint, the authorization endpoint and the portal accept 60 requests a minute from one address; the -sign-in form accepts 12 in three minutes. More are answered with 429. +The token endpoint, the authorization endpoint and the console accept 60 requests a minute from one address; the +sign-in forms accept 12 in three minutes. More are answered with 429. diff --git a/docs/README.md b/docs/README.md index e597b08..d681f6d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,7 +10,7 @@ so; [Known limitations](LIMITATIONS.md) collects those places. | --- | --- | | [Architecture](ARCHITECTURE.md) | which process serves which host, how a request travels, and where the trust boundaries are | | [Account API](ACCOUNT-API.md) | every endpoint of the account service: requests, responses, errors, cookies and limits | -| [OAuth](OAUTH.md) | Progmasoft OAuth for developers: registering applications, flows, scopes, consent, tokens and limits | +| [OAuth](OAUTH.md) | Progmasoft OAuth for developers: tokens in the Progmasoft Console, application types, flows, scopes, consent, tokens and limits | | [Localization](LOCALIZATION.md) | which languages are published, how a page picks one, how Hebrew is laid out, and how to add a language | | [Development](DEVELOPMENT.md) | how to run, test and document the project locally, and what each CI check enforces | | [Known limitations](LIMITATIONS.md) | what is deliberately missing or temporary, and what that means for operations | diff --git a/docs/api/namespaces/Progmasoft.OAuth.Api.md b/docs/api/namespaces/Progmasoft.OAuth.Api.md new file mode 100644 index 0000000..6b657d1 --- /dev/null +++ b/docs/api/namespaces/Progmasoft.OAuth.Api.md @@ -0,0 +1,9 @@ +--- +uid: Progmasoft.OAuth.Api +summary: *content +--- + +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 --> + +The JSON endpoints under `/api/v1/oauth` that the pages of credentials.progmasoft.com and console.progmasoft.com call: sign-in, consent, the allowed applications, the applications of the console, and the CORS rule for single-page applications. diff --git a/docs/api/namespaces/Progmasoft.OAuth.Developers.md b/docs/api/namespaces/Progmasoft.OAuth.Developers.md index 503b35e..e9106ab 100644 --- a/docs/api/namespaces/Progmasoft.OAuth.Developers.md +++ b/docs/api/namespaces/Progmasoft.OAuth.Developers.md @@ -6,4 +6,4 @@ summary: *content <!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> <!-- SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 --> -The developer portal: the rules an application registration follows, the registry that keeps applications per account, and the portal pages. +The applications of the Progmasoft Console: their types, the rules each type follows, and the registry that keeps applications per account. diff --git a/docs/api/namespaces/Progmasoft.OAuth.Pages.md b/docs/api/namespaces/Progmasoft.OAuth.Pages.md deleted file mode 100644 index b8700aa..0000000 --- a/docs/api/namespaces/Progmasoft.OAuth.Pages.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -uid: Progmasoft.OAuth.Pages -summary: *content ---- - -<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> -<!-- SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 --> - -The HTML pages of the OAuth host: sign-in, the home page, the applications an account has allowed, and the renderer with its content security policy. diff --git a/ops/README.md b/ops/README.md index 08fa832..1800d5f 100644 --- a/ops/README.md +++ b/ops/README.md @@ -113,10 +113,19 @@ the DNS, TLS, OpenDKIM, Postfix, Dovecot, sender-login, filesystem-permission, a ## Progmasoft OAuth -The account API also serves Progmasoft OAuth, the OAuth 2.1 and OpenID Connect provider, on -`credentials.progmasoft.com` (see [OAuth](../docs/OAUTH.md)). Nginx sends every path of that host to the API; the API -answers OAuth paths only there and nothing else there. The OAuth tables (`oauth_*`) live in the account database and -are created by the API at start, like the account tables. +The account API also serves Progmasoft OAuth, the OAuth 2.1 and OpenID Connect provider (see +[OAuth](../docs/OAUTH.md)), on three hosts. Nginx sends their API paths to the account API and every other path to the +Next.js site: + +| Host | To the account API | Next.js pages | +| --- | --- | --- | +| `credentials.progmasoft.com` (issuer) | `/connect`, `/.well-known`, `/api` | the home page | +| `authorize.progmasoft.com` | `/connect`, `/api` | sign-in, consent, allowed applications | +| `console.progmasoft.com` | `/api` | the Progmasoft Console | + +The API answers only the paths of each host there. The console uses the account session, whose cookie production +shares with `progmasoft.com` (`AccountSessions__CookieDomain`, set in `appsettings.json`). The OAuth tables +(`oauth_*`) live in the account database and are created by the API at start, like the account tables. Production needs two keys, kept outside the releases so that tokens survive a release and a restart: @@ -139,5 +148,6 @@ The service refuses to start in production without them. Replacing the signing k clients still hold; replacing the encryption key invalidates every access token, authorization code and refresh token, so every application has to ask again. Back up both files with the database. -The certificate of `progmasoft.com` must name `credentials.progmasoft.com` as well; expand it with certbot's webroot -plugin before the vhost is enabled, then check `/.well-known/openid-configuration` and the sign-in page from outside. +The certificate of `progmasoft.com` must name `credentials.progmasoft.com`, `authorize.progmasoft.com` and +`console.progmasoft.com` as well; expand it with certbot's webroot plugin before the vhosts are enabled, then check +`/.well-known/openid-configuration`, the sign-in page and the console from outside. diff --git a/ops/nginx/progmaweb.conf b/ops/nginx/progmaweb.conf index fd24489..a775fa5 100644 --- a/ops/nginx/progmaweb.conf +++ b/ops/nginx/progmaweb.conf @@ -187,8 +187,9 @@ server { } # Progmasoft OAuth: the OAuth 2.1 and OpenID Connect provider of Progmasoft -# accounts. Every path goes to the account API, which serves OAuth only on this -# host and nothing else here; its pages set their own content security policy. +# accounts. credentials.progmasoft.com is the issuer: the discovery documents, +# the key set and the endpoints clients call directly go to the account API; +# its home page is a page of the Next.js site. server { listen 80; listen [::]:80; @@ -222,7 +223,138 @@ server { add_header X-Robots-Tag "noindex, nofollow, noarchive" always; add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + # The protocol endpoints, the discovery documents and the JSON endpoints of + # the pages belong to the account API; it answers only OAuth paths here. + location ~ ^/(connect|\.well-known|api)/ { + proxy_pass http://127.0.0.1:5085; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_read_timeout 30s; + } + + # The home page of the issuer is a page of the Progmasoft site. + location / { + proxy_pass http://127.0.0.1:3010; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 60s; + } +} + +# authorize.progmasoft.com: the pages people see in Progmasoft OAuth. The +# authorization and end session endpoints and the JSON paths of the pages go to +# the account API; sign-in, the consent screen and the allowed applications are +# pages of the Next.js site. +server { + listen 80; + listen [::]:80; + server_name authorize.progmasoft.com; + + location ^~ /.well-known/acme-challenge/ { + root /var/lib/letsencrypt; + default_type text/plain; + } + + location / { + return 308 https://authorize.progmasoft.com$request_uri; + } +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name authorize.progmasoft.com; + + ssl_certificate /etc/letsencrypt/live/progmasoft.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/progmasoft.com/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + + client_max_body_size 64k; + + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header X-Robots-Tag "noindex, nofollow, noarchive" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + + # The authorization and end session endpoints and the JSON endpoints of the + # pages belong to the account API; it answers only those here. + location ~ ^/(connect|api)/ { + proxy_pass http://127.0.0.1:5085; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_read_timeout 30s; + } + + # Sign-in, the consent screen and the allowed applications are pages of the + # Progmasoft site. location / { + proxy_pass http://127.0.0.1:3010; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 60s; + } +} + +# The Progmasoft Console: developers make and manage the tokens of their +# applications here, signed in with their Progmasoft account session. The JSON +# paths go to the account API; the pages are pages of the Next.js site. +server { + listen 80; + listen [::]:80; + server_name console.progmasoft.com; + + location ^~ /.well-known/acme-challenge/ { + root /var/lib/letsencrypt; + default_type text/plain; + } + + location / { + return 308 https://console.progmasoft.com$request_uri; + } +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name console.progmasoft.com; + + ssl_certificate /etc/letsencrypt/live/progmasoft.com/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/progmasoft.com/privkey.pem; + include /etc/letsencrypt/options-ssl-nginx.conf; + + client_max_body_size 64k; + + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; + add_header X-Content-Type-Options "nosniff" always; + add_header X-Frame-Options "DENY" always; + add_header X-Robots-Tag "noindex, nofollow, noarchive" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; + + location ^~ /api/ { proxy_pass http://127.0.0.1:5085; proxy_http_version 1.1; proxy_set_header Host $host; @@ -232,4 +364,17 @@ server { proxy_set_header X-Forwarded-Host $host; proxy_read_timeout 30s; } + + location / { + proxy_pass http://127.0.0.1:3010; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $host; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_read_timeout 60s; + } }