Compare commits

..

12 Commits

Author SHA1 Message Date
Davide Scaini 0e8681e03a docs: mention AGPL v3 license in README
CI / Python tests (push) Waiting to run
CI / Frontend build (push) Waiting to run
2026-06-04 00:24:08 +02:00
Davide Scaini 15094fd954 Add AGPL v3 license
CI / Python tests (push) Waiting to run
CI / Frontend build (push) Waiting to run
2026-06-04 00:17:21 +02:00
Davide Scaini 29eb1dfcdc feat: show percentage next to progress bar in month header 2026-06-03 23:55:52 +02:00
Davide Scaini e967ef5322 feat: show goal progress bar inline in month header row 2026-06-03 23:51:43 +02:00
Davide Scaini 7a20af72fa feat: collapsible month rows in running costs, most recent auto-expanded 2026-06-03 23:47:09 +02:00
Davide Scaini da351cc53b feat: add weight fields to athlete profile and gear items 2026-06-03 23:39:03 +02:00
Davide Scaini 060bdf5114 fix: update tests to match current algorithm — thresholds, _best_climb tuples, ComputedMetrics fields
CI / Python tests (push) Waiting to run
CI / Frontend build (push) Waiting to run
2026-06-03 22:18:17 +02:00
Davide Scaini f167c6eed7 fix: add local _require_admin guard to proxied endpoints; update test to expect 503 without bincio-auth
CI / Python tests (push) Waiting to run
CI / Frontend build (push) Waiting to run
2026-06-03 22:07:41 +02:00
Davide Scaini 3624fd051f fix: TS syntax in define:vars IIFEs causes SyntaxError — use plain JS for authUrl 2026-06-03 22:03:21 +02:00
Davide Scaini ac18b73c07 feat: email field in settings — lets users set address for self-service password reset 2026-06-03 21:56:35 +02:00
Davide Scaini 5f916461ac fix: logout loop — authUrl was empty in user-widget script due to Astro 5 define:vars behaviour; read from window.__bincioAuthUrl instead
CI / Python tests (push) Waiting to run
CI / Frontend build (push) Waiting to run
2026-06-03 21:23:49 +02:00
Davide Scaini 3394be4ee9 auth: add RS256 validation via JWKS (Phase 3)
CI / Python tests (push) Waiting to run
CI / Frontend build (push) Waiting to run
When --oidc-issuer is set, validate tokens as RS256 id_tokens fetched
against bincio-auth's JWKS endpoint (cached for 1h). Falls back to
HS256 if the RS256 check fails, so existing sessions keep working
during the transition. DB session lookup is the final fallback.

New --oidc-issuer flag reads BINCIO_OIDC_ISSUER env var.
2026-06-03 15:43:44 +02:00
17 changed files with 1023 additions and 148 deletions
+663
View File
@@ -0,0 +1,663 @@
Copyright (C) 2026 Davide Scaini
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://www.gnu.org/licenses/>.
+4
View File
@@ -320,3 +320,7 @@ Databases add operational complexity — backups, migrations, running processes,
## Why federation?
Strava, Garmin Connect, and similar platforms are silos. If the company shuts down or changes its terms, your data and your social graph go with it. BincioActivity's federation model is inspired by the open web: you host your own data at a URL, friends subscribe to that URL, and no central authority is involved.
## License
[AGPL v3](LICENSE) — see the `LICENSE` file for details.
+9 -3
View File
@@ -24,11 +24,13 @@ console = Console()
@click.option("--sync-secret", default=None, envvar="BINCIO_SYNC_SECRET", help="Shared secret for POST /api/internal/rebuild (used by the sync-strava systemd timer).")
@click.option("--jwt-secret", default=None, envvar="BINCIO_AUTH_JWT_SECRET", help="Shared JWT secret from bincio-auth. When set, validates JWTs locally instead of DB session lookup.")
@click.option("--auth-api", default=None, envvar="BINCIO_AUTH_API", help="Internal URL of the bincio-auth API (e.g. http://127.0.0.1:4040). When set, admin user-state operations are proxied to bincio-auth.")
@click.option("--oidc-issuer", default=None, envvar="BINCIO_OIDC_ISSUER", help="OIDC issuer URL (e.g. https://bincio.org). When set, validates RS256 id_tokens via JWKS (preferred over HS256).")
def serve(data_dir: str, site_dir: str | None, host: str, port: int,
strava_client_id: str | None, strava_client_secret: str | None,
max_users: int | None, public_url: str | None,
webroot: str | None, dem_url: str | None,
sync_secret: str | None, jwt_secret: str | None, auth_api: str | None) -> None:
sync_secret: str | None, jwt_secret: str | None, auth_api: str | None,
oidc_issuer: str | None) -> None:
"""Start the bincio multi-user application server.
Handles auth, user management, and write operations.
@@ -72,6 +74,8 @@ def serve(data_dir: str, site_dir: str | None, host: str, port: int,
deps.jwt_secret = jwt_secret
if auth_api:
deps.auth_api = auth_api.rstrip("/")
if oidc_issuer:
deps.oidc_issuer = oidc_issuer
db = open_db(dd)
current_limit = get_setting(db, "max_users")
@@ -89,8 +93,10 @@ def serve(data_dir: str, site_dir: str | None, host: str, port: int,
else:
console.print(" Users: [dim]unlimited[/dim]")
console.print(f" DEM: [cyan]{deps.dem_url}[/cyan]")
if deps.jwt_secret:
console.print(" Auth: [green]JWT (bincio-auth)[/green]")
if deps.oidc_issuer:
console.print(f" Auth: [green]RS256 via {deps.oidc_issuer}[/green]" + (" + HS256 fallback" if deps.jwt_secret else ""))
elif deps.jwt_secret:
console.print(" Auth: [green]JWT HS256 (bincio-auth)[/green]")
else:
console.print(" Auth: [dim]local DB sessions[/dim]")
console.print()
+74 -6
View File
@@ -38,12 +38,20 @@ dem_url: str = "https://api.open-elevation.com"
sync_secret: str = ""
jwt_secret: str = "" # when set, validates JWTs from bincio-auth instead of DB session lookup
auth_api: str = "" # when set, proxies user-state admin ops to bincio-auth (e.g. http://127.0.0.1:4040)
oidc_issuer: str = "" # when set, validates RS256 id_tokens via bincio-auth JWKS
_db = None
_strava_sync_running = False
_strava_sync_lock = threading.Lock()
_garmin_sync_running = False
_garmin_sync_lock = threading.Lock()
# ── JWKS cache ────────────────────────────────────────────────────────────────
_jwks_public_key: object = None
_jwks_fetched_at: float = 0.0
_jwks_lock = threading.Lock()
_JWKS_TTL = 3600
# ── Constants ─────────────────────────────────────────────────────────────────
_VALID_HANDLE = re.compile(r'^[a-z0-9][a-z0-9_-]{0,29}$')
@@ -116,8 +124,59 @@ def _check_rate_limit(
# ── Auth dependency functions ─────────────────────────────────────────────────
def _decode_jwt(token: str) -> User | None:
"""Decode a bincio-auth JWT and return a User. Returns None on any failure."""
def _get_jwks_public_key() -> object:
"""Fetch and cache the RSA public key from bincio-auth's JWKS endpoint."""
global _jwks_public_key, _jwks_fetched_at
now = time.time()
with _jwks_lock:
if _jwks_public_key is not None and now - _jwks_fetched_at < _JWKS_TTL:
return _jwks_public_key
import base64
import urllib.request
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers
from cryptography.hazmat.backends import default_backend
url = f"{oidc_issuer.rstrip('/')}/.well-known/jwks.json"
with urllib.request.urlopen(url, timeout=5) as r:
jwks = json.loads(r.read())
k = jwks["keys"][0]
def _b64i(s: str) -> int:
s += "=" * (-len(s) % 4)
return int.from_bytes(base64.urlsafe_b64decode(s), "big")
pub = RSAPublicNumbers(_b64i(k["e"]), _b64i(k["n"])).public_key(default_backend())
_jwks_public_key = pub
_jwks_fetched_at = now
return pub
def _decode_rs256(token: str) -> User | None:
"""Decode an RS256 id_token from bincio-auth. Returns None on any failure."""
try:
pub = _get_jwks_public_key()
payload = _jwt.decode(
token, pub, algorithms=["RS256"],
options={"verify_aud": False},
issuer=oidc_issuer,
)
except Exception:
return None
handle = payload.get("sub")
if not handle:
return None
return User(
handle=handle,
display_name=payload.get("name") or payload.get("display_name", ""),
is_admin=bool(payload.get("is_admin", False)),
wiki_access=bool(payload.get("wiki_access", True)),
activity_access=bool(payload.get("activity_access", False)),
suspended=False,
created_at=0,
)
def _decode_hs256(token: str) -> User | None:
"""Decode a bincio-auth HS256 JWT and return a User. Returns None on any failure."""
try:
payload = _jwt.decode(token, jwt_secret, algorithms=["HS256"])
except _jwt.PyJWTError:
@@ -136,12 +195,21 @@ def _decode_jwt(token: str) -> User | None:
)
def _decode_token(token: str) -> User | None:
"""Try RS256 first (if oidc_issuer set), then HS256, then DB session."""
if oidc_issuer:
user = _decode_rs256(token)
if user:
return user
if jwt_secret:
return _decode_hs256(token)
return get_session(_get_db(), token)
def _current_user(bincio_session: str | None = Cookie(default=None)) -> User | None:
if not bincio_session:
return None
if jwt_secret:
return _decode_jwt(bincio_session)
return get_session(_get_db(), bincio_session)
return _decode_token(bincio_session)
def _require_user(bincio_session: str | None = Cookie(default=None)) -> User:
@@ -170,7 +238,7 @@ def _require_auth(
token = auth[7:]
if not token:
raise HTTPException(401, "Not authenticated")
user = _decode_jwt(token) if jwt_secret else get_session(_get_db(), token)
user = _decode_token(token)
if not user:
raise HTTPException(401, "Invalid or expired session")
return user
+4
View File
@@ -165,6 +165,7 @@ async def admin_reset_password_code(
bincio_session: str | None = Cookie(default=None),
) -> JSONResponse:
"""Generate a one-time password reset code for a user. Proxied to bincio-auth."""
deps._require_admin(bincio_session)
return await _auth_proxy("POST", f"/api/admin/users/{handle}/reset-password-code", bincio_session)
@@ -174,6 +175,7 @@ async def admin_suspend(
bincio_session: str | None = Cookie(default=None),
) -> JSONResponse:
"""Suspend a user account. Proxied to bincio-auth."""
deps._require_admin(bincio_session)
return await _auth_proxy("POST", f"/api/admin/users/{handle}/suspend", bincio_session)
@@ -183,6 +185,7 @@ async def admin_unsuspend(
bincio_session: str | None = Cookie(default=None),
) -> JSONResponse:
"""Re-enable a suspended user account. Proxied to bincio-auth."""
deps._require_admin(bincio_session)
return await _auth_proxy("POST", f"/api/admin/users/{handle}/unsuspend", bincio_session)
@@ -192,6 +195,7 @@ async def admin_delete_account(
bincio_session: str | None = Cookie(default=None),
) -> JSONResponse:
"""Delete a user account. Proxied to bincio-auth."""
deps._require_admin(bincio_session)
return await _auth_proxy("DELETE", f"/api/admin/users/{handle}/account", bincio_session)
+22
View File
@@ -58,6 +58,14 @@ async def gear_add(
if gear_type not in _GEAR_TYPES:
raise HTTPException(400, f"type must be one of: {', '.join(sorted(_GEAR_TYPES))}")
strava_id = str(body.get("strava_id", "")).strip() or None
weight_g = body.get("weight_g")
if weight_g is not None:
try:
weight_g = int(weight_g)
if weight_g < 0:
raise ValueError
except (TypeError, ValueError):
raise HTTPException(400, "weight_g must be a non-negative integer (grams)")
user_dir = deps._get_data_dir() / user.handle
items = _load(user_dir)
@@ -75,6 +83,8 @@ async def gear_add(
}
if strava_id:
item["strava_id"] = strava_id
if weight_g is not None:
item["weight_g"] = weight_g
items.append(item)
_save(user_dir, items)
@@ -110,6 +120,18 @@ async def gear_update(
item["type"] = gear_type
if "retired" in body:
item["retired"] = bool(body["retired"])
if "weight_g" in body:
w = body["weight_g"]
if w is None:
item.pop("weight_g", None)
else:
try:
w = int(w)
if w < 0:
raise ValueError
except (TypeError, ValueError):
raise HTTPException(400, "weight_g must be a non-negative integer (grams)")
item["weight_g"] = w
items[idx] = item
_save(user_dir, items)
+13 -2
View File
@@ -13,6 +13,7 @@
let maxHr: number | null = null;
let ftpW: number | null = null;
let weightKg: number | null = null;
let hrZones: [number, number][] = [];
let powerZones: [number, number][] = [];
let seasons: { name: string; start: string; end: string }[] = [];
@@ -24,8 +25,9 @@
const res = await fetch(`${editUrl}/api/athlete`);
if (!res.ok) throw new Error(await res.text());
const d = await res.json();
maxHr = d.max_hr ?? null;
ftpW = d.ftp_w ?? null;
maxHr = d.max_hr ?? null;
ftpW = d.ftp_w ?? null;
weightKg = d.weight_kg ?? null;
hrZones = d.hr_zones ? d.hr_zones.map((z: number[]) => [z[0], z[1]] as [number,number]) : [];
powerZones = d.power_zones ? d.power_zones.map((z: number[]) => [z[0], z[1]] as [number,number]) : [];
seasons = d.seasons ?? [];
@@ -76,6 +78,7 @@
body: JSON.stringify({
max_hr: maxHr,
ftp_w: ftpW,
weight_kg: weightKg,
hr_zones: hrZones,
power_zones: powerZones,
seasons,
@@ -144,6 +147,14 @@
class="w-full bg-zinc-900 border border-zinc-700 rounded-md px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
/>
</label>
<label class="block">
<span class="text-xs text-zinc-500 mb-1 block">Body weight (kg)</span>
<input
type="number" min="30" max="200" step="0.1"
bind:value={weightKg}
class="w-full bg-zinc-900 border border-zinc-700 rounded-md px-3 py-2 text-sm text-white focus:outline-none focus:border-blue-500"
/>
</label>
</div>
</section>
+23 -5
View File
@@ -53,7 +53,7 @@
// Gear tab state
interface GearReplacement { id: string; date: string; note?: string }
interface GearPart { id: string; name: string; threshold_km?: number; replacements: GearReplacement[] }
interface GearItem { id: string; name: string; type: string; retired: boolean; strava_id?: string; parts?: GearPart[] }
interface GearItem { id: string; name: string; type: string; retired: boolean; strava_id?: string; weight_g?: number; parts?: GearPart[] }
let gearItems: GearItem[] = [];
let gearLoading = false;
@@ -66,6 +66,7 @@
let gearEditName = '';
let gearEditType = 'bike';
let gearEditRetired = false;
let gearEditWeightG: number | null = null;
let gearSaving = false;
let gearExpandedId: string | null = null;
@@ -161,7 +162,7 @@
}
function gearStartEdit(item: GearItem) {
gearEditId = item.id; gearEditName = item.name; gearEditType = item.type; gearEditRetired = item.retired;
gearEditId = item.id; gearEditName = item.name; gearEditType = item.type; gearEditRetired = item.retired; gearEditWeightG = item.weight_g ?? null;
}
async function gearSaveEdit() {
@@ -171,7 +172,7 @@
const r = await fetch(`/api/gear/${gearEditId}`, {
method: 'PATCH', credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: gearEditName.trim(), type: gearEditType, retired: gearEditRetired }),
body: JSON.stringify({ name: gearEditName.trim(), type: gearEditType, retired: gearEditRetired, weight_g: gearEditWeightG }),
});
const d = await r.json();
if (r.ok) {
@@ -673,6 +674,14 @@
<input type="checkbox" bind:checked={gearEditRetired} class="accent-blue-500" />
Retired
</label>
<label class="flex items-center gap-1.5 text-sm text-zinc-400">
<input
type="number" min="0" step="1" placeholder="weight (g)"
bind:value={gearEditWeightG}
class="w-28 bg-zinc-700 text-white text-sm px-2 py-1 rounded border border-zinc-600 focus:border-blue-500 outline-none"
/>
<span class="text-xs">g</span>
</label>
<button
on:click={gearSaveEdit}
disabled={gearSaving || !gearEditName.trim()}
@@ -703,6 +712,9 @@
{#if gearDistances[item.name] > 0}
<span class="text-xs text-zinc-400">{formatDistance(gearDistances[item.name])}</span>
{/if}
{#if item.weight_g}
<span class="text-xs text-zinc-500">{item.weight_g >= 1000 ? (item.weight_g / 1000).toFixed(2).replace(/\.?0+$/, '') + ' kg' : item.weight_g + ' g'}</span>
{/if}
{#if item.retired}
<span class="text-xs text-zinc-600 border border-zinc-700 rounded px-1.5 py-0.5">Retired</span>
{/if}
@@ -910,8 +922,14 @@
<span class="text-white font-medium">{athlete.ftp_w} W</span>
</div>
{/if}
{#if !athlete.max_hr && !athlete.ftp_w}
<p class="text-zinc-500 text-sm">Set <code>athlete.max_hr</code> and <code>athlete.ftp_w</code> in your config, or use Edit profile.</p>
{#if athlete.weight_kg}
<div class="flex justify-between text-sm">
<span class="text-zinc-400">Weight</span>
<span class="text-white font-medium">{athlete.weight_kg} kg</span>
</div>
{/if}
{#if !athlete.max_hr && !athlete.ftp_w && !athlete.weight_kg}
<p class="text-zinc-500 text-sm">No key numbers set yet. Use Edit profile to add Max HR, FTP, and body weight.</p>
{/if}
</div>
+4 -1
View File
@@ -101,6 +101,7 @@ try {
{instancePrivate && !isPublicPage && (
<style is:inline>[data-auth-pending]{visibility:hidden}</style>
<script is:inline define:vars={{ authUrl }}>
window.__bincioAuthUrl = authUrl;
fetch('/api/me', { credentials: 'include' })
.then(r => {
if (r.status === 401 || r.status === 404) {
@@ -590,7 +591,8 @@ try {
<!-- User widget: only needed for multi-user (single-user nav links are static) -->
{!singleHandle && (
<script define:vars={{ baseUrl, authUrl }}>
<script define:vars={{ baseUrl }}>
const authUrl = window.__bincioAuthUrl || '';
(async () => {
try {
const r = await fetch('/api/me', { credentials: 'include' });
@@ -732,6 +734,7 @@ try {
{editEnabled && (
<script define:vars={{ editUrl, baseUrl }}>
const authUrl = window.__bincioAuthUrl || '';
const modal = document.getElementById('upload-modal');
const openBtn = document.getElementById('upload-btn');
const closeBtn = document.getElementById('upload-close');
+1
View File
@@ -44,6 +44,7 @@ export interface AthleteJson {
best_climbs?: BestClimb[];
max_hr?: number;
ftp_w?: number;
weight_kg?: number;
hr_zones?: [number, number][];
power_zones?: [number, number][];
seasons?: { name: string; start: string; end: string }[];
+57
View File
@@ -51,6 +51,25 @@ import Base from '../../layouts/Base.astro';
<p id="display-name-status" class="text-xs mt-2 hidden"></p>
</section>
<!-- Email card -->
<section class="mb-6 rounded-xl bg-zinc-900 border border-zinc-800 p-5">
<h2 class="text-sm font-semibold text-zinc-400 uppercase tracking-wider mb-1">Email</h2>
<p class="text-xs text-zinc-500 mb-4">Used to receive a reset link when you forget your password.</p>
<form id="email-form" class="flex gap-2 items-end">
<div class="flex-1">
<label class="block text-xs text-zinc-500 mb-1" for="email-input">Email address</label>
<input id="email-input" type="email" autocomplete="email"
class="w-full px-3 py-2 rounded-lg bg-zinc-800 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent] text-sm"
placeholder="you@example.com" />
</div>
<button type="submit"
class="px-4 py-2 rounded-lg text-sm bg-zinc-700 hover:bg-zinc-600 text-white transition-colors shrink-0">
Save
</button>
</form>
<p id="email-status" class="text-xs mt-2 hidden"></p>
</section>
<!-- Password card -->
<section class="mb-6 rounded-xl bg-zinc-900 border border-zinc-800 p-5">
<h2 class="text-sm font-semibold text-zinc-400 uppercase tracking-wider mb-4">Password</h2>
@@ -602,10 +621,48 @@ import Base from '../../layouts/Base.astro';
}
});
// ── Email ─────────────────────────────────────────────────────────────────────
const emailForm = document.getElementById('email-form') as HTMLFormElement;
const emailInput = document.getElementById('email-input') as HTMLInputElement;
const emailStatus = document.getElementById('email-status') as HTMLElement;
async function loadEmail() {
const authUrl: string = (window as any).__bincioAuthUrl ?? '';
if (!authUrl) return; // single-user / no bincio-auth
try {
const r = await fetch(`${authUrl}/api/me/email`, { credentials: 'include' });
if (r.ok) {
const { email } = await r.json();
if (email) emailInput.value = email;
}
} catch { /* ignore */ }
}
emailForm.addEventListener('submit', async e => {
e.preventDefault();
const authUrl: string = (window as any).__bincioAuthUrl ?? '';
if (!authUrl) { setStatus(emailStatus, 'Not available on this instance.', false); return; }
const email = emailInput.value.trim();
try {
const r = await fetch(`${authUrl}/api/me/email`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email }),
});
const d = await r.json().catch(() => ({}));
setStatus(emailStatus, r.ok ? 'Saved.' : (d.detail ?? 'Failed.'), r.ok);
} catch {
setStatus(emailStatus, 'Could not reach server.', false);
}
});
// ── Init ─────────────────────────────────────────────────────────────────────
loadMe();
loadStorage();
loadEmail();
loadNavPrefs();
loadActivityDefaults();
loadStravaCreds();
+109 -93
View File
@@ -355,6 +355,8 @@ if (location.hash.slice(1) === 'community') { communityLoaded = true; loadCommun
let budgetData: { monthly_target_eur: number | null; entries: any[] } | null = null;
let isAdmin = false;
let addEntryType: 'donation' | 'expense' = 'donation';
const expandedMonths = new Set<string>();
let budgetFirstRender = true;
async function loadBudget() {
try {
@@ -381,9 +383,9 @@ function monthLabel(ym: string) {
}
function renderBudget() {
const listEl = document.getElementById('budget-list')!;
const adminCtrls = document.getElementById('budget-admin-controls')!;
const goalInput = document.getElementById('budget-goal-input') as HTMLInputElement;
const listEl = document.getElementById('budget-list')!;
const adminCtrls = document.getElementById('budget-admin-controls')!;
const goalInput = document.getElementById('budget-goal-input') as HTMLInputElement;
if (isAdmin) {
adminCtrls.classList.remove('hidden');
@@ -400,7 +402,10 @@ function renderBudget() {
for (const e of entries) (byMonth[e.month] ??= []).push(e);
const months = Object.keys(byMonth).sort().reverse();
let html = '';
if (budgetFirstRender) { expandedMonths.add(months[0]); budgetFirstRender = false; }
listEl.innerHTML = '';
for (const ym of months) {
const items = byMonth[ym];
const donated = items.filter(e => e.type === 'donation').reduce((s, e) => s + e.amount_eur, 0);
@@ -408,101 +413,112 @@ function renderBudget() {
const balance = donated - spent;
const target = budgetData?.monthly_target_eur;
const pct = target ? Math.min(100, Math.round(donated / target * 100)) : null;
const open = expandedMonths.has(ym);
html += `<div class="mb-6">`;
html += `<h3 class="text-sm font-semibold text-white mb-2">${monthLabel(ym)}</h3>`;
const wrapper = document.createElement('div');
wrapper.className = 'mb-2 rounded-xl border border-zinc-800 overflow-hidden';
if (pct !== null) {
html += `<div class="mb-3">
<div class="flex justify-between text-xs text-zinc-500 mb-1">
<span>Donations toward monthly goal</span>
<span>${pct}% of ${fmtEur(target!)}</span>
</div>
<div class="h-1.5 rounded-full bg-zinc-800 overflow-hidden">
<div class="h-full rounded-full transition-all" style="width:${pct}%;background:var(--accent)"></div>
</div>
</div>`;
}
// ── Month header row ──────────────────────────────────────────────────
const header = document.createElement('button');
header.className = 'w-full flex items-center gap-2 px-3 py-2.5 bg-zinc-900 hover:bg-zinc-800/60 transition-colors text-sm';
header.innerHTML = `
<span class="font-medium text-white shrink-0">${monthLabel(ym)}</span>
${pct !== null
? `<div class="flex-1 mx-2 flex items-center gap-1.5"><div class="flex-1 h-1.5 rounded-full bg-zinc-800 overflow-hidden"><div class="h-full rounded-full" style="width:${pct}%;background:var(--accent)"></div></div><span class="text-xs text-zinc-500 shrink-0">${pct}%</span></div>`
: `<span class="flex-1"></span>`}
<span class="text-xs text-green-400"><span class="hidden sm:inline text-zinc-600 mr-0.5">donated</span>+${fmtEur(donated)}</span>
<span class="text-xs text-zinc-700">/</span>
<span class="text-xs text-red-400"><span class="hidden sm:inline text-zinc-600 mr-0.5">spent</span>${fmtEur(spent)}</span>
<span class="text-xs text-zinc-700">/</span>
<span class="text-xs ${balance >= 0 ? 'text-zinc-300' : 'text-red-400'}"><span class="hidden sm:inline text-zinc-600 mr-0.5">balance</span>${balance >= 0 ? '+' : ''}${fmtEur(Math.abs(balance))}</span>
<span class="text-zinc-600 text-xs ml-1">${open ? '▲' : '▼'}</span>`;
header.addEventListener('click', () => {
if (expandedMonths.has(ym)) expandedMonths.delete(ym); else expandedMonths.add(ym);
renderBudget();
});
wrapper.appendChild(header);
html += `<div class="divide-y divide-zinc-800/60 rounded-xl border border-zinc-800 overflow-hidden">`;
for (const e of items) {
const icon = e.type === 'donation' ? '💚' : '🔴';
const sign = e.type === 'donation' ? '+' : '';
const color = e.type === 'donation' ? 'text-green-400' : 'text-red-400';
const recurBadge = e.recurring
? `<span class="text-zinc-500 text-xs shrink-0" title="Repeats every month">↻</span>`
: e.recurring_from
? `<span class="text-zinc-600 text-xs shrink-0" title="Auto-added (recurring)">↻</span>`
// ── Expanded detail ───────────────────────────────────────────────────
if (open) {
const detail = document.createElement('div');
detail.className = 'border-t border-zinc-800';
const entriesDiv = document.createElement('div');
entriesDiv.className = 'divide-y divide-zinc-800/60';
let entriesHtml = '';
for (const e of items) {
const icon = e.type === 'donation' ? '💚' : '🔴';
const sign = e.type === 'donation' ? '+' : '';
const color = e.type === 'donation' ? 'text-green-400' : 'text-red-400';
const recurBadge = e.recurring
? `<span class="text-zinc-500 text-xs shrink-0" title="Repeats every month">↻</span>`
: e.recurring_from
? `<span class="text-zinc-600 text-xs shrink-0" title="Auto-added (recurring)">↻</span>`
: '';
const adminBtns = isAdmin
? `<button data-edit="${e.id}" class="edit-btn text-zinc-600 hover:text-zinc-300 text-xs px-1 transition-colors">✎</button>
<button data-del="${e.id}" class="del-btn text-zinc-700 hover:text-red-400 text-xs px-1 transition-colors">✕</button>`
: '';
const adminBtns = isAdmin
? `<button data-edit="${e.id}" class="edit-btn text-zinc-600 hover:text-zinc-300 text-xs px-1 transition-colors">✎</button>
<button data-del="${e.id}" class="del-btn text-zinc-700 hover:text-red-400 text-xs px-1 transition-colors">✕</button>`
: '';
html += `<div class="flex items-center gap-3 px-3 py-2 bg-zinc-900 text-sm" data-entry-id="${e.id}">
<span class="text-base shrink-0">${icon}</span>
<span class="flex-1 text-zinc-300 min-w-0">
${e.label}${e.note ? `<span class="text-zinc-600 text-xs ml-2">${e.note}</span>` : ''}
</span>
${recurBadge}
<span class="font-medium shrink-0 ${color}">${sign}${fmtEur(e.amount_eur)}</span>
${adminBtns}
</div>`;
}
html += `</div>`;
html += `<div class="flex gap-4 mt-2 text-xs text-zinc-500 px-1">
<span>Donated: <span class="text-green-400">${fmtEur(donated)}</span></span>
<span>Spent: <span class="text-red-400">${fmtEur(spent)}</span></span>
<span>Balance: <span class="${balance >= 0 ? 'text-zinc-300' : 'text-red-400'}">${balance >= 0 ? '+' : ''}${fmtEur(Math.abs(balance))}</span></span>
</div>`;
html += `</div>`;
}
listEl.innerHTML = html;
entriesHtml += `<div class="flex items-center gap-3 px-3 py-2 bg-zinc-900 text-sm" data-entry-id="${e.id}">
<span class="text-base shrink-0">${icon}</span>
<span class="flex-1 text-zinc-300 min-w-0">${e.label}${e.note ? `<span class="text-zinc-600 text-xs ml-2">${e.note}</span>` : ''}</span>
${recurBadge}
<span class="font-medium shrink-0 ${color}">${sign}${fmtEur(e.amount_eur)}</span>
${adminBtns}
</div>`;
}
entriesDiv.innerHTML = entriesHtml;
detail.appendChild(entriesDiv);
wrapper.appendChild(detail);
listEl.querySelectorAll<HTMLElement>('.del-btn').forEach(btn => {
btn.addEventListener('click', async () => {
if (!confirm('Delete this entry?')) return;
const r = await fetch(`/api/budget/entries/${btn.dataset.del}`, { method: 'DELETE', credentials: 'include' });
if (r.ok) { budgetData!.entries = budgetData!.entries.filter(e => e.id !== btn.dataset.del); renderBudget(); }
});
});
listEl.querySelectorAll<HTMLElement>('.edit-btn').forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.dataset.edit!;
const entry = budgetData!.entries.find(e => e.id === id);
if (!entry) return;
const row = listEl.querySelector<HTMLElement>(`[data-entry-id="${id}"]`)!;
row.innerHTML = `
<form class="inline-edit-form flex flex-wrap gap-2 items-center w-full py-1" data-id="${id}">
<select name="type" class="px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none">
<option value="donation" ${entry.type==='donation'?'selected':''}>💚 Donation</option>
<option value="expense" ${entry.type==='expense' ?'selected':''}>🔴 Expense</option>
</select>
<input name="label" value="${entry.label}" placeholder="Label"
class="flex-1 min-w-24 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
<input name="amount_eur" type="number" value="${entry.amount_eur}" step="0.01" min="0"
class="w-20 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
<input name="month" type="month" value="${entry.month}"
class="px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none [color-scheme:dark]" />
<input name="note" value="${entry.note}" placeholder="Note"
class="flex-1 min-w-24 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
<label class="flex items-center gap-1 text-xs text-zinc-400 cursor-pointer">
<input type="checkbox" name="recurring" ${entry.recurring?'checked':''} class="accent-[--accent] w-3 h-3" />↻
</label>
<button type="submit" class="px-3 py-1 rounded bg-[--accent] text-white text-xs hover:opacity-90">Save</button>
<button type="button" class="cancel-edit px-2 py-1 rounded bg-zinc-800 text-zinc-400 text-xs hover:bg-zinc-700">✕</button>
</form>`;
row.querySelector<HTMLFormElement>('.inline-edit-form')!.addEventListener('submit', async ev => {
ev.preventDefault();
const fd = new FormData(ev.target as HTMLFormElement);
const body = { type: fd.get('type'), label: fd.get('label'), amount_eur: parseFloat(fd.get('amount_eur') as string), month: fd.get('month'), note: fd.get('note'), recurring: fd.get('recurring') === 'on' };
const r = await fetch(`/api/budget/entries/${id}`, { method: 'PATCH', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
if (r.ok) { const updated = await r.json(); const idx = budgetData!.entries.findIndex(e => e.id === id); if (idx !== -1) budgetData!.entries[idx] = updated; renderBudget(); }
entriesDiv.querySelectorAll<HTMLElement>('.del-btn').forEach(btn => {
btn.addEventListener('click', async () => {
if (!confirm('Delete this entry?')) return;
const r = await fetch(`/api/budget/entries/${btn.dataset.del}`, { method: 'DELETE', credentials: 'include' });
if (r.ok) { budgetData!.entries = budgetData!.entries.filter(e => e.id !== btn.dataset.del); renderBudget(); }
});
});
row.querySelector('.cancel-edit')!.addEventListener('click', renderBudget);
});
});
entriesDiv.querySelectorAll<HTMLElement>('.edit-btn').forEach(btn => {
btn.addEventListener('click', () => {
const id = btn.dataset.edit!;
const entry = budgetData!.entries.find(e => e.id === id);
if (!entry) return;
const row = entriesDiv.querySelector<HTMLElement>(`[data-entry-id="${id}"]`)!;
row.innerHTML = `
<form class="inline-edit-form flex flex-wrap gap-2 items-center w-full py-1" data-id="${id}">
<select name="type" class="px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none">
<option value="donation" ${entry.type==='donation'?'selected':''}>💚 Donation</option>
<option value="expense" ${entry.type==='expense' ?'selected':''}>🔴 Expense</option>
</select>
<input name="label" value="${entry.label}" placeholder="Label"
class="flex-1 min-w-24 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
<input name="amount_eur" type="number" value="${entry.amount_eur}" step="0.01" min="0"
class="w-20 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
<input name="month" type="month" value="${entry.month}"
class="px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none [color-scheme:dark]" />
<input name="note" value="${entry.note ?? ''}" placeholder="Note"
class="flex-1 min-w-24 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-white text-xs focus:outline-none" />
<label class="flex items-center gap-1 text-xs text-zinc-400 cursor-pointer">
<input type="checkbox" name="recurring" ${entry.recurring?'checked':''} class="accent-[--accent] w-3 h-3" />↻
</label>
<button type="submit" class="px-3 py-1 rounded bg-[--accent] text-white text-xs hover:opacity-90">Save</button>
<button type="button" class="cancel-edit px-2 py-1 rounded bg-zinc-800 text-zinc-400 text-xs hover:bg-zinc-700">✕</button>
</form>`;
row.querySelector<HTMLFormElement>('.inline-edit-form')!.addEventListener('submit', async ev => {
ev.preventDefault();
const fd = new FormData(ev.target as HTMLFormElement);
const body = { type: fd.get('type'), label: fd.get('label'), amount_eur: parseFloat(fd.get('amount_eur') as string), month: fd.get('month'), note: fd.get('note'), recurring: fd.get('recurring') === 'on' };
const r = await fetch(`/api/budget/entries/${id}`, { method: 'PATCH', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
if (r.ok) { const updated = await r.json(); const idx = budgetData!.entries.findIndex(e => e.id === id); if (idx !== -1) budgetData!.entries[idx] = updated; renderBudget(); }
});
row.querySelector('.cancel-edit')!.addEventListener('click', renderBudget);
});
});
}
listEl.appendChild(wrapper);
}
}
// Load budget on page load (donate is the default tab)
+4 -9
View File
@@ -59,13 +59,8 @@ class TestAdminUserOps:
def test_delete_account_requires_admin(self, client: TestClient):
assert client.delete("/api/admin/users/alice/account").status_code == 401
def test_admin_reset_password_code(self, admin_client: TestClient, tmp_data):
from bincio.serve.db import create_user, open_db
db = open_db(tmp_data)
try:
create_user(db, "target", "Target", "targetpass1")
except Exception:
pass
def test_admin_reset_password_code_proxied(self, admin_client: TestClient):
# This endpoint proxies to bincio-auth; without BINCIO_AUTH_API configured
# in the test environment it returns 503.
r = admin_client.post("/api/admin/users/target/reset-password-code")
assert r.status_code == 200
assert "code" in r.json()
assert r.status_code == 503
+3 -3
View File
@@ -154,10 +154,10 @@ def test_hysteresis_recalc_barometric(tmp_path):
result = recalculate_elevation_hysteresis(tmp_path, "test-act")
assert result["altitude_source"] == "barometric"
assert result["threshold_m"] == pytest.approx(1.0)
assert result["threshold_m"] == pytest.approx(1.5)
# Edge effect is ≤1% on a 30-min ramp
assert result["elevation_gain_m"] == pytest.approx(1800.0, rel=0.02)
assert result["elevation_loss_m"] == pytest.approx(0.0, abs=1.0)
assert result["elevation_loss_m"] == pytest.approx(0.0, abs=1.5)
def test_hysteresis_recalc_gps(tmp_path):
@@ -166,7 +166,7 @@ def test_hysteresis_recalc_gps(tmp_path):
result = recalculate_elevation_hysteresis(tmp_path, "test-act")
assert result["threshold_m"] == pytest.approx(3.0)
assert result["threshold_m"] == pytest.approx(2.0)
assert result["elevation_gain_m"] == pytest.approx(1800.0, rel=0.02)
+5 -5
View File
@@ -73,25 +73,25 @@ class TestHysteresisEndpoint:
assert "elevation_loss_m" in body
assert body["elevation_gain_m"] > 0
assert body["altitude_source"] == "barometric"
assert body["threshold_m"] == pytest.approx(1.0)
assert body["threshold_m"] == pytest.approx(1.5)
def test_gps_source_uses_3m_threshold(self, tmp_path):
def test_gps_source_uses_2m_threshold(self, tmp_path):
elevations = [float(i) for i in range(1801)]
_make_activity(tmp_path, self.AID, elevations, altitude_source="gps")
r = CLIENT.post(f"/api/activity/{self.AID}/recalculate-elevation/hysteresis")
assert r.status_code == 200
assert r.json()["threshold_m"] == pytest.approx(3.0)
assert r.json()["threshold_m"] == pytest.approx(2.0)
def test_unknown_source_falls_back_to_gps_threshold(self, tmp_path):
def test_unknown_source_uses_1_5m_threshold(self, tmp_path):
elevations = [float(i) for i in range(1801)]
_make_activity(tmp_path, self.AID, elevations, altitude_source="unknown")
r = CLIENT.post(f"/api/activity/{self.AID}/recalculate-elevation/hysteresis")
assert r.status_code == 200
assert r.json()["threshold_m"] == pytest.approx(3.0)
assert r.json()["threshold_m"] == pytest.approx(1.5)
def test_uses_original_elevation_when_dem_backup_present(self, tmp_path):
original = [float(i) for i in range(1801)] # real 1800 m climb
+25 -21
View File
@@ -29,13 +29,14 @@ def _pt(offset_s: int, **kw) -> DataPoint:
return DataPoint(timestamp=_ts(offset_s), **kw)
def _activity(points: list[DataPoint], sport: str = "cycling") -> ParsedActivity:
def _activity(points: list[DataPoint], sport: str = "cycling", altitude_source: str = "unknown") -> ParsedActivity:
return ParsedActivity(
points=points,
sport=sport,
started_at=_ts(0),
source_file="test.fit",
source_hash="sha256:abc",
altitude_source=altitude_source,
)
@@ -110,12 +111,13 @@ def test_compute_moving_time_excludes_stops():
def test_compute_elevation_gain():
# Barometric source: no MA smoothing, so even 3 points produce correct gain.
pts = [
_pt(0, lat=48.0, lon=11.0, elevation_m=100.0),
_pt(10, lat=48.001, lon=11.0, elevation_m=150.0),
_pt(20, lat=48.002, lon=11.0, elevation_m=120.0),
]
m = compute(_activity(pts))
m = compute(_activity(pts, altitude_source="barometric"))
assert m.elevation_gain_m == 50.0
assert m.elevation_loss_m == 30.0
@@ -134,8 +136,8 @@ def _ele_pts(elevations: list[float]) -> list[DataPoint]:
def test_elevation_hysteresis_large_step_always_counted():
# A single 50m step is way above any threshold — both sources should count it.
pts = _ele_pts([100.0, 150.0])
# A 50m step with 5 points per level so the GPS moving average doesn't flatten it.
pts = _ele_pts([100.0] * 5 + [150.0] * 5)
gain_baro, _ = _elevation(pts, "barometric")
gain_gps, _ = _elevation(pts, "gps")
assert gain_baro == 50.0
@@ -143,26 +145,25 @@ def test_elevation_hysteresis_large_step_always_counted():
def test_elevation_hysteresis_flat_gps_noise_suppressed():
# Flat coastal route: 16m of GPS noise oscillating within ±8m.
# All steps are sub-1m — hysteresis should return ~0 gain.
import math
# GPS noise within ±0.5m — peak-to-peak 1.0m, well below the 2.0m GPS threshold.
n = 1000
elevations = [100.0 + 3.0 * math.sin(i * 0.1) for i in range(n)]
elevations = [100.0 + 0.5 * math.sin(i * 0.1) for i in range(n)]
pts = _ele_pts(elevations)
gain, loss = _elevation(pts, "gps")
# With threshold=10m no oscillation within ±3m should ever commit.
assert gain == 0.0
assert loss == 0.0
def test_elevation_hysteresis_barometric_threshold_lower():
# Steps of exactly 7m — above barometric (5m) but below GPS (10m) threshold.
elevations = [0.0, 7.0, 0.0, 7.0]
# 1.7m steps at 100m baseline (avoids sensor-dropout suppression which
# skips values near 0): above the 1.5m barometric threshold but, after GPS
# MA smoothing, the effective diff stays below the 2.0m GPS threshold.
elevations = [100.0, 101.7, 100.0, 101.7]
pts = _ele_pts(elevations)
gain_baro, _ = _elevation(pts, "barometric")
gain_gps, _ = _elevation(pts, "gps")
assert gain_baro == 14.0 # both 7m steps committed
assert gain_gps == 0.0 # 7m < 10m threshold suppressed
assert gain_baro == pytest.approx(3.4) # both 1.7m steps committed
assert gain_gps == 0.0 # MA + 2.0m threshold suppresses
def test_elevation_hysteresis_real_climb_approximated():
@@ -350,33 +351,36 @@ def test_best_efforts_no_targets_for_sport():
# ── best climb ────────────────────────────────────────────────────────────────
def test_best_climb_simple_ascent():
# 0 → 100 m with no gaps
ele = [float(i) for i in range(101)]
# 0 → 100 m with no gaps; x is cumulative distance (m)
ele = [(float(i), float(i)) for i in range(101)]
result = _best_climb(ele)
assert result == 100.0
def test_best_climb_with_descent():
# Up 50, down 20, up 80 → best contiguous window = 80
ele = list(range(0, 51)) + list(range(50, 30, -1)) + list(range(30, 111))
vals = list(range(0, 51)) + list(range(50, 30, -1)) + list(range(30, 111))
ele = [(float(i), float(v)) for i, v in enumerate(vals)]
result = _best_climb(ele)
assert result is not None
assert result >= 80.0
def test_best_climb_none_gap_resets_window():
# 50 m up, then a GPS gap, then 30 m up — windows don't bridge the gap
ele: list = list(range(0, 51)) + [None] + list(range(0, 31))
result = _best_climb(ele)
# 50 m up, then a GPS gap (skipped), then 30 m up — windows don't bridge the gap.
# None elevations are excluded when building dist_ele, so the climb restarts at 0.
ele_up1 = [(float(i), float(i)) for i in range(51)]
ele_up2 = [(float(51 + i), float(i)) for i in range(31)]
result = _best_climb(ele_up1 + ele_up2)
assert result == 50.0
def test_best_climb_only_descent():
ele = [100.0, 80.0, 60.0, 40.0]
ele = [(float(i), v) for i, v in enumerate([100.0, 80.0, 60.0, 40.0])]
result = _best_climb(ele)
assert result is None
def test_best_climb_too_few_samples():
assert _best_climb([]) is None
assert _best_climb([100.0]) is None
assert _best_climb([(0.0, 100.0)]) is None
+3
View File
@@ -70,6 +70,7 @@ def _dummy_metrics(**overrides):
avg_cadence_rpm=None, avg_power_w=None, np_power_w=None, max_power_w=None,
bbox=None, start_latlng=None, end_latlng=None,
mmp=None, best_efforts=None, best_climb_m=None,
climbing_vam_mh=None, climbing_time_s=None,
)
defaults.update(overrides)
return ComputedMetrics(**defaults)
@@ -216,6 +217,8 @@ def test_build_summary_required_fields():
mmp=None,
best_efforts=None,
best_climb_m=None,
climbing_vam_mh=None,
climbing_time_s=None,
)
summary = build_summary(act, metrics, "2024-06-01T073012Z-test-ride")
# Required fields per schema