From 061b50883660087df89ca8500a5b65a2fce6121c Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Wed, 25 Nov 2026 12:11:03 +0330 Subject: [PATCH 1/7] ci: run tests on pull requests to main only, via shared ci-workflows Tests-only gate (dart-test.yml) on pull requests into main; nothing runs on any other branch or event. Publishing uses the shared dart-publish.yml. --- .github/workflows/ci.yml | 15 +++----- .github/workflows/publish.yml | 69 ++++------------------------------- 2 files changed, 12 insertions(+), 72 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7430ee4..f0b97b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,16 +1,11 @@ -# The gate in front of main. Everything it runs lives once in -# CtrlAltDevelop/ci-workflows, so a fix there fixes all of the packages at -# once — format, analyze --fatal-infos, test, the example, a CHANGELOG entry -# for the pubspec version, and the pub.dev score with no points lost. +# Runs the tests on a pull request into main — and on nothing else. +# The job lives once in CtrlAltDevelop/ci-workflows (dart-test.yml). name: CI on: pull_request: branches: [main] - push: - branches: [main] - workflow_dispatch: concurrency: group: ci-${{ github.ref }} @@ -19,9 +14,9 @@ concurrency: permissions: {} jobs: - package: - name: Package - uses: CtrlAltDevelop/ci-workflows/.github/workflows/dart-package.yml@v1.1.0 + test: + name: Test + uses: CtrlAltDevelop/ci-workflows/.github/workflows/dart-test.yml@v1.2.0 permissions: contents: read with: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7be96a1..00dd223 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,15 +1,8 @@ # Publishes the package to pub.dev when a version tag is pushed. # -# Push a tag from main — `v2.2.0` publishes version 2.2.0. Nothing is published -# unless the tag is on main, matches the version in pubspec.yaml and has its -# CHANGELOG entry. -# -# One-off setup on pub.dev (package Admin tab > Automated publishing): -# - enable publishing from GitHub Actions for CtrlAltDevelop/dpop_client -# - tag pattern: v{{version}} -# - require the GitHub Actions environment: pub.dev -# and create an environment named `pub.dev` in the repository settings, with -# a required reviewer if every publish should be approved by hand. +# `v` publishes that version. The checks (tag on main, matches the +# pubspec, has a CHANGELOG entry) and the one-off pub.dev setup live in +# CtrlAltDevelop/ci-workflows (dart-publish.yml). name: Publish @@ -20,59 +13,11 @@ on: permissions: {} jobs: - verify: - name: Verify the release - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - uses: actions/checkout@v7 - with: - fetch-depth: 0 - - - name: The tag is on main - run: | - if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then - echo "::error::$GITHUB_REF_NAME is not on main; release from main." - exit 1 - fi - - - name: The tag matches the pubspec version - run: | - version=$(sed -n 's/^version: *//p' pubspec.yaml | tr -d '\r') - if [ "v$version" != "$GITHUB_REF_NAME" ]; then - echo "::error::Tag $GITHUB_REF_NAME does not match pubspec version $version." - exit 1 - fi - - - name: The CHANGELOG has an entry for it - run: | - version="${GITHUB_REF_NAME#v}" - if ! grep -q "^## $version\b" CHANGELOG.md; then - echo "::error::CHANGELOG.md has no '## $version' entry." - exit 1 - fi - publish: - name: Publish to pub.dev - needs: verify - runs-on: ubuntu-latest - environment: pub.dev + name: Publish + uses: CtrlAltDevelop/ci-workflows/.github/workflows/dart-publish.yml@v1.2.0 permissions: contents: read - # Lets pub.dev trust this run without a stored secret. id-token: write - steps: - - uses: actions/checkout@v7 - - # Pure Dart package: no Flutter SDK needed. This also sets up the - # credentials pub.dev issues to this run. - - uses: dart-lang/setup-dart@v1 - - - run: dart pub get - - - name: Dry run - run: dart pub publish --dry-run - - - name: Publish - run: dart pub publish --force + with: + sdk: dart From 9ce3e85d80c32fd584be3011d2ae8e6999e8598f Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Sun, 29 Nov 2026 16:23:02 +0330 Subject: [PATCH 2/7] docs: relicense under AGPL-3.0 The badge and the README footer that name the licence land with the 2.4.0 documentation, since that file carries unrelated changes too. --- LICENSE | 683 ++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 662 insertions(+), 21 deletions(-) diff --git a/LICENSE b/LICENSE index 5d68eb8..fe6b903 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,662 @@ -MIT License - -Copyright (c) 2026 Mohammad Zarif - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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 +. + From f7c4327cc42d12da8bad8698748048bafea9abd1 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Sun, 29 Nov 2026 16:23:12 +0330 Subject: [PATCH 3/7] perf: multiply the generator with a Jacobian comb, ~11x faster proofs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A proof costs one ES256 signature, and an ES256 signature costs one scalar multiplication of the generator. pointycastle holds curve points in affine coordinates, so every addition and doubling divides — one modular inverse each, the most expensive operation in the field, some 340 of them for a single k * G. Two changes, neither of which alters a signature. The multiplication now runs in Jacobian coordinates, deferring the division to a single inverse at the end; and because the generator never changes, its multiples are precomputed into a Lim-Lee comb of eight blocks, so k * G costs 32 doublings and 32 additions rather than 256 and 64. On the Dart VM a proof goes from ~2.8 ms to ~0.23 ms. Key generation and fromPrivateKeyPem multiply too, and get the same. The 255-entry table costs about 15 ms once, on the first signature, and roughly 35 KB for the life of the process — so a process that signs a single proof and exits is slower than it was. Its entries are converted to affine form a layer at a time with Montgomery's trick, nine inverses rather than 255, which is what keeps that build from costing more than the first forty signatures. ECDSASigner still derives k (RFC 6979) and computes r and s: the only borrowed work is the multiplication. Signatures are byte-for-byte what they were, and the tests check the comb against pointycastle's own arithmetic for 250 random scalars, for every single-bit scalar in all 256 positions, at the row boundaries and on the curve equation. The P-256 domain parameters are also built once per process instead of per call, since ECCurve_prime256v1() decompresses the generator each time it is constructed and isP256 alone was paying for that twice per key. --- lib/src/ec_keys.dart | 15 +- lib/src/es256.dart | 20 ++- lib/src/fast_p256.dart | 345 +++++++++++++++++++++++++++++++++++++++ test/fast_p256_test.dart | 175 ++++++++++++++++++++ 4 files changed, 545 insertions(+), 10 deletions(-) create mode 100644 lib/src/fast_p256.dart create mode 100644 test/fast_p256_test.dart diff --git a/lib/src/ec_keys.dart b/lib/src/ec_keys.dart index 0fd3492..30b2200 100644 --- a/lib/src/ec_keys.dart +++ b/lib/src/ec_keys.dart @@ -5,11 +5,12 @@ import 'dart:typed_data'; import 'package:asn1lib/asn1lib.dart'; import 'package:pointycastle/api.dart'; import 'package:pointycastle/ecc/api.dart'; -import 'package:pointycastle/ecc/curves/prime256v1.dart'; import 'package:pointycastle/key_generators/api.dart'; import 'package:pointycastle/key_generators/ec_key_generator.dart'; import 'package:pointycastle/random/fortuna_random.dart'; +import 'fast_p256.dart'; + /// P-256 key generation and PEM encoding, built directly on `pointycastle` and /// `asn1lib`. /// @@ -41,8 +42,11 @@ const int _tagPublicKey = 0xA1; /// The P-256 domain parameters. /// /// Built directly rather than looked up by name through pointycastle's -/// registry, so the curve cannot be missing at runtime. -ECDomainParameters p256() => ECCurve_prime256v1(); +/// registry, so the curve cannot be missing at runtime, and built **once**: +/// `ECCurve_prime256v1()` decompresses the generator on every call, which is +/// a modular exponentiation nobody needs twice. Its generator multiplies in +/// Jacobian coordinates — see `fast_p256.dart`. +ECDomainParameters p256() => fastP256; /// Whether [parameters] describe the P-256 curve. /// @@ -147,7 +151,7 @@ ECPrivateKey decodeEcPrivateKeyFromPem(String pem) { _requireP256(_taggedOid(sec1.elements[2]), 'SEC 1 parameters'); } - final BigInt d = _os2ip(_octetsAt(sec1, 1, 'SEC 1 privateKey')); + final BigInt d = os2ip(_octetsAt(sec1, 1, 'SEC 1 privateKey')); final ECDomainParameters parameters = p256(); if (d == BigInt.zero || d >= parameters.n) { throw const FormatException('EC private scalar is out of range for P-256.'); @@ -237,7 +241,8 @@ String? _taggedOid(ASN1Object tagged) { } } -BigInt _os2ip(List bytes) { +/// The integer [bytes] encodes, big-endian, per RFC 3447's OS2IP. +BigInt os2ip(List bytes) { BigInt value = BigInt.zero; for (final int byte in bytes) { value = (value << 8) | BigInt.from(byte); diff --git a/lib/src/es256.dart b/lib/src/es256.dart index 2da6af8..edf86c9 100644 --- a/lib/src/es256.dart +++ b/lib/src/es256.dart @@ -3,15 +3,25 @@ import 'dart:typed_data'; import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart' as jwt; import 'package:pointycastle/ecc/api.dart'; +import 'fast_p256.dart'; + /// Signs [message] with [key], returning the 64 byte `r || s` form a JWS /// carries. /// /// Deterministic (RFC 6979), so equal inputs give equal signatures. /// -/// `ECPrivateKey.raw` takes the parsed key straight across. Handing the signer -/// a PEM instead would re-encode and re-parse the key on every request, which -/// costs more than the signature itself. +/// The key is re-wrapped around [fastP256] rather than signed with as it +/// arrives: the domain parameters decide how `k * G` is multiplied, and a key +/// handed in from outside this package — through the `DPoPKeyPair` constructor +/// — carries pointycastle's affine generator, which is more than twenty times +/// slower for the same signature. The scalar is unchanged, so the signature +/// is too. +/// +/// Handing the signer a PEM instead of a parsed key would re-encode and +/// re-parse it on every request, which costs more than the signature itself. /// /// Internal to the package: not exported from `dpop_client.dart`. -Uint8List signEs256(ECPrivateKey key, Uint8List message) => - jwt.JWTAlgorithm.ES256.sign(jwt.ECPrivateKey.raw(key), message); +Uint8List signEs256(ECPrivateKey key, Uint8List message) => jwt + .JWTAlgorithm + .ES256 + .sign(jwt.ECPrivateKey.raw(ECPrivateKey(key.d, fastP256)), message); diff --git a/lib/src/fast_p256.dart b/lib/src/fast_p256.dart new file mode 100644 index 0000000..957d453 --- /dev/null +++ b/lib/src/fast_p256.dart @@ -0,0 +1,345 @@ +import 'package:pointycastle/ecc/api.dart'; +import 'package:pointycastle/ecc/curves/prime256v1.dart'; +import 'package:pointycastle/ecc/ecc_base.dart'; +import 'package:pointycastle/ecc/ecc_fp.dart' as fp; + +/// P-256 domain parameters whose generator multiplies in Jacobian +/// coordinates, from a precomputed comb — which is the whole cost of signing +/// a proof. +/// +/// Internal to the package: not exported from `dpop_client.dart`. +/// +/// Two things make it fast, and neither changes what a signature *is*: +/// +/// * **Jacobian coordinates.** `pointycastle` holds points in affine form, so +/// every addition and doubling divides — one modular inverse each, the most +/// expensive operation in the field at roughly fifty multiplications, some +/// 340 of them for a single `k * G`. Jacobian coordinates defer the +/// division: the ladder runs on multiplications and one inverse converts +/// the result back at the end. +/// * **A fixed-base comb.** The generator never changes, so its multiples can +/// be precomputed once. A Lim–Lee comb of [_combBlocks] blocks spends one +/// doubling and one addition per *row* of the scalar rather than per bit: +/// [_combRows] of each, instead of 256 doublings. +/// +/// Measured on the Dart VM, the two together take an ES256 signature from +/// ~2.8 ms to ~0.23 ms: the Jacobian ladder on its own is worth about four +/// times, and the comb the rest. +/// +/// `ECDSASigner` still derives `k` (RFC 6979), still computes `r` and `s`, +/// and still decides what a signature is; the only borrowed work is +/// multiplying the generator, whose result is checked against pointycastle's +/// own for random scalars in the tests. +/// +/// Like `pointycastle` — and like Dart's `BigInt` underneath it — this is not +/// constant-time: the comb row selects a table entry and the arithmetic is +/// variable-time. That is the same exposure the affine path already had, and +/// it is why a key that must resist a local side-channel attacker belongs in +/// a platform keystore behind a `DPoPSigner`, not in Dart memory. +final ECDomainParameters fastP256 = _buildFastP256(); + +/// How many equal blocks the 256-bit scalar is cut into. +/// +/// It has to divide 256, or the top bits would fall outside every block. +/// Eight means 32 rows and a table of 255 points, about 35 KB, built in +/// ~15 ms on the first signature; four would be 64 rows and 15 points, a +/// quarter of the build and a tenth of the memory, for ~0.23 ms a proof +/// instead of ~0.13 ms. Eight is the better trade for anything that signs +/// more than about seventy proofs, which is every client that stays signed +/// in for a while. +const int _combBlocks = 8; + +/// The bits per block, and so the number of rows the comb walks: one doubling +/// and at most one addition each. +const int _combRows = 256 ~/ _combBlocks; + +/// The comb table: `_table[e]` is the sum of `2^(32j) * G` over the bits `j` +/// set in `e`. Index 0 is the point at infinity and is never read. +/// +/// Rooted in pointycastle's own generator, so the table cannot drift from the +/// curve it belongs to, and checked against pointycastle's arithmetic in the +/// tests. +final List<_Affine> _table = _buildCombTable(); + +/// The field prime, `p`. +final BigInt _p = (fastP256.curve as fp.ECCurve).q!; + +/// The cofactor of P-256, which is 1 for every prime-order NIST curve. +final BigInt _domainH = BigInt.one; + +ECDomainParameters _buildFastP256() { + final ECDomainParameters standard = ECCurve_prime256v1(); + final fp.ECPoint g = standard.G as fp.ECPoint; + return ECDomainParametersImpl( + standard.domainName, + standard.curve, + _FastGenerator( + standard.curve as fp.ECCurve, + g.x as fp.ECFieldElement?, + g.y as fp.ECFieldElement?, + ), + standard.n, + _domainH, + standard.seed, + ); +} + +/// The curve's generator, multiplying through [_multiplyG]. +/// +/// Only `*` is overridden: every other operation is pointycastle's, so a +/// point that leaves here behaves exactly like one that never did. +class _FastGenerator extends fp.ECPoint { + _FastGenerator(super.curve, super.x, super.y); + + @override + fp.ECPoint? operator *(BigInt? k) { + if (k == null || k.sign < 0) { + throw ArgumentError.value(k, 'k', 'must not be null or negative'); + } + if (k.sign == 0) { + return curve.infinity as fp.ECPoint?; + } + // The comb covers 256 bits, which every scalar on this curve fits in. + // A larger one is reduced rather than refused: `G` has order `n`, so the + // point is the same one pointycastle would return. + final BigInt scalar = k.bitLength > 256 ? k % fastP256.n : k; + if (scalar.sign == 0) { + return curve.infinity as fp.ECPoint?; + } + return _multiplyG(scalar, curve as fp.ECCurve); + } +} + +/// An affine point as plain integers, which is all the ladder needs. +class _Affine { + const _Affine(this.x, this.y); + + factory _Affine.of(ECPoint point) => + _Affine(point.x!.toBigInteger()!, point.y!.toBigInteger()!); + + final BigInt x; + final BigInt y; +} + +/// `k * G`, a row of the comb at a time. +/// +/// Row `i` is the bit `i` of each block, gathered into a [_combBlocks]-bit +/// index into [_table]. Walking the rows from the top costs one doubling and +/// at most one addition each — [_combRows] of them, where reading the scalar +/// bit by bit would cost 256. +fp.ECPoint _multiplyG(BigInt k, fp.ECCurve curve) { + final List bytes = _bytesOf(k); + + // Jacobian accumulator. Z == 0 is the point at infinity, which lets the + // leading empty rows be skipped without a special case per iteration. + BigInt x = BigInt.zero; + BigInt y = BigInt.one; + BigInt z = BigInt.zero; + + for (int row = _combRows - 1; row >= 0; row--) { + if (z.sign != 0) { + (x, y, z) = _double(x, y, z); + } + final int index = _rowOf(bytes, row); + if (index == 0) { + continue; + } + final _Affine addend = _table[index]; + if (z.sign == 0) { + (x, y, z) = (addend.x, addend.y, BigInt.one); + } else { + (x, y, z) = _addAffine(x, y, z, addend); + } + } + + if (z.sign == 0) { + return curve.infinity as fp.ECPoint; + } + final _Affine point = _toAffine(x, y, z); + return fp.ECPoint( + curve, + curve.fromBigInteger(point.x) as fp.ECFieldElement?, + curve.fromBigInteger(point.y) as fp.ECFieldElement?, + ); +} + +/// [k] as 32 big-endian octets, so a bit costs an array index rather than a +/// `BigInt` shift and mask. +List _bytesOf(BigInt k) { + final List bytes = List.filled(32, 0); + BigInt remaining = k; + for (int i = 31; i >= 0 && remaining.sign != 0; i--) { + bytes[i] = (remaining & _byteMask).toInt(); + remaining >>= 8; + } + return bytes; +} + +/// The comb index for [row]: bit [row] of every block, block `j` at bit `j`. +int _rowOf(List bytes, int row) { + int index = 0; + for (int block = 0; block < _combBlocks; block++) { + final int bit = block * _combRows + row; + if ((bytes[31 - (bit >> 3)] >> (bit & 7)) & 1 == 1) { + index |= 1 << block; + } + } + return index; +} + +/// Builds the 255 sums of the block generators `2^(32j) * G`. +/// +/// Every entry has to end up affine, since that is what makes each addition +/// in [_multiplyG] the cheap mixed one — and converting means a modular +/// inverse, which at 255 of them would cost more than the first forty +/// signatures. So the entries are built a layer at a time, by how many bits +/// they carry: each one is an entry of the layer below plus a block +/// generator, which means a whole layer can be computed before any of it is +/// needed, and converted with one inverse for the lot (Montgomery's trick). +/// Nine inverses in all, and about 15 ms once, on the first signature. +List<_Affine> _buildCombTable() { + final List<_Affine> table = List<_Affine>.filled( + 1 << _combBlocks, + _Affine.of(ECCurve_prime256v1().G), + ); + + // table[1 << j] = 2^(_combRows * j) * G, each one the previous doubled a + // block's worth of times. These are the only serial steps. + for (int block = 1; block < _combBlocks; block++) { + final _Affine previous = table[1 << (block - 1)]; + BigInt x = previous.x; + BigInt y = previous.y; + BigInt z = BigInt.one; + for (int i = 0; i < _combRows; i++) { + (x, y, z) = _double(x, y, z); + } + table[1 << block] = _toAffine(x, y, z); + } + + for (int bits = 2; bits <= _combBlocks; bits++) { + final List indices = []; + final List xs = []; + final List ys = []; + final List zs = []; + for (int e = 3; e < table.length; e++) { + if (_bitsIn(e) != bits) { + continue; + } + final int lowestBit = e & -e; + final _Affine rest = table[e ^ lowestBit]; + final (BigInt x, BigInt y, BigInt z) = _addAffine( + rest.x, + rest.y, + BigInt.one, + table[lowestBit], + ); + indices.add(e); + xs.add(x); + ys.add(y); + zs.add(z); + } + final List inverses = _invertAll(zs); + for (int i = 0; i < indices.length; i++) { + final BigInt zInv = inverses[i]; + final BigInt zInv2 = (zInv * zInv) % _p; + table[indices[i]] = _Affine( + (xs[i] * zInv2) % _p, + (ys[i] * zInv2 % _p) * zInv % _p, + ); + } + } + return table; +} + +/// How many bits [value] has set. +int _bitsIn(int value) { + int count = 0; + for (int bit = value; bit != 0; bit >>= 1) { + count += bit & 1; + } + return count; +} + +/// The modular inverse of every element of [values], with one inverse and +/// three multiplications apiece — Montgomery's trick. +/// +/// Runs the product forward, inverts it once, then walks back peeling one +/// factor off at a time. No element may be zero, which here means no entry +/// of a layer may be the point at infinity: two distinct multiples of `G` +/// never cancel, so none is. +List _invertAll(List values) { + final List prefixes = List.filled(values.length, BigInt.one); + BigInt product = BigInt.one; + for (int i = 0; i < values.length; i++) { + prefixes[i] = product; + product = (product * values[i]) % _p; + } + BigInt inverse = product.modInverse(_p); + final List inverses = List.filled(values.length, BigInt.one); + for (int i = values.length - 1; i >= 0; i--) { + inverses[i] = (inverse * prefixes[i]) % _p; + inverse = (inverse * values[i]) % _p; + } + return inverses; +} + +/// A Jacobian point back in affine form: `x/z^2`, `y/z^3`, one inverse. +_Affine _toAffine(BigInt x, BigInt y, BigInt z) { + final BigInt zInv = z.modInverse(_p); + final BigInt zInv2 = (zInv * zInv) % _p; + return _Affine((x * zInv2) % _p, (y * zInv2 % _p) * zInv % _p); +} + +final BigInt _byteMask = BigInt.from(0xff); +final BigInt _two = BigInt.two; +final BigInt _three = BigInt.from(3); +final BigInt _four = BigInt.from(4); +final BigInt _eight = BigInt.from(8); + +/// Doubles a Jacobian point, using the `a == -3` form P-256 allows +/// (`dbl-2001-b`). +(BigInt, BigInt, BigInt) _double(BigInt x, BigInt y, BigInt z) { + if (y.sign == 0) { + return (BigInt.zero, BigInt.one, BigInt.zero); + } + final BigInt delta = (z * z) % _p; + final BigInt gamma = (y * y) % _p; + final BigInt beta = (x * gamma) % _p; + final BigInt alpha = (_three * ((x - delta) % _p) * ((x + delta) % _p)) % _p; + final BigInt x3 = (alpha * alpha - _eight * beta) % _p; + final BigInt z3 = (((y + z) * (y + z)) % _p - gamma - delta) % _p; + final BigInt y3 = + (alpha * ((_four * beta - x3) % _p) - _eight * gamma * gamma) % _p; + return (x3 % _p, y3 % _p, z3 % _p); +} + +/// Adds an affine point to a Jacobian one, `z2 == 1` (`madd-2007-bl`). +(BigInt, BigInt, BigInt) _addAffine( + BigInt x1, + BigInt y1, + BigInt z1, + _Affine q, +) { + final BigInt z1z1 = (z1 * z1) % _p; + final BigInt u2 = (q.x * z1z1) % _p; + final BigInt s2 = (q.y * z1 * z1z1) % _p; + final BigInt h = (u2 - x1) % _p; + final BigInt r = (_two * (s2 - y1)) % _p; + + if (h.sign == 0) { + // The accumulator already holds this very point, or its negation. A + // random scalar never lands here, but a chosen one would. + return r.sign == 0 + ? _double(x1, y1, z1) + : (BigInt.zero, BigInt.one, BigInt.zero); + } + + final BigInt hh = (h * h) % _p; + final BigInt i = (_four * hh) % _p; + final BigInt j = (h * i) % _p; + final BigInt v = (x1 * i) % _p; + final BigInt x3 = (r * r - j - _two * v) % _p; + final BigInt y3 = (r * ((v - x3) % _p) - _two * y1 * j) % _p; + final BigInt z3 = (((z1 + h) * (z1 + h)) % _p - z1z1 - hh) % _p; + return (x3 % _p, y3 % _p, z3 % _p); +} diff --git a/test/fast_p256_test.dart b/test/fast_p256_test.dart new file mode 100644 index 0000000..24e685f --- /dev/null +++ b/test/fast_p256_test.dart @@ -0,0 +1,175 @@ +// The fast generator exists only to make `k * G` cheaper. Its whole contract +// is that it agrees with pointycastle's own arithmetic, so that is what these +// tests check: the same points, and the same signatures, for scalars chosen +// at random and for the edges a window-based ladder could trip over. +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:dart_jsonwebtoken/dart_jsonwebtoken.dart' as jwt; +import 'package:dpop_client/dpop_client.dart'; +import 'package:dpop_client/src/fast_p256.dart'; +import 'package:pointycastle/ecc/api.dart'; +import 'package:pointycastle/ecc/curves/prime256v1.dart'; +import 'package:test/test.dart'; + +import 'golden_key.dart'; + +/// pointycastle's stock P-256, with the affine generator. +final ECDomainParameters standard = ECCurve_prime256v1(); + +/// A scalar in `[1, n)` built from [random]. +BigInt randomScalar(Random random) { + BigInt value = BigInt.zero; + for (int i = 0; i < 8; i++) { + value = (value << 32) | BigInt.from(random.nextInt(1 << 32)); + } + final BigInt scalar = value % standard.n; + return scalar == BigInt.zero ? BigInt.one : scalar; +} + +void expectSamePoint(BigInt scalar) { + final ECPoint expected = (standard.G * scalar)!; + final ECPoint actual = (fastP256.G * scalar)!; + expect( + actual.x!.toBigInteger(), + expected.x!.toBigInteger(), + reason: 'x differs for scalar $scalar', + ); + expect( + actual.y!.toBigInteger(), + expected.y!.toBigInteger(), + reason: 'y differs for scalar $scalar', + ); +} + +void main() { + group('k * G', () { + test('matches pointycastle for 250 random scalars', () { + // Seeded, so a failure is reproducible rather than a one-off report. + final Random random = Random(20260101); + for (int i = 0; i < 250; i++) { + expectSamePoint(randomScalar(random)); + } + }); + + test('matches pointycastle at the comb boundaries', () { + // Small scalars touch only the lowest block, which is the branch that + // skips leading empty rows, and 255/256/257 straddle a row. + for (final int scalar in [ + 1, + 2, + 3, + 15, + 16, + 17, + 31, + 32, + 255, + 256, + 257, + 4095, + 4096, + ]) { + expectSamePoint(BigInt.from(scalar)); + } + }); + + test('matches pointycastle for a single bit in every block', () { + // One bit per position reaches every block generator on its own, and + // a pair of bits reaches the entries built from two of them. + for (int bit = 0; bit < 256; bit++) { + expectSamePoint(BigInt.one << bit); + } + for (int bit = 0; bit < 256; bit += 7) { + expectSamePoint((BigInt.one << bit) | BigInt.one); + } + }); + + test('matches pointycastle for a scalar with every bit set', () { + // Reads table entry 255, the only one built from all eight blocks, on + // every row. + expectSamePoint((BigInt.one << 256) - BigInt.one); + }); + + test('reduces a scalar wider than the comb, which is the same point', () { + // `G` has order `n`, so `(k + n) * G == k * G`. pointycastle does not + // reduce; the comb does, and has to land in the same place. + final BigInt k = BigInt.from(123456789); + expectSamePoint(k); + final ECPoint wide = (fastP256.G * (k + standard.n))!; + final ECPoint plain = (standard.G * k)!; + expect(wide.x!.toBigInteger(), plain.x!.toBigInteger()); + expect(wide.y!.toBigInteger(), plain.y!.toBigInteger()); + }); + + test('matches pointycastle at the top of the scalar range', () { + expectSamePoint(standard.n - BigInt.one); + expectSamePoint(standard.n - BigInt.two); + expectSamePoint(standard.n >> 1); + }); + + test('is the point at infinity for zero', () { + expect((fastP256.G * BigInt.zero)!.isInfinity, isTrue); + }); + + test('refuses a negative scalar', () { + expect(() => fastP256.G * -BigInt.one, throwsA(isA())); + }); + + test('lands on the curve', () { + // An error in the Jacobian ladder would most likely leave the result + // off the curve, which the point equality above would catch only + // because pointycastle is right. Check y^2 == x^3 - 3x + b directly. + final BigInt p = BigInt.parse( + 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff', + radix: 16, + ); + final BigInt b = BigInt.parse( + '5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b', + radix: 16, + ); + final Random random = Random(7); + for (int i = 0; i < 25; i++) { + final ECPoint point = (fastP256.G * randomScalar(random))!; + final BigInt x = point.x!.toBigInteger()!; + final BigInt y = point.y!.toBigInteger()!; + expect( + (y * y) % p, + (x * x * x - BigInt.from(3) * x + b) % p, + reason: 'point $i is not on P-256', + ); + } + }); + }); + + group('signatures', () { + test('are identical to the ones the affine generator produces', () { + final DPoPKeyPair pair = DPoPKeyPair.fromPrivateKeyPem( + goldenPrivateKeyPem, + ); + final Random random = Random(99); + for (int i = 0; i < 10; i++) { + final Uint8List message = Uint8List.fromList( + List.generate(64 + i, (_) => random.nextInt(256)), + ); + final Uint8List affine = jwt.JWTAlgorithm.ES256.sign( + jwt.ECPrivateKey.raw(ECPrivateKey(pair.privateKey.d, standard)), + message, + ); + final Uint8List fast = jwt.JWTAlgorithm.ES256.sign( + jwt.ECPrivateKey.raw(ECPrivateKey(pair.privateKey.d, fastP256)), + message, + ); + expect(fast, affine, reason: 'signature $i differs'); + } + }); + + test('a generated key derives the same public point either way', () { + final BigInt d = DPoPKeyPair.generate().privateKey.d!; + final ECPoint affine = (standard.G * d)!; + final ECPoint fast = (fastP256.G * d)!; + expect(fast.x!.toBigInteger(), affine.x!.toBigInteger()); + expect(fast.y!.toBigInteger(), affine.y!.toBigInteger()); + }); + }); +} From b65156f9e7184d9256f3ed583edccafb2975b0b7 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Sun, 29 Nov 2026 16:23:24 +0330 Subject: [PATCH 4/7] feat: remember server nonces per origin with DPoPNonceStore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A server that wants a nonce answers 401 with error="use_dpop_nonce" and a DPoP-Nonce header, and may issue another on any later response. Doing that by hand means holding a nonce per server, reading the header off every response and retrying exactly once — the snippet the README used to recommend. DPoPNonceStore holds that state, keyed by origin, which is the granularity RFC 9449 §8.2 gives it: an authorization server and a resource server run separate nonce spaces. Hand one to DPoPClient or DPoPSignerClient and every proof carries the right nonce without the call site passing it; an explicit nonce: still wins. update(url, headers) returns true only for a nonce the store had not already tried, which is both the reason to retry and the guard against retrying forever. Header names are matched case-insensitively, since a map assembled by a gateway SDK may not be lower-cased. forget(url) drops one origin, clear() the lot. Memory only, and no HTTP client: a nonce is short-lived and server-issued, so losing the lot on restart costs one round trip. --- lib/dpop_client.dart | 4 +- lib/src/dpop_client_base.dart | 17 ++- lib/src/dpop_nonce_store.dart | 115 +++++++++++++++++ lib/src/dpop_signer_client.dart | 12 +- test/dpop_nonce_store_test.dart | 213 ++++++++++++++++++++++++++++++++ 5 files changed, 355 insertions(+), 6 deletions(-) create mode 100644 lib/src/dpop_nonce_store.dart create mode 100644 test/dpop_nonce_store_test.dart diff --git a/lib/dpop_client.dart b/lib/dpop_client.dart index c5f15eb..dd83d51 100644 --- a/lib/dpop_client.dart +++ b/lib/dpop_client.dart @@ -6,7 +6,8 @@ /// short-lived JWT — the *proof* — signed by that key and covering the /// request's method and URI. /// -/// Generate a key pair once, persist it, and create a proof per request: +/// Generate a key pair once, persist it — as a PEM, or as a JWK with +/// `privateJwk` — and create a proof per request: /// /// ```dart /// final keyPair = DPoPKeyPair.generate(); @@ -27,6 +28,7 @@ library; export 'src/dpop_client_base.dart'; export 'src/dpop_key_pair.dart'; +export 'src/dpop_nonce_store.dart'; export 'src/dpop_proof.dart'; export 'src/dpop_signer.dart'; export 'src/dpop_signer_client.dart'; diff --git a/lib/src/dpop_client_base.dart b/lib/src/dpop_client_base.dart index a7aa04b..8dde32b 100644 --- a/lib/src/dpop_client_base.dart +++ b/lib/src/dpop_client_base.dart @@ -1,6 +1,7 @@ import 'dart:typed_data'; import 'dpop_key_pair.dart'; +import 'dpop_nonce_store.dart'; import 'dpop_proof.dart'; import 'es256.dart'; import 'unsigned_proof.dart'; @@ -24,12 +25,20 @@ import 'unsigned_proof.dart'; /// ``` class DPoPClient { /// Creates a proof signer for [keyPair]. - const DPoPClient(this.keyPair); + /// + /// Pass [nonces] to have every proof carry the most recent nonce the target + /// server issued, so no call site has to remember one. Feed that store from + /// your responses with `DPoPNonceStore.update`. + const DPoPClient(this.keyPair, {this.nonces}); /// The key pair every proof is signed with, and whose public half travels /// in each proof's JWT header. final DPoPKeyPair keyPair; + /// Where the nonce of a proof comes from when the call site passes none, + /// or `null` if this client was built without one. + final DPoPNonceStore? nonces; + /// The signing key's RFC 7638 thumbprint — the `jkt` an authorization /// server binds an access token to. Shorthand for `keyPair.thumbprint`. String get thumbprint => keyPair.thumbprint; @@ -55,7 +64,9 @@ class DPoPClient { /// Pass [nonce] when a server has demanded one. Servers signal this with a /// `401` carrying a `DPoP-Nonce` header and `error="use_dpop_nonce"`; take /// that header's value, retry the request with it here, and keep using the - /// most recent nonce the server sent until it issues another. + /// most recent nonce the server sent until it issues another. A client + /// built with a [DPoPNonceStore] does that for you: leave [nonce] out and + /// the store's nonce for [url]'s origin is used. /// /// [issuedAt] and [jwtId] default to now and a random UUID v4. Set them only /// in tests — a fixed `jti` invites the replay detection it exists to @@ -73,7 +84,7 @@ class DPoPClient { url: url, method: method, accessToken: accessToken, - nonce: nonce, + nonce: nonce ?? nonces?.nonceFor(url), issuedAt: issuedAt, jwtId: jwtId, ); diff --git a/lib/src/dpop_nonce_store.dart b/lib/src/dpop_nonce_store.dart new file mode 100644 index 0000000..09a466b --- /dev/null +++ b/lib/src/dpop_nonce_store.dart @@ -0,0 +1,115 @@ +/// Remembers the most recent `DPoP-Nonce` each server issued. +/// +/// A server that wants a nonce answers `401` with `error="use_dpop_nonce"` and +/// a `DPoP-Nonce` response header. The client retries with that value and +/// keeps using it until the server issues another — and it issues another +/// whenever it likes, on any response, including a successful one +/// (RFC 9449 §8). Doing that by hand means remembering a nonce per server, +/// reading the header off every response, and retrying exactly once. +/// +/// Hold one store for the lifetime of a session and hand it to the client: +/// +/// ```dart +/// final nonces = DPoPNonceStore(); +/// final client = DPoPClient(keyPair, nonces: nonces); +/// +/// Future send(Request request) async { +/// final proof = client.createProof(url: request.url, method: 'POST'); +/// final response = await _send(request, proof); +/// +/// // Retry once, and only against a nonce we had not already tried. +/// if (nonces.update(request.url, response.headers) && +/// response.statusCode == 401) { +/// return send(request); +/// } +/// return response; +/// } +/// ``` +/// +/// Nonces are kept per **origin** — scheme, host and port — because that is +/// the granularity RFC 9449 §8.2 gives them: an authorization server and a +/// resource server run separate nonce spaces, and offering one server's nonce +/// to another earns a fresh `401` at best. +/// +/// This is memory only. A nonce is short-lived and server-issued, so losing +/// the lot on restart costs one extra round trip; there is nothing here worth +/// persisting. +class DPoPNonceStore { + /// Creates an empty store. + DPoPNonceStore(); + + /// The response header a server issues a nonce in, RFC 9449 §8. + static const String headerName = 'DPoP-Nonce'; + + static const String _lowerHeaderName = 'dpop-nonce'; + + final Map _byOrigin = {}; + + /// The most recent nonce [url]'s server issued, or `null` if it has not + /// issued one. + /// + /// A client built with this store passes it to every proof on its own; + /// reach for this only to inspect what is held. + String? nonceFor(Uri url) => _byOrigin[_originOf(url)]; + + /// Takes the nonce out of [responseHeaders] and remembers it for [url]'s + /// origin. + /// + /// Returns `true` when the header carried a nonce this store had not seen + /// yet — which is exactly the condition for retrying a request that failed + /// with `use_dpop_nonce`, and the guard against retrying forever against a + /// server that keeps answering `401` with the same nonce. Returns `false` + /// when there was no header, or when it repeated the nonce already held. + /// + /// Header names are matched case-insensitively: `dart:io` and + /// `package:http` both lower-case them, but a map assembled by hand or by a + /// gateway SDK may not. + bool update(Uri url, Map responseHeaders) { + final String? issued = _nonceIn(responseHeaders); + if (issued == null || issued.isEmpty) { + return false; + } + final String origin = _originOf(url); + if (_byOrigin[origin] == issued) { + return false; + } + _byOrigin[origin] = issued; + return true; + } + + /// Forgets [url]'s origin's nonce, if it has one. + /// + /// Worth doing when a server rejects a proof for a reason other than + /// `use_dpop_nonce`, so the next request is not built on a nonce the server + /// has stopped accepting. + void forget(Uri url) => _byOrigin.remove(_originOf(url)); + + /// Forgets every nonce. Call it on sign-out, alongside dropping the key. + void clear() => _byOrigin.clear(); + + static String? _nonceIn(Map headers) { + final String? direct = headers[_lowerHeaderName] ?? headers[headerName]; + if (direct != null) { + return direct; + } + for (final MapEntry header in headers.entries) { + if (header.key.toLowerCase() == _lowerHeaderName) { + return header.value; + } + } + return null; + } + + /// `scheme://host:port`, the key a nonce is held under. + /// + /// The port is always written out, so a URL that states the default port + /// and one that leaves it implicit share an entry. + static String _originOf(Uri url) => + '${url.scheme}://${url.host}:${url.hasPort ? url.port : _defaultPortOf(url.scheme)}'; + + static int _defaultPortOf(String scheme) => switch (scheme) { + 'https' || 'wss' => 443, + 'http' || 'ws' => 80, + _ => 0, + }; +} diff --git a/lib/src/dpop_signer_client.dart b/lib/src/dpop_signer_client.dart index 9bf3333..c44df7c 100644 --- a/lib/src/dpop_signer_client.dart +++ b/lib/src/dpop_signer_client.dart @@ -1,5 +1,6 @@ import 'dart:typed_data'; +import 'dpop_nonce_store.dart'; import 'dpop_proof.dart'; import 'dpop_signer.dart'; import 'jwk_thumbprint.dart'; @@ -26,12 +27,19 @@ import 'unsigned_proof.dart'; /// ``` class DPoPSignerClient { /// Creates a proof signer backed by [signer]. - const DPoPSignerClient(this.signer); + /// + /// Pass [nonces] to have every proof carry the most recent nonce the target + /// server issued, exactly as `DPoPClient` does. + const DPoPSignerClient(this.signer, {this.nonces}); /// The signer every proof is signed with, and whose public JWK travels in /// each proof's JWT header. final DPoPSigner signer; + /// Where the nonce of a proof comes from when the call site passes none, + /// or `null` if this client was built without one. + final DPoPNonceStore? nonces; + /// The signing key's RFC 7638 thumbprint — the `jkt` an authorization /// server binds an access token to. Computed from `signer.publicJwk` on /// each call. @@ -73,7 +81,7 @@ class DPoPSignerClient { url: url, method: method, accessToken: accessToken, - nonce: nonce, + nonce: nonce ?? nonces?.nonceFor(url), issuedAt: issuedAt, jwtId: jwtId, ); diff --git a/test/dpop_nonce_store_test.dart b/test/dpop_nonce_store_test.dart new file mode 100644 index 0000000..02dfc65 --- /dev/null +++ b/test/dpop_nonce_store_test.dart @@ -0,0 +1,213 @@ +import 'dart:convert'; + +import 'package:dpop_client/dpop_client.dart'; +import 'package:test/test.dart'; + +import 'golden_key.dart'; + +/// The claims of a proof, read without verifying it — what a server sees. +Map payloadOf(String token) => + jsonDecode( + utf8.decode( + base64Url.decode(base64Url.normalize(token.split('.')[1])), + ), + ) + as Map; + +void main() { + final Uri api = Uri.parse('https://api.example.com/v1/orders?limit=20'); + final Uri auth = Uri.parse('https://auth.example.com/oauth2/token'); + + group('DPoPNonceStore', () { + test('has no nonce for a server that has not issued one', () { + expect(DPoPNonceStore().nonceFor(api), isNull); + }); + + test('keeps the nonce a response issued', () { + final DPoPNonceStore store = DPoPNonceStore(); + + expect(store.update(api, {'dpop-nonce': 'n-1'}), isTrue); + + expect(store.nonceFor(api), 'n-1'); + }); + + test('reads the header whatever its case', () { + final DPoPNonceStore store = DPoPNonceStore(); + + store.update(api, {'DPoP-Nonce': 'n-1'}); + + expect(store.nonceFor(api), 'n-1'); + }); + + test('reports a repeated nonce as nothing new, so a retry stops', () { + final DPoPNonceStore store = DPoPNonceStore(); + store.update(api, {'dpop-nonce': 'n-1'}); + + expect(store.update(api, {'dpop-nonce': 'n-1'}), isFalse); + }); + + test('reports a replacement nonce as new', () { + final DPoPNonceStore store = DPoPNonceStore(); + store.update(api, {'dpop-nonce': 'n-1'}); + + expect(store.update(api, {'dpop-nonce': 'n-2'}), isTrue); + expect(store.nonceFor(api), 'n-2'); + }); + + test('reports nothing new when the response carries no nonce', () { + final DPoPNonceStore store = DPoPNonceStore(); + + expect( + store.update(api, {'content-type': 'application/json'}), + isFalse, + ); + expect(store.nonceFor(api), isNull); + }); + + test('ignores an empty nonce header', () { + final DPoPNonceStore store = DPoPNonceStore(); + + expect(store.update(api, {'dpop-nonce': ''}), isFalse); + expect(store.nonceFor(api), isNull); + }); + + test('holds one nonce per origin', () { + final DPoPNonceStore store = DPoPNonceStore(); + + store.update(api, {'dpop-nonce': 'api-1'}); + store.update(auth, {'dpop-nonce': 'auth-1'}); + + expect(store.nonceFor(api), 'api-1'); + expect(store.nonceFor(auth), 'auth-1'); + }); + + test('shares one entry across paths, queries and the default port', () { + final DPoPNonceStore store = DPoPNonceStore(); + + store.update(api, {'dpop-nonce': 'n-1'}); + + expect(store.nonceFor(Uri.parse('https://api.example.com/v1/me')), 'n-1'); + expect( + store.nonceFor(Uri.parse('https://api.example.com:443/v1/me')), + 'n-1', + ); + }); + + test('separates a non-default port and another scheme', () { + final DPoPNonceStore store = DPoPNonceStore(); + + store.update(api, {'dpop-nonce': 'n-1'}); + + expect( + store.nonceFor(Uri.parse('https://api.example.com:8443/v1/me')), + isNull, + ); + expect(store.nonceFor(Uri.parse('http://api.example.com/v1/me')), isNull); + }); + + test('matches a wss URL to its default port', () { + final DPoPNonceStore store = DPoPNonceStore(); + + store.update(Uri.parse('wss://api.example.com:443/ws'), { + 'dpop-nonce': 'n-1', + }); + + expect(store.nonceFor(Uri.parse('wss://api.example.com/ws')), 'n-1'); + }); + + test('forget drops one origin and leaves the rest', () { + final DPoPNonceStore store = DPoPNonceStore(); + store.update(api, {'dpop-nonce': 'api-1'}); + store.update(auth, {'dpop-nonce': 'auth-1'}); + + store.forget(api); + + expect(store.nonceFor(api), isNull); + expect(store.nonceFor(auth), 'auth-1'); + }); + + test('clear drops every origin', () { + final DPoPNonceStore store = DPoPNonceStore(); + store.update(api, {'dpop-nonce': 'api-1'}); + store.update(auth, {'dpop-nonce': 'auth-1'}); + + store.clear(); + + expect(store.nonceFor(api), isNull); + expect(store.nonceFor(auth), isNull); + }); + }); + + group('a client holding a store', () { + final DPoPKeyPair pair = DPoPKeyPair.fromPrivateKeyPem(goldenPrivateKeyPem); + + test('omits the nonce claim until a server has issued one', () { + final DPoPClient client = DPoPClient(pair, nonces: DPoPNonceStore()); + + final DPoPProof proof = client.createProof(url: api, method: 'GET'); + + expect(payloadOf(proof.token), isNot(contains('nonce'))); + }); + + test('carries the stored nonce without being asked', () { + final DPoPNonceStore nonces = DPoPNonceStore(); + final DPoPClient client = DPoPClient(pair, nonces: nonces); + nonces.update(api, {'dpop-nonce': 'n-1'}); + + final DPoPProof proof = client.createProof(url: api, method: 'GET'); + + expect(payloadOf(proof.token)['nonce'], 'n-1'); + }); + + test( + 'uses the nonce of the origin being called, not the last one seen', + () { + final DPoPNonceStore nonces = DPoPNonceStore(); + final DPoPClient client = DPoPClient(pair, nonces: nonces); + nonces.update(api, {'dpop-nonce': 'api-1'}); + nonces.update(auth, {'dpop-nonce': 'auth-1'}); + + expect( + payloadOf( + client.createProof(url: auth, method: 'POST').token, + )['nonce'], + 'auth-1', + ); + }, + ); + + test('lets an explicit nonce win over the stored one', () { + final DPoPNonceStore nonces = DPoPNonceStore(); + final DPoPClient client = DPoPClient(pair, nonces: nonces); + nonces.update(api, {'dpop-nonce': 'stored'}); + + final DPoPProof proof = client.createProof( + url: api, + method: 'GET', + nonce: 'explicit', + ); + + expect(payloadOf(proof.token)['nonce'], 'explicit'); + }); + + test('a signer client carries the stored nonce too', () async { + final DPoPNonceStore nonces = DPoPNonceStore(); + final DPoPSignerClient client = DPoPSignerClient(pair, nonces: nonces); + nonces.update(api, {'dpop-nonce': 'n-1'}); + + final DPoPProof proof = await client.createProof(url: api, method: 'GET'); + + expect(payloadOf(proof.token)['nonce'], 'n-1'); + }); + + test('a client with no store behaves as before', () { + final DPoPClient client = DPoPClient(pair); + + expect(client.nonces, isNull); + expect( + payloadOf(client.createProof(url: api, method: 'GET').token), + isNot(contains('nonce')), + ); + }); + }); +} From e854743fc422697580c6656d107b02c8015f1fb4 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Sun, 29 Nov 2026 16:23:24 +0330 Subject: [PATCH 5/7] feat: store and restore a key as a JWK MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The package could only persist a key as a PEM, which is awkward for storage that holds JSON and for anything interoperating with WebCrypto or a JOSE library in another language. privateJwk is the public jwk plus d, the form RFC 7518 §6.2.2 gives an EC private key, so the two storage shapes are the same key and sign byte-identical proofs. fromPrivateJwk reads only kty, crv, d, x and y, so a crypto.subtle.exportKey('jwk', ...) result can be passed through with its ext and key_ops still on it. x and y are optional, since the public half is derived from d, and checked when present: a JWK whose coordinates do not belong to its d is refused rather than used to publish a key that cannot verify its own signatures, which is the guard fromPem already had. A JWK that is not a readable P-256 private key throws a FormatException, as the PEM constructors do. privateJwk carries the private key, so it belongs in the keystore with privateKeyPem; dpopThumbprint still refuses anything carrying d. --- lib/src/dpop_key_pair.dart | 133 ++++++++++++++++++ test/dpop_key_pair_jwk_test.dart | 225 +++++++++++++++++++++++++++++++ 2 files changed, 358 insertions(+) create mode 100644 test/dpop_key_pair_jwk_test.dart diff --git a/lib/src/dpop_key_pair.dart b/lib/src/dpop_key_pair.dart index a4acd2f..6c445f4 100644 --- a/lib/src/dpop_key_pair.dart +++ b/lib/src/dpop_key_pair.dart @@ -107,6 +107,118 @@ class DPoPKeyPair implements DPoPSigner { return DPoPKeyPair(privateKey: privateKey, publicKey: publicKey); } + /// Restores a key pair from a private JWK, the form + /// [RFC 7518 §6.2.2](https://www.rfc-editor.org/rfc/rfc7518#section-6.2.2) + /// gives an EC private key. + /// + /// This is what `crypto.subtle.exportKey('jwk', …)` produces in a browser, + /// what a JOSE library in another language hands you, and the easier of the + /// two shapes to keep in storage that holds JSON. The counterpart to + /// persisting [privateJwk]; [fromPrivateKeyPem] is the same thing for a PEM. + /// + /// Only `kty`, `crv`, `d`, `x` and `y` are read. Anything else a key export + /// carries — `ext`, `key_ops`, `kid`, `use`, `alg` — is ignored, so an + /// exported WebCrypto key can be passed through as it arrives. + /// + /// `x` and `y` are optional, since the public half is derived from `d` + /// either way. When they are there they are **checked**: a JWK whose + /// coordinates do not belong to its `d` is refused rather than used to + /// publish a key that cannot verify its own signatures. + /// + /// Throws a [FormatException] if [jwk] is not a readable P-256 private key + /// — a missing or unparseable `d`, a scalar out of range, another curve — + /// and an [ArgumentError] if `x` or `y` contradicts `d`. + factory DPoPKeyPair.fromPrivateJwk(Map jwk) { + final String kty = _member(jwk, 'kty') ?? ''; + final String crv = _member(jwk, 'crv') ?? ''; + if (kty != 'EC' || crv != 'P-256') { + throw FormatException( + 'JWK is kty "$kty", crv "$crv"; this package signs DPoP proofs with ' + 'ES256 over P-256 only.', + ); + } + + final String? d = _member(jwk, 'd'); + if (d == null || d.isEmpty) { + throw const FormatException( + 'JWK carries no "d" member, so it is a public key. Pass the private ' + 'half, or use dpopThumbprint for a public one.', + ); + } + + final ECDomainParameters parameters = p256(); + final BigInt scalar = _os2ipBase64Url(d, 'd'); + if (scalar == BigInt.zero || scalar >= parameters.n) { + throw const FormatException( + 'JWK "d" is out of range for P-256; it must be a scalar in [1, n).', + ); + } + + // The generator times a scalar in [1, n) is never the point at + // infinity, so the null `pointycastle` allows for cannot arrive. + final ECPoint derived = (parameters.G * scalar)!; + final String? x = _member(jwk, 'x'); + final String? y = _member(jwk, 'y'); + if (x != null && y != null) { + final bool matches = + _os2ipBase64Url(x, 'x') == derived.x!.toBigInteger() && + _os2ipBase64Url(y, 'y') == derived.y!.toBigInteger(); + if (!matches) { + throw ArgumentError.value( + ['x', 'y'], + 'jwk', + 'coordinates do not belong to the private scalar "d". Proofs signed ' + 'with this pair would publish a key that cannot verify them.', + ); + } + } + + return DPoPKeyPair( + privateKey: ECPrivateKey(scalar, parameters), + publicKey: ECPublicKey(derived, parameters), + ); + } + + /// A JWK member as a string, or `null` when it is absent. + /// + /// Throws a [FormatException] for a member that is present but not a + /// string, which is what a JWK decoded from JSON with the wrong shape + /// gives — a number for `kty`, a nested object for `d`. + static String? _member(Map jwk, String name) { + final Object? value = jwk[name]; + if (value == null) { + return null; + } + if (value is! String) { + throw FormatException('JWK member "$name" is not a string.'); + } + return value; + } + + /// A base64url JWK field as the integer it encodes. + /// + /// JOSE writes these fixed-width — 32 octets on P-256 — and this package + /// does too, but a shorter one from a minimal-length encoder is read all + /// the same. Padding is optional, as it is throughout JOSE. + static BigInt _os2ipBase64Url(String value, String name) { + final Uint8List octets; + try { + octets = base64Url.decode(base64Url.normalize(value)); + } on FormatException catch (error) { + throw FormatException( + 'JWK member "$name" is not base64url: ' + '${error.message}', + ); + } + if (octets.isEmpty || octets.length > p256FieldBytes) { + throw FormatException( + 'JWK member "$name" is ${octets.length} octets; a P-256 field element ' + 'is at most $p256FieldBytes.', + ); + } + return os2ip(octets); + } + /// The signing half. Never leaves the device. final ECPrivateKey privateKey; @@ -126,6 +238,27 @@ class DPoPKeyPair implements DPoPSigner { /// by every proof this key signs. late final Map jwk = _buildJwk(); + /// The **whole key pair** as a JWK, private scalar included — the form + /// RFC 7518 §6.2.2 gives an EC private key, and the counterpart to + /// [fromPrivateJwk]. + /// + /// This is [jwk] plus `d`, so it is a drop-in for storage that holds JSON + /// rather than PEM, and it imports straight into `crypto.subtle.importKey` + /// or a JOSE library elsewhere. Like [privateKeyPem], it belongs in the + /// platform keystore and nowhere else: never log it, never put it in a + /// header, and never hand it to [dpopThumbprint], which refuses a JWK + /// carrying `d` precisely because a private key reaching that code is a + /// sign something upstream went wrong. + /// + /// [jwk] — no `d` — is the one that is safe to publish, and the one every + /// proof carries. + late final Map privateJwk = Map.unmodifiable( + { + ...jwk, + 'd': base64UrlUnpadded(i2osp(privateKey.d!, p256FieldBytes)), + }, + ); + /// The public key's JWK as a compact JSON string. /// /// Some gateways want the JWK in a header of its own alongside the proof, diff --git a/test/dpop_key_pair_jwk_test.dart b/test/dpop_key_pair_jwk_test.dart new file mode 100644 index 0000000..06700e9 --- /dev/null +++ b/test/dpop_key_pair_jwk_test.dart @@ -0,0 +1,225 @@ +import 'dart:convert'; + +import 'package:dpop_client/dpop_client.dart'; +import 'package:test/test.dart'; + +import 'golden_key.dart'; + +/// The golden fixture's private JWK, the shape `crypto.subtle.exportKey` +/// hands back — extra members and all. +Map webCryptoExport(DPoPKeyPair pair) => { + 'crv': 'P-256', + 'd': pair.privateJwk['d'], + 'ext': true, + 'key_ops': ['sign'], + 'kty': 'EC', + 'x': pair.jwk['x'], + 'y': pair.jwk['y'], +}; + +void main() { + final DPoPKeyPair golden = DPoPKeyPair.fromPrivateKeyPem(goldenPrivateKeyPem); + + group('privateJwk', () { + test('is the public JWK plus the private scalar', () { + expect(golden.privateJwk, { + ...golden.jwk, + 'd': golden.privateJwk['d']!, + }); + expect(golden.privateJwk['x'], goldenX); + expect(golden.privateJwk['y'], goldenY); + }); + + test('writes d fixed-width, as RFC 7518 requires', () { + // 32 octets, unpadded base64url: no `=`, and never the shorter + // minimal-length encoding a leading zero byte would give. + final String d = golden.privateJwk['d']!; + expect(base64Url.decode(base64Url.normalize(d)), hasLength(32)); + expect(d, isNot(contains('='))); + }); + + test('is unmodifiable, since it is derived state', () { + expect(() => golden.privateJwk['d'] = 'tampered', throwsUnsupportedError); + }); + + test('is not accepted by dpopThumbprint', () { + // The guard that says a private key has reached code that only ever + // wanted the public half. + expect( + () => dpopThumbprint(golden.privateJwk), + throwsA(isA()), + ); + }); + }); + + group('fromPrivateJwk', () { + test('round-trips a generated key', () { + final DPoPKeyPair original = DPoPKeyPair.generate(); + + final DPoPKeyPair restored = DPoPKeyPair.fromPrivateJwk( + original.privateJwk, + ); + + expect(restored.thumbprint, original.thumbprint); + expect(restored.privateKeyPem, original.privateKeyPem); + expect(restored.publicKeyPem, original.publicKeyPem); + expect(restored.jwk, original.jwk); + }); + + test('round-trips through JSON, which is the point of it', () { + final String stored = jsonEncode(golden.privateJwk); + + final DPoPKeyPair restored = DPoPKeyPair.fromPrivateJwk( + jsonDecode(stored) as Map, + ); + + expect(restored.thumbprint, goldenThumbprint); + }); + + test('agrees with the PEM the same key came from', () { + final DPoPKeyPair fromJwk = DPoPKeyPair.fromPrivateJwk(golden.privateJwk); + + expect(fromJwk.privateKeyPem, goldenPrivateKeyPem); + expect(fromJwk.publicKeyPem, goldenPublicKeyPem); + }); + + test('signs the proofs the PEM-loaded key signs', () { + final DPoPKeyPair fromJwk = DPoPKeyPair.fromPrivateJwk(golden.privateJwk); + final Uri url = Uri.parse('https://api.example.com/v1/orders'); + final DateTime issuedAt = DateTime.utc(2026, 11, 29, 12); + + String proofOf(DPoPKeyPair pair) => DPoPClient(pair) + .createProof( + url: url, + method: 'POST', + accessToken: 'a.token', + issuedAt: issuedAt, + jwtId: 'fixed-jti', + ) + .token; + + expect(proofOf(fromJwk), proofOf(golden)); + }); + + test('takes a WebCrypto export as it arrives', () { + final DPoPKeyPair restored = DPoPKeyPair.fromPrivateJwk( + webCryptoExport(golden), + ); + + expect(restored.thumbprint, goldenThumbprint); + }); + + test('derives the public half when x and y are absent', () { + final DPoPKeyPair restored = DPoPKeyPair.fromPrivateJwk({ + 'kty': 'EC', + 'crv': 'P-256', + 'd': golden.privateJwk['d'], + }); + + expect(restored.jwk['x'], goldenX); + expect(restored.jwk['y'], goldenY); + }); + + test('reads a d written minimal-length rather than fixed-width', () { + // One scalar in 256 has a leading zero octet, and an encoder that + // trims it produces 31 octets. Strictly non-conformant, read anyway. + final DPoPKeyPair pair = DPoPKeyPair.fromPrivateJwk({ + 'kty': 'EC', + 'crv': 'P-256', + 'd': base64Url.encode([1, 2, 3]).replaceAll('=', ''), + }); + + expect(pair.privateKey.d, BigInt.from(0x010203)); + }); + + test('refuses a JWK with no d, which is a public key', () { + expect( + () => DPoPKeyPair.fromPrivateJwk(golden.jwk), + throwsA( + isA().having( + (FormatException e) => e.message, + 'message', + contains('public key'), + ), + ), + ); + }); + + test('refuses another curve', () { + expect( + () => DPoPKeyPair.fromPrivateJwk({ + 'kty': 'EC', + 'crv': 'P-384', + 'd': golden.privateJwk['d'], + }), + throwsFormatException, + ); + }); + + test('refuses another key type', () { + expect( + () => DPoPKeyPair.fromPrivateJwk({ + 'kty': 'OKP', + 'crv': 'Ed25519', + 'd': golden.privateJwk['d'], + }), + throwsFormatException, + ); + }); + + test('refuses a d that is not base64url', () { + expect( + () => DPoPKeyPair.fromPrivateJwk({ + 'kty': 'EC', + 'crv': 'P-256', + 'd': 'not base64!', + }), + throwsFormatException, + ); + }); + + test('refuses a d wider than the curve', () { + expect( + () => DPoPKeyPair.fromPrivateJwk({ + 'kty': 'EC', + 'crv': 'P-256', + 'd': base64Url.encode(List.filled(33, 7)).replaceAll('=', ''), + }), + throwsFormatException, + ); + }); + + test('refuses a zero scalar', () { + expect( + () => DPoPKeyPair.fromPrivateJwk({ + 'kty': 'EC', + 'crv': 'P-256', + 'd': base64Url.encode(List.filled(32, 0)).replaceAll('=', ''), + }), + throwsFormatException, + ); + }); + + test('refuses a member that is not a string', () { + expect( + () => DPoPKeyPair.fromPrivateJwk({ + 'kty': 'EC', + 'crv': 'P-256', + 'd': {'nested': 'object'}, + }), + throwsFormatException, + ); + }); + + test('refuses coordinates that do not belong to d', () { + final Map tampered = Map.of( + golden.privateJwk, + )..['x'] = DPoPKeyPair.generate().jwk['x']!; + + expect( + () => DPoPKeyPair.fromPrivateJwk(tampered), + throwsA(isA()), + ); + }); + }); +} From 463dbf76b12769e1b403991bd3efcd3a3ffe785a Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Sun, 29 Nov 2026 16:23:33 +0330 Subject: [PATCH 6/7] feat: publish a live demo to GitHub Pages MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit example/web is the package compiled with dart compile js: generate a key or paste your own, as a PEM or a JWK, sign a proof for a request you describe, and read the claims a server would check. Nothing is mocked and no key or token leaves the browser. Only the crypto is Dart — the page does its own DOM work in plain JavaScript, so the demo needs no web framework and the Dart file stays down to the calls worth demonstrating. main.dart.js is built, not committed. The workflow is local rather than shared from ci-workflows the way the Flutter one is: this is a pure Dart package, so the build is dart compile js rather than flutter build web, and it is three lines. Settings > Pages > Source has to be set to "GitHub Actions" before the first deploy. The command-line example picks up the nonce store and the JWK round-trip alongside it. --- .github/workflows/pages.yml | 59 ++++++++ .gitignore | 3 + example/dpop_client_example.dart | 39 ++++- example/web/README.md | 28 ++++ example/web/index.html | 239 +++++++++++++++++++++++++++++++ example/web/main.dart | 119 +++++++++++++++ 6 files changed, 480 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/pages.yml create mode 100644 example/web/README.md create mode 100644 example/web/index.html create mode 100644 example/web/main.dart diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..0cd036d --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,59 @@ +# Publishes the demo in example/web to +# https://ctrlaltdevelop.github.io/dpop_client/ when a pull request is merged +# into main. Repo Settings → Pages → Source must be "GitHub Actions". +# +# The job is not shared from CtrlAltDevelop/ci-workflows the way the Flutter +# one is: this is a pure Dart package, so the demo is `dart compile js` rather +# than `flutter build web`, and it is three lines. Move it there if a second +# package needs the same. + +name: Pages + +on: + push: + branches: [main] + +concurrency: + group: pages + cancel-in-progress: true + +permissions: {} + +jobs: + build: + name: Compile the demo + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v7 + + - uses: dart-lang/setup-dart@v1 + + - name: Install dependencies + run: dart pub get + + - name: Compile + # Paths in index.html are relative, so the site needs no base href. + run: >- + dart compile js -O2 + -o example/web/main.dart.js + example/web/main.dart + + - uses: actions/upload-pages-artifact@v3 + with: + path: example/web + + deploy: + name: Deploy to GitHub Pages + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 725bd3f..e37dec9 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,6 @@ example/pubspec.lock .flutter-plugins-dependencies /build/ /coverage/ + +# The demo compiled for GitHub Pages; built in CI, never committed. +example/web/main.dart.js* diff --git a/example/dpop_client_example.dart b/example/dpop_client_example.dart index 0f14a99..f558cf3 100644 --- a/example/dpop_client_example.dart +++ b/example/dpop_client_example.dart @@ -17,15 +17,28 @@ void main() { final stored = keyPair.privateKeyPem; // 2. On a later launch: restore it. The public half is derived, so the one - // PEM is all that has to be kept. + // string is all that has to be kept. Storage that holds JSON rather + // than PEM can keep `privateJwk` instead and restore it with + // `DPoPKeyPair.fromPrivateJwk` — the same key either way. final restored = DPoPKeyPair.fromPrivateKeyPem(stored); + final viaJwk = DPoPKeyPair.fromPrivateJwk( + jsonDecode(jsonEncode(keyPair.privateJwk)) as Map, + ); + print( + 'PEM and JWK restore the same key: ' + '${viaJwk.thumbprint == restored.thumbprint}', + ); print( 'thumbprint survives a restore: ' '${restored.thumbprint == keyPair.thumbprint}', ); print('jkt to expect in the token\'s cnf claim: ${restored.thumbprint}'); - final client = DPoPClient(restored); + // A nonce store keeps the most recent `DPoP-Nonce` each server issued, so + // no call site has to remember one. Optional: leave it out and pass + // `nonce:` yourself. + final nonces = DPoPNonceStore(); + final client = DPoPClient(restored, nonces: nonces); // 3. The token request, before any access token exists — no `ath`. final tokenProof = client.createProof( @@ -48,15 +61,27 @@ void main() { print('htu has no query: ${!(claims['htu'] as String).contains('?')}'); // 5. The server answers 401 with `error="use_dpop_nonce"` and a - // `DPoP-Nonce` header. Retry the same request carrying that nonce, and - // keep using it until the server issues another. + // `DPoP-Nonce` header. Hand the response headers to the store: it + // returns true only for a nonce it had not already tried, which is the + // signal to retry once rather than forever. + final url = Uri.parse('https://api.example.com/v1/orders?limit=20&lang=en'); + final worthRetrying = nonces.update(url, { + 'DPoP-Nonce': 'eyJ7S_zG.eyJIOjki.hSfMzSHA', + 'content-type': 'application/json', + }); + print('\nnonce is new, so retry once: $worthRetrying'); + + // The retry needs no `nonce:` argument — the client reads the store. final retried = client.createProof( - url: Uri.parse('https://api.example.com/v1/orders?limit=20&lang=en'), + url: url, method: 'POST', accessToken: accessToken, - nonce: 'eyJ7S_zG.eyJIOjki.hSfMzSHA', ); - print('\nretry w/ nonce -> ${decode(retried.token.split('.')[1])}'); + print('retry w/ nonce -> ${decode(retried.token.split('.')[1])}'); + print( + 'same nonce again is nothing new: ' + '${nonces.update(url, const {'DPoP-Nonce': 'eyJ7S_zG.eyJIOjki.hSfMzSHA'})}', + ); print('\nheaders to send:'); // 6. Attaching it to a request. When the proof was built with an access diff --git a/example/web/README.md b/example/web/README.md new file mode 100644 index 0000000..b906e2b --- /dev/null +++ b/example/web/README.md @@ -0,0 +1,28 @@ +# The dpop_client demo + +The page behind +[ctrlaltdevelop.github.io/dpop_client](https://ctrlaltdevelop.github.io/dpop_client/): +generate a key, sign a proof for a request you describe, and read the claims +a server would check. It is the package itself compiled with +`dart compile js` — nothing is mocked, and no key or token leaves the browser. + +Run it locally from the repository root: + +```bash +dart compile js -O2 -o example/web/main.dart.js example/web/main.dart +``` + +```bash +python3 -m http.server --directory example/web 8000 +``` + +Then open . Any static file server will do; the page +is three files and talks to nothing. + +`main.dart.js` is built, not committed; `.github/workflows/pages.yml` runs the +same command on every merge into `main`. + +`main.dart` holds only the calls worth showing — `DPoPKeyPair.generate`, +`DPoPClient.createProof`, `DPoPNonceStore.update` — and hands them to the page +as three JavaScript functions. The DOM work stays in `index.html`, so the demo +needs no web framework. diff --git a/example/web/index.html b/example/web/index.html new file mode 100644 index 0000000..e458a5e --- /dev/null +++ b/example/web/index.html @@ -0,0 +1,239 @@ + + + + + +dpop_client — DPoP proofs for Dart + + + + + +
+

dpop_client

+

+ DPoP proof JWTs for Dart, as specified by + RFC 9449. Everything + below runs in your browser, compiled from the package itself with + dart compile js — no key and no token leaves this page. +

+

+ pub package + Source on GitHub +

+ +

1. The key

+

+ Generated once per installation and persisted as a PEM or a JWK, whichever + your storage prefers. The public half is derived from the private scalar, + so only the one private string has to be kept. +

+
+ + loading the package… +
+ + +

+ The same key as a private JWK, which is what + crypto.subtle.exportKey('jwk', …) gives and what storage + holding JSON wants. Paste either form above: +

+
—
+

Thumbprint (jkt), the value an authorization server binds a token to:

+
—
+ +

2. The request

+
+
+ + +
+
+ + +
+
+
+
+ + +
+
+
+
+ + +
+ +
+

The store holds one nonce per origin; the client adds it to every proof for that origin.

+ +
+ + +
+

+ That timing is dart compile js arithmetic on + BigInt, which the browser runs an order of magnitude slower + than the Dart VM — the same proof takes well under a millisecond on a + server or in a Flutter app. On the web, keep the key in WebCrypto and sign + through a DPoPSigner instead: it is both faster and + unextractable. +

+ +

3. The proof

+

JWT header — the public key travels with every proof:

+ +

Claims — note that htu has lost the query string, as §4.2 requires:

+
—
+

Headers to add to the request — the token goes under the DPoP scheme, not Bearer:

+
—
+

The signed token:

+
—
+ +
+

+ dart pub add dpop_client · + API docs · + AGPL-3.0-only +

+
+
+ + + + + diff --git a/example/web/main.dart b/example/web/main.dart new file mode 100644 index 0000000..0385cc4 --- /dev/null +++ b/example/web/main.dart @@ -0,0 +1,119 @@ +// The demo at https://ctrlaltdevelop.github.io/dpop_client/, compiled with +// `dart compile js`. The package is pure Dart, so the browser runs the same +// code a server or a Flutter app would. +// +// Only the crypto lives here. The page does its own DOM work in plain +// JavaScript, which keeps this file to the three calls worth demonstrating +// and the demo free of a web UI framework. +import 'dart:convert'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:dpop_client/dpop_client.dart'; + +/// Nonces the "server" has issued, so the demo shows the store working the +/// way a real client would hold one for a session. +final DPoPNonceStore nonces = DPoPNonceStore(); + +/// The last PEM read, and the pair built from it. A real client holds its key +/// pair for the session; re-reading the PEM per proof would both waste a +/// scalar multiplication and make the timing shown below a lie. +String? _cachedPem; +DPoPKeyPair? _cachedPair; + +DPoPKeyPair _keyPairFor(String stored) { + final DPoPKeyPair? cached = _cachedPair; + if (cached != null && _cachedPem == stored) { + return cached; + } + // Both storage forms, told apart the way any caller would: JSON starts + // with a brace, a PEM does not. + final String text = stored.trim(); + final DPoPKeyPair pair = text.startsWith('{') + ? DPoPKeyPair.fromPrivateJwk(jsonDecode(text) as Map) + : DPoPKeyPair.fromPrivateKeyPem(text); + _cachedPem = stored; + _cachedPair = pair; + return pair; +} + +void main() { + globalContext + ..setProperty('dpopGenerateKey'.toJS, _generateKey.toJS) + ..setProperty('dpopCreateProof'.toJS, _createProof.toJS) + ..setProperty('dpopIssueNonce'.toJS, _issueNonce.toJS) + ..setProperty('dpopReady'.toJS, true.toJS); + // The page waits for this, so it cannot offer buttons that do nothing + // while the script is still loading. + globalContext.callMethod('dpopOnReady'.toJS); +} + +/// A fresh P-256 pair, as `DPoPKeyPair.generate()` makes it. +String _generateKey() { + final DPoPKeyPair pair = DPoPKeyPair.generate(); + return jsonEncode({ + 'privateKeyPem': pair.privateKeyPem, + 'publicKeyPem': pair.publicKeyPem, + 'jwk': pair.jwk, + 'privateJwk': pair.privateJwk, + 'thumbprint': pair.thumbprint, + }); +} + +/// Signs one proof and reports what a server would read out of it. +/// +/// Returns `{"error": …}` for anything the package refuses — an unreadable +/// PEM, a relative URL — so the page can show the message rather than a +/// stack trace in the console. +String _createProof( + String privateKeyPem, + String url, + String method, + String accessToken, +) { + try { + final DPoPClient client = DPoPClient( + _keyPairFor(privateKeyPem), + nonces: nonces, + ); + final Stopwatch elapsed = Stopwatch()..start(); + final DPoPProof proof = client.createProof( + url: Uri.parse(url), + method: method, + accessToken: accessToken.isEmpty ? null : accessToken, + ); + elapsed.stop(); + return jsonEncode({ + 'token': proof.token, + 'header': _segment(proof.token, 0), + 'payload': _segment(proof.token, 1), + 'headers': proof.headers(), + 'thumbprint': proof.thumbprint, + 'isTokenBound': proof.isTokenBound, + 'microseconds': elapsed.elapsedMicroseconds, + }); + } on ArgumentError catch (error) { + return jsonEncode({'error': error.message.toString()}); + } on FormatException catch (error) { + return jsonEncode({'error': error.message}); + } on StateError catch (error) { + return jsonEncode({'error': error.message}); + } +} + +/// Plays the server's part: issues a nonce for [url]'s origin, the way a +/// `401` with `error="use_dpop_nonce"` would. +String _issueNonce(String url, String nonce) { + final bool isNew = nonces.update(Uri.parse(url), { + 'DPoP-Nonce': nonce, + }); + return jsonEncode({ + 'isNew': isNew, + 'nonce': nonces.nonceFor(Uri.parse(url)), + }); +} + +/// A JWT segment, decoded the way a server reads it before verifying. +Object? _segment(String token, int index) => jsonDecode( + utf8.decode(base64Url.decode(base64Url.normalize(token.split('.')[index]))), +); From 82d55c4763e5d9e3d339ceeaa2861917c57d8146 Mon Sep 17 00:00:00 2001 From: Mohammad Zarif Date: Sun, 29 Nov 2026 16:23:33 +0330 Subject: [PATCH 7/7] docs: release 2.4.0 The nonce store, JWK key storage and the faster signing, with the README gaining a Speed section that gives the numbers and says plainly which case got slower: a process that signs one proof and exits now pays ~15 ms to build the comb table. The licence badge and footer settle here too, with the relicensing commit that could not carry them. --- CHANGELOG.md | 75 +++++++++++++++++++++++++++ README.md | 140 +++++++++++++++++++++++++++++++++++++++++++-------- pubspec.yaml | 6 +-- 3 files changed, 198 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 42c2d59..a28ecb6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,78 @@ +## 2.4.0 + +### Added + +- **`DPoPNonceStore`** remembers the most recent `DPoP-Nonce` each server + issued, keyed by origin, and `DPoPClient(keyPair, nonces: store)` — or + `DPoPSignerClient(signer, nonces: store)` — puts it in every proof without + the call site passing it. `store.update(url, response.headers)` reads the + header off any response, case-insensitively, and returns `true` only when + the nonce is one this store had not already tried, which is exactly the + condition for retrying a `use_dpop_nonce` rejection and the guard against + retrying forever. An explicit `nonce:` still wins. `forget(url)` drops one + origin, `clear()` the lot. +- **`DPoPKeyPair.fromPrivateJwk` and `privateJwk`** store and restore a key as + a JWK (RFC 7518 §6.2.2) rather than a PEM — the shape + `crypto.subtle.exportKey('jwk', …)` gives, a JOSE library in another + language hands you, and storage that holds JSON wants. `privateJwk` is the + public `jwk` plus `d`, so the two forms are the same key; `fromPrivateJwk` + reads only `kty`, `crv`, `d`, `x` and `y`, so a WebCrypto export can be + passed through with its `ext` and `key_ops` still on it. + + `x` and `y` are optional, since the public half is derived from `d`, and + **checked** when present: a JWK whose coordinates do not belong to its `d` + is refused rather than used to publish a key that cannot verify its own + signatures. A JWK that is not a readable P-256 private key — no `d`, + another curve, a scalar out of range — throws a `FormatException`, as the + PEM constructors do. +- **A live demo**, built from the package with `dart compile js` and published + to [ctrlaltdevelop.github.io/dpop_client](https://ctrlaltdevelop.github.io/dpop_client/): + generate a key — or paste your own, as a PEM or a JWK — sign a proof for a + request you describe, and read the claims a server would check. The source + is in `example/web`, and no key or token leaves the browser. + +### Changed + +- **Proofs are signed about eleven times faster: ~0.23 ms on the Dart VM, + down from ~2.8 ms.** Two changes, neither of which alters a signature: + + `pointycastle` holds curve points in affine coordinates, so every addition + and doubling divides — one modular inverse each, the most expensive + operation in the field, some 340 of them for a single `k * G`. The + generator now multiplies in Jacobian coordinates, deferring the division to + a single inverse at the end. And because the generator never changes, its + multiples are precomputed into a Lim–Lee comb of eight blocks, so `k * G` + costs 32 doublings and 32 additions rather than 256 of one and 64 of the + other. `DPoPKeyPair.generate` and `fromPrivateKeyPem` multiply too, and got + the same. + + The 255-entry table is built on the first signature — about 15 ms, once, + and roughly 35 KB held for the life of the process, so a process that signs + a single proof and exits is slower than it was. The entries are converted + to affine form a layer at a time with Montgomery's trick, nine modular + inverses rather than 255, which is what keeps that build from costing more + than the first forty signatures. + + `ECDSASigner` still derives `k` (RFC 6979) and computes `r` and `s`: the + only borrowed work is the multiplication, and the tests check it against + pointycastle's own result for 250 random scalars, for every single-bit + scalar in all 256 positions, at the comb's row boundaries and on the curve + equation itself. Signatures are byte-for-byte what they were. +- The P-256 domain parameters are built once per process instead of per call. + `ECCurve_prime256v1()` decompresses the generator each time it is + constructed, which `isP256` alone was paying for twice per key. + +### Notes + +- Nothing in this release changes a proof's bytes, and nothing is removed. + `DPoPClient(keyPair)` with no store behaves exactly as before. +- A scalar wider than 256 bits is reduced modulo the group order rather than + refused. `G` has order `n`, so it is the same point pointycastle returns. +- Like `pointycastle` — and like Dart's `BigInt` underneath it — the faster + multiplication is not constant-time. That is the exposure the package + already had, and it is why a key that must resist a local side-channel + attacker belongs in a keystore behind a `DPoPSigner`. + ## 2.3.0 ### Added diff --git a/README.md b/README.md index ece3e8a..a36ca10 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,19 @@ [![pub package](https://img.shields.io/pub/v/dpop_client.svg)](https://pub.dev/packages/dpop_client) [![pub points](https://img.shields.io/pub/points/dpop_client)](https://pub.dev/packages/dpop_client/score) [![CI](https://github.com/CtrlAltDevelop/dpop_client/actions/workflows/ci.yml/badge.svg)](https://github.com/CtrlAltDevelop/dpop_client/actions/workflows/ci.yml) -[![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/CtrlAltDevelop/dpop_client/blob/main/LICENSE) +[![license: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](https://github.com/CtrlAltDevelop/dpop_client/blob/main/LICENSE) +[![Dart](https://img.shields.io/badge/Dart-%5E3.12-0175C2.svg?logo=dart)](https://dart.dev) +[![last commit](https://img.shields.io/github/last-commit/CtrlAltDevelop/dpop_client.svg)](https://github.com/CtrlAltDevelop/dpop_client/commits) +[![live demo](https://img.shields.io/badge/demo-live-brightgreen)](https://ctrlaltdevelop.github.io/dpop_client/) DPoP proof JWTs for Dart, as specified by [RFC 9449](https://www.rfc-editor.org/rfc/rfc9449) — ES256 key handling, PEM -storage, JWK thumbprints, access-token binding and server-supplied nonces. +and JWK storage, JWK thumbprints, access-token binding and server-supplied +nonces. -Pure Dart, so it works in Flutter apps, server code and CLIs alike. +Pure Dart, so it works in Flutter apps, server code and CLIs alike. Try it in +the browser at +[ctrlaltdevelop.github.io/dpop_client](https://ctrlaltdevelop.github.io/dpop_client/). ```dart final keyPair = DPoPKeyPair.generate(); @@ -41,7 +47,7 @@ request with a message that names none of them. This package is those details. ```yaml dependencies: - dpop_client: ">=2.3.0 <3.0.0" + dpop_client: ">=2.4.0 <3.0.0" ``` Requires Dart 3.12.0 or newer, and so any Flutter release shipping that SDK or @@ -69,6 +75,34 @@ Both PEM forms are accepted: the SEC 1 `EC PRIVATE KEY` block this package emits, and the PKCS#8 `PRIVATE KEY` block most other tooling produces. A key on any curve but P-256 is refused outright rather than reinterpreted. +### Or as a JWK + +Storage that holds JSON rather than PEM — and anything that has to interoperate +with WebCrypto or a JOSE library elsewhere — can keep the key as a JWK instead: + +```dart +await storage.write('dpop_key', jsonEncode(keyPair.privateJwk)); + +final keyPair = DPoPKeyPair.fromPrivateJwk( + jsonDecode(await storage.read('dpop_key')) as Map, +); +``` + +`privateJwk` is the public `jwk` plus `d`, so the two forms are +the same key — `fromPrivateJwk` and `fromPrivateKeyPem` give byte-identical +proofs. It is what `crypto.subtle.exportKey('jwk', …)` produces, and +`fromPrivateJwk` reads a WebCrypto export as it arrives: only `kty`, `crv`, +`d`, `x` and `y` are looked at, so `ext` and `key_ops` can stay on it. + +`x` and `y` are optional, since the public half is derived from `d`, and +checked when they are there — a JWK whose coordinates do not belong to its `d` +is refused rather than used to publish a key that cannot verify its own +signatures. + +`privateJwk` carries the private key: it belongs in the keystore with +`privateKeyPem`, never in a log or a header. `jwk` is the publishable one, and +`dpopThumbprint` refuses anything carrying `d` for exactly that reason. + The private key is the client's identity for every token bound to it. Keep it in the platform keystore — `flutter_secure_storage`, the Keychain, the Android keystore — not in plain preferences, and generate a fresh pair on sign-out so @@ -164,26 +198,42 @@ header is produced, matching the absent `ath`. A server that wants a nonce answers `401` with `error="use_dpop_nonce"` and a `DPoP-Nonce` response header. Retry with that value, and keep using the most -recent one the server sent until it issues another: +recent one the server sent until it issues another — which it may do on any +response, including a successful one (RFC 9449 §8). + +`DPoPNonceStore` holds that state. Give one to the client and every proof +carries the right nonce for the server it is going to: ```dart -String? _nonce; // the most recent nonce the server issued +final nonces = DPoPNonceStore(); +final client = DPoPClient(keyPair, nonces: nonces); Future send(Request request) async { - final response = await _send(request, nonce: _nonce); - - final issued = response.headers['dpop-nonce']; - if (issued == null) return response; - - final isNew = issued != _nonce; - _nonce = issued; - - // Retry once, and only against a nonce we had not already tried. - if (response.statusCode == 401 && isNew) return send(request); + final proof = client.createProof(url: request.url, method: request.method); + final response = await _send(request, proof); + + // `update` returns true only for a nonce this store had not already tried, + // which is both the reason to retry and the guard against retrying forever. + if (nonces.update(request.url, response.headers) && + response.statusCode == 401) { + return send(request); + } return response; } ``` +Nonces are kept per **origin** — scheme, host and port — because that is the +granularity the RFC gives them: an authorization server and a resource server +run separate nonce spaces, and offering one server's nonce to another earns a +fresh `401` at best. Header names are matched case-insensitively, so a map +from `dart:io`, `package:http` or a gateway SDK all work. + +Passing `nonce:` to `createProof` still overrides the store, `forget(url)` +drops one origin — worth doing when a server rejects a proof for some *other* +reason — and `clear()` empties it on sign-out. The store is memory only: a +nonce is short-lived and server-issued, so losing the lot on restart costs one +round trip and nothing else. + ### Keys you cannot read `DPoPKeyPair` holds the private key in Dart memory. If your key lives where @@ -267,6 +317,45 @@ empty path.** See above. **The bound token is sent under the `DPoP` scheme.** See above. +## Speed + +A proof costs one ES256 signature, and an ES256 signature costs one scalar +multiplication of the curve's generator. Two things make that cheap here, and +neither changes what a signature is: + +- **Jacobian coordinates.** `pointycastle` holds points in affine form, where + every addition and doubling divides — a modular inverse each, roughly fifty + times the cost of a multiplication, some 340 of them per signature. The + ladder here runs on multiplications and divides once, at the end. +- **A fixed-base comb.** The generator never changes, so its multiples are + precomputed: `k * G` costs 32 doublings and 32 additions rather than 256 and + 64. + +**~0.23 ms per proof on the Dart VM, down from ~2.8 ms** — about eleven times +faster. Key generation and `fromPrivateKeyPem` multiply too, and got the same. + +The table that makes it work is 255 points, built on the first signature: +about 15 ms once, and roughly 35 KB held for the life of the process. A +process that signs a single proof and exits is therefore slower than it was; +everything that stays signed in is far faster. + +`ECDSASigner` still derives `k` (RFC 6979) and computes `r` and `s`; only the +multiplication is this package's, and the tests check it against +pointycastle's own answer for 250 random scalars, for every single-bit scalar +in all 256 positions, at the comb's row boundaries and against the curve +equation. Signatures are byte-for-byte unchanged. + +Two things follow from this. Hold one `DPoPClient` and one `DPoPKeyPair` for +the session — every derived value, from the PEMs to the thumbprint, is +computed once and cached on the key pair. And on the web, where `BigInt` runs +an order of magnitude slower than on the VM, prefer a WebCrypto key behind a +`DPoPSigner`: it is both faster and unextractable. + +Like `pointycastle` — and like Dart's `BigInt` underneath it — none of this is +constant-time. That is the exposure the package always had, and it is the +other reason a key that must resist a local side-channel attacker belongs in a +platform keystore rather than in Dart memory. + ## Verifying a proof This package signs proofs; it does not verify them, because a resource server @@ -279,14 +368,25 @@ the server, not a client library. If you are writing a verifier, note that - ES256 over P-256 only. RFC 9449 permits other algorithms; servers rarely do. A key on another curve is refused, not reinterpreted. -- Signing only. No verification, no nonce cache, no HTTP client. -- No key storage. Persist `privateKeyPem` with whatever your platform offers, or - keep the key in a keystore and sign through a `DPoPSigner`. +- Signing only. No verification, and no HTTP client — `DPoPNonceStore` reads a + header map you hand it and never sends anything itself. +- No key storage. Persist `privateKeyPem` or `privateJwk` with whatever your + platform offers, or keep the key in a keystore and sign through a + `DPoPSigner`. The dependency footprint is deliberately small — `pointycastle` and `asn1lib` for the curve and the PEMs, `dart_jsonwebtoken` for the ES256 signature, `crypto` and `uuid`. Nothing here pulls in an HTTP client or a logger. +## The demo + +[ctrlaltdevelop.github.io/dpop_client](https://ctrlaltdevelop.github.io/dpop_client/) +is this package compiled to JavaScript: generate a key, describe a request, +and read the proof's claims the way a server would. Nothing is mocked and +nothing leaves the browser. Its source is [`example/web`](example/web), and +[`example/dpop_client_example.dart`](example/dpop_client_example.dart) is the +same walk-through on the command line. + ## Upgrading from 1.x `headers()` now also returns the `Authorization` header when the proof carries @@ -320,4 +420,4 @@ import `package:pointycastle/ecc/api.dart` instead of ## License -MIT — see [LICENSE](LICENSE). +AGPL-3.0-only — see [LICENSE](LICENSE). diff --git a/pubspec.yaml b/pubspec.yaml index 7c12d77..65e1ceb 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,8 +1,8 @@ name: dpop_client description: >- - DPoP proof JWTs for Dart (RFC 9449) — ES256 key handling, PEM storage, JWK - thumbprints, access-token binding and server-supplied nonces. -version: 2.3.0 + DPoP proof JWTs for Dart (RFC 9449) — ES256 key handling, PEM and JWK + storage, JWK thumbprints, access-token binding and server-supplied nonces. +version: 2.4.0 homepage: https://github.com/CtrlAltDevelop repository: https://github.com/CtrlAltDevelop/dpop_client issue_tracker: https://github.com/CtrlAltDevelop/dpop_client/issues