chore(server): checkpoint deployed services and unfinished forums

User requested a checkpoint and stopped all agents. Deployed artifacts remain the last verified releases; unfinished settings/categories/forums are preserved as WIP. See TODO/roadmap for verification and remaining release/updater work.
This commit is contained in:
Loki 2026-11-01 15:31:20 +01:00
parent d6d406bbf5
commit c18ccadf99
Signed by: boba
GPG key ID: 253067914055423B
96 changed files with 8665 additions and 276 deletions

View file

@ -55,7 +55,7 @@ Per address 1 per 60 s and 5 per hour; per source (`X-Forwarded-For`, as GitHub
Addresses are trimmed and lowercased; only ASCII, a local part of `[a-z0-9._%+-]` without leading/trailing/double dots, at most 64 characters, a multi-label hostname whose last label is alphabetic, at most 254 characters in total. `+tag` is not stripped and Gmail dots are not folded. Unusual legal addresses are rejected on purpose.
The identity is `external_identities(provider='email', subject=<normalized address>)`, reusing the existing table so one address maps to one account, and it can never collide with `github.com` subjects. A matching GitHub account or email is never merged automatically. A first successful verification creates an account with a generated `u_<uuid>` handle and the neutral display name `Vnox user`; the local part of the address is never used. Choosing a handle and display name after registration is not implemented yet (an own avatar can be uploaded, see below) (see `design/accounts-and-avatars.md`). The address is kept in plain normalized form in `external_identities` because later features (security notices, adding a second sign-in method) need it; it is used for nothing except sending codes today.
The identity is `external_identities(provider='email', subject=<normalized address>)`, reusing the existing table so one address maps to one account, and it can never collide with `github.com` subjects. A matching GitHub account or email is never merged automatically. A first successful verification creates an account with a generated `u_<uuid>` handle and the neutral display name `Vnox user`; the local part of the address is never used. The profile API below selects a handle and display name after registration; browser onboarding is still separate work. An own avatar can be uploaded, see below. The address is kept in plain normalized form in `external_identities` because later features (security notices, adding a second sign-in method) need it; it is used for nothing except sending codes today.
### Mail and logging
@ -104,3 +104,63 @@ The provider avatar URL stays on `accounts.avatar_url` and is the fallback after
- Avatars are public to anyone who knows the id; ids are not secret but are not listed anywhere. Identical images from two accounts share an id.
- Deleted photos can remain in database backups. The project owner decided that backups keep deleted data for up to 30 days; this needs backup rotation to be implemented and is not enforced by the Hub.
- Decoding uses the `image` crate with only the `png`, `jpeg` and `webp` features. `cargo audit` reported no advisories when this was added. Decoder bugs in these crates are the main residual risk; decoding is bounded in size, memory and concurrency.
## Account profile and registration completion
`PUT /v1/account/profile` accepts JSON with exactly `handle` and `display_name`.
It requires the session cookie, exact Origin and X-CSRF-Token, like avatar changes.
The body limit is 1 KiB. Successful responses are `200 {"user": ...}`; session and
email verification responses also include `user.profile_complete`. Existing and
new accounts start with `profile_complete: false`; generated `u_<uuid>` handles
are placeholders, never selected automatically from a provider identity.
Handles are trimmed, ASCII-lowercased, 3 to 24 characters, start with a letter,
and contain only ASCII letters, digits and underscore. Names starting with `u_`
are reserved for generated accounts; `admin`, `administrator`, `root`, `system`,
`support`, `vnox`, `central`, `moderator`, `everyone` and `here` are reserved.
A unique database index enforces case-insensitive ownership, including concurrent
claims. Once selected, a handle cannot change; submitting the same normalized
handle permits display-name changes and makes retries safe. Display names are
trimmed, 1 to 64 Unicode scalar values, with control characters and Unicode
bidirectional formatting controls rejected. Names are plain text, not markup.
Errors: `400 invalid_request`, `422 invalid_handle` / `invalid_display_name`,
`409 handle_taken` / `handle_locked`, standard session/Origin/CSRF errors,
`413` for bodies over the limit, `429 try_later`, `503 try_later`. Malformed JSON,
unknown fields and missing fields are rejected without changing the account.
`/v1/info` advertises `capabilities.account_profile: "enabled"` independently of
which sign-in providers are configured. Profile writes are limited to 10 attempts per account and 30 per source per hour,
with bounded in-memory counters (reset at restart). Authentication precedes body
reading; errors and success responses are no-store. Provider sign-in preserves
the selected profile. User ID and provider bindings never change.
## Desktop browser approval (LNEx v4)
Desktop enrollment uses the existing email/GitHub browser session and explicit
approval at `/desktop`. Profile completion is not required. The public pairing
code and full local Ed25519 public key appear in the browser; private keys and
bearer credentials never do. The full protocol and claim format are specified in
[central-account.md](../docs/02-protocol/central-account.md).
- `POST /v1/auth/desktop/start`: `{public_key}` returns a private `device_secret`,
public `user_code`, `verification_uri`, `expires_at`, and five-second `interval`.
- `GET /v1/auth/desktop/request?code=...`: public key, expiry, approval state.
- `POST /v1/auth/desktop/approve`: `{code}`, authenticated session, exact Origin,
session CSRF header; requires explicit user action.
- `POST /v1/auth/desktop/poll`: `{device_secret}` returns 202 while pending;
approved requests are consumed once and return account proof, refresh secret,
account details, and proof expiry.
- `POST /v1/auth/desktop/cancel`: `{device_secret}` cancels either pending request
or consumed enrollment, covering cancellation and lost-response races.
- `POST /v1/auth/desktop/refresh`: `{refresh_secret}` issues a fresh proof only
for an unexpired, unrevoked enrollment.
- `POST /v1/auth/desktop/revoke`: `{refresh_secret}`, idempotently revokes it.
Requests expire in ten minutes; enrollments expire in thirty days. Hub stores
only hashes of pairing, device, and refresh secrets. Proofs last at most ten
minutes and bind the Central account UUID to the local identity key. All LNEx v4
gateways require a proof verified against explicit issuer UUID/public-key trust;
there is no anonymous or private-server exception. Revocation prevents new proof
issuance; issued proofs and existing gateway sessions retain their documented
lifetimes. Desktop logout disables local admission immediately and retains a
private revocation tombstone for retry if Central is unavailable.

View file

@ -12,6 +12,7 @@ Community messages and voice never pass through this process.
- `/v1/info`: public issuer ID/key and honest feature availability.
- `/`: deployment status page; `/assets/vnox-mark.svg`: approved V connection mark.
- Durable SQLite schema and issuer identity with a private `0600` key file.
- Account profile: `PUT /v1/account/profile` selects a unique permanent handle, edits the display name and completes registration (`user.profile_complete`; see `AUTH.md`).
- Own avatar for signed-in web sessions: `POST`/`DELETE /v1/account/avatar`, public `GET /v1/avatars/<id>` (re-encoded 256x256 PNG in SQLite, see `AUTH.md`).
- TLS-only SMTP transport and HTML/plain-text transactional email templates.
@ -80,3 +81,6 @@ Hub. An invalid/malformed issuer file likewise fails closed. Protect the entire
data directory, not only the JSON file. Additional account/device revocation,
registry authorization, mailbox lifecycle and storage policies require their own
implementation and security review before those capabilities are enabled.
Community server listings are unverified browser submissions. Public reads and authenticated
owner-managed publication are documented in [the HTTP contract](../docs/05-features/hub-server-directory.md).

View file

@ -0,0 +1,9 @@
# Friendly Russian nickname words
Data source: [OpenRussian / Badestrand Russian Dictionary](https://github.com/Badestrand/russian-dictionary), maintained by OpenRussian and its contributors.
Pinned revision: `50e210c4803237779cb562bc1abcea529066031c`; downloaded `nouns.csv` from https://raw.githubusercontent.com/Badestrand/russian-dictionary/50e210c4803237779cb562bc1abcea529066031c/nouns.csv .
The source and this derived JSON word selection are licensed under **Creative Commons Attribution-ShareAlike 4.0 International**. The full license is adjacent in LICENSE-CC-BY-SA-4.0.txt. This data license is separate from the application's code license. No endorsement is implied.
Modifications by VNOX contributors (2026): manually selected friendly nature, animal, food and object nouns; retained only upstream bare dictionary forms; sorted and deduplicated; converted TSV data to a JSON array. 385 words. No people's names, email identifiers, insults or political/military labels are intentionally included. Words are display names, not unique handles.

View file

@ -0,0 +1,427 @@
Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View file

@ -0,0 +1,387 @@
[
"абрикос",
"аист",
"айва",
"айсберг",
"акация",
"акварель",
"аккорд",
"акробат",
"альбатрос",
"альбом",
"ананас",
"анемон",
"антилопа",
"апельсин",
"арбуз",
"арка",
"арлекин",
"аромат",
"астра",
"атлас",
"афалина",
"бабочка",
"багет",
"бамбук",
"банан",
"бантик",
"барбарис",
"барс",
"барсук",
"бархат",
"бегония",
"белка",
"бергамот",
"берёза",
"бинокль",
"бисквит",
"блик",
"бобр",
"бокал",
"боровик",
"брусника",
"букет",
"булочка",
"бурундук",
"бусина",
"василёк",
"вафля",
"веер",
"велосипед",
"верба",
"верблюд",
"вереск",
"весна",
"ветер",
"ветка",
"веточка",
"вишня",
"волна",
"волчок",
"воробей",
"воск",
"восход",
"выдра",
"вьюнок",
"газель",
"галактика",
"гамак",
"гвоздика",
"гейзер",
"георгин",
"гепард",
"гиацинт",
"глобус",
"голубика",
"голубь",
"горизонт",
"горлица",
"горошек",
"гортензия",
"гранат",
"графит",
"гребешок",
"грейпфрут",
"гриб",
"груша",
"гусеница",
"гусь",
"дельфин",
"джем",
"дождик",
"дождь",
"долька",
"домик",
"дракон",
"дрозд",
"дуб",
"дудочка",
"дыня",
"ежевика",
"ель",
"енот",
"жасмин",
"жемчуг",
"жираф",
"жук",
"журавль",
"звезда",
"земляника",
"зефир",
"зима",
"зимородок",
"зонтик",
"зубр",
"ива",
"игрушка",
"изумруд",
"имбирь",
"иней",
"инжир",
"ирис",
"искра",
"какао",
"кактус",
"калейдоскоп",
"калина",
"камелия",
"камень",
"камыш",
"канарейка",
"капель",
"карамель",
"карусель",
"каштан",
"кедр",
"кекс",
"кенгуру",
"кипарис",
"кисточка",
"кит",
"клавиша",
"клевер",
"клубника",
"клюква",
"клён",
"колибри",
"колокольчик",
"колос",
"комета",
"конверт",
"конфета",
"коралл",
"корица",
"космос",
"кот",
"котёнок",
"крекер",
"крендель",
"кристалл",
"крокус",
"кролик",
"крыжовник",
"кувшинка",
"кузнечик",
"купол",
"куропатка",
"лабрадор",
"лаванда",
"лампа",
"ландыш",
"ласточка",
"лебедь",
"лев",
"леденец",
"лемур",
"лепесток",
"лес",
"лесник",
"лето",
"лилия",
"лимон",
"липа",
"лис",
"лиса",
"лисичка",
"лист",
"листок",
"лодка",
"лоза",
"лосось",
"лотос",
"луг",
"луч",
"лучик",
"львёнок",
"лютик",
"магнолия",
"мак",
"малина",
"манго",
"мандарин",
"маргаритка",
"мармелад",
"марципан",
"маяк",
"медвежонок",
"мел",
"мелодия",
"метеор",
"мимоза",
"миндаль",
"мишка",
"можжевельник",
"море",
"мороженое",
"морошка",
"морс",
"мотылёк",
"мох",
"муравей",
"мята",
"нарцисс",
"незабудка",
"нектар",
"нить",
"нотка",
"облако",
"овсянка",
"огонёк",
"одуванчик",
"озеро",
"олень",
"олива",
"опал",
"орех",
"орешек",
"орхидея",
"осень",
"остров",
"оттенок",
"павлин",
"палитра",
"папоротник",
"парус",
"пастила",
"пеликан",
"пенёк",
"персик",
"песок",
"петрушка",
"пион",
"пихта",
"планета",
"платан",
"плед",
"плющ",
"подснежник",
"подушка",
"полюс",
"помело",
"пони",
"попугай",
"пряник",
"пуговица",
"пудель",
"пчела",
"пчёлка",
"пшеница",
"радуга",
"ракета",
"ракушка",
"рассвет",
"редис",
"репа",
"риф",
"рогалик",
"роза",
"розмарин",
"ромашка",
"роса",
"роща",
"рубин",
"ручей",
"рысь",
"рябина",
"рябчик",
"саламандра",
"самовар",
"сапфир",
"сахар",
"сверчок",
"свет",
"свирель",
"свиристель",
"север",
"сияние",
"скворец",
"скрипка",
"слива",
"слон",
"слонёнок",
"смородина",
"снег",
"снегирь",
"снежинка",
"сова",
"совёнок",
"сокол",
"солнце",
"соловей",
"сорока",
"сосна",
"соты",
"спираль",
"стебель",
"стрекоза",
"стриж",
"суслик",
"суфле",
"тайга",
"тамаринд",
"тапир",
"тень",
"тигр",
"тигрёнок",
"тополь",
"трель",
"тропа",
"туман",
"тыква",
"тюльпан",
"уголь",
"уголёк",
"узор",
"укроп",
"улитка",
"улыбка",
"утка",
"утро",
"утёнок",
"фазан",
"факел",
"фиалка",
"фикус",
"филин",
"финик",
"фонарь",
"фонтан",
"фрегат",
"хамелеон",
"хвоя",
"хомяк",
"цапля",
"цветок",
"чай",
"чайка",
"чашка",
"черепаха",
"черешня",
"черника",
"черёмуха",
"чечевица",
"чибис",
"чиж",
"шиповник",
"шишка",
"шмель",
"шорох",
"шпинат",
"щавель",
"щенок",
"эвкалипт",
"эдельвейс",
"эскимо",
"юла",
"юрта",
"яблоко",
"яблоня",
"ягода",
"ягуар",
"янтарь",
"ясень",
"ястреб",
"ящерица",
"ёж",
"ёлка"
]

View file

@ -0,0 +1,22 @@
//! Writes a deterministic contact sheet without opening a desktop window or account.
fn main() -> anyhow::Result<()> {
let output = std::env::args()
.nth(1)
.unwrap_or_else(|| "/tmp/vnox-monsters.png".into());
let mut sheet = image::RgbImage::from_pixel(832, 624, image::Rgb([17, 19, 24]));
for index in 0..12 {
let id = format!("00000000-0000-4000-8000-{:012x}", index + 1);
let png =
vnox_hub::avatar::default_v2_png(&id).map_err(|_| anyhow::anyhow!("render failed"))?;
let image = image::load_from_memory(&png)?.to_rgb8();
let image = image::imageops::resize(&image, 192, 192, image::imageops::FilterType::Nearest);
image::imageops::replace(
&mut sheet,
&image,
(index % 4 * 208 + 8).into(),
(index / 4 * 208 + 8).into(),
);
}
sheet.save(output)?;
Ok(())
}

View file

@ -0,0 +1,4 @@
-- Generated accounts remain incomplete until the owner selects a handle.
ALTER TABLE accounts ADD COLUMN profile_complete INTEGER NOT NULL DEFAULT 0
CHECK (profile_complete IN (0, 1));
CREATE UNIQUE INDEX accounts_handle_case_insensitive ON accounts(handle COLLATE NOCASE);

View file

@ -0,0 +1,10 @@
-- Separate unverified browser submissions from cryptographic server registrations.
CREATE TABLE community_servers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL CHECK(length(name) BETWEEN 1 AND 80),
address TEXT NOT NULL UNIQUE,
description TEXT NOT NULL CHECK(length(description) <= 500),
owner_id TEXT NOT NULL REFERENCES accounts(user_id) ON DELETE CASCADE,
created_at INTEGER NOT NULL
);
CREATE INDEX community_servers_owner ON community_servers(owner_id);

View file

@ -0,0 +1,17 @@
CREATE TABLE desktop_authorizations (
device_hash TEXT PRIMARY KEY,
code_hash TEXT NOT NULL UNIQUE,
public_key TEXT NOT NULL,
user_id TEXT REFERENCES accounts(user_id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL
);
CREATE INDEX desktop_authorization_expiry ON desktop_authorizations(expires_at);
CREATE TABLE desktop_devices (
refresh_hash TEXT PRIMARY KEY,
device_hash TEXT NOT NULL UNIQUE,
public_key TEXT NOT NULL,
user_id TEXT NOT NULL REFERENCES accounts(user_id) ON DELETE CASCADE,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL
);
CREATE INDEX desktop_device_expiry ON desktop_devices(expires_at);

View file

@ -0,0 +1,8 @@
-- Existing accounts have no row and never receive a first-registration prompt.
-- This migration is independent of optional handle/profile completion migrations.
CREATE TABLE account_onboarding (
user_id TEXT PRIMARY KEY REFERENCES accounts(user_id) ON DELETE CASCADE,
decided_at INTEGER,
decision TEXT CHECK (decision IN ('rename', 'later')),
CHECK ((decided_at IS NULL) = (decision IS NULL))
);

View file

@ -1,4 +1,5 @@
pub mod email;
mod nicknames;
pub mod provider;
mod routes;
pub mod store;
@ -26,16 +27,19 @@ pub struct AuthService {
/// Present only when a mail transport is configured.
pub email: Option<email::EmailAuth>,
limits: Mutex<HashMap<String, (i64, u32)>>,
profile_events: Mutex<HashMap<String, Vec<i64>>>,
directory_reads: Mutex<HashMap<String, (i64, u32)>>,
directory_events: Mutex<HashMap<String, Vec<i64>>>,
avatar_events: Mutex<HashMap<String, Vec<i64>>>,
/// Bounds concurrent image decodes, which are the most expensive thing a session can ask for.
pub avatar_decoding: tokio::sync::Semaphore,
pub avatar_decoding: Arc<tokio::sync::Semaphore>,
}
/// Avatar changes (upload or removal) per account and per source within one hour.
const AVATAR_PER_USER_HOUR: usize = 10;
const AVATAR_PER_SOURCE_HOUR: usize = 30;
const AVATAR_WINDOW: i64 = 3600;
const AVATAR_TRACKED_KEYS: usize = 8192;
/// Independent profile/avatar budgets per account and per source within one hour.
const CHANGE_PER_USER_HOUR: usize = 10;
const CHANGE_PER_SOURCE_HOUR: usize = 30;
const CHANGE_WINDOW: i64 = 3600;
const CHANGE_TRACKED_KEYS: usize = 8192;
impl AuthService {
pub fn new(
@ -62,8 +66,11 @@ impl AuthService {
provider,
email: None,
limits: Mutex::new(HashMap::new()),
profile_events: Mutex::new(HashMap::new()),
directory_reads: Mutex::new(HashMap::new()),
directory_events: Mutex::new(HashMap::new()),
avatar_events: Mutex::new(HashMap::new()),
avatar_decoding: tokio::sync::Semaphore::new(2),
avatar_decoding: Arc::new(tokio::sync::Semaphore::new(2)),
}
}
/// Enables email sign-in. Callers do this only when SMTP is configured (or a test sender).
@ -78,7 +85,13 @@ impl AuthService {
self.provider.is_some()
}
pub fn allow(&self, ip: &str) -> bool {
let Ok(mut limits) = self.limits.lock() else {
Self::allow_reads(&self.limits, ip)
}
pub fn allow_directory_read(&self, ip: &str) -> bool {
Self::allow_reads(&self.directory_reads, ip)
}
fn allow_reads(limits: &Mutex<HashMap<String, (i64, u32)>>, ip: &str) -> bool {
let Ok(mut limits) = limits.lock() else {
return false;
};
let now = store::now();
@ -101,20 +114,30 @@ impl AuthService {
/// budgets still had room. A refused attempt is not recorded, so a blocked client does
/// not extend its own block.
pub fn allow_avatar(&self, user: &str, source: &str) -> bool {
let Ok(mut events) = self.avatar_events.lock() else {
Self::allow_changes(&self.avatar_events, user, source)
}
/// Profile writes have an independent, bounded hourly account/source budget.
pub fn allow_profile(&self, user: &str, source: &str) -> bool {
Self::allow_changes(&self.profile_events, user, source)
}
pub fn allow_directory(&self, user: &str, source: &str) -> bool {
Self::allow_changes(&self.directory_events, user, source)
}
fn allow_changes(events: &Mutex<HashMap<String, Vec<i64>>>, user: &str, source: &str) -> bool {
let Ok(mut events) = events.lock() else {
return false;
};
let now = store::now();
events.retain(|_, times| {
times.retain(|at| now - *at < AVATAR_WINDOW);
times.retain(|at| now - *at < CHANGE_WINDOW);
!times.is_empty()
});
let user_key = format!("u:{user}");
let source_key = format!("s:{source}");
let count = |key: &str| events.get(key).map_or(0, Vec::len);
if count(&user_key) >= AVATAR_PER_USER_HOUR
|| count(&source_key) >= AVATAR_PER_SOURCE_HOUR
|| events.len() + 2 > AVATAR_TRACKED_KEYS
if count(&user_key) >= CHANGE_PER_USER_HOUR
|| count(&source_key) >= CHANGE_PER_SOURCE_HOUR
|| events.len() + 2 > CHANGE_TRACKED_KEYS
{
return false;
}

41
hub/src/auth/nicknames.rs Normal file
View file

@ -0,0 +1,41 @@
//! First-registration display names, independent of provider names and public handles.
use rand::RngExt;
use std::sync::LazyLock;
static WORDS: LazyLock<Vec<String>> = LazyLock::new(|| {
serde_json::from_str(include_str!("../../assets/nicknames/friendly-ru.json"))
.expect("checked-in nickname words are validated by tests")
});
pub(super) fn generate() -> String {
// ThreadRng is the OS-seeded cryptographic generator; rejection-sampled ranges
// avoid biased suffixes. Display names deliberately need not be unique handles.
let mut random = rand::rng();
format!(
"{}_{:04}",
WORDS[random.random_range(0..WORDS.len())],
random.random_range(0..10_000)
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bundled_words_and_generated_names_are_bounded_friendly_forms() {
assert!(WORDS.len() >= 300);
let unique: std::collections::HashSet<_> = WORDS.iter().collect();
assert_eq!(unique.len(), WORDS.len());
for word in WORDS.iter() {
assert!(word.chars().all(|c| ('а'..='я').contains(&c) || c == 'ё'));
assert!(word.chars().count() <= 59);
}
for _ in 0..1000 {
let name = generate();
let (word, suffix) = name.rsplit_once('_').unwrap();
assert!(WORDS.iter().any(|candidate| candidate == word));
assert_eq!(suffix.len(), 4);
assert!(suffix.bytes().all(|c| c.is_ascii_digit()));
assert!(name.chars().count() <= 64);
}
}
}

View file

@ -8,13 +8,18 @@ use axum::{
extract::{DefaultBodyLimit, Query, State, rejection::JsonRejection},
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Redirect, Response},
routing::{get, post},
routing::{get, post, put},
};
use cookie::{Cookie, SameSite};
use oauth2::{CsrfToken, PkceCodeChallenge};
use serde::Deserialize;
use serde_json::json;
mod avatar;
mod desktop;
mod desktop_avatar;
mod directory;
mod onboarding;
mod profile;
use std::sync::Arc;
use subtle::ConstantTimeEq;
const BROWSER: &str = "__Host-vnox_oauth";
@ -22,6 +27,31 @@ const EMAIL_BROWSER: &str = "__Host-vnox_email";
const SESSION: &str = "__Host-vnox_session";
pub fn router() -> Router<Arc<HubState>> {
Router::new()
.route("/v1/auth/desktop/start", post(desktop::start))
.route("/v1/auth/desktop/request", get(desktop::request))
.route("/v1/auth/desktop/approve", post(desktop::approve))
.route("/v1/auth/desktop/poll", post(desktop::poll))
.route("/v1/auth/desktop/cancel", post(desktop::cancel))
.route("/v1/auth/desktop/refresh", post(desktop::refresh))
.route("/v1/auth/desktop/revoke", post(desktop::revoke))
.layer(DefaultBodyLimit::max(4096))
.route(
"/v1/auth/desktop/profile",
post(desktop_avatar::mutate).layer(DefaultBodyLimit::max(1024)),
)
.route(
"/v1/auth/desktop/avatar",
post(desktop_avatar::mutate)
.delete(desktop_avatar::mutate)
.layer(DefaultBodyLimit::max(crate::avatar::MAX_UPLOAD_BYTES)),
)
.route(
"/v1/servers",
get(directory::list)
.post(directory::create)
.layer(DefaultBodyLimit::max(4096)),
)
.route("/v1/servers/{id}", axum::routing::delete(directory::remove))
.route("/v1/auth/github/start", get(start))
.route("/v1/auth/github/callback", get(callback))
.route(
@ -38,7 +68,24 @@ pub fn router() -> Router<Arc<HubState>> {
"/v1/account/avatar",
post(avatar::upload).delete(avatar::remove),
)
.route(
"/v1/account/onboarding",
post(onboarding::decide).layer(DefaultBodyLimit::max(1024)),
)
.route(
"/v1/account/display-name",
post(onboarding::rename).layer(DefaultBodyLimit::max(1024)),
)
.route(
"/v1/avatars/default-v2/{user_id}",
get(avatar::generated_v2),
)
.route("/v1/avatars/{id}", get(avatar::serve))
.route("/v1/avatars/default/{user_id}", get(avatar::generated))
.route(
"/v1/account/profile",
put(profile::update).layer(DefaultBodyLimit::max(1024)),
)
}
fn failure(status: StatusCode, code: &'static str) -> Response {
(status, Json(json!({"error":code}))).into_response()
@ -323,8 +370,13 @@ async fn email_verify(
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
};
drop_old_session(auth, &headers).await;
let mut response =
Json(json!({"authenticated":true,"user":user,"csrf_token":csrf})).into_response();
let Ok(pending) = store::onboarding_pending(&auth.pool, &user.user_id).await else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
};
let mut response = Json(
json!({"authenticated":true,"user":user,"csrf_token":csrf,"onboarding_pending":pending}),
)
.into_response();
set_cookie(&mut response, SESSION, token, store::SESSION_TTL);
set_cookie(&mut response, EMAIL_BROWSER, String::new(), 0);
response
@ -333,7 +385,11 @@ async fn session(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Resp
if let Some(token) = cookie(&headers, SESSION) {
match store::get_session(&state.auth.pool, &token).await {
Ok(Some((user, csrf))) => {
return Json(json!({"authenticated":true,"user":user,"csrf_token":csrf}))
let Ok(pending) = store::onboarding_pending(&state.auth.pool, &user.user_id).await
else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
};
return Json(json!({"authenticated":true,"user":user,"csrf_token":csrf,"onboarding_pending":pending}))
.into_response();
}
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),

View file

@ -51,11 +51,14 @@ pub(super) async fn upload(
let Ok(data) = to_bytes(body, avatar::MAX_UPLOAD_BYTES).await else {
return failure(StatusCode::PAYLOAD_TOO_LARGE, "too_large");
};
let Ok(permit) = state.auth.avatar_decoding.try_acquire() else {
let Ok(permit) = state.auth.avatar_decoding.clone().try_acquire_owned() else {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
};
let processed = tokio::task::spawn_blocking(move || avatar::normalize(&declared, &data)).await;
drop(permit);
let processed = tokio::task::spawn_blocking(move || {
let _permit = permit;
avatar::normalize(&declared, &data)
})
.await;
let png = match processed {
Ok(Ok(png)) => png,
Ok(Err(avatar::AvatarError::UnsupportedType)) => {
@ -79,7 +82,7 @@ pub(super) async fn upload(
}
/// `DELETE /v1/account/avatar`: drops the own photo; the answer carries the avatar now in
/// effect (the provider's, or null for the default).
/// effect (the generated VNOX default).
pub(super) async fn remove(State(state): State<Arc<HubState>>, headers: HeaderMap) -> Response {
let user = match authorized(&state, &headers).await {
Ok((user, _)) => user,
@ -92,10 +95,7 @@ pub(super) async fn remove(State(state): State<Arc<HubState>>, headers: HeaderMa
if avatar::remove(pool, &user.user_id).await.is_err() {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
}
match avatar::provider_url(pool, &user.user_id).await {
Ok(url) => Json(json!({"avatar_url": url})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
Json(json!({"avatar_url": avatar::default_url(&user.user_id)})).into_response()
}
/// `GET /v1/avatars/<id>`: public and immutable, because the id is the content hash.
@ -130,3 +130,59 @@ pub(super) async fn serve(State(state): State<Arc<HubState>>, Path(id): Path<Str
}
response
}
// Public rendering has its own bounded budget and cannot queue unlimited blocking jobs
// or consume the authenticated upload decode slots.
static DEFAULT_RENDERING: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(4);
/// Generated public avatar for a canonical UUID; never queries account existence.
pub(super) async fn generated(Path(user_id): Path<String>) -> Response {
generated_response(user_id, false).await
}
pub(super) async fn generated_v2(Path(user_id): Path<String>) -> Response {
generated_response(user_id, true).await
}
async fn generated_response(user_id: String, version_two: bool) -> Response {
if !uuid::Uuid::parse_str(&user_id).is_ok_and(|id| id.to_string() == user_id) {
return failure(StatusCode::NOT_FOUND, "not_found");
}
let Ok(permit) = DEFAULT_RENDERING.try_acquire() else {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
};
let png = match tokio::task::spawn_blocking(move || {
// Keep the slot while rendering even if the requesting browser disconnects.
let _permit = permit;
if version_two {
avatar::default_v2_png(&user_id)
} else {
avatar::default_png(&user_id)
}
})
.await
{
Ok(Ok(png)) => png,
_ => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
};
let id = avatar::content_id(&png);
let mut response = png.into_response();
let headers = response.headers_mut();
headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("image/png"));
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("public, max-age=31536000, immutable"),
);
headers.insert(
header::CONTENT_SECURITY_POLICY,
HeaderValue::from_static("default-src 'none'; sandbox; frame-ancestors 'none'"),
);
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_static("inline; filename=\"avatar.png\""),
);
if let Ok(value) = HeaderValue::from_str(&format!("\"{id}\"")) {
headers.insert(header::ETAG, value);
}
response
}

View file

@ -0,0 +1,287 @@
//! Browser-approved desktop enrollment. All bearer secrets stay outside browser URLs.
use super::{authorized, failure};
use crate::{auth::store, web::HubState};
use axum::{
Json,
extract::{Query, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::sync::Arc;
const REQUEST_TTL: i64 = 600;
const DEVICE_TTL: i64 = 30 * 24 * 3600;
const PROOF_TTL: i64 = 600;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Start {
public_key: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Code {
code: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Device {
device_secret: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Refresh {
refresh_secret: String,
}
pub(super) fn secret_shape(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}
fn available(state: &HubState, headers: &HeaderMap) -> bool {
state.auth.allow_directory_read(&super::client_ip(headers))
}
async fn cleanup(state: &HubState) -> anyhow::Result<()> {
sqlx::query("DELETE FROM desktop_authorizations WHERE expires_at<=?")
.bind(store::now())
.execute(&state.database)
.await?;
sqlx::query("DELETE FROM desktop_devices WHERE expires_at<=?")
.bind(store::now())
.execute(&state.database)
.await?;
Ok(())
}
pub(super) async fn start(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
Json(body): Json<Start>,
) -> Response {
if !available(&state, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let valid_key = hex::decode(&body.public_key)
.ok()
.and_then(|b| <[u8; 32]>::try_from(b).ok())
.and_then(|b| ed25519_dalek::VerifyingKey::from_bytes(&b).ok());
if !secret_shape(&body.public_key) || valid_key.is_none() {
return failure(StatusCode::BAD_REQUEST, "invalid_public_key");
}
if cleanup(&state).await.is_err() {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
}
let device_secret = store::token();
let code = store::token();
let expires_at = store::now() + REQUEST_TTL;
// The SQL capacity guard and insert are atomic even across concurrent requests.
let result=sqlx::query("INSERT INTO desktop_authorizations(device_hash,code_hash,public_key,expires_at) SELECT ?,?,?,? WHERE (SELECT COUNT(*) FROM desktop_authorizations)<4096")
.bind(store::hash(&device_secret)).bind(store::hash(&code)).bind(&body.public_key).bind(expires_at).execute(&state.database).await;
if !matches!(result,Ok(r) if r.rows_affected()==1) {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");
}
let mut uri = state.auth.origin.join("desktop").expect("fixed path");
uri.query_pairs_mut().append_pair("code", &code);
Json(json!({"device_secret":device_secret,"user_code":code,"verification_uri":uri,"expires_at":expires_at,"interval":5})).into_response()
}
pub(super) async fn request(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
Query(body): Query<Code>,
) -> Response {
if !available(&state, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
if !secret_shape(&body.code) {
return failure(StatusCode::BAD_REQUEST, "invalid_code");
}
let row: Result<Option<(String,i64,bool)>,_>=sqlx::query_as("SELECT public_key,expires_at,user_id IS NOT NULL FROM desktop_authorizations WHERE code_hash=? AND expires_at>?")
.bind(store::hash(&body.code)).bind(store::now()).fetch_optional(&state.database).await;
match row {
Ok(Some((public_key, expires_at, approved))) => {
Json(json!({"public_key":public_key,"expires_at":expires_at,"approved":approved}))
.into_response()
}
Ok(None) => failure(StatusCode::GONE, "request_expired"),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
pub(super) async fn approve(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
Json(body): Json<Code>,
) -> Response {
let user = match authorized(&state, &headers).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !available(&state, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
if !secret_shape(&body.code) {
return failure(StatusCode::BAD_REQUEST, "invalid_code");
}
// Approval cannot replace an account already bound to this request.
match sqlx::query("UPDATE desktop_authorizations SET user_id=? WHERE code_hash=? AND expires_at>? AND user_id IS NULL")
.bind(user.user_id).bind(store::hash(&body.code)).bind(store::now()).execute(&state.database).await {
Ok(r) if r.rows_affected()==1=>Json(json!({"approved":true})).into_response(),
Ok(_)=>failure(StatusCode::GONE,"request_expired"),
Err(_)=>failure(StatusCode::SERVICE_UNAVAILABLE,"try_later"),
}
}
#[derive(Serialize)]
struct Claims<'a> {
version: u32,
issuer: String,
subject: &'a str,
public_key: &'a str,
issued_at: i64,
expires_at: i64,
audience: &'static str,
display_name: String,
avatar_url: Option<String>,
}
async fn proof(state: &HubState, user: &str, key: &str) -> anyhow::Result<serde_json::Value> {
let now = store::now();
let profile = account(state, user).await?;
let claims = serde_json::to_vec(&Claims {
display_name: profile.display_name,
avatar_url: profile.avatar_url,
version: 1,
issuer: state.issuer.id.to_string(),
subject: user,
public_key: key,
issued_at: now,
expires_at: now + PROOF_TTL,
audience: "vnox-gateway",
})?;
Ok(
json!({"claims":hex::encode(&claims),"signature":hex::encode(state.issuer.sign_account_claims(&claims))}),
)
}
#[derive(Serialize, sqlx::FromRow)]
pub(super) struct DesktopUser {
user_id: String,
handle: String,
display_name: String,
avatar_url: Option<String>,
}
pub(super) async fn account(state: &HubState, user: &str) -> anyhow::Result<DesktopUser> {
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,'/v1/avatars/default-v2/'||a.user_id) AS avatar_url FROM accounts a LEFT JOIN avatars v ON v.user_id=a.user_id WHERE a.user_id=?").bind(user).fetch_one(&state.database).await?)
}
pub(super) async fn poll(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
Json(body): Json<Device>,
) -> Response {
if !available(&state, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
if !secret_shape(&body.device_secret) {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
}
let result:anyhow::Result<Option<serde_json::Value>>=async {
let mut tx=state.database.begin().await?;
let row:Option<(String,Option<String>,i64)>=sqlx::query_as("SELECT public_key,user_id,expires_at FROM desktop_authorizations WHERE device_hash=?")
.bind(store::hash(&body.device_secret)).fetch_optional(&mut *tx).await?;
let Some((key,user,expires))=row else {anyhow::bail!("expired")};
anyhow::ensure!(expires>store::now(),"expired");
let Some(user)=user else {return Ok(None)};
let removed=sqlx::query("DELETE FROM desktop_authorizations WHERE device_hash=?").bind(store::hash(&body.device_secret)).execute(&mut *tx).await?;
anyhow::ensure!(removed.rows_affected()==1,"consumed");
let refresh=store::token();
sqlx::query("INSERT INTO desktop_devices(refresh_hash,device_hash,public_key,user_id,created_at,expires_at) VALUES(?,?,?,?,?,?)")
.bind(store::hash(&refresh)).bind(store::hash(&body.device_secret)).bind(&key).bind(&user).bind(store::now()).bind(store::now()+DEVICE_TTL).execute(&mut *tx).await?;
let user_account:DesktopUser=sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,'/v1/avatars/default-v2/'||a.user_id) AS avatar_url FROM accounts a LEFT JOIN avatars v ON v.user_id=a.user_id WHERE a.user_id=?").bind(&user).fetch_one(&mut *tx).await?;
let result=json!({"account_proof":proof(&state,&user,&key).await?,"refresh_secret":refresh,"expires_at":store::now()+PROOF_TTL,"user":user_account});
tx.commit().await?;
Ok(Some(result))
}.await;
match result {
Ok(Some(value)) => Json(value).into_response(),
Ok(None) => (StatusCode::ACCEPTED, Json(json!({"status":"pending"}))).into_response(),
Err(_) => failure(StatusCode::GONE, "request_expired"),
}
}
pub(super) async fn cancel(
State(state): State<Arc<HubState>>,
Json(body): Json<Device>,
) -> Response {
if !secret_shape(&body.device_secret) {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
}
let result: anyhow::Result<()> = async {
let mut tx = state.database.begin().await?;
sqlx::query("DELETE FROM desktop_authorizations WHERE device_hash=?")
.bind(store::hash(&body.device_secret))
.execute(&mut *tx)
.await?;
// A concurrent successful poll may already have consumed the request. The
// pairing secret still revokes that enrollment, including a lost HTTP reply.
sqlx::query("DELETE FROM desktop_devices WHERE device_hash=?")
.bind(store::hash(&body.device_secret))
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}
.await;
match result {
Ok(()) => StatusCode::NO_CONTENT.into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
pub(super) async fn refresh(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
Json(body): Json<Refresh>,
) -> Response {
if !available(&state, &headers) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
if !secret_shape(&body.refresh_secret) {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
}
let row: Result<Option<(String, String)>, _> = sqlx::query_as(
"SELECT public_key,user_id FROM desktop_devices WHERE refresh_hash=? AND expires_at>?",
)
.bind(store::hash(&body.refresh_secret))
.bind(store::now())
.fetch_optional(&state.database)
.await;
let Ok(Some((key, user))) = row else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
};
let result:anyhow::Result<_>=async {Ok(json!({"account_proof":proof(&state,&user,&key).await?,"expires_at":store::now()+PROOF_TTL,"user":account(&state,&user).await?}))}.await;
match result {
Ok(value) => Json(value).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
pub(super) async fn revoke(
State(state): State<Arc<HubState>>,
Json(body): Json<Refresh>,
) -> Response {
if !secret_shape(&body.refresh_secret) {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
}
match sqlx::query("DELETE FROM desktop_devices WHERE refresh_hash=?")
.bind(store::hash(&body.refresh_secret))
.execute(&state.database)
.await
{
Ok(_) => StatusCode::NO_CONTENT.into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}

View file

@ -0,0 +1,177 @@
//! Desktop avatar mutations require an active enrollment and its device signature.
use super::{allowed_avatar, desktop, failure};
use crate::{auth::store, avatar, web::HubState};
use axum::{
Json,
body::{Body, to_bytes},
extract::{OriginalUri, State},
http::{HeaderMap, Method, StatusCode, header},
response::{IntoResponse, Response},
};
use ed25519_dalek::{Signature, VerifyingKey};
use sha2::{Digest, Sha256};
use std::sync::Arc;
const SIGN_CONTEXT: &[u8] = b"VNOX-CENTRAL-PROFILE-v1\0";
fn transcript(method: &str, path: &str, timestamp: &str, body: &[u8]) -> Vec<u8> {
let mut bytes = SIGN_CONTEXT.to_vec();
bytes.extend_from_slice(method.as_bytes());
bytes.push(0);
bytes.extend_from_slice(path.as_bytes());
bytes.push(0);
bytes.extend_from_slice(timestamp.as_bytes());
bytes.push(0);
bytes.extend_from_slice(&Sha256::digest(body));
bytes
}
fn field<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers.get(name)?.to_str().ok()
}
pub(super) async fn mutate(
State(state): State<Arc<HubState>>,
method: Method,
OriginalUri(uri): OriginalUri,
headers: HeaderMap,
body: Body,
) -> Response {
let profile = uri.path() == "/v1/auth/desktop/profile";
let Some(secret) = field(&headers, "authorization").and_then(|s| s.strip_prefix("Bearer "))
else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
};
let Some(public) = field(&headers, "x-vnox-public-key") else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
};
let Some(timestamp) = field(&headers, "x-vnox-timestamp") else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
};
let Some(signature) = field(&headers, "x-vnox-signature") else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
};
if !desktop::secret_shape(secret)
|| !desktop::secret_shape(public)
|| !timestamp
.parse::<i64>()
.is_ok_and(|time| store::now().abs_diff(time) <= 60)
{
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
}
let key = hex::decode(public)
.ok()
.and_then(|v| <[u8; 32]>::try_from(v).ok())
.and_then(|v| VerifyingKey::from_bytes(&v).ok());
let signature = hex::decode(signature)
.ok()
.and_then(|v| Signature::from_slice(&v).ok());
let (Some(key), Some(signature)) = (key, signature) else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
};
let refresh_hash = store::hash(secret);
let row: Result<Option<String>,_> = sqlx::query_scalar("SELECT user_id FROM desktop_devices WHERE refresh_hash=? AND public_key=? AND expires_at>?")
.bind(&refresh_hash).bind(public).bind(store::now()).fetch_optional(&state.database).await;
let Ok(Some(user)) = row else {
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
};
if !(if profile {
state.auth.allow_profile(&user, &super::client_ip(&headers))
} else {
allowed_avatar(&state.auth, &user, &headers)
}) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let Ok(bytes) = to_bytes(
body,
if profile {
1024
} else {
avatar::MAX_UPLOAD_BYTES
},
)
.await
else {
return failure(StatusCode::PAYLOAD_TOO_LARGE, "too_large");
};
if key
.verify_strict(
&transcript(method.as_str(), uri.path(), timestamp, &bytes),
&signature,
)
.is_err()
{
return failure(StatusCode::UNAUTHORIZED, "not_authenticated");
}
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Name {
display_name: String,
}
let display_name = if profile {
let Ok(name) = serde_json::from_slice::<Name>(&bytes) else {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
};
let Some(name) = normalize_name(&name.display_name) else {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_display_name");
};
Some(name.to_owned())
} else {
None
};
let png = if profile {
None
} else if method == Method::POST {
if field(&headers, header::CONTENT_TYPE.as_str()) != Some("image/png") {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported_type");
}
let Ok(permit) = state.auth.avatar_decoding.clone().try_acquire_owned() else {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
};
let result = tokio::task::spawn_blocking(move || {
let _permit = permit;
avatar::normalize("image/png", &bytes)
})
.await;
match result {
Ok(Ok(png)) => Some(png),
Ok(Err(avatar::AvatarError::UnsupportedType | avatar::AvatarError::TypeMismatch)) => {
return failure(StatusCode::UNSUPPORTED_MEDIA_TYPE, "unsupported_type");
}
Ok(Err(_)) => return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_image"),
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
} else {
if !bytes.is_empty() {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
}
None
};
// Recheck enrollment under the write transaction after expensive decoding. Revocation
// that committed first must prevent the mutation, not only its response.
let result: anyhow::Result<bool> = async {
let mut tx=state.database.begin().await?;
let valid: bool=sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM desktop_devices WHERE refresh_hash=? AND public_key=? AND user_id=? AND expires_at>?)")
.bind(&refresh_hash).bind(public).bind(&user).bind(store::now()).fetch_one(&mut *tx).await?;
if !valid {return Ok(false)}
if let Some(name)=display_name {
sqlx::query("UPDATE accounts SET display_name=? WHERE user_id=?").bind(name).bind(&user).execute(&mut *tx).await?;
} else if let Some(png)=png {
sqlx::query("INSERT INTO avatars(user_id,id,content_type,bytes,created_at) VALUES(?,?,?,?,?) ON CONFLICT(user_id) DO UPDATE SET id=excluded.id,content_type=excluded.content_type,bytes=excluded.bytes,created_at=excluded.created_at")
.bind(&user).bind(avatar::content_id(&png)).bind("image/png").bind(png).bind(store::now()).execute(&mut *tx).await?;
} else {sqlx::query("DELETE FROM avatars WHERE user_id=?").bind(&user).execute(&mut *tx).await?;}
tx.commit().await?; Ok(true)
}.await;
match result {
Ok(true) => match desktop::account(&state, &user).await {
Ok(user) => Json(serde_json::json!({"user":user})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
},
Ok(false) => failure(StatusCode::UNAUTHORIZED, "not_authenticated"),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
fn normalize_name(value: &str) -> Option<&str> {
if value.chars().any(|c| c.is_control() || matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) { return None; }
let name = value.trim();
(1..=64).contains(&name.chars().count()).then_some(name)
}

View file

@ -0,0 +1,241 @@
//! Unverified community submissions; never resolves or connects to submitted addresses.
use super::{authorized, client_ip, failure, store};
use crate::web::HubState;
use axum::{
Json,
extract::{FromRequest, Path, Query, Request, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
net::{IpAddr, SocketAddr},
sync::Arc,
};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Submission {
name: String,
address: String,
description: String,
}
#[derive(Serialize, sqlx::FromRow)]
struct Listing {
id: String,
name: String,
address: String,
description: String,
owner_id: String,
created_at: i64,
}
#[derive(Deserialize)]
pub(super) struct Page {
after: Option<String>,
}
fn text(value: &str, max: usize, empty: bool) -> Option<String> {
if value.chars().any(|c| c.is_control() || matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) { return None; }
let value = value.trim();
((empty || !value.is_empty()) && value.chars().count() <= max).then(|| value.to_owned())
}
fn public_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(ip) => {
let [a, b, c, _] = ip.octets();
!ip.is_private()
&& !ip.is_loopback()
&& !ip.is_link_local()
&& !ip.is_multicast()
&& a != 0
&& a < 240
&& !(a == 100 && (64..=127).contains(&b))
&& !(a == 192 && (b == 0 || (b == 88 && c == 99)))
&& !(a == 198 && (b == 18 || b == 19 || (b == 51 && c == 100)))
&& !(a == 203 && b == 0 && c == 113)
}
IpAddr::V6(ip) => ip
.to_ipv4_mapped()
.map(|v| public_ip(IpAddr::V4(v)))
.unwrap_or_else(|| {
let segments = ip.segments();
(segments[0] & 0xe000) == 0x2000
&& !(segments[0] == 0x2001 && segments[1] < 0x200)
&& !(segments[0] == 0x2001 && segments[1] == 0xdb8)
}),
}
}
fn address(value: &str) -> Option<String> {
if value.len() > 260
|| value
.bytes()
.any(|b| b.is_ascii_whitespace() || b.is_ascii_control())
{
return None;
}
if let Ok(mut socket) = value.parse::<SocketAddr>() {
if let IpAddr::V6(ip) = socket.ip()
&& let Some(ip) = ip.to_ipv4_mapped()
{
socket.set_ip(IpAddr::V4(ip));
}
return (socket.port() != 0 && public_ip(socket.ip())).then(|| socket.to_string());
}
let (host, port) = value.rsplit_once(':')?;
let port: u16 = port.parse().ok()?;
let host = host.strip_suffix('.').unwrap_or(host).to_ascii_lowercase();
if port == 0 || host.len() > 253 || !host.contains('.') || host.parse::<IpAddr>().is_ok() {
return None;
}
if !host.split('.').all(|part| {
!part.is_empty()
&& part.len() <= 63
&& part.as_bytes()[0].is_ascii_alphanumeric()
&& part.as_bytes()[part.len() - 1].is_ascii_alphanumeric()
&& part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
}) {
return None;
}
let tld = host.rsplit('.').next()?;
if !tld.bytes().any(|b| b.is_ascii_alphabetic())
|| matches!(
tld,
"localhost" | "local" | "internal" | "test" | "invalid" | "example" | "onion"
)
{
return None;
}
Some(format!("{host}:{port}"))
}
pub(super) async fn list(
State(state): State<Arc<HubState>>,
headers: HeaderMap,
page: Result<Query<Page>, axum::extract::rejection::QueryRejection>,
) -> Response {
if !state.auth.allow_directory_read(&client_ip(&headers)) {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let Ok(Query(page)) = page else {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
};
if page
.after
.as_ref()
.is_some_and(|id| Uuid::parse_str(id).is_err())
{
return failure(StatusCode::BAD_REQUEST, "invalid_request");
}
match sqlx::query_as::<_, Listing>(
"SELECT * FROM community_servers WHERE id > ? ORDER BY id LIMIT 100",
)
.bind(page.after.unwrap_or_default())
.fetch_all(&state.auth.pool)
.await
{
Ok(servers) => Json(json!({"servers":servers})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
pub(super) async fn create(State(state): State<Arc<HubState>>, request: Request) -> Response {
let user = match authorized(&state, request.headers()).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !state
.auth
.allow_directory(&user.user_id, &client_ip(request.headers()))
{
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let body = match Json::<Submission>::from_request(request, &state).await {
Ok(Json(body)) => body,
Err(e) => {
return failure(
if e.status() == StatusCode::PAYLOAD_TOO_LARGE {
e.status()
} else {
StatusCode::BAD_REQUEST
},
"invalid_request",
);
}
};
let (Some(name), Some(address), Some(description)) = (
text(&body.name, 80, false),
address(&body.address),
text(&body.description, 500, true),
) else {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_server");
};
let id = Uuid::new_v4().to_string();
// The conditional INSERT makes the account cap atomic with concurrent submissions.
let result = sqlx::query_as::<_, Listing>("INSERT INTO community_servers(id,name,address,description,owner_id,created_at) SELECT ?,?,?,?,?,? WHERE (SELECT COUNT(*) FROM community_servers WHERE owner_id=?) < 10 RETURNING *")
.bind(id).bind(name).bind(address).bind(description).bind(&user.user_id).bind(store::now()).bind(&user.user_id).fetch_optional(&state.auth.pool).await;
match result {
Ok(Some(server)) => (StatusCode::CREATED, Json(json!({"server":server}))).into_response(),
Ok(None) => failure(StatusCode::CONFLICT, "listing_limit"),
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
failure(StatusCode::CONFLICT, "address_taken")
}
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
pub(super) async fn remove(
State(state): State<Arc<HubState>>,
Path(id): Path<String>,
headers: HeaderMap,
) -> Response {
let user = match authorized(&state, &headers).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !state
.auth
.allow_directory(&user.user_id, &client_ip(&headers))
{
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
match sqlx::query("DELETE FROM community_servers WHERE id=? AND owner_id=?")
.bind(id)
.bind(user.user_id)
.execute(&state.auth.pool)
.await
{
Ok(result) if result.rows_affected() == 1 => StatusCode::NO_CONTENT.into_response(),
Ok(_) => failure(StatusCode::NOT_FOUND, "server_not_found"),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalizes_addresses_and_rejects_unsafe_inputs() {
assert_eq!(
address("VOICE.Example.COM.:07600"),
Some("voice.example.com:7600".into())
);
assert_eq!(address("8.8.8.8:7600"), Some("8.8.8.8:7600".into()));
assert_eq!(address("[::ffff:8.8.8.8]:7600"), address("8.8.8.8:7600"));
for bad in [
"127.0.0.1:7600",
"10.1.1.1:7600",
"[::1]:7600",
"[::ffff:127.0.0.1]:7600",
"voice.local:7600",
"foo:7600",
"foo.com:0",
"foo.com:65536",
"https://foo.com:7600",
"x@foo.com:7600",
"foo.com/path:7600",
"foo.com:7600\n",
"1.2.3.999:7600",
] {
assert_eq!(address(bad), None, "{bad}");
}
assert_eq!(text("line\nbreak", 80, false), None);
assert_eq!(text(&"x".repeat(81), 80, false), None);
}
}

View file

@ -0,0 +1,93 @@
//! Profile-name decisions do not select or change the unique public handle.
use super::{authorized, client_ip, failure, store};
use crate::web::HubState;
use axum::{
Json,
extract::{FromRequest, Request, State},
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use serde_json::json;
use std::sync::Arc;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Choice {
decision: Decision,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum Decision {
Rename,
Later,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Name {
display_name: String,
}
pub(super) async fn decide(State(state): State<Arc<HubState>>, request: Request) -> Response {
let user = match authorized(&state, request.headers()).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !state
.auth
.allow_profile(&user.user_id, &client_ip(request.headers()))
{
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let Ok(Json(choice)) = Json::<Choice>::from_request(request, &state).await else {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
};
let decision = match choice.decision {
Decision::Rename => "rename",
Decision::Later => "later",
};
match sqlx::query("UPDATE account_onboarding SET decided_at=?,decision=? WHERE user_id=? AND decided_at IS NULL")
.bind(store::now()).bind(decision).bind(&user.user_id).execute(&state.database).await {
Ok(_) => Json(json!({"onboarding_pending":false})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
pub(super) async fn rename(State(state): State<Arc<HubState>>, request: Request) -> Response {
let user = match authorized(&state, request.headers()).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !state
.auth
.allow_profile(&user.user_id, &client_ip(request.headers()))
{
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
let Ok(Json(name)) = Json::<Name>::from_request(request, &state).await else {
return failure(StatusCode::BAD_REQUEST, "invalid_request");
};
let Some(name) = normalize_name(&name.display_name) else {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_display_name");
};
// An explicit name save also resolves the first-registration prompt. Handle and
// pending handle-selection semantics are independent and never touched here.
let result: anyhow::Result<()> = async {
let mut tx = state.database.begin().await?;
sqlx::query("UPDATE accounts SET display_name=? WHERE user_id=?")
.bind(name).bind(&user.user_id).execute(&mut *tx).await?;
sqlx::query("UPDATE account_onboarding SET decided_at=?,decision='rename' WHERE user_id=? AND decided_at IS NULL")
.bind(store::now()).bind(&user.user_id).execute(&mut *tx).await?;
tx.commit().await?;
Ok(())
}.await;
match result {
Ok(()) => Json(json!({"display_name":name,"onboarding_pending":false})).into_response(),
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}
fn normalize_name(value: &str) -> Option<&str> {
if value.chars().any(|c| c.is_control() || matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) { return None; }
let name = value.trim();
(1..=64).contains(&name.chars().count()).then_some(name)
}

View file

@ -0,0 +1,106 @@
//! Owner-selected profile; provider logins never select or overwrite a handle.
use super::{authorized, client_ip, failure, store};
use crate::web::HubState;
use axum::{
Json,
extract::{FromRequest, Request, State},
http::StatusCode,
response::{IntoResponse, Response},
};
use serde::Deserialize;
use serde_json::json;
use std::sync::Arc;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Profile {
handle: String,
display_name: String,
}
fn normalize_handle(value: &str) -> Option<String> {
let handle = value.trim().to_ascii_lowercase();
if !(3..=24).contains(&handle.len())
|| !handle.as_bytes()[0].is_ascii_lowercase()
|| !handle
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_')
|| handle.starts_with("u_")
|| matches!(
handle.as_str(),
"admin"
| "administrator"
| "root"
| "system"
| "support"
| "vnox"
| "central"
| "moderator"
| "everyone"
| "here"
)
{
return None;
}
Some(handle)
}
fn normalize_name(value: &str) -> Option<&str> {
// Reject controls before trimming, so line breaks cannot silently disappear.
if value.chars().any(|c| c.is_control() || matches!(c, '\u{061c}' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')) {
return None;
}
let name = value.trim();
(1..=64).contains(&name.chars().count()).then_some(name)
}
pub(super) async fn update(State(state): State<Arc<HubState>>, request: Request) -> Response {
let user = match authorized(&state, request.headers()).await {
Ok((user, _)) => user,
Err(response) => return *response,
};
if !state
.auth
.allow_profile(&user.user_id, &client_ip(request.headers()))
{
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
// Extract only after authorization, including for oversized or invalid bodies.
let body = match Json::<Profile>::from_request(request, &state).await {
Ok(Json(body)) => body,
Err(error) => {
return failure(
if error.status() == StatusCode::PAYLOAD_TOO_LARGE {
StatusCode::PAYLOAD_TOO_LARGE
} else {
StatusCode::BAD_REQUEST
},
"invalid_request",
);
}
};
let Some(handle) = normalize_handle(&body.handle) else {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_handle");
};
let Some(name) = normalize_name(&body.display_name) else {
return failure(StatusCode::UNPROCESSABLE_ENTITY, "invalid_display_name");
};
// One statement serializes first selection, uniqueness and subsequent edits. Never
// authorize a handle change using the potentially stale session snapshot above.
let result = sqlx::query_as::<_, store::User>(
"UPDATE accounts SET handle=?,display_name=?,profile_complete=1 \
WHERE user_id=? AND (profile_complete=0 OR handle=?) \
RETURNING user_id,handle,display_name,profile_complete,\
COALESCE((SELECT '/v1/avatars/'||id FROM avatars WHERE user_id=accounts.user_id),'/v1/avatars/default-v2/'||accounts.user_id) AS avatar_url",
)
.bind(&handle).bind(name).bind(&user.user_id).bind(&handle)
.fetch_optional(&state.auth.pool).await;
match result {
Ok(Some(user)) => Json(json!({"user":user})).into_response(),
Ok(None) => failure(StatusCode::CONFLICT, "handle_locked"),
Err(sqlx::Error::Database(error)) if error.is_unique_violation() => {
failure(StatusCode::CONFLICT, "handle_taken")
}
Err(_) => failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
}
}

View file

@ -14,6 +14,7 @@ pub struct User {
pub handle: String,
pub display_name: String,
pub avatar_url: Option<String>,
pub profile_complete: bool,
}
pub fn hash(value: &str) -> String {
@ -79,40 +80,21 @@ pub async fn consume_attempt(
}
pub async fn upsert_identity(pool: &SqlitePool, profile: &GitHubProfile) -> anyhow::Result<User> {
let name = profile
.name
.as_deref()
.unwrap_or(&profile.login)
.chars()
.take(100)
.collect::<String>();
let avatar = profile.avatar_url.as_deref().filter(|value| {
url::Url::parse(value).is_ok_and(|url| {
url.scheme() == "https"
&& url.host_str() == Some("avatars.githubusercontent.com")
&& url.username().is_empty()
&& url.password().is_none()
})
});
upsert_external(pool, "github.com", &profile.id.to_string(), &name, avatar).await
// Provider names and photos never select the public VNOX profile.
upsert_external(pool, "github.com", &profile.id.to_string()).await
}
/// Account for a verified, normalized email address. The display name is deliberately
/// neutral: the local part of an address must never become a public profile string.
pub async fn upsert_email_identity(pool: &SqlitePool, email: &str) -> anyhow::Result<User> {
upsert_external(pool, "email", email, "Vnox user", None).await
upsert_external(pool, "email", email).await
}
async fn upsert_external(
pool: &SqlitePool,
provider: &str,
subject: &str,
name: &str,
avatar: Option<&str>,
) -> anyhow::Result<User> {
async fn upsert_external(pool: &SqlitePool, provider: &str, subject: &str) -> anyhow::Result<User> {
if let Some(user) = lookup_identity(pool, provider, subject).await? {
return Ok(user);
}
let name = super::nicknames::generate();
let id = Uuid::new_v4();
// Generated stable handle avoids claiming a privileged/reused handle from another provider.
let handle = format!("u_{}", id.simple());
@ -124,9 +106,13 @@ async fn upsert_external(
.bind(handle)
.bind(now())
.bind(name)
.bind(avatar)
.bind(None::<&str>)
.execute(&mut *transaction)
.await?;
sqlx::query("INSERT INTO account_onboarding(user_id) VALUES(?)")
.bind(id.to_string())
.execute(&mut *transaction)
.await?;
let inserted = sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES(?,?,?,?) ON CONFLICT(provider,subject) DO NOTHING")
.bind(provider).bind(subject).bind(id.to_string()).bind(now()).execute(&mut *transaction).await?;
if inserted.rows_affected() == 0 {
@ -144,8 +130,8 @@ async fn lookup_identity(
provider: &str,
subject: &str,
) -> anyhow::Result<Option<User>> {
// The own avatar (same-origin path) wins over the provider URL kept on the account.
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url FROM accounts a LEFT JOIN avatars v ON v.user_id=a.user_id JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
// Only same-origin own or generated avatars are exposed, including for legacy accounts.
Ok(sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.profile_complete,COALESCE('/v1/avatars/'||v.id,'/v1/avatars/default-v2/'||a.user_id) AS avatar_url FROM accounts a LEFT JOIN avatars v ON v.user_id=a.user_id JOIN external_identities e ON e.user_id=a.user_id WHERE e.provider=? AND e.subject=?")
.bind(provider).bind(subject).fetch_optional(pool).await?)
}
@ -168,8 +154,9 @@ pub async fn get_session(
display_name: String,
avatar_url: Option<String>,
csrf_token: String,
profile_complete: bool,
}
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,COALESCE('/v1/avatars/'||v.id,a.avatar_url) AS avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id LEFT JOIN avatars v ON v.user_id=a.user_id WHERE s.token_hash=? AND s.expires_at>?")
let row: Option<Row> = sqlx::query_as("SELECT a.user_id,a.handle,a.display_name,a.profile_complete,COALESCE('/v1/avatars/'||v.id,'/v1/avatars/default-v2/'||a.user_id) AS avatar_url,s.csrf_token FROM web_sessions s JOIN accounts a ON a.user_id=s.user_id LEFT JOIN avatars v ON v.user_id=a.user_id WHERE s.token_hash=? AND s.expires_at>?")
.bind(hash(session)).bind(now()).fetch_optional(pool).await?;
Ok(row.map(|r| {
(
@ -178,8 +165,19 @@ pub async fn get_session(
handle: r.handle,
display_name: r.display_name,
avatar_url: r.avatar_url,
profile_complete: r.profile_complete,
},
r.csrf_token,
)
}))
}
/// Only accounts created after onboarding was introduced have pending rows.
pub async fn onboarding_pending(pool: &SqlitePool, user_id: &str) -> anyhow::Result<bool> {
Ok(sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM account_onboarding WHERE user_id=? AND decided_at IS NULL)",
)
.bind(user_id)
.fetch_one(pool)
.await?)
}

View file

@ -6,6 +6,8 @@
//! resized and written again as a fresh PNG. A fresh PNG carries no EXIF, GPS, ICC, text or
//! other ancillary chunks from the source, so metadata cannot survive.
mod monsters;
use std::io::Cursor;
use image::{
@ -149,17 +151,87 @@ pub async fn fetch(pool: &SqlitePool, id: &str) -> anyhow::Result<Option<(String
)
}
/// The provider avatar kept on the account, if any.
pub async fn provider_url(pool: &SqlitePool, user_id: &str) -> anyhow::Result<Option<String>> {
Ok(
sqlx::query_scalar("SELECT avatar_url FROM accounts WHERE user_id=?")
.bind(user_id)
.fetch_optional(pool)
.await?
.flatten(),
)
/// Same-origin default, derived only from a public account identifier. No provider image.
pub fn default_url(user_id: &str) -> String {
format!("/v1/avatars/default-v2/{user_id}")
}
/// A bounded, deterministic mirrored mosaic. The endpoint never looks up an account,
/// so it cannot reveal whether an identifier is registered. Keep this algorithm stable:
/// generated images are immutable and may be cached by browsers.
pub fn default_png(user_id: &str) -> Result<Vec<u8>, AvatarError> {
let digest = Sha256::digest(format!("vnox-default-avatar-v1:{user_id}"));
let foreground = image::Rgb([
128 + digest[0] / 2,
128 + digest[1] / 2,
128 + digest[2] / 2,
]);
let mut pixels =
image::RgbImage::from_pixel(OUTPUT_SIDE, OUTPUT_SIDE, image::Rgb([35, 35, 37]));
for y in 0..5_u32 {
for x in 0..3_u32 {
if digest[(3 + y * 3 + x) as usize] & 1 == 0 {
continue;
}
for mirrored in [x, 4 - x] {
for py in 28 + y * 40..28 + (y + 1) * 40 {
for px in 28 + mirrored * 40..28 + (mirrored + 1) * 40 {
pixels.put_pixel(px, py, foreground);
}
}
}
}
}
let mut out = Vec::new();
PngEncoder::new(&mut out)
.write_image(
pixels.as_raw(),
OUTPUT_SIDE,
OUTPUT_SIDE,
image::ExtendedColorType::Rgb8,
)
.map_err(|_| AvatarError::Invalid)?;
Ok(out)
}
/// Versioned original pixel monsters. Keep v1 rendering unchanged for immutable cached URLs.
pub fn default_v2_png(user_id: &str) -> Result<Vec<u8>, AvatarError> {
let pixels = monsters::render(user_id);
let mut output = Vec::new();
PngEncoder::new(&mut output)
.write_image(
pixels.as_raw(),
OUTPUT_SIDE,
OUTPUT_SIDE,
image::ExtendedColorType::Rgb8,
)
.map_err(|_| AvatarError::Invalid)?;
Ok(output)
}
pub fn url_path(id: &str) -> String {
format!("/v1/avatars/{id}")
}
#[cfg(test)]
mod generated_v2_tests {
use super::*;
#[test]
fn monsters_are_stable_bounded_distinct_and_preserve_the_old_renderer() {
let id = "11111111-1111-4111-8111-111111111111";
let png = default_v2_png(id).unwrap();
assert_eq!(png, default_v2_png(id).unwrap());
assert_ne!(png, default_png(id).unwrap());
let image = image::load_from_memory(&png).unwrap();
assert_eq!((image.width(), image.height()), (256, 256));
assert!(png.len() < 16 * 1024);
let variants: std::collections::HashSet<_> = (1..=64)
.map(|index| {
content_id(
&default_v2_png(&format!("00000000-0000-4000-8000-{index:012x}")).unwrap(),
)
})
.collect();
assert_eq!(variants.len(), 64);
}
}

157
hub/src/avatar/monsters.rs Normal file
View file

@ -0,0 +1,157 @@
//! Original procedural pixel characters; no external artwork or account lookup.
use image::{Rgb, RgbImage};
use sha2::{Digest, Sha256};
const SIZE: u32 = 32;
const INK: [u8; 3] = [27, 31, 43];
const WHITE: [u8; 3] = [255, 249, 237];
const PALETTES: [([u8; 3], [u8; 3]); 10] = [
([29, 38, 49], [111, 213, 211]),
([40, 31, 49], [201, 154, 241]),
([33, 41, 36], [165, 218, 128]),
([43, 34, 32], [246, 179, 113]),
([36, 34, 49], [143, 180, 245]),
([45, 31, 40], [240, 150, 187]),
([38, 39, 29], [230, 216, 122]),
([28, 42, 43], [123, 218, 177]),
([43, 31, 34], [239, 139, 122]),
([30, 35, 48], [176, 182, 242]),
];
fn rect(image: &mut RgbImage, x: i32, y: i32, w: i32, h: i32, color: [u8; 3]) {
for py in y.max(0)..(y + h).min(SIZE as i32) {
for px in x.max(0)..(x + w).min(SIZE as i32) {
image.put_pixel(px as u32, py as u32, Rgb(color));
}
}
}
fn shade(color: [u8; 3], factor: u16) -> [u8; 3] {
color.map(|channel| (u16::from(channel) * factor / 100).min(255) as u8)
}
fn eye(image: &mut RgbImage, x: i32, y: i32, size: i32, gaze: i32) {
rect(image, x - 1, y, size + 2, size, INK);
rect(image, x, y - 1, size, size + 2, INK);
rect(image, x, y, size, size, WHITE);
let pupil = if size >= 7 { 3 } else { 2 };
let center = (size - pupil) / 2;
rect(
image,
x + (center + gaze).clamp(0, size - pupil),
y + center,
pupil,
pupil + 1,
INK,
);
}
/// 32 logical pixels enlarged with nearest-neighbor so small avatars retain crisp features.
pub(super) fn render(user_id: &str) -> RgbImage {
let seed = Sha256::digest(format!("vnox-pixel-monster-v2:{user_id}"));
let (background, body) = PALETTES[seed[0] as usize % PALETTES.len()];
let dark = shade(body, 69);
let light = shade(body, 115);
let mut image = RgbImage::from_pixel(SIZE, SIZE, Rgb(background));
// A quiet backdrop and ground shadow keep the silhouette legible inside a round crop.
rect(&mut image, 7, 6, 18, 20, shade(background, 120));
rect(&mut image, 9, 28, 14, 1, shade(background, 65));
let half = 7 + i32::from(seed[1] % 3);
let left = 16 - half;
let top = 10 + i32::from(seed[2] % 2);
let bottom = 25;
// Feet, hands, then the body: overlapping pixels create simple original silhouettes.
let foot = i32::from(seed[3] % 2);
rect(&mut image, 10 - foot, 24, 4, 4, dark);
rect(&mut image, 18 + foot, 24, 4, 4, dark);
rect(
&mut image,
left - 3,
18,
4,
4 + i32::from(seed[4] % 2),
dark,
);
rect(
&mut image,
16 + half - 1,
18,
4,
4 + i32::from(seed[4] % 2),
dark,
);
for y in top..bottom {
let cut = if y == top {
3
} else if y == top + 1 || y == bottom - 1 {
1
} else {
0
};
rect(&mut image, left + cut, y, half * 2 - cut * 2, 1, body);
if y > top + 2 && y < bottom - 1 {
rect(&mut image, 16 + half - 2, y, 2, 1, dark);
}
}
match seed[5] % 4 {
0 => {
// Two soft horns.
for x in [left + 2, 16 + half - 5] {
rect(&mut image, x, top - 3, 3, 5, dark);
rect(&mut image, x + 1, top - 4, 2, 3, WHITE);
}
}
1 => {
// A single offset antenna.
let x = 13 + i32::from(seed[6] % 5);
rect(&mut image, x, top - 4, 2, 5, dark);
rect(&mut image, x - 1, top - 6, 4, 3, light);
}
2 => {
// Broad folded ears.
rect(&mut image, left - 2, top, 4, 6, dark);
rect(&mut image, 16 + half - 2, top, 4, 6, dark);
rect(&mut image, left - 1, top + 1, 2, 3, light);
rect(&mut image, 16 + half - 1, top + 1, 2, 3, light);
}
_ => {
// A three-pixel tuft.
for (x, h) in [(13, 3), (16, 5), (19, 2)] {
rect(&mut image, x, top - h, 2, h + 1, dark);
}
}
}
let gaze = i32::from(seed[7] % 3) - 1;
if seed[8] % 4 == 0 {
eye(&mut image, 12, 13, 8, gaze);
} else {
eye(&mut image, 10, 14, 5, gaze);
eye(&mut image, 18, 14, 5, gaze);
if seed[9] & 1 == 0 {
rect(&mut image, 10, 12, 4, 1, dark);
rect(&mut image, 19, 12, 4, 1, dark);
}
}
rect(&mut image, 9, 21, 2, 1, light);
rect(&mut image, 23, 21, 2, 1, light);
match seed[10] % 3 {
0 => {
rect(&mut image, 13, 22, 7, 2, INK);
rect(&mut image, 14, 24, 5, 1, INK);
rect(&mut image, 14, 22, 2, 1, WHITE);
}
1 => {
rect(&mut image, 14, 22, 5, 2, INK);
rect(&mut image, 16, 23, 2, 1, [244, 130, 154]);
}
_ => {
rect(&mut image, 13, 22, 2, 1, INK);
rect(&mut image, 18, 22, 2, 1, INK);
rect(&mut image, 15, 23, 3, 1, INK);
}
}
image::imageops::resize(
&image,
super::OUTPUT_SIDE,
super::OUTPUT_SIDE,
image::imageops::FilterType::Nearest,
)
}

View file

@ -1,7 +1,7 @@
use std::{fs::OpenOptions, io::Write, path::Path};
use anyhow::{Context, Result, bail};
use ed25519_dalek::SigningKey;
use ed25519_dalek::{Signer, SigningKey};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@ -16,11 +16,19 @@ struct StoredIdentity {
/// Stable issuer identity. Only its public projection is exposed through HTTP.
pub struct Issuer {
signing_key: SigningKey,
pub id: Uuid,
pub public_key: String,
}
impl Issuer {
/// Sign an account admission claim with the stable private issuer key.
pub fn sign_account_claims(&self, claims: &[u8]) -> Vec<u8> {
let mut transcript = b"VNOX-CENTRAL-ACCOUNT-v1\0".to_vec();
transcript.extend_from_slice(claims);
self.signing_key.sign(&transcript).to_bytes().to_vec()
}
pub fn load_or_create(directory: &Path) -> Result<Self> {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
@ -66,6 +74,7 @@ impl Issuer {
bail!("Hub issuer identity failed integrity validation");
}
Ok(Self {
signing_key: key,
id: stored.issuer_id,
public_key: stored.public_key,
})

View file

@ -77,6 +77,8 @@ async fn info(State(state): State<Arc<HubState>>) -> Json<Value> {
"capabilities": {
"email_auth": if state.auth.email_enabled() { "enabled" } else { "not_enabled" },
"github_auth": if state.auth.configured() { "enabled" } else { "not_enabled" },
"account_profile": "enabled",
"community_directory": "enabled",
"server_registry": "not_enabled",
"friends": "not_enabled",
"direct_messages": "not_enabled",

View file

@ -129,6 +129,23 @@ async fn login_browser_binding_replay_session_and_csrf() {
response.headers()["location"],
"https://central.loki-code.dev/account"
);
let persisted_cookie = response
.headers()
.get_all("set-cookie")
.iter()
.find(|v| v.to_str().unwrap().starts_with("__Host-vnox_session="))
.unwrap()
.to_str()
.unwrap();
for property in [
"Secure",
"HttpOnly",
"SameSite=Lax",
"Path=/",
"Max-Age=604800",
] {
assert!(persisted_cookie.contains(property), "{property}");
}
let session = response
.headers()
.get_all("set-cookie")

View file

@ -276,7 +276,10 @@ async fn assert_error(response: Response<Body>, status: StatusCode, code: &str)
async fn upload_reencodes_to_a_square_png_and_serves_it_with_safe_headers() {
let fx = fixture().await;
let alice = fx.email_user("alice@example.com").await;
assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null);
assert_eq!(
fx.session_avatar(&alice).await,
vnox_hub::avatar::default_url(&alice.user.user_id)
);
let response = fx.upload(&alice, "image/png", png(600, 300)).await;
assert_eq!(response.status(), StatusCode::OK);
@ -325,7 +328,9 @@ async fn jpeg_and_webp_are_accepted_and_exif_and_png_text_chunks_are_removed() {
.as_str()
.unwrap()
.to_owned();
let body = bytes(fx.get(&url).await).await;
let body = to_bytes(fx.get(&url).await.into_body(), usize::MAX)
.await
.unwrap();
assert!(!contains(&body, b"SECRET"));
assert!(!contains(&body, b"Exif"));
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
@ -339,7 +344,9 @@ async fn jpeg_and_webp_are_accepted_and_exif_and_png_text_chunks_are_removed() {
.as_str()
.unwrap()
.to_owned();
let body = bytes(fx.get(&url).await).await;
let body = to_bytes(fx.get(&url).await.into_body(), usize::MAX)
.await
.unwrap();
assert!(!contains(&body, b"SECRET"));
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
@ -453,7 +460,10 @@ async fn another_account_cannot_change_or_remove_my_avatar() {
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
assert_eq!(fx.session_avatar(&alice).await, alice_url);
assert_eq!(fx.session_avatar(&bob).await, serde_json::Value::Null);
assert_eq!(
fx.session_avatar(&bob).await,
vnox_hub::avatar::default_url(&bob.user.user_id)
);
// Bob acting as himself only affects Bob.
assert_eq!(
@ -622,32 +632,42 @@ async fn a_new_upload_replaces_the_old_one() {
}
#[tokio::test]
async fn delete_returns_the_provider_avatar_or_the_default() {
async fn delete_restores_vnox_default_and_legacy_provider_images_are_never_exposed() {
let fx = fixture().await;
let github = fx.github_user().await;
assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR);
let default = vnox_hub::avatar::default_url(&github.user.user_id);
assert_eq!(fx.session_avatar(&github).await, default);
let url = json(fx.upload(&github, "image/png", png(64, 64)).await).await["avatar_url"]
.as_str()
.unwrap()
.to_owned();
assert_ne!(fx.session_avatar(&github).await, GITHUB_AVATAR);
assert_eq!(fx.session_avatar(&github).await, url);
let response = fx.remove(&github).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["cache-control"], "no-store");
assert_eq!(json(response).await["avatar_url"], GITHUB_AVATAR);
assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR);
assert_eq!(json(response).await["avatar_url"], default);
assert_eq!(fx.session_avatar(&github).await, default);
assert_eq!(fx.get(&url).await.status(), StatusCode::NOT_FOUND);
assert_eq!(fx.avatar_rows().await, 0);
// Removing again is harmless, and an email account falls back to the default (null).
// Removing again is harmless; email accounts also get a stable VNOX default.
assert_eq!(fx.remove(&github).await.status(), StatusCode::OK);
let alice = fx.email_user("alice@example.com").await;
fx.upload(&alice, "image/png", png(64, 64)).await;
let response = fx.remove(&alice).await;
assert_eq!(json(response).await["avatar_url"], serde_json::Value::Null);
assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null);
let alice_default = vnox_hub::avatar::default_url(&alice.user.user_id);
assert_eq!(json(response).await["avatar_url"], alice_default);
assert_eq!(fx.session_avatar(&alice).await, alice_default);
// Simulate an old row that still carries a GitHub provider URL.
sqlx::query("UPDATE accounts SET avatar_url=? WHERE user_id=?")
.bind(GITHUB_AVATAR)
.bind(&github.user.user_id)
.execute(&fx.state.database)
.await
.unwrap();
assert_eq!(fx.session_avatar(&github).await, default);
}
#[tokio::test]
@ -740,3 +760,37 @@ async fn deleting_an_account_removes_its_avatar() {
.unwrap();
assert_eq!(fx.avatar_rows().await, 0);
}
#[tokio::test]
async fn generated_defaults_are_stable_pngs_without_account_enumeration() {
let fx = fixture().await;
let id = uuid::Uuid::new_v4().to_string();
let url = vnox_hub::avatar::default_url(&id);
let response = fx.get(&url).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "image/png");
assert_eq!(
response.headers()["cache-control"],
"public, max-age=31536000, immutable"
);
let first = to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert_eq!(image::load_from_memory(&first).unwrap().width(), 256);
assert_eq!(
first,
to_bytes(fx.get(&url).await.into_body(), usize::MAX)
.await
.unwrap()
);
let other = vnox_hub::avatar::default_url(&uuid::Uuid::new_v4().to_string());
assert_ne!(
first,
to_bytes(fx.get(&other).await.into_body(), usize::MAX)
.await
.unwrap()
);
assert_eq!(
fx.get("/v1/avatars/default/not-a-uuid").await.status(),
StatusCode::NOT_FOUND
);
assert_eq!(fx.avatar_rows().await, 0);
}

614
hub/tests/desktop_auth.rs Normal file
View file

@ -0,0 +1,614 @@
use axum::{
Router,
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use ed25519_dalek::{Signature, VerifyingKey};
use serde_json::{Value, json};
use std::sync::Arc;
use tower::ServiceExt;
use vnox_hub::{
auth::{self, store},
database,
identity::Issuer,
web::{self, HubState},
};
async fn setup() -> (tempfile::TempDir, Arc<HubState>, Router, String, String) {
let dir = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
}
let issuer = Issuer::load_or_create(dir.path()).unwrap();
let pool = database::open(dir.path(), &issuer).await.unwrap();
let auth = auth::AuthService::with_provider(
pool.clone(),
url::Url::parse("https://central.loki-code.dev").unwrap(),
None,
);
let user = store::upsert_email_identity(&pool, "test@example.org")
.await
.unwrap();
let (session, csrf) = store::create_session(&pool, &user.user_id).await.unwrap();
let state = Arc::new(HubState {
database: pool,
auth: Arc::new(auth),
issuer,
smtp_configured: false,
started: std::time::Instant::now(),
});
let app = web::router(state.clone());
(dir, state, app, session, csrf)
}
async fn call(
app: &Router,
path: &str,
body: Value,
session: Option<(&str, &str)>,
) -> (StatusCode, Value) {
let mut b = Request::builder()
.method("POST")
.uri(path)
.header("content-type", "application/json");
if let Some((session, csrf)) = session {
b = b
.header("origin", "https://central.loki-code.dev")
.header("cookie", format!("__Host-vnox_session={session}"))
.header("x-csrf-token", csrf);
}
let response = app
.clone()
.oneshot(b.body(Body::from(body.to_string())).unwrap())
.await
.unwrap();
let status = response.status();
let bytes = to_bytes(response.into_body(), 65536).await.unwrap();
(
status,
serde_json::from_slice(&bytes).unwrap_or(Value::Null),
)
}
async fn start(app: &Router) -> (String, Value) {
let key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
let public = hex::encode(key.verifying_key().to_bytes());
let (status, request) = call(
app,
"/v1/auth/desktop/start",
json!({"public_key":public}),
None,
)
.await;
assert_eq!(status, StatusCode::OK);
(public, request)
}
#[tokio::test]
async fn browser_approval_proof_binding_single_use_and_revocation() {
let (_dir, state, app, session, csrf) = setup().await;
let (public, request) = start(&app).await;
let code = request["user_code"].as_str().unwrap();
let secret = request["device_secret"].as_str().unwrap();
assert!(
!request["verification_uri"]
.as_str()
.unwrap()
.contains(secret)
);
assert_eq!(
call(
&app,
"/v1/auth/desktop/poll",
json!({"device_secret":secret}),
None
)
.await
.0,
StatusCode::ACCEPTED
);
assert_eq!(
call(&app, "/v1/auth/desktop/approve", json!({"code":code}), None)
.await
.0,
StatusCode::FORBIDDEN
);
assert_eq!(
call(
&app,
"/v1/auth/desktop/approve",
json!({"code":code}),
Some((&session, "wrong"))
)
.await
.0,
StatusCode::FORBIDDEN
);
assert_eq!(
call(
&app,
"/v1/auth/desktop/approve",
json!({"code":code}),
Some((&session, &csrf))
)
.await
.0,
StatusCode::OK
);
let (status, approved) = call(
&app,
"/v1/auth/desktop/poll",
json!({"device_secret":secret}),
None,
)
.await;
assert_eq!(status, StatusCode::OK);
let claims = hex::decode(approved["account_proof"]["claims"].as_str().unwrap()).unwrap();
let claim: Value = serde_json::from_slice(&claims).unwrap();
assert_eq!(claim["public_key"], public);
assert_eq!(claim["subject"], approved["user"]["user_id"]);
assert_eq!(
claim["expires_at"].as_i64().unwrap() - claim["issued_at"].as_i64().unwrap(),
600
);
let key = VerifyingKey::from_bytes(
&hex::decode(&state.issuer.public_key)
.unwrap()
.try_into()
.unwrap(),
)
.unwrap();
let sig = Signature::from_slice(
&hex::decode(approved["account_proof"]["signature"].as_str().unwrap()).unwrap(),
)
.unwrap();
let mut transcript = b"VNOX-CENTRAL-ACCOUNT-v1\0".to_vec();
transcript.extend_from_slice(&claims);
key.verify_strict(&transcript, &sig).unwrap();
assert_eq!(
call(
&app,
"/v1/auth/desktop/poll",
json!({"device_secret":secret}),
None
)
.await
.0,
StatusCode::GONE
);
let refresh = approved["refresh_secret"].as_str().unwrap();
let body = json!({"refresh_secret":refresh});
assert_eq!(
call(&app, "/v1/auth/desktop/refresh", body.clone(), None)
.await
.0,
StatusCode::OK
);
let stored: String = sqlx::query_scalar("SELECT refresh_hash FROM desktop_devices")
.fetch_one(&state.database)
.await
.unwrap();
assert_eq!(stored, store::hash(refresh));
assert_ne!(stored, refresh);
assert_eq!(
call(&app, "/v1/auth/desktop/revoke", body.clone(), None)
.await
.0,
StatusCode::NO_CONTENT
);
assert_eq!(
call(&app, "/v1/auth/desktop/refresh", body, None).await.0,
StatusCode::UNAUTHORIZED
);
}
#[tokio::test]
async fn canceled_expired_and_invalid_requests_fail_closed() {
let (_dir, state, app, session, csrf) = setup().await;
for expire in [false, true] {
let (_, request) = start(&app).await;
let secret = request["device_secret"].as_str().unwrap();
let code = request["user_code"].as_str().unwrap();
if expire {
sqlx::query("UPDATE desktop_authorizations SET expires_at=0")
.execute(&state.database)
.await
.unwrap();
} else {
assert_eq!(
call(
&app,
"/v1/auth/desktop/cancel",
json!({"device_secret":secret}),
None
)
.await
.0,
StatusCode::NO_CONTENT
);
}
assert_eq!(
call(
&app,
"/v1/auth/desktop/approve",
json!({"code":code}),
Some((&session, &csrf))
)
.await
.0,
StatusCode::GONE
);
assert_eq!(
call(
&app,
"/v1/auth/desktop/poll",
json!({"device_secret":secret}),
None
)
.await
.0,
StatusCode::GONE
);
}
assert_eq!(
call(
&app,
"/v1/auth/desktop/start",
json!({"public_key":"bad"}),
None
)
.await
.0,
StatusCode::BAD_REQUEST
);
}
#[tokio::test]
async fn cancel_also_revokes_an_enrollment_whose_poll_response_was_lost() {
let (_dir, _state, app, session, csrf) = setup().await;
let (_, request) = start(&app).await;
let code = request["user_code"].as_str().unwrap();
let device = json!({"device_secret":request["device_secret"]});
assert_eq!(
call(
&app,
"/v1/auth/desktop/approve",
json!({"code":code}),
Some((&session, &csrf))
)
.await
.0,
StatusCode::OK
);
let (status, approved) = call(&app, "/v1/auth/desktop/poll", device.clone(), None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
call(&app, "/v1/auth/desktop/cancel", device, None).await.0,
StatusCode::NO_CONTENT
);
let refresh = json!({"refresh_secret":approved["refresh_secret"]});
assert_eq!(
call(&app, "/v1/auth/desktop/refresh", refresh, None)
.await
.0,
StatusCode::UNAUTHORIZED
);
}
async fn enroll(
app: &Router,
session: &str,
csrf: &str,
) -> (ed25519_dalek::SigningKey, String, Value) {
let key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
let (_, request) = call(
app,
"/v1/auth/desktop/start",
json!({"public_key":hex::encode(key.verifying_key().to_bytes())}),
None,
)
.await;
assert_eq!(
call(
app,
"/v1/auth/desktop/approve",
json!({"code":request["user_code"]}),
Some((session, csrf))
)
.await
.0,
StatusCode::OK
);
let (status, approved) = call(
app,
"/v1/auth/desktop/poll",
json!({"device_secret":request["device_secret"]}),
None,
)
.await;
assert_eq!(status, StatusCode::OK);
(
key,
approved["refresh_secret"].as_str().unwrap().to_owned(),
approved["user"].clone(),
)
}
fn test_png() -> Vec<u8> {
let picture = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
64,
64,
image::Rgba([20, 100, 220, 255]),
));
let mut bytes = std::io::Cursor::new(Vec::new());
picture
.write_to(&mut bytes, image::ImageFormat::Png)
.unwrap();
bytes.into_inner()
}
async fn mutate(
app: &Router,
method: &str,
path: &str,
key: &ed25519_dalek::SigningKey,
secret: &str,
bytes: Vec<u8>,
timestamp: i64,
) -> (StatusCode, Value) {
use ed25519_dalek::Signer;
use sha2::{Digest, Sha256};
let timestamp = timestamp.to_string();
let mut signed = b"VNOX-CENTRAL-PROFILE-v1\0".to_vec();
signed.extend_from_slice(method.as_bytes());
signed.push(0);
signed.extend_from_slice(path.as_bytes());
signed.push(0);
signed.extend_from_slice(timestamp.as_bytes());
signed.push(0);
signed.extend_from_slice(&Sha256::digest(&bytes));
let request = Request::builder()
.method(method)
.uri(path)
.header("authorization", format!("Bearer {secret}"))
.header(
"x-vnox-public-key",
hex::encode(key.verifying_key().to_bytes()),
)
.header("x-vnox-timestamp", timestamp)
.header(
"x-vnox-signature",
hex::encode(key.sign(&signed).to_bytes()),
)
.header(
"content-type",
if path.ends_with("profile") {
"application/json"
} else {
"image/png"
},
)
.body(Body::from(bytes))
.unwrap();
let response = app.clone().oneshot(request).await.unwrap();
let status = response.status();
let bytes = to_bytes(response.into_body(), 65536).await.unwrap();
(
status,
serde_json::from_slice(&bytes).unwrap_or(Value::Null),
)
}
#[tokio::test]
async fn desktop_avatar_upload_delete_and_website_refresh_share_one_account() {
let (_dir, state, app, session, csrf) = setup().await;
let (key, secret, user) = enroll(&app, &session, &csrf).await;
let user_id = user["user_id"].as_str().unwrap();
let website_url = vnox_hub::avatar::replace(&state.database, user_id, &test_png())
.await
.unwrap();
let (status, fresh) = call(
&app,
"/v1/auth/desktop/refresh",
json!({"refresh_secret":secret}),
None,
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(fresh["user"]["avatar_url"], website_url);
let claims: Value = serde_json::from_slice(
&hex::decode(fresh["account_proof"]["claims"].as_str().unwrap()).unwrap(),
)
.unwrap();
assert_eq!(claims["avatar_url"], website_url);
let (status, uploaded) = mutate(
&app,
"POST",
"/v1/auth/desktop/avatar",
&key,
&secret,
test_png(),
store::now(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(uploaded["user"]["user_id"], user_id);
let url = uploaded["user"]["avatar_url"].as_str().unwrap();
assert_ne!(
url, website_url,
"desktop normalizes source to a fresh stored 256px PNG"
);
let response = app
.clone()
.oneshot(Request::builder().uri(url).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
let image = image::load_from_memory(&bytes).unwrap();
assert_eq!((image.width(), image.height()), (256, 256));
let (status, deleted) = mutate(
&app,
"DELETE",
"/v1/auth/desktop/avatar",
&key,
&secret,
Vec::new(),
store::now(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
deleted["user"]["avatar_url"],
format!("/v1/avatars/default-v2/{user_id}")
);
}
#[tokio::test]
async fn desktop_profile_name_changes_without_handle_or_identity_reassignment() {
let (_dir, _state, app, session, csrf) = setup().await;
let (key, secret, user) = enroll(&app, &session, &csrf).await;
let (status, updated) = mutate(
&app,
"POST",
"/v1/auth/desktop/profile",
&key,
&secret,
br#"{"display_name":" New Name "}"#.to_vec(),
store::now(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(updated["user"]["display_name"], "New Name");
assert_eq!(updated["user"]["handle"], user["handle"]);
assert_eq!(updated["user"]["user_id"], user["user_id"]);
let (_, fresh) = call(
&app,
"/v1/auth/desktop/refresh",
json!({"refresh_secret":secret}),
None,
)
.await;
let claim: Value = serde_json::from_slice(
&hex::decode(fresh["account_proof"]["claims"].as_str().unwrap()).unwrap(),
)
.unwrap();
assert_eq!(claim["display_name"], "New Name");
for name in ["", "\nBad", "Bad\u{202e}Name"] {
assert_eq!(
mutate(
&app,
"POST",
"/v1/auth/desktop/profile",
&key,
&secret,
serde_json::to_vec(&json!({"display_name":name})).unwrap(),
store::now()
)
.await
.0,
StatusCode::UNPROCESSABLE_ENTITY
);
}
assert_eq!(
mutate(
&app,
"POST",
"/v1/auth/desktop/profile",
&key,
&secret,
serde_json::to_vec(&json!({"display_name":"x".repeat(65)})).unwrap(),
store::now()
)
.await
.0,
StatusCode::UNPROCESSABLE_ENTITY
);
}
#[tokio::test]
async fn desktop_avatar_requires_live_secret_device_signature_and_bounded_valid_png() {
let (_dir, state, app, session, csrf) = setup().await;
let (key, secret, _) = enroll(&app, &session, &csrf).await;
let other = ed25519_dalek::SigningKey::generate(&mut rand::rng());
for (signer, secret, time) in [
(&other, secret.as_str(), store::now()),
(
&key,
"0000000000000000000000000000000000000000000000000000000000000000",
store::now(),
),
(&key, secret.as_str(), store::now() - 61),
] {
assert_eq!(
mutate(
&app,
"POST",
"/v1/auth/desktop/avatar",
signer,
secret,
test_png(),
time
)
.await
.0,
StatusCode::UNAUTHORIZED
);
}
assert_eq!(
mutate(
&app,
"POST",
"/v1/auth/desktop/avatar",
&key,
&secret,
b"not png".to_vec(),
store::now()
)
.await
.0,
StatusCode::UNSUPPORTED_MEDIA_TYPE
);
assert_eq!(
mutate(
&app,
"POST",
"/v1/auth/desktop/avatar",
&key,
&secret,
vec![0; 2 * 1024 * 1024 + 1],
store::now()
)
.await
.0,
StatusCode::PAYLOAD_TOO_LARGE
);
sqlx::query("UPDATE desktop_devices SET expires_at=0")
.execute(&state.database)
.await
.unwrap();
assert_eq!(
mutate(
&app,
"DELETE",
"/v1/auth/desktop/avatar",
&key,
&secret,
Vec::new(),
store::now()
)
.await
.0,
StatusCode::UNAUTHORIZED
);
sqlx::query("DELETE FROM desktop_devices")
.execute(&state.database)
.await
.unwrap();
assert_eq!(
mutate(
&app,
"POST",
"/v1/auth/desktop/profile",
&key,
&secret,
br#"{"display_name":"Changed"}"#.to_vec(),
store::now()
)
.await
.0,
StatusCode::UNAUTHORIZED
);
}

230
hub/tests/directory.rs Normal file
View file

@ -0,0 +1,230 @@
use axum::{
Router,
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use serde_json::{Value, json};
use std::sync::Arc;
use tower::ServiceExt;
use vnox_hub::{
auth::{self, store},
database,
identity::Issuer,
web::{self, HubState},
};
const ORIGIN: &str = "https://central.loki-code.dev";
struct Fixture {
_dir: tempfile::TempDir,
state: Arc<HubState>,
app: Router,
}
struct Session {
user: store::User,
token: String,
csrf: String,
}
async fn fixture() -> Fixture {
let dir = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
}
let issuer = Issuer::load_or_create(dir.path()).unwrap();
let pool = database::open(dir.path(), &issuer).await.unwrap();
let auth = auth::AuthService::with_provider(pool.clone(), ORIGIN.parse().unwrap(), None);
let state = Arc::new(HubState {
database: pool,
auth: Arc::new(auth),
issuer,
smtp_configured: false,
started: std::time::Instant::now(),
});
Fixture {
_dir: dir,
app: web::router(state.clone()),
state,
}
}
impl Fixture {
async fn login(&self, email: &str) -> Session {
let user = store::upsert_email_identity(&self.state.database, email)
.await
.unwrap();
let (token, csrf) = store::create_session(&self.state.database, &user.user_id)
.await
.unwrap();
Session { user, token, csrf }
}
fn request(&self, s: &Session, body: String) -> Request<Body> {
Request::builder()
.method("POST")
.uri("/v1/servers")
.header("origin", ORIGIN)
.header("content-type", "application/json")
.header("cookie", format!("__Host-vnox_session={}", s.token))
.header("x-csrf-token", &s.csrf)
.body(Body::from(body))
.unwrap()
}
async fn send(&self, r: Request<Body>) -> (StatusCode, Value) {
let r = self.app.clone().oneshot(r).await.unwrap();
assert_eq!(r.headers()["cache-control"], "no-store");
let status = r.status();
(
status,
serde_json::from_slice(&to_bytes(r.into_body(), 1048576).await.unwrap()).unwrap(),
)
}
}
#[tokio::test]
async fn directory_auth_ownership_normalization_and_persistence() {
let f = fixture().await;
let owner = f.login("owner@example.org").await;
let other = f.login("other@example.org").await;
let body =
json!({"name":" Voice ","address":"Voice.Example.COM.:07600","description":" public "})
.to_string();
let mut unauth = f.request(&owner, body.clone());
unauth.headers_mut().remove("cookie");
assert_eq!(f.send(unauth).await.0, StatusCode::UNAUTHORIZED);
for header in ["origin", "x-csrf-token"] {
let mut req = f.request(&owner, body.clone());
req.headers_mut().remove(header);
assert_eq!(f.send(req).await.0, StatusCode::FORBIDDEN);
}
let (status, result) = f.send(f.request(&owner, body.clone())).await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(result["server"]["address"], "voice.example.com:7600");
assert_eq!(result["server"]["owner_id"], owner.user.user_id);
assert_eq!(
f.send(f.request(&owner, body)).await.0,
StatusCode::CONFLICT
);
let id = result["server"]["id"].as_str().unwrap();
let mut remove = f.request(&other, String::new());
*remove.method_mut() = axum::http::Method::DELETE;
*remove.uri_mut() = format!("/v1/servers/{id}").parse().unwrap();
assert_eq!(f.send(remove).await.0, StatusCode::NOT_FOUND);
let pool = database::open(f._dir.path(), &f.state.issuer)
.await
.unwrap();
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM community_servers")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(count, 1);
let (_, page) = f
.send(
Request::builder()
.uri("/v1/servers")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(page["servers"].as_array().unwrap().len(), 1);
sqlx::query("DELETE FROM accounts WHERE user_id=?")
.bind(owner.user.user_id)
.execute(&pool)
.await
.unwrap();
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM community_servers")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(count, 0);
}
#[tokio::test]
async fn directory_rejects_bad_json_oversize_and_bounds() {
let f = fixture().await;
let s = f.login("bounds@example.org").await;
assert_eq!(
f.send(f.request(&s, "{".into())).await.0,
StatusCode::BAD_REQUEST
);
assert_eq!(
f.send(f.request(&s, "x".repeat(4097))).await.0,
StatusCode::PAYLOAD_TOO_LARGE
);
for body in [
json!({"name":"","address":"voice.example.com:7600","description":""}),
json!({"name":"voice","address":"127.0.0.1:7600","description":""}),
json!({"name":"voice","address":"voice.example.com:7600","description":"x".repeat(501)}),
] {
assert_eq!(
f.send(f.request(&s, body.to_string())).await.0,
StatusCode::UNPROCESSABLE_ENTITY
);
}
}
#[tokio::test]
async fn directory_owner_can_remove_and_rate_budget_is_independent() {
let f = fixture().await;
let s = f.login("delete@example.org").await;
let (_, result) = f
.send(f.request(
&s,
json!({"name":"Voice","address":"voice.example.org:7600","description":""}).to_string(),
))
.await;
let mut req = f.request(&s, String::new());
*req.method_mut() = axum::http::Method::DELETE;
*req.uri_mut() = format!("/v1/servers/{}", result["server"]["id"].as_str().unwrap())
.parse()
.unwrap();
let response = f.app.clone().oneshot(req).await.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
for _ in 0..8 {
assert!(f.state.auth.allow_directory(&s.user.user_id, "local"));
}
assert!(!f.state.auth.allow_directory(&s.user.user_id, "local"));
assert!(f.state.auth.allow_avatar(&s.user.user_id, "local"));
}
#[tokio::test]
async fn directory_account_cap_and_pagination_are_bounded() {
let f = fixture().await;
let s = f.login("cap@example.org").await;
for i in 0..105 {
sqlx::query("INSERT INTO community_servers(id,name,address,description,owner_id,created_at) VALUES (?,?,?,?,?,?)")
.bind(format!("00000000-0000-4000-8000-{i:012}" )).bind("voice").bind(format!("voice{i}.example.org:7600")).bind("").bind(&s.user.user_id).bind(1_i64).execute(&f.state.database).await.unwrap();
}
let (status, page) = f
.send(
Request::builder()
.uri("/v1/servers")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(page["servers"].as_array().unwrap().len(), 100);
let last = page["servers"][99]["id"].as_str().unwrap();
let (_, next) = f
.send(
Request::builder()
.uri(format!("/v1/servers?after={last}"))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(next["servers"].as_array().unwrap().len(), 5);
assert_eq!(
f.send(f.request(
&s,
json!({"name":"voice","address":"new.example.org:7600","description":""}).to_string()
))
.await
.1["error"],
"listing_limit"
);
}
#[tokio::test]
async fn directory_reads_do_not_consume_login_budget() {
let f = fixture().await;
for _ in 0..20 {
assert!(f.state.auth.allow_directory_read("source"));
}
assert!(!f.state.auth.allow_directory_read("source"));
assert!(f.state.auth.allow("source"));
}

View file

@ -288,7 +288,12 @@ async fn full_flow_creates_neutral_account_and_session() {
}
let json: Value = serde_json::from_str(&body).unwrap();
assert_eq!(json["authenticated"], true);
assert_eq!(json["user"]["display_name"], "Vnox user");
let initial_name = json["user"]["display_name"].as_str().unwrap();
let (word, digits) = initial_name.rsplit_once('_').unwrap();
assert!(word.chars().all(|c| ('а'..='я').contains(&c) || c == 'ё'));
assert_eq!(digits.len(), 4);
assert!(digits.bytes().all(|c| c.is_ascii_digit()));
assert_eq!(json["onboarding_pending"], true);
let handle = json["user"]["handle"].as_str().unwrap();
assert!(handle.starts_with("u_") && !handle.contains("alice"));
assert!(!body.to_lowercase().contains("alice"));

View file

@ -184,6 +184,7 @@ async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
"marketplace",
] {
assert_eq!(value["capabilities"][capability], "not_enabled");
assert_eq!(value["capabilities"]["account_profile"], "enabled");
}
assert_eq!(value["smtp"]["public_send_endpoint"], false);
assert!(value.get("secret_key").is_none());
@ -203,7 +204,10 @@ async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
.unwrap();
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
}
for path in ["/v1/servers/register", "/v1/mail/send"] {
for (path, expected) in [
("/v1/servers/register", StatusCode::METHOD_NOT_ALLOWED),
("/v1/mail/send", StatusCode::NOT_FOUND),
] {
let response = app
.clone()
.oneshot(
@ -215,7 +219,7 @@ async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(response.status(), expected);
}
}

265
hub/tests/onboarding.rs Normal file
View file

@ -0,0 +1,265 @@
//! Own-origin profile onboarding with isolated SQLite and synthetic email/GitHub identities.
use axum::{
Router,
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use serde_json::{Value, json};
use std::sync::Arc;
use tower::ServiceExt;
use vnox_hub::{
auth::{self, provider::GitHubProfile, store},
database,
identity::Issuer,
web::{self, HubState},
};
const ORIGIN: &str = "https://central.loki-code.dev";
struct Fixture {
_dir: tempfile::TempDir,
state: Arc<HubState>,
app: Router,
}
async fn fixture() -> Fixture {
let dir = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
}
let issuer = Issuer::load_or_create(dir.path()).unwrap();
let pool = database::open(dir.path(), &issuer).await.unwrap();
let auth = auth::AuthService::with_provider(pool.clone(), ORIGIN.parse().unwrap(), None);
let state = Arc::new(HubState {
database: pool,
auth: Arc::new(auth),
issuer,
smtp_configured: false,
started: std::time::Instant::now(),
});
Fixture {
_dir: dir,
app: web::router(state.clone()),
state,
}
}
async fn call(
f: &Fixture,
user: &str,
path: &str,
body: Value,
origin: &str,
csrf_ok: bool,
) -> (StatusCode, Value) {
let (token, csrf) = store::create_session(&f.state.database, user)
.await
.unwrap();
let req = Request::builder()
.method("POST")
.uri(path)
.header("origin", origin)
.header("content-type", "application/json")
.header("cookie", format!("__Host-vnox_session={token}"))
.header("x-csrf-token", if csrf_ok { csrf } else { "bad".into() })
.body(Body::from(body.to_string()))
.unwrap();
let r = f.app.clone().oneshot(req).await.unwrap();
let status = r.status();
let bytes = to_bytes(r.into_body(), 2048).await.unwrap();
(status, serde_json::from_slice(&bytes).unwrap())
}
fn generated(name: &str) {
let (word, digits) = name.rsplit_once('_').unwrap();
assert!(word.chars().all(|c| ('а'..='я').contains(&c) || c == 'ё'));
assert_eq!(digits.len(), 4);
assert!(digits.bytes().all(|c| c.is_ascii_digit()));
}
#[tokio::test]
async fn names_are_generated_once_for_both_providers_and_user_names_survive_login() {
let f = fixture().await;
let mail = store::upsert_email_identity(&f.state.database, "first@example.org")
.await
.unwrap();
generated(&mail.display_name);
let profile = GitHubProfile {
id: 1234,
login: "provider_private_login".into(),
name: Some("Provider Name".into()),
avatar_url: None,
};
let github = store::upsert_identity(&f.state.database, &profile)
.await
.unwrap();
generated(&github.display_name);
assert_ne!(github.display_name, "Provider Name");
assert!(
store::onboarding_pending(&f.state.database, &github.user_id)
.await
.unwrap()
);
for (user, provider) in [(&mail, "email"), (&github, "github")] {
let before = user.handle.clone();
let (status, body) = call(
&f,
&user.user_id,
"/v1/account/display-name",
json!({"display_name":" Моё имя "}),
ORIGIN,
true,
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["display_name"], "Моё имя");
assert!(
!store::onboarding_pending(&f.state.database, &user.user_id)
.await
.unwrap()
);
let again = if provider == "email" {
store::upsert_email_identity(&f.state.database, "first@example.org")
.await
.unwrap()
} else {
store::upsert_identity(&f.state.database, &profile)
.await
.unwrap()
};
assert_eq!(again.display_name, "Моё имя");
assert_eq!(again.handle, before);
}
}
#[tokio::test]
async fn decision_is_persisted_idempotently_and_not_created_for_existing_accounts() {
let f = fixture().await;
let user = store::upsert_email_identity(&f.state.database, "new@example.org")
.await
.unwrap();
assert!(
store::onboarding_pending(&f.state.database, &user.user_id)
.await
.unwrap()
);
for decision in ["later", "rename"] {
assert_eq!(
call(
&f,
&user.user_id,
"/v1/account/onboarding",
json!({"decision":decision}),
ORIGIN,
true
)
.await
.0,
StatusCode::OK
);
}
let saved: String =
sqlx::query_scalar("SELECT decision FROM account_onboarding WHERE user_id=?")
.bind(&user.user_id)
.fetch_one(&f.state.database)
.await
.unwrap();
assert_eq!(saved, "later");
assert!(
!store::onboarding_pending(&f.state.database, &user.user_id)
.await
.unwrap()
);
sqlx::query("DELETE FROM account_onboarding WHERE user_id=?")
.bind(&user.user_id)
.execute(&f.state.database)
.await
.unwrap();
let again = store::upsert_email_identity(&f.state.database, "new@example.org")
.await
.unwrap();
assert_eq!(again.display_name, user.display_name);
assert!(
!store::onboarding_pending(&f.state.database, &user.user_id)
.await
.unwrap()
);
}
#[tokio::test]
async fn session_exposes_pending_and_actions_require_origin_csrf_and_valid_name() {
let f = fixture().await;
let user = store::upsert_email_identity(&f.state.database, "secure@example.org")
.await
.unwrap();
let (token, _) = store::create_session(&f.state.database, &user.user_id)
.await
.unwrap();
let r = f
.app
.clone()
.oneshot(
Request::builder()
.uri("/v1/auth/session")
.header("cookie", format!("__Host-vnox_session={token}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let body: Value =
serde_json::from_slice(&to_bytes(r.into_body(), 4096).await.unwrap()).unwrap();
assert_eq!(body["onboarding_pending"], true);
for path in ["/v1/account/onboarding", "/v1/account/display-name"] {
for (origin, csrf) in [("https://evil.example", true), (ORIGIN, false)] {
assert_eq!(
call(
&f,
&user.user_id,
path,
json!({"decision":"later"}),
origin,
csrf
)
.await
.0,
StatusCode::FORBIDDEN
);
}
}
for name in ["", "bad\nname", "\u{202e}evil"] {
assert_eq!(
call(
&f,
&user.user_id,
"/v1/account/display-name",
json!({"display_name":name}),
ORIGIN,
true
)
.await
.0,
StatusCode::UNPROCESSABLE_ENTITY
);
}
assert_eq!(
call(
&f,
&user.user_id,
"/v1/account/display-name",
json!({"display_name":"Name","handle":"override"}),
ORIGIN,
true
)
.await
.0,
StatusCode::BAD_REQUEST
);
assert_eq!(
call(
&f,
&user.user_id,
"/v1/account/onboarding",
json!({"decision":"bad"}),
ORIGIN,
true
)
.await
.0,
StatusCode::BAD_REQUEST
);
}

412
hub/tests/profile.rs Normal file
View file

@ -0,0 +1,412 @@
use axum::{
Router,
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use serde_json::{Value, json};
use std::sync::Arc;
use tower::ServiceExt;
use vnox_hub::{
auth::{self, store},
database,
identity::Issuer,
web::{self, HubState},
};
const ORIGIN: &str = "https://central.loki-code.dev";
struct Fixture {
_dir: tempfile::TempDir,
state: Arc<HubState>,
app: Router,
}
struct Session {
user: store::User,
token: String,
csrf: String,
}
async fn fixture() -> Fixture {
let dir = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
}
let issuer = Issuer::load_or_create(dir.path()).unwrap();
let pool = database::open(dir.path(), &issuer).await.unwrap();
let auth = auth::AuthService::with_provider(pool.clone(), ORIGIN.parse().unwrap(), None);
let state = Arc::new(HubState {
database: pool,
auth: Arc::new(auth),
issuer,
smtp_configured: false,
started: std::time::Instant::now(),
});
Fixture {
_dir: dir,
app: web::router(state.clone()),
state,
}
}
impl Fixture {
async fn login(&self, email: &str) -> Session {
let user = store::upsert_email_identity(&self.state.database, email)
.await
.unwrap();
let (token, csrf) = store::create_session(&self.state.database, &user.user_id)
.await
.unwrap();
Session { user, token, csrf }
}
fn request(&self, s: &Session, body: String) -> Request<Body> {
Request::builder()
.method("PUT")
.uri("/v1/account/profile")
.header("origin", ORIGIN)
.header("content-type", "application/json")
.header("cookie", format!("__Host-vnox_session={}", s.token))
.header("x-csrf-token", &s.csrf)
.body(Body::from(body))
.unwrap()
}
async fn send(&self, r: Request<Body>) -> (StatusCode, Value) {
let r = self.app.clone().oneshot(r).await.unwrap();
assert_eq!(r.headers()["cache-control"], "no-store");
let status = r.status();
(
status,
serde_json::from_slice(&to_bytes(r.into_body(), 8192).await.unwrap()).unwrap(),
)
}
async fn update(&self, s: &Session, handle: &str, name: &str) -> (StatusCode, Value) {
self.send(self.request(s, json!({"handle":handle,"display_name":name}).to_string()))
.await
}
}
#[tokio::test]
async fn selection_is_normalized_persisted_and_preserved_by_login() {
let f = fixture().await;
let s = f.login("person@example.org").await;
assert!(!s.user.profile_complete);
let (status, body) = f.update(&s, " Alice_123 ", " Алиса ").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["user"]["handle"], "alice_123");
assert_eq!(body["user"]["display_name"], "Алиса");
assert_eq!(body["user"]["profile_complete"], true);
assert_eq!(body["user"]["user_id"], s.user.user_id);
let again = f.login("person@example.org").await;
assert_eq!(again.user.handle, "alice_123");
assert_eq!(again.user.display_name, "Алиса");
assert!(again.user.profile_complete);
let session = f
.send(
Request::builder()
.uri("/v1/auth/session")
.header("cookie", format!("__Host-vnox_session={}", s.token))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(session.1["user"], body["user"]);
assert_eq!(
f.update(&s, "ALICE_123", "New name").await.0,
StatusCode::OK
);
assert_eq!(
f.update(&again, "other_handle", "Changed").await.1["error"],
"handle_locked"
);
}
#[tokio::test]
async fn case_insensitive_claims_are_atomic_and_leave_loser_unchanged() {
let f = fixture().await;
let a = f.login("a@example.org").await;
let b = f.login("b@example.org").await;
let (left, right) = tokio::join!(
f.update(&a, "Same_Name", "A"),
f.update(&b, "same_name", "B")
);
assert_eq!(
[left.0, right.0]
.iter()
.filter(|s| **s == StatusCode::OK)
.count(),
1
);
let (loser, conflict) = if left.0 == StatusCode::OK {
(&b, right)
} else {
(&a, left)
};
assert_eq!(conflict.0, StatusCode::CONFLICT);
assert_eq!(conflict.1["error"], "handle_taken");
let (user, _) = store::get_session(&f.state.database, &loser.token)
.await
.unwrap()
.unwrap();
assert_eq!(user.handle, loser.user.handle);
assert_eq!(user.display_name, loser.user.display_name);
assert!(!user.profile_complete);
}
#[tokio::test]
async fn concurrent_sessions_cannot_choose_two_handles() {
let f = fixture().await;
let a = f.login("a@example.org").await;
let b = f.login("a@example.org").await;
let (left, right) = tokio::join!(
f.update(&a, "first_name", "A"),
f.update(&b, "second_name", "B")
);
assert_eq!(
[left.0, right.0]
.iter()
.filter(|s| **s == StatusCode::OK)
.count(),
1
);
assert_eq!(
if left.0 == StatusCode::OK {
right.1
} else {
left.1
}["error"],
"handle_locked"
);
}
#[tokio::test]
async fn authorization_and_expiry_precede_body_parsing() {
let f = fixture().await;
let s = f.login("a@example.org").await;
for (header, error) in [
("origin", "invalid_origin"),
("cookie", "not_authenticated"),
("x-csrf-token", "invalid_csrf"),
] {
let mut r = f.request(&s, "invalid JSON".into());
r.headers_mut().remove(header);
assert_eq!(f.send(r).await.1["error"], error);
}
let mut r = f.request(&s, "x".repeat(2048));
r.headers_mut()
.insert("origin", "https://wrong.example".parse().unwrap());
assert_eq!(f.send(r).await.1["error"], "invalid_origin");
sqlx::query("UPDATE web_sessions SET expires_at=0")
.execute(&f.state.database)
.await
.unwrap();
assert_eq!(
f.update(&s, "valid_name", "Name").await.0,
StatusCode::UNAUTHORIZED
);
}
#[tokio::test]
async fn validation_and_body_limits_leave_account_unchanged() {
let f = fixture().await;
for handle in [
"ab",
"1alice",
"алиса",
"with-dash",
"with space",
"u_placeholder",
"ADMIN",
"root",
"everyone",
"abcdefghijklmnopqrstuvwxyz",
] {
let s = f
.login(&format!("{}@example.org", uuid::Uuid::new_v4()))
.await;
assert_eq!(
f.update(&s, handle, "Name").await.1["error"],
"invalid_handle"
);
assert!(
!store::get_session(&f.state.database, &s.token)
.await
.unwrap()
.unwrap()
.0
.profile_complete
);
}
let s = f.login("names@example.org").await;
for name in [
"".to_owned(),
" ".into(),
"n\n".into(),
"x\u{202e}y".into(),
"x\u{2066}y".into(),
"я".repeat(65),
] {
assert_eq!(
f.update(&s, "valid_name", &name).await.1["error"],
"invalid_display_name"
);
}
for body in [
"{}",
"{",
r#"{"handle":"valid_name","display_name":"Name","user_id":"other"}"#,
] {
assert_eq!(
f.send(f.request(&s, body.into())).await.0,
StatusCode::BAD_REQUEST
);
}
let s = f.login("large@example.org").await;
assert_eq!(
f.send(f.request(&s, "x".repeat(1025))).await.0,
StatusCode::PAYLOAD_TOO_LARGE
);
assert_eq!(
f.update(&s, "valid_name", &"я".repeat(64)).await.0,
StatusCode::OK
);
}
#[tokio::test]
async fn budgets_limit_accounts_and_sources_independently() {
let f = fixture().await;
let s = f.login("person@example.org").await;
for _ in 0..10 {
assert_eq!(f.update(&s, "person", "Person").await.0, StatusCode::OK);
}
assert_eq!(
f.update(&s, "person", "Person").await.0,
StatusCode::TOO_MANY_REQUESTS
);
for i in 0..2 {
let s = f.login(&format!("p{i}@example.org")).await;
for _ in 0..10 {
assert_eq!(
f.update(&s, &format!("person{i}"), "Name").await.0,
StatusCode::OK
);
}
}
let s = f.login("last@example.org").await;
assert_eq!(
f.update(&s, "last_person", "Name").await.0,
StatusCode::TOO_MANY_REQUESTS
);
let mut r = f.request(
&s,
json!({"handle":"last_person","display_name":"Name"}).to_string(),
);
r.headers_mut()
.insert("x-forwarded-for", "192.0.2.1".parse().unwrap());
assert_eq!(f.send(r).await.0, StatusCode::OK);
}
#[tokio::test]
async fn github_relogin_preserves_selected_profile_and_own_avatar() {
use vnox_hub::auth::provider::GitHubProfile;
let f = fixture().await;
let mut provider = GitHubProfile {
id: 123,
login: "original".into(),
name: Some("Provider name".into()),
avatar_url: Some("https://avatars.githubusercontent.com/u/123".into()),
};
let user = store::upsert_identity(&f.state.database, &provider)
.await
.unwrap();
let (token, csrf) = store::create_session(&f.state.database, &user.user_id)
.await
.unwrap();
let s = Session { user, token, csrf };
let png = image::RgbImage::new(256, 256);
let mut bytes = std::io::Cursor::new(Vec::new());
png.write_to(&mut bytes, image::ImageFormat::Png).unwrap();
let avatar = vnox_hub::avatar::replace(&f.state.database, &s.user.user_id, bytes.get_ref())
.await
.unwrap();
let (status, body) = f.update(&s, "my_handle", "My name").await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["user"]["avatar_url"], avatar);
provider.login = "renamed".into();
provider.name = Some("New provider name".into());
let user = store::upsert_identity(&f.state.database, &provider)
.await
.unwrap();
assert_eq!(user.user_id, s.user.user_id);
assert_eq!(user.handle, "my_handle");
assert_eq!(user.display_name, "My name");
assert_eq!(user.avatar_url.as_deref(), Some(avatar.as_str()));
assert!(user.profile_complete);
}
#[tokio::test]
async fn upgrading_legacy_database_preserves_accounts_bindings_sessions_and_avatars() {
let dir = tempfile::tempdir().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap();
}
let issuer = Issuer::load_or_create(dir.path()).unwrap();
let migrations = tempfile::tempdir().unwrap();
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("migrations");
for name in [
"0001_foundation.sql",
"0002_github_auth.sql",
"0003_email_auth.sql",
"0004_email_resend_chain.sql",
"0005_avatars.sql",
] {
std::fs::copy(source.join(name), migrations.path().join(name)).unwrap();
}
let options = sqlx::sqlite::SqliteConnectOptions::new()
.filename(dir.path().join("hub.sqlite3"))
.create_if_missing(true)
.foreign_keys(true);
let pool = sqlx::sqlite::SqlitePoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.unwrap();
sqlx::migrate::Migrator::new(migrations.path())
.await
.unwrap()
.run(&pool)
.await
.unwrap();
sqlx::query("INSERT INTO accounts(user_id,handle,created_at,display_name) VALUES('legacy-id','u_legacy',1,'Legacy')").execute(&pool).await.unwrap();
sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES('email','legacy@example.org','legacy-id',1)").execute(&pool).await.unwrap();
let (token, csrf) = store::create_session(&pool, "legacy-id").await.unwrap();
let avatar = vnox_hub::avatar::replace(&pool, "legacy-id", b"stored legacy avatar")
.await
.unwrap();
pool.close().await;
let upgraded = database::open(dir.path(), &issuer).await.unwrap();
let (user, stored_csrf) = store::get_session(&upgraded, &token)
.await
.unwrap()
.unwrap();
assert_eq!(stored_csrf, csrf);
assert_eq!(user.user_id, "legacy-id");
assert_eq!(user.handle, "u_legacy");
assert_eq!(user.display_name, "Legacy");
assert!(!user.profile_complete);
assert_eq!(user.avatar_url.as_deref(), Some(avatar.as_str()));
assert_eq!(
store::upsert_email_identity(&upgraded, "legacy@example.org")
.await
.unwrap()
.user_id,
"legacy-id"
);
// The new index also protects writes outside the HTTP handler.
assert!(
sqlx::query("INSERT INTO accounts(user_id,handle,created_at) VALUES('other','U_LEGACY',1)")
.execute(&upgraded)
.await
.is_err()
);
upgraded.close().await;
let reopened = database::open(dir.path(), &issuer).await.unwrap();
assert!(
store::get_session(&reopened, &token)
.await
.unwrap()
.is_some()
);
}