R9 Web Push, then the honest version: VAPID key, push subscriptions, encrypted pushes, 4.5.0 advertised

The server's VAPID key (PushKeys, made on first need, in Mongo) is the instance API's vapid.public_key and every app's
vapid_key. /api/v1/push/subscription (POST, GET, PUT, DELETE) keeps one subscription per access token, so per persona;
every notification kept (never a filtered one) is queued as a SendPush job for the subscriptions whose alert and policy
admit it, and sent through the `push` client (the safe handler, https only) encrypted as RFC 8291 aes128gcm or the
aesgcm draft with an ES256 VAPID JWT. 404/410 delete the subscription, 429/5xx/timeouts retry, other answers drop the
push. Subscriptions end with their tokens (revocation, sessions ended, suspension, deletion, a restore); backups hold
neither keys nor subscriptions. The walk of every Mastodon 4.3-4.5 client route (docs/MASTODON-API.md) added
conversations/:id/unread, domain_blocks/preview, v2 notifications clear and PUT policy, /oauth/userinfo and stubs, so both
instance APIs now say 4.5.0 (compatible; PrivaPub <release>). The pasture gets a push sink (pushsink.test) and
scenarios/push.sh in batch A.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WpVCoDeM1qUTRp4fXQdfof
This commit is contained in:
thepraandClaude Opus 5.5 committed 2026-10-18 09:18:26 +02:00
1 parent 87529bca49
commit 9b792042e6
43 files changed
+2079 -49

No files matched your search

+17
View File
@@ -72,6 +72,23 @@ namespace PrivaPub.Api.Mastodon.Auth
options.AddEventHandler<ApplyAuthorizationResponseContext>(builder => builder.UseInlineHandler(OutOfBandCode)
.SetOrder(OpenIddictServerAspNetCoreHandlers.Authentication.ProcessFormPostResponse.Descriptor.Order - 1_000)
.SetType(OpenIddictServerHandlerType.Custom));
// a revoked token takes its Web Push subscription with it (R9), once OpenIddict has revoked it
options.AddEventHandler<HandleRevocationRequestContext>(builder => builder.UseInlineHandler(async context =>
{
if (context.GenericTokenPrincipal?.GetTokenId() is { Length: > 0 } tokenId)
await PrivaPub.Domain.Social.WebPush.ForgetToken(tokenId);
})
.SetOrder(OpenIddictServerHandlers.Revocation.RevokeToken.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.Custom));
// Mastodon 4.4's userinfo (Controllers/UserinfoController), named in the authorization server's metadata
options.AddEventHandler<HandleConfigurationRequestContext>(builder => builder.UseInlineHandler(context =>
{
if (context.Issuer != default)
context.UserInfoEndpoint = new Uri(context.Issuer, Controllers.UserinfoController.Path.TrimStart('/'));
return default;
})
.SetOrder(OpenIddictServerHandlers.Discovery.AttachEndpoints.Descriptor.Order + 1_000)
.SetType(OpenIddictServerHandlerType.Custom));
options.AddEventHandler<ApplyTokenResponseContext>(builder => builder.UseInlineHandler(context =>
{
if (context.Response.AccessToken != default)
@@ -27,6 +27,9 @@ namespace PrivaPub.Api.Mastodon.Auth
public static string FirstPartyClientId(IConfiguration configuration) =>
configuration["ClientApi:FirstPartyClientId"] is { Length: > 0 } clientId ? clientId : "decepub";
// what the first-party client's persona tokens may hold: push since R9, so decePub can subscribe to Web Push
public static readonly string[] FirstPartyScopes = { "read", "write", "follow", "push" };
//the first-party application: public (a browser keeps no secret), token exchange only, no redirect
public static async Task EnsureFirstPartyClient(IServiceProvider services, CancellationToken token)
{
@@ -46,7 +49,7 @@ namespace PrivaPub.Api.Mastodon.Auth
Permissions.GrantTypes.TokenExchange
}
};
foreach (var scopeName in new[] { "read", "write", "follow" })
foreach (var scopeName in FirstPartyScopes)
descriptor.Permissions.Add(Permissions.Prefixes.Scope + scopeName);
var existing = await applications.FindByClientIdAsync(clientId, token);
@@ -70,7 +70,7 @@ namespace PrivaPub.Api.Mastodon.Auth
var identity = new ClaimsIdentity(TokenValidationParameters.DefaultAuthenticationType, Claims.Name, Claims.Role);
identity.SetClaim(Claims.Subject, avatar.ID);
identity.SetClaim(Claims.Name, avatar.UserName);
identity.SetScopes(MastodonScopes.Parse(request.Scope).Intersect(new[] { "read", "write", "follow" }));
identity.SetScopes(MastodonScopes.Parse(request.Scope).Intersect(PersonaExchange.FirstPartyScopes));
identity.SetDestinations(_ => new[] { Destinations.AccessToken });
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
@@ -47,7 +47,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
_outbox = outbox;
}
[HttpGet("/api/v1/accounts/verify_credentials"), Scope("read:accounts")]
// Mastodon 4.4: a token with the profile scope alone may read it too
[HttpGet("/api/v1/accounts/verify_credentials"), Scope("read:accounts|profile")]
public async Task<IActionResult> VerifyCredentials(CancellationToken token) => Json(await _mapper.Local(Me, withSource: true, token));
[HttpPatch("/api/v1/accounts/update_credentials"), Scope("write:accounts"), EnableRateLimiting(RateLimiting.Uploads), RequestSizeLimit(20 * 1024 * 1024),
@@ -398,6 +399,28 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> DomainBlocks(CancellationToken token) =>
Json((await DB.Default.Find<AccountDomainBlock>().Match(b => b.AvatarId == MyId).Sort(b => b.Domain, Order.Ascending).ExecuteAsync(token)).Select(b => b.Domain).ToList());
// Mastodon's preview of a server block: how many of the accounts the persona follows, and of those following it, the
// block would take away, counted as BlockDomain takes them (an account on the server or a subdomain, or whose handle
// is)
[HttpGet("/api/v1/domain_blocks/preview"), Scope("write:blocks")]
public async Task<IActionResult> PreviewDomainBlock(CancellationToken token)
{
var domain = Params.Get("domain")?.Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(domain))
return Error(StatusCodes.Status400BadRequest, "Param is missing or the value is empty: domain");
if (Uri.CheckHostName(domain) != UriHostNameType.Dns)
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Domain is invalid");
var followings = await _dbEntities.Followings.Match(f => f.AvatarId == MyId && !f.TargetIsLocal && f.State == FollowState.Accepted)
.ExecuteAsync(token);
var followers = await _dbEntities.Followers.Match(f => f.LocalActorId == MyId && f.IsAccepted).ExecuteAsync(token);
var handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token);
return Json(new
{
following_count = followings.Count(f => Hidden.Blocks(domain, f.TargetActorURI, handles.GetValueOrDefault(f.TargetActorURI))),
followers_count = followers.Count(f => Hidden.Blocks(domain, f.ActorURI, handles.GetValueOrDefault(f.ActorURI)))
});
}
[HttpPost("/api/v1/domain_blocks"), Scope("write:blocks")]
public async Task<IActionResult> BlockDomain(CancellationToken token)
{
@@ -16,10 +16,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
public class AppsController : MastodonController
{
readonly IOpenIddictApplicationManager _applications;
readonly PrivaPub.Infrastructure.Push.IVapid _vapid;
public AppsController(IOpenIddictApplicationManager applications)
public AppsController(IOpenIddictApplicationManager applications, PrivaPub.Infrastructure.Push.IVapid vapid)
{
_applications = applications;
_vapid = vapid;
}
[HttpPost("/api/v1/apps"), AllowAnonymous]
@@ -69,7 +71,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
RedirectUris = redirects,
RedirectUri = string.Join("\n", redirects),
ClientId = descriptor.ClientId,
ClientSecret = descriptor.ClientSecret
ClientSecret = descriptor.ClientSecret,
VapidKey = (await _vapid.Key(token)).ForApi//Web Push's server key, as Mastodon still gives it here
});
}
@@ -88,7 +91,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
website = properties.TryGetValue("website", out var website) ? website.GetString() : default,
scopes = User.GetScopes().ToList(),
redirect_uris = (await _applications.GetRedirectUrisAsync(application, token)).ToList(),
vapid_key = string.Empty
vapid_key = (await _vapid.Key(token)).ForApi
});
}
@@ -28,7 +28,19 @@ namespace PrivaPub.Api.Mastodon.Controllers
// are enforced.
public class InstanceController : MastodonController
{
public const string Version = "4.2.0 (compatible; PrivaPub)";
// The Mastodon version this API answers as, then PrivaPub's own release (its tag, or the commit a build came from).
// 4.5.0 since R9 (2026-10-18): every client route of Mastodon 4.3, 4.4 and 4.5 is served or answers as a documented
// stub (docs/MASTODON-API.md), streaming and Web Push included. api_versions.mastodon is 4.5's own, 7.
public const string MastodonVersion = "4.5.0";
public static readonly string Version = Advertised(string.IsNullOrEmpty(BuildInfo.Ref) ? BuildInfo.Commit : BuildInfo.Ref);
static string Advertised(string release)
{
var own = release?.Trim();
if (own is { Length: > 1 } && own[0] == 'v' && char.IsDigit(own[1]))
own = own[1..];//a tag v1.27.0 is release 1.27.0
return string.IsNullOrEmpty(own) ? $"{MastodonVersion} (compatible; PrivaPub)" : $"{MastodonVersion} (compatible; PrivaPub {own})";
}
const int ActivityWeeks = 12;
static readonly TimeSpan ActivityLifetime = TimeSpan.FromHours(1);
static volatile CachedActivity _activity;
@@ -39,14 +51,16 @@ namespace PrivaPub.Api.Mastodon.Controllers
readonly IOptionsMonitor<RegistrationOptions> _registrations;
readonly IInstanceSettings _settings;
readonly MastodonMapper _mapper;
readonly PrivaPub.Infrastructure.Push.IVapid _vapid;
public InstanceController(ILocalActorService localActors, IOptionsMonitor<RegistrationOptions> registrations, IInstanceSettings settings,
MastodonMapper mapper)
MastodonMapper mapper, PrivaPub.Infrastructure.Push.IVapid vapid)
{
_localActors = localActors;
_registrations = registrations;
_settings = settings;
_mapper = mapper;
_vapid = vapid;
}
bool Open => _registrations.CurrentValue.IsOpen;
@@ -165,7 +179,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
statuses = Statuses,
media_attachments = MediaAttachments,
polls = Polls,
translation = new { enabled = false }
translation = new { enabled = false },
vapid = new { public_key = (await _vapid.Key(token)).ForApi }//Web Push (R9): the key every push is signed with
},
registrations = new { enabled = Open, approval_required = false, message = Open ? default : RegistrationOptions.ClosedMessage },
contact = new { email = Settings.ContactEmail ?? string.Empty, account = await ContactAccount(Settings, token) },
@@ -69,7 +69,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v2/notifications/policy"), Scope("read:notifications")]
public async Task<IActionResult> Policy(CancellationToken token) => Json(await V2(await NotificationPolicies.Of(MyId, token), token));
[HttpPatch("/api/v2/notifications/policy"), Scope("write:notifications")]
[HttpPatch("/api/v2/notifications/policy"), HttpPut("/api/v2/notifications/policy"), Scope("write:notifications")]
public async Task<IActionResult> SetPolicy(CancellationToken token)
{
var policy = await NotificationPolicies.Of(MyId, token);
@@ -0,0 +1,169 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using MongoDB.Entities;
using OpenIddict.Abstractions;
using OpenIddict.Validation.AspNetCore;
using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Domain.Social;
using PrivaPub.Infrastructure.Http;
using PrivaPub.Infrastructure.Push;
using PrivaPub.Models.Social;
namespace PrivaPub.Api.Mastodon.Controllers
{
// Mastodon's Web Push API (completion program R9): one subscription per access token, so per persona, made, read, changed
// and deleted with the token itself (the `push` scope). Its parameters as Mastodon takes them, as a form or JSON:
// subscription[endpoint], subscription[keys][p256dh], subscription[keys][auth], subscription[standard] (4.4: RFC 8291
// and RFC 8292, else the aesgcm draft), data[alerts][<type>] and data[policy] (all, followed, follower, none). Its answer is
// Mastodon's WebPushSubscription. What is pushed, and how, is WebPushDispatcher's and WebPushJob's.
public class PushController : MastodonController
{
const int MaxEndpointLength = 2048;
readonly IVapid _vapid;
readonly IOptionsMonitor<FederationOptions> _federation;
public PushController(IVapid vapid, IOptionsMonitor<FederationOptions> federation)
{
_vapid = vapid;
_federation = federation;
}
string TokenId => User.GetTokenId();
// a new subscription replaces the one this token had, as on Mastodon
[HttpPost("/api/v1/push/subscription"), Scope("push")]
public async Task<IActionResult> Create(CancellationToken token)
{
var endpoint = Params.Get("subscription[endpoint]")?.Trim();
if (string.IsNullOrEmpty(endpoint))
return Error(StatusCodes.Status400BadRequest, "Param is missing or the value is empty: subscription");
if (endpoint.Length > MaxEndpointLength || !Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || !WebPushJob.IsAllowed(uri, _federation.CurrentValue))
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Endpoint is not a valid URL");
var p256dh = Params.Get("subscription[keys][p256dh]")?.Trim();
var auth = Params.Get("subscription[keys][auth]")?.Trim();
if (string.IsNullOrEmpty(p256dh) || string.IsNullOrEmpty(auth))
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Key p256dh can't be blank, Key auth can't be blank");
if (!WebPushCrypto.AreUsable(WebPushCrypto.FromBase64Url(p256dh), WebPushCrypto.FromBase64Url(auth)))
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Keys are not valid Web Push keys");
var (alerts, policy, invalid) = Data();
if (invalid != default)
return invalid;
var tokenId = TokenId;
var accessToken = await AccessToken();
if (string.IsNullOrEmpty(tokenId) || string.IsNullOrEmpty(accessToken))
return Error(StatusCodes.Status401Unauthorized, "The access token is invalid");
var subscription = new PushSubscription
{
AvatarId = MyId,
TokenId = tokenId,
AccessToken = accessToken,
Endpoint = endpoint,
P256dh = p256dh,
Auth = auth,
Standard = Params.Bool("subscription[standard]") == true,
Alerts = alerts,
Policy = policy
};
// (two at once with one token: the unique index on the token keeps one, and the later replaces it)
for (var attempt = 0; ; attempt++)
{
await WebPush.ForgetToken(tokenId);
try
{
subscription.ID = default;
await DB.Default.SaveAsync(subscription, token);
break;
}
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey && attempt < 2)
{
}
}
return Json(await View(subscription, token));
}
[HttpGet("/api/v1/push/subscription"), Scope("push")]
public async Task<IActionResult> Show(CancellationToken token) =>
await Mine(token) is { } subscription ? Json(await View(subscription, token)) : NotFoundError();
// Mastodon's update: the data given replaces what was there (alerts left out are off, the policy left out is all)
[HttpPut("/api/v1/push/subscription"), Scope("push")]
public async Task<IActionResult> Update(CancellationToken token)
{
var subscription = await Mine(token);
if (subscription == default)
return NotFoundError();
var (alerts, policy, invalid) = Data();
if (invalid != default)
return invalid;
subscription.Alerts = alerts;
subscription.Policy = policy;
subscription.UpdatedAt = DateTime.UtcNow;
await DB.Default.Update<PushSubscription>().MatchID(subscription.ID)
.Modify(s => s.Alerts, alerts)
.Modify(s => s.Policy, policy)
.Modify(s => s.UpdatedAt, subscription.UpdatedAt)
.ExecuteAsync(token);
return Json(await View(subscription, token));
}
[HttpDelete("/api/v1/push/subscription"), Scope("push")]
public async Task<IActionResult> Delete(CancellationToken token)
{
await WebPush.ForgetToken(TokenId);
return Json(new { });
}
async Task<PushSubscription> Mine(CancellationToken token)
{
var tokenId = TokenId;
var avatarId = MyId;
return string.IsNullOrEmpty(tokenId) ? default
: await DB.Default.Find<PushSubscription>().Match(s => s.TokenId == tokenId && s.AvatarId == avatarId).ExecuteFirstAsync(token);
}
// data[alerts][<type>] (each true or false; unknown types are ignored, as Mastodon permits only its own) and
// data[policy]
(List<string> Alerts, PushPolicy Policy, IActionResult Invalid) Data()
{
var alerts = WebPush.Alerts.Where(alert => Params.Bool($"data[alerts][{alert}]") == true).ToList();
var given = Params.Get("data[policy]");
if (string.IsNullOrWhiteSpace(given))
return (alerts, PushPolicy.All, default);
return WebPush.ParsePolicy(given) is { } policy
? (alerts, policy, default)
: (alerts, PushPolicy.All, Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Policy is not included in the list"));
}
// the bearer token of this request, wherever the client put it (OpenIddict takes the header, a form field or the
// query): the payload carries it back, as Mastodon's does
async Task<string> AccessToken()
{
var stored = await HttpContext.GetTokenAsync(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme,
OpenIddictValidationAspNetCoreConstants.Tokens.AccessToken);
if (!string.IsNullOrEmpty(stored))
return stored;
var header = Request.Headers.Authorization.ToString();
if (header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return header["Bearer ".Length..].Trim();
return Params.Get("access_token");
}
// Mastodon's WebPushSubscription
async Task<object> View(PushSubscription subscription, CancellationToken token) => new
{
id = subscription.ID,
endpoint = subscription.Endpoint,
standard = subscription.Standard,
alerts = WebPush.Alerts.ToDictionary(alert => alert, alert => subscription.Alerts.Contains(alert)),
server_key = (await _vapid.Key(token)).ForApi,
policy = WebPush.Name(subscription.Policy)
};
}
}
@@ -140,9 +140,6 @@ namespace PrivaPub.Api.Mastodon.Controllers
public class StubsController : MastodonController
{
[HttpGet("/api/v1/push/subscription"), Scope("push")]
public IActionResult PushSubscription() => Error(StatusCodes.Status404NotFound, "Record not found");
// Routes Mastodon answers that we have nothing behind: an empty or default answer lets clients degrade, where a
// 404 breaks some of them (Mastodon invariant 5)
[HttpGet("/api/v1/timelines/link"), Microsoft.AspNetCore.Authorization.AllowAnonymous]
@@ -163,9 +160,35 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpPost("/api/v1/statuses/{id}/translate"), Scope("read:statuses")]
public IActionResult Translate(string id) => Error(StatusCodes.Status422UnprocessableEntity, "Translation is not available on this server");
// Mastodon 4.3's yearly reports (Wrapstodon): none are made here, so there are never any to show
[HttpGet("/api/v1/annual_reports"), Scope("read:accounts")]
public IActionResult AnnualReports() => Json(new { annual_reports = Array.Empty<object>(), accounts = Array.Empty<object>(), statuses = Array.Empty<object>() });
// Mastodon 4.3's yearly reports (Wrapstodon): none are made here, so there are never any to show, for any year (4.4's
// show), and marking one read changes nothing
[HttpGet("/api/v1/annual_reports"), HttpGet("/api/v1/annual_reports/{year}"), Scope("read:accounts")]
public IActionResult AnnualReports(string year) => Json(new { annual_reports = Array.Empty<object>(), accounts = Array.Empty<object>(), statuses = Array.Empty<object>() });
[HttpPost("/api/v1/annual_reports/{year}/read"), Scope("write:accounts")]
public IActionResult ReadAnnualReport(string year) => Json(new { });
// Registration through the API is cut (owner decision 2026-10-17): a login is made by setup or an invitation, on
// /clientapi. Mastodon answers this when its registrations are closed; its e-mail confirmation routes follow, since no
// account here waits for one
[HttpPost("/api/v1/accounts"), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public IActionResult Register() => Error(StatusCodes.Status403Forbidden, "This action is not allowed");
[HttpPost("/api/v1/emails/confirmations"), Scope("write:accounts")]
public IActionResult ResendConfirmation() =>
Error(StatusCodes.Status403Forbidden, "This method is only available while the e-mail is awaiting confirmation");
[HttpGet("/api/v1/emails/check_confirmation"), Scope("read:accounts")]
public IActionResult CheckConfirmation() => Json(true);
// the peers' names are not published (/instance/peers stays empty), so a search of them finds none
[HttpGet("/api/v1/peers/search"), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public IActionResult SearchPeers() => Json(Array.Empty<string>());
// Mastodon 4.4's asynchronous refreshes are announced by a Mastodon-Async-Refresh header, which PrivaPub never sends
// (a thread's replies are read again in the background and simply show up): there is never one to ask about
[HttpGet("/api/v1_alpha/async_refreshes/{id}"), Scope("read")]
public IActionResult AsyncRefresh(string id) => NotFoundError();
// the Mastodon admin API is cut: moderation stays on /clientapi (ModeratorController, AdminController), so every
// admin route answers as Mastodon answers an account that may not use it, whoever asks
@@ -177,6 +177,18 @@ namespace PrivaPub.Api.Mastodon.Controllers
return Json(conversation ?? new Conversation { Id = group.ID });
}
// Mastodon's unread (R9): shown unread again until it is read
[HttpPost("/api/v1/conversations/{id}/unread"), Scope("write:conversations")]
public async Task<IActionResult> UnreadConversation(string id, CancellationToken token)
{
var group = await MyConversation(id, token);
if (group == default)
return NotFoundError();
await ConversationStates.Unread(MyId, group.ID, token);
var conversation = (await ConversationsOf(new List<DmGroup> { group }, token)).FirstOrDefault();
return Json(conversation ?? new Conversation { Id = group.ID, Unread = true });
}
// off the persona's list until a newer message; the messages themselves stay
[HttpDelete("/api/v1/conversations/{id}"), Scope("write:conversations")]
public async Task<IActionResult> RemoveConversation(string id, CancellationToken token)
@@ -410,7 +422,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return mapped == default ? NotFoundError() : Json(mapped);
}
[HttpPost("/api/v1/notifications/clear"), Scope("write:notifications")]
[HttpPost("/api/v1/notifications/clear"), HttpPost("/api/v2/notifications/clear"), Scope("write:notifications")]
public async Task<IActionResult> Clear(CancellationToken token)
{
await DB.Default.DeleteAsync<NotificationEntity>(n => n.AvatarId == MyId);
@@ -0,0 +1,40 @@
using Microsoft.AspNetCore.Mvc;
using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Federation.Actors;
namespace PrivaPub.Api.Mastodon.Controllers
{
// Mastodon 4.4's OAuth userinfo (OpenID Connect's shape, GET or POST, the `profile` scope): who the token's persona is,
// for a site that signs in with it. Only what its public account says already; never its login. The authorization
// server's metadata names it (OAuthSetup).
public class UserinfoController : MastodonController
{
public const string Path = "/oauth/userinfo";
readonly MastodonMapper _mapper;
readonly ILocalActorService _localActors;
public UserinfoController(MastodonMapper mapper, ILocalActorService localActors)
{
_mapper = mapper;
_localActors = localActors;
}
[HttpGet(Path), HttpPost(Path), Scope("profile")]
public async Task<IActionResult> Show(CancellationToken token)
{
var account = await _mapper.Local(Me, false, token);
return Json(new
{
iss = _localActors.BaseAddress + "/",
sub = Me.Uri,
name = account.DisplayName,
preferred_username = account.Username,
profile = account.Url,
picture = account.Avatar
});
}
}
}
@@ -48,7 +48,8 @@ namespace PrivaPub.Api.Mastodon.Infrastructure
var scope = context.ActionDescriptor.EndpointMetadata.OfType<ScopeAttribute>().LastOrDefault();
if (User.Identity?.IsAuthenticated == true)
{
if (scope != default && !MastodonScopes.Grants(User.GetScopes(), scope.Scope))
// (a scope written a|b is either)
if (scope != default && !scope.Scope.Split('|').Any(one => MastodonScopes.Grants(User.GetScopes(), one)))
{
context.Result = Error(StatusCodes.Status403Forbidden, "This action is outside the authorized scopes");
return;