mirror of
https://github.com/Shu-Ying/farm_service.git
synced 2026-11-02 10:39:59 +08:00
add # 初始化仓库
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
# Documentation template only; the program reads process environment variables.
|
||||
# Generate a random token of at least 32 ASCII characters. Do not commit it.
|
||||
FARM_API_TOKEN=
|
||||
FARM_BIND=127.0.0.1:8080
|
||||
FARM_DATA_DIR=./data
|
||||
FARM_LOG_DIR=./logs
|
||||
RUST_LOG=farm_service=info
|
||||
# Optional: leave unset to disable asset distribution. Sibling assets.zip required.
|
||||
# The release files live in this repository's root assets/ directory.
|
||||
# FARM_ASSET_MANIFEST=./assets/manifest.json
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
# Rust build output; Cargo.lock is intentionally tracked for this application.
|
||||
/target/
|
||||
/dist/
|
||||
**/*.rs.bk
|
||||
*.pdb
|
||||
profraw
|
||||
*.profraw
|
||||
*.profdata
|
||||
/coverage/
|
||||
/tarpaulin-report.html
|
||||
|
||||
# Local runtime state and secrets.
|
||||
/data/
|
||||
/logs/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
*.sqlite
|
||||
*.sqlite-shm
|
||||
*.sqlite-wal
|
||||
*.sqlite3
|
||||
*.sqlite3-shm
|
||||
*.sqlite3-wal
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
# Editors and operating systems.
|
||||
/.idea/
|
||||
/.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
Generated
+1868
File diff suppressed because it is too large
Load Diff
+28
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "farm_service"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Farm service with authenticated user profile collection"
|
||||
license = "AGPL-3.0-only"
|
||||
repository = "https://github.com/Shu-Ying/farm_service"
|
||||
publish = false
|
||||
default-run = "farm_service"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
axum = "0.8"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
sha2 = "0.10"
|
||||
url = "2"
|
||||
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite", "macros", "migrate"] }
|
||||
subtle = "2"
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal"] }
|
||||
tracing = "0.1"
|
||||
tracing-appender = "0.2"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,235 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,144 @@
|
||||
# farm_service
|
||||
|
||||
真寻文字农场的 Rust 服务端起点。当前实现用户基础资料上报和查询,
|
||||
另提供可选的公开素材分发接口,尚未实现活动发布中心,
|
||||
也尚未接入 QQ 机器人自动上报。
|
||||
|
||||
## 当前能力
|
||||
|
||||
- `GET /health`:公开就绪检查,实际检查数据库。
|
||||
- `GET /v1/assets/manifest.json`:公开素材清单,含版本、SHA256、大小及三源绝对URL。
|
||||
- `GET /v1/assets/{sha256}/assets.zip`:下载启动时校验过的素材快照,支持ETag。
|
||||
- [资源分发接口与三端接入约定](docs/assets.md)。
|
||||
- 素材发布文件位于根目录 `assets/manifest.json` 和 `assets/assets.zip`;
|
||||
ZIP 仅由本服务仓库发布,三个插件分发包不包含 ZIP。
|
||||
- `PUT /v1/users`:受保护的用户资料新增/更新;重复上报不会重复建档。
|
||||
- `GET /v1/users/{platform}/{platform_user_id}`:受保护的单用户查询。
|
||||
- 独立 SQLite 数据库,启动自动迁移;不访问农场插件的数据库。
|
||||
- 每日 JSON 文件日志;不记录 QQ 号、昵称、令牌、完整请求或 SQL 参数。
|
||||
- AGPL v3 开源协议(`AGPL-3.0-only`)。二进制应用的 `Cargo.lock` 应纳入版本控制。
|
||||
|
||||
此阶段用 SQLite 降低首次运行门槛。此前活动规划中的 PostgreSQL、
|
||||
发布目录、活动账户和跨库奖励交付尚未实施,不创建占位字段或空模块。
|
||||
|
||||
## 用户字段与身份
|
||||
|
||||
| 字段 | 用途与约束 |
|
||||
|---|---|
|
||||
| `platform` | 平台命名空间:`qq`、`telegram`、`discord` |
|
||||
| `platform_user_id` | 字符串形式的正整数 ID,不接受前导零;QQ 最多 20 位,其他最多 32 位 |
|
||||
| `nickname` | 当前昵称,去除首尾空白后 1~64 个 Unicode 字符,禁止控制字符 |
|
||||
| `created_at` | 首次建档 UTC 时间,更新昵称时保留 |
|
||||
| `updated_at` | 最近资料写入 UTC 时间 |
|
||||
|
||||
`platform + platform_user_id` 是唯一键。同一 QQ 在不同机器人上报时
|
||||
对应同一份基础资料,不包含农场余额、机器人内玩家归属或群成员信息。
|
||||
这些资料来自持有令牌的受信机器人,不代表服务端已向 QQ 验证身份。
|
||||
|
||||
`qq` 只表示普通 QQ 号码(如 OneBot 适配器提供的标识),
|
||||
不接受官方 QQ OpenID/UnionID,也不把它们自动转换成 QQ 号。
|
||||
以后接入官方 QQ 时须增加应用作用域,避免不同应用的 OpenID 被混用。
|
||||
不要另外添加与 `platform_user_id` 重复、无独立用途的 `qq_number` 字段。
|
||||
|
||||
## 启动
|
||||
|
||||
需要 stable Rust 工具链和本机 C/C++ 构建工具(SQLite 原生依赖需要)。
|
||||
Windows 推荐 Visual Studio Build Tools 的“使用 C++ 的桌面开发”。
|
||||
依赖版本由 `Cargo.lock` 固定;首次构建需要访问 crates.io。
|
||||
|
||||
PowerShell 示例:
|
||||
|
||||
```powershell
|
||||
# 仅供本地启动。生成令牌后妥善保存,调用方使用同一令牌。
|
||||
$env:FARM_API_TOKEN = [Convert]::ToHexString(
|
||||
[System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32)
|
||||
)
|
||||
$env:FARM_BIND = "127.0.0.1:8080"
|
||||
cargo run --locked
|
||||
```
|
||||
|
||||
| 环境变量 | 默认值 / 作用 |
|
||||
|---|---|
|
||||
| `FARM_API_TOKEN` | 必填,32~256 个可见 ASCII 字符;建议随机生成 |
|
||||
| `FARM_BIND` | `127.0.0.1:8080` |
|
||||
| `FARM_DATA_DIR` | `./data`,保存 `farm_service.sqlite3` |
|
||||
| `FARM_LOG_DIR` | `./logs`,保存每日滚动日志 |
|
||||
| `RUST_LOG` | `farm_service=info` |
|
||||
| `FARM_ASSET_MANIFEST` | 可选,建议 `./assets/manifest.json`;同目录须有assets.zip;未设置时资源接口返回503 |
|
||||
|
||||
相对目录以进程工作目录为基准;生产建议使用固定绝对路径。
|
||||
`.env.example` 只是模板,程序**不会自动加载 .env**。
|
||||
Ctrl+C 停止;Unix 同时支持 SIGTERM,等待在途 HTTP 请求结束后关闭连接池。
|
||||
日志按日切分,不自动清理历史日志;部署时配置保留期限和磁盘监控。
|
||||
|
||||
插件的「资源获取地址」与「farm_service 地址」始终同时保留。
|
||||
资源源可选 `Github`、`Gitea`、`farm_service`,默认 `Github`;
|
||||
服务地址独立供资源、活动等功能使用,活动接口当前尚未实现。
|
||||
GitHub/Gitea 的清单及 ZIP 均从本服务仓库根目录 `assets/` 的 raw 直链读取,
|
||||
详见[资源发布位置](docs/assets.md#仓库文件与发布位置)。
|
||||
当前本地清单中的 `https://farm.example` 明确为占位地址,
|
||||
客户端选择服务源时使用其独立配置的真实基础地址。
|
||||
本轮仅准备本地文件,未提交、推送或部署,远端可用性尚未验证。
|
||||
|
||||
## 调用示例
|
||||
|
||||
在启动服务时设置过令牌的 PowerShell 会话中执行:
|
||||
|
||||
```powershell
|
||||
$headers = @{ Authorization = "Bearer $env:FARM_API_TOKEN" }
|
||||
$profile = @{
|
||||
platform = "qq"
|
||||
platform_user_id = "12345678"
|
||||
nickname = "农场玩家"
|
||||
} | ConvertTo-Json
|
||||
|
||||
Invoke-RestMethod -Method Put -Uri "http://127.0.0.1:8080/v1/users" `
|
||||
-Headers $headers -ContentType "application/json; charset=utf-8" `
|
||||
-Body ([System.Text.Encoding]::UTF8.GetBytes($profile))
|
||||
|
||||
Invoke-RestMethod -Uri "http://127.0.0.1:8080/v1/users/qq/12345678" `
|
||||
-Headers $headers
|
||||
```
|
||||
|
||||
写入和更新均返回 HTTP 200 与完整资料。JSON 只接受上述三个输入字段。
|
||||
请求体上限 4 KiB。非法资料返回 400;JSON 类型/格式错误可能返回
|
||||
400/415/422;超大请求返回 413;鉴权失败返回 401;用户不存在返回 404;
|
||||
存储不可用返回 503,不向客户端泄漏数据库细节。
|
||||
|
||||
## 接入与部署边界
|
||||
|
||||
插件需要在接入层从可信事件取得用户 ID、昵称及平台,再显式上报;
|
||||
当前不会自动读取 QQ、扫描群成员或收集历史消息。
|
||||
只在确有业务用途时上报这些字段,并向用户说明用途及保留策略。
|
||||
|
||||
本版本一个令牌对应一个受信服务访问范围,持有者可以查询或更新已知 ID
|
||||
的资料,尚无租户级权限或管理员账户。令牌不能放进群消息、前端或日志。
|
||||
暂不提供用户枚举/批量查询接口。
|
||||
|
||||
默认仅监听本机;公网部署需 HTTPS 反向代理、限流及访问控制。
|
||||
反向代理的 URL 访问日志可能包含查询路径中的用户 ID,应关闭该路径的
|
||||
访问日志或脱敏。数据目录/备份仅授予服务账户权限,备份按个人资料保护。
|
||||
用户删除和保留政策需在正式收集前落实,本轮未实现删除接口或自动清理。
|
||||
|
||||
## 开发验证
|
||||
|
||||
```text
|
||||
cargo fmt --check
|
||||
cargo test --locked --all-targets
|
||||
cargo clippy --locked --all-targets -- -D warnings
|
||||
```
|
||||
|
||||
测试覆盖鉴权、资料校验、昵称更新、重启持久化、平台隔离、并发建档、
|
||||
请求大小及数据库不可用。测试使用临时目录,不写入实际用户数据库。
|
||||
|
||||
## 开源协议
|
||||
|
||||
Copyright (c) 2026 Shu-Ying。
|
||||
本项目采用 GNU Affero General Public License v3.0,
|
||||
SPDX 标识为 `AGPL-3.0-only`,完整条款见 [LICENSE](LICENSE)。
|
||||
|
||||
允许使用、修改、分发及商用,但须遵守协议的版权、源码提供等要求。
|
||||
特别是修改后的版本通过网络与用户交互时,应按第 13 节向这些用户
|
||||
显著提供免费取得该修改版本对应源码的机会。
|
||||
源码地址应指向实际运行版本,不能仅指向不包含这些修改的上游仓库。
|
||||
协议针对程序及其对应源码,不要求公开 API 令牌、用户资料或数据库内容。
|
||||
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "farm-assets-v1",
|
||||
"sha256": "78d6e8e448fd5296b21d471b98ea7d58c81ef78a82b0e192a1ed041bb5fddad9",
|
||||
"size_bytes": 21264561,
|
||||
"sources": {
|
||||
"github": "https://raw.githubusercontent.com/Shu-Ying/farm_service/main/assets/assets.zip",
|
||||
"gitea": "https://gitea.diuse.work/Diuse/farm_service/raw/branch/main/assets/assets.zip",
|
||||
"farm_service": "https://farm.example/v1/assets/78d6e8e448fd5296b21d471b98ea7d58c81ef78a82b0e192a1ed041bb5fddad9/assets.zip"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"version": "farm-assets-v1",
|
||||
"sha256": "78d6e8e448fd5296b21d471b98ea7d58c81ef78a82b0e192a1ed041bb5fddad9",
|
||||
"size_bytes": 21264561,
|
||||
"sources": {
|
||||
"github": "https://raw.githubusercontent.com/Shu-Ying/farm_service/main/assets/assets.zip",
|
||||
"gitea": "https://gitea.diuse.work/Diuse/farm_service/raw/branch/main/assets/assets.zip",
|
||||
"farm_service": "https://farm.example/v1/assets/78d6e8e448fd5296b21d471b98ea7d58c81ef78a82b0e192a1ed041bb5fddad9/assets.zip"
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
# 资源分发接口与三端接入约定
|
||||
|
||||
本文件位于 farm_service 项目。服务端接口及准备工具已实现,
|
||||
素材发布文件位于本仓库根目录 `assets/`。当前文件只完成本地准备,
|
||||
尚未提交或发布到 GitHub/Gitea,不能据此认定远端直链已经可用。
|
||||
活动接口尚未实施,不因为预留服务地址就返回虚构的活动数据。
|
||||
|
||||
## 已确认的客户端配置约定
|
||||
|
||||
两个配置项始终同时存在,不根据选项隐藏:
|
||||
|
||||
| 配置 | 约定 |
|
||||
| --- | --- |
|
||||
| 资源获取地址 | 选项 Github、Gitea、farm_service;默认 Github |
|
||||
| farm_service 地址 | 独立的服务基础地址,供资源、活动等功能共同使用 |
|
||||
|
||||
选择 Github 或 Gitea 时,farm_service 地址仍保留,未来活动查询仍可使用。
|
||||
选择 farm_service 获取资源时,该地址必须有效。客户端根据此配置构造
|
||||
`/v1/assets/{sha256}/assets.zip` 请求,不依赖清单中服务地址的占位值。
|
||||
三端接入状态及具体配置字段以插件实现为准,不能把此文档当作线上验证。
|
||||
|
||||
Farm当前本地已接入共享启动校验/下载器,三端插件包不再包含assets.zip。
|
||||
NoneBot字段为`FARM_RESOURCE_SOURCE`、`FARM_SERVICE_URL`;AstrBot字段为
|
||||
`resource_source`、`farm_service_url`;真寻配置名为「资源获取地址」、
|
||||
「farm_service 地址」。均默认Github,服务地址默认空,修改后重载。
|
||||
源码及离线测试已适配不代表真实公网下载或宿主验证已完成。
|
||||
|
||||
## 仓库文件与发布位置
|
||||
|
||||
```text
|
||||
assets/
|
||||
manifest.json
|
||||
assets.zip
|
||||
```
|
||||
|
||||
`assets/manifest.json` 和 `assets/assets.zip` 是实际发布文件;
|
||||
`docs/assets.manifest.example.json` 与实际清单保持一致,仅用于阅读示例。
|
||||
ZIP 从现有农场素材复制,源文件不由准备工具删除。
|
||||
后续素材发布只更新并提交 farm_service 仓库内的这组文件,
|
||||
不要把 ZIP 加回 NoneBot、真寻或 AstrBot 的插件仓库、生成目录或发布包。
|
||||
插件可以携带绑定版本的轻量清单,但不携带 `assets.zip`。
|
||||
|
||||
发布到 `main` 分支后,公开静态清单直链为:
|
||||
|
||||
- GitHub:`https://raw.githubusercontent.com/Shu-Ying/farm_service/main/assets/manifest.json`
|
||||
- Gitea:`https://gitea.diuse.work/Diuse/farm_service/raw/branch/main/assets/manifest.json`
|
||||
|
||||
对应 ZIP 位于相同目录,文件名为 `assets.zip`。选择 GitHub/Gitea 时
|
||||
可独立访问公开静态清单和 ZIP,无需 farm_service 在线。
|
||||
本轮没有提交、推送或验证这些远端文件。
|
||||
|
||||
## 服务端部署文件
|
||||
|
||||
服务不从用户输入下载ZIP,也不代理任意URL。管理员准备本地发布文件;
|
||||
`FARM_ASSET_MANIFEST`指向JSON,其同目录固定文件名为`assets.zip`。
|
||||
启动读取并检查schema、版本、URL、大小、整个ZIP的SHA256及ZIP文件头。
|
||||
校验失败拒绝启动,不对外提供损坏素材。未设置该环境变量时,其余服务
|
||||
正常启动,资源接口返回503。现有用户资料接口仍需要Bearer鉴权。
|
||||
|
||||
ZIP不解压。启用后保留最多64 MiB的单份只读内存快照,请求共享这份内容;
|
||||
不会每个请求重复读取磁盘和计算SHA。运行中修改磁盘不会改变当前返回内容,
|
||||
更新清单或ZIP需先准备一套完整目录,再修改配置并重启服务。
|
||||
当前仅托管一个活动资源版本;请求其他SHA返回404,历史版本仍需保留在
|
||||
GitHub/Gitea中,或以后扩展多版本服务。资源版本不必等于插件版本。
|
||||
|
||||
## 用Rust工具生成清单
|
||||
|
||||
不手填SHA。工具从现有ZIP计算SHA256与字节数,并复制文件、输出JSON;
|
||||
输出目录必须不存在,不覆盖旧发布目录,不上传、不访问远端。
|
||||
|
||||
[实际清单](../assets/manifest.json)及[完整JSON示例](assets.manifest.example.json)
|
||||
已使用当前农场 ZIP 生成真实 SHA 与大小。生成根目录 `assets/` 的示例如下;
|
||||
已存在时请选择新的临时输出目录,检查后再替换一整套发布文件。
|
||||
|
||||
```powershell
|
||||
cargo run --locked --bin prepare_assets -- `
|
||||
D:\Work\farm\src\farm_render\data\assets.zip `
|
||||
.\assets `
|
||||
farm-assets-v1 `
|
||||
https://raw.githubusercontent.com/Shu-Ying/farm_service/main/assets/assets.zip `
|
||||
https://gitea.diuse.work/Diuse/farm_service/raw/branch/main/assets/assets.zip `
|
||||
https://farm.example
|
||||
```
|
||||
|
||||
`https://farm.example` 是明确的占位域名(placeholder),不是已部署服务。
|
||||
目前未提供公网地址,所以实际清单及示例暂保留该值;客户端使用独立的
|
||||
「farm_service 地址」配置构造请求,不请求该占位地址。
|
||||
部署时应通过准备工具改为真实公网基础地址,支持反向代理路径前缀。
|
||||
公网访问由部署者配置HTTPS代理,
|
||||
服务仍默认监听127.0.0.1:8080。不要使用GitHub/Gitea仓库网页URL替代raw文件URL。
|
||||
|
||||
准备完成后设置环境变量(PowerShell示例):
|
||||
|
||||
```powershell
|
||||
$env:FARM_ASSET_MANIFEST = (Resolve-Path .\assets\manifest.json).Path
|
||||
# FARM_API_TOKEN等原有必填配置沿用原部署方式,不在本文放入真实令牌。
|
||||
cargo run --locked --bin farm_service
|
||||
```
|
||||
|
||||
此时依旧需要原有用户服务的FARM_API_TOKEN;公开资源下载不使用它。
|
||||
不要将资料API令牌打包进插件或写入资源JSON。
|
||||
|
||||
## JSON协议
|
||||
|
||||
`schema`固定为1;工具实际生成有效64位小写SHA256,下面仅解释字段:
|
||||
|
||||
| 字段 | 类型 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| schema | 整数 | 清单协议版本1 |
|
||||
| version | 字符串 | 资源发布标签,1~64个字母、数字、点、下划线或连字符 |
|
||||
| sha256 | 字符串 | 整个ZIP的64位小写SHA256 |
|
||||
| size_bytes | 整数 | ZIP字节数,1~67,108,864 |
|
||||
| sources.github | 字符串 | GitHub绝对HTTPS下载URL |
|
||||
| sources.gitea | 字符串 | Gitea绝对HTTPS下载URL |
|
||||
| sources.farm_service | 字符串 | 服务绝对HTTPS下载URL,包含相同SHA256 |
|
||||
|
||||
JSON不接受未知字段;URL不允许凭据、查询参数或fragment。
|
||||
清单大小限制16 KiB。服务端校验本地ZIP,不会主动探测两个镜像是否一致;
|
||||
发布者须确保三源文件字节相同。主分支raw文件可能变更,长期建议采用
|
||||
固定提交、标签或Release附件直链。SHA固定而raw发生变化时,客户端必须
|
||||
拒绝新字节,不能通过重新获取任意清单来跳过版本兼容性检查。
|
||||
|
||||
## HTTP接口
|
||||
|
||||
### GET /v1/assets/manifest.json
|
||||
|
||||
公开,无需资料API令牌;200返回上述JSON,Cache-Control为no-cache。
|
||||
未启用资源服务时503,错误码`assets_unavailable`。
|
||||
|
||||
### GET /v1/assets/{sha256}/assets.zip
|
||||
|
||||
公开,只有SHA与当前校验资源一致时返回200,Content-Type为application/zip。
|
||||
下载内容与清单的SHA及大小一致;ETag为带双引号的完整SHA。
|
||||
支持If-None-Match条件请求,命中返回304;返回不可变长期缓存标记。
|
||||
未知或旧SHA返回404及`asset_not_found`。不支持任意路径访问,也不执行解压。
|
||||
不是活动接口,不读取玩家库。未启用资源服务时返回503。
|
||||
|
||||
## 三端下载器接入约定
|
||||
|
||||
1. 启动时计算本地ZIP的SHA256;符合插件绑定的资源版本和摘要则直接复用。
|
||||
2. 缺失或不匹配才按「资源获取地址」选择源下载;网络不可用不应损坏旧文件。
|
||||
3. 将内容下载到临时文件,限制字节数和超时,校验大小、SHA及必要ZIP条目,
|
||||
通过后原子替换,避免并发启动重复下载。
|
||||
4. 只有摘要和布局元数据匹配的ZIP才能参与绘图,不能任意跟随服务的最新版本。
|
||||
5. 清单可以从farm_service接口读取,也可将工具生成的同一JSON发布到镜像,
|
||||
并随插件保留经过版本绑定的清单,避免选择Github后又强依赖服务在线。
|
||||
6. 三端共用同一实现;无可用素材时保留文字功能并提示管理员,不能使用损坏包。
|
||||
7. 当前按所选源下载,不自动跨源回退;失败保留文字模式,调整配置后重载重试。
|
||||
8. 本地缓存路径为插件数据目录`assets/<sha256>/assets.zip`,可手动预置离线包。
|
||||
同进程并发启动合并下载,跨进程使用独立临时文件与原子替换保证写入完整。
|
||||
不解压到磁盘,缓存中存在旧版本时不自动删除,便于回滚。
|
||||
|
||||
## 离线验证
|
||||
|
||||
```text
|
||||
cargo fmt --check
|
||||
cargo test --locked --offline --all-targets
|
||||
cargo clippy --locked --offline --all-targets -- -D warnings
|
||||
```
|
||||
|
||||
测试覆盖公开清单、ZIP下载、条件缓存、磁盘变动后快照一致性、损坏/缺失
|
||||
文件及非法URL拒绝、资源未启用,另保留原用户接口鉴权和持久化测试。
|
||||
离线验证不代表真实公网部署、镜像发布或三端集成完成。
|
||||
@@ -0,0 +1,36 @@
|
||||
# 初始化验证记录
|
||||
|
||||
日期:2026-10-21。验证环境:Windows,rustc/cargo 1.98.0。
|
||||
|
||||
## 已完成
|
||||
|
||||
- 从用户指定的空仓库克隆至 `D:\Work\farm_service`。
|
||||
- 初始化 Rust 2024 二进制应用和中文 README;协议初始为 MIT,后于
|
||||
2026-10-21 按用户选择切换为 AGPL v3(AGPL-3.0-only)。
|
||||
- 用户资料使用单条 SQLite UPSERT 原子写入,按平台和用户 ID 去重。
|
||||
- 首次正常编译完成,生成 `Cargo.lock`。
|
||||
- `cargo test --all-targets`:6 项集成测试通过,无失败。
|
||||
- `cargo fmt --check`:通过。
|
||||
- `cargo clippy --locked --all-targets -- -D warnings`:通过,无警告。
|
||||
- 真实本机 HTTP:健康检查、资料写入、资料读取、无令牌 401 均通过。
|
||||
- 指定 info 日志级别,确认启动及资料写入事件写入每日 JSON 文件;
|
||||
日志只记录事件和平台,不包含测试用户 ID、昵称或令牌。
|
||||
- Git 忽略规则实际检查:target、数据库、日志、.env、.env.local 被忽略;
|
||||
Cargo.lock、.env.example 可纳入版本控制。
|
||||
|
||||
## 验证边界
|
||||
|
||||
- 测试使用临时数据库与合成资料;没有采集真实 QQ 用户信息。
|
||||
- 测试 HTTP 进程已停止;没有部署常驻服务。
|
||||
- 未接入农场插件自动上报,未验证真实 QQ 群、官方 QQ 或公网代理。
|
||||
- 本轮未实现活动管理、中心账本、多租户鉴权、用户删除及数据自动清理。
|
||||
- 未执行 Linux 运行验证、依赖漏洞专项扫描或生产负载测试。
|
||||
- 未提交、推送或创建 PR。新文件保留在本地仓库,供后续检查。
|
||||
|
||||
## 后续接入顺序
|
||||
|
||||
1. 在农场接入层取得可信的 QQ 号码与昵称,确认信息用途及保留政策。
|
||||
2. 将平台命名空间明确为普通 qq,不能将官方 QQ OpenID 填成 QQ 号码。
|
||||
3. 用仅保存在服务端和机器人配置中的令牌调用资料接口。
|
||||
4. 为上报配置短超时;资料服务故障不能回滚已完成的基础农场操作。
|
||||
5. 生产部署前落实 HTTPS、限流、访问日志脱敏、资料删除与备份政策。
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Platform separates identities; the API currently supports ordinary QQ numbers.
|
||||
CREATE TABLE users (
|
||||
platform TEXT NOT NULL,
|
||||
platform_user_id TEXT NOT NULL,
|
||||
nickname TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
|
||||
PRIMARY KEY (platform, platform_user_id),
|
||||
CHECK (platform IN ('qq', 'telegram', 'discord')),
|
||||
CHECK (length(platform_user_id) BETWEEN 1 AND 32),
|
||||
CHECK (length(nickname) BETWEEN 1 AND 64)
|
||||
);
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{DefaultBodyLimit, Path, Request, State, rejection::JsonRejection},
|
||||
http::{StatusCode, header},
|
||||
middleware::{self, Next},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, put},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::{FromRow, SqlitePool};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
/// Shared HTTP dependencies. The token must never be logged.
|
||||
#[derive(Clone)]
|
||||
struct AppState {
|
||||
/// Persistent profile storage.
|
||||
pool: SqlitePool,
|
||||
/// Expected full Authorization header.
|
||||
authorization: Arc<str>,
|
||||
}
|
||||
|
||||
/// One explicitly supported account namespace.
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum Platform {
|
||||
/// QQ number from a trusted OneBot-style adapter, not official QQ OpenID.
|
||||
Qq,
|
||||
/// Telegram numeric user ID.
|
||||
Telegram,
|
||||
/// Discord numeric user ID.
|
||||
Discord,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Qq => "qq",
|
||||
Self::Telegram => "telegram",
|
||||
Self::Discord => "discord",
|
||||
}
|
||||
}
|
||||
|
||||
fn max_id_len(self) -> usize {
|
||||
match self {
|
||||
Self::Qq => 20,
|
||||
Self::Telegram | Self::Discord => 32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// User profile supplied by an authenticated bot deployment.
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct UserInput {
|
||||
/// Account namespace used together with the ID as the unique key.
|
||||
platform: Platform,
|
||||
/// Decimal string; for qq this is the QQ number.
|
||||
platform_user_id: String,
|
||||
/// Current display name (QQ nickname on the qq platform).
|
||||
nickname: String,
|
||||
}
|
||||
|
||||
impl UserInput {
|
||||
fn validate(&mut self) -> Result<(), ApiError> {
|
||||
validate_id(self.platform, &self.platform_user_id)?;
|
||||
self.nickname = self.nickname.trim().to_owned();
|
||||
if self.nickname.is_empty()
|
||||
|| self.nickname.chars().count() > 64
|
||||
|| self.nickname.chars().any(char::is_control)
|
||||
{
|
||||
return Err(ApiError::bad_request(
|
||||
"nickname must contain 1..=64 characters without control characters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Persisted profile and UTC timestamps returned to the authenticated caller.
|
||||
#[derive(Serialize, FromRow)]
|
||||
struct UserProfile {
|
||||
/// Stored platform namespace.
|
||||
platform: String,
|
||||
/// Stored decimal identity, preserved as a string.
|
||||
platform_user_id: String,
|
||||
/// Most recently reported nickname.
|
||||
nickname: String,
|
||||
/// First successful registration time, in UTC.
|
||||
created_at: String,
|
||||
/// Last successful profile write time, in UTC.
|
||||
updated_at: String,
|
||||
}
|
||||
|
||||
/// Stable machine-readable error without request data.
|
||||
#[derive(Serialize)]
|
||||
struct ErrorBody {
|
||||
/// Error category.
|
||||
code: &'static str,
|
||||
/// Safe explanation without user identifiers or database details.
|
||||
message: &'static str,
|
||||
}
|
||||
|
||||
/// Internal error mapping to an HTTP response.
|
||||
struct ApiError {
|
||||
/// HTTP status for this error.
|
||||
status: StatusCode,
|
||||
/// Safe public payload.
|
||||
body: ErrorBody,
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
fn new(status: StatusCode, code: &'static str, message: &'static str) -> Self {
|
||||
Self {
|
||||
status,
|
||||
body: ErrorBody { code, message },
|
||||
}
|
||||
}
|
||||
|
||||
fn bad_request(message: &'static str) -> Self {
|
||||
Self::new(StatusCode::BAD_REQUEST, "invalid_input", message)
|
||||
}
|
||||
|
||||
fn database(error: sqlx::Error) -> Self {
|
||||
// Do not log error text: constraint failures may contain user data.
|
||||
tracing::error!(
|
||||
kind = database_error_kind(&error),
|
||||
"database_operation_failed"
|
||||
);
|
||||
Self::new(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
"storage_unavailable",
|
||||
"storage temporarily unavailable",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn database_error_kind(error: &sqlx::Error) -> &'static str {
|
||||
match error {
|
||||
sqlx::Error::Database(_) => "database",
|
||||
sqlx::Error::PoolTimedOut => "pool_timeout",
|
||||
sqlx::Error::PoolClosed => "pool_closed",
|
||||
_ => "storage",
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
(self.status, Json(self.body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a router; only the readiness endpoint is public.
|
||||
pub fn router(pool: SqlitePool, api_token: String) -> Router {
|
||||
let state = AppState {
|
||||
pool,
|
||||
authorization: Arc::from(format!("Bearer {api_token}")),
|
||||
};
|
||||
let protected = Router::new()
|
||||
.route("/v1/users", put(upsert_user))
|
||||
.route("/v1/users/{platform}/{platform_user_id}", get(get_user))
|
||||
.route_layer(middleware::from_fn_with_state(state.clone(), authenticate));
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
.merge(protected)
|
||||
.layer(DefaultBodyLimit::max(4096))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
async fn authenticate(State(state): State<AppState>, request: Request, next: Next) -> Response {
|
||||
let supplied = request.headers().get(header::AUTHORIZATION);
|
||||
let authorized = supplied
|
||||
.is_some_and(|value| bool::from(value.as_bytes().ct_eq(state.authorization.as_bytes())));
|
||||
if !authorized {
|
||||
tracing::warn!("authentication_rejected");
|
||||
let mut response = ApiError::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"unauthorized",
|
||||
"valid bearer token required",
|
||||
)
|
||||
.into_response();
|
||||
response.headers_mut().insert(
|
||||
header::WWW_AUTHENTICATE,
|
||||
header::HeaderValue::from_static("Bearer"),
|
||||
);
|
||||
return response;
|
||||
}
|
||||
next.run(request).await
|
||||
}
|
||||
|
||||
/// Database readiness result.
|
||||
#[derive(Serialize)]
|
||||
struct Health {
|
||||
/// Ready only after a successful database probe.
|
||||
status: &'static str,
|
||||
}
|
||||
|
||||
async fn health(State(state): State<AppState>) -> Result<Json<Health>, ApiError> {
|
||||
sqlx::query("SELECT 1")
|
||||
.execute(&state.pool)
|
||||
.await
|
||||
.map_err(ApiError::database)?;
|
||||
Ok(Json(Health { status: "ok" }))
|
||||
}
|
||||
|
||||
async fn upsert_user(
|
||||
State(state): State<AppState>,
|
||||
payload: Result<Json<UserInput>, JsonRejection>,
|
||||
) -> Result<Json<UserProfile>, ApiError> {
|
||||
let Json(mut input) = payload.map_err(|rejection| {
|
||||
ApiError::new(
|
||||
rejection.status(),
|
||||
"invalid_json",
|
||||
"expected JSON profile; check field names, types and body size",
|
||||
)
|
||||
})?;
|
||||
input.validate()?;
|
||||
// One SQL statement makes create/update atomic under concurrent reports.
|
||||
let profile = sqlx::query_as::<_, UserProfile>(
|
||||
"INSERT INTO users (platform, platform_user_id, nickname)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(platform, platform_user_id) DO UPDATE SET
|
||||
nickname = excluded.nickname,
|
||||
updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
|
||||
RETURNING platform, platform_user_id, nickname, created_at, updated_at",
|
||||
)
|
||||
.bind(input.platform.as_str())
|
||||
.bind(&input.platform_user_id)
|
||||
.bind(&input.nickname)
|
||||
.fetch_one(&state.pool)
|
||||
.await
|
||||
.map_err(ApiError::database)?;
|
||||
tracing::info!(platform = input.platform.as_str(), "user_profile_saved");
|
||||
Ok(Json(profile))
|
||||
}
|
||||
|
||||
async fn get_user(
|
||||
State(state): State<AppState>,
|
||||
Path((platform, platform_user_id)): Path<(Platform, String)>,
|
||||
) -> Result<Json<UserProfile>, ApiError> {
|
||||
validate_id(platform, &platform_user_id)?;
|
||||
let profile = sqlx::query_as::<_, UserProfile>(
|
||||
"SELECT platform, platform_user_id, nickname, created_at, updated_at
|
||||
FROM users WHERE platform = ? AND platform_user_id = ?",
|
||||
)
|
||||
.bind(platform.as_str())
|
||||
.bind(platform_user_id)
|
||||
.fetch_optional(&state.pool)
|
||||
.await
|
||||
.map_err(ApiError::database)?
|
||||
.ok_or_else(|| ApiError::new(StatusCode::NOT_FOUND, "not_found", "user not found"))?;
|
||||
Ok(Json(profile))
|
||||
}
|
||||
|
||||
fn validate_id(platform: Platform, id: &str) -> Result<(), ApiError> {
|
||||
if id.is_empty()
|
||||
|| id.len() > platform.max_id_len()
|
||||
|| !id.bytes().all(|byte| byte.is_ascii_digit())
|
||||
|| id.starts_with('0')
|
||||
{
|
||||
return Err(ApiError::bad_request(
|
||||
"platform_user_id must be a nonzero decimal string without leading zeros",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
//! Public, versioned asset manifest and an immutable in-memory ZIP snapshot.
|
||||
//! Profiles remain behind their existing bearer authentication middleware.
|
||||
|
||||
use std::{fs::File, io::Read, path::Path};
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::Bytes,
|
||||
extract::{Path as RoutePath, State},
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use url::Url;
|
||||
|
||||
/// Maximum ZIP bytes held in memory for the active immutable snapshot.
|
||||
pub const MAX_BUNDLE_BYTES: usize = 64 * 1024 * 1024;
|
||||
/// Maximum JSON manifest size accepted from disk.
|
||||
const MAX_MANIFEST_BYTES: usize = 16 * 1024;
|
||||
|
||||
/// Absolute HTTPS mirrors for the same exact ZIP bytes.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Sources {
|
||||
/// Public GitHub raw or versioned release URL.
|
||||
pub github: String,
|
||||
/// Owner-controlled Gitea raw or versioned release URL.
|
||||
pub gitea: String,
|
||||
/// Public farm_service download endpoint; never a profile API token.
|
||||
pub farm_service: String,
|
||||
}
|
||||
|
||||
/// Public JSON contract; schema and asset version are separate concepts.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Manifest {
|
||||
/// Contract version, currently one.
|
||||
pub schema: u32,
|
||||
/// Immutable release label selected by the operator.
|
||||
pub version: String,
|
||||
/// Lowercase SHA256 of the complete ZIP, not individual pictures.
|
||||
pub sha256: String,
|
||||
/// Compressed ZIP byte length for transfer limits and integrity checks.
|
||||
pub size_bytes: u64,
|
||||
/// Download mirrors containing byte-identical content.
|
||||
pub sources: Sources,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(self.schema == 1, "unsupported asset manifest schema");
|
||||
ensure!(
|
||||
!self.version.is_empty()
|
||||
&& self.version.len() <= 64
|
||||
&& self
|
||||
.version
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)),
|
||||
"invalid asset version"
|
||||
);
|
||||
ensure!(
|
||||
self.sha256.len() == 64
|
||||
&& self
|
||||
.sha256
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
|
||||
"invalid asset SHA256"
|
||||
);
|
||||
ensure!(
|
||||
self.size_bytes > 0 && self.size_bytes <= MAX_BUNDLE_BYTES as u64,
|
||||
"invalid asset size"
|
||||
);
|
||||
for value in [
|
||||
&self.sources.github,
|
||||
&self.sources.gitea,
|
||||
&self.sources.farm_service,
|
||||
] {
|
||||
validate_url(value)?;
|
||||
}
|
||||
let service_url = Url::parse(&self.sources.farm_service)?;
|
||||
ensure!(
|
||||
service_url
|
||||
.path()
|
||||
.ends_with(&format!("/v1/assets/{}/assets.zip", self.sha256)),
|
||||
"farm_service URL must include the bundle SHA256"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_url(value: &str) -> Result<()> {
|
||||
ensure!(value.len() <= 2048, "asset URL too long");
|
||||
let url = Url::parse(value).context("invalid asset URL")?;
|
||||
ensure!(
|
||||
url.scheme() == "https" && url.host_str().is_some(),
|
||||
"asset URL requires HTTPS"
|
||||
);
|
||||
ensure!(
|
||||
url.username().is_empty()
|
||||
&& url.password().is_none()
|
||||
&& url.query().is_none()
|
||||
&& url.fragment().is_none(),
|
||||
"asset URL cannot contain credentials, queries or fragments"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read_bounded(path: &Path, max: usize) -> Result<Vec<u8>> {
|
||||
let file = File::open(path).context("cannot open asset file")?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(max as u64 + 1).read_to_end(&mut bytes)?;
|
||||
ensure!(bytes.len() <= max, "asset file exceeds size limit");
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// A verified snapshot shared by HTTP requests without disk rereads or copies.
|
||||
#[derive(Clone)]
|
||||
pub struct AssetBundle {
|
||||
/// Validated public manifest.
|
||||
manifest: Manifest,
|
||||
/// Exactly the bytes used to compute the manifest digest.
|
||||
content: Bytes,
|
||||
}
|
||||
|
||||
impl AssetBundle {
|
||||
/// Load manifest.json and its sibling assets.zip, verifying both at startup.
|
||||
pub fn load(manifest_path: &Path) -> Result<Self> {
|
||||
let manifest: Manifest =
|
||||
serde_json::from_slice(&read_bounded(manifest_path, MAX_MANIFEST_BYTES)?)
|
||||
.context("invalid asset manifest JSON")?;
|
||||
manifest.validate()?;
|
||||
let content = read_bounded(
|
||||
&manifest_path.with_file_name("assets.zip"),
|
||||
MAX_BUNDLE_BYTES,
|
||||
)?;
|
||||
ensure!(
|
||||
content.len() as u64 == manifest.size_bytes,
|
||||
"asset size mismatch"
|
||||
);
|
||||
ensure!(digest(&content) == manifest.sha256, "asset SHA256 mismatch");
|
||||
ensure!(
|
||||
content.starts_with(b"PK\x03\x04"),
|
||||
"asset file is not a ZIP"
|
||||
);
|
||||
tracing::info!(asset_version = %manifest.version, bytes = content.len(), "assets_verified");
|
||||
Ok(Self {
|
||||
manifest,
|
||||
content: Bytes::from(content),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn manifest(&self) -> &Manifest {
|
||||
&self.manifest
|
||||
}
|
||||
}
|
||||
|
||||
pub fn digest(content: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(content))
|
||||
}
|
||||
|
||||
/// Build independent public read-only routes. None means assets are disabled.
|
||||
pub fn router(bundle: Option<AssetBundle>) -> Router {
|
||||
Router::new()
|
||||
.route("/v1/assets/manifest.json", get(get_manifest))
|
||||
.route("/v1/assets/{sha256}/assets.zip", get(download))
|
||||
.with_state(bundle)
|
||||
}
|
||||
|
||||
async fn get_manifest(State(bundle): State<Option<AssetBundle>>) -> Response {
|
||||
match bundle {
|
||||
Some(bundle) => {
|
||||
([(header::CACHE_CONTROL, "no-cache")], Json(bundle.manifest)).into_response()
|
||||
}
|
||||
None => unavailable(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn download(
|
||||
State(bundle): State<Option<AssetBundle>>,
|
||||
RoutePath(sha256): RoutePath<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let Some(bundle) = bundle else {
|
||||
return unavailable();
|
||||
};
|
||||
if sha256 != bundle.manifest.sha256 {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(serde_json::json!({
|
||||
"code": "asset_not_found", "message": "requested asset version is unavailable"
|
||||
})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let etag = format!("\"{}\"", bundle.manifest.sha256);
|
||||
let cached = headers
|
||||
.get(header::IF_NONE_MATCH)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|value| {
|
||||
value
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.any(|v| v == "*" || v.trim_start_matches("W/") == etag)
|
||||
});
|
||||
let mut response = if cached {
|
||||
StatusCode::NOT_MODIFIED.into_response()
|
||||
} else {
|
||||
(
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/zip"),
|
||||
(
|
||||
header::CONTENT_DISPOSITION,
|
||||
"attachment; filename=assets.zip",
|
||||
),
|
||||
],
|
||||
bundle.content,
|
||||
)
|
||||
.into_response()
|
||||
};
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(header::ETAG, etag.parse().expect("hex digest header"));
|
||||
response.headers_mut().insert(
|
||||
header::CACHE_CONTROL,
|
||||
"public, max-age=31536000, immutable"
|
||||
.parse()
|
||||
.expect("constant header"),
|
||||
);
|
||||
response
|
||||
}
|
||||
|
||||
fn unavailable() -> Response {
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(serde_json::json!({
|
||||
"code": "assets_unavailable", "message": "asset distribution is not configured"
|
||||
})),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Prepare a local asset directory; never uploads files or fetches mirrors.
|
||||
use std::{env, fs, path::PathBuf};
|
||||
|
||||
use anyhow::{Result, ensure};
|
||||
use farm_service::assets::{AssetBundle, MAX_BUNDLE_BYTES, Manifest, Sources, digest};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<String> = env::args().skip(1).collect();
|
||||
ensure!(
|
||||
args.len() == 6,
|
||||
"usage: prepare_assets ZIP OUTPUT_DIR VERSION GITHUB_URL GITEA_URL PUBLIC_BASE_URL"
|
||||
);
|
||||
let source = PathBuf::from(&args[0]);
|
||||
let output = PathBuf::from(&args[1]);
|
||||
ensure!(!output.exists(), "use a new output directory");
|
||||
ensure!(
|
||||
fs::metadata(&source)?.len() <= MAX_BUNDLE_BYTES as u64,
|
||||
"asset ZIP too large"
|
||||
);
|
||||
let content = fs::read(source)?;
|
||||
ensure!(
|
||||
content.starts_with(b"PK\x03\x04"),
|
||||
"asset file is not a ZIP"
|
||||
);
|
||||
let sha256 = digest(&content);
|
||||
let public = args[5].trim_end_matches('/');
|
||||
let manifest = Manifest {
|
||||
schema: 1,
|
||||
version: args[2].clone(),
|
||||
sources: Sources {
|
||||
github: args[3].clone(),
|
||||
gitea: args[4].clone(),
|
||||
farm_service: format!("{public}/v1/assets/{sha256}/assets.zip"),
|
||||
},
|
||||
sha256,
|
||||
size_bytes: content.len() as u64,
|
||||
};
|
||||
manifest.validate()?;
|
||||
fs::create_dir_all(&output)?;
|
||||
fs::write(output.join("assets.zip"), content)?;
|
||||
fs::write(
|
||||
output.join("manifest.json"),
|
||||
serde_json::to_vec_pretty(&manifest)?,
|
||||
)?;
|
||||
AssetBundle::load(&output.join("manifest.json"))?;
|
||||
println!(
|
||||
"prepared {} ({} bytes, SHA256 {})",
|
||||
manifest.version, manifest.size_bytes, manifest.sha256
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use std::{env, net::SocketAddr, path::PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
|
||||
/// Startup configuration. Deliberately not Debug: it contains a secret.
|
||||
pub struct Config {
|
||||
/// Listen address; loopback by default.
|
||||
pub bind: SocketAddr,
|
||||
/// Service-to-service bearer token; never supplied by ordinary QQ players.
|
||||
pub api_token: String,
|
||||
/// Directory containing the persistent SQLite database.
|
||||
pub data_dir: PathBuf,
|
||||
/// Directory for daily JSON log files.
|
||||
pub log_dir: PathBuf,
|
||||
/// Optional verified asset manifest; sibling assets.zip is loaded once.
|
||||
pub asset_manifest: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn from_env() -> Result<Self> {
|
||||
let api_token =
|
||||
env::var("FARM_API_TOKEN").context("FARM_API_TOKEN must be set to a random token")?;
|
||||
ensure!(
|
||||
api_token.len() >= 32
|
||||
&& api_token.len() <= 256
|
||||
&& api_token.bytes().all(|b| b.is_ascii_graphic()),
|
||||
"FARM_API_TOKEN must contain 32..=256 visible ASCII characters"
|
||||
);
|
||||
Ok(Self {
|
||||
bind: env::var("FARM_BIND")
|
||||
.unwrap_or_else(|_| "127.0.0.1:8080".into())
|
||||
.parse()
|
||||
.context("invalid FARM_BIND address")?,
|
||||
api_token,
|
||||
asset_manifest: env::var_os("FARM_ASSET_MANIFEST").map(PathBuf::from),
|
||||
data_dir: env::var_os("FARM_DATA_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("data")),
|
||||
log_dir: env::var_os("FARM_LOG_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from("logs")),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
use anyhow::Result;
|
||||
use sqlx::{
|
||||
ConnectOptions, SqlitePool,
|
||||
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions},
|
||||
};
|
||||
|
||||
/// Open the standalone service database and apply checked-in migrations.
|
||||
pub async fn open_database(path: &Path) -> Result<SqlitePool> {
|
||||
let options = SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.create_if_missing(true)
|
||||
.journal_mode(SqliteJournalMode::Wal)
|
||||
.busy_timeout(Duration::from_secs(5))
|
||||
// SQL statements and parameters must not enter the log.
|
||||
.disable_statement_logging();
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(5)
|
||||
.acquire_timeout(Duration::from_secs(5))
|
||||
.connect_with(options)
|
||||
.await?;
|
||||
sqlx::migrate!().run(&pool).await?;
|
||||
Ok(pool)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod api;
|
||||
pub mod assets;
|
||||
pub mod config;
|
||||
pub mod db;
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
use anyhow::{Context, Result};
|
||||
use farm_service::{api, assets, config::Config, db};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let config = Config::from_env()?;
|
||||
std::fs::create_dir_all(&config.log_dir)?;
|
||||
let file = tracing_appender::rolling::daily(&config.log_dir, "farm_service.jsonl");
|
||||
let (writer, _log_guard) = tracing_appender::non_blocking(file);
|
||||
tracing_subscriber::fmt()
|
||||
.json()
|
||||
.with_ansi(false)
|
||||
.with_env_filter(
|
||||
EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("farm_service=info")),
|
||||
)
|
||||
.with_writer(writer)
|
||||
.init();
|
||||
|
||||
let bundle = config
|
||||
.asset_manifest
|
||||
.as_deref()
|
||||
.map(assets::AssetBundle::load)
|
||||
.transpose()
|
||||
.context("asset startup verification failed")?;
|
||||
std::fs::create_dir_all(&config.data_dir)?;
|
||||
let pool = db::open_database(&config.data_dir.join("farm_service.sqlite3"))
|
||||
.await
|
||||
.context("database startup failed")?;
|
||||
let listener = tokio::net::TcpListener::bind(config.bind).await?;
|
||||
tracing::info!(address = %listener.local_addr()?, "service_ready");
|
||||
let app = api::router(pool.clone(), config.api_token).merge(assets::router(bundle));
|
||||
let result = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown())
|
||||
.await;
|
||||
pool.close().await;
|
||||
result.context("HTTP server failed")?;
|
||||
tracing::info!("service_stopped");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown() {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let mut terminate =
|
||||
signal(SignalKind::terminate()).expect("failed to register SIGTERM handler");
|
||||
tokio::select! {
|
||||
_ = tokio::signal::ctrl_c() => {},
|
||||
_ = terminate.recv() => {},
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode},
|
||||
};
|
||||
use farm_service::assets::{self, AssetBundle, Manifest, Sources, digest};
|
||||
use tower::ServiceExt;
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, Manifest, Vec<u8>) {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
// A real ZIP with one member named x containing a; no external ZIP dependency.
|
||||
let content = vec![
|
||||
80, 75, 3, 4, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 190, 183, 232, 1, 0, 0, 0, 1, 0, 0, 0, 1,
|
||||
0, 0, 0, 120, 97, 80, 75, 1, 2, 20, 3, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 67, 190, 183, 232, 1,
|
||||
0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128, 1, 0, 0, 0, 0, 120, 80, 75,
|
||||
5, 6, 0, 0, 0, 0, 1, 0, 1, 0, 47, 0, 0, 0, 32, 0, 0, 0, 0, 0,
|
||||
];
|
||||
let sha256 = digest(&content);
|
||||
let manifest = Manifest {
|
||||
schema: 1,
|
||||
version: "assets-test-1".into(),
|
||||
size_bytes: content.len() as u64,
|
||||
sources: Sources {
|
||||
github: "https://raw.githubusercontent.com/owner/farm/main/assets.zip".into(),
|
||||
gitea: "https://gitea.example/owner/farm/raw/branch/main/assets.zip".into(),
|
||||
farm_service: format!("https://farm.example/v1/assets/{sha256}/assets.zip"),
|
||||
},
|
||||
sha256,
|
||||
};
|
||||
std::fs::write(directory.path().join("assets.zip"), &content).unwrap();
|
||||
save(&directory, &manifest);
|
||||
(directory, manifest, content)
|
||||
}
|
||||
|
||||
fn save(directory: &tempfile::TempDir, manifest: &Manifest) {
|
||||
std::fs::write(
|
||||
directory.path().join("manifest.json"),
|
||||
serde_json::to_vec(manifest).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_manifest_download_cache_and_snapshot() {
|
||||
let (directory, manifest, content) = fixture();
|
||||
let bundle = AssetBundle::load(&directory.path().join("manifest.json")).unwrap();
|
||||
let app = assets::router(Some(bundle));
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/assets/manifest.json")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = to_bytes(response.into_body(), 16384).await.unwrap();
|
||||
let result: Manifest = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(result.sha256, manifest.sha256);
|
||||
assert_eq!(result.sources.github, manifest.sources.github);
|
||||
// Requests must keep serving exactly the already-verified bytes, even if disk changes.
|
||||
std::fs::write(directory.path().join("assets.zip"), b"changed").unwrap();
|
||||
let uri = format!("/v1/assets/{}/assets.zip", manifest.sha256);
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(Request::builder().uri(&uri).body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["content-type"], "application/zip");
|
||||
let etag = response.headers()["etag"].clone();
|
||||
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), content);
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri(uri)
|
||||
.header("if-none-match", etag)
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/assets/unknown/assets.zip")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_corruption_invalid_urls_and_missing_files() {
|
||||
let (directory, original, mut content) = fixture();
|
||||
let path = directory.path().join("manifest.json");
|
||||
for value in [
|
||||
"http://farm.example/a",
|
||||
"https://user:pass@farm.example/a",
|
||||
"https://farm.example/a?q=token",
|
||||
] {
|
||||
let mut manifest = original.clone();
|
||||
manifest.sources.github = value.into();
|
||||
save(&directory, &manifest);
|
||||
assert!(AssetBundle::load(&path).is_err());
|
||||
}
|
||||
let mut manifest = original.clone();
|
||||
manifest.size_bytes += 1;
|
||||
save(&directory, &manifest);
|
||||
assert!(AssetBundle::load(&path).is_err());
|
||||
save(&directory, &original);
|
||||
content[31] ^= 1;
|
||||
std::fs::write(directory.path().join("assets.zip"), content).unwrap();
|
||||
assert!(
|
||||
AssetBundle::load(&path)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("SHA256")
|
||||
);
|
||||
std::fs::write(directory.path().join("assets.zip"), b"corrupt").unwrap();
|
||||
assert!(AssetBundle::load(&path).is_err());
|
||||
std::fs::remove_file(directory.path().join("assets.zip")).unwrap();
|
||||
assert!(AssetBundle::load(&path).is_err());
|
||||
std::fs::write(path.clone(), b"{}").unwrap();
|
||||
assert!(AssetBundle::load(&path).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_resources_do_not_expose_files() {
|
||||
let response = assets::router(None)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.uri("/v1/assets/manifest.json")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_assets_do_not_bypass_profile_authentication() {
|
||||
let (directory, _, _) = fixture();
|
||||
let pool = farm_service::db::open_database(&directory.path().join("users.sqlite3"))
|
||||
.await
|
||||
.unwrap();
|
||||
let bundle = AssetBundle::load(&directory.path().join("manifest.json")).unwrap();
|
||||
let app = farm_service::api::router(pool.clone(), "test-only-token".into())
|
||||
.merge(assets::router(Some(bundle)));
|
||||
for (uri, status) in [
|
||||
("/v1/assets/manifest.json", StatusCode::OK),
|
||||
("/v1/users/qq/123456", StatusCode::UNAUTHORIZED),
|
||||
] {
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), status);
|
||||
}
|
||||
pool.close().await;
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
use axum::{
|
||||
Router,
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use farm_service::{api, db};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::SqlitePool;
|
||||
use tempfile::TempDir;
|
||||
use tower::ServiceExt;
|
||||
|
||||
const TOKEN: &str = "integration-test-token-not-for-production";
|
||||
|
||||
async fn app() -> (TempDir, SqlitePool, Router) {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let pool = db::open_database(&directory.path().join("test.sqlite3"))
|
||||
.await
|
||||
.unwrap();
|
||||
let router = api::router(pool.clone(), TOKEN.into());
|
||||
(directory, pool, router)
|
||||
}
|
||||
|
||||
fn profile(platform: &str, id: &str, nickname: &str) -> Value {
|
||||
json!({
|
||||
"platform": platform,
|
||||
"platform_user_id": id,
|
||||
"nickname": nickname
|
||||
})
|
||||
}
|
||||
|
||||
async fn send(app: Router, method: &str, uri: &str, body: Value, authenticated: bool) -> Response {
|
||||
let mut request = Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.header("content-type", "application/json");
|
||||
if authenticated {
|
||||
request = request.header("authorization", format!("Bearer {TOKEN}"));
|
||||
}
|
||||
app.oneshot(request.body(Body::from(body.to_string())).unwrap())
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn json_body(response: Response) -> Value {
|
||||
let bytes = to_bytes(response.into_body(), 8192).await.unwrap();
|
||||
serde_json::from_slice(&bytes).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_checks_database_readiness() {
|
||||
let (_directory, pool, router) = app().await;
|
||||
let response = send(router.clone(), "GET", "/health", Value::Null, false).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(json_body(response).await, json!({"status": "ok"}));
|
||||
pool.close().await;
|
||||
let response = send(router, "GET", "/health", Value::Null, false).await;
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn authentication_prevents_profile_reads_and_writes() {
|
||||
let (_directory, pool, router) = app().await;
|
||||
for (method, uri) in [("PUT", "/v1/users"), ("GET", "/v1/users/qq/12345678")] {
|
||||
let response = send(
|
||||
router.clone(),
|
||||
method,
|
||||
uri,
|
||||
profile("qq", "12345678", "测试昵称"),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
let response = router
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("PUT")
|
||||
.uri("/v1/users")
|
||||
.header("authorization", "Bearer incorrect-token")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(profile("qq", "12345678", "测试").to_string()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
pool.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn profile_updates_are_persistent_and_preserve_creation_time() {
|
||||
let (directory, pool, router) = app().await;
|
||||
let first = send(
|
||||
router.clone(),
|
||||
"PUT",
|
||||
"/v1/users",
|
||||
profile("qq", "12345678", " 初始昵称 "),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(first.status(), StatusCode::OK);
|
||||
let first = json_body(first).await;
|
||||
assert_eq!(first["nickname"], "初始昵称");
|
||||
let updated = send(
|
||||
router.clone(),
|
||||
"PUT",
|
||||
"/v1/users",
|
||||
profile("qq", "12345678", "新昵称"),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(updated.status(), StatusCode::OK);
|
||||
let updated = json_body(updated).await;
|
||||
assert_eq!(first["created_at"], updated["created_at"]);
|
||||
assert_eq!(updated["platform_user_id"], "12345678");
|
||||
drop(router);
|
||||
pool.close().await;
|
||||
|
||||
let reopened = db::open_database(&directory.path().join("test.sqlite3"))
|
||||
.await
|
||||
.unwrap();
|
||||
let response = send(
|
||||
api::router(reopened.clone(), TOKEN.into()),
|
||||
"GET",
|
||||
"/v1/users/qq/12345678",
|
||||
Value::Null,
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(json_body(response).await["nickname"], "新昵称");
|
||||
reopened.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn platforms_do_not_merge_equal_numeric_ids() {
|
||||
let (_directory, pool, router) = app().await;
|
||||
for platform in ["qq", "telegram", "discord"] {
|
||||
let response = send(
|
||||
router.clone(),
|
||||
"PUT",
|
||||
"/v1/users",
|
||||
profile(platform, "12345678", platform),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
}
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 3);
|
||||
let missing = send(router, "GET", "/v1/users/qq/99999999", Value::Null, true).await;
|
||||
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
|
||||
pool.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_profiles_do_not_write_any_data() {
|
||||
let (_directory, pool, router) = app().await;
|
||||
let mut cases = vec![
|
||||
profile("qq", "0", "昵称"),
|
||||
profile("qq", "00123456", "昵称"),
|
||||
profile("qq", "-123", "昵称"),
|
||||
profile("qq", "123", "昵称"),
|
||||
profile("qq", "12345678", " "),
|
||||
profile("qq", "12345678", "换行\n昵称"),
|
||||
profile("qq", "12345678", &"字".repeat(65)),
|
||||
profile("qq", &"1".repeat(21), "昵称"),
|
||||
profile("unknown", "12345678", "昵称"),
|
||||
json!({"platform": "qq", "platform_user_id": 12345678, "nickname": "昵称"}),
|
||||
];
|
||||
let mut unknown = profile("qq", "12345678", "昵称");
|
||||
unknown["unused_field"] = json!(true);
|
||||
cases.push(unknown);
|
||||
for body in cases {
|
||||
let response = send(router.clone(), "PUT", "/v1/users", body, true).await;
|
||||
assert!(response.status().is_client_error());
|
||||
}
|
||||
let oversized = send(
|
||||
router,
|
||||
"PUT",
|
||||
"/v1/users",
|
||||
profile("qq", "12345678", &"a".repeat(5000)),
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(oversized.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
pool.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_reports_create_one_profile() {
|
||||
let (_directory, pool, router) = app().await;
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
for index in 0..12 {
|
||||
let router = router.clone();
|
||||
tasks.spawn(async move {
|
||||
send(
|
||||
router,
|
||||
"PUT",
|
||||
"/v1/users",
|
||||
profile("qq", "12345678", &format!("昵称{index}")),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.status()
|
||||
});
|
||||
}
|
||||
while let Some(status) = tasks.join_next().await {
|
||||
assert_eq!(status.unwrap(), StatusCode::OK);
|
||||
}
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM users")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 1);
|
||||
pool.close().await;
|
||||
}
|
||||
Reference in New Issue
Block a user