v4: users sign in to one gerbeur instance with their account on another — topic instances, each with its own admins, domain and data, had no way to share accounts. Sign-in is federated over a subset of OpenID Connect, the authorization code flow with PKCE: each instance is an identity provider for its own users and a client for the others', and signs what it tells them with an Ed25519 key kept in federation_keys and published at /.well-known/jwks.json, beside its metadata at /.well-known/openid-configuration. Only sign-in is federated: an account from another instance is a local users row linked to (issuer, subject) in user_identities, with no password (password_hash ''), so sessions, roles, permissions, the socket and every foreign key work as before.
A remote user is name@host here, in users.username, in paths (/@alice@music.example) and in mentions, through one handle rule in shared/validation.ts that paths, MENTION_RE and Markdown all build on; Markdown undoes GFM's email autolink of a handle. Their name, email and avatar come from their home at each sign-in and by its signed events (federation_outbox, delivered by the federation job with backoff): a rename at home leaves the old handle an alias here, and a password change or a withdrawn grant ends their sessions here. Their password, email, avatar and name can't change here (assertLocalUser), nor can they sign in elsewhere from here. An admin keeps the trusted and blocked instances on /manage (federation:manage): a trusted instance's users sign in from a button on the login page, a blocked one's can't and are signed out at once, and any other's join with an invite from the register page. The /authorize page asks the user once per instance, and /settings lists the instances their account signs in to, each disconnectable; /login?next= brings a signed-out visitor back to /authorize. Emails stay unique among local accounts only, and migration 0024 adds the tables, makes that index partial and reserves authorize and federation as category slugs. remote/gerbeur-instance.ts is the only way to other instances: https and public addresses only, no redirects, no certificate fallback, unless GERBEUR_FEDERATION_ALLOW_PRIVATE lets two instances on one machine talk. 298 backend tests and 702 frontend tests pass, and deno check, deno fmt, deno lint, tsc, eslint, doc:lint and i18n:compile --strict are clean; checked end to end with two built instances on one machine: sign-in through the other's login and consent pages, consent skipped once granted and asked again after disconnecting, a rename and a password change at home reaching the other, and blocking; screenshots of the login, consent, profile, settings and manage pages at 1280 and 390px. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -71,6 +71,11 @@ GERBEUR_DEFAULT_STYLE=smooth
|
||||
# How often, in minutes, the /community page's figures are recomputed.
|
||||
GERBEUR_COMMUNITY_REFRESH_MINUTES=15
|
||||
|
||||
# Set to 1 to let federated sign-in reach other instances on private addresses
|
||||
# (localhost included) and over plain http, so that two instances on one
|
||||
# machine can trust each other in development. Never in production.
|
||||
# GERBEUR_FEDERATION_ALLOW_PRIVATE=1
|
||||
|
||||
# Markdown body of the welcome email sent on account creation, replacing the
|
||||
# built-in one (written in GERBEUR_EMAIL_LOCALE). Supports {{username}} and
|
||||
# {{site_name}}. Use \n for line breaks in single-line .env values, or a
|
||||
|
||||
210
API.md
210
API.md
@@ -1,44 +1,47 @@
|
||||
# gerbeur's URLs
|
||||
|
||||
Every page and every API endpoint follows one of two rules. This file
|
||||
summarizes them. Each router's module doc in `api/routes/` lists its own
|
||||
endpoints in full, and a route change updates both. `shared/paths.ts` builds
|
||||
and parses the page paths.
|
||||
Every page and every API endpoint follows one of two rules. This file summarizes
|
||||
them. Each router's module doc in `api/routes/` lists its own endpoints in full,
|
||||
and a route change updates both. `shared/paths.ts` builds and parses the page
|
||||
paths.
|
||||
|
||||
## The two rules
|
||||
|
||||
**Pages.** The path is a hierarchy. `@name` is a user. Any other word under
|
||||
the root is a category or an app page. Under a user, each segment is a fixed
|
||||
tab name, and under `dumps` or `playlists`, a slug. A view of a page is one
|
||||
more segment. A default view is the bare path, with no redirect.
|
||||
**Pages.** The path is a hierarchy. `@name` is a user, and `@name@host` a user
|
||||
whose account lives on another instance. Any other word under the root is a
|
||||
category or an app page. Under a user, each segment is a fixed tab name, and
|
||||
under `dumps` or `playlists`, a slug. A view of a page is one more segment. A
|
||||
default view is the bare path, with no redirect.
|
||||
|
||||
**API.** A resource is `/api/<plural>/<key>[/<noun>]`. Its key is its id,
|
||||
except a user's, which may also be `@name`. The `@` keeps the two apart, so no
|
||||
regex sniffing is needed. A read by page path mirrors the page:
|
||||
**API.** A resource is `/api/<plural>/<key>[/<noun>]`. Its key is its id, except
|
||||
a user's, which may also be `@name`. The `@` keeps the two apart, so no regex
|
||||
sniffing is needed. A read by page path mirrors the page:
|
||||
`/api/users/@bob/dumps/<slug>`. The caller's own things live under `/api/me`.
|
||||
Media is a sub-resource. A lookup by another key is a query filter. Each
|
||||
concept has one word, the same as in pages.
|
||||
Media is a sub-resource. A lookup by another key is a query filter. Each concept
|
||||
has one word, the same as in pages.
|
||||
|
||||
## Pages
|
||||
|
||||
| Path | Views | Access | Page |
|
||||
|---|---|---|---|
|
||||
| `/` | `/hot`, `/new`, `/journal`, `/follow`; the bare `/` is the viewer's default tab | anyone, `/follow` signed in | `Index` |
|
||||
| `/<category>` | `/<category>/hot`, `/new`, `/journal`, `/follow` | anyone | `Index` |
|
||||
| `/@<name>` | the overview: dumps beside upvoted | anyone | `UserPublicProfile` |
|
||||
| `/@<name>/dumps`, `/upvoted`, `/playlists`, `/invitees` | | anyone | `UserPublicProfile` |
|
||||
| `/@<name>/follow` | `/@<name>/follow/playlists`; the bare tab lists users | anyone | `UserPublicProfile` |
|
||||
| `/@<name>/manage` | | `user:manage`, on others' profiles | `UserPublicProfile` |
|
||||
| `/@<name>/dumps/<slug>` | | anyone; a private dump, its poster | `Dump` |
|
||||
| `/@<name>/dumps/<slug>/edit` | | its poster, `dump:moderate` | `DumpEdit` |
|
||||
| `/@<name>/playlists/<slug>` | | anyone; a private playlist, its owner | `PlaylistDetail` |
|
||||
| `/search?q=` | `/search/users?q=`, `/search/playlists?q=` | anyone | `Search` |
|
||||
| `/notifications` | | signed in | `Notifications` |
|
||||
| `/community` | `/community/monthly`; the bare path is the week | signed in | `Community` |
|
||||
| `/settings` | | signed in | `Settings` |
|
||||
| `/manage` | | `category:manage` | `Manage` |
|
||||
| `/login`, `/register?token=` | | signed out | `UserLogin`, `UserRegister` |
|
||||
| `/reset-password?token=`, `/unsubscribe?token=` | | anyone | `ResetPassword`, `Unsubscribe` |
|
||||
| Path | Views | Access | Page |
|
||||
| ------------------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------- | ------------------------------ |
|
||||
| `/` | `/hot`, `/new`, `/journal`, `/follow`; the bare `/` is the viewer's default tab | anyone, `/follow` signed in | `Index` |
|
||||
| `/<category>` | `/<category>/hot`, `/new`, `/journal`, `/follow` | anyone | `Index` |
|
||||
| `/@<name>` | the overview: dumps beside upvoted | anyone | `UserPublicProfile` |
|
||||
| `/@<name>/dumps`, `/upvoted`, `/playlists`, `/invitees` | | anyone | `UserPublicProfile` |
|
||||
| `/@<name>/follow` | `/@<name>/follow/playlists`; the bare tab lists users | anyone | `UserPublicProfile` |
|
||||
| `/@<name>/manage` | | `user:manage`, on others' profiles | `UserPublicProfile` |
|
||||
| `/@<name>/dumps/<slug>` | | anyone; a private dump, its poster | `Dump` |
|
||||
| `/@<name>/dumps/<slug>/edit` | | its poster, `dump:moderate` | `DumpEdit` |
|
||||
| `/@<name>/playlists/<slug>` | | anyone; a private playlist, its owner | `PlaylistDetail` |
|
||||
| `/search?q=` | `/search/users?q=`, `/search/playlists?q=` | anyone | `Search` |
|
||||
| `/notifications` | | signed in | `Notifications` |
|
||||
| `/community` | `/community/monthly`; the bare path is the week | signed in | `Community` |
|
||||
| `/settings` | | signed in | `Settings` |
|
||||
| `/manage` | | `category:manage`, `federation:manage` | `Manage` |
|
||||
| `/login`, `/register?token=` | `/login?next=<path>` comes back to a page | signed out | `UserLogin`, `UserRegister` |
|
||||
| `/authorize?client_id=…` | | signed in, else via `/login?next=` | `Authorize` |
|
||||
| `/federation/callback?code=&state=` | | anyone | `FederationCallback` |
|
||||
| `/reset-password?token=`, `/unsubscribe?token=` | | anyone | `ResetPassword`, `Unsubscribe` |
|
||||
|
||||
`/?share_url=` opens the create form on a link shared from Android,
|
||||
`/?chat=open` opens the chat over any page, and `#comment-<id>` scrolls a dump's
|
||||
@@ -46,39 +49,44 @@ page to a comment.
|
||||
|
||||
## Names
|
||||
|
||||
- **Slugs** of categories, dumps and playlists are lowercase letters and
|
||||
digits in words joined by single hyphens (`shared/slug.ts`). A category's is
|
||||
at most 50 characters, a dump's or a playlist's at most 60.
|
||||
- **Slugs** of categories, dumps and playlists are lowercase letters and digits
|
||||
in words joined by single hyphens (`shared/slug.ts`). A category's is at most
|
||||
50 characters, a dump's or a playlist's at most 60.
|
||||
- **A dump's or a playlist's slug** is made from its title when it is created,
|
||||
unique among its owner's items of that kind: a clash gets `-2`, `-3`. It
|
||||
changes only when someone edits it: the edit forms propose
|
||||
`slugify(newTitle)` when the title changes. Its owner may change it 3 times
|
||||
a day; moderators (`dump:moderate`, `playlist:moderate`) may edit any slug,
|
||||
at any time.
|
||||
- **A username** is 1 to 32 letters, digits and underscores, unique in any
|
||||
case. A page writes it in its stored case, and another case still resolves.
|
||||
Users can't rename themselves: those with `user:manage` rename anyone, from
|
||||
changes only when someone edits it: the edit forms propose `slugify(newTitle)`
|
||||
when the title changes. Its owner may change it 3 times a day; moderators
|
||||
(`dump:moderate`, `playlist:moderate`) may edit any slug, at any time.
|
||||
- **A username** is 1 to 32 letters, digits and underscores, unique in any case.
|
||||
A page writes it in its stored case, and another case still resolves. Users
|
||||
can't rename themselves: those with `user:manage` rename anyone, from
|
||||
`/@<name>/manage`.
|
||||
- **A user from another instance** is `name@host` here: their name at home and
|
||||
their home's host, with its port if it has one (`alice@music.example`). Their
|
||||
name is their home's to change, which leaves the old handle an alias here too.
|
||||
Mentions write the whole handle.
|
||||
- **Aliases.** A slug or a name left behind stays an alias for good, which
|
||||
always names the item or user itself, so redirects never chain. Nobody else
|
||||
can take one. An item can take back one of its own. Deleting an item frees
|
||||
its aliases.
|
||||
- **Redirects.** A page reached by an alias, or by a name in another case,
|
||||
gets the item from the API under its current path and replaces its URL.
|
||||
The server answers the same path with a 301 to crawlers and full page loads.
|
||||
can take one. An item can take back one of its own. Deleting an item frees its
|
||||
aliases.
|
||||
- **Redirects.** A page reached by an alias, or by a name in another case, gets
|
||||
the item from the API under its current path and replaces its URL. The server
|
||||
answers the same path with a 301 to crawlers and full page loads.
|
||||
- **Reserved words.** A category can't take a word the root already uses:
|
||||
`hot new journal follow search login register notifications reset-password
|
||||
unsubscribe settings manage community api ws assets emojibase`
|
||||
(`api/lib/reserved-slugs.ts`). Dump and playlist slugs reserve nothing, and
|
||||
no slug has an `@`.
|
||||
unsubscribe settings manage community authorize federation api ws assets
|
||||
emojibase`
|
||||
(`api/lib/reserved-slugs.ts`). Dump and playlist slugs reserve nothing, and no
|
||||
slug has an `@`.
|
||||
|
||||
## API
|
||||
|
||||
Every JSON endpoint answers the envelope of `shared/api.ts`:
|
||||
`{ "success": true, "data": … }`, or `{ "success": false, "error": { "code",
|
||||
"message" } }` with the matching HTTP status. A list answers
|
||||
`{ "items", "hasMore" }` and takes `?page=` (from 1) and `?limit=` (20 by
|
||||
default, 100 at most). "Signed in" means a session token as
|
||||
`{ "success": true, "data": … }`, or
|
||||
`{ "success": false, "error": { "code",
|
||||
"message" } }` with the matching HTTP
|
||||
status. A list answers `{ "items", "hasMore" }` and takes `?page=` (from 1) and
|
||||
`?limit=` (20 by default, 100 at most). "Signed in" means a session token as
|
||||
`Authorization: Bearer …`. Media can't send a header, so a private file,
|
||||
thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
`?token=`.
|
||||
@@ -89,19 +97,25 @@ thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
- `PATCH /api/me` — signed in. Changes the description and email.
|
||||
- `GET /api/me/media-token` — signed in. A media token.
|
||||
- `GET`, `PATCH /api/me/settings` — signed in. The caller's settings.
|
||||
- `PUT /api/me/password` — signed in, with the current one. A new password,
|
||||
and fresh tokens.
|
||||
- `PUT /api/me/password` — signed in, with the current one. A new password, and
|
||||
fresh tokens.
|
||||
- `PUT /api/me/avatar` — signed in. A new avatar (multipart).
|
||||
- `GET /api/me/playlists?contains=:dumpId` — signed in. The caller's
|
||||
playlists, and whether each holds the dump.
|
||||
- `GET /api/me/follow` — signed in. The ids of the users and playlists
|
||||
followed.
|
||||
- `GET /api/me/playlists?contains=:dumpId` — signed in. The caller's playlists,
|
||||
and whether each holds the dump.
|
||||
- `GET /api/me/follow` — signed in. The ids of the users and playlists followed.
|
||||
- `PUT`, `DELETE /api/me/follow/users/:id`, `/api/me/follow/playlists/:id` —
|
||||
signed in. Follows or stops following.
|
||||
- `GET /api/me/feed?from=users|playlists&category=` — signed in. The dumps of
|
||||
what the caller follows.
|
||||
- `GET /api/me/notifications` — signed in. The caller's notifications.
|
||||
- `POST /api/me/notifications/read` — signed in. Marks them all read.
|
||||
- `GET /api/me/grants` — signed in. The other instances the caller's account
|
||||
signs in to.
|
||||
- `DELETE /api/me/grants/:host` — signed in. Withdraws one, ending the caller's
|
||||
sessions there.
|
||||
|
||||
An account from another instance changes its password, email, avatar and name
|
||||
there: those endpoints answer it 400.
|
||||
|
||||
### users
|
||||
|
||||
@@ -109,10 +123,10 @@ thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
- `GET /api/users?q=` — anyone. Up to 8 users whose name starts with `q`.
|
||||
- `GET /api/users/:key` — anyone. A profile.
|
||||
- `GET /api/users/:key/avatar` — anyone. The avatar.
|
||||
- `GET /api/users/:key/dumps`, `/upvoted`, `/playlists` — anyone; private
|
||||
items to their owner only. Their lists.
|
||||
- `GET /api/users/:key/dumps/:slug`, `/playlists/:slug` — anyone; private
|
||||
items to their owner only. An item by its page path, by an alias too.
|
||||
- `GET /api/users/:key/dumps`, `/upvoted`, `/playlists` — anyone; private items
|
||||
to their owner only. Their lists.
|
||||
- `GET /api/users/:key/dumps/:slug`, `/playlists/:slug` — anyone; private items
|
||||
to their owner only. An item by its page path, by an alias too.
|
||||
- `GET /api/users/:key/follow/users`, `/follow/playlists` — anyone. What they
|
||||
follow.
|
||||
- `GET /api/users/:key/invitees` — anyone. The tree of users they invited.
|
||||
@@ -125,16 +139,16 @@ thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
- `GET /api/dumps` — anyone. The feed; `?category=<slug>` narrows it, and
|
||||
`?url=` answers the dumps of the same link instead.
|
||||
- `GET /api/dumps/:id` — anyone who may see it. A dump.
|
||||
- `GET /api/dumps/:id/voters`, `/related`, `/playlists` — the same. Who
|
||||
upvoted it, the dumps linked to or from it, the playlists holding it.
|
||||
- `GET /api/dumps/:id/voters`, `/related`, `/playlists` — the same. Who upvoted
|
||||
it, the dumps linked to or from it, the playlists holding it.
|
||||
- `PUT /api/dumps/:id` — its poster, `dump:moderate`. Title, slug, note,
|
||||
visibility, categories, link.
|
||||
- `POST /api/dumps/:id/metadata` — the same. Fetches a link's preview again.
|
||||
- `DELETE /api/dumps/:id` — the same. Deletes it.
|
||||
- `GET`, `PUT /api/dumps/:id/file` — the file; a new one, by its poster or
|
||||
`dump:moderate`.
|
||||
- `GET`, `PUT`, `DELETE /api/dumps/:id/thumbnail` — the thumbnail; a custom
|
||||
one, set or removed by its poster or `dump:moderate`.
|
||||
- `GET`, `PUT`, `DELETE /api/dumps/:id/thumbnail` — the thumbnail; a custom one,
|
||||
set or removed by its poster or `dump:moderate`.
|
||||
- `GET /api/dumps/:id/waveform` — anyone who may see it. An audio file's
|
||||
waveform, `{ "peaks" }`, for the player to seek on.
|
||||
- `GET`, `POST /api/dumps/:id/comments` — anyone who may see the dump; posting
|
||||
@@ -144,18 +158,18 @@ thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
|
||||
- `POST /api/playlists` — signed in. Creates a playlist.
|
||||
- `GET /api/playlists/:id` — anyone who may see it. A playlist and its dumps.
|
||||
- `PUT`, `DELETE /api/playlists/:id` — its owner, `playlist:moderate`.
|
||||
Title, slug, description, visibility; deletion.
|
||||
- `POST`, `DELETE /api/playlists/:id/dumps/:dumpId` — the same. Adds or
|
||||
removes a dump.
|
||||
- `PUT`, `DELETE /api/playlists/:id` — its owner, `playlist:moderate`. Title,
|
||||
slug, description, visibility; deletion.
|
||||
- `POST`, `DELETE /api/playlists/:id/dumps/:dumpId` — the same. Adds or removes
|
||||
a dump.
|
||||
- `PUT /api/playlists/:id/order` — the same. Reorders its dumps.
|
||||
- `GET`, `PUT /api/playlists/:id/cover` — the cover; a new one, by its owner
|
||||
or `playlist:moderate`.
|
||||
- `GET`, `PUT /api/playlists/:id/cover` — the cover; a new one, by its owner or
|
||||
`playlist:moderate`.
|
||||
|
||||
### comments
|
||||
|
||||
- `PATCH`, `DELETE /api/comments/:id` — its author, `comment:moderate`. Edits
|
||||
or deletes a comment.
|
||||
- `PATCH`, `DELETE /api/comments/:id` — its author, `comment:moderate`. Edits or
|
||||
deletes a comment.
|
||||
- `GET /api/comments/:id/likers` — anyone. Who likes it.
|
||||
|
||||
### categories
|
||||
@@ -166,17 +180,17 @@ thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
|
||||
### community
|
||||
|
||||
- `GET /api/community?period=weekly|monthly` — signed in. The site's top
|
||||
dumps, new members, new public playlists and totals over the last week (by
|
||||
default) or month, as of the server's last refresh.
|
||||
- `GET /api/community?period=weekly|monthly` — signed in. The site's top dumps,
|
||||
new members, new public playlists and totals over the last week (by default)
|
||||
or month, as of the server's last refresh.
|
||||
|
||||
### chat
|
||||
|
||||
- `GET /api/chat?before=&after=` — signed in. A page of messages. The chat
|
||||
itself goes over `/ws`.
|
||||
- A message from a moderator or an admin (`chat:everyone`) that says
|
||||
`@everyone` notifies every user who doesn't have the chat open, and comes
|
||||
flagged `mentionsEveryone`. No account may be named `everyone`.
|
||||
- A message from a moderator or an admin (`chat:everyone`) that says `@everyone`
|
||||
notifies every user who doesn't have the chat open, and comes flagged
|
||||
`mentionsEveryone`. No account may be named `everyone`.
|
||||
|
||||
### invites
|
||||
|
||||
@@ -188,10 +202,36 @@ thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
- `POST /api/sessions` — anyone. Signs in.
|
||||
- `POST /api/password-resets` — anyone. Emails a reset link.
|
||||
- `PUT /api/password-resets/:token` — with the link's token. A new password.
|
||||
- `POST /api/unsubscribe?token=` — with a digest's token. Turns it off. Its
|
||||
v3 path, `POST /api/users/unsubscribe`, stays for good, since sent emails'
|
||||
- `POST /api/unsubscribe?token=` — with a digest's token. Turns it off. Its v3
|
||||
path, `POST /api/users/unsubscribe`, stays for good, since sent emails'
|
||||
`List-Unsubscribe` headers name it.
|
||||
|
||||
### federation, oauth, .well-known
|
||||
|
||||
Federated sign-in (`shared/federation.ts`): a user signs in here with their
|
||||
account on another gerbeur instance, their home, by OpenID Connect's
|
||||
authorization code flow with PKCE, with tokens signed by each instance's Ed25519
|
||||
key.
|
||||
|
||||
- `GET /.well-known/openid-configuration`, `/.well-known/jwks.json` — anyone.
|
||||
The instance's metadata and public keys, bare JSON: the one exception to the
|
||||
`/api/` rule, at the paths the standard fixes.
|
||||
- `POST /api/federation/logins` — anyone. Starts a sign-in with an account on
|
||||
another instance; one neither trusted nor already home to someone here needs
|
||||
an invite.
|
||||
- `POST /api/federation/sessions` — anyone. Finishes it, as a sign-in.
|
||||
- `POST /api/federation/events` — another instance. Its signed news of one of
|
||||
its users here: a new name, email or avatar, or the end of their sessions.
|
||||
- `GET /api/federation/peers` — anyone the trusted instances,
|
||||
`federation:manage` every listed one.
|
||||
- `PUT /api/federation/peers`, `DELETE /api/federation/peers/:host` —
|
||||
`federation:manage`. Trusts or blocks an instance, or takes it off the lists.
|
||||
- `GET /api/oauth/clients?client_id=` — signed in. The instance asking to sign
|
||||
the caller in.
|
||||
- `POST /api/oauth/codes` — signed in. The caller's consent, and a code.
|
||||
- `POST /api/oauth/tokens` — another instance, form-encoded. Trades a code for
|
||||
an identity token, bare JSON.
|
||||
|
||||
### search
|
||||
|
||||
- `GET /api/search?q=` — anyone. A page of dumps, and up to 20 users and
|
||||
@@ -211,5 +251,5 @@ thumbnail, waveform, cover or attachment takes the owner's media token as
|
||||
|
||||
### /ws
|
||||
|
||||
- `GET /ws?token=` — anyone; a session token signs it in. The WebSocket of
|
||||
live updates and the chat (`shared/ws.ts`).
|
||||
- `GET /ws?token=` — anyone; a session token signs it in. The WebSocket of live
|
||||
updates and the chat (`shared/ws.ts`).
|
||||
|
||||
37
README.md
37
README.md
@@ -60,6 +60,7 @@ variables:
|
||||
| `GERBEUR_EMAIL_LOCALE` | Language of every email: `en` or `fr` | `en` |
|
||||
| `GERBEUR_DEFAULT_STYLE` | The instance's style (`smooth`, `brutalist`, `geocities`, `nyt`, `kanagawa`, `melange`): the site's until one is picked, and the welcome and reset emails' | `smooth` |
|
||||
| `GERBEUR_WELCOME_EMAIL_BODY` | Markdown body for the account-creation welcome email; supports `{{username}}` and `{{site_name}}` | built-in template |
|
||||
| `GERBEUR_FEDERATION_ALLOW_PRIVATE` | `1` lets federated sign-in reach instances on private addresses and over http — for two instances on one machine, never in production | unset |
|
||||
| `GERBEUR_COMMUNITY_REFRESH_MINUTES` | How often, in minutes, the `/community` page's figures are recomputed | `15` |
|
||||
| `VITE_API_PROTOCOL` | API protocol baked into the frontend bundle (see [Production](#production)) | `http` |
|
||||
| `VITE_API_HOSTNAME` | API hostname baked into the frontend bundle | `localhost` |
|
||||
@@ -122,6 +123,28 @@ example.com {
|
||||
}
|
||||
```
|
||||
|
||||
### Several instances
|
||||
|
||||
Each instance is its own deployment, with its own database, uploads, admins and
|
||||
domain, but its users can sign in to the others with their account, and the
|
||||
other way round. A user from `music.example` is `@alice@music.example` on the
|
||||
instances they sign in to. Their password, email, avatar and name stay on their
|
||||
home instance, and the others follow its changes.
|
||||
|
||||
Every instance is ready for it: nothing to configure, as long as
|
||||
`GERBEUR_PUBLIC_URL` is the instance's https origin (no path) and the instances
|
||||
can reach each other. An admin decides who comes in, on `/manage`:
|
||||
|
||||
- users of a **trusted** instance sign in directly, from a button on the login
|
||||
page;
|
||||
- users of a **blocked** instance can't, and those already in are signed out;
|
||||
- users of **any other** instance join with an invite, from the register page,
|
||||
and sign in without one afterwards.
|
||||
|
||||
To try it on one machine, run two instances on different ports with
|
||||
`GERBEUR_FEDERATION_ALLOW_PRIVATE=1`, which lets them reach each other over
|
||||
plain http on localhost. Never set it in production.
|
||||
|
||||
## Project structure
|
||||
|
||||
```
|
||||
@@ -165,13 +188,13 @@ public/ # Static assets (favicon, manifest, service worker)
|
||||
|
||||
### URLs
|
||||
|
||||
Every page and API path follows one of two rules, which [API.md](API.md)
|
||||
states, along with every page, the slug and username rules and every
|
||||
endpoint. Pages are a hierarchy under `@name` for users and plain words for
|
||||
categories and app pages (`/@bob/dumps/never-gonna`, `/music/hot`), built and
|
||||
parsed by `shared/paths.ts`. API resources are `/api/<plural>/<key>`, the
|
||||
caller's own under `/api/me`. A route change updates its router's module doc
|
||||
and API.md together.
|
||||
Every page and API path follows one of two rules, which [API.md](API.md) states,
|
||||
along with every page, the slug and username rules and every endpoint. Pages are
|
||||
a hierarchy under `@name` for users and plain words for categories and app pages
|
||||
(`/@bob/dumps/never-gonna`, `/music/hot`), built and parsed by
|
||||
`shared/paths.ts`. API resources are `/api/<plural>/<key>`, the caller's own
|
||||
under `/api/me`. A route change updates its router's module doc and API.md
|
||||
together.
|
||||
|
||||
Whatever crosses the wire is defined once, in `shared/`: the API envelope
|
||||
(`shared/api.ts`), each domain's types and request bodies (`shared/dump.ts`,
|
||||
|
||||
@@ -222,3 +222,13 @@ export const ALLOWED_ORIGINS: string[] = Array.from(
|
||||
...rawOrigins.split(",").map((o) => o.trim()).filter(Boolean),
|
||||
]),
|
||||
);
|
||||
|
||||
/**
|
||||
* Lets federated sign-in reach instances on private addresses, `localhost`
|
||||
* among them, and over plain http (`GERBEUR_FEDERATION_ALLOW_PRIVATE=1`), so
|
||||
* that two instances on one machine can trust each other in development.
|
||||
* Off, `remote/gerbeur-instance.ts` reaches only public https instances, since
|
||||
* an identity is only as safe as the connection it came over.
|
||||
*/
|
||||
export const FEDERATION_ALLOW_PRIVATE: boolean =
|
||||
Deno.env.get("GERBEUR_FEDERATION_ALLOW_PRIVATE")?.trim() === "1";
|
||||
|
||||
@@ -30,6 +30,7 @@ import { up as up0020DigestSchedule } from "./migrations/0020_digest_schedule.ts
|
||||
import { up as up0021PageUrls } from "./migrations/0021_page_urls.ts";
|
||||
import { up as up0022ReserveCommunity } from "./migrations/0022_reserve_community.ts";
|
||||
import { up as up0023MentionEveryone } from "./migrations/0023_mention_everyone.ts";
|
||||
import { up as up0024Federation } from "./migrations/0024_federation.ts";
|
||||
|
||||
interface Migration {
|
||||
name: string;
|
||||
@@ -72,6 +73,7 @@ const MIGRATIONS: Migration[] = [
|
||||
{ name: "0021_page_urls", up: up0021PageUrls },
|
||||
{ name: "0022_reserve_community", up: up0022ReserveCommunity },
|
||||
{ name: "0023_mention_everyone", up: up0023MentionEveryone },
|
||||
{ name: "0024_federation", up: up0024Federation },
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
105
api/db/migrations/0024_federation.ts
Normal file
105
api/db/migrations/0024_federation.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Prepares federated sign-in, by which a user signs in here with their
|
||||
* account on another gerbeur instance, and the other way round. It adds the
|
||||
* instance's signing key, the link from a local account to the one it stands
|
||||
* for elsewhere, the instances an admin trusts or blocks, the state of the
|
||||
* sign-ins in progress on both sides, the grants users gave other instances,
|
||||
* and the events owed to them.
|
||||
*
|
||||
* `/authorize` and `/federation/callback` become pages, so their first
|
||||
* segments are reserved.
|
||||
*
|
||||
* An account from another instance has no password here: its `password_hash`
|
||||
* is `''`, which no password verifies. Emails stay unique among local accounts
|
||||
* only, since the same person may also have a local account, or come from two
|
||||
* instances, with one address.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { renameReservedCategories } from "../../lib/reserved-slugs.ts";
|
||||
|
||||
/**
|
||||
* Run once by `runMigrations`. Nothing exists to convert, since every account
|
||||
* so far is local, but `authorize` and `federation` become the pages of a
|
||||
* sign-in, so a category that had one as its slug is renamed.
|
||||
*/
|
||||
export function up(db: DatabaseSync): void {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS federation_keys (
|
||||
kid TEXT PRIMARY KEY,
|
||||
private_jwk TEXT NOT NULL,
|
||||
public_jwk TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_identities (
|
||||
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
issuer TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
picture TEXT,
|
||||
synced_at TEXT NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_identities_subject
|
||||
ON user_identities(issuer, subject);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS federation_peers (
|
||||
issuer TEXT PRIMARY KEY,
|
||||
status TEXT NOT NULL,
|
||||
name TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS federation_logins (
|
||||
state TEXT PRIMARY KEY,
|
||||
issuer TEXT NOT NULL,
|
||||
code_verifier TEXT NOT NULL,
|
||||
nonce TEXT NOT NULL,
|
||||
invite_token TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS oauth_codes (
|
||||
code_hash TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
client_id TEXT NOT NULL,
|
||||
redirect_uri TEXT NOT NULL,
|
||||
code_challenge TEXT NOT NULL,
|
||||
nonce TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS federation_grants (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
client_id TEXT NOT NULL,
|
||||
client_name TEXT,
|
||||
granted_at TEXT NOT NULL,
|
||||
last_used_at TEXT NOT NULL,
|
||||
PRIMARY KEY (user_id, client_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS federation_outbox (
|
||||
id TEXT PRIMARY KEY,
|
||||
client_id TEXT NOT NULL,
|
||||
event TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_attempt_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_federation_outbox_next
|
||||
ON federation_outbox(next_attempt_at);
|
||||
`);
|
||||
|
||||
const emailIndex = db.prepare(
|
||||
`SELECT sql FROM sqlite_master WHERE name = 'idx_users_email_lower';`,
|
||||
).get() as { sql: string } | undefined;
|
||||
if (!emailIndex?.sql.includes("WHERE")) {
|
||||
db.exec(`
|
||||
DROP INDEX IF EXISTS idx_users_email_lower;
|
||||
CREATE UNIQUE INDEX idx_users_email_lower ON users(lower(email))
|
||||
WHERE password_hash != '';
|
||||
`);
|
||||
}
|
||||
renameReservedCategories(db);
|
||||
}
|
||||
@@ -176,7 +176,10 @@ CREATE TABLE invites (
|
||||
CREATE INDEX idx_invites_inviter ON invites(inviter_id);
|
||||
CREATE INDEX idx_users_invited_by ON users(invited_by);
|
||||
CREATE UNIQUE INDEX idx_users_username_lower ON users(lower(username));
|
||||
CREATE UNIQUE INDEX idx_users_email_lower ON users(lower(email));
|
||||
-- An account from another instance has no password (''), and its email may
|
||||
-- also be a local account's.
|
||||
CREATE UNIQUE INDEX idx_users_email_lower ON users(lower(email))
|
||||
WHERE password_hash != '';
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id TEXT PRIMARY KEY,
|
||||
@@ -270,3 +273,65 @@ CREATE TABLE chat_messages (
|
||||
);
|
||||
CREATE INDEX idx_chat_messages_created_id ON chat_messages(created_at, id);
|
||||
CREATE INDEX idx_chat_messages_user ON chat_messages(user_id);
|
||||
|
||||
CREATE TABLE federation_keys (
|
||||
kid TEXT PRIMARY KEY,
|
||||
private_jwk TEXT NOT NULL,
|
||||
public_jwk TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE user_identities (
|
||||
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
||||
issuer TEXT NOT NULL,
|
||||
subject TEXT NOT NULL,
|
||||
picture TEXT,
|
||||
synced_at TEXT NOT NULL
|
||||
);
|
||||
CREATE UNIQUE INDEX idx_user_identities_subject
|
||||
ON user_identities(issuer, subject);
|
||||
|
||||
CREATE TABLE federation_peers (
|
||||
issuer TEXT PRIMARY KEY,
|
||||
status TEXT NOT NULL,
|
||||
name TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE federation_logins (
|
||||
state TEXT PRIMARY KEY,
|
||||
issuer TEXT NOT NULL,
|
||||
code_verifier TEXT NOT NULL,
|
||||
nonce TEXT NOT NULL,
|
||||
invite_token TEXT,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE oauth_codes (
|
||||
code_hash TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
client_id TEXT NOT NULL,
|
||||
redirect_uri TEXT NOT NULL,
|
||||
code_challenge TEXT NOT NULL,
|
||||
nonce TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE federation_grants (
|
||||
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
client_id TEXT NOT NULL,
|
||||
client_name TEXT,
|
||||
granted_at TEXT NOT NULL,
|
||||
last_used_at TEXT NOT NULL,
|
||||
PRIMARY KEY (user_id, client_id)
|
||||
);
|
||||
|
||||
CREATE TABLE federation_outbox (
|
||||
id TEXT PRIMARY KEY,
|
||||
client_id TEXT NOT NULL,
|
||||
event TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_attempt_at TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_federation_outbox_next ON federation_outbox(next_attempt_at);
|
||||
|
||||
113
api/lib/jwt.ts
113
api/lib/jwt.ts
@@ -4,12 +4,27 @@
|
||||
* expiry are checked here: `lib/auth.ts` checks a session or media token
|
||||
* against its user.
|
||||
*
|
||||
* It also signs and verifies the tokens instances exchange for federated
|
||||
* sign-in (identity tokens and events), EdDSA with the instance's Ed25519 key,
|
||||
* whose public half other instances fetch: `instance-key-service.ts` keeps
|
||||
* the key, and the federation services pass it in.
|
||||
*
|
||||
* Importing this module throws when `GERBEUR_JWT_SECRET` is unset.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { jwtVerify, SignJWT } from "@panva/jose";
|
||||
import {
|
||||
createLocalJWKSet,
|
||||
exportJWK,
|
||||
generateKeyPair,
|
||||
importJWK,
|
||||
type JSONWebKeySet,
|
||||
type JWK,
|
||||
type JWTPayload,
|
||||
jwtVerify,
|
||||
SignJWT,
|
||||
} from "@panva/jose";
|
||||
|
||||
import {
|
||||
type AuthPayload,
|
||||
@@ -184,3 +199,99 @@ export async function verifyUnsubscribeToken(
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The algorithm of the tokens instances exchange: Ed25519 signatures, short
|
||||
* and fast, with no parameters to get wrong.
|
||||
*/
|
||||
const INSTANCE_ALG = "EdDSA";
|
||||
|
||||
/**
|
||||
* An instance's key, ready to sign, from {@link importInstanceKey}. Its
|
||||
* `kid` names the public half in the instance's JWKS.
|
||||
*/
|
||||
export interface InstanceSigningKey {
|
||||
kid: string;
|
||||
privateKey: CryptoKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a new Ed25519 key pair as JWKs, with a random `kid`, for
|
||||
* `instance-key-service.ts` to store when the instance has none. The public
|
||||
* JWK carries the `kid`, `alg` and `use` a JWKS entry needs.
|
||||
*/
|
||||
export async function generateInstanceKey(): Promise<
|
||||
{ kid: string; privateJwk: JWK; publicJwk: JWK }
|
||||
> {
|
||||
const { privateKey, publicKey } = await generateKeyPair(INSTANCE_ALG, {
|
||||
crv: "Ed25519",
|
||||
extractable: true,
|
||||
});
|
||||
const kid = crypto.randomUUID();
|
||||
return {
|
||||
kid,
|
||||
privateJwk: await exportJWK(privateKey),
|
||||
publicJwk: {
|
||||
...await exportJWK(publicKey),
|
||||
kid,
|
||||
alg: INSTANCE_ALG,
|
||||
use: "sig",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns the stored private JWK `privateJwk` as a key to sign with. */
|
||||
export async function importInstanceKey(
|
||||
kid: string,
|
||||
privateJwk: JWK,
|
||||
): Promise<InstanceSigningKey> {
|
||||
const privateKey = await importJWK(privateJwk, INSTANCE_ALG);
|
||||
if (!(privateKey instanceof CryptoKey)) {
|
||||
throw new Error("The instance key is not an asymmetric key");
|
||||
}
|
||||
return { kid, privateKey };
|
||||
}
|
||||
|
||||
/**
|
||||
* Signs `payload` with the instance's key, from `issuer` (this instance) to
|
||||
* `audience` (the instance it is for), valid for `expiresIn`, with a random
|
||||
* `jti`. The identity tokens of `POST /api/oauth/tokens` and the events of
|
||||
* the outbox are signed with it.
|
||||
*/
|
||||
export async function signInstanceToken(
|
||||
payload: JWTPayload,
|
||||
key: InstanceSigningKey,
|
||||
claims: { issuer: string; audience: string; subject: string },
|
||||
expiresIn: string,
|
||||
): Promise<string> {
|
||||
return await new SignJWT(payload)
|
||||
.setProtectedHeader({ alg: INSTANCE_ALG, kid: key.kid })
|
||||
.setIssuer(claims.issuer)
|
||||
.setAudience(claims.audience)
|
||||
.setSubject(claims.subject)
|
||||
.setIssuedAt()
|
||||
.setJti(crypto.randomUUID())
|
||||
.setExpirationTime(expiresIn)
|
||||
.sign(key.privateKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the payload of `token` once its signature checks against `jwks`,
|
||||
* the keys of `issuer`, and it is addressed to `audience` and unexpired.
|
||||
*
|
||||
* @throws {Error} jose's error when it doesn't verify; its `code` is
|
||||
* `ERR_JWKS_NO_MATCHING_KEY` when no key of `jwks` has its `kid`, which
|
||||
* tells the caller to refetch the keys, the issuer having rotated them.
|
||||
*/
|
||||
export async function verifyInstanceToken(
|
||||
token: string,
|
||||
jwks: JSONWebKeySet,
|
||||
claims: { issuer: string; audience: string },
|
||||
): Promise<JWTPayload> {
|
||||
const { payload } = await jwtVerify(token, createLocalJWKSet(jwks), {
|
||||
issuer: claims.issuer,
|
||||
audience: claims.audience,
|
||||
algorithms: [INSTANCE_ALG],
|
||||
});
|
||||
return payload;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ export const RESERVED_SLUGS: readonly string[] = [
|
||||
"settings",
|
||||
"manage",
|
||||
"community",
|
||||
"authorize",
|
||||
"federation",
|
||||
"api",
|
||||
"ws",
|
||||
"assets",
|
||||
@@ -46,7 +48,8 @@ export function isReservedSlug(slug: string): boolean {
|
||||
/**
|
||||
* Renames each category whose slug is now reserved, such as `hot`, to the
|
||||
* first of `<slug>-2`, `<slug>-3`… that is free, and logs it. Migration 0021
|
||||
* runs it for v4's words, and 0022 for `community`.
|
||||
* runs it for v4's words, 0022 for `community`, and 0024 for `authorize` and
|
||||
* `federation`.
|
||||
*/
|
||||
export function renameReservedCategories(db: DatabaseSync): void {
|
||||
const rows = db.prepare(`SELECT id, slug FROM categories;`).all() as {
|
||||
|
||||
@@ -19,10 +19,12 @@ import communityRouter from "./routes/community.ts";
|
||||
import commentsRouter from "./routes/comments.ts";
|
||||
import dumpsRouter from "./routes/dumps.ts";
|
||||
import filesRouter from "./routes/files.ts";
|
||||
import federationRouter from "./routes/federation.ts";
|
||||
import followsRouter from "./routes/follows.ts";
|
||||
import invitesRouter from "./routes/invites.ts";
|
||||
import meRouter from "./routes/me.ts";
|
||||
import notificationsRouter from "./routes/notifications.ts";
|
||||
import oauthRouter from "./routes/oauth.ts";
|
||||
import passwordResetsRouter from "./routes/password-resets.ts";
|
||||
import playlistsRouter from "./routes/playlists.ts";
|
||||
import remoteRouter from "./routes/remote.ts";
|
||||
@@ -32,6 +34,7 @@ import thumbnailsRouter from "./routes/thumbnails.ts";
|
||||
import waveformsRouter from "./routes/waveforms.ts";
|
||||
import unsubscribeRouter from "./routes/unsubscribe.ts";
|
||||
import usersRouter from "./routes/users.ts";
|
||||
import wellKnownRouter from "./routes/well-known.ts";
|
||||
import wsRouter from "./routes/ws.ts";
|
||||
|
||||
import { ALLOWED_ORIGINS, LISTEN_HOST, PORT, PUBLIC_URL } from "./config.ts";
|
||||
@@ -43,6 +46,7 @@ import { rateLimitSweepJob } from "./lib/rate-limit.ts";
|
||||
import { digestJob } from "./services/digest-service.ts";
|
||||
import { communityJob } from "./services/community-service.ts";
|
||||
import { pingJob, typingExpiryJob } from "./services/ws-service.ts";
|
||||
import { outboxJob } from "./services/identity-provider-service.ts";
|
||||
|
||||
/**
|
||||
* The whole server, exported so the tests' helpers can send it requests
|
||||
@@ -87,6 +91,9 @@ for (
|
||||
invitesRouter,
|
||||
attachmentsRouter,
|
||||
remoteRouter,
|
||||
federationRouter,
|
||||
oauthRouter,
|
||||
wellKnownRouter,
|
||||
wsRouter,
|
||||
]
|
||||
) {
|
||||
@@ -114,6 +121,7 @@ if (import.meta.main) {
|
||||
pingJob,
|
||||
typingExpiryJob,
|
||||
rateLimitSweepJob,
|
||||
outboxJob,
|
||||
]);
|
||||
await app.listen({ hostname: LISTEN_HOST, port: PORT });
|
||||
}
|
||||
|
||||
@@ -19,8 +19,22 @@ import {
|
||||
* it carries the password hash.
|
||||
*/
|
||||
export interface User extends SelfUser {
|
||||
/** From `hashPassword`, as `hash.salt`. */
|
||||
passwordHash: string;
|
||||
/**
|
||||
* From `hashPassword`, as `hash.salt`, or null for an account from another
|
||||
* instance ({@link isRemoteUser}), which signs in there and never with a
|
||||
* password here. The row stores that as `''`.
|
||||
*/
|
||||
passwordHash: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether `user`'s account lives on another instance, whose user signs
|
||||
* in here through federation (`federation-service.ts`). Their password,
|
||||
* email, avatar and name are that instance's to change, so the routes that
|
||||
* change them here refuse.
|
||||
*/
|
||||
export function isRemoteUser(user: User): boolean {
|
||||
return user.passwordHash === null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -49,6 +63,7 @@ export function toSelfUser({ passwordHash: _, ...user }: User): SelfUser {
|
||||
export interface UserRow {
|
||||
id: string;
|
||||
username: string;
|
||||
/** `''` for an account from another instance, which has no password. */
|
||||
password_hash: string;
|
||||
role: Role;
|
||||
created_at: string;
|
||||
@@ -97,7 +112,7 @@ export function userRowToApi(row: UserRow): User {
|
||||
return {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
passwordHash: row.password_hash,
|
||||
passwordHash: row.password_hash || null,
|
||||
role: row.role,
|
||||
createdAt: new Date(row.created_at),
|
||||
updatedAt: row.updated_at ? new Date(row.updated_at) : undefined,
|
||||
@@ -118,7 +133,7 @@ export function userApiToRow(user: User): UserRow {
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
password_hash: user.passwordHash,
|
||||
password_hash: user.passwordHash ?? "",
|
||||
role: user.role,
|
||||
created_at: user.createdAt.toISOString(),
|
||||
updated_at: user.updatedAt?.toISOString() ?? null,
|
||||
|
||||
224
api/remote/gerbeur-instance.ts
Normal file
224
api/remote/gerbeur-instance.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
/**
|
||||
* Talks to other gerbeur instances for federated sign-in: it reads their
|
||||
* metadata and public keys, trades a code for an identity token, delivers
|
||||
* events, and fetches a user's avatar. `federation-service.ts`,
|
||||
* `identity-provider-service.ts` and `federation-peer-service.ts` reach other
|
||||
* instances only through it.
|
||||
*
|
||||
* An identity is only as safe as the connection it came over, so unlike
|
||||
* `fetch.ts` it never falls back to skipping certificate checks, and follows
|
||||
* no redirect. It reaches only https instances on public addresses, unless
|
||||
* `GERBEUR_FEDERATION_ALLOW_PRIVATE` lets two instances on one machine talk.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import type { JSONWebKeySet } from "@panva/jose";
|
||||
import {
|
||||
type InstanceMetadata,
|
||||
isInstanceMetadata,
|
||||
} from "../../shared/federation.ts";
|
||||
import {
|
||||
FEDERATION_ALLOW_PRIVATE,
|
||||
MAX_IMAGE_SIZE_BYTES,
|
||||
OG_SITE_NAME,
|
||||
} from "../config.ts";
|
||||
import { resolvePublicAddress } from "./public-address.ts";
|
||||
import { readBytesCapped, readTextCapped } from "./fetch.ts";
|
||||
import { TtlCache } from "../lib/ttl-cache.ts";
|
||||
|
||||
/** How long a request to another instance may take, body included. */
|
||||
const TIMEOUT_MS = 8000;
|
||||
|
||||
/** Caps a metadata document, a key set or a token response. */
|
||||
const MAX_JSON_BYTES = 64 * 1024;
|
||||
|
||||
const USER_AGENT = `gerbeur (${OG_SITE_NAME}; federation)`;
|
||||
|
||||
/**
|
||||
* Keeps each instance's metadata and keys for 10 minutes, so that a sign-in
|
||||
* or an event doesn't fetch them each time. A key set is refetched sooner
|
||||
* when a token names a key it lacks ({@link fetchKeys} with `fresh`).
|
||||
*/
|
||||
const metadataCache = new TtlCache<InstanceMetadata>(10 * 60_000, 500);
|
||||
const keysCache = new TtlCache<JSONWebKeySet>(10 * 60_000, 500);
|
||||
|
||||
/**
|
||||
* Checks that `url` may be reached: https on a public address, or anything
|
||||
* under `GERBEUR_FEDERATION_ALLOW_PRIVATE`.
|
||||
*
|
||||
* @throws {Error} When it may not.
|
||||
*/
|
||||
export async function assertReachable(url: URL): Promise<void> {
|
||||
if (FEDERATION_ALLOW_PRIVATE) {
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
||||
throw new Error(`Unsupported protocol ${url.protocol}`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (url.protocol !== "https:") {
|
||||
throw new Error(`Refusing to reach ${url.origin} without https`);
|
||||
}
|
||||
await resolvePublicAddress(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes one request to another instance, after {@link assertReachable}, with
|
||||
* the deadline covering the body. The caller reads or cancels the body.
|
||||
*/
|
||||
async function request(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
const target = new URL(url);
|
||||
await assertReachable(target);
|
||||
return await fetch(target, {
|
||||
...init,
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
headers: {
|
||||
"User-Agent": USER_AGENT,
|
||||
"Accept": "application/json",
|
||||
...init.headers,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the JSON body of `res`, up to {@link MAX_JSON_BYTES}.
|
||||
*
|
||||
* @throws {Error} When the status isn't a success or the body isn't JSON.
|
||||
*/
|
||||
async function readJson(res: Response, what: string): Promise<unknown> {
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel();
|
||||
throw new Error(`${what} answered ${res.status}`);
|
||||
}
|
||||
return JSON.parse(await readTextCapped(res, MAX_JSON_BYTES));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the metadata of the instance at `origin`, from its
|
||||
* `/.well-known/openid-configuration`, cached. It must name `origin` as its
|
||||
* issuer and speak this protocol's version.
|
||||
*
|
||||
* @throws {Error} When it can't be reached or isn't a gerbeur instance.
|
||||
*/
|
||||
export async function fetchMetadata(origin: string): Promise<InstanceMetadata> {
|
||||
const hit = metadataCache.get(origin);
|
||||
if (hit) return hit;
|
||||
const body = await readJson(
|
||||
await request(`${origin}/.well-known/openid-configuration`),
|
||||
origin,
|
||||
);
|
||||
if (!isInstanceMetadata(body)) {
|
||||
throw new Error(`${origin} is not a gerbeur instance this one can trust`);
|
||||
}
|
||||
if (body.issuer !== origin) {
|
||||
throw new Error(`${origin} names itself ${body.issuer}`);
|
||||
}
|
||||
return metadataCache.set(origin, body);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the public keys of the instance at `origin`, cached unless `fresh`
|
||||
* asks to refetch them.
|
||||
*
|
||||
* @throws {Error} When they can't be fetched.
|
||||
*/
|
||||
export async function fetchKeys(
|
||||
origin: string,
|
||||
fresh = false,
|
||||
): Promise<JSONWebKeySet> {
|
||||
const hit = fresh ? undefined : keysCache.get(origin);
|
||||
if (hit) return hit;
|
||||
const { jwks_uri } = await fetchMetadata(origin);
|
||||
const body = await readJson(await request(jwks_uri), `${origin}'s keys`);
|
||||
if (
|
||||
!body || typeof body !== "object" ||
|
||||
!Array.isArray((body as { keys?: unknown }).keys)
|
||||
) {
|
||||
throw new Error(`${origin}'s keys are not a key set`);
|
||||
}
|
||||
return keysCache.set(origin, body as JSONWebKeySet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Trades `code` for an identity token at the token endpoint of the instance
|
||||
* at `origin`, and returns the token, unverified.
|
||||
*
|
||||
* @throws {Error} When the instance refuses or answers no token.
|
||||
*/
|
||||
export async function exchangeCode(
|
||||
origin: string,
|
||||
params: {
|
||||
code: string;
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
codeVerifier: string;
|
||||
},
|
||||
): Promise<string> {
|
||||
const { token_endpoint } = await fetchMetadata(origin);
|
||||
const body = await readJson(
|
||||
await request(token_endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code: params.code,
|
||||
client_id: params.clientId,
|
||||
redirect_uri: params.redirectUri,
|
||||
code_verifier: params.codeVerifier,
|
||||
}),
|
||||
}),
|
||||
`${origin}'s token endpoint`,
|
||||
);
|
||||
const idToken = (body as { id_token?: unknown } | null)?.id_token;
|
||||
if (typeof idToken !== "string") {
|
||||
throw new Error(`${origin} answered no identity token`);
|
||||
}
|
||||
return idToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the signed event `event` to the events endpoint of the instance at
|
||||
* `origin`, and returns whether it took it. A 4xx other than 429 means it never
|
||||
* will, which the caller treats as delivered.
|
||||
*
|
||||
* @throws {Error} When it can't be reached, or answers 429 or a 5xx.
|
||||
*/
|
||||
export async function postEvent(
|
||||
origin: string,
|
||||
event: string,
|
||||
): Promise<boolean> {
|
||||
const { gerbeur_events_endpoint } = await fetchMetadata(origin);
|
||||
const res = await request(gerbeur_events_endpoint, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ event }),
|
||||
});
|
||||
await res.body?.cancel();
|
||||
if (res.ok) return true;
|
||||
if (res.status === 429 || res.status >= 500) {
|
||||
throw new Error(`${origin}'s events endpoint answered ${res.status}`);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the image at `url`, a user's avatar on their home instance, up to
|
||||
* the size an avatar may be.
|
||||
*
|
||||
* @throws {Error} When it can't be fetched.
|
||||
*/
|
||||
export async function fetchAvatar(url: string): Promise<Uint8Array> {
|
||||
const res = await request(url, { headers: { "Accept": "image/*" } });
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel();
|
||||
throw new Error(`The avatar at ${url} answered ${res.status}`);
|
||||
}
|
||||
return await readBytesCapped(res, MAX_IMAGE_SIZE_BYTES + 1);
|
||||
}
|
||||
|
||||
/** Empties the caches, for the tests' reset between cases. */
|
||||
export function clearInstanceCaches(): void {
|
||||
metadataCache.clear();
|
||||
keysCache.clear();
|
||||
}
|
||||
@@ -5,7 +5,8 @@
|
||||
*
|
||||
* - `PUT /api/me/avatar` — signed in. Replaces the caller's avatar (multipart
|
||||
* `file`, at most 5 MB), sends `user_updated` to everyone, and answers the
|
||||
* caller's user.
|
||||
* caller's user. 400 for an account from another instance, whose avatar
|
||||
* comes from there. The instances the caller signed in to are told.
|
||||
* - `GET /api/users/:key/avatar` — public. Serves a user's avatar; 404 without
|
||||
* one.
|
||||
*
|
||||
@@ -15,23 +16,17 @@
|
||||
import { Router } from "@oak/oak";
|
||||
import { authMiddleware } from "../middleware/auth.ts";
|
||||
import {
|
||||
assertLocalUser,
|
||||
getUserById,
|
||||
resolveUserKey,
|
||||
updateUserAvatar,
|
||||
setUserAvatar,
|
||||
} from "../services/user-service.ts";
|
||||
import {
|
||||
broadcastUserUpdated,
|
||||
updateClientAvatar,
|
||||
} from "../services/ws-service.ts";
|
||||
import { type APIResponse } from "../../shared/api.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import type { SelfUser } from "../../shared/user.ts";
|
||||
import { toPublicUser, toSelfUser } from "../model/user.ts";
|
||||
import {
|
||||
replaceUploadedFile,
|
||||
serveUploadedFile,
|
||||
validateImageUpload,
|
||||
} from "../lib/upload.ts";
|
||||
import { toSelfUser } from "../model/user.ts";
|
||||
import { serveUploadedFile } from "../lib/upload.ts";
|
||||
import { notifyClients } from "../services/identity-provider-service.ts";
|
||||
import { AVATARS_DIR } from "../config.ts";
|
||||
|
||||
/**
|
||||
@@ -54,19 +49,12 @@ router.put("/api/me/avatar", authMiddleware, async (ctx) => {
|
||||
throw new APIException(400, "Missing file field");
|
||||
}
|
||||
|
||||
const data = new Uint8Array(await file.arrayBuffer());
|
||||
const mime = validateImageUpload(data);
|
||||
|
||||
// Written before the record announces it, or clients would fetch it too
|
||||
// early.
|
||||
await replaceUploadedFile(`${AVATARS_DIR}/${authPayload.userId}`, data);
|
||||
updateUserAvatar(authPayload.userId, mime);
|
||||
updateClientAvatar(authPayload.userId, mime);
|
||||
|
||||
const user = getUserById(authPayload.userId);
|
||||
// Presence alone would update only the online list; `user_updated` reaches
|
||||
// every avatar on screen, and its bumped `updatedAt` busts their cache.
|
||||
broadcastUserUpdated(toPublicUser(user));
|
||||
assertLocalUser(getUserById(authPayload.userId));
|
||||
const user = await setUserAvatar(
|
||||
authPayload.userId,
|
||||
new Uint8Array(await file.arrayBuffer()),
|
||||
);
|
||||
await notifyClients(user.id, { type: "update" });
|
||||
const responseBody: APIResponse<SelfUser> = {
|
||||
success: true,
|
||||
data: toSelfUser(user),
|
||||
|
||||
149
api/routes/federation.ts
Normal file
149
api/routes/federation.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Lets users of other gerbeur instances sign in here with their account
|
||||
* there, as `federation-service.ts` describes, and lets admins pick the
|
||||
* instances to trust or block. The login and register pages start a sign-in,
|
||||
* the `/federation/callback` page finishes it, `/manage` edits the peers, and
|
||||
* the other instances' servers send their events.
|
||||
*
|
||||
* - `POST /api/federation/logins` — public. Starts a sign-in with an account
|
||||
* on another instance (`FederationLoginRequest`, with an invite unless it
|
||||
* is trusted), and answers its `/authorize` page to go to. Rate-limited per
|
||||
* instance.
|
||||
* - `POST /api/federation/sessions` — public. Finishes it
|
||||
* (`FederationSessionRequest`) and answers the user and their tokens, as a
|
||||
* sign-in does. Rate-limited per instance.
|
||||
* - `POST /api/federation/events` — public, server to server. Applies a
|
||||
* home instance's signed event about one of its users (`{ event }`).
|
||||
* - `GET /api/federation/peers` — optional sign-in. Answers the trusted
|
||||
* instances, or every listed one to `federation:manage`.
|
||||
* - `PUT /api/federation/peers` — permission `federation:manage`. Trusts or
|
||||
* blocks an instance (`SetPeerRequest`) and answers it; 502 when it
|
||||
* doesn't answer as a gerbeur.
|
||||
* - `DELETE /api/federation/peers/:host` — permission `federation:manage`.
|
||||
* Takes an instance off the lists.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import type { APIResponse } from "../../shared/api.ts";
|
||||
import {
|
||||
type FederationLoginResponse,
|
||||
type FederationPeer,
|
||||
parseInstance,
|
||||
} from "../../shared/federation.ts";
|
||||
import type { AuthResponse } from "../../shared/user.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { parseOptionalAuth } from "../lib/auth.ts";
|
||||
import { issueTokens } from "../lib/jwt.ts";
|
||||
import { hasPermission } from "../../shared/permissions.ts";
|
||||
import { type RateLimit, takeToken } from "../lib/rate-limit.ts";
|
||||
import {
|
||||
type AuthContext,
|
||||
authMiddleware,
|
||||
requirePermission,
|
||||
} from "../middleware/auth.ts";
|
||||
import { toSelfUser } from "../model/user.ts";
|
||||
import {
|
||||
isFederationLoginRequest,
|
||||
isFederationSessionRequest,
|
||||
isSetPeerRequest,
|
||||
} from "../validators/federation.ts";
|
||||
import {
|
||||
completeLogin,
|
||||
receiveEvent,
|
||||
startLogin,
|
||||
} from "../services/federation-service.ts";
|
||||
import {
|
||||
listPeers,
|
||||
removePeer,
|
||||
setPeer,
|
||||
} from "../services/federation-peer-service.ts";
|
||||
import { getUserById } from "../services/user-service.ts";
|
||||
import { fieldOf } from "../validators/user.ts";
|
||||
|
||||
/**
|
||||
* Allows a burst of 30 sign-ins per instance, then one every 2 seconds, so
|
||||
* that nobody makes this instance hammer another.
|
||||
*/
|
||||
const LOGIN_LIMIT: RateLimit = { capacity: 30, refill: 1 / 2 };
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
* An `APIException` thrown by a handler becomes the JSON error response there.
|
||||
*/
|
||||
const router: Router = new Router({ prefix: "/api/federation" });
|
||||
|
||||
router.post("/logins", async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isFederationLoginRequest(body)) {
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
if (!takeToken(`federation:${parseInstance(body.instance)}`, LOGIN_LIMIT)) {
|
||||
throw new APIException(429, "Too many sign-ins — try again in a minute");
|
||||
}
|
||||
const responseBody: APIResponse<FederationLoginResponse> = {
|
||||
success: true,
|
||||
data: { authorizeUrl: await startLogin(body) },
|
||||
};
|
||||
ctx.response.body = responseBody;
|
||||
});
|
||||
|
||||
router.post("/sessions", async (ctx) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isFederationSessionRequest(body)) {
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
const user = await completeLogin(body);
|
||||
const responseBody: APIResponse<AuthResponse> = {
|
||||
success: true,
|
||||
data: { ...await issueTokens(user), user: toSelfUser(user) },
|
||||
};
|
||||
ctx.response.body = responseBody;
|
||||
});
|
||||
|
||||
router.post("/events", async (ctx) => {
|
||||
const event = fieldOf(await ctx.request.body.json(), "event");
|
||||
if (typeof event !== "string") throw new APIException(400, "Invalid event");
|
||||
await receiveEvent(event);
|
||||
ctx.response.status = 204;
|
||||
});
|
||||
|
||||
router.get("/peers", async (ctx) => {
|
||||
const userId = await parseOptionalAuth(ctx);
|
||||
const all = !!userId &&
|
||||
hasPermission(getUserById(userId).role, "federation:manage");
|
||||
const responseBody: APIResponse<FederationPeer[]> = {
|
||||
success: true,
|
||||
data: listPeers(!all),
|
||||
};
|
||||
ctx.response.body = responseBody;
|
||||
});
|
||||
|
||||
router.put(
|
||||
"/peers",
|
||||
authMiddleware,
|
||||
requirePermission("federation:manage"),
|
||||
async (ctx: AuthContext) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isSetPeerRequest(body)) throw new APIException(400, "Invalid request");
|
||||
const responseBody: APIResponse<FederationPeer> = {
|
||||
success: true,
|
||||
data: await setPeer(body.instance, body.status),
|
||||
};
|
||||
ctx.response.body = responseBody;
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
"/peers/:host",
|
||||
authMiddleware,
|
||||
requirePermission("federation:manage"),
|
||||
(ctx: AuthContext<"/peers/:host">) => {
|
||||
removePeer(ctx.params.host);
|
||||
const responseBody: APIResponse<null> = { success: true, data: null };
|
||||
ctx.response.body = responseBody;
|
||||
},
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -7,7 +7,8 @@
|
||||
*
|
||||
* - `GET /api/me` — signed in. Answers the caller's own user.
|
||||
* - `PATCH /api/me` — signed in. Changes the caller's description and email,
|
||||
* and answers their user. A username changes only by `user:manage`, through
|
||||
* and answers their user. The email of an account from another instance is
|
||||
* that instance's: 400. A username changes only by `user:manage`, through
|
||||
* `PATCH /api/users/:key/username`.
|
||||
* - `GET /api/me/media-token` — signed in. Answers a media token, for a
|
||||
* session that predates them.
|
||||
@@ -15,9 +16,17 @@
|
||||
* - `PATCH /api/me/settings` — signed in. Changes some of the caller's
|
||||
* settings, and answers them all.
|
||||
* - `PUT /api/me/password` — signed in, with the current password. Sets a new
|
||||
* one, ending every other session, and answers fresh tokens.
|
||||
* one, ending every other session, and answers fresh tokens. 400 for an
|
||||
* account from another instance, which has no password here.
|
||||
* - `GET /api/me/playlists?contains=:dumpId` — signed in. Answers each of the
|
||||
* caller's playlists and whether it holds the dump.
|
||||
* - `GET /api/me/grants` — signed in. Answers the other instances the caller
|
||||
* let their account sign in to.
|
||||
* - `DELETE /api/me/grants/:host` — signed in. Withdraws that grant, which
|
||||
* ends the caller's sessions there.
|
||||
*
|
||||
* A change to the caller's email or password is told to those instances
|
||||
* (`notifyClients`).
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -39,11 +48,21 @@ import { toPublicUser, toSelfUser } from "../model/user.ts";
|
||||
import { createMediaToken, issueTokens } from "../lib/jwt.ts";
|
||||
import { verifyPassword } from "../lib/password.ts";
|
||||
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
|
||||
import { getUserById, updateUser } from "../services/user-service.ts";
|
||||
import {
|
||||
assertLocalUser,
|
||||
getUserById,
|
||||
updateUser,
|
||||
} from "../services/user-service.ts";
|
||||
import { getSettings, updateSettings } from "../services/settings-service.ts";
|
||||
import { getPlaylistMembershipsForDump } from "../services/playlist-service.ts";
|
||||
import { broadcastUserUpdated } from "../services/ws-service.ts";
|
||||
import { VALIDATION } from "../../shared/validation.ts";
|
||||
import type { FederationGrant } from "../../shared/federation.ts";
|
||||
import {
|
||||
listGrants,
|
||||
notifyClients,
|
||||
revokeGrant,
|
||||
} from "../services/identity-provider-service.ts";
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
@@ -65,6 +84,7 @@ router.patch("/", authMiddleware, async (ctx: AuthContext) => {
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
const userId = ctx.state.user.userId;
|
||||
if (body.email !== undefined) assertLocalUser(getUserById(userId));
|
||||
// Only these fields: a stolen token alone must not change the role or the
|
||||
// password, which needs the current one.
|
||||
const updated = await updateUser(userId, {
|
||||
@@ -72,6 +92,7 @@ router.patch("/", authMiddleware, async (ctx: AuthContext) => {
|
||||
email: body.email,
|
||||
});
|
||||
broadcastUserUpdated(toPublicUser(updated));
|
||||
if (body.email !== undefined) await notifyClients(userId, { type: "update" });
|
||||
const responseBody: APIResponse<SelfUser> = {
|
||||
success: true,
|
||||
data: toSelfUser(updated),
|
||||
@@ -127,7 +148,8 @@ router.put("/password", authMiddleware, async (ctx: AuthContext) => {
|
||||
}
|
||||
|
||||
const user = getUserById(ctx.state.user.userId);
|
||||
const valid = await verifyPassword(currentPassword, user.passwordHash);
|
||||
assertLocalUser(user);
|
||||
const valid = await verifyPassword(currentPassword, user.passwordHash ?? "");
|
||||
if (!valid) {
|
||||
throw new APIException(403, "Current password is incorrect");
|
||||
}
|
||||
@@ -137,6 +159,7 @@ router.put("/password", authMiddleware, async (ctx: AuthContext) => {
|
||||
const updated = await updateUser(ctx.state.user.userId, {
|
||||
password: newPassword,
|
||||
});
|
||||
await notifyClients(updated.id, { type: "revoke" });
|
||||
const responseBody: APIResponse<AuthTokens> = {
|
||||
success: true,
|
||||
data: await issueTokens(updated),
|
||||
@@ -154,4 +177,22 @@ router.get("/playlists", authMiddleware, (ctx: AuthContext) => {
|
||||
ctx.response.body = responseBody;
|
||||
});
|
||||
|
||||
router.get("/grants", authMiddleware, (ctx: AuthContext) => {
|
||||
const responseBody: APIResponse<FederationGrant[]> = {
|
||||
success: true,
|
||||
data: listGrants(ctx.state.user.userId),
|
||||
};
|
||||
ctx.response.body = responseBody;
|
||||
});
|
||||
|
||||
router.delete(
|
||||
"/grants/:host",
|
||||
authMiddleware,
|
||||
async (ctx: AuthContext<"/grants/:host">) => {
|
||||
await revokeGrant(ctx.state.user.userId, ctx.params.host);
|
||||
const responseBody: APIResponse<null> = { success: true, data: null };
|
||||
ctx.response.body = responseBody;
|
||||
},
|
||||
);
|
||||
|
||||
export default router;
|
||||
|
||||
78
api/routes/oauth.ts
Normal file
78
api/routes/oauth.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Lets this instance's users sign in to other gerbeur instances with their
|
||||
* account here, as `identity-provider-service.ts` describes. The client's
|
||||
* `/authorize` page calls the first two; the other instance's server calls the
|
||||
* last.
|
||||
*
|
||||
* - `GET /api/oauth/clients?client_id=` — signed in. Answers the instance
|
||||
* asking to sign the caller in (`OAuthClient`), and whether they already
|
||||
* let it; 400 for an account from another instance, 403 when that instance
|
||||
* is blocked here, 502 when it doesn't answer as a gerbeur.
|
||||
* - `POST /api/oauth/codes` — signed in. Records the caller's consent to the
|
||||
* request (`AuthorizeRequest`) and answers where to send them, the
|
||||
* instance's callback page with a code.
|
||||
* - `POST /api/oauth/tokens` — public, form-encoded, server to server. Trades
|
||||
* a code and its PKCE verifier for an identity token (`id_token`), bare
|
||||
* JSON as OAuth has it; 400 when anything doesn't match. Rate-limited per
|
||||
* client.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import type { APIResponse } from "../../shared/api.ts";
|
||||
import type {
|
||||
AuthorizeResponse,
|
||||
OAuthClient,
|
||||
} from "../../shared/federation.ts";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { type RateLimit, takeToken } from "../lib/rate-limit.ts";
|
||||
import { type AuthContext, authMiddleware } from "../middleware/auth.ts";
|
||||
import { isAuthorizeRequest } from "../validators/federation.ts";
|
||||
import {
|
||||
createAuthorizationCode,
|
||||
describeClient,
|
||||
exchangeCode,
|
||||
} from "../services/identity-provider-service.ts";
|
||||
|
||||
/** Allows a burst of 30 code trades per client instance, then one a second. */
|
||||
const TOKEN_LIMIT: RateLimit = { capacity: 30, refill: 1 };
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
* An `APIException` thrown by a handler becomes the JSON error response there.
|
||||
*/
|
||||
const router: Router = new Router({ prefix: "/api/oauth" });
|
||||
|
||||
router.get("/clients", authMiddleware, async (ctx: AuthContext) => {
|
||||
const clientId = ctx.request.url.searchParams.get("client_id");
|
||||
if (!clientId) throw new APIException(400, "client_id is required");
|
||||
const responseBody: APIResponse<OAuthClient> = {
|
||||
success: true,
|
||||
data: await describeClient(ctx.state.user.userId, clientId),
|
||||
};
|
||||
ctx.response.body = responseBody;
|
||||
});
|
||||
|
||||
router.post("/codes", authMiddleware, async (ctx: AuthContext) => {
|
||||
const body: unknown = await ctx.request.body.json();
|
||||
if (!isAuthorizeRequest(body)) throw new APIException(400, "Invalid request");
|
||||
const responseBody: APIResponse<AuthorizeResponse> = {
|
||||
success: true,
|
||||
data: {
|
||||
redirectTo: await createAuthorizationCode(ctx.state.user.userId, body),
|
||||
},
|
||||
};
|
||||
ctx.response.body = responseBody;
|
||||
});
|
||||
|
||||
router.post("/tokens", async (ctx) => {
|
||||
const params = new URLSearchParams(await ctx.request.body.text());
|
||||
if (!takeToken(`oauth-token:${params.get("client_id")}`, TOKEN_LIMIT)) {
|
||||
throw new APIException(429, "Too many requests");
|
||||
}
|
||||
ctx.response.headers.set("Cache-Control", "no-store");
|
||||
ctx.response.body = await exchangeCode(params);
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -31,7 +31,9 @@
|
||||
* - `PATCH /api/users/:key/role` — permission `user:manage`. Sets another
|
||||
* user's role.
|
||||
* - `PATCH /api/users/:key/username` — permission `user:manage`. Renames a
|
||||
* user, the caller included. It is the only way a name changes.
|
||||
* user, the caller included. It is the only way a local name changes; a
|
||||
* user from another instance is named there (400). The instances the user
|
||||
* signed in to are told.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -64,6 +66,7 @@ import {
|
||||
import { parseOptionalAuth } from "../lib/auth.ts";
|
||||
import { parsePagination } from "../lib/pagination.ts";
|
||||
import {
|
||||
assertLocalUser,
|
||||
createUser,
|
||||
getInviteTree,
|
||||
renameUser,
|
||||
@@ -73,6 +76,7 @@ import {
|
||||
updateUser,
|
||||
} from "../services/user-service.ts";
|
||||
import { claimInvite, releaseInvite } from "../services/invite-service.ts";
|
||||
import { notifyClients } from "../services/identity-provider-service.ts";
|
||||
import {
|
||||
broadcastUserUpdated,
|
||||
updateClientUsername,
|
||||
@@ -293,9 +297,11 @@ router.patch(
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
const user = resolveUserKey(ctx.params.key);
|
||||
assertLocalUser(user);
|
||||
const publicUser = toPublicUser(renameUser(user.id, username));
|
||||
updateClientUsername(publicUser.id, publicUser.username);
|
||||
broadcastUserUpdated(publicUser);
|
||||
await notifyClients(publicUser.id, { type: "update" });
|
||||
const responseBody: APIResponse<PublicUser> = {
|
||||
success: true,
|
||||
data: publicUser,
|
||||
|
||||
36
api/routes/well-known.ts
Normal file
36
api/routes/well-known.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Serves what other gerbeur instances read about this one before federated
|
||||
* sign-in, at the root paths OpenID Connect fixes, which are the one
|
||||
* exception to the API's `/api/` rule. `remote/gerbeur-instance.ts` reads
|
||||
* them on the other side.
|
||||
*
|
||||
* - `GET /.well-known/openid-configuration` — public. Answers the instance's
|
||||
* metadata (`InstanceMetadata`): its endpoints, its name and the protocol's
|
||||
* version. Bare JSON, not the API's envelope.
|
||||
* - `GET /.well-known/jwks.json` — public. Answers the public keys its tokens
|
||||
* are signed with. Bare JSON.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Router } from "@oak/oak";
|
||||
import { getInstanceMetadata } from "../services/identity-provider-service.ts";
|
||||
import { getPublicKeys } from "../services/instance-key-service.ts";
|
||||
|
||||
/**
|
||||
* Mounted by `api/main.ts` behind the error, Open Graph and CORS middleware.
|
||||
* An `APIException` thrown by a handler becomes the JSON error response there.
|
||||
*/
|
||||
const router: Router = new Router({ prefix: "/.well-known" });
|
||||
|
||||
router.get("/openid-configuration", (ctx) => {
|
||||
ctx.response.headers.set("Cache-Control", "public, max-age=600");
|
||||
ctx.response.body = getInstanceMetadata();
|
||||
});
|
||||
|
||||
router.get("/jwks.json", async (ctx) => {
|
||||
ctx.response.headers.set("Cache-Control", "public, max-age=600");
|
||||
ctx.response.body = await getPublicKeys();
|
||||
});
|
||||
|
||||
export default router;
|
||||
125
api/services/federation-peer-service.ts
Normal file
125
api/services/federation-peer-service.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Keeps the instances an admin trusts or blocks for federated sign-in
|
||||
* (`federation_peers`). Users of a trusted instance sign in here directly,
|
||||
* those of a blocked one never do, and an instance on neither list is invite
|
||||
* only. `federation-service.ts` reads it at each sign-in, `/manage` edits it
|
||||
* through `routes/federation.ts`, and the login page offers the trusted ones.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { db } from "../db/connection.ts";
|
||||
import { PUBLIC_URL } from "../config.ts";
|
||||
import {
|
||||
type FederationPeer,
|
||||
instanceHost,
|
||||
isPeerStatus,
|
||||
parseInstance,
|
||||
type PeerStatus,
|
||||
} from "../../shared/federation.ts";
|
||||
import { fetchMetadata } from "../remote/gerbeur-instance.ts";
|
||||
import { closeUserSockets } from "./ws-service.ts";
|
||||
|
||||
interface PeerRow {
|
||||
issuer: string;
|
||||
status: string;
|
||||
name: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** Converts a row to a {@link FederationPeer}. */
|
||||
function rowToPeer(row: PeerRow): FederationPeer {
|
||||
return {
|
||||
issuer: row.issuer,
|
||||
host: instanceHost(row.issuer),
|
||||
name: row.name,
|
||||
status: isPeerStatus(row.status) ? row.status : "blocked",
|
||||
createdAt: new Date(row.created_at),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns what an admin decided about the instance at `issuer`, or null when
|
||||
* it is on neither list.
|
||||
*/
|
||||
export function getPeerStatus(issuer: string): PeerStatus | null {
|
||||
const row = db.prepare(
|
||||
`SELECT status FROM federation_peers WHERE issuer = ?;`,
|
||||
).get(issuer) as { status: string } | undefined;
|
||||
return row && isPeerStatus(row.status) ? row.status : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instances on the lists, by name: every one for `/manage`, or
|
||||
* only the trusted ones, which the login page offers.
|
||||
*/
|
||||
export function listPeers(trustedOnly: boolean): FederationPeer[] {
|
||||
const rows = db.prepare(
|
||||
`SELECT issuer, status, name, created_at FROM federation_peers
|
||||
${trustedOnly ? "WHERE status = 'trusted'" : ""}
|
||||
ORDER BY lower(coalesce(name, issuer));`,
|
||||
).all() as unknown as PeerRow[];
|
||||
return rows.map(rowToPeer);
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the instance `instance` names on the list of `status`, for `/manage`,
|
||||
* and returns it. It must answer as a gerbeur instance, whose name is kept.
|
||||
* Blocking one ends the sessions of its users here at once: their tokens stop
|
||||
* counting by `getSessionState`, and this closes their sockets.
|
||||
*
|
||||
* @throws {APIException} 400 when `instance` names no instance, or this one,
|
||||
* 502 when it doesn't answer as a gerbeur instance.
|
||||
*/
|
||||
export async function setPeer(
|
||||
instance: string,
|
||||
status: PeerStatus,
|
||||
): Promise<FederationPeer> {
|
||||
const issuer = parseInstance(instance);
|
||||
if (!issuer) throw new APIException(400, "Not an instance's address");
|
||||
if (issuer === PUBLIC_URL) {
|
||||
throw new APIException(400, "That is this instance");
|
||||
}
|
||||
let name: string;
|
||||
try {
|
||||
name = (await fetchMetadata(issuer)).gerbeur_site_name;
|
||||
} catch (err) {
|
||||
console.error(`[federation] ${issuer} can't be added:`, err);
|
||||
throw new APIException(502, "That address doesn't answer as a gerbeur");
|
||||
}
|
||||
db.prepare(
|
||||
`INSERT INTO federation_peers (issuer, status, name, created_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT (issuer) DO UPDATE SET status = excluded.status, name = excluded.name;`,
|
||||
).run(issuer, status, name, new Date().toISOString());
|
||||
|
||||
if (status === "blocked") {
|
||||
const users = db.prepare(
|
||||
`SELECT user_id FROM user_identities WHERE issuer = ?;`,
|
||||
).all(issuer) as { user_id: string }[];
|
||||
for (const { user_id } of users) {
|
||||
closeUserSockets(user_id, "Instance blocked");
|
||||
}
|
||||
}
|
||||
|
||||
const row = db.prepare(
|
||||
`SELECT issuer, status, name, created_at FROM federation_peers WHERE issuer = ?;`,
|
||||
).get(issuer) as unknown as PeerRow;
|
||||
return rowToPeer(row);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes the instance whose host is `host` off the lists, for `/manage`: its
|
||||
* users are invite only again, and those already here may sign in again if it
|
||||
* was blocked.
|
||||
*
|
||||
* @throws {APIException} 404 when no listed instance has that host.
|
||||
*/
|
||||
export function removePeer(host: string): void {
|
||||
const peer = listPeers(false).find((p) => p.host === host.toLowerCase());
|
||||
if (!peer) throw new APIException(404, "Instance not found");
|
||||
db.prepare(`DELETE FROM federation_peers WHERE issuer = ?;`).run(
|
||||
peer.issuer,
|
||||
);
|
||||
}
|
||||
376
api/services/federation-service.ts
Normal file
376
api/services/federation-service.ts
Normal file
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* Plays the client in federated sign-in: it lets users of other gerbeur
|
||||
* instances sign in here with their account there, their home.
|
||||
*
|
||||
* 1. The login or register page names the user's home, and
|
||||
* {@link startLogin} answers the home's `/authorize` page with a request:
|
||||
* a random state, the hash of a PKCE verifier, and a nonce, kept in
|
||||
* `federation_logins` for 10 minutes.
|
||||
* 2. The home sends the user back to the `/federation/callback` page with a
|
||||
* code. {@link completeLogin} trades it for the home's identity token,
|
||||
* checks its signature against the home's keys, and finds or creates the
|
||||
* local account linked to it (`user_identities`), named `<name>@<host>`.
|
||||
* 3. The home's events ({@link receiveEvent}) keep the account's name, email
|
||||
* and avatar in step, and end its sessions when the home says so.
|
||||
*
|
||||
* Whether a user of another instance may join is the admin's call
|
||||
* (`federation-peer-service.ts`): from a trusted instance they may, from a
|
||||
* blocked one they may not, and from any other only with an invite, which the
|
||||
* register page carries. Once here, an account works like any other, but its
|
||||
* password, email, avatar and name are its home's (`assertLocalUser`).
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { decodeJwt } from "@panva/jose";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { db, transaction } from "../db/connection.ts";
|
||||
import { verifyInstanceToken } from "../lib/jwt.ts";
|
||||
import {
|
||||
type FederationLoginRequest,
|
||||
type FederationSessionRequest,
|
||||
type IdentityClaims,
|
||||
instanceHost,
|
||||
isFederationEvent,
|
||||
isIdentityClaims,
|
||||
parseInstance,
|
||||
} from "../../shared/federation.ts";
|
||||
import { EMAIL_RE, USERNAME_RE } from "../../shared/validation.ts";
|
||||
import { toPublicUser, type User } from "../model/user.ts";
|
||||
import {
|
||||
exchangeCode,
|
||||
fetchAvatar,
|
||||
fetchKeys,
|
||||
fetchMetadata,
|
||||
} from "../remote/gerbeur-instance.ts";
|
||||
import { ISSUER, REDIRECT_URI } from "./identity-provider-service.ts";
|
||||
import { getPeerStatus } from "./federation-peer-service.ts";
|
||||
import {
|
||||
claimInvite,
|
||||
releaseInvite,
|
||||
validateInvite,
|
||||
} from "./invite-service.ts";
|
||||
import {
|
||||
createRemoteUser,
|
||||
getUserById,
|
||||
revokeSessions,
|
||||
sendWelcomeEmail,
|
||||
setUserAvatar,
|
||||
setUsername,
|
||||
updateUser,
|
||||
} from "./user-service.ts";
|
||||
import { broadcastUserUpdated, updateClientUsername } from "./ws-service.ts";
|
||||
|
||||
/** How long a sign-in may take, from the login page to the callback. */
|
||||
const LOGIN_TTL_MS = 10 * 60_000;
|
||||
|
||||
/**
|
||||
* Returns the origin of the instance `instance` names, checked as a home: not
|
||||
* this instance, nor a blocked one.
|
||||
*
|
||||
* @throws {APIException} 400 when it names no instance or this one, 403 when
|
||||
* it is blocked.
|
||||
*/
|
||||
function homeOf(instance: string): string {
|
||||
const issuer = parseInstance(instance);
|
||||
if (!issuer) throw new APIException(400, "Not an instance's address");
|
||||
if (issuer === ISSUER) throw new APIException(400, "That is this instance");
|
||||
if (getPeerStatus(issuer) === "blocked") {
|
||||
throw new APIException(403, "This instance is blocked here");
|
||||
}
|
||||
return issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a sign-in with an account on the instance `request.instance` names,
|
||||
* and returns its `/authorize` page with the request, for
|
||||
* `POST /api/federation/logins`. Unless that instance is trusted, or someone
|
||||
* here already comes from it, the request must carry a valid invite, which is
|
||||
* claimed only once the account is made; {@link completeLogin} makes no
|
||||
* account without one.
|
||||
*
|
||||
* @throws {APIException} 400 when the instance isn't one; 403 when it is
|
||||
* blocked, or neither trusted nor invited; 404 or 409 when the invite doesn't
|
||||
* work; 502 when it doesn't answer as a gerbeur.
|
||||
*/
|
||||
export async function startLogin(
|
||||
request: FederationLoginRequest,
|
||||
): Promise<string> {
|
||||
const issuer = homeOf(request.instance);
|
||||
if (request.inviteToken) {
|
||||
validateInvite(request.inviteToken);
|
||||
} else if (
|
||||
getPeerStatus(issuer) !== "trusted" &&
|
||||
// Someone who joined with an invite signs in again without one; whether
|
||||
// this user is one of them is only known once their home answers.
|
||||
!db.prepare(`SELECT 1 FROM user_identities WHERE issuer = ? LIMIT 1;`)
|
||||
.get(issuer)
|
||||
) {
|
||||
throw new APIException(
|
||||
403,
|
||||
"Users of this instance need an invite to join",
|
||||
);
|
||||
}
|
||||
|
||||
let authorizationEndpoint: string;
|
||||
try {
|
||||
authorizationEndpoint = (await fetchMetadata(issuer))
|
||||
.authorization_endpoint;
|
||||
} catch (err) {
|
||||
console.error(`[federation] ${issuer} unreachable:`, err);
|
||||
throw new APIException(502, "That instance doesn't answer as a gerbeur");
|
||||
}
|
||||
|
||||
const state = randomBytes(24).toString("base64url");
|
||||
const verifier = randomBytes(48).toString("base64url");
|
||||
const nonce = randomBytes(24).toString("base64url");
|
||||
const now = new Date();
|
||||
transaction(() => {
|
||||
db.prepare(`DELETE FROM federation_logins WHERE created_at < ?;`).run(
|
||||
new Date(now.getTime() - LOGIN_TTL_MS).toISOString(),
|
||||
);
|
||||
db.prepare(
|
||||
`INSERT INTO federation_logins (state, issuer, code_verifier, nonce, invite_token, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?);`,
|
||||
).run(
|
||||
state,
|
||||
issuer,
|
||||
verifier,
|
||||
nonce,
|
||||
request.inviteToken ?? null,
|
||||
now.toISOString(),
|
||||
);
|
||||
});
|
||||
|
||||
const url = new URL(authorizationEndpoint);
|
||||
url.search = new URLSearchParams({
|
||||
response_type: "code",
|
||||
scope: "openid profile email",
|
||||
client_id: ISSUER,
|
||||
redirect_uri: REDIRECT_URI,
|
||||
state,
|
||||
code_challenge: createHash("sha256").update(verifier).digest("base64url"),
|
||||
code_challenge_method: "S256",
|
||||
nonce,
|
||||
}).toString();
|
||||
return url.href;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the payload of `token`, an identity token or an event from the
|
||||
* instance at `issuer`, once its signature checks against that instance's
|
||||
* keys and it is addressed to this one. The keys are refetched once when the
|
||||
* token names one they lack.
|
||||
*
|
||||
* @throws {APIException} 401 when it doesn't verify.
|
||||
*/
|
||||
async function verifyFrom(
|
||||
token: string,
|
||||
issuer: string,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const claims = { issuer, audience: ISSUER };
|
||||
try {
|
||||
try {
|
||||
return await verifyInstanceToken(token, await fetchKeys(issuer), claims);
|
||||
} catch (err) {
|
||||
if ((err as { code?: string }).code !== "ERR_JWKS_NO_MATCHING_KEY") {
|
||||
throw err;
|
||||
}
|
||||
return await verifyInstanceToken(
|
||||
token,
|
||||
await fetchKeys(issuer, true),
|
||||
claims,
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[federation] a token from ${issuer} failed:`, err);
|
||||
throw new APIException(401, "Invalid token");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `claims` once checked: a name a local user could have, and an email.
|
||||
*
|
||||
* @throws {APIException} 502 when the home sent something else.
|
||||
*/
|
||||
function checkClaims(claims: unknown): IdentityClaims {
|
||||
if (
|
||||
!isIdentityClaims(claims) ||
|
||||
!USERNAME_RE.test(claims.preferred_username) ||
|
||||
!EMAIL_RE.test(claims.email)
|
||||
) {
|
||||
throw new APIException(502, "The instance sent an invalid identity");
|
||||
}
|
||||
return claims;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes a sign-in begun by {@link startLogin}, for
|
||||
* `POST /api/federation/sessions`, and returns the account it signs in to:
|
||||
* the one linked to the identity, brought up to date, or a new one. A login
|
||||
* works once. A new account needs the home to be trusted, or the invite the
|
||||
* login was started with, claimed now.
|
||||
*
|
||||
* @throws {APIException} 400 when the login is unknown or expired; 401 when
|
||||
* the identity token doesn't verify; 403 when the account may not be created;
|
||||
* 409 when its handle is someone's; 502 when the home fails.
|
||||
*/
|
||||
export async function completeLogin(
|
||||
request: FederationSessionRequest,
|
||||
): Promise<User> {
|
||||
const login = db.prepare(
|
||||
`DELETE FROM federation_logins WHERE state = ?
|
||||
RETURNING issuer, code_verifier, nonce, invite_token, created_at;`,
|
||||
).get(request.state) as
|
||||
| {
|
||||
issuer: string;
|
||||
code_verifier: string;
|
||||
nonce: string;
|
||||
invite_token: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
| undefined;
|
||||
if (
|
||||
!login ||
|
||||
Date.now() - new Date(login.created_at).getTime() > LOGIN_TTL_MS
|
||||
) {
|
||||
throw new APIException(400, "This sign-in has expired, start again");
|
||||
}
|
||||
const issuer = login.issuer;
|
||||
|
||||
let idToken: string;
|
||||
try {
|
||||
idToken = await exchangeCode(issuer, {
|
||||
code: request.code,
|
||||
clientId: ISSUER,
|
||||
redirectUri: REDIRECT_URI,
|
||||
codeVerifier: login.code_verifier,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`[federation] ${issuer} refused a code:`, err);
|
||||
throw new APIException(502, "The instance refused the sign-in");
|
||||
}
|
||||
const payload = await verifyFrom(idToken, issuer);
|
||||
if (payload.nonce !== login.nonce || typeof payload.sub !== "string") {
|
||||
throw new APIException(401, "Invalid token");
|
||||
}
|
||||
const claims = checkClaims(payload);
|
||||
const subject = payload.sub;
|
||||
|
||||
const identity = db.prepare(
|
||||
`SELECT user_id FROM user_identities WHERE issuer = ? AND subject = ?;`,
|
||||
).get(issuer, subject) as { user_id: string } | undefined;
|
||||
if (getPeerStatus(issuer) === "blocked") {
|
||||
throw new APIException(403, "This instance is blocked here");
|
||||
}
|
||||
if (identity) {
|
||||
return await applyClaims(identity.user_id, issuer, claims);
|
||||
}
|
||||
|
||||
const trusted = getPeerStatus(issuer) === "trusted";
|
||||
if (!trusted && !login.invite_token) {
|
||||
throw new APIException(
|
||||
403,
|
||||
"Users of this instance need an invite to join",
|
||||
);
|
||||
}
|
||||
const inviterId = trusted ? null : claimInvite(login.invite_token!);
|
||||
let user: User;
|
||||
try {
|
||||
user = transaction(() => {
|
||||
const created = createRemoteUser({
|
||||
username: `${claims.preferred_username}@${instanceHost(issuer)}`,
|
||||
email: claims.email,
|
||||
}, inviterId);
|
||||
db.prepare(
|
||||
`INSERT INTO user_identities (user_id, issuer, subject, synced_at) VALUES (?, ?, ?, ?);`,
|
||||
).run(created.id, issuer, subject, new Date().toISOString());
|
||||
return created;
|
||||
});
|
||||
} catch (err) {
|
||||
if (!trusted) releaseInvite(login.invite_token!);
|
||||
throw err;
|
||||
}
|
||||
sendWelcomeEmail(user);
|
||||
return await applyClaims(user.id, issuer, claims);
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings the account `userId`, from the instance at `issuer`, in step with
|
||||
* `claims` and returns it: a new name at home renames it, the old handle
|
||||
* staying its alias, and a new email or avatar replaces its own. A failed
|
||||
* avatar fetch is logged, and tried again at the next change or sign-in.
|
||||
*
|
||||
* @throws {APIException} 409 when the new handle is someone else's.
|
||||
*/
|
||||
async function applyClaims(
|
||||
userId: string,
|
||||
issuer: string,
|
||||
claims: IdentityClaims,
|
||||
): Promise<User> {
|
||||
let user = getUserById(userId);
|
||||
const handle = `${claims.preferred_username}@${instanceHost(issuer)}`;
|
||||
if (handle !== user.username) {
|
||||
user = setUsername(userId, handle);
|
||||
updateClientUsername(userId, handle);
|
||||
broadcastUserUpdated(toPublicUser(user));
|
||||
}
|
||||
if (claims.email !== user.email) {
|
||||
user = await updateUser(userId, { email: claims.email });
|
||||
}
|
||||
|
||||
const { picture } = db.prepare(
|
||||
`SELECT picture FROM user_identities WHERE user_id = ?;`,
|
||||
).get(userId) as { picture: string | null };
|
||||
let synced = claims.picture ?? null;
|
||||
if (claims.picture && claims.picture !== picture) {
|
||||
try {
|
||||
user = await setUserAvatar(userId, await fetchAvatar(claims.picture));
|
||||
} catch (err) {
|
||||
console.error(`[federation] ${handle}'s avatar failed:`, err);
|
||||
synced = picture;
|
||||
}
|
||||
}
|
||||
db.prepare(
|
||||
`UPDATE user_identities SET picture = ?, synced_at = ? WHERE user_id = ?;`,
|
||||
).run(synced, new Date().toISOString(), userId);
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the signed event `token` from a user's home, for
|
||||
* `POST /api/federation/events`: `update` brings their account in step,
|
||||
* `revoke` ends their sessions here. Only an instance some account here comes
|
||||
* from may send one, about one of those accounts.
|
||||
*
|
||||
* @throws {APIException} 400 when it isn't an event of a known instance about
|
||||
* one of its users; 401 when it doesn't verify.
|
||||
*/
|
||||
export async function receiveEvent(token: string): Promise<void> {
|
||||
let issuer: unknown;
|
||||
try {
|
||||
issuer = decodeJwt(token).iss;
|
||||
} catch {
|
||||
throw new APIException(400, "Invalid event");
|
||||
}
|
||||
if (
|
||||
typeof issuer !== "string" ||
|
||||
!db.prepare(`SELECT 1 FROM user_identities WHERE issuer = ? LIMIT 1;`)
|
||||
.get(issuer)
|
||||
) {
|
||||
throw new APIException(400, "Unknown instance");
|
||||
}
|
||||
const payload = await verifyFrom(token, issuer);
|
||||
const identity = db.prepare(
|
||||
`SELECT user_id FROM user_identities WHERE issuer = ? AND subject = ?;`,
|
||||
).get(issuer, String(payload.sub)) as { user_id: string } | undefined;
|
||||
if (!identity || !isFederationEvent(payload)) {
|
||||
throw new APIException(400, "Invalid event");
|
||||
}
|
||||
if (payload.type === "revoke") {
|
||||
revokeSessions(identity.user_id, new Date(), "Signed out by home");
|
||||
} else {
|
||||
await applyClaims(identity.user_id, issuer, checkClaims(payload.claims));
|
||||
}
|
||||
}
|
||||
438
api/services/identity-provider-service.ts
Normal file
438
api/services/identity-provider-service.ts
Normal file
@@ -0,0 +1,438 @@
|
||||
/**
|
||||
* Plays the home instance in federated sign-in: it lets this instance's users
|
||||
* sign in to other gerbeur instances with their account here.
|
||||
*
|
||||
* The flow is OpenID Connect's authorization code with PKCE, in three steps.
|
||||
*
|
||||
* 1. Another instance, the client, sends the user to the `/authorize` page
|
||||
* with a request. The page shows who asks ({@link describeClient}) and,
|
||||
* once the user consents, gets a code ({@link createAuthorizationCode}),
|
||||
* which it carries back to the client's callback page.
|
||||
* 2. The client trades the code for an identity token, server to server
|
||||
* ({@link exchangeCode}): this user's name, email and avatar, signed with
|
||||
* the instance key.
|
||||
* 3. While the user's grant lasts, the client hears of their changes: a new
|
||||
* name, email or avatar, and the end of their sessions after a password
|
||||
* change. {@link notifyClients} queues the signed events in
|
||||
* `federation_outbox`, and {@link outboxJob} delivers them.
|
||||
*
|
||||
* Only a local account signs in elsewhere: a user who came from another
|
||||
* instance signs in from there. `routes/oauth.ts`, `routes/well-known.ts` and
|
||||
* the routes that change a user call it.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { APIException } from "../lib/api-exception.ts";
|
||||
import { db, transaction } from "../db/connection.ts";
|
||||
import { FRONTEND_URL, OG_SITE_NAME, PUBLIC_URL } from "../config.ts";
|
||||
import { signInstanceToken } from "../lib/jwt.ts";
|
||||
import type { Job } from "../lib/scheduler.ts";
|
||||
import {
|
||||
type AuthorizeRequest,
|
||||
FEDERATION_VERSION,
|
||||
type FederationEvent,
|
||||
type FederationGrant,
|
||||
type IdentityClaims,
|
||||
instanceHost,
|
||||
type InstanceMetadata,
|
||||
type OAuthClient,
|
||||
parseInstance,
|
||||
} from "../../shared/federation.ts";
|
||||
import { fetchMetadata, postEvent } from "../remote/gerbeur-instance.ts";
|
||||
import { isRemoteUser, type User } from "../model/user.ts";
|
||||
import { getSigningKey } from "./instance-key-service.ts";
|
||||
import { getUserById } from "./user-service.ts";
|
||||
import { getPeerStatus } from "./federation-peer-service.ts";
|
||||
|
||||
/**
|
||||
* The instance's name in every token it signs and every token addressed to
|
||||
* it: its public URL, which must be an origin for other instances to find
|
||||
* its metadata.
|
||||
*/
|
||||
export const ISSUER: string = PUBLIC_URL;
|
||||
|
||||
/**
|
||||
* The client's page a home instance sends the user back to, on the frontend.
|
||||
* Its metadata announces it, and a home accepts no other.
|
||||
*/
|
||||
export const REDIRECT_URI = `${FRONTEND_URL}/federation/callback`;
|
||||
|
||||
/** How long a code may wait to be traded, from the consent. */
|
||||
const CODE_TTL_MS = 60_000;
|
||||
|
||||
/**
|
||||
* How long an identity token is valid: enough to cross from one server to the
|
||||
* other, never enough to be replayed later.
|
||||
*/
|
||||
const ID_TOKEN_TTL = "5m";
|
||||
|
||||
/**
|
||||
* How long an event is valid, and so how long the outbox keeps trying to
|
||||
* deliver it before giving up.
|
||||
*/
|
||||
const EVENT_TTL_MS = 3 * 86_400_000;
|
||||
|
||||
/** The longest wait between two tries of an event. */
|
||||
const MAX_RETRY_MS = 6 * 3_600_000;
|
||||
|
||||
/**
|
||||
* Returns the instance's metadata, served at
|
||||
* `/.well-known/openid-configuration`.
|
||||
*/
|
||||
export function getInstanceMetadata(): InstanceMetadata {
|
||||
return {
|
||||
issuer: ISSUER,
|
||||
authorization_endpoint: `${FRONTEND_URL}/authorize`,
|
||||
token_endpoint: `${PUBLIC_URL}/api/oauth/tokens`,
|
||||
jwks_uri: `${PUBLIC_URL}/.well-known/jwks.json`,
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code"],
|
||||
subject_types_supported: ["public"],
|
||||
id_token_signing_alg_values_supported: ["EdDSA"],
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
scopes_supported: ["openid", "profile", "email"],
|
||||
gerbeur_federation: FEDERATION_VERSION,
|
||||
gerbeur_site_name: OG_SITE_NAME,
|
||||
gerbeur_redirect_uri: REDIRECT_URI,
|
||||
gerbeur_events_endpoint: `${PUBLIC_URL}/api/federation/events`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns the SHA-256 of `value`, as base64url. */
|
||||
function sha256(value: string): string {
|
||||
return createHash("sha256").update(value).digest("base64url");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns what this instance tells another of `user`: their name, email and
|
||||
* avatar, whose URL changes with each new one.
|
||||
*/
|
||||
export function identityClaims(user: User): IdentityClaims {
|
||||
return {
|
||||
preferred_username: user.username,
|
||||
email: user.email,
|
||||
...(user.avatarMime && {
|
||||
picture: `${PUBLIC_URL}/api/users/${user.id}/avatar?v=${
|
||||
user.updatedAt?.getTime() ?? 0
|
||||
}`,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the client `clientId` names, checked: an instance other than this
|
||||
* one, not blocked here, answering as a gerbeur. `user` must have a local
|
||||
* account, which alone may sign in elsewhere.
|
||||
*
|
||||
* @throws {APIException} 400 when `clientId` isn't an instance's address, is
|
||||
* this instance, or `user` comes from another instance; 403 when the client
|
||||
* is blocked here; 502 when it doesn't answer as a gerbeur.
|
||||
*/
|
||||
async function checkClient(
|
||||
user: User,
|
||||
clientId: string,
|
||||
): Promise<{ clientId: string; metadata: InstanceMetadata }> {
|
||||
if (isRemoteUser(user)) {
|
||||
throw new APIException(
|
||||
400,
|
||||
"This account signs in from the instance it comes from",
|
||||
);
|
||||
}
|
||||
if (parseInstance(clientId) !== clientId || clientId === ISSUER) {
|
||||
throw new APIException(400, "Invalid client");
|
||||
}
|
||||
if (getPeerStatus(clientId) === "blocked") {
|
||||
throw new APIException(403, "This instance is blocked here");
|
||||
}
|
||||
try {
|
||||
return { clientId, metadata: await fetchMetadata(clientId) };
|
||||
} catch (err) {
|
||||
console.error(`[federation] client ${clientId} unreachable:`, err);
|
||||
throw new APIException(502, "That instance doesn't answer as a gerbeur");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instance `clientId` names, for the `/authorize` page's question
|
||||
* to user `userId`, and whether they already let it sign them in.
|
||||
*
|
||||
* @throws {APIException} As {@link checkClient}.
|
||||
*/
|
||||
export async function describeClient(
|
||||
userId: string,
|
||||
clientId: string,
|
||||
): Promise<OAuthClient> {
|
||||
const { metadata } = await checkClient(getUserById(userId), clientId);
|
||||
const granted = !!db.prepare(
|
||||
`SELECT 1 FROM federation_grants WHERE user_id = ? AND client_id = ?;`,
|
||||
).get(userId, clientId);
|
||||
return {
|
||||
clientId,
|
||||
host: instanceHost(clientId),
|
||||
name: metadata.gerbeur_site_name,
|
||||
granted,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Records user `userId`'s consent to sign in to the client of `request`, and
|
||||
* returns where to send them: the client's callback page with a code, which
|
||||
* the client trades within a minute ({@link exchangeCode}). The grant lasts
|
||||
* until they withdraw it, so the page asks no more.
|
||||
*
|
||||
* @throws {APIException} 400 when the request is malformed or its
|
||||
* `redirectUri` isn't the client's own; otherwise as {@link checkClient}.
|
||||
*/
|
||||
export async function createAuthorizationCode(
|
||||
userId: string,
|
||||
request: AuthorizeRequest,
|
||||
): Promise<string> {
|
||||
const user = getUserById(userId);
|
||||
const { clientId, metadata } = await checkClient(user, request.clientId);
|
||||
if (request.redirectUri !== metadata.gerbeur_redirect_uri) {
|
||||
throw new APIException(400, "Invalid redirect URI");
|
||||
}
|
||||
if (
|
||||
request.codeChallengeMethod !== "S256" ||
|
||||
!/^[A-Za-z0-9_-]{43}$/.test(request.codeChallenge) ||
|
||||
!request.state || request.state.length > 512 ||
|
||||
!request.nonce || request.nonce.length > 512
|
||||
) {
|
||||
throw new APIException(400, "Invalid request");
|
||||
}
|
||||
|
||||
const code = randomBytes(32).toString("base64url");
|
||||
const now = new Date();
|
||||
transaction(() => {
|
||||
db.prepare(`DELETE FROM oauth_codes WHERE expires_at < ?;`).run(
|
||||
now.toISOString(),
|
||||
);
|
||||
db.prepare(
|
||||
`INSERT INTO oauth_codes (code_hash, user_id, client_id, redirect_uri, code_challenge, nonce, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?);`,
|
||||
).run(
|
||||
sha256(code),
|
||||
userId,
|
||||
clientId,
|
||||
request.redirectUri,
|
||||
request.codeChallenge,
|
||||
request.nonce,
|
||||
new Date(now.getTime() + CODE_TTL_MS).toISOString(),
|
||||
);
|
||||
db.prepare(
|
||||
`INSERT INTO federation_grants (user_id, client_id, client_name, granted_at, last_used_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
ON CONFLICT (user_id, client_id) DO UPDATE SET client_name = excluded.client_name;`,
|
||||
).run(
|
||||
userId,
|
||||
clientId,
|
||||
metadata.gerbeur_site_name,
|
||||
now.toISOString(),
|
||||
now.toISOString(),
|
||||
);
|
||||
});
|
||||
|
||||
const redirect = new URL(request.redirectUri);
|
||||
redirect.searchParams.set("code", code);
|
||||
redirect.searchParams.set("state", request.state);
|
||||
// RFC 9207: tells the client which instance answered, against mix-ups.
|
||||
redirect.searchParams.set("iss", ISSUER);
|
||||
return redirect.href;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trades a code for an identity token, for `POST /api/oauth/tokens`, which
|
||||
* the client calls server to server with the form `params`. A code works once,
|
||||
* within a minute, for the client and redirect it was made for, and with the
|
||||
* verifier whose hash the request carried (PKCE). The token, signed with the
|
||||
* instance key and addressed to the client, carries {@link identityClaims}
|
||||
* and the request's nonce.
|
||||
*
|
||||
* @throws {APIException} 400 when anything doesn't match.
|
||||
*/
|
||||
export async function exchangeCode(
|
||||
params: URLSearchParams,
|
||||
): Promise<{ id_token: string; token_type: string }> {
|
||||
const code = params.get("code");
|
||||
const clientId = params.get("client_id");
|
||||
const verifier = params.get("code_verifier");
|
||||
if (
|
||||
params.get("grant_type") !== "authorization_code" || !code || !clientId ||
|
||||
!verifier || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)
|
||||
) {
|
||||
throw new APIException(400, "invalid_request");
|
||||
}
|
||||
|
||||
// Taken in the same statement that finds it, so it can't be traded twice.
|
||||
const row = db.prepare(
|
||||
`DELETE FROM oauth_codes WHERE code_hash = ?
|
||||
RETURNING user_id, client_id, redirect_uri, code_challenge, nonce, expires_at;`,
|
||||
).get(sha256(code)) as
|
||||
| {
|
||||
user_id: string;
|
||||
client_id: string;
|
||||
redirect_uri: string;
|
||||
code_challenge: string;
|
||||
nonce: string;
|
||||
expires_at: string;
|
||||
}
|
||||
| undefined;
|
||||
if (
|
||||
!row || row.expires_at < new Date().toISOString() ||
|
||||
row.client_id !== clientId ||
|
||||
row.redirect_uri !== params.get("redirect_uri") ||
|
||||
row.code_challenge !== sha256(verifier)
|
||||
) {
|
||||
throw new APIException(400, "invalid_grant");
|
||||
}
|
||||
|
||||
const user = getUserById(row.user_id);
|
||||
if (isRemoteUser(user)) throw new APIException(400, "invalid_grant");
|
||||
db.prepare(
|
||||
`UPDATE federation_grants SET last_used_at = ? WHERE user_id = ? AND client_id = ?;`,
|
||||
).run(new Date().toISOString(), user.id, clientId);
|
||||
|
||||
const idToken = await signInstanceToken(
|
||||
{ ...identityClaims(user), nonce: row.nonce },
|
||||
await getSigningKey(),
|
||||
{ issuer: ISSUER, audience: clientId, subject: user.id },
|
||||
ID_TOKEN_TTL,
|
||||
);
|
||||
return { id_token: idToken, token_type: "Bearer" };
|
||||
}
|
||||
|
||||
interface GrantRow {
|
||||
client_id: string;
|
||||
client_name: string | null;
|
||||
granted_at: string;
|
||||
last_used_at: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instances user `userId` let their account sign in to, the most
|
||||
* recently used first, for the settings page.
|
||||
*/
|
||||
export function listGrants(userId: string): FederationGrant[] {
|
||||
const rows = db.prepare(
|
||||
`SELECT client_id, client_name, granted_at, last_used_at FROM federation_grants
|
||||
WHERE user_id = ? ORDER BY last_used_at DESC;`,
|
||||
).all(userId) as unknown as GrantRow[];
|
||||
return rows.map((r) => ({
|
||||
clientId: r.client_id,
|
||||
host: instanceHost(r.client_id),
|
||||
name: r.client_name,
|
||||
grantedAt: new Date(r.granted_at),
|
||||
lastUsedAt: new Date(r.last_used_at),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Withdraws user `userId`'s grant to the instance whose host is `host`: it
|
||||
* stops answering for them there, and is told to end their sessions.
|
||||
*
|
||||
* @throws {APIException} 404 when they gave that instance no grant.
|
||||
*/
|
||||
export async function revokeGrant(userId: string, host: string): Promise<void> {
|
||||
const grant = listGrants(userId).find((g) => g.host === host.toLowerCase());
|
||||
if (!grant) throw new APIException(404, "Grant not found");
|
||||
await notifyClients(userId, { type: "revoke" }, [grant.clientId]);
|
||||
db.prepare(
|
||||
`DELETE FROM federation_grants WHERE user_id = ? AND client_id = ?;`,
|
||||
).run(userId, grant.clientId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells each instance user `userId` signed in to of `event`, or only those of
|
||||
* `clientIds`: `update` when their name, email or avatar changed, `revoke`
|
||||
* when their sessions there must end. The routes that change a user call it,
|
||||
* and for an `update`, `event` may be just the type: the claims are read now.
|
||||
* The events are queued in the outbox and their delivery starts at once.
|
||||
*/
|
||||
export async function notifyClients(
|
||||
userId: string,
|
||||
event: FederationEvent | { type: "update" },
|
||||
clientIds?: string[],
|
||||
): Promise<void> {
|
||||
const clients = clientIds ?? listGrants(userId).map((g) => g.clientId);
|
||||
if (clients.length === 0) return;
|
||||
const payload: FederationEvent = event.type === "update"
|
||||
? { type: "update", claims: identityClaims(getUserById(userId)) }
|
||||
: event;
|
||||
|
||||
const key = await getSigningKey();
|
||||
const now = new Date();
|
||||
for (const clientId of clients) {
|
||||
const token = await signInstanceToken(
|
||||
{ ...payload },
|
||||
key,
|
||||
{ issuer: ISSUER, audience: clientId, subject: userId },
|
||||
`${EVENT_TTL_MS / 1000}s`,
|
||||
);
|
||||
db.prepare(
|
||||
`INSERT INTO federation_outbox (id, client_id, event, next_attempt_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?);`,
|
||||
).run(
|
||||
crypto.randomUUID(),
|
||||
clientId,
|
||||
token,
|
||||
now.toISOString(),
|
||||
now.toISOString(),
|
||||
);
|
||||
}
|
||||
deliverOutbox().catch((err) =>
|
||||
console.error("[federation] delivery failed:", err)
|
||||
);
|
||||
}
|
||||
|
||||
/** Set while {@link deliverOutbox} runs, so that two runs don't overlap. */
|
||||
let delivering = false;
|
||||
|
||||
/**
|
||||
* Sends each due event of the outbox to its instance. One it took, or refused
|
||||
* for good, leaves the outbox; one that failed waits twice as long as the time
|
||||
* before, up to 6 hours, until it expires after 3 days.
|
||||
*/
|
||||
export async function deliverOutbox(): Promise<void> {
|
||||
if (delivering) return;
|
||||
delivering = true;
|
||||
try {
|
||||
const now = new Date();
|
||||
db.prepare(`DELETE FROM federation_outbox WHERE created_at < ?;`).run(
|
||||
new Date(now.getTime() - EVENT_TTL_MS).toISOString(),
|
||||
);
|
||||
const due = db.prepare(
|
||||
`SELECT id, client_id, event, attempts FROM federation_outbox
|
||||
WHERE next_attempt_at <= ? ORDER BY created_at LIMIT 100;`,
|
||||
).all(now.toISOString()) as {
|
||||
id: string;
|
||||
client_id: string;
|
||||
event: string;
|
||||
attempts: number;
|
||||
}[];
|
||||
for (const row of due) {
|
||||
try {
|
||||
if (!await postEvent(row.client_id, row.event)) {
|
||||
console.error(`[federation] ${row.client_id} refused an event`);
|
||||
}
|
||||
db.prepare(`DELETE FROM federation_outbox WHERE id = ?;`).run(row.id);
|
||||
} catch (err) {
|
||||
const wait = Math.min(60_000 * 2 ** row.attempts, MAX_RETRY_MS);
|
||||
db.prepare(
|
||||
`UPDATE federation_outbox SET attempts = attempts + 1, next_attempt_at = ? WHERE id = ?;`,
|
||||
).run(new Date(Date.now() + wait).toISOString(), row.id);
|
||||
console.error(`[federation] ${row.client_id} unreachable:`, err);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
delivering = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Retries the outbox's failed events every minute. */
|
||||
export const outboxJob: Job = {
|
||||
name: "federation",
|
||||
everyMs: 60_000,
|
||||
run: deliverOutbox,
|
||||
};
|
||||
73
api/services/instance-key-service.ts
Normal file
73
api/services/instance-key-service.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Keeps the instance's Ed25519 key, which signs what it tells other instances
|
||||
* in federated sign-in: the identity tokens of `identity-provider-service.ts`
|
||||
* and the events of its outbox. The key is made the first time it's needed
|
||||
* and stored in `federation_keys`, so it survives restarts; other instances
|
||||
* fetch its public half from `GET /.well-known/jwks.json`.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import type { JSONWebKeySet, JWK } from "@panva/jose";
|
||||
import { db } from "../db/connection.ts";
|
||||
import {
|
||||
generateInstanceKey,
|
||||
importInstanceKey,
|
||||
type InstanceSigningKey,
|
||||
} from "../lib/jwt.ts";
|
||||
|
||||
/**
|
||||
* Holds the key once loaded. It is a promise so that two first requests in a
|
||||
* row don't each make a key.
|
||||
*/
|
||||
let current: Promise<InstanceSigningKey> | null = null;
|
||||
|
||||
/**
|
||||
* Returns the key the instance signs with now: the newest stored, or a new
|
||||
* one, stored, when there is none.
|
||||
*/
|
||||
export function getSigningKey(): Promise<InstanceSigningKey> {
|
||||
current ??= loadOrCreate().catch((err) => {
|
||||
current = null;
|
||||
throw err;
|
||||
});
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Reads the newest stored key, or makes and stores the first one. */
|
||||
async function loadOrCreate(): Promise<InstanceSigningKey> {
|
||||
const row = db.prepare(
|
||||
`SELECT kid, private_jwk FROM federation_keys ORDER BY created_at DESC LIMIT 1;`,
|
||||
).get() as { kid: string; private_jwk: string } | undefined;
|
||||
if (row) {
|
||||
return await importInstanceKey(row.kid, JSON.parse(row.private_jwk));
|
||||
}
|
||||
const { kid, privateJwk, publicJwk } = await generateInstanceKey();
|
||||
db.prepare(
|
||||
`INSERT INTO federation_keys (kid, private_jwk, public_jwk, created_at) VALUES (?, ?, ?, ?);`,
|
||||
).run(
|
||||
kid,
|
||||
JSON.stringify(privateJwk),
|
||||
JSON.stringify(publicJwk),
|
||||
new Date().toISOString(),
|
||||
);
|
||||
return await importInstanceKey(kid, privateJwk);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the public halves of every stored key, for
|
||||
* `GET /.well-known/jwks.json`. It makes the first key when there is none, so
|
||||
* that the set is never empty.
|
||||
*/
|
||||
export async function getPublicKeys(): Promise<JSONWebKeySet> {
|
||||
await getSigningKey();
|
||||
const rows = db.prepare(
|
||||
`SELECT public_jwk FROM federation_keys ORDER BY created_at DESC;`,
|
||||
).all() as { public_jwk: string }[];
|
||||
return { keys: rows.map((r) => JSON.parse(r.public_jwk) as JWK) };
|
||||
}
|
||||
|
||||
/** Forgets the loaded key, for the tests, which wipe the table between cases. */
|
||||
export function resetSigningKey(): void {
|
||||
current = null;
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
UserSuggestion,
|
||||
} from "../../shared/user.ts";
|
||||
import {
|
||||
isRemoteUser,
|
||||
isUserRow,
|
||||
toPublicUser,
|
||||
type User,
|
||||
@@ -24,7 +25,13 @@ import {
|
||||
userRowToApi,
|
||||
} from "../model/user.ts";
|
||||
import { db, transaction } from "../db/connection.ts";
|
||||
import { closeUserSockets } from "./ws-service.ts";
|
||||
import {
|
||||
broadcastUserUpdated,
|
||||
closeUserSockets,
|
||||
updateClientAvatar,
|
||||
} from "./ws-service.ts";
|
||||
import { replaceUploadedFile, validateImageUpload } from "../lib/upload.ts";
|
||||
import { AVATARS_DIR } from "../config.ts";
|
||||
|
||||
import { hashPassword } from "../lib/password.ts";
|
||||
import { linkAttachments } from "./attachment-service.ts";
|
||||
@@ -116,6 +123,39 @@ export async function createUser(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the account of a user from another instance, named `username`
|
||||
* (their handle here, `name@host`), with no password, for
|
||||
* `federation-service.ts`, which links it to their identity there in the same
|
||||
* transaction. `inviterId` is whoever invited them, or null when their
|
||||
* instance is trusted.
|
||||
*
|
||||
* @throws {APIException} 409 when the handle is or was someone else's.
|
||||
*/
|
||||
export function createRemoteUser(
|
||||
request: { username: string; email: string },
|
||||
inviterId: string | null,
|
||||
): User {
|
||||
const userId = crypto.randomUUID();
|
||||
const createdAt = new Date();
|
||||
assertUsernameAvailable(request.username);
|
||||
try {
|
||||
db.prepare(
|
||||
`INSERT INTO users (id, username, password_hash, role, created_at, invited_by, email)
|
||||
VALUES (?, ?, '', 'user', ?, ?, ?);`,
|
||||
).run(
|
||||
userId,
|
||||
request.username,
|
||||
createdAt.toISOString(),
|
||||
inviterId,
|
||||
request.email,
|
||||
);
|
||||
} catch (err) {
|
||||
throw uniqueViolationToConflict(err);
|
||||
}
|
||||
return getUserById(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Emails `user` the welcome message, if email is configured. The register
|
||||
* route calls it once the account exists, and doesn't wait: a slow or failing
|
||||
@@ -146,18 +186,28 @@ export function getUserById(userId: string): User {
|
||||
|
||||
/**
|
||||
* Returns the user's live role and their last password change, before which
|
||||
* their tokens don't count, or undefined when the user is gone. `lib/auth.ts`
|
||||
* checks every session and media token against it.
|
||||
* their tokens don't count, or undefined when the user is gone, or comes from
|
||||
* an instance an admin blocked. `lib/auth.ts` checks every session and media
|
||||
* token against it.
|
||||
*/
|
||||
export function getSessionState(
|
||||
userId: string,
|
||||
): { role: Role; tokensValidAfter: string | null } | undefined {
|
||||
const row = db.prepare(
|
||||
`SELECT role, tokens_valid_after FROM users WHERE id = ?;`,
|
||||
`SELECT u.role, u.tokens_valid_after, p.status AS peer_status
|
||||
FROM users u
|
||||
LEFT JOIN user_identities ui ON ui.user_id = u.id
|
||||
LEFT JOIN federation_peers p ON p.issuer = ui.issuer
|
||||
WHERE u.id = ?;`,
|
||||
).get(userId) as
|
||||
| { role: Role; tokens_valid_after: string | null }
|
||||
| {
|
||||
role: Role;
|
||||
tokens_valid_after: string | null;
|
||||
peer_status: string | null;
|
||||
}
|
||||
| undefined;
|
||||
return row && {
|
||||
if (!row || row.peer_status === "blocked") return undefined;
|
||||
return {
|
||||
role: row.role,
|
||||
tokensValidAfter: row.tokens_valid_after,
|
||||
};
|
||||
@@ -225,6 +275,19 @@ export function renameUser(userId: string, username: string): User {
|
||||
`Username must be ${VALIDATION.USERNAME_MIN}–${VALIDATION.USERNAME_MAX} characters and contain only letters, numbers, or underscores`,
|
||||
);
|
||||
}
|
||||
return setUsername(userId, username);
|
||||
}
|
||||
|
||||
/**
|
||||
* Names user `userId` `username`, keeping the old name as their alias as
|
||||
* {@link renameUser} describes, and returns them. The caller has checked the
|
||||
* name: {@link renameUser} checks a local one, and `federation-service.ts`
|
||||
* the handle of a user renamed on their home instance.
|
||||
*
|
||||
* @throws {APIException} 404 when there is no such user, 409 when the name is
|
||||
* or was someone else's.
|
||||
*/
|
||||
export function setUsername(userId: string, username: string): User {
|
||||
const user = getUserById(userId);
|
||||
if (username === user.username) return user;
|
||||
|
||||
@@ -246,13 +309,29 @@ export function renameUser(userId: string, username: string): User {
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws a 409 when an account other than `exceptUserId` has `email`, in any
|
||||
* case. Password resets are looked up by email, so an address must belong to
|
||||
* one account only.
|
||||
* Throws a 400 when `user`'s account lives on another instance
|
||||
* ({@link isRemoteUser}), whose password, email, avatar and name are that
|
||||
* instance's to change. The routes that change them call it first.
|
||||
*/
|
||||
export function assertLocalUser(user: User): void {
|
||||
if (isRemoteUser(user)) {
|
||||
throw new APIException(
|
||||
400,
|
||||
"This account is managed on the instance it comes from",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws a 409 when a local account other than `exceptUserId` has `email`, in
|
||||
* any case. Password resets are looked up by email, so an address must belong
|
||||
* to one local account only; an account from another instance may share it,
|
||||
* as the same person may have both.
|
||||
*/
|
||||
function assertEmailAvailable(email: string, exceptUserId?: string): void {
|
||||
const row = db.prepare(
|
||||
`SELECT id FROM users WHERE lower(email) = lower(?) AND id != ?;`,
|
||||
`SELECT id FROM users
|
||||
WHERE lower(email) = lower(?) AND id != ? AND password_hash != '';`,
|
||||
).get(email, exceptUserId ?? "");
|
||||
if (row) {
|
||||
throw new APIException(409, "Email already in use");
|
||||
@@ -271,12 +350,13 @@ function uniqueViolationToConflict(err: unknown): unknown {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the user whose email is `email`, in any case, or null, for
|
||||
* `requestPasswordReset`.
|
||||
* Returns the local user whose email is `email`, in any case, or null, for
|
||||
* `requestPasswordReset`. An account from another instance has no password
|
||||
* here to reset.
|
||||
*/
|
||||
export function getUserByEmail(email: string): User | null {
|
||||
const userRow = db.prepare(
|
||||
`${USER_SELECT} WHERE lower(u.email) = lower(?)`,
|
||||
`${USER_SELECT} WHERE lower(u.email) = lower(?) AND u.password_hash != ''`,
|
||||
).get(email);
|
||||
|
||||
if (!userRow || !isUserRow(userRow)) return null;
|
||||
@@ -385,13 +465,7 @@ export async function updateUser(
|
||||
throw new APIException(404, "User not found");
|
||||
}
|
||||
|
||||
if (password) {
|
||||
db.prepare(`UPDATE users SET tokens_valid_after = ? WHERE id = ?;`).run(
|
||||
now.toISOString(),
|
||||
userId,
|
||||
);
|
||||
closeUserSockets(userId, "Password changed");
|
||||
}
|
||||
if (password) revokeSessions(userId, now, "Password changed");
|
||||
|
||||
if (updatedUser.description) {
|
||||
linkAttachments(updatedUser.description, "user", userId);
|
||||
@@ -400,14 +474,54 @@ export async function updateUser(
|
||||
return updatedUser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends every session of user `userId` opened before `at`, closing their
|
||||
* sockets with `reason`: their tokens stop counting
|
||||
* (`users.tokens_valid_after`, which `getSessionState` reads). A password
|
||||
* change calls it, and so does the sign-out of a user from another instance,
|
||||
* when that instance says so or an admin blocks it.
|
||||
*/
|
||||
export function revokeSessions(userId: string, at: Date, reason: string): void {
|
||||
db.prepare(`UPDATE users SET tokens_valid_after = ? WHERE id = ?;`).run(
|
||||
at.toISOString(),
|
||||
userId,
|
||||
);
|
||||
closeUserSockets(userId, reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the image `data` user `userId`'s avatar and returns them, for an
|
||||
* upload (`PUT /api/me/avatar`) and for the avatar a user from another
|
||||
* instance has there (`federation-service.ts`). Presence alone would update
|
||||
* only the online list, so it also sends `user_updated`, which reaches every
|
||||
* avatar on screen, its bumped `updatedAt` busting their cache.
|
||||
*
|
||||
* @throws {APIException} 400 when `data` isn't an image an avatar may be, 404
|
||||
* when there is no such user.
|
||||
*/
|
||||
export async function setUserAvatar(
|
||||
userId: string,
|
||||
data: Uint8Array,
|
||||
): Promise<User> {
|
||||
const mime = validateImageUpload(data);
|
||||
// Written before the record announces it, or clients would fetch it too
|
||||
// early.
|
||||
await replaceUploadedFile(`${AVATARS_DIR}/${userId}`, data);
|
||||
updateUserAvatar(userId, mime);
|
||||
updateClientAvatar(userId, mime);
|
||||
const user = getUserById(userId);
|
||||
broadcastUserUpdated(toPublicUser(user));
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that user `userId` now has an avatar of type `mime`, once
|
||||
* `PUT /api/me/avatar` has written the file. It bumps `updated_at`, which
|
||||
* {@link setUserAvatar} has written the file. It bumps `updated_at`, which
|
||||
* the client uses to reload the image.
|
||||
*
|
||||
* @throws {APIException} 404 when there is no such user.
|
||||
*/
|
||||
export function updateUserAvatar(userId: string, mime: string): void {
|
||||
function updateUserAvatar(userId: string, mime: string): void {
|
||||
const result = db.prepare(
|
||||
`UPDATE users SET avatar_mime = ?, updated_at = ? WHERE id = ?`,
|
||||
).run(mime, new Date().toISOString(), userId);
|
||||
|
||||
@@ -28,14 +28,14 @@ Deno.test("runMigrations: a fresh database is left as schema.sql made it", () =>
|
||||
.get() as {
|
||||
n: number;
|
||||
};
|
||||
assertEquals(applied.n, 23);
|
||||
assertEquals(applied.n, 24);
|
||||
// Running again applies nothing.
|
||||
runMigrations(db);
|
||||
assertEquals(
|
||||
(db.prepare(`SELECT COUNT(*) as n FROM schema_migrations;`).get() as {
|
||||
n: number;
|
||||
}).n,
|
||||
23,
|
||||
24,
|
||||
);
|
||||
db.close();
|
||||
});
|
||||
|
||||
43
api/test/db/migrations/0024_federation.test.ts
Normal file
43
api/test/db/migrations/0024_federation.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import "../../setup.ts";
|
||||
import { assertEquals, assertThrows } from "@std/assert";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { up as up0024 } from "../../../db/migrations/0024_federation.ts";
|
||||
|
||||
Deno.test("migration 0024 adds federation and frees remote accounts' emails", () => {
|
||||
const db = new DatabaseSync(":memory:");
|
||||
db.exec(`
|
||||
CREATE TABLE users (id TEXT PRIMARY KEY, username TEXT, password_hash TEXT, email TEXT);
|
||||
CREATE UNIQUE INDEX idx_users_email_lower ON users(lower(email));
|
||||
CREATE TABLE categories (id TEXT PRIMARY KEY, slug TEXT);
|
||||
INSERT INTO users VALUES ('a', 'ann', 'h.s', 'a@x.test');
|
||||
INSERT INTO categories VALUES ('c', 'authorize'), ('d', 'music');
|
||||
`);
|
||||
up0024(db);
|
||||
up0024(db); // idempotent
|
||||
|
||||
// Two accounts without a password may share an address with a local one.
|
||||
db.exec(`
|
||||
INSERT INTO users VALUES ('b', 'ann@one.test', '', 'a@x.test');
|
||||
INSERT INTO users VALUES ('c', 'ann@two.test', '', 'A@x.test');
|
||||
`);
|
||||
assertThrows(() =>
|
||||
db.exec(`INSERT INTO users VALUES ('d', 'dup', 'h.s', 'a@X.test');`)
|
||||
);
|
||||
const slugs = db.prepare(`SELECT slug FROM categories ORDER BY id;`)
|
||||
.all() as { slug: string }[];
|
||||
assertEquals(slugs.map((r) => r.slug), ["authorize-2", "music"]);
|
||||
for (
|
||||
const table of [
|
||||
"federation_keys",
|
||||
"user_identities",
|
||||
"federation_peers",
|
||||
"federation_logins",
|
||||
"oauth_codes",
|
||||
"federation_grants",
|
||||
"federation_outbox",
|
||||
]
|
||||
) {
|
||||
db.prepare(`SELECT COUNT(*) FROM ${table};`).get();
|
||||
}
|
||||
db.close();
|
||||
});
|
||||
@@ -4,7 +4,13 @@ import { TEST_DIR } from "./setup.ts";
|
||||
import { stub } from "@std/testing/mock";
|
||||
import { app } from "../main.ts";
|
||||
import { db } from "../db/connection.ts";
|
||||
import { createJWT, createMediaToken } from "../lib/jwt.ts";
|
||||
import {
|
||||
createJWT,
|
||||
createMediaToken,
|
||||
generateInstanceKey,
|
||||
importInstanceKey,
|
||||
signInstanceToken,
|
||||
} from "../lib/jwt.ts";
|
||||
import { hashPassword } from "../lib/password.ts";
|
||||
import { uniqueSlug } from "../lib/slugify.ts";
|
||||
import { slugify } from "../../shared/slug.ts";
|
||||
@@ -12,6 +18,7 @@ import { dumpPath, playlistPath } from "../../shared/paths.ts";
|
||||
import { canonicalizeUrl } from "../lib/canonical-url.ts";
|
||||
import { clearRichContentCache } from "../services/rich-content-service.ts";
|
||||
import { clearImageCache } from "../remote/image-proxy.ts";
|
||||
import { clearInstanceCaches } from "../remote/gerbeur-instance.ts";
|
||||
import {
|
||||
type OutgoingEmail,
|
||||
setEmailTransport,
|
||||
@@ -24,6 +31,12 @@ export { app, db, TEST_DIR };
|
||||
// ── Database ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const TABLES = [
|
||||
"user_identities",
|
||||
"federation_peers",
|
||||
"federation_logins",
|
||||
"oauth_codes",
|
||||
"federation_grants",
|
||||
"federation_outbox",
|
||||
"dump_backlinks",
|
||||
"dump_categories",
|
||||
"playlist_dumps",
|
||||
@@ -393,6 +406,7 @@ export function stubNetwork(
|
||||
// A new network: metadata cached from the last one no longer describes it.
|
||||
clearRichContentCache();
|
||||
clearImageCache();
|
||||
clearInstanceCaches();
|
||||
const fetchStub = stub(
|
||||
globalThis,
|
||||
"fetch",
|
||||
@@ -419,6 +433,137 @@ export function stubNetwork(
|
||||
};
|
||||
}
|
||||
|
||||
// ── Federation ───────────────────────────────────────────────────────────────
|
||||
|
||||
/** A user of a {@link FakeInstance}, as its identity tokens describe them. */
|
||||
export interface FakeIdentity {
|
||||
sub: string;
|
||||
preferred_username: string;
|
||||
email: string;
|
||||
picture?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Another gerbeur instance at `origin`, answering through {@link stubNetwork}
|
||||
* (`stubNetwork((url, init) => fake.handle(url, init) ?? ...)`): its metadata,
|
||||
* its keys, a token endpoint that trades the codes the test `issue`s, an
|
||||
* events endpoint recording what it receives, and avatars.
|
||||
*/
|
||||
export interface FakeInstance {
|
||||
origin: string;
|
||||
/**
|
||||
* Makes a code for `identity`, answering the authorize URL `authorizeUrl`
|
||||
* (this instance's request) as the home would after consent.
|
||||
*/
|
||||
issue(authorizeUrl: string, identity: FakeIdentity): string;
|
||||
/** Signs an event about `sub` for this instance, as its outbox would. */
|
||||
event(sub: string, payload: Record<string, unknown>): Promise<string>;
|
||||
/** The events posted to it, as their JWTs. */
|
||||
received: string[];
|
||||
/** Answers a request to it, or null when `url` isn't on it. */
|
||||
handle(url: URL, init?: RequestInit): Promise<Response> | null;
|
||||
}
|
||||
|
||||
/** Makes a {@link FakeInstance} at `origin` with a fresh key. */
|
||||
export async function fakeInstance(origin: string): Promise<FakeInstance> {
|
||||
const { kid, privateJwk, publicJwk } = await generateInstanceKey();
|
||||
const key = await importInstanceKey(kid, privateJwk);
|
||||
const codes = new Map<
|
||||
string,
|
||||
{ identity: FakeIdentity; nonce: string; challenge: string; client: string }
|
||||
>();
|
||||
const received: string[] = [];
|
||||
const json = (body: unknown, status = 200) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
const handle = async (url: URL, init?: RequestInit): Promise<Response> => {
|
||||
switch (url.pathname) {
|
||||
case "/.well-known/openid-configuration":
|
||||
return json({
|
||||
issuer: origin,
|
||||
authorization_endpoint: `${origin}/authorize`,
|
||||
token_endpoint: `${origin}/api/oauth/tokens`,
|
||||
jwks_uri: `${origin}/.well-known/jwks.json`,
|
||||
response_types_supported: ["code"],
|
||||
grant_types_supported: ["authorization_code"],
|
||||
subject_types_supported: ["public"],
|
||||
id_token_signing_alg_values_supported: ["EdDSA"],
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
scopes_supported: ["openid", "profile", "email"],
|
||||
gerbeur_federation: 1,
|
||||
gerbeur_site_name: `Fake ${new URL(origin).host}`,
|
||||
gerbeur_redirect_uri: `${origin}/federation/callback`,
|
||||
gerbeur_events_endpoint: `${origin}/api/federation/events`,
|
||||
});
|
||||
case "/.well-known/jwks.json":
|
||||
return json({ keys: [publicJwk] });
|
||||
case "/api/oauth/tokens": {
|
||||
const form = new URLSearchParams(String(init?.body));
|
||||
const entry = codes.get(form.get("code") ?? "");
|
||||
codes.delete(form.get("code") ?? "");
|
||||
const verifier = form.get("code_verifier") ?? "";
|
||||
const hash = new Uint8Array(
|
||||
await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
new TextEncoder().encode(verifier),
|
||||
),
|
||||
);
|
||||
const challenge = btoa(String.fromCharCode(...hash))
|
||||
.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
if (
|
||||
!entry || entry.challenge !== challenge ||
|
||||
entry.client !== form.get("client_id")
|
||||
) {
|
||||
return json({ error: "invalid_grant" }, 400);
|
||||
}
|
||||
const { sub, ...claims } = entry.identity;
|
||||
return json({
|
||||
id_token: await signInstanceToken(
|
||||
{ ...claims, nonce: entry.nonce },
|
||||
key,
|
||||
{ issuer: origin, audience: entry.client, subject: sub },
|
||||
"5m",
|
||||
),
|
||||
});
|
||||
}
|
||||
case "/api/federation/events":
|
||||
received.push(JSON.parse(String(init?.body)).event);
|
||||
return new Response(null, { status: 204 });
|
||||
default:
|
||||
if (url.pathname.endsWith("/avatar")) {
|
||||
return new Response(PNG, {
|
||||
headers: { "content-type": "image/png" },
|
||||
});
|
||||
}
|
||||
return json({ error: "not found" }, 404);
|
||||
}
|
||||
};
|
||||
return {
|
||||
origin,
|
||||
received,
|
||||
issue(authorizeUrl, identity) {
|
||||
const q = new URL(authorizeUrl).searchParams;
|
||||
const code = crypto.randomUUID();
|
||||
codes.set(code, {
|
||||
identity,
|
||||
nonce: q.get("nonce") ?? "",
|
||||
challenge: q.get("code_challenge") ?? "",
|
||||
client: q.get("client_id") ?? "",
|
||||
});
|
||||
return code;
|
||||
},
|
||||
event: (sub, payload) =>
|
||||
signInstanceToken(payload, key, {
|
||||
issuer: origin,
|
||||
audience: BASE_URL,
|
||||
subject: sub,
|
||||
}, "1h"),
|
||||
handle: (url, init) => url.origin === origin ? handle(url, init) : null,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Email ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
326
api/test/services/federation-service.test.ts
Normal file
326
api/test/services/federation-service.test.ts
Normal file
@@ -0,0 +1,326 @@
|
||||
import {
|
||||
createUser,
|
||||
db,
|
||||
del,
|
||||
type FakeInstance,
|
||||
fakeInstance,
|
||||
formWithFile,
|
||||
get,
|
||||
patch,
|
||||
PNG,
|
||||
post,
|
||||
put,
|
||||
stubNetwork,
|
||||
test,
|
||||
} from "../helpers.ts";
|
||||
import { assert, assertEquals, assertMatch } from "@std/assert";
|
||||
import type {
|
||||
FederationLoginResponse,
|
||||
FederationPeer,
|
||||
} from "../../../shared/federation.ts";
|
||||
import type { AuthResponse, SelfUser } from "../../../shared/user.ts";
|
||||
|
||||
const HOME = "https://home.test";
|
||||
|
||||
/** Puts `fake` behind the network, every other host answering 404. */
|
||||
function network(...fakes: FakeInstance[]) {
|
||||
return stubNetwork((url, init) => {
|
||||
for (const fake of fakes) {
|
||||
const res = fake.handle(url, init);
|
||||
if (res) return res;
|
||||
}
|
||||
return new Response("", { status: 404 });
|
||||
});
|
||||
}
|
||||
|
||||
async function trust(issuer: string, status = "trusted") {
|
||||
const admin = await createUser({ role: "admin" });
|
||||
return await put<FederationPeer>("/api/federation/peers", {
|
||||
auth: admin.auth,
|
||||
json: { instance: issuer, status },
|
||||
});
|
||||
}
|
||||
|
||||
/** Signs in through `home` as `identity`, as the pages would. */
|
||||
async function signIn(
|
||||
home: FakeInstance,
|
||||
identity: {
|
||||
sub: string;
|
||||
preferred_username: string;
|
||||
email: string;
|
||||
picture?: string;
|
||||
},
|
||||
inviteToken?: string,
|
||||
) {
|
||||
const start = await post<FederationLoginResponse>("/api/federation/logins", {
|
||||
json: { instance: new URL(home.origin).host, inviteToken },
|
||||
});
|
||||
if (start.status !== 200) return start;
|
||||
const authorizeUrl = start.data.authorizeUrl;
|
||||
const code = home.issue(authorizeUrl, identity);
|
||||
return await post<AuthResponse>("/api/federation/sessions", {
|
||||
json: { code, state: new URL(authorizeUrl).searchParams.get("state") },
|
||||
});
|
||||
}
|
||||
|
||||
const ALICE = {
|
||||
sub: "alice-id",
|
||||
preferred_username: "alice",
|
||||
email: "alice@home.example",
|
||||
picture: `${HOME}/api/users/alice-id/avatar?v=1`,
|
||||
};
|
||||
|
||||
test("federation: a trusted instance's user signs in as name@host, once made", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
using net = network(home);
|
||||
assertEquals((await trust("home.test")).data.name, "Fake home.test");
|
||||
|
||||
const start = await post<FederationLoginResponse>("/api/federation/logins", {
|
||||
json: { instance: "home.test" },
|
||||
});
|
||||
const url = new URL(start.data.authorizeUrl);
|
||||
assertEquals(url.origin + url.pathname, `${HOME}/authorize`);
|
||||
assertEquals(url.searchParams.get("client_id"), "http://gerbeur.test");
|
||||
assertEquals(
|
||||
url.searchParams.get("redirect_uri"),
|
||||
"http://gerbeur.test/federation/callback",
|
||||
);
|
||||
assertEquals(url.searchParams.get("code_challenge_method"), "S256");
|
||||
|
||||
const first = await signIn(home, ALICE);
|
||||
const { user, token } = first.data as AuthResponse;
|
||||
assertEquals(user.username, "alice@home.test");
|
||||
assertEquals(user.email, "alice@home.example");
|
||||
assertEquals(user.role, "user");
|
||||
assertEquals(user.avatarMime, "image/png");
|
||||
assert(net.calls.some((u) => u.pathname === "/api/users/alice-id/avatar"));
|
||||
|
||||
const me = await get<SelfUser>("/api/me", {
|
||||
auth: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
assertEquals(me.data.id, user.id);
|
||||
|
||||
// The same identity signs in to the same account.
|
||||
const again = await signIn(home, ALICE);
|
||||
assertEquals((again.data as AuthResponse).user.id, user.id);
|
||||
|
||||
// It has no password here.
|
||||
const login = await post("/api/sessions", {
|
||||
json: { username: "alice@home.test", password: "" },
|
||||
});
|
||||
assertEquals(login.status, 401);
|
||||
assertEquals(
|
||||
(await get<SelfUser>("/api/users/@alice@home.test")).data.id,
|
||||
user.id,
|
||||
);
|
||||
// The client encodes the handle's `@`.
|
||||
assertEquals(
|
||||
(await get<SelfUser>("/api/users/@alice%40home.test")).data.id,
|
||||
user.id,
|
||||
);
|
||||
});
|
||||
|
||||
test("federation: a login works once, with the code the home made for it", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
using _net = network(home);
|
||||
await trust(HOME);
|
||||
const start = await post<FederationLoginResponse>("/api/federation/logins", {
|
||||
json: { instance: HOME },
|
||||
});
|
||||
const state = new URL(start.data.authorizeUrl).searchParams.get("state");
|
||||
const wrong = await post("/api/federation/sessions", {
|
||||
json: { code: "made-up", state },
|
||||
});
|
||||
assertEquals(wrong.status, 502);
|
||||
// The failed try used the login up.
|
||||
const code = home.issue(start.data.authorizeUrl, ALICE);
|
||||
const replay = await post("/api/federation/sessions", {
|
||||
json: { code, state },
|
||||
});
|
||||
assertEquals(replay.status, 400);
|
||||
});
|
||||
|
||||
test("federation: an instance on neither list needs an invite, claimed on joining", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
using _net = network(home);
|
||||
const refused = await signIn(home, ALICE);
|
||||
assertEquals(refused.status, 403);
|
||||
|
||||
const inviter = await createUser();
|
||||
const { token } = (await post<{ token: string }>("/api/invites", {
|
||||
auth: inviter.auth,
|
||||
})).data;
|
||||
const joined = await signIn(home, ALICE, token);
|
||||
const { user } = joined.data as AuthResponse;
|
||||
assertEquals(user.username, "alice@home.test");
|
||||
const row = db.prepare(`SELECT invited_by FROM users WHERE id = ?;`).get(
|
||||
user.id,
|
||||
) as { invited_by: string };
|
||||
assertEquals(row.invited_by, inviter.id);
|
||||
assertEquals((await get(`/api/invites/${token}`)).status, 404);
|
||||
|
||||
// Once here, no invite is needed; another user of that instance still
|
||||
// needs one.
|
||||
assertEquals((await signIn(home, ALICE)).status, 200);
|
||||
const bob = { ...ALICE, sub: "bob-id", preferred_username: "bob" };
|
||||
assertEquals((await signIn(home, bob)).status, 403);
|
||||
});
|
||||
|
||||
test("federation: blocking an instance refuses its users and ends their sessions", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
using _net = network(home);
|
||||
await trust(HOME);
|
||||
const { token } = (await signIn(home, ALICE)).data as AuthResponse;
|
||||
const auth = { Authorization: `Bearer ${token}` };
|
||||
assertEquals((await get("/api/me", { auth })).status, 200);
|
||||
|
||||
await trust(HOME, "blocked");
|
||||
assertEquals((await get("/api/me", { auth })).status, 401);
|
||||
assertEquals((await signIn(home, ALICE)).status, 403);
|
||||
|
||||
const admin = await createUser({ role: "admin" });
|
||||
const peers = await get<FederationPeer[]>("/api/federation/peers", {
|
||||
auth: admin.auth,
|
||||
});
|
||||
assertEquals(peers.data.map((p) => p.status), ["blocked"]);
|
||||
assertEquals((await get<FederationPeer[]>("/api/federation/peers")).data, []);
|
||||
assertEquals(
|
||||
(await del("/api/federation/peers/home.test", { auth: admin.auth }))
|
||||
.status,
|
||||
200,
|
||||
);
|
||||
assertEquals((await get("/api/me", { auth })).status, 200);
|
||||
});
|
||||
|
||||
test("federation: only admins edit the peers, which must answer as gerbeurs", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
using _net = network(home);
|
||||
const user = await createUser();
|
||||
const admin = await createUser({ role: "admin" });
|
||||
assertEquals(
|
||||
(await put("/api/federation/peers", {
|
||||
auth: user.auth,
|
||||
json: { instance: HOME, status: "trusted" },
|
||||
})).status,
|
||||
403,
|
||||
);
|
||||
for (const instance of ["elsewhere.test", "https://home.test/path"]) {
|
||||
const res = await put("/api/federation/peers", {
|
||||
auth: admin.auth,
|
||||
json: { instance, status: "trusted" },
|
||||
});
|
||||
assert(res.status >= 400, instance);
|
||||
}
|
||||
assertEquals(
|
||||
(await put("/api/federation/peers", {
|
||||
auth: admin.auth,
|
||||
json: { instance: "http://gerbeur.test", status: "trusted" },
|
||||
})).status,
|
||||
400,
|
||||
);
|
||||
});
|
||||
|
||||
test("federation: the home's events rename, update and sign out its users", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
const other = await fakeInstance("https://other.test");
|
||||
using _net = network(home, other);
|
||||
await trust(HOME);
|
||||
const { user, token } = (await signIn(home, ALICE)).data as AuthResponse;
|
||||
const auth = { Authorization: `Bearer ${token}` };
|
||||
|
||||
const update = await home.event(ALICE.sub, {
|
||||
type: "update",
|
||||
claims: { ...ALICE, preferred_username: "alicia", email: "a@new.example" },
|
||||
});
|
||||
assertEquals(
|
||||
(await post("/api/federation/events", { json: { event: update } }))
|
||||
.status,
|
||||
204,
|
||||
);
|
||||
const renamed = await get<SelfUser>("/api/me", { auth });
|
||||
assertEquals(renamed.data.username, "alicia@home.test");
|
||||
assertEquals(renamed.data.email, "a@new.example");
|
||||
// The old handle still leads to them.
|
||||
assertEquals(
|
||||
(await get<SelfUser>("/api/users/@alice@home.test")).data.id,
|
||||
user.id,
|
||||
);
|
||||
|
||||
// Another instance can't speak for this one's users.
|
||||
const forged = await other.event(ALICE.sub, { type: "revoke" });
|
||||
assertEquals(
|
||||
(await post("/api/federation/events", { json: { event: forged } }))
|
||||
.status,
|
||||
400,
|
||||
);
|
||||
|
||||
// Revoking a little later than the token was issued, as it would be.
|
||||
await new Promise((r) => setTimeout(r, 1100));
|
||||
const revoke = await home.event(ALICE.sub, { type: "revoke" });
|
||||
assertEquals(
|
||||
(await post("/api/federation/events", { json: { event: revoke } }))
|
||||
.status,
|
||||
204,
|
||||
);
|
||||
assertEquals((await get("/api/me", { auth })).status, 401);
|
||||
});
|
||||
|
||||
test("federation: an account from another instance changes its password, email, avatar and name there", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
using _net = network(home);
|
||||
await trust(HOME);
|
||||
const { user, token } = (await signIn(home, ALICE)).data as AuthResponse;
|
||||
const auth = { Authorization: `Bearer ${token}` };
|
||||
const admin = await createUser({ role: "admin" });
|
||||
|
||||
assertEquals(
|
||||
(await put("/api/me/password", {
|
||||
auth,
|
||||
json: { currentPassword: "", newPassword: "long-enough" },
|
||||
})).status,
|
||||
400,
|
||||
);
|
||||
assertEquals(
|
||||
(await patch("/api/me", { auth, json: { email: "x@example.test" } }))
|
||||
.status,
|
||||
400,
|
||||
);
|
||||
assertEquals(
|
||||
(await patch<SelfUser>("/api/me", { auth, json: { description: "hi" } }))
|
||||
.data.description,
|
||||
"hi",
|
||||
);
|
||||
assertEquals(
|
||||
(await put("/api/me/avatar", { auth, form: formWithFile(PNG) })).status,
|
||||
400,
|
||||
);
|
||||
assertEquals(
|
||||
(await patch(`/api/users/${user.id}/username`, {
|
||||
auth: admin.auth,
|
||||
json: { username: "bob" },
|
||||
})).status,
|
||||
400,
|
||||
);
|
||||
});
|
||||
|
||||
test("federation: an email may be both a local account's and a remote one's", async () => {
|
||||
const home = await fakeInstance(HOME);
|
||||
using _net = network(home);
|
||||
await trust(HOME);
|
||||
const local = await createUser({ email: ALICE.email });
|
||||
const res = await signIn(home, ALICE);
|
||||
assertMatch((res.data as AuthResponse).user.username, /@home\.test$/);
|
||||
// A reset by that address reaches the local account only.
|
||||
const row = db.prepare(
|
||||
`SELECT COUNT(*) AS n FROM users WHERE lower(email) = lower(?);`,
|
||||
).get(ALICE.email) as { n: number };
|
||||
assertEquals(row.n, 2);
|
||||
assertEquals(
|
||||
(await post("/api/password-resets", { json: { email: ALICE.email } }))
|
||||
.status,
|
||||
200,
|
||||
);
|
||||
const tokens = db.prepare(`SELECT user_id FROM password_reset_tokens;`)
|
||||
.all() as { user_id: string }[];
|
||||
assert(tokens.every((t) => t.user_id === local.id));
|
||||
});
|
||||
268
api/test/services/identity-provider-service.test.ts
Normal file
268
api/test/services/identity-provider-service.test.ts
Normal file
@@ -0,0 +1,268 @@
|
||||
import {
|
||||
app,
|
||||
BASE_URL,
|
||||
createUser,
|
||||
db,
|
||||
del,
|
||||
type FakeInstance,
|
||||
fakeInstance,
|
||||
get,
|
||||
patch,
|
||||
post,
|
||||
put,
|
||||
stubNetwork,
|
||||
test,
|
||||
} from "../helpers.ts";
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { createHash } from "node:crypto";
|
||||
import { decodeJwt, type JSONWebKeySet } from "@panva/jose";
|
||||
import { verifyInstanceToken } from "../../lib/jwt.ts";
|
||||
import type {
|
||||
AuthorizeResponse,
|
||||
FederationGrant,
|
||||
InstanceMetadata,
|
||||
OAuthClient,
|
||||
} from "../../../shared/federation.ts";
|
||||
|
||||
const CLIENT = "https://client.test";
|
||||
const CALLBACK = `${CLIENT}/federation/callback`;
|
||||
|
||||
function network(fake: FakeInstance, events?: () => Response) {
|
||||
return stubNetwork((url, init) => {
|
||||
if (events && url.pathname === "/api/federation/events") return events();
|
||||
return fake.handle(url, init) ?? new Response("", { status: 404 });
|
||||
});
|
||||
}
|
||||
|
||||
/** A PKCE pair: the verifier, and the challenge the request carries. */
|
||||
function pkce() {
|
||||
const verifier = crypto.randomUUID() + crypto.randomUUID();
|
||||
return {
|
||||
verifier,
|
||||
challenge: createHash("sha256").update(verifier).digest("base64url"),
|
||||
};
|
||||
}
|
||||
|
||||
function authorize(
|
||||
auth: { Authorization: string },
|
||||
challenge: string,
|
||||
overrides: Record<string, string> = {},
|
||||
) {
|
||||
return post<AuthorizeResponse>("/api/oauth/codes", {
|
||||
auth,
|
||||
json: {
|
||||
clientId: CLIENT,
|
||||
redirectUri: CALLBACK,
|
||||
state: "the-state",
|
||||
codeChallenge: challenge,
|
||||
codeChallengeMethod: "S256",
|
||||
nonce: "the-nonce",
|
||||
...overrides,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** Trades `code` at the token endpoint, as the client's server would. */
|
||||
async function trade(code: string, verifier: string, client = CLIENT) {
|
||||
const res = await app.handle(
|
||||
new Request(`${BASE_URL}/api/oauth/tokens`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code,
|
||||
client_id: client,
|
||||
redirect_uri: CALLBACK,
|
||||
code_verifier: verifier,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
return { status: res!.status, body: await res!.json() };
|
||||
}
|
||||
|
||||
async function until(check: () => boolean) {
|
||||
for (let i = 0; i < 50 && !check(); i++) {
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
}
|
||||
|
||||
test("identity provider: metadata and keys are served at the well-known paths", async () => {
|
||||
const meta = await get("/.well-known/openid-configuration");
|
||||
const body = JSON.parse(
|
||||
new TextDecoder().decode(meta.bytes),
|
||||
) as InstanceMetadata;
|
||||
assertEquals(body.issuer, BASE_URL);
|
||||
assertEquals(body.authorization_endpoint, `${BASE_URL}/authorize`);
|
||||
assertEquals(body.gerbeur_redirect_uri, `${BASE_URL}/federation/callback`);
|
||||
assertEquals(body.gerbeur_federation, 1);
|
||||
const jwks = await get("/.well-known/jwks.json");
|
||||
const keys = JSON.parse(new TextDecoder().decode(jwks.bytes)).keys;
|
||||
assertEquals(keys[0].crv, "Ed25519");
|
||||
assertEquals(keys[0].d, undefined);
|
||||
});
|
||||
|
||||
test("identity provider: a consenting user's code trades once for their identity", async () => {
|
||||
const fake = await fakeInstance(CLIENT);
|
||||
using _net = network(fake);
|
||||
const user = await createUser({ username: "carol" });
|
||||
|
||||
const client = await get<OAuthClient>(
|
||||
`/api/oauth/clients?client_id=${encodeURIComponent(CLIENT)}`,
|
||||
{ auth: user.auth },
|
||||
);
|
||||
assertEquals(client.data, {
|
||||
clientId: CLIENT,
|
||||
host: "client.test",
|
||||
name: "Fake client.test",
|
||||
granted: false,
|
||||
});
|
||||
|
||||
const { verifier, challenge } = pkce();
|
||||
const redirect = new URL(
|
||||
(await authorize(user.auth, challenge)).data
|
||||
.redirectTo,
|
||||
);
|
||||
assertEquals(redirect.origin + redirect.pathname, CALLBACK);
|
||||
assertEquals(redirect.searchParams.get("state"), "the-state");
|
||||
assertEquals(redirect.searchParams.get("iss"), BASE_URL);
|
||||
const code = redirect.searchParams.get("code")!;
|
||||
|
||||
assertEquals((await trade(code, pkce().verifier)).status, 400);
|
||||
// A failed trade used the code up too.
|
||||
assertEquals((await trade(code, verifier)).status, 400);
|
||||
|
||||
const { challenge: c2, verifier: v2 } = pkce();
|
||||
const code2 = new URL((await authorize(user.auth, c2)).data.redirectTo)
|
||||
.searchParams.get("code")!;
|
||||
assertEquals((await trade(code2, v2, "https://elsewhere.test")).status, 400);
|
||||
const { challenge: c3, verifier: v3 } = pkce();
|
||||
const code3 = new URL((await authorize(user.auth, c3)).data.redirectTo)
|
||||
.searchParams.get("code")!;
|
||||
const traded = await trade(code3, v3);
|
||||
assertEquals(traded.status, 200);
|
||||
|
||||
const keys = JSON.parse(
|
||||
new TextDecoder().decode((await get("/.well-known/jwks.json")).bytes),
|
||||
) as JSONWebKeySet;
|
||||
const claims = await verifyInstanceToken(traded.body.id_token, keys, {
|
||||
issuer: BASE_URL,
|
||||
audience: CLIENT,
|
||||
});
|
||||
assertEquals(claims.sub, user.id);
|
||||
assertEquals(claims.preferred_username, "carol");
|
||||
assertEquals(claims.email, user.email);
|
||||
assertEquals(claims.nonce, "the-nonce");
|
||||
|
||||
const again = await get<OAuthClient>(
|
||||
`/api/oauth/clients?client_id=${encodeURIComponent(CLIENT)}`,
|
||||
{ auth: user.auth },
|
||||
);
|
||||
assertEquals(again.data.granted, true);
|
||||
const grants = await get<FederationGrant[]>("/api/me/grants", {
|
||||
auth: user.auth,
|
||||
});
|
||||
assertEquals(grants.data.map((g) => g.host), ["client.test"]);
|
||||
});
|
||||
|
||||
test("identity provider: codes are only for a known client's own callback", async () => {
|
||||
const fake = await fakeInstance(CLIENT);
|
||||
using _net = network(fake);
|
||||
const user = await createUser();
|
||||
const admin = await createUser({ role: "admin" });
|
||||
const { challenge } = pkce();
|
||||
assertEquals(
|
||||
(await authorize(user.auth, challenge, {
|
||||
redirectUri: "https://evil.test/cb",
|
||||
})).status,
|
||||
400,
|
||||
);
|
||||
assertEquals(
|
||||
(await authorize(user.auth, challenge, { clientId: BASE_URL })).status,
|
||||
400,
|
||||
);
|
||||
assertEquals(
|
||||
(await authorize(user.auth, challenge, { codeChallengeMethod: "plain" }))
|
||||
.status,
|
||||
400,
|
||||
);
|
||||
assertEquals(
|
||||
(await authorize(user.auth, challenge, {
|
||||
clientId: "https://nowhere.test",
|
||||
})).status,
|
||||
502,
|
||||
);
|
||||
await put("/api/federation/peers", {
|
||||
auth: admin.auth,
|
||||
json: { instance: CLIENT, status: "blocked" },
|
||||
});
|
||||
assertEquals((await authorize(user.auth, challenge)).status, 403);
|
||||
});
|
||||
|
||||
test("identity provider: an account from another instance doesn't sign in elsewhere from here", async () => {
|
||||
const fake = await fakeInstance(CLIENT);
|
||||
using _net = network(fake);
|
||||
const user = await createUser();
|
||||
db.prepare(`UPDATE users SET password_hash = '' WHERE id = ?;`).run(user.id);
|
||||
assertEquals((await authorize(user.auth, pkce().challenge)).status, 400);
|
||||
});
|
||||
|
||||
test("identity provider: the instances a user signed in to hear of their changes", async () => {
|
||||
const fake = await fakeInstance(CLIENT);
|
||||
using _net = network(fake);
|
||||
const user = await createUser({ username: "dave" });
|
||||
const admin = await createUser({ role: "admin" });
|
||||
await authorize(user.auth, pkce().challenge);
|
||||
|
||||
await patch(`/api/users/${user.id}/username`, {
|
||||
auth: admin.auth,
|
||||
json: { username: "david" },
|
||||
});
|
||||
await until(() => fake.received.length === 1);
|
||||
const update = decodeJwt(fake.received[0]);
|
||||
assertEquals(update.type, "update");
|
||||
assertEquals(update.sub, user.id);
|
||||
assertEquals(update.aud, CLIENT);
|
||||
assertEquals(
|
||||
(update.claims as { preferred_username: string }).preferred_username,
|
||||
"david",
|
||||
);
|
||||
|
||||
await put("/api/me/password", {
|
||||
auth: user.auth,
|
||||
json: { currentPassword: "correct-horse", newPassword: "new-password" },
|
||||
});
|
||||
await until(() => fake.received.length === 2);
|
||||
assertEquals(decodeJwt(fake.received[1]).type, "revoke");
|
||||
|
||||
const token = (await post<{ token: string }>("/api/sessions", {
|
||||
json: { username: "david", password: "new-password" },
|
||||
})).data.token;
|
||||
const auth = { Authorization: `Bearer ${token}` };
|
||||
assertEquals(
|
||||
(await del("/api/me/grants/client.test", { auth })).status,
|
||||
200,
|
||||
);
|
||||
await until(() => fake.received.length === 3);
|
||||
assertEquals(decodeJwt(fake.received[2]).type, "revoke");
|
||||
assertEquals(
|
||||
(await get<FederationGrant[]>("/api/me/grants", { auth })).data,
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test("identity provider: an event an instance fails to take waits in the outbox", async () => {
|
||||
const fake = await fakeInstance(CLIENT);
|
||||
using _net = network(fake, () => new Response("", { status: 503 }));
|
||||
const user = await createUser();
|
||||
await authorize(user.auth, pkce().challenge);
|
||||
await patch("/api/me", { auth: user.auth, json: { email: "e@new.test" } });
|
||||
let row: { attempts: number } | undefined;
|
||||
await until(() => {
|
||||
row = db.prepare(`SELECT attempts FROM federation_outbox;`).get() as
|
||||
| { attempts: number }
|
||||
| undefined;
|
||||
return (row?.attempts ?? 0) > 0;
|
||||
});
|
||||
assert(row);
|
||||
assertEquals(row.attempts, 1);
|
||||
});
|
||||
56
api/validators/federation.ts
Normal file
56
api/validators/federation.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Checks the JSON bodies that the federation routes (`routes/federation.ts`,
|
||||
* `routes/oauth.ts`) receive before they read them. They check the shapes
|
||||
* only: whether an instance answers, or a code or an invite works, is the
|
||||
* services' check.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import {
|
||||
type AuthorizeRequest,
|
||||
type FederationLoginRequest,
|
||||
type FederationSessionRequest,
|
||||
isPeerStatus,
|
||||
type SetPeerRequest,
|
||||
} from "../../shared/federation.ts";
|
||||
|
||||
/** Returns whether `obj` is an object whose `keys` are all strings. */
|
||||
function hasStrings(obj: unknown, keys: string[]): boolean {
|
||||
return !!obj && typeof obj === "object" &&
|
||||
keys.every((k) => typeof (obj as Record<string, unknown>)[k] === "string");
|
||||
}
|
||||
|
||||
/** Checks whether `obj` is a {@link FederationLoginRequest}. */
|
||||
export function isFederationLoginRequest(
|
||||
obj: unknown,
|
||||
): obj is FederationLoginRequest {
|
||||
if (!hasStrings(obj, ["instance"])) return false;
|
||||
const invite = (obj as Record<string, unknown>).inviteToken;
|
||||
return invite === undefined || typeof invite === "string";
|
||||
}
|
||||
|
||||
/** Checks whether `obj` is a {@link FederationSessionRequest}. */
|
||||
export function isFederationSessionRequest(
|
||||
obj: unknown,
|
||||
): obj is FederationSessionRequest {
|
||||
return hasStrings(obj, ["code", "state"]);
|
||||
}
|
||||
|
||||
/** Checks whether `obj` is an {@link AuthorizeRequest}. */
|
||||
export function isAuthorizeRequest(obj: unknown): obj is AuthorizeRequest {
|
||||
return hasStrings(obj, [
|
||||
"clientId",
|
||||
"redirectUri",
|
||||
"state",
|
||||
"codeChallenge",
|
||||
"codeChallengeMethod",
|
||||
"nonce",
|
||||
]);
|
||||
}
|
||||
|
||||
/** Checks whether `obj` is a {@link SetPeerRequest}. */
|
||||
export function isSetPeerRequest(obj: unknown): obj is SetPeerRequest {
|
||||
return hasStrings(obj, ["instance"]) &&
|
||||
isPeerStatus((obj as Record<string, unknown>).status);
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
276
locales/en.po
276
locales/en.po
@@ -51,7 +51,7 @@ msgstr "{0} more online: {restNames}"
|
||||
|
||||
#. placeholder {0}: VALIDATION.USERNAME_MIN
|
||||
#. placeholder {1}: VALIDATION.USERNAME_MAX
|
||||
#: src/pages/UserRegister.tsx:145
|
||||
#: src/pages/UserRegister.tsx:147
|
||||
msgid "{0}–{1} characters: letters, numbers, or underscores"
|
||||
msgstr "{0}–{1} characters: letters, numbers, or underscores"
|
||||
|
||||
@@ -280,6 +280,10 @@ msgstr "<0>{0}</0> upvoted <1>{1}</1>"
|
||||
msgid "<0>{0}</0> was added to <1>{1}</1>"
|
||||
msgstr "<0>{0}</0> was added to <1>{1}</1>"
|
||||
|
||||
#: src/pages/Authorize.tsx:138
|
||||
msgid "<0>{name}</0> ({host}) asks to sign you in with your account here, <1>@{username}</1>. It will receive your username, your email address and your avatar."
|
||||
msgstr "<0>{name}</0> ({host}) asks to sign you in with your account here, <1>@{username}</1>. It will receive your username, your email address and your avatar."
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:778
|
||||
msgid "1 new message"
|
||||
msgstr "1 new message"
|
||||
@@ -296,10 +300,14 @@ msgstr "A link is required"
|
||||
msgid "a post"
|
||||
msgstr "a post"
|
||||
|
||||
#: src/pages/Settings.tsx:85
|
||||
#: src/pages/Settings.tsx:89
|
||||
msgid "Account"
|
||||
msgstr "Account"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:144
|
||||
msgid "Account on <0>{host}</0>"
|
||||
msgstr "Account on <0>{host}</0>"
|
||||
|
||||
#: src/components/comment/CommentThread.tsx:102
|
||||
msgid "Add a comment…"
|
||||
msgstr "Add a comment…"
|
||||
@@ -309,7 +317,7 @@ msgstr "Add a comment…"
|
||||
msgid "Add category"
|
||||
msgstr "Add category"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:153
|
||||
#: src/components/profile/ProfileHeader.tsx:173
|
||||
msgid "Add email…"
|
||||
msgstr "Add email…"
|
||||
|
||||
@@ -342,10 +350,14 @@ msgstr "All"
|
||||
msgid "Already dumped by {0} {1}"
|
||||
msgstr "Already dumped by {0} {1}"
|
||||
|
||||
#: src/pages/UserRegister.tsx:175
|
||||
#: src/pages/UserRegister.tsx:179
|
||||
msgid "Already have an account? <0>Log in</0>"
|
||||
msgstr "Already have an account? <0>Log in</0>"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:149
|
||||
msgid "An instance's address, like music.example"
|
||||
msgstr "An instance's address, like music.example"
|
||||
|
||||
#: src/utils/shared/api.ts:35
|
||||
msgid "An unexpected error occurred."
|
||||
msgstr "An unexpected error occurred."
|
||||
@@ -355,14 +367,14 @@ msgstr "An unexpected error occurred."
|
||||
msgid "email.digest.andMore"
|
||||
msgstr "and {n} more"
|
||||
|
||||
#: src/pages/Settings.tsx:101
|
||||
#: src/pages/Settings.tsx:134
|
||||
msgid "Appearance"
|
||||
msgstr "Appearance"
|
||||
|
||||
#. placeholder {0}: VALIDATION.PASSWORD_MIN
|
||||
#: src/components/profile/ChangePasswordModal.tsx:101
|
||||
#: src/pages/ResetPassword.tsx:124
|
||||
#: src/pages/UserRegister.tsx:164
|
||||
#: src/pages/UserRegister.tsx:166
|
||||
msgid "At least {0} characters"
|
||||
msgstr "At least {0} characters"
|
||||
|
||||
@@ -370,7 +382,7 @@ msgstr "At least {0} characters"
|
||||
msgid "At most {maxLength} characters."
|
||||
msgstr "At most {maxLength} characters."
|
||||
|
||||
#: src/pages/Settings.tsx:46
|
||||
#: src/pages/Settings.tsx:48
|
||||
msgid "Auto"
|
||||
msgstr "Auto"
|
||||
|
||||
@@ -379,6 +391,18 @@ msgstr "Auto"
|
||||
msgid "Back to login"
|
||||
msgstr "Back to login"
|
||||
|
||||
#: src/pages/FederationCallback.tsx:66
|
||||
msgid "Back to the login page"
|
||||
msgstr "Back to the login page"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:163
|
||||
msgid "Block"
|
||||
msgstr "Block"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:33
|
||||
msgid "Blocked"
|
||||
msgstr "Blocked"
|
||||
|
||||
#. js-lingui-explicit-id
|
||||
#: api/mail/digest.ts:225
|
||||
msgid "email.digest.by"
|
||||
@@ -394,6 +418,11 @@ msgstr "by @{username} · {n, plural, one {# dump} other {# dumps}}"
|
||||
msgid "Can't connect to the live updates server. Upvotes and notifications may not sync until it reconnects."
|
||||
msgstr "Can't connect to the live updates server. Upvotes and notifications may not sync until it reconnects."
|
||||
|
||||
#: src/pages/Authorize.tsx:117
|
||||
#: src/pages/Authorize.tsx:145
|
||||
msgid "Can't sign in there"
|
||||
msgstr "Can't sign in there"
|
||||
|
||||
#: src/components/category/CategoryManager.tsx:225
|
||||
#: src/components/category/CategoryManager.tsx:226
|
||||
#: src/components/chat/ChatEditBox.tsx:92
|
||||
@@ -404,6 +433,7 @@ msgstr "Can't connect to the live updates server. Upvotes and notifications may
|
||||
#: src/components/profile/DescriptionEditor.tsx:97
|
||||
#: src/components/profile/EmailEditor.tsx:83
|
||||
#: src/components/shared/ConfirmModal.tsx:63
|
||||
#: src/pages/Authorize.tsx:158
|
||||
#: src/pages/Dump.tsx:445
|
||||
#: src/pages/DumpEdit.tsx:565
|
||||
msgid "Cancel"
|
||||
@@ -423,7 +453,7 @@ msgid "Cancel search"
|
||||
msgstr "Cancel search"
|
||||
|
||||
#: src/components/category/CategorySelect.tsx:33
|
||||
#: src/pages/Manage.tsx:30
|
||||
#: src/pages/Manage.tsx:36
|
||||
msgid "Categories"
|
||||
msgstr "Categories"
|
||||
|
||||
@@ -431,7 +461,7 @@ msgstr "Categories"
|
||||
msgid "Category"
|
||||
msgstr "Category"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:95
|
||||
#: src/components/profile/ProfileHeader.tsx:102
|
||||
msgid "Change avatar"
|
||||
msgstr "Change avatar"
|
||||
|
||||
@@ -439,12 +469,16 @@ msgstr "Change avatar"
|
||||
msgid "Change image"
|
||||
msgstr "Change image"
|
||||
|
||||
#: src/pages/Settings.tsx:101
|
||||
msgid "Change it on {home}"
|
||||
msgstr "Change it on {home}"
|
||||
|
||||
#: src/components/profile/ChangePasswordModal.tsx:66
|
||||
#: src/components/profile/ChangePasswordModal.tsx:120
|
||||
msgid "Change password"
|
||||
msgstr "Change password"
|
||||
|
||||
#: src/pages/Settings.tsx:96
|
||||
#: src/pages/Settings.tsx:112
|
||||
msgid "Change password…"
|
||||
msgstr "Change password…"
|
||||
|
||||
@@ -464,10 +498,14 @@ msgstr "Chat"
|
||||
msgid "Chat ({unreadChatCount} unread)"
|
||||
msgstr "Chat ({unreadChatCount} unread)"
|
||||
|
||||
#: src/pages/UserRegister.tsx:106
|
||||
#: src/pages/UserRegister.tsx:108
|
||||
msgid "Checking invite…"
|
||||
msgstr "Checking invite…"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:154
|
||||
msgid "Checking…"
|
||||
msgstr "Checking…"
|
||||
|
||||
#: src/components/profile/ChangePasswordModal.tsx:75
|
||||
#: src/components/shared/Modal.tsx:76
|
||||
msgid "Close"
|
||||
@@ -493,7 +531,7 @@ msgstr "Close without posting? The attached file won't be kept — everything yo
|
||||
msgid "Collapse player"
|
||||
msgstr "Collapse player"
|
||||
|
||||
#: src/pages/Settings.tsx:110
|
||||
#: src/pages/Settings.tsx:143
|
||||
msgid "Color scheme"
|
||||
msgstr "Color scheme"
|
||||
|
||||
@@ -507,10 +545,22 @@ msgstr "Community"
|
||||
msgid "Confirm new password"
|
||||
msgstr "Confirm new password"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:111
|
||||
msgid "Connecting…"
|
||||
msgstr "Connecting…"
|
||||
|
||||
#: src/contexts/ws/WSProvider.tsx:757
|
||||
msgid "Connection lost — this message may not have been sent"
|
||||
msgstr "Connection lost — this message may not have been sent"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:113
|
||||
msgid "Continue"
|
||||
msgstr "Continue"
|
||||
|
||||
#: src/pages/Authorize.tsx:155
|
||||
msgid "Continue as @{username}"
|
||||
msgstr "Continue as @{username}"
|
||||
|
||||
#: src/components/profile/ProfileOwnActions.tsx:99
|
||||
msgid "Copied!"
|
||||
msgstr "Copied!"
|
||||
@@ -540,6 +590,10 @@ msgstr "Could not rename"
|
||||
msgid "Could not save"
|
||||
msgstr "Could not save"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:146
|
||||
msgid "Couldn't add that instance"
|
||||
msgstr "Couldn't add that instance"
|
||||
|
||||
#: src/components/dump/create/DumpCreateModal.tsx:607
|
||||
msgid "Couldn't load a preview for this link — check it, or post it as-is and refresh the preview later."
|
||||
msgstr "Couldn't load a preview for this link — check it, or post it as-is and refresh the preview later."
|
||||
@@ -548,6 +602,10 @@ msgstr "Couldn't load a preview for this link — check it, or post it as-is and
|
||||
msgid "Couldn't load the chat."
|
||||
msgstr "Couldn't load the chat."
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:102
|
||||
msgid "Couldn't reach that instance"
|
||||
msgstr "Couldn't reach that instance"
|
||||
|
||||
#: src/pages/Unsubscribe.tsx:116
|
||||
msgid "Couldn't unsubscribe"
|
||||
msgstr "Couldn't unsubscribe"
|
||||
@@ -576,11 +634,11 @@ msgstr "Creating…"
|
||||
msgid "Current password"
|
||||
msgstr "Current password"
|
||||
|
||||
#: src/pages/Settings.tsx:48
|
||||
#: src/pages/Settings.tsx:50
|
||||
msgid "Dark"
|
||||
msgstr "Dark"
|
||||
|
||||
#: src/pages/Settings.tsx:121
|
||||
#: src/pages/Settings.tsx:154
|
||||
msgid "Default tab"
|
||||
msgstr "Default tab"
|
||||
|
||||
@@ -655,6 +713,10 @@ msgstr "Description (optional)"
|
||||
msgid "Discard"
|
||||
msgstr "Discard"
|
||||
|
||||
#: src/components/federation/GrantList.tsx:84
|
||||
msgid "Disconnect"
|
||||
msgstr "Disconnect"
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:743
|
||||
msgid "Disconnected — reconnecting…"
|
||||
msgstr "Disconnected — reconnecting…"
|
||||
@@ -730,7 +792,7 @@ msgstr "Edit {0}"
|
||||
msgid "Edit description"
|
||||
msgstr "Edit description"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:151
|
||||
#: src/components/profile/ProfileHeader.tsx:171
|
||||
msgid "Edit email"
|
||||
msgstr "Edit email"
|
||||
|
||||
@@ -772,11 +834,11 @@ msgstr "Editing"
|
||||
msgid "Editing {0}"
|
||||
msgstr "Editing {0}"
|
||||
|
||||
#: src/pages/Settings.tsx:145
|
||||
#: src/pages/Settings.tsx:178
|
||||
msgid "Email"
|
||||
msgstr "Email"
|
||||
|
||||
#: src/pages/UserRegister.tsx:152
|
||||
#: src/pages/UserRegister.tsx:154
|
||||
msgid "Email address"
|
||||
msgstr "Email address"
|
||||
|
||||
@@ -822,6 +884,8 @@ msgstr "Failed to post comment"
|
||||
msgid "Failed to post reply"
|
||||
msgstr "Failed to post reply"
|
||||
|
||||
#: src/components/federation/GrantList.tsx:98
|
||||
#: src/components/federation/PeerManager.tsx:143
|
||||
#: src/components/playlist/PlaylistEditForm.tsx:185
|
||||
#: src/components/profile/DescriptionEditor.tsx:99
|
||||
#: src/components/profile/EmailEditor.tsx:86
|
||||
@@ -836,7 +900,7 @@ msgstr "Failed to save category"
|
||||
msgid "Failed to save edit"
|
||||
msgstr "Failed to save edit"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:162
|
||||
#: src/components/profile/ProfileHeader.tsx:182
|
||||
msgid "Failed to update avatar"
|
||||
msgstr "Failed to update avatar"
|
||||
|
||||
@@ -844,7 +908,7 @@ msgstr "Failed to update avatar"
|
||||
msgid "Failed to update role"
|
||||
msgstr "Failed to update role"
|
||||
|
||||
#: src/pages/Settings.tsx:119
|
||||
#: src/pages/Settings.tsx:152
|
||||
msgid "Feeds"
|
||||
msgstr "Feeds"
|
||||
|
||||
@@ -879,7 +943,7 @@ msgstr "Follow some users to see their dumps here."
|
||||
|
||||
#: src/components/feed/FeedTabBar.tsx:43
|
||||
#: src/components/profile/ProfileFollowTab.tsx:140
|
||||
#: src/pages/Settings.tsx:55
|
||||
#: src/pages/Settings.tsx:57
|
||||
#: src/pages/UserPublicProfile.tsx:161
|
||||
msgid "Followed"
|
||||
msgstr "Followed"
|
||||
@@ -894,7 +958,7 @@ msgstr "Following"
|
||||
msgid "email.digest.forYou"
|
||||
msgstr "For you"
|
||||
|
||||
#: src/pages/UserLogin.tsx:97
|
||||
#: src/pages/UserLogin.tsx:101
|
||||
msgid "Forgot password?"
|
||||
msgstr "Forgot password?"
|
||||
|
||||
@@ -929,11 +993,11 @@ msgid "email.reset.hi"
|
||||
msgstr "Hi {username},"
|
||||
|
||||
#: src/components/feed/FeedTabBar.tsx:39
|
||||
#: src/pages/Settings.tsx:52
|
||||
#: src/pages/Settings.tsx:54
|
||||
msgid "Hot"
|
||||
msgstr "Hot"
|
||||
|
||||
#: src/pages/UserLogin.tsx:136
|
||||
#: src/pages/UserLogin.tsx:142
|
||||
msgid "If that address is registered you'll receive a reset link shortly."
|
||||
msgstr "If that address is registered you'll receive a reset link shortly."
|
||||
|
||||
@@ -965,7 +1029,11 @@ msgstr "In the chat"
|
||||
msgid "Insert emoji"
|
||||
msgstr "Insert emoji"
|
||||
|
||||
#: src/pages/UserRegister.tsx:117
|
||||
#: src/pages/Manage.tsx:43
|
||||
msgid "Instances"
|
||||
msgstr "Instances"
|
||||
|
||||
#: src/pages/UserRegister.tsx:119
|
||||
msgid "Invalid invite"
|
||||
msgstr "Invalid invite"
|
||||
|
||||
@@ -979,7 +1047,7 @@ msgstr "Invalid link"
|
||||
msgid "Invite link"
|
||||
msgstr "Invite link"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:116
|
||||
#: src/components/profile/ProfileHeader.tsx:126
|
||||
msgid "invited by"
|
||||
msgstr "invited by"
|
||||
|
||||
@@ -998,8 +1066,12 @@ msgstr "invited by you"
|
||||
msgid "Invitees"
|
||||
msgstr "Invitees"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:105
|
||||
msgid "Its address, like music.example"
|
||||
msgstr "Its address, like music.example"
|
||||
|
||||
#: src/components/feed/FeedTabBar.tsx:41
|
||||
#: src/pages/Settings.tsx:54
|
||||
#: src/pages/Settings.tsx:56
|
||||
msgid "Journal"
|
||||
msgstr "Journal"
|
||||
|
||||
@@ -1007,11 +1079,16 @@ msgstr "Journal"
|
||||
msgid "Keep editing"
|
||||
msgstr "Keep editing"
|
||||
|
||||
#. placeholder {0}: relativeTime(grant.lastUsedAt)
|
||||
#: src/components/federation/GrantList.tsx:77
|
||||
msgid "last used {0}"
|
||||
msgstr "last used {0}"
|
||||
|
||||
#: src/components/profile/UsernameField.tsx:59
|
||||
msgid "Letters, numbers and underscores only"
|
||||
msgstr "Letters, numbers and underscores only"
|
||||
|
||||
#: src/pages/Settings.tsx:47
|
||||
#: src/pages/Settings.tsx:49
|
||||
msgid "Light"
|
||||
msgstr "Light"
|
||||
|
||||
@@ -1068,17 +1145,20 @@ msgstr "Loading profile…"
|
||||
#: src/components/category/CategoryManager.tsx:60
|
||||
#: src/components/chat/ChatModal.tsx:763
|
||||
#: src/components/editor/EmojiPickerPopup.tsx:125
|
||||
#: src/components/federation/PeerManager.tsx:108
|
||||
#: src/components/playlist/PlaylistMembershipPanel.tsx:45
|
||||
#: src/components/shared/ListState.tsx:38
|
||||
#: src/components/shared/LoadMoreButton.tsx:32
|
||||
#: src/components/social/UserListPopover.tsx:151
|
||||
#: src/pages/Authorize.tsx:122
|
||||
msgid "Loading…"
|
||||
msgstr "Loading…"
|
||||
|
||||
#: src/components/layout/AppHeader.tsx:208
|
||||
#: src/pages/UserLogin.tsx:41
|
||||
#: src/pages/UserLogin.tsx:67
|
||||
#: src/pages/UserLogin.tsx:86
|
||||
#: src/pages/FederationCallback.tsx:31
|
||||
#: src/pages/UserLogin.tsx:44
|
||||
#: src/pages/UserLogin.tsx:71
|
||||
#: src/pages/UserLogin.tsx:90
|
||||
msgid "Log in"
|
||||
msgstr "Log in"
|
||||
|
||||
@@ -1090,16 +1170,22 @@ msgstr "Log in to like"
|
||||
msgid "Log in to vote"
|
||||
msgstr "Log in to vote"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:126
|
||||
#. placeholder {0}: peer.name ?? peer.host
|
||||
#: src/components/federation/FederatedSignIn.tsx:97
|
||||
msgid "Log in with {0}"
|
||||
msgstr "Log in with {0}"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:127
|
||||
#: src/pages/UserPublicProfile.tsx:131
|
||||
msgid "Log out"
|
||||
msgstr "Log out"
|
||||
|
||||
#: src/pages/UserLogin.tsx:85
|
||||
#: src/pages/UserLogin.tsx:89
|
||||
msgid "Logging in…"
|
||||
msgstr "Logging in…"
|
||||
|
||||
#: src/pages/UserLogin.tsx:72
|
||||
#: src/pages/FederationCallback.tsx:63
|
||||
#: src/pages/UserLogin.tsx:76
|
||||
msgid "Login failed"
|
||||
msgstr "Login failed"
|
||||
|
||||
@@ -1107,9 +1193,9 @@ msgstr "Login failed"
|
||||
msgid "Lowercase letters, numbers and single hyphens only"
|
||||
msgstr "Lowercase letters, numbers and single hyphens only"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:113
|
||||
#: src/pages/Manage.tsx:24
|
||||
#: src/pages/Manage.tsx:29
|
||||
#: src/components/layout/UserMenu.tsx:114
|
||||
#: src/pages/Manage.tsx:27
|
||||
#: src/pages/Manage.tsx:34
|
||||
#: src/pages/UserPublicProfile.tsx:164
|
||||
msgid "Manage"
|
||||
msgstr "Manage"
|
||||
@@ -1138,7 +1224,7 @@ msgstr "Name"
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:692
|
||||
#: src/components/feed/FeedTabBar.tsx:40
|
||||
#: src/pages/Settings.tsx:53
|
||||
#: src/pages/Settings.tsx:55
|
||||
msgid "New"
|
||||
msgstr "New"
|
||||
|
||||
@@ -1231,6 +1317,10 @@ msgstr "No users match \"{q}\"."
|
||||
msgid "Not following anyone yet."
|
||||
msgstr "Not following anyone yet."
|
||||
|
||||
#: src/pages/Authorize.tsx:103
|
||||
msgid "Not from here"
|
||||
msgstr "Not from here"
|
||||
|
||||
#: src/pages/Community.tsx:127
|
||||
msgid "Nothing happened this month."
|
||||
msgstr "Nothing happened this month."
|
||||
@@ -1248,7 +1338,7 @@ msgstr "Nothing here yet."
|
||||
#: src/components/layout/NotificationBell.tsx:57
|
||||
#: src/pages/Notifications.tsx:387
|
||||
#: src/pages/Notifications.tsx:505
|
||||
#: src/pages/Settings.tsx:130
|
||||
#: src/pages/Settings.tsx:163
|
||||
msgid "Notifications"
|
||||
msgstr "Notifications"
|
||||
|
||||
@@ -1256,11 +1346,11 @@ msgstr "Notifications"
|
||||
msgid "Notifications ({unreadNotificationCount} unread)"
|
||||
msgstr "Notifications ({unreadNotificationCount} unread)"
|
||||
|
||||
#: src/pages/Settings.tsx:60
|
||||
#: src/pages/Settings.tsx:62
|
||||
msgid "Off"
|
||||
msgstr "Off"
|
||||
|
||||
#: src/pages/Settings.tsx:59
|
||||
#: src/pages/Settings.tsx:61
|
||||
msgid "On"
|
||||
msgstr "On"
|
||||
|
||||
@@ -1300,6 +1390,18 @@ msgstr "Open the chat"
|
||||
msgid "or <0>browse files</0>"
|
||||
msgstr "or <0>browse files</0>"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:82
|
||||
msgid "Or join with your account on another gerbeur"
|
||||
msgstr "Or join with your account on another gerbeur"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:83
|
||||
msgid "Or log in with your account on another gerbeur"
|
||||
msgstr "Or log in with your account on another gerbeur"
|
||||
|
||||
#: src/pages/Settings.tsx:128
|
||||
msgid "Other instances"
|
||||
msgstr "Other instances"
|
||||
|
||||
#: src/pages/UserPublicProfile.tsx:157
|
||||
msgid "Overview"
|
||||
msgstr "Overview"
|
||||
@@ -1308,13 +1410,14 @@ msgstr "Overview"
|
||||
msgid "Page not found"
|
||||
msgstr "Page not found"
|
||||
|
||||
#: src/pages/Settings.tsx:90
|
||||
#: src/pages/UserLogin.tsx:82
|
||||
#: src/pages/Settings.tsx:96
|
||||
#: src/pages/Settings.tsx:106
|
||||
#: src/pages/UserLogin.tsx:86
|
||||
msgid "Password"
|
||||
msgstr "Password"
|
||||
|
||||
#. placeholder {0}: VALIDATION.PASSWORD_MIN
|
||||
#: src/pages/UserRegister.tsx:158
|
||||
#: src/pages/UserRegister.tsx:160
|
||||
msgid "Password (min. {0} characters)"
|
||||
msgstr "Password (min. {0} characters)"
|
||||
|
||||
@@ -1416,17 +1519,17 @@ msgstr "Refreshing stream…"
|
||||
msgid "Refreshing…"
|
||||
msgstr "Refreshing…"
|
||||
|
||||
#: src/pages/UserRegister.tsx:45
|
||||
#: src/pages/UserRegister.tsx:129
|
||||
#: src/pages/UserRegister.tsx:169
|
||||
#: src/pages/UserRegister.tsx:47
|
||||
#: src/pages/UserRegister.tsx:131
|
||||
#: src/pages/UserRegister.tsx:171
|
||||
msgid "Register"
|
||||
msgstr "Register"
|
||||
|
||||
#: src/pages/UserRegister.tsx:168
|
||||
#: src/pages/UserRegister.tsx:170
|
||||
msgid "Registering…"
|
||||
msgstr "Registering…"
|
||||
|
||||
#: src/pages/UserRegister.tsx:134
|
||||
#: src/pages/UserRegister.tsx:136
|
||||
msgid "Registration failed"
|
||||
msgstr "Registration failed"
|
||||
|
||||
@@ -1434,6 +1537,12 @@ msgstr "Registration failed"
|
||||
msgid "Related"
|
||||
msgstr "Related"
|
||||
|
||||
#. placeholder {0}: peer.host
|
||||
#: src/components/federation/PeerManager.tsx:133
|
||||
#: src/components/federation/PeerManager.tsx:134
|
||||
msgid "Remove {0}"
|
||||
msgstr "Remove {0}"
|
||||
|
||||
#: src/components/form/FileDropZone.tsx:139
|
||||
msgid "Remove file"
|
||||
msgstr "Remove file"
|
||||
@@ -1472,7 +1581,7 @@ msgstr "Reply"
|
||||
msgid "Replying to"
|
||||
msgstr "Replying to"
|
||||
|
||||
#: src/pages/UserLogin.tsx:148
|
||||
#: src/pages/UserLogin.tsx:154
|
||||
msgid "Request failed"
|
||||
msgstr "Request failed"
|
||||
|
||||
@@ -1579,12 +1688,12 @@ msgstr "Seek"
|
||||
msgid "Send"
|
||||
msgstr "Send"
|
||||
|
||||
#: src/pages/UserLogin.tsx:157
|
||||
#: src/pages/UserLogin.tsx:163
|
||||
msgid "Send reset link"
|
||||
msgstr "Send reset link"
|
||||
|
||||
#: src/components/chat/PendingItem.tsx:104
|
||||
#: src/pages/UserLogin.tsx:156
|
||||
#: src/pages/UserLogin.tsx:162
|
||||
msgid "Sending…"
|
||||
msgstr "Sending…"
|
||||
|
||||
@@ -1603,8 +1712,8 @@ msgid "email.settings"
|
||||
msgstr "Settings"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:104
|
||||
#: src/pages/Settings.tsx:72
|
||||
#: src/pages/Settings.tsx:84
|
||||
#: src/pages/Settings.tsx:75
|
||||
#: src/pages/Settings.tsx:88
|
||||
msgid "Settings"
|
||||
msgstr "Settings"
|
||||
|
||||
@@ -1612,6 +1721,19 @@ msgstr "Settings"
|
||||
msgid "Several people are typing…"
|
||||
msgstr "Several people are typing…"
|
||||
|
||||
#: src/pages/Authorize.tsx:37
|
||||
msgid "Sign in elsewhere"
|
||||
msgstr "Sign in elsewhere"
|
||||
|
||||
#: src/pages/Authorize.tsx:135
|
||||
msgid "Sign in to {name}?"
|
||||
msgstr "Sign in to {name}?"
|
||||
|
||||
#: src/pages/Authorize.tsx:154
|
||||
#: src/pages/FederationCallback.tsx:73
|
||||
msgid "Signing you in…"
|
||||
msgstr "Signing you in…"
|
||||
|
||||
#: src/components/profile/ProfileOwnActions.tsx:102
|
||||
msgid "Single use, valid for 7 days."
|
||||
msgstr "Single use, valid for 7 days."
|
||||
@@ -1636,7 +1758,7 @@ msgstr "Someone asked to reset the password of your {site} account. The button b
|
||||
msgid "Something went wrong"
|
||||
msgstr "Something went wrong"
|
||||
|
||||
#: src/pages/Settings.tsx:132
|
||||
#: src/pages/Settings.tsx:165
|
||||
msgid "Sounds"
|
||||
msgstr "Sounds"
|
||||
|
||||
@@ -1644,7 +1766,7 @@ msgstr "Sounds"
|
||||
msgid "Start fresh"
|
||||
msgstr "Start fresh"
|
||||
|
||||
#: src/pages/Settings.tsx:103
|
||||
#: src/pages/Settings.tsx:136
|
||||
msgid "Style"
|
||||
msgstr "Style"
|
||||
|
||||
@@ -1696,11 +1818,11 @@ msgstr "The new order couldn't be saved. Try again."
|
||||
msgid "This comment couldn't be deleted. Try again."
|
||||
msgstr "This comment couldn't be deleted. Try again."
|
||||
|
||||
#: src/pages/UserRegister.tsx:118
|
||||
#: src/pages/UserRegister.tsx:120
|
||||
msgid "This invite link is missing, expired, or already used."
|
||||
msgstr "This invite link is missing, expired, or already used."
|
||||
|
||||
#: src/pages/UserLogin.tsx:104
|
||||
#: src/pages/UserLogin.tsx:110
|
||||
msgid "This is a mirage."
|
||||
msgstr "This is a mirage."
|
||||
|
||||
@@ -1716,7 +1838,11 @@ msgstr "This page does not exist."
|
||||
msgid "This reset link is missing or malformed."
|
||||
msgstr "This reset link is missing or malformed."
|
||||
|
||||
#: src/pages/Settings.tsx:168
|
||||
#: src/pages/FederationCallback.tsx:38
|
||||
msgid "This sign-in link is incomplete."
|
||||
msgstr "This sign-in link is incomplete."
|
||||
|
||||
#: src/pages/Settings.tsx:201
|
||||
msgid "This site doesn't send email, so no digest goes out."
|
||||
msgstr "This site doesn't send email, so no digest goes out."
|
||||
|
||||
@@ -1763,6 +1889,14 @@ msgstr "Top this week"
|
||||
msgid "Track {0}"
|
||||
msgstr "Track {0}"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:155
|
||||
msgid "Trust"
|
||||
msgstr "Trust"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:32
|
||||
msgid "Trusted"
|
||||
msgstr "Trusted"
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:668
|
||||
msgid "Try again"
|
||||
msgstr "Try again"
|
||||
@@ -1826,7 +1960,7 @@ msgstr "Unsubscribed"
|
||||
msgid "email.digest.upload"
|
||||
msgstr "upload"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:72
|
||||
#: src/components/profile/ProfileHeader.tsx:79
|
||||
msgid "Upload failed"
|
||||
msgstr "Upload failed"
|
||||
|
||||
@@ -1883,9 +2017,9 @@ msgstr "User menu"
|
||||
|
||||
#: src/components/profile/ProfileManageTab.tsx:61
|
||||
#: src/components/profile/UsernameField.tsx:51
|
||||
#: src/pages/Settings.tsx:87
|
||||
#: src/pages/UserLogin.tsx:75
|
||||
#: src/pages/UserRegister.tsx:137
|
||||
#: src/pages/Settings.tsx:91
|
||||
#: src/pages/UserLogin.tsx:79
|
||||
#: src/pages/UserRegister.tsx:139
|
||||
msgid "Username"
|
||||
msgstr "Username"
|
||||
|
||||
@@ -1894,6 +2028,10 @@ msgstr "Username"
|
||||
msgid "Users"
|
||||
msgstr "Users"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:169
|
||||
msgid "Users of a trusted instance sign in here with their account there. Those of a blocked one can't. Users of any other instance need an invite."
|
||||
msgstr "Users of a trusted instance sign in here with their account there. Those of a blocked one can't. Users of any other instance need an invite."
|
||||
|
||||
#: src/components/profile/ProfileSection.tsx:43
|
||||
msgid "View all →"
|
||||
msgstr "View all →"
|
||||
@@ -1952,6 +2090,10 @@ msgstr "Yesterday"
|
||||
msgid "You can post it anyway."
|
||||
msgstr "You can post it anyway."
|
||||
|
||||
#: src/components/federation/GrantList.tsx:93
|
||||
msgid "You haven't signed in to another gerbeur with this account yet."
|
||||
msgstr "You haven't signed in to another gerbeur with this account yet."
|
||||
|
||||
#: src/pages/Unsubscribe.tsx:94
|
||||
msgid "You won't get the monthly recap any more. You can turn it back on in your settings."
|
||||
msgstr "You won't get the monthly recap any more. You can turn it back on in your settings."
|
||||
@@ -1997,7 +2139,15 @@ msgstr "You've reached the end."
|
||||
msgid "email.welcome.preheader"
|
||||
msgstr "Your account is ready."
|
||||
|
||||
#: src/pages/UserLogin.tsx:152
|
||||
#: src/pages/Authorize.tsx:104
|
||||
msgid "Your account lives on {home}: sign in to other instances from there."
|
||||
msgstr "Your account lives on {home}: sign in to other instances from there."
|
||||
|
||||
#: src/pages/Settings.tsx:119
|
||||
msgid "Your account lives on {home}: your password, email address, avatar and username change there."
|
||||
msgstr "Your account lives on {home}: your password, email address, avatar and username change there."
|
||||
|
||||
#: src/pages/UserLogin.tsx:158
|
||||
msgid "Your email address"
|
||||
msgstr "Your email address"
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
276
locales/fr.po
276
locales/fr.po
@@ -51,7 +51,7 @@ msgstr "{0} de plus en ligne : {restNames}"
|
||||
|
||||
#. placeholder {0}: VALIDATION.USERNAME_MIN
|
||||
#. placeholder {1}: VALIDATION.USERNAME_MAX
|
||||
#: src/pages/UserRegister.tsx:145
|
||||
#: src/pages/UserRegister.tsx:147
|
||||
msgid "{0}–{1} characters: letters, numbers, or underscores"
|
||||
msgstr "{0}–{1} caractères : lettres, chiffres ou tirets bas"
|
||||
|
||||
@@ -280,6 +280,10 @@ msgstr "<0>{0}</0> a voté pour <1>{1}</1>"
|
||||
msgid "<0>{0}</0> was added to <1>{1}</1>"
|
||||
msgstr "<0>{0}</0> a été ajouté à <1>{1}</1>"
|
||||
|
||||
#: src/pages/Authorize.tsx:138
|
||||
msgid "<0>{name}</0> ({host}) asks to sign you in with your account here, <1>@{username}</1>. It will receive your username, your email address and your avatar."
|
||||
msgstr "<0>{name}</0> ({host}) demande à vous connecter avec votre compte d'ici, <1>@{username}</1>. Il recevra votre nom d'utilisateur, votre adresse e-mail et votre avatar."
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:778
|
||||
msgid "1 new message"
|
||||
msgstr "1 nouveau message"
|
||||
@@ -296,10 +300,14 @@ msgstr "Il faut un lien"
|
||||
msgid "a post"
|
||||
msgstr "une publication"
|
||||
|
||||
#: src/pages/Settings.tsx:85
|
||||
#: src/pages/Settings.tsx:89
|
||||
msgid "Account"
|
||||
msgstr "Compte"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:144
|
||||
msgid "Account on <0>{host}</0>"
|
||||
msgstr "Compte sur <0>{host}</0>"
|
||||
|
||||
#: src/components/comment/CommentThread.tsx:102
|
||||
msgid "Add a comment…"
|
||||
msgstr "Ajouter un commentaire…"
|
||||
@@ -309,7 +317,7 @@ msgstr "Ajouter un commentaire…"
|
||||
msgid "Add category"
|
||||
msgstr "Ajouter une catégorie"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:153
|
||||
#: src/components/profile/ProfileHeader.tsx:173
|
||||
msgid "Add email…"
|
||||
msgstr "Ajouter un e-mail…"
|
||||
|
||||
@@ -342,10 +350,14 @@ msgstr "Tout"
|
||||
msgid "Already dumped by {0} {1}"
|
||||
msgstr "Déjà recommandé par {0} {1}"
|
||||
|
||||
#: src/pages/UserRegister.tsx:175
|
||||
#: src/pages/UserRegister.tsx:179
|
||||
msgid "Already have an account? <0>Log in</0>"
|
||||
msgstr "Vous avez déjà un compte ? <0>Se connecter</0>"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:149
|
||||
msgid "An instance's address, like music.example"
|
||||
msgstr "L'adresse d'une instance, comme music.example"
|
||||
|
||||
#: src/utils/shared/api.ts:35
|
||||
msgid "An unexpected error occurred."
|
||||
msgstr "Une erreur inattendue s'est produite."
|
||||
@@ -355,14 +367,14 @@ msgstr "Une erreur inattendue s'est produite."
|
||||
msgid "email.digest.andMore"
|
||||
msgstr "et {n} de plus"
|
||||
|
||||
#: src/pages/Settings.tsx:101
|
||||
#: src/pages/Settings.tsx:134
|
||||
msgid "Appearance"
|
||||
msgstr "Apparence"
|
||||
|
||||
#. placeholder {0}: VALIDATION.PASSWORD_MIN
|
||||
#: src/components/profile/ChangePasswordModal.tsx:101
|
||||
#: src/pages/ResetPassword.tsx:124
|
||||
#: src/pages/UserRegister.tsx:164
|
||||
#: src/pages/UserRegister.tsx:166
|
||||
msgid "At least {0} characters"
|
||||
msgstr "Au moins {0} caractères"
|
||||
|
||||
@@ -370,7 +382,7 @@ msgstr "Au moins {0} caractères"
|
||||
msgid "At most {maxLength} characters."
|
||||
msgstr "{maxLength} caractères au maximum."
|
||||
|
||||
#: src/pages/Settings.tsx:46
|
||||
#: src/pages/Settings.tsx:48
|
||||
msgid "Auto"
|
||||
msgstr "Auto"
|
||||
|
||||
@@ -379,6 +391,18 @@ msgstr "Auto"
|
||||
msgid "Back to login"
|
||||
msgstr "Retour à la connexion"
|
||||
|
||||
#: src/pages/FederationCallback.tsx:66
|
||||
msgid "Back to the login page"
|
||||
msgstr "Retour à la page de connexion"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:163
|
||||
msgid "Block"
|
||||
msgstr "Bloquer"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:33
|
||||
msgid "Blocked"
|
||||
msgstr "Bloquée"
|
||||
|
||||
#. js-lingui-explicit-id
|
||||
#: api/mail/digest.ts:225
|
||||
msgid "email.digest.by"
|
||||
@@ -394,6 +418,11 @@ msgstr "par @{username} · {n, plural, one {# reco} other {# recos}}"
|
||||
msgid "Can't connect to the live updates server. Upvotes and notifications may not sync until it reconnects."
|
||||
msgstr "Impossible de se connecter au serveur de mises à jour en direct. Les votes et les notifications pourraient ne pas se synchroniser avant la reconnexion."
|
||||
|
||||
#: src/pages/Authorize.tsx:117
|
||||
#: src/pages/Authorize.tsx:145
|
||||
msgid "Can't sign in there"
|
||||
msgstr "Connexion impossible"
|
||||
|
||||
#: src/components/category/CategoryManager.tsx:225
|
||||
#: src/components/category/CategoryManager.tsx:226
|
||||
#: src/components/chat/ChatEditBox.tsx:92
|
||||
@@ -404,6 +433,7 @@ msgstr "Impossible de se connecter au serveur de mises à jour en direct. Les vo
|
||||
#: src/components/profile/DescriptionEditor.tsx:97
|
||||
#: src/components/profile/EmailEditor.tsx:83
|
||||
#: src/components/shared/ConfirmModal.tsx:63
|
||||
#: src/pages/Authorize.tsx:158
|
||||
#: src/pages/Dump.tsx:445
|
||||
#: src/pages/DumpEdit.tsx:565
|
||||
msgid "Cancel"
|
||||
@@ -423,7 +453,7 @@ msgid "Cancel search"
|
||||
msgstr "Annuler la recherche"
|
||||
|
||||
#: src/components/category/CategorySelect.tsx:33
|
||||
#: src/pages/Manage.tsx:30
|
||||
#: src/pages/Manage.tsx:36
|
||||
msgid "Categories"
|
||||
msgstr "Catégories"
|
||||
|
||||
@@ -431,7 +461,7 @@ msgstr "Catégories"
|
||||
msgid "Category"
|
||||
msgstr "Catégorie"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:95
|
||||
#: src/components/profile/ProfileHeader.tsx:102
|
||||
msgid "Change avatar"
|
||||
msgstr "Changer l'avatar"
|
||||
|
||||
@@ -439,12 +469,16 @@ msgstr "Changer l'avatar"
|
||||
msgid "Change image"
|
||||
msgstr "Changer l'image"
|
||||
|
||||
#: src/pages/Settings.tsx:101
|
||||
msgid "Change it on {home}"
|
||||
msgstr "Le changer sur {home}"
|
||||
|
||||
#: src/components/profile/ChangePasswordModal.tsx:66
|
||||
#: src/components/profile/ChangePasswordModal.tsx:120
|
||||
msgid "Change password"
|
||||
msgstr "Changer le mot de passe"
|
||||
|
||||
#: src/pages/Settings.tsx:96
|
||||
#: src/pages/Settings.tsx:112
|
||||
msgid "Change password…"
|
||||
msgstr "Changer le mot de passe…"
|
||||
|
||||
@@ -464,10 +498,14 @@ msgstr "Tribune"
|
||||
msgid "Chat ({unreadChatCount} unread)"
|
||||
msgstr "{unreadChatCount} messages non lus"
|
||||
|
||||
#: src/pages/UserRegister.tsx:106
|
||||
#: src/pages/UserRegister.tsx:108
|
||||
msgid "Checking invite…"
|
||||
msgstr "Vérification de l'invitation…"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:154
|
||||
msgid "Checking…"
|
||||
msgstr "Vérification…"
|
||||
|
||||
#: src/components/profile/ChangePasswordModal.tsx:75
|
||||
#: src/components/shared/Modal.tsx:76
|
||||
msgid "Close"
|
||||
@@ -493,7 +531,7 @@ msgstr "Fermer sans publier ? Le fichier joint sera perdu — ce que vous avez
|
||||
msgid "Collapse player"
|
||||
msgstr "Réduire le lecteur"
|
||||
|
||||
#: src/pages/Settings.tsx:110
|
||||
#: src/pages/Settings.tsx:143
|
||||
msgid "Color scheme"
|
||||
msgstr "Thème de couleur"
|
||||
|
||||
@@ -507,10 +545,22 @@ msgstr "Communauté"
|
||||
msgid "Confirm new password"
|
||||
msgstr "Confirmer le nouveau mot de passe"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:111
|
||||
msgid "Connecting…"
|
||||
msgstr "Connexion…"
|
||||
|
||||
#: src/contexts/ws/WSProvider.tsx:757
|
||||
msgid "Connection lost — this message may not have been sent"
|
||||
msgstr "Connexion perdue — ce message n'a peut-être pas été envoyé"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:113
|
||||
msgid "Continue"
|
||||
msgstr "Continuer"
|
||||
|
||||
#: src/pages/Authorize.tsx:155
|
||||
msgid "Continue as @{username}"
|
||||
msgstr "Continuer en tant que @{username}"
|
||||
|
||||
#: src/components/profile/ProfileOwnActions.tsx:99
|
||||
msgid "Copied!"
|
||||
msgstr "Copié !"
|
||||
@@ -540,6 +590,10 @@ msgstr "Renommage impossible"
|
||||
msgid "Could not save"
|
||||
msgstr "Sauvegarde impossible"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:146
|
||||
msgid "Couldn't add that instance"
|
||||
msgstr "Impossible d'ajouter cette instance"
|
||||
|
||||
#: src/components/dump/create/DumpCreateModal.tsx:607
|
||||
msgid "Couldn't load a preview for this link — check it, or post it as-is and refresh the preview later."
|
||||
msgstr "Impossible de charger un aperçu pour ce lien — vérifiez-le, ou publiez-le tel quel et actualisez l'aperçu plus tard."
|
||||
@@ -548,6 +602,10 @@ msgstr "Impossible de charger un aperçu pour ce lien — vérifiez-le, ou publi
|
||||
msgid "Couldn't load the chat."
|
||||
msgstr "Impossible de charger le chat."
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:102
|
||||
msgid "Couldn't reach that instance"
|
||||
msgstr "Impossible de joindre cette instance"
|
||||
|
||||
#: src/pages/Unsubscribe.tsx:116
|
||||
msgid "Couldn't unsubscribe"
|
||||
msgstr "Désabonnement impossible"
|
||||
@@ -576,11 +634,11 @@ msgstr "Création…"
|
||||
msgid "Current password"
|
||||
msgstr "Mot de passe actuel"
|
||||
|
||||
#: src/pages/Settings.tsx:48
|
||||
#: src/pages/Settings.tsx:50
|
||||
msgid "Dark"
|
||||
msgstr "Sombre"
|
||||
|
||||
#: src/pages/Settings.tsx:121
|
||||
#: src/pages/Settings.tsx:154
|
||||
msgid "Default tab"
|
||||
msgstr "Onglet par défaut"
|
||||
|
||||
@@ -655,6 +713,10 @@ msgstr "Description (facultatif)"
|
||||
msgid "Discard"
|
||||
msgstr "Abandonner"
|
||||
|
||||
#: src/components/federation/GrantList.tsx:84
|
||||
msgid "Disconnect"
|
||||
msgstr "Déconnecter"
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:743
|
||||
msgid "Disconnected — reconnecting…"
|
||||
msgstr "Déconnecté — reconnexion…"
|
||||
@@ -730,7 +792,7 @@ msgstr "Modifier {0}"
|
||||
msgid "Edit description"
|
||||
msgstr "Modifier la description"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:151
|
||||
#: src/components/profile/ProfileHeader.tsx:171
|
||||
msgid "Edit email"
|
||||
msgstr "Modifier l'e-mail"
|
||||
|
||||
@@ -772,11 +834,11 @@ msgstr "Modification"
|
||||
msgid "Editing {0}"
|
||||
msgstr "Édition de {0}"
|
||||
|
||||
#: src/pages/Settings.tsx:145
|
||||
#: src/pages/Settings.tsx:178
|
||||
msgid "Email"
|
||||
msgstr "E-mail"
|
||||
|
||||
#: src/pages/UserRegister.tsx:152
|
||||
#: src/pages/UserRegister.tsx:154
|
||||
msgid "Email address"
|
||||
msgstr "Adresse e-mail"
|
||||
|
||||
@@ -822,6 +884,8 @@ msgstr "Impossible de publier le commentaire"
|
||||
msgid "Failed to post reply"
|
||||
msgstr "Impossible de publier la réponse"
|
||||
|
||||
#: src/components/federation/GrantList.tsx:98
|
||||
#: src/components/federation/PeerManager.tsx:143
|
||||
#: src/components/playlist/PlaylistEditForm.tsx:185
|
||||
#: src/components/profile/DescriptionEditor.tsx:99
|
||||
#: src/components/profile/EmailEditor.tsx:86
|
||||
@@ -836,7 +900,7 @@ msgstr "Échec de l’enregistrement de la catégorie"
|
||||
msgid "Failed to save edit"
|
||||
msgstr "Impossible d'enregistrer la modification"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:162
|
||||
#: src/components/profile/ProfileHeader.tsx:182
|
||||
msgid "Failed to update avatar"
|
||||
msgstr "Impossible de mettre à jour l'avatar"
|
||||
|
||||
@@ -844,7 +908,7 @@ msgstr "Impossible de mettre à jour l'avatar"
|
||||
msgid "Failed to update role"
|
||||
msgstr "Erreur lors de la mise à jour du rôle"
|
||||
|
||||
#: src/pages/Settings.tsx:119
|
||||
#: src/pages/Settings.tsx:152
|
||||
msgid "Feeds"
|
||||
msgstr "Flux"
|
||||
|
||||
@@ -879,7 +943,7 @@ msgstr "Suivez des utilisateurs pour voir leurs recos ici."
|
||||
|
||||
#: src/components/feed/FeedTabBar.tsx:43
|
||||
#: src/components/profile/ProfileFollowTab.tsx:140
|
||||
#: src/pages/Settings.tsx:55
|
||||
#: src/pages/Settings.tsx:57
|
||||
#: src/pages/UserPublicProfile.tsx:161
|
||||
msgid "Followed"
|
||||
msgstr "Suivi"
|
||||
@@ -894,7 +958,7 @@ msgstr "Abonné"
|
||||
msgid "email.digest.forYou"
|
||||
msgstr "Pour vous"
|
||||
|
||||
#: src/pages/UserLogin.tsx:97
|
||||
#: src/pages/UserLogin.tsx:101
|
||||
msgid "Forgot password?"
|
||||
msgstr "Mot de passe oublié ?"
|
||||
|
||||
@@ -929,11 +993,11 @@ msgid "email.reset.hi"
|
||||
msgstr "Bonjour {username},"
|
||||
|
||||
#: src/components/feed/FeedTabBar.tsx:39
|
||||
#: src/pages/Settings.tsx:52
|
||||
#: src/pages/Settings.tsx:54
|
||||
msgid "Hot"
|
||||
msgstr "Tendances"
|
||||
|
||||
#: src/pages/UserLogin.tsx:136
|
||||
#: src/pages/UserLogin.tsx:142
|
||||
msgid "If that address is registered you'll receive a reset link shortly."
|
||||
msgstr "Si cette adresse est enregistrée, vous recevrez un lien de réinitialisation sous peu."
|
||||
|
||||
@@ -965,7 +1029,11 @@ msgstr "Dans la tribune"
|
||||
msgid "Insert emoji"
|
||||
msgstr "Insérer un emoji"
|
||||
|
||||
#: src/pages/UserRegister.tsx:117
|
||||
#: src/pages/Manage.tsx:43
|
||||
msgid "Instances"
|
||||
msgstr "Instances"
|
||||
|
||||
#: src/pages/UserRegister.tsx:119
|
||||
msgid "Invalid invite"
|
||||
msgstr "Invitation invalide"
|
||||
|
||||
@@ -979,7 +1047,7 @@ msgstr "Lien invalide"
|
||||
msgid "Invite link"
|
||||
msgstr "Lien d'invitation"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:116
|
||||
#: src/components/profile/ProfileHeader.tsx:126
|
||||
msgid "invited by"
|
||||
msgstr "invité par"
|
||||
|
||||
@@ -998,8 +1066,12 @@ msgstr "sur votre invitation"
|
||||
msgid "Invitees"
|
||||
msgstr "Invités"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:105
|
||||
msgid "Its address, like music.example"
|
||||
msgstr "Son adresse, comme music.example"
|
||||
|
||||
#: src/components/feed/FeedTabBar.tsx:41
|
||||
#: src/pages/Settings.tsx:54
|
||||
#: src/pages/Settings.tsx:56
|
||||
msgid "Journal"
|
||||
msgstr "Journal"
|
||||
|
||||
@@ -1007,11 +1079,16 @@ msgstr "Journal"
|
||||
msgid "Keep editing"
|
||||
msgstr "Continuer l'édition"
|
||||
|
||||
#. placeholder {0}: relativeTime(grant.lastUsedAt)
|
||||
#: src/components/federation/GrantList.tsx:77
|
||||
msgid "last used {0}"
|
||||
msgstr "utilisée {0}"
|
||||
|
||||
#: src/components/profile/UsernameField.tsx:59
|
||||
msgid "Letters, numbers and underscores only"
|
||||
msgstr "Lettres, chiffres et tirets bas seulement"
|
||||
|
||||
#: src/pages/Settings.tsx:47
|
||||
#: src/pages/Settings.tsx:49
|
||||
msgid "Light"
|
||||
msgstr "Clair"
|
||||
|
||||
@@ -1068,17 +1145,20 @@ msgstr "Chargement du profil…"
|
||||
#: src/components/category/CategoryManager.tsx:60
|
||||
#: src/components/chat/ChatModal.tsx:763
|
||||
#: src/components/editor/EmojiPickerPopup.tsx:125
|
||||
#: src/components/federation/PeerManager.tsx:108
|
||||
#: src/components/playlist/PlaylistMembershipPanel.tsx:45
|
||||
#: src/components/shared/ListState.tsx:38
|
||||
#: src/components/shared/LoadMoreButton.tsx:32
|
||||
#: src/components/social/UserListPopover.tsx:151
|
||||
#: src/pages/Authorize.tsx:122
|
||||
msgid "Loading…"
|
||||
msgstr "Chargement…"
|
||||
|
||||
#: src/components/layout/AppHeader.tsx:208
|
||||
#: src/pages/UserLogin.tsx:41
|
||||
#: src/pages/UserLogin.tsx:67
|
||||
#: src/pages/UserLogin.tsx:86
|
||||
#: src/pages/FederationCallback.tsx:31
|
||||
#: src/pages/UserLogin.tsx:44
|
||||
#: src/pages/UserLogin.tsx:71
|
||||
#: src/pages/UserLogin.tsx:90
|
||||
msgid "Log in"
|
||||
msgstr "Se connecter"
|
||||
|
||||
@@ -1090,16 +1170,22 @@ msgstr "Se connecter pour aimer"
|
||||
msgid "Log in to vote"
|
||||
msgstr "Se connecter pour voter"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:126
|
||||
#. placeholder {0}: peer.name ?? peer.host
|
||||
#: src/components/federation/FederatedSignIn.tsx:97
|
||||
msgid "Log in with {0}"
|
||||
msgstr "Se connecter avec {0}"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:127
|
||||
#: src/pages/UserPublicProfile.tsx:131
|
||||
msgid "Log out"
|
||||
msgstr "Se déconnecter"
|
||||
|
||||
#: src/pages/UserLogin.tsx:85
|
||||
#: src/pages/UserLogin.tsx:89
|
||||
msgid "Logging in…"
|
||||
msgstr "Connexion…"
|
||||
|
||||
#: src/pages/UserLogin.tsx:72
|
||||
#: src/pages/FederationCallback.tsx:63
|
||||
#: src/pages/UserLogin.tsx:76
|
||||
msgid "Login failed"
|
||||
msgstr "Connexion échouée"
|
||||
|
||||
@@ -1107,9 +1193,9 @@ msgstr "Connexion échouée"
|
||||
msgid "Lowercase letters, numbers and single hyphens only"
|
||||
msgstr "Minuscules, chiffres et tirets simples seulement"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:113
|
||||
#: src/pages/Manage.tsx:24
|
||||
#: src/pages/Manage.tsx:29
|
||||
#: src/components/layout/UserMenu.tsx:114
|
||||
#: src/pages/Manage.tsx:27
|
||||
#: src/pages/Manage.tsx:34
|
||||
#: src/pages/UserPublicProfile.tsx:164
|
||||
msgid "Manage"
|
||||
msgstr "Administration"
|
||||
@@ -1138,7 +1224,7 @@ msgstr "Nom"
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:692
|
||||
#: src/components/feed/FeedTabBar.tsx:40
|
||||
#: src/pages/Settings.tsx:53
|
||||
#: src/pages/Settings.tsx:55
|
||||
msgid "New"
|
||||
msgstr "Nouveau"
|
||||
|
||||
@@ -1231,6 +1317,10 @@ msgstr "Aucun utilisateur ne correspond à « {q} »."
|
||||
msgid "Not following anyone yet."
|
||||
msgstr "Aucun abonnement pour le moment."
|
||||
|
||||
#: src/pages/Authorize.tsx:103
|
||||
msgid "Not from here"
|
||||
msgstr "Compte d'ailleurs"
|
||||
|
||||
#: src/pages/Community.tsx:127
|
||||
msgid "Nothing happened this month."
|
||||
msgstr "Rien de neuf ce mois-ci."
|
||||
@@ -1248,7 +1338,7 @@ msgstr "Rien ici pour l'instant."
|
||||
#: src/components/layout/NotificationBell.tsx:57
|
||||
#: src/pages/Notifications.tsx:387
|
||||
#: src/pages/Notifications.tsx:505
|
||||
#: src/pages/Settings.tsx:130
|
||||
#: src/pages/Settings.tsx:163
|
||||
msgid "Notifications"
|
||||
msgstr "Notifications"
|
||||
|
||||
@@ -1256,11 +1346,11 @@ msgstr "Notifications"
|
||||
msgid "Notifications ({unreadNotificationCount} unread)"
|
||||
msgstr "Notifications ({unreadNotificationCount} non lues)"
|
||||
|
||||
#: src/pages/Settings.tsx:60
|
||||
#: src/pages/Settings.tsx:62
|
||||
msgid "Off"
|
||||
msgstr "Désactivés"
|
||||
|
||||
#: src/pages/Settings.tsx:59
|
||||
#: src/pages/Settings.tsx:61
|
||||
msgid "On"
|
||||
msgstr "Activés"
|
||||
|
||||
@@ -1300,6 +1390,18 @@ msgstr "Ouvrir la tribune"
|
||||
msgid "or <0>browse files</0>"
|
||||
msgstr "ou <0>parcourir les fichiers</0>"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:82
|
||||
msgid "Or join with your account on another gerbeur"
|
||||
msgstr "Ou rejoignez-nous avec votre compte d'un autre gerbeur"
|
||||
|
||||
#: src/components/federation/FederatedSignIn.tsx:83
|
||||
msgid "Or log in with your account on another gerbeur"
|
||||
msgstr "Ou connectez-vous avec votre compte d'un autre gerbeur"
|
||||
|
||||
#: src/pages/Settings.tsx:128
|
||||
msgid "Other instances"
|
||||
msgstr "Autres instances"
|
||||
|
||||
#: src/pages/UserPublicProfile.tsx:157
|
||||
msgid "Overview"
|
||||
msgstr "Aperçu"
|
||||
@@ -1308,13 +1410,14 @@ msgstr "Aperçu"
|
||||
msgid "Page not found"
|
||||
msgstr "Page introuvable"
|
||||
|
||||
#: src/pages/Settings.tsx:90
|
||||
#: src/pages/UserLogin.tsx:82
|
||||
#: src/pages/Settings.tsx:96
|
||||
#: src/pages/Settings.tsx:106
|
||||
#: src/pages/UserLogin.tsx:86
|
||||
msgid "Password"
|
||||
msgstr "Mot de passe"
|
||||
|
||||
#. placeholder {0}: VALIDATION.PASSWORD_MIN
|
||||
#: src/pages/UserRegister.tsx:158
|
||||
#: src/pages/UserRegister.tsx:160
|
||||
msgid "Password (min. {0} characters)"
|
||||
msgstr "Mot de passe (min. {0} caractères)"
|
||||
|
||||
@@ -1416,17 +1519,17 @@ msgstr "Actualisation du flux…"
|
||||
msgid "Refreshing…"
|
||||
msgstr "Actualisation…"
|
||||
|
||||
#: src/pages/UserRegister.tsx:45
|
||||
#: src/pages/UserRegister.tsx:129
|
||||
#: src/pages/UserRegister.tsx:169
|
||||
#: src/pages/UserRegister.tsx:47
|
||||
#: src/pages/UserRegister.tsx:131
|
||||
#: src/pages/UserRegister.tsx:171
|
||||
msgid "Register"
|
||||
msgstr "S'inscrire"
|
||||
|
||||
#: src/pages/UserRegister.tsx:168
|
||||
#: src/pages/UserRegister.tsx:170
|
||||
msgid "Registering…"
|
||||
msgstr "Inscription…"
|
||||
|
||||
#: src/pages/UserRegister.tsx:134
|
||||
#: src/pages/UserRegister.tsx:136
|
||||
msgid "Registration failed"
|
||||
msgstr "Inscription échouée"
|
||||
|
||||
@@ -1434,6 +1537,12 @@ msgstr "Inscription échouée"
|
||||
msgid "Related"
|
||||
msgstr "Connexe"
|
||||
|
||||
#. placeholder {0}: peer.host
|
||||
#: src/components/federation/PeerManager.tsx:133
|
||||
#: src/components/federation/PeerManager.tsx:134
|
||||
msgid "Remove {0}"
|
||||
msgstr "Retirer {0}"
|
||||
|
||||
#: src/components/form/FileDropZone.tsx:139
|
||||
msgid "Remove file"
|
||||
msgstr "Supprimer le fichier"
|
||||
@@ -1472,7 +1581,7 @@ msgstr "Répondre"
|
||||
msgid "Replying to"
|
||||
msgstr "En réponse à"
|
||||
|
||||
#: src/pages/UserLogin.tsx:148
|
||||
#: src/pages/UserLogin.tsx:154
|
||||
msgid "Request failed"
|
||||
msgstr "Échec de la demande"
|
||||
|
||||
@@ -1579,12 +1688,12 @@ msgstr "Position"
|
||||
msgid "Send"
|
||||
msgstr "Envoyer"
|
||||
|
||||
#: src/pages/UserLogin.tsx:157
|
||||
#: src/pages/UserLogin.tsx:163
|
||||
msgid "Send reset link"
|
||||
msgstr "Envoyer le lien de réinitialisation"
|
||||
|
||||
#: src/components/chat/PendingItem.tsx:104
|
||||
#: src/pages/UserLogin.tsx:156
|
||||
#: src/pages/UserLogin.tsx:162
|
||||
msgid "Sending…"
|
||||
msgstr "Envoi…"
|
||||
|
||||
@@ -1603,8 +1712,8 @@ msgid "email.settings"
|
||||
msgstr "Paramètres"
|
||||
|
||||
#: src/components/layout/UserMenu.tsx:104
|
||||
#: src/pages/Settings.tsx:72
|
||||
#: src/pages/Settings.tsx:84
|
||||
#: src/pages/Settings.tsx:75
|
||||
#: src/pages/Settings.tsx:88
|
||||
msgid "Settings"
|
||||
msgstr "Paramètres"
|
||||
|
||||
@@ -1612,6 +1721,19 @@ msgstr "Paramètres"
|
||||
msgid "Several people are typing…"
|
||||
msgstr "Plusieurs personnes écrivent…"
|
||||
|
||||
#: src/pages/Authorize.tsx:37
|
||||
msgid "Sign in elsewhere"
|
||||
msgstr "Se connecter ailleurs"
|
||||
|
||||
#: src/pages/Authorize.tsx:135
|
||||
msgid "Sign in to {name}?"
|
||||
msgstr "Se connecter à {name} ?"
|
||||
|
||||
#: src/pages/Authorize.tsx:154
|
||||
#: src/pages/FederationCallback.tsx:73
|
||||
msgid "Signing you in…"
|
||||
msgstr "Connexion…"
|
||||
|
||||
#: src/components/profile/ProfileOwnActions.tsx:102
|
||||
msgid "Single use, valid for 7 days."
|
||||
msgstr "Usage unique, valable 7 jours."
|
||||
@@ -1636,7 +1758,7 @@ msgstr "Quelqu'un a demandé à réinitialiser le mot de passe de votre compte {
|
||||
msgid "Something went wrong"
|
||||
msgstr "Une erreur est survenue"
|
||||
|
||||
#: src/pages/Settings.tsx:132
|
||||
#: src/pages/Settings.tsx:165
|
||||
msgid "Sounds"
|
||||
msgstr "Sons"
|
||||
|
||||
@@ -1644,7 +1766,7 @@ msgstr "Sons"
|
||||
msgid "Start fresh"
|
||||
msgstr "Repartir de zéro"
|
||||
|
||||
#: src/pages/Settings.tsx:103
|
||||
#: src/pages/Settings.tsx:136
|
||||
msgid "Style"
|
||||
msgstr "Style"
|
||||
|
||||
@@ -1696,11 +1818,11 @@ msgstr "Le nouvel ordre n'a pas pu être enregistré. Réessayez."
|
||||
msgid "This comment couldn't be deleted. Try again."
|
||||
msgstr "Ce commentaire n'a pas pu être supprimé. Réessayez."
|
||||
|
||||
#: src/pages/UserRegister.tsx:118
|
||||
#: src/pages/UserRegister.tsx:120
|
||||
msgid "This invite link is missing, expired, or already used."
|
||||
msgstr "Ce lien d'invitation est manquant, expiré ou déjà utilisé."
|
||||
|
||||
#: src/pages/UserLogin.tsx:104
|
||||
#: src/pages/UserLogin.tsx:110
|
||||
msgid "This is a mirage."
|
||||
msgstr "C'est un mirage."
|
||||
|
||||
@@ -1716,7 +1838,11 @@ msgstr "Rien à voir, circulez."
|
||||
msgid "This reset link is missing or malformed."
|
||||
msgstr "Ce lien de réinitialisation est absent ou malformé."
|
||||
|
||||
#: src/pages/Settings.tsx:168
|
||||
#: src/pages/FederationCallback.tsx:38
|
||||
msgid "This sign-in link is incomplete."
|
||||
msgstr "Ce lien de connexion est incomplet."
|
||||
|
||||
#: src/pages/Settings.tsx:201
|
||||
msgid "This site doesn't send email, so no digest goes out."
|
||||
msgstr "Ce site n'envoie pas d'e-mails, aucun résumé ne part donc."
|
||||
|
||||
@@ -1763,6 +1889,14 @@ msgstr "Les plus votées de la semaine"
|
||||
msgid "Track {0}"
|
||||
msgstr "Piste {0}"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:155
|
||||
msgid "Trust"
|
||||
msgstr "Approuver"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:32
|
||||
msgid "Trusted"
|
||||
msgstr "Approuvée"
|
||||
|
||||
#: src/components/chat/ChatModal.tsx:668
|
||||
msgid "Try again"
|
||||
msgstr "Réessayer"
|
||||
@@ -1826,7 +1960,7 @@ msgstr "Désabonné"
|
||||
msgid "email.digest.upload"
|
||||
msgstr "fichier"
|
||||
|
||||
#: src/components/profile/ProfileHeader.tsx:72
|
||||
#: src/components/profile/ProfileHeader.tsx:79
|
||||
msgid "Upload failed"
|
||||
msgstr "Envoi échoué"
|
||||
|
||||
@@ -1883,9 +2017,9 @@ msgstr "Menu utilisateur"
|
||||
|
||||
#: src/components/profile/ProfileManageTab.tsx:61
|
||||
#: src/components/profile/UsernameField.tsx:51
|
||||
#: src/pages/Settings.tsx:87
|
||||
#: src/pages/UserLogin.tsx:75
|
||||
#: src/pages/UserRegister.tsx:137
|
||||
#: src/pages/Settings.tsx:91
|
||||
#: src/pages/UserLogin.tsx:79
|
||||
#: src/pages/UserRegister.tsx:139
|
||||
msgid "Username"
|
||||
msgstr "Nom d'utilisateur"
|
||||
|
||||
@@ -1894,6 +2028,10 @@ msgstr "Nom d'utilisateur"
|
||||
msgid "Users"
|
||||
msgstr "Utilisateurs"
|
||||
|
||||
#: src/components/federation/PeerManager.tsx:169
|
||||
msgid "Users of a trusted instance sign in here with their account there. Those of a blocked one can't. Users of any other instance need an invite."
|
||||
msgstr "Les utilisateurs d'une instance approuvée se connectent ici avec leur compte de là-bas. Ceux d'une instance bloquée ne le peuvent pas. Ceux de toute autre instance ont besoin d'une invitation."
|
||||
|
||||
#: src/components/profile/ProfileSection.tsx:43
|
||||
msgid "View all →"
|
||||
msgstr "Tout voir →"
|
||||
@@ -1952,6 +2090,10 @@ msgstr "Hier"
|
||||
msgid "You can post it anyway."
|
||||
msgstr "Vous pouvez la publier quand même."
|
||||
|
||||
#: src/components/federation/GrantList.tsx:93
|
||||
msgid "You haven't signed in to another gerbeur with this account yet."
|
||||
msgstr "Vous ne vous êtes encore connecté à aucun autre gerbeur avec ce compte."
|
||||
|
||||
#: src/pages/Unsubscribe.tsx:94
|
||||
msgid "You won't get the monthly recap any more. You can turn it back on in your settings."
|
||||
msgstr "Vous ne recevrez plus le récap mensuel. Vous pouvez le réactiver dans vos paramètres."
|
||||
@@ -1997,7 +2139,15 @@ msgstr "Vous avez tout lu, tout vu, tout bu."
|
||||
msgid "email.welcome.preheader"
|
||||
msgstr "Votre compte est prêt."
|
||||
|
||||
#: src/pages/UserLogin.tsx:152
|
||||
#: src/pages/Authorize.tsx:104
|
||||
msgid "Your account lives on {home}: sign in to other instances from there."
|
||||
msgstr "Votre compte est sur {home} : connectez-vous aux autres instances depuis là-bas."
|
||||
|
||||
#: src/pages/Settings.tsx:119
|
||||
msgid "Your account lives on {home}: your password, email address, avatar and username change there."
|
||||
msgstr "Votre compte est sur {home} : votre mot de passe, votre adresse e-mail, votre avatar et votre nom d'utilisateur se changent là-bas."
|
||||
|
||||
#: src/pages/UserLogin.tsx:158
|
||||
msgid "Your email address"
|
||||
msgstr "Votre adresse e-mail"
|
||||
|
||||
|
||||
267
shared/federation.ts
Normal file
267
shared/federation.ts
Normal file
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* Types what crosses the wire for federated sign-in, by which a user signs in
|
||||
* to one gerbeur instance with their account on another.
|
||||
*
|
||||
* The protocol is a subset of OpenID Connect, the authorization code flow
|
||||
* with PKCE, with tokens signed by each instance's Ed25519 key. Between the
|
||||
* instances, and between each instance and its client, travel:
|
||||
*
|
||||
* - each instance's metadata, served at `/.well-known/openid-configuration`;
|
||||
* - the pages' requests to start and finish a sign-in, here
|
||||
* (`/api/federation/*`) and on the home instance (`/api/oauth/*`);
|
||||
* - the claims of an identity, and the events a home instance sends the
|
||||
* instances its users signed in to;
|
||||
* - the instances an admin trusts or blocks, and the instances a user let
|
||||
* their account sign in to.
|
||||
*
|
||||
* In the code, the user's own instance is their home, playing the identity
|
||||
* provider; the instance they sign in to is the client.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/**
|
||||
* The version of the protocol below, which an instance announces in its
|
||||
* {@link InstanceMetadata}. An instance refuses one announcing another.
|
||||
*/
|
||||
export const FEDERATION_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Served by every instance at `/.well-known/openid-configuration`
|
||||
* (`routes/well-known.ts`), and read by another before it trusts it, starts a
|
||||
* sign-in on it or sends it an event. The names are OpenID Connect's, and the
|
||||
* `gerbeur_` fields are this protocol's own.
|
||||
*/
|
||||
export interface InstanceMetadata {
|
||||
/** The instance's public URL, an origin, which names it in every token. */
|
||||
issuer: string;
|
||||
/** Its `/authorize` page, where a user lets another instance sign them in. */
|
||||
authorization_endpoint: string;
|
||||
/** `POST /api/oauth/tokens`, which trades a code for an identity token. */
|
||||
token_endpoint: string;
|
||||
/** `GET /.well-known/jwks.json`, its public keys. */
|
||||
jwks_uri: string;
|
||||
response_types_supported: string[];
|
||||
grant_types_supported: string[];
|
||||
subject_types_supported: string[];
|
||||
id_token_signing_alg_values_supported: string[];
|
||||
code_challenge_methods_supported: string[];
|
||||
scopes_supported: string[];
|
||||
/** {@link FEDERATION_VERSION}. */
|
||||
gerbeur_federation: number;
|
||||
/** The site's name, which a consent page and the peer list show. */
|
||||
gerbeur_site_name: string;
|
||||
/**
|
||||
* Where its home instance sends a user back once they consent, as a client:
|
||||
* its `/federation/callback` page, on its frontend.
|
||||
*/
|
||||
gerbeur_redirect_uri: string;
|
||||
/** `POST /api/federation/events`, where it receives a home's events. */
|
||||
gerbeur_events_endpoint: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether `value` is an {@link InstanceMetadata} of this protocol's
|
||||
* version, as `remote/gerbeur-instance.ts` must before reading one.
|
||||
*/
|
||||
export function isInstanceMetadata(value: unknown): value is InstanceMetadata {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.issuer === "string" &&
|
||||
typeof v.authorization_endpoint === "string" &&
|
||||
typeof v.token_endpoint === "string" &&
|
||||
typeof v.jwks_uri === "string" &&
|
||||
v.gerbeur_federation === FEDERATION_VERSION &&
|
||||
typeof v.gerbeur_site_name === "string" &&
|
||||
typeof v.gerbeur_redirect_uri === "string" &&
|
||||
typeof v.gerbeur_events_endpoint === "string";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the origin of the instance `input` names, or null when it names
|
||||
* none. Someone may type a bare host (`music.example`, taken as https), a URL,
|
||||
* or a handle's host with its port (`localhost:8001`); a URL with a path names
|
||||
* no instance. Whether plain http is allowed is the server's call.
|
||||
*/
|
||||
export function parseInstance(input: string): string | null {
|
||||
const trimmed = input.trim().replace(/\/+$/, "");
|
||||
if (!trimmed) return null;
|
||||
try {
|
||||
const url = new URL(
|
||||
/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`,
|
||||
);
|
||||
if (url.protocol !== "https:" && url.protocol !== "http:") return null;
|
||||
if (url.pathname !== "/" || url.search || url.hash) return null;
|
||||
if (url.username || url.password) return null;
|
||||
return url.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the host of the instance at `issuer`, with its port if it has one:
|
||||
* the part after the `@` of its users' handles here (`alice@music.example`).
|
||||
*/
|
||||
export function instanceHost(issuer: string): string {
|
||||
return new URL(issuer).host;
|
||||
}
|
||||
|
||||
/**
|
||||
* What an admin decided about an instance. Users of a trusted one sign in
|
||||
* here directly; those of a blocked one never do, and its users already here
|
||||
* are signed out. An instance with neither is invite only: its users sign in
|
||||
* here with an invite.
|
||||
*/
|
||||
export type PeerStatus = "trusted" | "blocked";
|
||||
|
||||
/** Every {@link PeerStatus}. */
|
||||
export const PEER_STATUSES: readonly PeerStatus[] = ["trusted", "blocked"];
|
||||
|
||||
/** Checks whether `value` is a {@link PeerStatus}. */
|
||||
export function isPeerStatus(value: unknown): value is PeerStatus {
|
||||
return typeof value === "string" &&
|
||||
(PEER_STATUSES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/federation/peers`: the login page offers each trusted
|
||||
* one, and `/manage` lists them all.
|
||||
*/
|
||||
export interface FederationPeer {
|
||||
issuer: string;
|
||||
/** {@link instanceHost} of the issuer. */
|
||||
host: string;
|
||||
/** The site's name, as its metadata gave it when it was added. */
|
||||
name: string | null;
|
||||
status: PeerStatus;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** Sent to `PUT /api/federation/peers` by `/manage`. */
|
||||
export interface SetPeerRequest {
|
||||
/** As someone typed it, read with {@link parseInstance}. */
|
||||
instance: string;
|
||||
status: PeerStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sent to `POST /api/federation/logins` by the login page, or by the register
|
||||
* page with the invite it was opened with.
|
||||
*/
|
||||
export interface FederationLoginRequest {
|
||||
/** The user's home instance, read with {@link parseInstance}. */
|
||||
instance: string;
|
||||
inviteToken?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `POST /api/federation/logins`: the home instance's `/authorize`
|
||||
* page with the request in its query, which the client navigates to.
|
||||
*/
|
||||
export interface FederationLoginResponse {
|
||||
authorizeUrl: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sent to `POST /api/federation/sessions` by the `/federation/callback` page,
|
||||
* from the query the home instance sent the user back with. The answer is an
|
||||
* `AuthResponse`, as a sign-in's.
|
||||
*/
|
||||
export interface FederationSessionRequest {
|
||||
code: string;
|
||||
state: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/oauth/clients?client_id=` to the `/authorize` page,
|
||||
* which asks the user whether to sign in there.
|
||||
*/
|
||||
export interface OAuthClient {
|
||||
clientId: string;
|
||||
host: string;
|
||||
name: string;
|
||||
/**
|
||||
* Whether the user already let it sign them in, in which case the page
|
||||
* doesn't ask again.
|
||||
*/
|
||||
granted: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sent to `POST /api/oauth/codes` by the `/authorize` page once the user
|
||||
* consents, from the query the client instance sent them with.
|
||||
*/
|
||||
export interface AuthorizeRequest {
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
state: string;
|
||||
codeChallenge: string;
|
||||
codeChallengeMethod: string;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `POST /api/oauth/codes`: the client's callback page with the
|
||||
* code, where the `/authorize` page sends the user.
|
||||
*/
|
||||
export interface AuthorizeResponse {
|
||||
redirectTo: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returned by `GET /api/me/grants` to the settings page: an instance the
|
||||
* user let their account sign in to.
|
||||
*/
|
||||
export interface FederationGrant {
|
||||
clientId: string;
|
||||
host: string;
|
||||
name: string | null;
|
||||
grantedAt: Date;
|
||||
lastUsedAt: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carried by an identity token and by an `update` event: what a home instance
|
||||
* tells another of a user. The names are OpenID Connect's.
|
||||
*/
|
||||
export interface IdentityClaims {
|
||||
/** The user's name at home; the client calls them `<name>@<host>`. */
|
||||
preferred_username: string;
|
||||
email: string;
|
||||
/** Their avatar's URL at home, versioned; absent without one. */
|
||||
picture?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The payload of a signed event, which a home instance sends each instance a
|
||||
* user signed in to (`POST /api/federation/events`): `update` when their name,
|
||||
* email or avatar changed, `revoke` when their sessions there must end, after
|
||||
* a password change or when they withdraw the grant.
|
||||
*/
|
||||
export type FederationEvent =
|
||||
| { type: "update"; claims: IdentityClaims }
|
||||
| { type: "revoke" };
|
||||
|
||||
/**
|
||||
* Checks whether `value` is a {@link FederationEvent}, as the events endpoint
|
||||
* must once the signature is verified.
|
||||
*/
|
||||
export function isFederationEvent(value: unknown): value is FederationEvent {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
if (v.type === "revoke") return true;
|
||||
return v.type === "update" && isIdentityClaims(v.claims);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether `value` carries the {@link IdentityClaims}, as a client must
|
||||
* before creating or updating an account from them.
|
||||
*/
|
||||
export function isIdentityClaims(value: unknown): value is IdentityClaims {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.preferred_username === "string" &&
|
||||
typeof v.email === "string" &&
|
||||
(v.picture === undefined || typeof v.picture === "string");
|
||||
}
|
||||
@@ -5,8 +5,11 @@
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { HANDLE_SOURCE } from "./validation.ts";
|
||||
|
||||
/**
|
||||
* Matches an @username, with the name as its first group. The `@` must not
|
||||
* Matches an @handle, a local `@name` or a remote user's `@name@host`
|
||||
* (`HANDLE_SOURCE`), with the handle as its first group. The `@` must not
|
||||
* follow a word character, so an email address mentions no one. Nor may it
|
||||
* follow `[` or `(`, which leaves out a Markdown link's text or URL starting
|
||||
* with `@`, and also a plain `(@name)`. The editor's suggestions match its
|
||||
@@ -14,7 +17,10 @@
|
||||
* `Markdown` links mentions with a looser pattern of its own, on text already
|
||||
* parsed, where code and URLs are out of the way.
|
||||
*/
|
||||
export const MENTION_RE: RegExp = /(?<![[(\w])@(\w+)/g;
|
||||
export const MENTION_RE: RegExp = new RegExp(
|
||||
`(?<![[(\\w])@(${HANDLE_SOURCE})`,
|
||||
"g",
|
||||
);
|
||||
|
||||
/**
|
||||
* Returns the names `body` mentions, in lower case, each once. Code, fenced
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Builds and parses the site's page paths, by the one rule they all follow:
|
||||
* the path is a hierarchy, `@name` is a user, and any other word under the
|
||||
* the path is a hierarchy, `@name` is a user (`@name@host` one whose account
|
||||
* lives on another instance), and any other word under the
|
||||
* root is a category or an app page. Under a user each segment is a fixed tab
|
||||
* name, and under `dumps` or `playlists` a slug. A view of a page is one more
|
||||
* segment, and a default view is the bare path.
|
||||
@@ -16,6 +17,7 @@
|
||||
*/
|
||||
|
||||
import { DIGEST_CADENCES, type DigestCadence } from "./settings.ts";
|
||||
import { HANDLE_RE, splitHandle } from "./validation.ts";
|
||||
|
||||
/**
|
||||
* The feed tabs, in the tab bar's order. Each is a path segment: `/hot` for
|
||||
@@ -71,6 +73,15 @@ export interface OwnedItem {
|
||||
|
||||
const seg = encodeURIComponent;
|
||||
|
||||
/**
|
||||
* Writes a handle as a path segment. A host's characters are all safe in a
|
||||
* path, so `/@alice@music.example` keeps its `@` rather than `%40`.
|
||||
*/
|
||||
function handleSeg(handle: string): string {
|
||||
const { name, host } = splitHandle(handle);
|
||||
return host ? `${seg(name)}@${host}` : seg(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path of `username`'s profile, of one of its tabs, or of a view
|
||||
* of the `follow` tab. The default view, `users`, is the bare tab.
|
||||
@@ -80,7 +91,7 @@ export function userPath(
|
||||
tab?: ProfileTab,
|
||||
view?: FollowView,
|
||||
): string {
|
||||
const base = `/@${seg(username)}`;
|
||||
const base = `/@${handleSeg(username)}`;
|
||||
if (!tab) return base;
|
||||
return view && view !== FOLLOW_VIEWS[0]
|
||||
? `${base}/${tab}/${view}`
|
||||
@@ -145,7 +156,9 @@ export function parsePagePath(pathname: string): PagePath | null {
|
||||
return null;
|
||||
}
|
||||
const [handle, section, slug, ...more] = segments;
|
||||
if (!handle?.startsWith("@") || !/^\w+$/.test(handle.slice(1))) return null;
|
||||
if (!handle?.startsWith("@") || !HANDLE_RE.test(handle.slice(1))) {
|
||||
return null;
|
||||
}
|
||||
const username = handle.slice(1);
|
||||
|
||||
if ((section === "dumps" || section === "playlists") && slug) {
|
||||
|
||||
@@ -20,7 +20,8 @@ export type Permission =
|
||||
| "chat:moderate"
|
||||
| "chat:everyone"
|
||||
| "user:manage"
|
||||
| "category:manage";
|
||||
| "category:manage"
|
||||
| "federation:manage";
|
||||
|
||||
const ALL_PERMISSIONS: readonly Permission[] = [
|
||||
"dump:moderate",
|
||||
@@ -30,6 +31,7 @@ const ALL_PERMISSIONS: readonly Permission[] = [
|
||||
"chat:everyone",
|
||||
"user:manage",
|
||||
"category:manage",
|
||||
"federation:manage",
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
49
shared/test/federation.test.ts
Normal file
49
shared/test/federation.test.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { assertEquals } from "@std/assert";
|
||||
import {
|
||||
instanceHost,
|
||||
isFederationEvent,
|
||||
parseInstance,
|
||||
} from "../federation.ts";
|
||||
import { HANDLE_RE, splitHandle } from "../validation.ts";
|
||||
|
||||
Deno.test("parseInstance: a host or a URL names an instance's origin", () => {
|
||||
assertEquals(parseInstance("music.example"), "https://music.example");
|
||||
assertEquals(parseInstance(" Music.Example/ "), "https://music.example");
|
||||
assertEquals(
|
||||
parseInstance("http://localhost:8001"),
|
||||
"http://localhost:8001",
|
||||
);
|
||||
assertEquals(parseInstance("localhost:8001"), "https://localhost:8001");
|
||||
assertEquals(parseInstance("https://music.example/path"), null);
|
||||
assertEquals(parseInstance("ftp://music.example"), null);
|
||||
assertEquals(parseInstance("https://u:p@music.example"), null);
|
||||
assertEquals(parseInstance(""), null);
|
||||
assertEquals(instanceHost("http://localhost:8001"), "localhost:8001");
|
||||
});
|
||||
|
||||
Deno.test("handles: a name, and a host for a user from another instance", () => {
|
||||
assertEquals(splitHandle("bob"), { name: "bob" });
|
||||
assertEquals(splitHandle("alice@music.example"), {
|
||||
name: "alice",
|
||||
host: "music.example",
|
||||
});
|
||||
for (const ok of ["bob", "alice@music.example", "c_1@localhost:8001"]) {
|
||||
assertEquals(HANDLE_RE.test(ok), true, ok);
|
||||
}
|
||||
for (const bad of ["", "a@", "a@b.", "a b", "a@b@c", "a@-b"]) {
|
||||
assertEquals(HANDLE_RE.test(bad), false, bad);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("isFederationEvent: an update carries the claims", () => {
|
||||
assertEquals(isFederationEvent({ type: "revoke" }), true);
|
||||
assertEquals(
|
||||
isFederationEvent({
|
||||
type: "update",
|
||||
claims: { preferred_username: "a", email: "a@b.c" },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
assertEquals(isFederationEvent({ type: "update" }), false);
|
||||
assertEquals(isFederationEvent({ type: "delete" }), false);
|
||||
});
|
||||
21
shared/test/mention.test.ts
Normal file
21
shared/test/mention.test.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { mentionedUsernames, mentionsEveryone } from "../mention.ts";
|
||||
|
||||
Deno.test("mentionedUsernames: local names and remote handles, once each", () => {
|
||||
assertEquals(
|
||||
mentionedUsernames(
|
||||
"hi @Bob and @alice@Music.example. Also @carol@localhost:8001, @bob!",
|
||||
),
|
||||
["bob", "alice@music.example", "carol@localhost:8001"],
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("mentionedUsernames: emails, code, links and URLs mention no one", () => {
|
||||
assertEquals(
|
||||
mentionedUsernames(
|
||||
"mail bob@example.com, `@code`, [@x](https://a.example), https://a.example/@dan",
|
||||
),
|
||||
[],
|
||||
);
|
||||
assertEquals(mentionsEveryone("hey @everyone"), true);
|
||||
});
|
||||
@@ -75,3 +75,23 @@ Deno.test("parsePagePath: what a path under a user names", () => {
|
||||
assertEquals(parsePagePath(other), null, other);
|
||||
}
|
||||
});
|
||||
|
||||
Deno.test("handles: a user from another instance is /@name@host", () => {
|
||||
assertEquals(userPath("alice@music.example"), "/@alice@music.example");
|
||||
assertEquals(
|
||||
dumpPath({ ownerUsername: "alice@localhost:8001", slug: "x" }),
|
||||
"/@alice@localhost:8001/dumps/x",
|
||||
);
|
||||
assertEquals(parsePagePath("/@alice@music.example/playlists/mix"), {
|
||||
kind: "playlist",
|
||||
username: "alice@music.example",
|
||||
slug: "mix",
|
||||
});
|
||||
assertEquals(parsePagePath("/@alice%40music.example"), {
|
||||
kind: "user",
|
||||
username: "alice@music.example",
|
||||
rest: [],
|
||||
});
|
||||
assertEquals(parsePagePath("/@alice@"), null);
|
||||
assertEquals(parsePagePath("/@alice@-bad.example"), null);
|
||||
});
|
||||
|
||||
@@ -30,13 +30,51 @@ export const VALIDATION = {
|
||||
|
||||
/**
|
||||
* Matches a valid username, made of letters, digits and underscores within the
|
||||
* `VALIDATION` limits. Sign-up checks it on both sides. It uses the same `\w`
|
||||
* that a mention's pattern reads a name with.
|
||||
* `VALIDATION` limits. Sign-up and renaming check it on both sides. It uses the
|
||||
* same `\w` that a handle's pattern ({@link HANDLE_SOURCE}) reads a name with;
|
||||
* only a user from another instance has the `@host` part.
|
||||
*/
|
||||
export const USERNAME_RE: RegExp = new RegExp(
|
||||
`^[a-zA-Z0-9_]{${VALIDATION.USERNAME_MIN},${VALIDATION.USERNAME_MAX}}$`,
|
||||
);
|
||||
|
||||
/**
|
||||
* The pattern of an instance's host as a handle writes it: DNS labels, and a
|
||||
* port for instances on one machine (`localhost:8001`). It ends on a letter or
|
||||
* a digit, so the period that ends a sentence after a mention isn't taken in.
|
||||
* {@link HANDLE_SOURCE} builds on it.
|
||||
*/
|
||||
export const HOST_SOURCE: string =
|
||||
"[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*(?::\\d{1,5})?";
|
||||
|
||||
/**
|
||||
* The pattern of a handle, the name a user goes by on this instance: a local
|
||||
* user's username, or `name@host` for a user whose account lives on another
|
||||
* gerbeur (`federation-service.ts` stores it so in `users.username`). Paths,
|
||||
* mentions and the profile links all read names by it, through
|
||||
* {@link HANDLE_RE}, `MENTION_RE` (shared/mention.ts) and `parsePagePath`
|
||||
* (shared/paths.ts).
|
||||
*/
|
||||
export const HANDLE_SOURCE: string = `\\w+(?:@${HOST_SOURCE})?`;
|
||||
|
||||
/** Matches a whole handle ({@link HANDLE_SOURCE}). */
|
||||
export const HANDLE_RE: RegExp = new RegExp(`^${HANDLE_SOURCE}$`);
|
||||
|
||||
/** Matches a whole host ({@link HOST_SOURCE}). */
|
||||
export const HOST_RE: RegExp = new RegExp(`^${HOST_SOURCE}$`);
|
||||
|
||||
/**
|
||||
* Returns the name and, for a user from another instance, the host of
|
||||
* `handle`. `splitHandle("alice@music.example")` is
|
||||
* `{ name: "alice", host: "music.example" }`; a local name has no host.
|
||||
*/
|
||||
export function splitHandle(handle: string): { name: string; host?: string } {
|
||||
const at = handle.indexOf("@");
|
||||
return at < 0
|
||||
? { name: handle }
|
||||
: { name: handle.slice(0, at), host: handle.slice(at + 1) };
|
||||
}
|
||||
|
||||
/**
|
||||
* How often a dump's or a playlist's slug may change, counted from the aliases
|
||||
* the changes left: 3 times a day. Moderators are exempt. slug-service refuses
|
||||
|
||||
100
src/App.css
100
src/App.css
@@ -2297,6 +2297,19 @@ body.has-player .chat-fab {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* The `@host` of a user whose account lives on another instance. */
|
||||
.profile-username-host {
|
||||
font-weight: 400;
|
||||
color: var(--color-text-muted);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.profile-home {
|
||||
font-size: var(--text-xs);
|
||||
color: var(--color-text-muted);
|
||||
margin: 0 0 0.4rem;
|
||||
}
|
||||
|
||||
/* Role badge — elevated roles only (see RoleChip) */
|
||||
.profile-role-chip {
|
||||
padding: 0.1rem 0.55rem;
|
||||
@@ -3317,6 +3330,53 @@ body.has-player .chat-fab {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
/* Signing in with an account on another instance, under the login and
|
||||
register forms, and the consent page that instance shows. */
|
||||
.auth-federated {
|
||||
border-top: 1px solid var(--color-border-subtle);
|
||||
padding-top: 1rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-federated-title {
|
||||
margin: 0;
|
||||
font-size: var(--text-sm);
|
||||
text-align: center;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.auth-federated-peer {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.25rem 0.5rem;
|
||||
}
|
||||
|
||||
.auth-federated-host {
|
||||
font-size: var(--text-xs);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.auth-consent {
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.auth-consent-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.auth-consent-actions > * {
|
||||
flex: 1 1 auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ── Form pages (DumpCreate / DumpEdit) ── */
|
||||
@keyframes page-enter {
|
||||
from {
|
||||
@@ -7271,6 +7331,46 @@ body.has-player .chat-fab {
|
||||
margin: 0.75rem 0 0;
|
||||
}
|
||||
|
||||
/* ── Instances (/manage, /settings) ─────────────────────────────────────── */
|
||||
|
||||
.peer-manager {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.peer-name {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.peer-host {
|
||||
font-weight: 400;
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
|
||||
.peer-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.peer-add {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.peer-add-actions {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.peer-add-actions > * {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ── Categories ─────────────────────────────────────────────────────────── */
|
||||
|
||||
.visually-hidden {
|
||||
|
||||
21
src/App.tsx
21
src/App.tsx
@@ -9,12 +9,16 @@
|
||||
* the create form on a shared link.
|
||||
* - `/search` and `/search/:searchTab` are the search results (`Search`).
|
||||
* - `/register` and `/login` sign up and sign in (`UserRegister`,
|
||||
* `UserLogin`), signed out only.
|
||||
* `UserLogin`), signed out only, `/login?next=` coming back to a page.
|
||||
* - `/authorize` lets another gerbeur instance sign the user in with their
|
||||
* account here (`Authorize`), and `/federation/callback` finishes a sign-in
|
||||
* here with an account on another (`FederationCallback`).
|
||||
* - `/reset-password` sets a new password from an emailed link
|
||||
* (`ResetPassword`), and `/unsubscribe` turns off a digest from its emailed
|
||||
* link (`Unsubscribe`).
|
||||
* - `/notifications` (`Notifications`) and `/settings` (`Settings`), signed in
|
||||
* only, and `/manage`, the site's tools, for `category:manage` (`Manage`).
|
||||
* only, and `/manage`, the site's tools, for `category:manage` or
|
||||
* `federation:manage` (`Manage`).
|
||||
* - `/community` and `/community/monthly`, the site's week and month
|
||||
* (`Community`), signed in only.
|
||||
* - `/@:username/*` is a user's (`UserRoutes`): their profile and its tabs,
|
||||
@@ -108,6 +112,14 @@ const ResetPassword = lazy(() =>
|
||||
const Unsubscribe = lazy(() =>
|
||||
import("./pages/Unsubscribe.tsx").then((m) => ({ default: m.Unsubscribe }))
|
||||
);
|
||||
const Authorize = lazy(() =>
|
||||
import("./pages/Authorize.tsx").then((m) => ({ default: m.Authorize }))
|
||||
);
|
||||
const FederationCallback = lazy(() =>
|
||||
import("./pages/FederationCallback.tsx").then((m) => ({
|
||||
default: m.FederationCallback,
|
||||
}))
|
||||
);
|
||||
const NotFound = lazy(() =>
|
||||
import("./pages/NotFound.tsx").then((m) => ({ default: m.NotFound }))
|
||||
);
|
||||
@@ -202,6 +214,11 @@ function AppRoutes() {
|
||||
</RestrictedGuest>
|
||||
}
|
||||
/>
|
||||
<Route path="/authorize" element={<Authorize />} />
|
||||
<Route
|
||||
path="/federation/callback"
|
||||
element={<FederationCallback />}
|
||||
/>
|
||||
<Route path="/reset-password" element={<ResetPassword />} />
|
||||
<Route path="/unsubscribe" element={<Unsubscribe />} />
|
||||
<Route
|
||||
|
||||
@@ -12,6 +12,7 @@ import remarkGfm from "remark-gfm";
|
||||
import { useAuth } from "../../hooks/auth/useAuth.ts";
|
||||
import { userPath } from "../../../shared/paths.ts";
|
||||
import { EVERYONE } from "../../../shared/mention.ts";
|
||||
import { HANDLE_SOURCE } from "../../../shared/validation.ts";
|
||||
import { isAttachmentUrl } from "../../../shared/attachment.ts";
|
||||
|
||||
/** Passed to {@link Markdown} by any component that shows a user's text. */
|
||||
@@ -36,7 +37,7 @@ export interface MarkdownProps {
|
||||
* parsed text: link syntax is already parsed away here, so only a preceding
|
||||
* word character (an email address) rules a mention out.
|
||||
*/
|
||||
const MENTION_RE = /(?<!\w)@(\w+)/g;
|
||||
const MENTION_RE = new RegExp(`(?<!\\w)@(${HANDLE_SOURCE})`, "g");
|
||||
|
||||
/** The part of a Markdown syntax tree node that the plugins below read. */
|
||||
interface MdNode {
|
||||
@@ -49,9 +50,37 @@ interface MdNode {
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a bare `@username` into a link to that user's profile. It works on the
|
||||
* parsed tree rather than the source, so code keeps its `@`s and a URL that
|
||||
* contains one (`https://mastodon.social/@bob`) isn't split in two.
|
||||
* Returns `children` with each `@name@host` that GFM took for an email address
|
||||
* (text ending in `@`, then a `mailto:` link of `name@host`) back in one text
|
||||
* node, which {@link remarkMentions} then reads as a remote user's handle.
|
||||
*/
|
||||
function unlinkHandles(children: MdNode[]): MdNode[] {
|
||||
const out: MdNode[] = [];
|
||||
for (const child of children) {
|
||||
const prev = out.at(-1);
|
||||
const only = child.children?.length === 1 ? child.children[0] : undefined;
|
||||
const address = child.type === "link" && only?.type === "text"
|
||||
? only.value
|
||||
: undefined;
|
||||
if (
|
||||
prev?.type === "text" &&
|
||||
((address && child.url === `mailto:${address}` &&
|
||||
/(?<!\w)@$/.test(prev.value ?? "")) ||
|
||||
child.type === "text")
|
||||
) {
|
||||
prev.value = `${prev.value}${address ?? child.value}`;
|
||||
continue;
|
||||
}
|
||||
out.push(child);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a bare `@username`, or a remote user's `@name@host`, into a link to
|
||||
* that user's profile. It works on the parsed tree rather than the source, so
|
||||
* code keeps its `@`s and a URL that contains one
|
||||
* (`https://mastodon.social/@bob`) isn't split in two.
|
||||
* `@everyone` names no profile: it is left as text, or with `everyone` set,
|
||||
* becomes a `span.md-everyone`.
|
||||
*/
|
||||
@@ -60,7 +89,7 @@ function remarkMentions({ everyone = false }: { everyone?: boolean } = {}) {
|
||||
if (!node.children) return;
|
||||
// Link text is already a link, whatever it says.
|
||||
if (node.type === "link" || node.type === "linkReference") return;
|
||||
node.children = node.children.flatMap((child) => {
|
||||
node.children = unlinkHandles(node.children).flatMap((child) => {
|
||||
if (child.type !== "text" || !child.value?.includes("@")) {
|
||||
walk(child);
|
||||
return [child];
|
||||
|
||||
119
src/components/federation/FederatedSignIn.tsx
Normal file
119
src/components/federation/FederatedSignIn.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* Renders the way in for users of another gerbeur instance, under the login
|
||||
* form and, with the invite, under the register form.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { FormProvider } from "react-hook-form";
|
||||
|
||||
import { API_URL } from "../../config/api.ts";
|
||||
import type { Wire } from "../../../shared/api.ts";
|
||||
import type {
|
||||
FederationLoginRequest,
|
||||
FederationLoginResponse,
|
||||
FederationPeer,
|
||||
} from "../../../shared/federation.ts";
|
||||
import { dataOr, expectOk } from "../../utils/shared/api.ts";
|
||||
import { deserializeFederationPeer } from "../../utils/shared/deserialize.ts";
|
||||
import { useApiForm } from "../../hooks/form/useApiForm.ts";
|
||||
import { FormError } from "../form/FormError.tsx";
|
||||
import { SubmitButton } from "../form/SubmitButton.tsx";
|
||||
import { TextField } from "../form/TextField.tsx";
|
||||
|
||||
/** Passed to {@link FederatedSignIn} by `UserLogin` and `UserRegister`. */
|
||||
export interface FederatedSignInProps {
|
||||
/**
|
||||
* The invite the register page was opened with, which lets a user of any
|
||||
* instance join; the login page has none, and offers the trusted instances.
|
||||
*/
|
||||
inviteToken?: string;
|
||||
}
|
||||
|
||||
interface Values {
|
||||
instance: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a button per trusted instance (`GET /api/federation/peers`) and a
|
||||
* field for any other's address. Either starts the sign-in
|
||||
* (`POST /api/federation/logins`) and leaves for that instance's `/authorize`
|
||||
* page, which sends the user back to `/federation/callback`.
|
||||
*/
|
||||
export function FederatedSignIn(
|
||||
{ inviteToken }: FederatedSignInProps,
|
||||
): React.JSX.Element {
|
||||
const [peers, setPeers] = useState<FederationPeer[]>([]);
|
||||
const form = useApiForm<Values>({ defaultValues: { instance: "" } });
|
||||
|
||||
useEffect(() => {
|
||||
if (inviteToken) return;
|
||||
const controller = new AbortController();
|
||||
fetch(`${API_URL}/api/federation/peers`, { signal: controller.signal })
|
||||
.then((res) => dataOr<Wire<FederationPeer>[]>(res, []))
|
||||
.then((list) => setPeers(list.map(deserializeFederationPeer)))
|
||||
.catch(() => {});
|
||||
return () => controller.abort();
|
||||
}, [inviteToken]);
|
||||
|
||||
const onSubmit = form.submit(async ({ instance }) => {
|
||||
const { authorizeUrl } = await expectOk<FederationLoginResponse>(
|
||||
await fetch(`${API_URL}/api/federation/logins`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(
|
||||
{
|
||||
instance: instance.trim(),
|
||||
inviteToken,
|
||||
} satisfies FederationLoginRequest,
|
||||
),
|
||||
}),
|
||||
);
|
||||
globalThis.location.assign(authorizeUrl);
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="auth-federated">
|
||||
<p className="auth-federated-title">
|
||||
{inviteToken
|
||||
? <Trans>Or join with your account on another gerbeur</Trans>
|
||||
: <Trans>Or log in with your account on another gerbeur</Trans>}
|
||||
</p>
|
||||
<FormProvider {...form}>
|
||||
{peers.map((peer) => (
|
||||
<button
|
||||
key={peer.issuer}
|
||||
type="button"
|
||||
className="btn-secondary auth-federated-peer"
|
||||
disabled={form.formState.isSubmitting}
|
||||
onClick={() => {
|
||||
form.setValue("instance", peer.issuer);
|
||||
onSubmit();
|
||||
}}
|
||||
>
|
||||
<Trans>Log in with {peer.name ?? peer.host}</Trans>
|
||||
<span className="auth-federated-host">{peer.host}</span>
|
||||
</button>
|
||||
))}
|
||||
<form onSubmit={onSubmit} className="form">
|
||||
<FormError title={t`Couldn't reach that instance`} />
|
||||
<TextField<Values>
|
||||
name="instance"
|
||||
placeholder={t`Its address, like music.example`}
|
||||
autoComplete="url"
|
||||
rules={{ required: true }}
|
||||
/>
|
||||
<SubmitButton
|
||||
className="btn-secondary"
|
||||
pendingLabel={<Trans>Connecting…</Trans>}
|
||||
>
|
||||
<Trans>Continue</Trans>
|
||||
</SubmitButton>
|
||||
</form>
|
||||
</FormProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
101
src/components/federation/GrantList.tsx
Normal file
101
src/components/federation/GrantList.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Renders the other gerbeur instances the signed-in user let their account
|
||||
* sign in to, on `/settings`.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
import { API_URL } from "../../config/api.ts";
|
||||
import type { Wire } from "../../../shared/api.ts";
|
||||
import type { FederationGrant } from "../../../shared/federation.ts";
|
||||
import { useAuth } from "../../hooks/auth/useAuth.ts";
|
||||
import { expectOk, friendlyFetchError } from "../../utils/shared/api.ts";
|
||||
import { deserializeFederationGrant } from "../../utils/shared/deserialize.ts";
|
||||
import { relativeTime } from "../../utils/shared/relativeTime.ts";
|
||||
import { ErrorCard } from "../shared/ErrorCard.tsx";
|
||||
import { SettingRow } from "../profile/SettingRow.tsx";
|
||||
|
||||
/**
|
||||
* Renders each instance (`GET /api/me/grants`), when it last signed the user
|
||||
* in, and a button that withdraws it (`DELETE /api/me/grants/:host`), which
|
||||
* signs them out there; signing in there again asks them again.
|
||||
*/
|
||||
export function GrantList(): React.JSX.Element {
|
||||
const { authFetch } = useAuth();
|
||||
const [grants, setGrants] = useState<FederationGrant[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const fetchGrants = useCallback(
|
||||
async () =>
|
||||
(await expectOk<Wire<FederationGrant>[]>(
|
||||
await authFetch(`${API_URL}/api/me/grants`),
|
||||
)).map(deserializeFederationGrant),
|
||||
[authFetch],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchGrants()
|
||||
.then(setGrants)
|
||||
.catch((err) => setError(friendlyFetchError(err)));
|
||||
}, [fetchGrants]);
|
||||
|
||||
const revoke = async (grant: FederationGrant) => {
|
||||
setError(null);
|
||||
try {
|
||||
await expectOk(
|
||||
await authFetch(
|
||||
`${API_URL}/api/me/grants/${encodeURIComponent(grant.host)}`,
|
||||
{ method: "DELETE" },
|
||||
),
|
||||
);
|
||||
setGrants(await fetchGrants());
|
||||
} catch (err) {
|
||||
setError(friendlyFetchError(err));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{grants && grants.length > 0 && (
|
||||
<div className="profile-appearance-grid">
|
||||
{grants.map((grant) => (
|
||||
<SettingRow
|
||||
key={grant.clientId}
|
||||
label={
|
||||
<span className="peer-name">
|
||||
{grant.name ?? grant.host}
|
||||
<span className="peer-host">{grant.host}</span>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<span className="peer-controls">
|
||||
<span className="form-hint">
|
||||
<Trans>last used {relativeTime(grant.lastUsedAt)}</Trans>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => revoke(grant)}
|
||||
>
|
||||
<Trans>Disconnect</Trans>
|
||||
</button>
|
||||
</span>
|
||||
</SettingRow>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{grants?.length === 0 && (
|
||||
<p className="form-hint">
|
||||
<Trans>
|
||||
You haven't signed in to another gerbeur with this account yet.
|
||||
</Trans>
|
||||
</p>
|
||||
)}
|
||||
{error && <ErrorCard title={t`Failed to save`} message={error} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
177
src/components/federation/PeerManager.tsx
Normal file
177
src/components/federation/PeerManager.tsx
Normal file
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* Renders the list of the other gerbeur instances an admin trusts or blocks,
|
||||
* on `/manage`, for those who hold `federation:manage`.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
import { FormProvider } from "react-hook-form";
|
||||
|
||||
import { API_URL } from "../../config/api.ts";
|
||||
import type { Wire } from "../../../shared/api.ts";
|
||||
import type {
|
||||
FederationPeer,
|
||||
PeerStatus,
|
||||
SetPeerRequest,
|
||||
} from "../../../shared/federation.ts";
|
||||
import { useAuth } from "../../hooks/auth/useAuth.ts";
|
||||
import { useApiForm } from "../../hooks/form/useApiForm.ts";
|
||||
import { expectOk, friendlyFetchError } from "../../utils/shared/api.ts";
|
||||
import { deserializeFederationPeer } from "../../utils/shared/deserialize.ts";
|
||||
import { FormError } from "../form/FormError.tsx";
|
||||
import { SubmitButton } from "../form/SubmitButton.tsx";
|
||||
import { TextField } from "../form/TextField.tsx";
|
||||
import { ErrorCard } from "../shared/ErrorCard.tsx";
|
||||
import { Segmented, type SegmentedOption } from "../shared/Segmented.tsx";
|
||||
import { SettingRow } from "../profile/SettingRow.tsx";
|
||||
|
||||
const STATUS_OPTIONS: SegmentedOption<PeerStatus>[] = [
|
||||
{ value: "trusted", label: <Trans>Trusted</Trans> },
|
||||
{ value: "blocked", label: <Trans>Blocked</Trans> },
|
||||
];
|
||||
|
||||
interface Values {
|
||||
instance: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders each listed instance with its status, which a click changes
|
||||
* (`PUT /api/federation/peers`), and a button that takes it off the lists
|
||||
* (`DELETE /api/federation/peers/:host`), then a field that adds one. The
|
||||
* server checks that it answers as a gerbeur, and the permission again.
|
||||
*/
|
||||
export function PeerManager(): React.JSX.Element {
|
||||
const { authFetch } = useAuth();
|
||||
const [peers, setPeers] = useState<FederationPeer[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const form = useApiForm<Values>({ defaultValues: { instance: "" } });
|
||||
|
||||
const fetchPeers = useCallback(
|
||||
async () =>
|
||||
(await expectOk<Wire<FederationPeer>[]>(
|
||||
await authFetch(`${API_URL}/api/federation/peers`),
|
||||
)).map(deserializeFederationPeer),
|
||||
[authFetch],
|
||||
);
|
||||
const load = async () => setPeers(await fetchPeers());
|
||||
|
||||
useEffect(() => {
|
||||
fetchPeers()
|
||||
.then(setPeers)
|
||||
.catch((err) => setError(friendlyFetchError(err)));
|
||||
}, [fetchPeers]);
|
||||
|
||||
const save = async (instance: string, status: PeerStatus) => {
|
||||
await expectOk<Wire<FederationPeer>>(
|
||||
await authFetch(`${API_URL}/api/federation/peers`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ instance, status } satisfies SetPeerRequest),
|
||||
}),
|
||||
);
|
||||
await load();
|
||||
};
|
||||
|
||||
/** Runs a change from a row, whose failure shows above the form. */
|
||||
const change = async (run: () => Promise<void>) => {
|
||||
setError(null);
|
||||
try {
|
||||
await run();
|
||||
} catch (err) {
|
||||
setError(friendlyFetchError(err));
|
||||
}
|
||||
};
|
||||
|
||||
const remove = (peer: FederationPeer) =>
|
||||
change(async () => {
|
||||
await expectOk(
|
||||
await authFetch(
|
||||
`${API_URL}/api/federation/peers/${encodeURIComponent(peer.host)}`,
|
||||
{ method: "DELETE" },
|
||||
),
|
||||
);
|
||||
await load();
|
||||
});
|
||||
|
||||
const add = (status: PeerStatus) =>
|
||||
form.submit(async ({ instance }) => {
|
||||
await save(instance.trim(), status);
|
||||
form.reset();
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="peer-manager">
|
||||
{peers === null && !error && (
|
||||
<p className="index-status">
|
||||
<Trans>Loading…</Trans>
|
||||
</p>
|
||||
)}
|
||||
{peers && peers.length > 0 && (
|
||||
<div className="profile-appearance-grid">
|
||||
{peers.map((peer) => (
|
||||
<SettingRow
|
||||
key={peer.issuer}
|
||||
label={
|
||||
<span className="peer-name">
|
||||
{peer.name ?? peer.host}
|
||||
<span className="peer-host">{peer.host}</span>
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<span className="peer-controls">
|
||||
<Segmented
|
||||
options={STATUS_OPTIONS}
|
||||
value={peer.status}
|
||||
onChange={(status) => change(() => save(peer.issuer, status))}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="btn--ghost peer-remove"
|
||||
onClick={() => remove(peer)}
|
||||
title={t`Remove ${peer.host}`}
|
||||
aria-label={t`Remove ${peer.host}`}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</span>
|
||||
</SettingRow>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{error && <ErrorCard title={t`Failed to save`} message={error} />}
|
||||
<FormProvider {...form}>
|
||||
<form className="form peer-add" onSubmit={add("trusted")}>
|
||||
<FormError title={t`Couldn't add that instance`} />
|
||||
<TextField<Values>
|
||||
name="instance"
|
||||
placeholder={t`An instance's address, like music.example`}
|
||||
autoComplete="url"
|
||||
rules={{ required: true }}
|
||||
/>
|
||||
<div className="peer-add-actions">
|
||||
<SubmitButton pendingLabel={<Trans>Checking…</Trans>}>
|
||||
<Trans>Trust</Trans>
|
||||
</SubmitButton>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-secondary"
|
||||
disabled={form.formState.isSubmitting}
|
||||
onClick={add("blocked")}
|
||||
>
|
||||
<Trans>Block</Trans>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</FormProvider>
|
||||
<p className="form-hint">
|
||||
<Trans>
|
||||
Users of a trusted instance sign in here with their account there.
|
||||
Those of a blocked one can't. Users of any other instance need an
|
||||
invite.
|
||||
</Trans>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -26,8 +26,8 @@ export interface UserMenuProps {
|
||||
/**
|
||||
* Renders the signed-in user's avatar, which opens a menu with links to their
|
||||
* profile, their playlists, `/community` and `/settings`, to `/manage` for
|
||||
* those who hold `category:manage`, and a Log out button. A click outside or
|
||||
* Escape closes it.
|
||||
* those who hold `category:manage` or `federation:manage`, and a Log out
|
||||
* button. A click outside or Escape closes it.
|
||||
*/
|
||||
export function UserMenu({ user }: UserMenuProps): React.JSX.Element {
|
||||
const { i18n } = useLingui();
|
||||
@@ -103,7 +103,8 @@ export function UserMenu({ user }: UserMenuProps): React.JSX.Element {
|
||||
>
|
||||
<Trans>Settings</Trans>
|
||||
</Link>
|
||||
{can(user, "category:manage") && (
|
||||
{(can(user, "category:manage") ||
|
||||
can(user, "federation:manage")) && (
|
||||
<Link
|
||||
to="/manage"
|
||||
className="user-menu-item"
|
||||
|
||||
@@ -23,6 +23,8 @@ import { EmailEditor } from "./EmailEditor.tsx";
|
||||
import { ProfileOwnActions } from "./ProfileOwnActions.tsx";
|
||||
import { RoleChip } from "./RoleSwitcher.tsx";
|
||||
import { userPath } from "../../../shared/paths.ts";
|
||||
import { splitHandle } from "../../../shared/validation.ts";
|
||||
import { homeUrl } from "../../utils/auth/home.ts";
|
||||
|
||||
/** Passed to {@link ProfileHeader} by `UserPublicProfile`, once loaded. */
|
||||
export interface ProfileHeaderProps {
|
||||
@@ -33,10 +35,12 @@ export interface ProfileHeaderProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the avatar, username, role and inviter. Visitors get a follow
|
||||
* button. On their own profile, users change their avatar
|
||||
* (`PUT /api/me/avatar`) and email, and invite someone; their settings, the
|
||||
* site's tools and logging out are in the header's avatar menu.
|
||||
* Renders the avatar, username, role and inviter, and for a user from another
|
||||
* instance, a link to their profile there. Visitors get a follow button. On
|
||||
* their own profile, users change their avatar (`PUT /api/me/avatar`) and
|
||||
* email, unless their account comes from another instance, and invite
|
||||
* someone; their settings, the site's tools and logging out are in the
|
||||
* header's avatar menu.
|
||||
*/
|
||||
export function ProfileHeader(
|
||||
{ user, isOwnProfile, onUserChange }: ProfileHeaderProps,
|
||||
@@ -47,6 +51,9 @@ export function ProfileHeader(
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [emailEditing, setEmailEditing] = useState(false);
|
||||
const infoRef = useHeightTransition<HTMLDivElement>(emailEditing);
|
||||
const { name, host } = splitHandle(user.username);
|
||||
// A user from another instance changes their avatar and email there.
|
||||
const editable = isOwnProfile && !host;
|
||||
|
||||
const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
@@ -91,7 +98,7 @@ export function ProfileHeader(
|
||||
size={128}
|
||||
version={user.updatedAt?.getTime()}
|
||||
/>
|
||||
{isOwnProfile && (
|
||||
{editable && (
|
||||
<label className="avatar-change-overlay" title={t`Change avatar`}>
|
||||
{uploading ? "…" : "✎"}
|
||||
<input
|
||||
@@ -107,7 +114,10 @@ export function ProfileHeader(
|
||||
</div>
|
||||
<div className="profile-info" ref={infoRef}>
|
||||
<div className="profile-username-row">
|
||||
<h1 className="profile-username">{user.username}</h1>
|
||||
<h1 className="profile-username">
|
||||
{name}
|
||||
{host && <span className="profile-username-host">@{host}</span>}
|
||||
</h1>
|
||||
<RoleChip role={user.role} />
|
||||
</div>
|
||||
{user.invitedByUsername
|
||||
@@ -122,12 +132,22 @@ export function ProfileHeader(
|
||||
</Link>
|
||||
</p>
|
||||
)
|
||||
: (
|
||||
// Without an inviter, a local user was here first; one from a
|
||||
// trusted instance just came in.
|
||||
: !host && (
|
||||
<p className="profile-invited-by profile-invited-by--founding">
|
||||
O.G.
|
||||
</p>
|
||||
)}
|
||||
{isOwnProfile && (
|
||||
{host && (
|
||||
<p className="profile-home">
|
||||
<Trans>
|
||||
Account on{" "}
|
||||
<a href={homeUrl(user.username) ?? undefined}>{host}</a>
|
||||
</Trans>
|
||||
</p>
|
||||
)}
|
||||
{editable && (
|
||||
emailEditing
|
||||
? (
|
||||
<EmailEditor
|
||||
|
||||
164
src/pages/Authorize.tsx
Normal file
164
src/pages/Authorize.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
/**
|
||||
* Renders the page where another gerbeur instance asks to sign the user in
|
||||
* with their account here, `/authorize`. That instance's login page sends
|
||||
* them, with its request in the query, and this page sends them back to it.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link, Navigate, useLocation, useSearchParams } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import type {
|
||||
AuthorizeRequest,
|
||||
AuthorizeResponse,
|
||||
OAuthClient,
|
||||
} from "../../shared/federation.ts";
|
||||
import { useAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { ErrorCard } from "../components/shared/ErrorCard.tsx";
|
||||
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
|
||||
import { homeHost } from "../utils/auth/home.ts";
|
||||
import { loginPath } from "../utils/auth/next.ts";
|
||||
|
||||
/**
|
||||
* Renders `/authorize?client_id=&redirect_uri=&state=&code_challenge=&nonce=`.
|
||||
* A signed-out visitor signs in first and comes back. The page names the
|
||||
* instance asking (`GET /api/oauth/clients`) and what it will receive; once
|
||||
* the user continues, or at once if they already did before, it gets a code
|
||||
* (`POST /api/oauth/codes`) and goes back to the instance with it. An account
|
||||
* that itself comes from another instance can't be used from here.
|
||||
*/
|
||||
export function Authorize(): React.JSX.Element {
|
||||
useDocumentTitle(t`Sign in elsewhere`);
|
||||
const { user, authFetch } = useAuth();
|
||||
const location = useLocation();
|
||||
const [params] = useSearchParams();
|
||||
const [client, setClient] = useState<OAuthClient | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [leaving, setLeaving] = useState(false);
|
||||
const clientId = params.get("client_id") ?? "";
|
||||
const home = user ? homeHost(user.username) : undefined;
|
||||
|
||||
const approve = useCallback(async () => {
|
||||
setError(null);
|
||||
setLeaving(true);
|
||||
try {
|
||||
const request: AuthorizeRequest = {
|
||||
clientId,
|
||||
redirectUri: params.get("redirect_uri") ?? "",
|
||||
state: params.get("state") ?? "",
|
||||
codeChallenge: params.get("code_challenge") ?? "",
|
||||
codeChallengeMethod: params.get("code_challenge_method") ?? "",
|
||||
nonce: params.get("nonce") ?? "",
|
||||
};
|
||||
const { redirectTo } = await expectOk<AuthorizeResponse>(
|
||||
await authFetch(`${API_URL}/api/oauth/codes`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(request),
|
||||
}),
|
||||
);
|
||||
globalThis.location.assign(redirectTo);
|
||||
} catch (err) {
|
||||
setError(friendlyFetchError(err));
|
||||
setLeaving(false);
|
||||
}
|
||||
}, [authFetch, clientId, params]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || home) return;
|
||||
let cancelled = false;
|
||||
authFetch(
|
||||
`${API_URL}/api/oauth/clients?client_id=${encodeURIComponent(clientId)}`,
|
||||
)
|
||||
.then((res) => expectOk<OAuthClient>(res))
|
||||
.then((found) => {
|
||||
if (cancelled) return;
|
||||
setClient(found);
|
||||
if (found.granted) approve();
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!cancelled) setError(friendlyFetchError(err));
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// Asked once per instance; approving changes nothing to ask again.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [user?.id, home, clientId]);
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to={loginPath(location.pathname + location.search)} />;
|
||||
}
|
||||
|
||||
if (home) {
|
||||
return (
|
||||
<PageShell centered>
|
||||
<div className="page-error-wrap">
|
||||
<ErrorCard
|
||||
title={t`Not from here`}
|
||||
message={t`Your account lives on ${home}: sign in to other instances from there.`}
|
||||
/>
|
||||
</div>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
|
||||
if (!client) {
|
||||
return (
|
||||
<PageShell centered>
|
||||
{error
|
||||
? (
|
||||
<div className="page-error-wrap">
|
||||
<ErrorCard title={t`Can't sign in there`} message={error} />
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<p className="page-loading">
|
||||
<Trans>Loading…</Trans>
|
||||
</p>
|
||||
)}
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
|
||||
const { name, host } = client;
|
||||
const username = user.username;
|
||||
return (
|
||||
<PageShell centered>
|
||||
<div className="auth-card">
|
||||
<h1 className="auth-card-title">
|
||||
<Trans>Sign in to {name}?</Trans>
|
||||
</h1>
|
||||
<p className="auth-consent">
|
||||
<Trans>
|
||||
<strong>{name}</strong>{" "}
|
||||
({host}) asks to sign you in with your account here,{" "}
|
||||
<strong>@{username}</strong>. It will receive your username, your
|
||||
email address and your avatar.
|
||||
</Trans>
|
||||
</p>
|
||||
{error && <ErrorCard title={t`Can't sign in there`} message={error} />}
|
||||
<div className="auth-consent-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn-primary"
|
||||
onClick={approve}
|
||||
disabled={leaving}
|
||||
>
|
||||
{leaving
|
||||
? <Trans>Signing you in…</Trans>
|
||||
: <Trans>Continue as @{username}</Trans>}
|
||||
</button>
|
||||
<Link to="/" className="btn-secondary">
|
||||
<Trans>Cancel</Trans>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
78
src/pages/FederationCallback.tsx
Normal file
78
src/pages/FederationCallback.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Renders the page another gerbeur instance sends a user back to once they
|
||||
* let it sign them in here, `/federation/callback`.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Link, useNavigate, useSearchParams } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
import { API_URL } from "../config/api.ts";
|
||||
import type { Wire } from "../../shared/api.ts";
|
||||
import type { FederationSessionRequest } from "../../shared/federation.ts";
|
||||
import type { AuthResponse } from "../../shared/user.ts";
|
||||
import { useAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { useDocumentTitle } from "../hooks/shared/useDocumentTitle.ts";
|
||||
import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { ErrorCard } from "../components/shared/ErrorCard.tsx";
|
||||
import { expectOk, friendlyFetchError } from "../utils/shared/api.ts";
|
||||
import { deserializeAuthResponse } from "../utils/shared/deserialize.ts";
|
||||
|
||||
/**
|
||||
* Renders `/federation/callback?code=&state=`. It finishes the sign-in
|
||||
* (`POST /api/federation/sessions`), once: a code works only once, and a
|
||||
* second request would fail the sign-in. On success the user lands on `/`,
|
||||
* signed in.
|
||||
*/
|
||||
export function FederationCallback(): React.JSX.Element {
|
||||
useDocumentTitle(t`Log in`);
|
||||
const [params] = useSearchParams();
|
||||
const navigate = useNavigate();
|
||||
const { login } = useAuth();
|
||||
const code = params.get("code");
|
||||
const state = params.get("state");
|
||||
const [error, setError] = useState<string | null>(
|
||||
code && state ? null : t`This sign-in link is incomplete.`,
|
||||
);
|
||||
const sent = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (sent.current || !code || !state) return;
|
||||
sent.current = true;
|
||||
fetch(`${API_URL}/api/federation/sessions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code, state } satisfies FederationSessionRequest),
|
||||
})
|
||||
.then((res) => expectOk<Wire<AuthResponse>>(res))
|
||||
.then((data) => {
|
||||
login(deserializeAuthResponse(data));
|
||||
navigate("/", { replace: true });
|
||||
})
|
||||
.catch((err) => setError(friendlyFetchError(err)));
|
||||
}, [code, state, login, navigate]);
|
||||
|
||||
return (
|
||||
<PageShell centered>
|
||||
{error
|
||||
? (
|
||||
<div className="page-error-wrap">
|
||||
<ErrorCard title={t`Login failed`} message={error} />
|
||||
<p className="auth-card-footer">
|
||||
<Link to="/login">
|
||||
<Trans>Back to the login page</Trans>
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<p className="page-loading">
|
||||
<Trans>Signing you in…</Trans>
|
||||
</p>
|
||||
)}
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Renders the site's tools, `/manage`, for those who hold `category:manage`.
|
||||
* Another user's role and name are managed on their profile's "manage" tab.
|
||||
* Renders the site's tools, `/manage`, for those who hold `category:manage` or
|
||||
* `federation:manage`. Another user's role and name are managed on their
|
||||
* profile's "manage" tab.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
@@ -14,24 +15,37 @@ import { PageShell } from "../components/layout/PageShell.tsx";
|
||||
import { PageHeader } from "../components/layout/PageHeader.tsx";
|
||||
import { PageGroup } from "../components/layout/PageGroup.tsx";
|
||||
import { CategoryManager } from "../components/category/CategoryManager.tsx";
|
||||
import { PeerManager } from "../components/federation/PeerManager.tsx";
|
||||
import { NotFound } from "./NotFound.tsx";
|
||||
|
||||
/**
|
||||
* Renders the category manager, signed in only; without `category:manage`,
|
||||
* which the API checks again, the page isn't found.
|
||||
* Renders the category manager and the instances the site trusts or blocks,
|
||||
* each to those who hold its permission, which the API checks again; without
|
||||
* either, the page isn't found.
|
||||
*/
|
||||
export function Manage(): React.JSX.Element {
|
||||
useDocumentTitle(t`Manage`);
|
||||
const { user } = useRequiredAuth();
|
||||
if (!can(user, "category:manage")) return <NotFound />;
|
||||
const categories = can(user, "category:manage");
|
||||
const instances = can(user, "federation:manage");
|
||||
if (!categories && !instances) return <NotFound />;
|
||||
return (
|
||||
<PageShell narrow>
|
||||
<PageHeader icon="🛠️" title={<Trans>Manage</Trans>} />
|
||||
<PageGroup label={<Trans>Categories</Trans>}>
|
||||
<div className="page-card">
|
||||
<CategoryManager />
|
||||
</div>
|
||||
</PageGroup>
|
||||
{categories && (
|
||||
<PageGroup label={<Trans>Categories</Trans>}>
|
||||
<div className="page-card">
|
||||
<CategoryManager />
|
||||
</div>
|
||||
</PageGroup>
|
||||
)}
|
||||
{instances && (
|
||||
<PageGroup label={<Trans>Instances</Trans>}>
|
||||
<div className="page-card">
|
||||
<PeerManager />
|
||||
</div>
|
||||
</PageGroup>
|
||||
)}
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,9 +5,10 @@
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { Navigate } from "react-router";
|
||||
import { Navigate, useSearchParams } from "react-router";
|
||||
|
||||
import { useAuth } from "../hooks/auth/useAuth.ts";
|
||||
import { nextPath } from "../utils/auth/next.ts";
|
||||
|
||||
/** Passed to {@link RestrictedGuest} by `App`, around a route's page. */
|
||||
export interface RestrictedGuestProps {
|
||||
@@ -15,12 +16,16 @@ export interface RestrictedGuestProps {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders `children` when no one is signed in, and redirects to `/` otherwise.
|
||||
* Renders `children` when no one is signed in, and redirects otherwise: to the
|
||||
* page a `?next=` names (`nextPath`), or to `/`.
|
||||
*/
|
||||
export function RestrictedGuest(
|
||||
{ children }: RestrictedGuestProps,
|
||||
): React.JSX.Element {
|
||||
const { user } = useAuth();
|
||||
const [params] = useSearchParams();
|
||||
|
||||
return user ? <Navigate to="/" /> : <>{children}</>;
|
||||
return user
|
||||
? <Navigate to={nextPath(params) ?? "/"} replace />
|
||||
: <>{children}</>;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ import {
|
||||
} from "../components/shared/Segmented.tsx";
|
||||
import { ChangePasswordModal } from "../components/profile/ChangePasswordModal.tsx";
|
||||
import { SettingRow } from "../components/profile/SettingRow.tsx";
|
||||
import { GrantList } from "../components/federation/GrantList.tsx";
|
||||
import { homeHost, homeUrl } from "../utils/auth/home.ts";
|
||||
|
||||
// The styles' names are their own, in every language.
|
||||
const STYLE_OPTIONS: SegmentedOption<StyleName>[] = [
|
||||
@@ -63,8 +65,9 @@ const ON_OFF_OPTIONS: SegmentedOption<boolean>[] = [
|
||||
/**
|
||||
* Renders `/settings`, signed in only: the username, which only a moderator
|
||||
* changes (`ProfileManageTab`), the password change, which opens
|
||||
* {@link ChangePasswordModal}, and the settings, each saved as soon as it is
|
||||
* clicked. The style, color scheme and digests are saved to the account; the
|
||||
* {@link ChangePasswordModal}, the other instances the account signs in to
|
||||
* ({@link GrantList}), and the settings, each saved as soon as it is
|
||||
* clicked. An account from another instance changes its password there. The style, color scheme and digests are saved to the account; the
|
||||
* default feed tab and sounds, for now, to this browser.
|
||||
*/
|
||||
export function Settings(): React.JSX.Element {
|
||||
@@ -78,6 +81,7 @@ export function Settings(): React.JSX.Element {
|
||||
// Until the session has the settings, a click would save over unknown ones.
|
||||
const digestsDisabled = !EMAIL_ENABLED || !settings;
|
||||
const [changePasswordOpen, setChangePasswordOpen] = useState(false);
|
||||
const home = homeHost(user.username);
|
||||
|
||||
return (
|
||||
<PageShell narrow>
|
||||
@@ -87,17 +91,46 @@ export function Settings(): React.JSX.Element {
|
||||
<SettingRow label={<Trans>Username</Trans>}>
|
||||
<span className="profile-appearance-value">{user.username}</span>
|
||||
</SettingRow>
|
||||
<SettingRow label={<Trans>Password</Trans>}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => setChangePasswordOpen(true)}
|
||||
>
|
||||
<Trans>Change password…</Trans>
|
||||
</button>
|
||||
</SettingRow>
|
||||
{home
|
||||
? (
|
||||
<SettingRow label={<Trans>Password</Trans>}>
|
||||
<a
|
||||
className="btn btn--ghost"
|
||||
href={homeUrl(user.username, "/settings") ?? undefined}
|
||||
>
|
||||
<Trans>Change it on {home}</Trans>
|
||||
</a>
|
||||
</SettingRow>
|
||||
)
|
||||
: (
|
||||
<SettingRow label={<Trans>Password</Trans>}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--ghost"
|
||||
onClick={() => setChangePasswordOpen(true)}
|
||||
>
|
||||
<Trans>Change password…</Trans>
|
||||
</button>
|
||||
</SettingRow>
|
||||
)}
|
||||
</div>
|
||||
{home && (
|
||||
<p className="form-hint profile-appearance-note">
|
||||
<Trans>
|
||||
Your account lives on{" "}
|
||||
{home}: your password, email address, avatar and username change
|
||||
there.
|
||||
</Trans>
|
||||
</p>
|
||||
)}
|
||||
</PageGroup>
|
||||
{!home && (
|
||||
<PageGroup label={<Trans>Other instances</Trans>}>
|
||||
<div className="page-card">
|
||||
<GrantList />
|
||||
</div>
|
||||
</PageGroup>
|
||||
)}
|
||||
<PageGroup label={<Trans>Appearance</Trans>}>
|
||||
<div className="page-card profile-appearance-grid">
|
||||
<SettingRow label={<Trans>Style</Trans>}>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { useNavigate, useSearchParams } from "react-router";
|
||||
import { t } from "@lingui/core/macro";
|
||||
import { Trans } from "@lingui/react/macro";
|
||||
|
||||
@@ -23,6 +23,8 @@ import { FormProvider } from "react-hook-form";
|
||||
import { SubmitButton } from "../components/form/SubmitButton.tsx";
|
||||
import { TextField } from "../components/form/TextField.tsx";
|
||||
import { useApiForm } from "../hooks/form/useApiForm.ts";
|
||||
import { FederatedSignIn } from "../components/federation/FederatedSignIn.tsx";
|
||||
import { nextPath } from "../utils/auth/next.ts";
|
||||
|
||||
interface LoginValues {
|
||||
username: string;
|
||||
@@ -34,12 +36,14 @@ interface ResetValues {
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders `/login`, for the signed out. A sign-in lands on `/`, and "Forgot
|
||||
* password?" unfolds the reset request form below.
|
||||
* Renders `/login`, for the signed out. A sign-in lands on the page `?next=`
|
||||
* names, or `/`, and "Forgot password?" unfolds the reset request form below.
|
||||
* Users of another instance sign in through {@link FederatedSignIn}.
|
||||
*/
|
||||
export function UserLogin(): React.JSX.Element {
|
||||
useDocumentTitle(t`Log in`);
|
||||
const navigate = useNavigate();
|
||||
const [params] = useSearchParams();
|
||||
const { login } = useAuth();
|
||||
const [showReset, setShowReset] = useState(false);
|
||||
const cardRef = useHeightTransition<HTMLDivElement>(showReset);
|
||||
@@ -57,7 +61,7 @@ export function UserLogin(): React.JSX.Element {
|
||||
}),
|
||||
);
|
||||
login(deserializeAuthResponse(data));
|
||||
navigate("/");
|
||||
navigate(nextPath(params) ?? "/", { replace: true });
|
||||
});
|
||||
|
||||
return (
|
||||
@@ -100,6 +104,8 @@ export function UserLogin(): React.JSX.Element {
|
||||
|
||||
{showReset && <ResetRequestPanel />}
|
||||
|
||||
<FederatedSignIn />
|
||||
|
||||
<p className="auth-card-footer">
|
||||
<Trans>This is a mirage.</Trans>
|
||||
</p>
|
||||
|
||||
@@ -25,6 +25,7 @@ import { FormProvider } from "react-hook-form";
|
||||
import { SubmitButton } from "../components/form/SubmitButton.tsx";
|
||||
import { TextField } from "../components/form/TextField.tsx";
|
||||
import { useApiForm } from "../hooks/form/useApiForm.ts";
|
||||
import { FederatedSignIn } from "../components/federation/FederatedSignIn.tsx";
|
||||
|
||||
type TokenState =
|
||||
| { status: "checking" }
|
||||
@@ -39,7 +40,8 @@ interface Values {
|
||||
|
||||
/**
|
||||
* Renders `/register?token=`, for the signed out. It checks the invite before
|
||||
* showing the form, and signs the new user in on success.
|
||||
* showing the form, and signs the new user in on success. A user of another
|
||||
* instance joins with that account instead, through {@link FederatedSignIn}.
|
||||
*/
|
||||
export function UserRegister(): React.JSX.Element {
|
||||
useDocumentTitle(t`Register`);
|
||||
@@ -171,6 +173,8 @@ export function UserRegister(): React.JSX.Element {
|
||||
</form>
|
||||
</FormProvider>
|
||||
|
||||
<FederatedSignIn inviteToken={token} />
|
||||
|
||||
<p className="auth-card-footer">
|
||||
<Trans>
|
||||
Already have an account? <Link to="/login">Log in</Link>
|
||||
|
||||
@@ -33,6 +33,17 @@ describe("Markdown", () => {
|
||||
expect(currentPath()).toBe("/@ann");
|
||||
});
|
||||
|
||||
test("a remote user's @name@host links to their profile here", () => {
|
||||
md("hi @alice@music.example. and @bob@localhost:8001!");
|
||||
expect(
|
||||
screen.getByRole("link", { name: "@alice@music.example" }),
|
||||
).toHaveAttribute("href", "/@alice@music.example");
|
||||
expect(
|
||||
screen.getByRole("link", { name: "@bob@localhost:8001" }),
|
||||
).toHaveAttribute("href", "/@bob@localhost:8001");
|
||||
expect(document.querySelector('a[href^="mailto:"]')).toBeNull();
|
||||
});
|
||||
|
||||
test("@everyone links nowhere, and shows as a mention only when flagged", () => {
|
||||
md("hi @everyone");
|
||||
expect(screen.queryByRole("link")).toBeNull();
|
||||
|
||||
109
src/test/pages/Authorize.test.tsx
Normal file
109
src/test/pages/Authorize.test.tsx
Normal file
@@ -0,0 +1,109 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { Route } from "react-router";
|
||||
import { Authorize } from "../../pages/Authorize.tsx";
|
||||
import { calls, fail, route } from "../fetch.ts";
|
||||
import { makeSession } from "../fixtures.ts";
|
||||
import { currentPath, renderApp } from "../render.tsx";
|
||||
|
||||
const QUERY =
|
||||
"?response_type=code&client_id=https%3A%2F%2Fmusic.example&redirect_uri=https%3A%2F%2Fmusic.example%2Ffederation%2Fcallback&state=s1&code_challenge=c1&code_challenge_method=S256&nonce=n1";
|
||||
|
||||
const ann = makeSession({ id: "ann", username: "ann" });
|
||||
|
||||
describe("Authorize", () => {
|
||||
const assign = vi.fn();
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("location", { ...globalThis.location, assign });
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
assign.mockReset();
|
||||
});
|
||||
|
||||
function open(session = ann) {
|
||||
const user = userEvent.setup();
|
||||
renderApp(<Authorize />, {
|
||||
route: `/authorize${QUERY}`,
|
||||
path: "/authorize",
|
||||
session,
|
||||
extraRoutes: <Route path="/login" element={<p>login page</p>} />,
|
||||
});
|
||||
return user;
|
||||
}
|
||||
|
||||
test("asks before signing in, then goes back with a code", async () => {
|
||||
route("GET /api/oauth/clients", () => ({
|
||||
clientId: "https://music.example",
|
||||
host: "music.example",
|
||||
name: "Music",
|
||||
granted: false,
|
||||
}));
|
||||
route("POST /api/oauth/codes", () => ({
|
||||
redirectTo: "https://music.example/federation/callback?code=x&state=s1",
|
||||
}));
|
||||
const user = open();
|
||||
expect(await screen.findByText("Sign in to Music?")).toBeInTheDocument();
|
||||
expect(calls("GET /api/oauth/clients")[0].url.searchParams.get("client_id"))
|
||||
.toBe("https://music.example");
|
||||
expect(calls("POST /api/oauth/codes")).toHaveLength(0);
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Continue as @ann" }));
|
||||
await waitFor(() =>
|
||||
expect(assign).toHaveBeenCalledWith(
|
||||
"https://music.example/federation/callback?code=x&state=s1",
|
||||
)
|
||||
);
|
||||
expect(calls("POST /api/oauth/codes")[0].body).toEqual({
|
||||
clientId: "https://music.example",
|
||||
redirectUri: "https://music.example/federation/callback",
|
||||
state: "s1",
|
||||
codeChallenge: "c1",
|
||||
codeChallengeMethod: "S256",
|
||||
nonce: "n1",
|
||||
});
|
||||
});
|
||||
|
||||
test("goes straight back once the user already agreed", async () => {
|
||||
route("GET /api/oauth/clients", () => ({
|
||||
clientId: "https://music.example",
|
||||
host: "music.example",
|
||||
name: "Music",
|
||||
granted: true,
|
||||
}));
|
||||
route("POST /api/oauth/codes", () => ({ redirectTo: "https://x/cb" }));
|
||||
open();
|
||||
await waitFor(() => expect(assign).toHaveBeenCalledWith("https://x/cb"));
|
||||
});
|
||||
|
||||
test("a signed-out visitor logs in first and comes back", async () => {
|
||||
renderApp(<Authorize />, {
|
||||
route: `/authorize${QUERY}`,
|
||||
path: "/authorize",
|
||||
extraRoutes: <Route path="/login" element={<p>login page</p>} />,
|
||||
});
|
||||
await screen.findByText("login page");
|
||||
expect(currentPath()).toBe(
|
||||
`/login?next=${encodeURIComponent(`/authorize${QUERY}`)}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("an account from another instance is turned away", async () => {
|
||||
open(makeSession({ id: "bob", username: "bob@home.example" }));
|
||||
expect(
|
||||
await screen.findByText(/Your account lives on home\.example/),
|
||||
).toBeInTheDocument();
|
||||
expect(calls("GET /api/oauth/clients")).toHaveLength(0);
|
||||
});
|
||||
|
||||
test("an instance the server refuses is reported", async () => {
|
||||
route(
|
||||
"GET /api/oauth/clients",
|
||||
() => fail("This instance is blocked", 403),
|
||||
);
|
||||
open();
|
||||
expect(await screen.findByText("This instance is blocked"))
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
51
src/test/pages/FederationCallback.test.tsx
Normal file
51
src/test/pages/FederationCallback.test.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { Route } from "react-router";
|
||||
import { FederationCallback } from "../../pages/FederationCallback.tsx";
|
||||
import { AUTH_STORAGE_KEY } from "../../utils/auth/storage.ts";
|
||||
import { calls, fail, route } from "../fetch.ts";
|
||||
import { makeSession, wire } from "../fixtures.ts";
|
||||
import { renderApp } from "../render.tsx";
|
||||
|
||||
function open(query: string) {
|
||||
renderApp(<FederationCallback />, {
|
||||
route: `/federation/callback${query}`,
|
||||
path: "/federation/callback",
|
||||
extraRoutes: <Route path="/" element={<p>home page</p>} />,
|
||||
});
|
||||
}
|
||||
|
||||
describe("FederationCallback", () => {
|
||||
test("finishes the sign-in once and lands home signed in", async () => {
|
||||
route(
|
||||
"POST /api/federation/sessions",
|
||||
() => wire(makeSession({ username: "alice@home.example" })),
|
||||
);
|
||||
open("?code=c&state=s&iss=https%3A%2F%2Fhome.example");
|
||||
await screen.findByText("home page");
|
||||
expect(calls("POST /api/federation/sessions").map((c) => c.body)).toEqual(
|
||||
[{ code: "c", state: "s" }],
|
||||
);
|
||||
expect(JSON.parse(localStorage.getItem(AUTH_STORAGE_KEY)!).user.username)
|
||||
.toBe("alice@home.example");
|
||||
});
|
||||
|
||||
test("a refusal is shown, with the way back", async () => {
|
||||
route(
|
||||
"POST /api/federation/sessions",
|
||||
() => fail("This sign-in has expired, start again"),
|
||||
);
|
||||
open("?code=c&state=s");
|
||||
expect(await screen.findByText("This sign-in has expired, start again"))
|
||||
.toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Back to the login page" }))
|
||||
.toHaveAttribute("href", "/login");
|
||||
});
|
||||
|
||||
test("a link without its code says so", async () => {
|
||||
open("?state=s");
|
||||
expect(await screen.findByText("This sign-in link is incomplete."))
|
||||
.toBeInTheDocument();
|
||||
expect(calls("POST /api/federation/sessions")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import { renderApp } from "../render.tsx";
|
||||
const admin = makeSession({ id: "ann", username: "ann", role: "admin" });
|
||||
|
||||
function open(session = admin) {
|
||||
route("GET /api/federation/peers", () => [], { fallback: true });
|
||||
const user = userEvent.setup();
|
||||
renderApp(<Manage />, { route: "/manage", path: "/manage", session });
|
||||
return user;
|
||||
@@ -78,6 +79,55 @@ describe("Manage", () => {
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("an admin trusts, blocks and removes other instances", async () => {
|
||||
route("GET /api/categories", () => []);
|
||||
const music = {
|
||||
issuer: "https://music.example",
|
||||
host: "music.example",
|
||||
name: "Music",
|
||||
status: "trusted",
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
let peers: (typeof music)[] = [];
|
||||
route("GET /api/federation/peers", () => peers);
|
||||
route("PUT /api/federation/peers", (req) => {
|
||||
const { status } = req.body as { status: string };
|
||||
peers = [{ ...music, status }];
|
||||
return peers[0];
|
||||
});
|
||||
route("DELETE /api/federation/peers/:host", () => {
|
||||
peers = [];
|
||||
return null;
|
||||
});
|
||||
const user = open();
|
||||
await user.type(
|
||||
await screen.findByPlaceholderText(
|
||||
"An instance's address, like music.example",
|
||||
),
|
||||
"music.example",
|
||||
);
|
||||
await user.click(screen.getByRole("button", { name: "Trust" }));
|
||||
expect(await screen.findByText("Music")).toBeInTheDocument();
|
||||
expect(calls("PUT /api/federation/peers")[0].body).toEqual({
|
||||
instance: "music.example",
|
||||
status: "trusted",
|
||||
});
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Blocked" }));
|
||||
await waitFor(() =>
|
||||
expect(calls("PUT /api/federation/peers")[1]?.body).toEqual({
|
||||
instance: "https://music.example",
|
||||
status: "blocked",
|
||||
})
|
||||
);
|
||||
await user.click(
|
||||
screen.getByRole("button", { name: "Remove music.example" }),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByText("Music")).not.toBeInTheDocument()
|
||||
);
|
||||
});
|
||||
|
||||
test("without category:manage, the page isn't found", async () => {
|
||||
open(makeSession({ id: "mod", role: "moderator" }));
|
||||
expect(await screen.findByText("This page does not exist."))
|
||||
|
||||
@@ -23,6 +23,7 @@ const annSession = makeSession({
|
||||
});
|
||||
|
||||
function open(session = annSession) {
|
||||
route("GET /api/me/grants", () => [], { fallback: true });
|
||||
const user = userEvent.setup();
|
||||
renderApp(<Settings />, { route: "/settings", path: "/settings", session });
|
||||
return user;
|
||||
@@ -170,4 +171,42 @@ describe("Settings", () => {
|
||||
"Current password is incorrect",
|
||||
);
|
||||
});
|
||||
|
||||
test("lists the instances the account signs in to, and disconnects one", async () => {
|
||||
const now = new Date().toISOString();
|
||||
let grants = [{
|
||||
clientId: "https://music.example",
|
||||
host: "music.example",
|
||||
name: "Music",
|
||||
grantedAt: now,
|
||||
lastUsedAt: now,
|
||||
}];
|
||||
route("GET /api/me/grants", () => grants);
|
||||
route("DELETE /api/me/grants/:host", () => {
|
||||
grants = [];
|
||||
return null;
|
||||
});
|
||||
const user = open();
|
||||
expect(await screen.findByText("Music")).toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Disconnect" }));
|
||||
expect(
|
||||
await screen.findByText(/You haven't signed in to another gerbeur/),
|
||||
).toBeInTheDocument();
|
||||
expect(calls("DELETE /api/me/grants/:host")[0].path).toBe(
|
||||
"/api/me/grants/music.example",
|
||||
);
|
||||
});
|
||||
|
||||
test("an account from another instance changes its password there", async () => {
|
||||
open(makeSession({ id: "al", username: "alice@home.example" }));
|
||||
const link = await screen.findByRole("link", {
|
||||
name: "Change it on home.example",
|
||||
});
|
||||
expect(link).toHaveAttribute(
|
||||
"href",
|
||||
`${location.protocol}//home.example/settings`,
|
||||
);
|
||||
expect(screen.queryByText("Other instances")).not.toBeInTheDocument();
|
||||
expect(calls("GET /api/me/grants")).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { Route } from "react-router";
|
||||
import { UserLogin } from "../../pages/UserLogin.tsx";
|
||||
@@ -120,4 +120,96 @@ describe("UserLogin", () => {
|
||||
expect(screen.queryByText(/you'll receive a reset link/)).not
|
||||
.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test("a sign-in follows ?next= on this site, and only there", async () => {
|
||||
route("POST /api/sessions", () => wire(makeSession()));
|
||||
const user = userEvent.setup();
|
||||
renderWithContexts(<UserLogin />, {
|
||||
route: `/login?next=${encodeURIComponent("/authorize?client_id=x")}`,
|
||||
path: "/login",
|
||||
extraRoutes: <Route path="/authorize" element={<p>authorize</p>} />,
|
||||
});
|
||||
await user.type(screen.getByPlaceholderText("Username"), "ann");
|
||||
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
|
||||
await screen.findByText("authorize");
|
||||
expect(currentPath()).toBe("/authorize?client_id=x");
|
||||
});
|
||||
|
||||
test("ignores a ?next= that leaves the site", async () => {
|
||||
route("POST /api/sessions", () => wire(makeSession()));
|
||||
const user = userEvent.setup();
|
||||
renderWithContexts(<UserLogin />, {
|
||||
route: `/login?next=${encodeURIComponent("//evil.example")}`,
|
||||
path: "/login",
|
||||
extraRoutes: home,
|
||||
});
|
||||
await user.type(screen.getByPlaceholderText("Username"), "ann");
|
||||
await user.type(screen.getByPlaceholderText("Password"), "pw{Enter}");
|
||||
await screen.findByText("home page");
|
||||
});
|
||||
|
||||
describe("with an account on another instance", () => {
|
||||
const assign = vi.fn();
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
assign.mockReset();
|
||||
});
|
||||
|
||||
test("a trusted instance's button, or any address, starts the sign-in there", async () => {
|
||||
vi.stubGlobal("location", { ...globalThis.location, assign });
|
||||
route("GET /api/federation/peers", () => [{
|
||||
issuer: "https://music.example",
|
||||
host: "music.example",
|
||||
name: "Music",
|
||||
status: "trusted",
|
||||
createdAt: new Date().toISOString(),
|
||||
}]);
|
||||
route("POST /api/federation/logins", (req) => ({
|
||||
authorizeUrl: `https://${
|
||||
(req.body as { instance: string }).instance.replace(/^https:\/\//, "")
|
||||
}/authorize?x`,
|
||||
}));
|
||||
const user = setup();
|
||||
await user.click(
|
||||
await screen.findByRole("button", { name: /Log in with Music/ }),
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(assign).toHaveBeenCalledWith(
|
||||
"https://music.example/authorize?x",
|
||||
)
|
||||
);
|
||||
expect(calls("POST /api/federation/logins")[0].body).toEqual({
|
||||
instance: "https://music.example",
|
||||
});
|
||||
|
||||
await user.clear(
|
||||
screen.getByPlaceholderText("Its address, like music.example"),
|
||||
);
|
||||
await user.type(
|
||||
screen.getByPlaceholderText("Its address, like music.example"),
|
||||
" films.example {Enter}",
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(assign).toHaveBeenLastCalledWith(
|
||||
"https://films.example/authorize?x",
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
test("a refusal is shown under the field", async () => {
|
||||
route("GET /api/federation/peers", () => []);
|
||||
route(
|
||||
"POST /api/federation/logins",
|
||||
() => fail("Users of this instance need an invite to join", 403),
|
||||
);
|
||||
const user = setup();
|
||||
await user.type(
|
||||
screen.getByPlaceholderText("Its address, like music.example"),
|
||||
"films.example{Enter}",
|
||||
);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"need an invite",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -56,6 +56,27 @@ function open(
|
||||
}
|
||||
|
||||
describe("UserPublicProfile", () => {
|
||||
test("a user from another instance shows their home, and edits nothing here", async () => {
|
||||
const alice = makeUser({ id: "al", username: "alice@home.example" });
|
||||
open({
|
||||
user: alice,
|
||||
url: "/@alice@home.example",
|
||||
session: makeSession({ id: "al", username: "alice@home.example" }),
|
||||
});
|
||||
expect(await screen.findByRole("heading", { name: "alice@home.example" }))
|
||||
.toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "home.example" })).toHaveAttribute(
|
||||
"href",
|
||||
`${location.protocol}//home.example/@alice`,
|
||||
);
|
||||
expect(screen.queryByTitle("Change avatar")).not.toBeInTheDocument();
|
||||
expect(screen.queryByTitle("Edit email")).not.toBeInTheDocument();
|
||||
expect(screen.queryByText("O.G.")).not.toBeInTheDocument();
|
||||
expect(calls("GET /api/users/:u")[0].path).toBe(
|
||||
"/api/users/@alice%40home.example",
|
||||
);
|
||||
});
|
||||
|
||||
test("header, description, and the overview", async () => {
|
||||
open();
|
||||
expect(await screen.findByRole("heading", { name: "ann" }))
|
||||
|
||||
15
src/test/utils/auth/next.test.ts
Normal file
15
src/test/utils/auth/next.test.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { loginPath, nextPath } from "../../../utils/auth/next.ts";
|
||||
|
||||
describe("next", () => {
|
||||
test("comes back only to a path on this site", () => {
|
||||
const next = (value: string) =>
|
||||
nextPath(new URLSearchParams({ next: value }));
|
||||
expect(next("/authorize?client_id=x")).toBe("/authorize?client_id=x");
|
||||
expect(next("//evil.example")).toBeNull();
|
||||
expect(next("/\\evil.example")).toBeNull();
|
||||
expect(next("https://evil.example")).toBeNull();
|
||||
expect(nextPath(new URLSearchParams())).toBeNull();
|
||||
expect(loginPath("/a?b=c")).toBe("/login?next=%2Fa%3Fb%3Dc");
|
||||
});
|
||||
});
|
||||
30
src/utils/auth/home.ts
Normal file
30
src/utils/auth/home.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Points at the instance an account from another gerbeur comes from, its
|
||||
* home, where its password, email, avatar and name are changed. Such a user's
|
||||
* handle here is `name@host` (`splitHandle`); the profile, the settings and
|
||||
* the `/authorize` page read it through these.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { splitHandle } from "../../../shared/validation.ts";
|
||||
import { userPath } from "../../../shared/paths.ts";
|
||||
|
||||
/**
|
||||
* Returns the host of `handle`'s home instance, or undefined for a local
|
||||
* user.
|
||||
*/
|
||||
export function homeHost(handle: string): string | undefined {
|
||||
return splitHandle(handle).host;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URL of `path` on `handle`'s home instance, their profile there
|
||||
* by default, or null for a local user. Instances speak the same protocol as
|
||||
* this page, https outside development.
|
||||
*/
|
||||
export function homeUrl(handle: string, path?: string): string | null {
|
||||
const { name, host } = splitHandle(handle);
|
||||
if (!host) return null;
|
||||
return `${globalThis.location.protocol}//${host}${path ?? userPath(name)}`;
|
||||
}
|
||||
25
src/utils/auth/next.ts
Normal file
25
src/utils/auth/next.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Brings a visitor back to the page that sent them to sign in. The
|
||||
* `/authorize` page sends a signed-out visitor to `/login?next=`, and the
|
||||
* login page and `RestrictedGuest` follow `next` once they are signed in.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/**
|
||||
* Returns the `/login` path that comes back to `path` after signing in, a
|
||||
* path on this site with its query.
|
||||
*/
|
||||
export function loginPath(path: string): string {
|
||||
return `/login?next=${encodeURIComponent(path)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the `next` of `params` when it is a path on this site, or null.
|
||||
* Anything else, `//elsewhere.example` included, is ignored, so a link can't
|
||||
* send someone off the site through the login page.
|
||||
*/
|
||||
export function nextPath(params: URLSearchParams): string | null {
|
||||
const next = params.get("next");
|
||||
return next && /^\/(?![/\\])/.test(next) ? next : null;
|
||||
}
|
||||
@@ -13,6 +13,10 @@ import type { ChatMessage } from "../../../shared/chat.ts";
|
||||
import type { Comment } from "../../../shared/comment.ts";
|
||||
import type { CommunityStats } from "../../../shared/community.ts";
|
||||
import type { Dump, DumpUrlMatch } from "../../../shared/dump.ts";
|
||||
import type {
|
||||
FederationGrant,
|
||||
FederationPeer,
|
||||
} from "../../../shared/federation.ts";
|
||||
import type { Notification } from "../../../shared/notification.ts";
|
||||
import type {
|
||||
Playlist,
|
||||
@@ -142,3 +146,21 @@ export function deserializeCommunityStats(
|
||||
playlists: raw.playlists.map(deserializePlaylist),
|
||||
};
|
||||
}
|
||||
|
||||
/** Returns `raw` as a {@link FederationPeer}. */
|
||||
export function deserializeFederationPeer(
|
||||
raw: Wire<FederationPeer>,
|
||||
): FederationPeer {
|
||||
return { ...raw, createdAt: new Date(raw.createdAt) };
|
||||
}
|
||||
|
||||
/** Returns `raw` as a {@link FederationGrant}. */
|
||||
export function deserializeFederationGrant(
|
||||
raw: Wire<FederationGrant>,
|
||||
): FederationGrant {
|
||||
return {
|
||||
...raw,
|
||||
grantedAt: new Date(raw.grantedAt),
|
||||
lastUsedAt: new Date(raw.lastUsedAt),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user