Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
13bf2a1
feat: refactor the backend to use XrpcErrorOr<T>.
purifetchi Mar 25, 2025
21b3edf
fix: stop erroring out on this event.
purifetchi Mar 25, 2025
877470d
fix: use the last time_us for playback.
purifetchi Mar 25, 2025
b41ebb5
feat: surround the login in try/catch.
purifetchi Mar 25, 2025
db336a4
refactor: move out models to a shared dll.
purifetchi Mar 26, 2025
4c21585
refactor: implement the XRPC client in a more sane way.
purifetchi Mar 26, 2025
abf20c2
refactor: get rid of all stray Console.WriteLines.
purifetchi Mar 26, 2025
f96d036
refactor: slight refactor of the XRPC handler.
purifetchi Mar 26, 2025
48e5392
feat: invalidation of password auth sessions.
purifetchi Mar 28, 2025
a66e5fc
feat: style the PinkSea AppView info page a bit.
purifetchi Mar 28, 2025
20fd947
docs: expand on the manual running section of the docs.
purifetchi Mar 28, 2025
3c188fe
docs: relicense all libraries under CC0.
purifetchi Mar 28, 2025
c6dfd67
feat: add OAuth2 token revocation.
purifetchi Mar 28, 2025
a03eabf
refactor: better error logging for XRPC handlers.
purifetchi Mar 28, 2025
fb2ebe2
fix: replace '-' with '_' in ToNormalizedTag().
purifetchi Mar 28, 2025
594bee8
docs: further improvements to the docs!
purifetchi Mar 28, 2025
36599fd
chore: add nuget information to library csprojs.
purifetchi Mar 29, 2025
e0b959f
docs: add the footer.
purifetchi Mar 29, 2025
d5a2851
docs: adjust the contributors.
purifetchi Mar 29, 2025
00a77c8
feat: deserialize OAuth errors properly.
purifetchi Mar 30, 2025
1e17f2e
docs: readmes.
purifetchi Mar 30, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Meta/banner.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Meta/footer.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified Meta/screenshot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
145 changes: 121 additions & 24 deletions PinkSea.AtProto.Server/LICENSE
Original file line number Diff line number Diff line change
@@ -1,24 +1,121 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
Creative Commons Legal Code

CC0 1.0 Universal

CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
HEREUNDER.

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without fear
of later claims of infringement build upon, modify, incorporate in other
works, reuse and redistribute as freely as possible in any form whatsoever
and for any purposes, including without limitation commercial purposes.
These owners may contribute to the Commons to promote the ideal of a free
culture and the further production of creative, cultural and scientific
works, or to gain reputation or greater distribution for their Work in
part through the use and efforts of others.

For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under its
terms, with knowledge of his or her Copyright and Related Rights in the
Work and the meaning and intended legal effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not
limited to, the following:

i. the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or
likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data
in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation
thereof, including any amended or successor version of such
directive); and
vii. other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention
of, applicable law, Affirmer hereby overtly, fully, permanently,
irrevocably and unconditionally waives, abandons, and surrenders all of
Affirmer's Copyright and Related Rights and associated claims and causes
of action, whether now known or unknown (including existing as well as
future claims and causes of action), in the Work (i) in all territories
worldwide, (ii) for the maximum duration provided by applicable law or
treaty (including future time extensions), (iii) in any current or future
medium and for any number of copies, and (iv) for any purpose whatsoever,
including without limitation commercial, advertising or promotional
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
member of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal or
equitable action to disrupt the quiet enjoyment of the Work by the public
as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason
be judged legally invalid or ineffective under applicable law, then the
Waiver shall be preserved to the maximum extent permitted taking into
account Affirmer's express Statement of Purpose. In addition, to the
extent the Waiver is so judged Affirmer hereby grants to each affected
person a royalty-free, non transferable, non sublicensable, non exclusive,
irrevocable and unconditional license to exercise Affirmer's Copyright and
Related Rights in the Work (i) in all territories worldwide, (ii) for the
maximum duration provided by applicable law or treaty (including future
time extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"License"). The License shall be deemed effective as of the date CC0 was
applied by Affirmer to the Work. Should any part of the License for any
reason be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the remainder
of the License, and in such case Affirmer hereby affirms that he or she
will not (i) exercise any of his or her remaining Copyright and Related
Rights in the Work or (ii) assert any associated claims and causes of
action with respect to the Work, in either case contrary to Affirmer's
express Statement of Purpose.

4. Limitations and Disclaimers.

a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy, or
the present or absence of errors, whether or not discoverable, all to
the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without
limitation any person's Copyright and Related Rights in the Work.
Further, Affirmer disclaims responsibility for obtaining any necessary
consents, permissions or other rights required for any use of the
Work.
d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to
this CC0 or use of the Work.
10 changes: 10 additions & 0 deletions PinkSea.AtProto.Server/PinkSea.AtProto.Server.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,20 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<OutputType>library</OutputType>
<Authors>shinonome laboratories</Authors>
<Description>An XRPC handler implementation for ASP.NET Core based on top of PinkSea.AtProto.</Description>
<PackageProjectUrl>https://github.com/shinolabs/PinkSea/tree/master/PinkSea.AtProto.Server</PackageProjectUrl>
<PackageLicenseUrl>https://creativecommons.org/public-domain/cc0/</PackageLicenseUrl>
<RepositoryUrl>https://github.com/shinolabs/PinkSea</RepositoryUrl>
<RepositoryType>git</RepositoryType>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\PinkSea.AtProto.Shared\PinkSea.AtProto.Shared.csproj" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion PinkSea.AtProto.Server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,4 @@ Your new query will now be available at `<your url>/xrpc/tld.domain.handlerName`

# Licensing

Unlike the rest of the PinkSea repository, which is EUPL licensed, PinkSea.AtProto is released under the public domain, as described by the Unlicense. Please build on top of it!
Unlike the rest of the PinkSea repository, which is EUPL licensed, PinkSea.AtProto.Server is released under the Creative Commons Zero license, effectively putting it in the public domain. Please build on top of it!
84 changes: 59 additions & 25 deletions PinkSea.AtProto.Server/Xrpc/DefaultXrpcHandler.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,65 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using PinkSea.AtProto.Shared.Models;
using PinkSea.AtProto.Shared.Xrpc;

namespace PinkSea.AtProto.Server.Xrpc;

/// <summary>
/// The default XRPC handler.
/// </summary>
/// <param name="serviceProvider"></param>
public class DefaultXrpcHandler(
IServiceProvider serviceProvider) : IXrpcHandler
{
/// <inheritdoc />
public async Task<object?> HandleXrpc(
public async Task<IXrpcErrorOr?> HandleXrpc(
string nsid,
HttpContext context)
{
var implementationType = XrpcTypeResolver.GetTypeMappingFor(nsid);
if (implementationType is null)
return null;
{
return XrpcErrorOr<object>.Fail(
"NotFound",
$"Did not find a handler for {nsid}",
404);
}

var service = serviceProvider.GetService(implementationType.HandlerType);
if (service is null)
return null;
{
return XrpcErrorOr<object>.Fail(
"NoHandler",
$"No handler was registered for {nsid}.",
500);
}

var requestObject = await GetObjectForType(implementationType, context);
if (requestObject is null)
return null;
if (requestObject.IsError)
{
return XrpcErrorOr<object>.Fail(
"FailedDeserialization",
requestObject.Error!);
}

if (requestObject.Value is null)
{
return XrpcErrorOr<object>.Fail(
"FailedDeserialization",
"An unknown error has occurred while deserializing the call parameters.");
}

var method = service.GetType()
.GetMethod("Handle")!;

var task = (Task)method.Invoke(service, [requestObject])!;
var task = (Task)method.Invoke(service, [requestObject.Value])!;
await task.ConfigureAwait(false);

var resultProperty = task.GetType()
.GetProperty("Result")!;
return resultProperty.GetValue(task);

var errorOr = resultProperty.GetValue(task) as IXrpcErrorOr;
return errorOr;
}

/// <summary>
Expand All @@ -44,30 +68,40 @@ public class DefaultXrpcHandler(
/// <param name="typeMapping">The XRPC type mapping.</param>
/// <param name="context">The HTTP context.</param>
/// <returns>The deserialized object.</returns>
private static async Task<object?> GetObjectForType(
private static async Task<ErrorOr<object?>> GetObjectForType(
XrpcTypeMapping typeMapping,
HttpContext context)
{
// If this is a procedure, we just have to parse JSON. Nice!
if (!typeMapping.IsQuery)
try
{
var json = await JsonSerializer.DeserializeAsync(
context.Request.Body,
typeMapping.RequestType);
// If this is a procedure, we just have to parse JSON. Nice!
if (!typeMapping.IsQuery)
{
var json = await JsonSerializer.DeserializeAsync(
context.Request.Body,
typeMapping.RequestType);

return json;
}
return ErrorOr<object?>.Ok(json);
}

// Dirty hack :3
var queryDict = context
.Request
.Query
.ToDictionary(k => k.Key, v => v.Value.ToString());
// Dirty hack :3
var queryDict = context
.Request
.Query
.ToDictionary(k => k.Key, v => v.Value.ToString());

var queryJson = JsonSerializer.Serialize(queryDict);
return JsonSerializer.Deserialize(queryJson, typeMapping.RequestType, new JsonSerializerOptions(JsonSerializerDefaults.Web)
var queryJson = JsonSerializer.Serialize(queryDict);
return ErrorOr<object?>.Ok(JsonSerializer.Deserialize(
queryJson,
typeMapping.RequestType,
new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
NumberHandling = JsonNumberHandling.AllowReadingFromString
}));
}
catch (JsonException e)
{
NumberHandling = JsonNumberHandling.AllowReadingFromString
});
return ErrorOr<object?>.Fail($"Failed deserializing parameters for XRPC call: {e.Message}");
}
}
}
4 changes: 3 additions & 1 deletion PinkSea.AtProto.Server/Xrpc/IXrpcHandler.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using PinkSea.AtProto.Shared.Xrpc;

namespace PinkSea.AtProto.Server.Xrpc;

/// <summary>
Expand All @@ -11,7 +13,7 @@ public interface IXrpcHandler
/// <param name="nsid">The namespace ID.</param>
/// <param name="context">The HTTP context.</param>
/// <returns>The response from the handler.</returns>
Task<object?> HandleXrpc(
Task<IXrpcErrorOr?> HandleXrpc(
string nsid,
HttpContext context);
}
9 changes: 6 additions & 3 deletions PinkSea.AtProto.Server/Xrpc/IXrpcRequestHandler.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
using PinkSea.AtProto.Shared.Xrpc;

namespace PinkSea.AtProto.Server.Xrpc;

/// <summary>
/// A generic base XRPC request handler.
/// </summary>
/// <typeparam name="TRequest">The type of the request.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
public interface IXrpcRequestHandler<TRequest, TResponse> : IXrpcRequestHandler
public interface IXrpcRequestHandler<TRequest, TResponse>
: IXrpcRequestHandler
{
Task<TResponse?> Handle(TRequest request);
Task<XrpcErrorOr<TResponse>> Handle(TRequest request);
}

/// <summary>
/// The base XRPC request handler type, only for finding which type inherits from which.
/// </summary>
/// </summary>4
public interface IXrpcRequestHandler
{

Expand Down
23 changes: 18 additions & 5 deletions PinkSea.AtProto.Server/Xrpc/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using PinkSea.AtProto.Shared.Xrpc;

namespace PinkSea.AtProto.Server.Xrpc;

Expand Down Expand Up @@ -45,17 +46,29 @@ public static IEndpointRouteBuilder UseXrpcHandler(this IEndpointRouteBuilder ro
return routeBuilder;
}

/// <summary>
/// Handles an XRPC call.
/// </summary>
/// <param name="ctx">The context.</param>
/// <param name="nsid">The namespace ID.</param>
/// <param name="serviceProvider">The service provider.</param>
/// <returns>The result of the xrpc call.</returns>
private static async Task<IResult> HandleXrpc(
HttpContext ctx,
string nsid,
[FromServices] IServiceProvider serviceProvider)
{
var xrpcHandler = serviceProvider.GetRequiredService<IXrpcHandler>();
var result = await xrpcHandler.HandleXrpc(nsid, ctx);
var result = await xrpcHandler.HandleXrpc(nsid, ctx) ?? XrpcErrorOr<object>.Fail(
"InternalServerError",
"An unknown error has occurred.",
500);

if (result.IsSuccess)
return Results.Ok(result.GetUnderlyingObject());

if (result is null)
return Results.BadRequest();

return Results.Ok(result);
return Results.Json(
result.Error,
statusCode: result.Error!.StatusCode ?? 400);
}
}
Loading