From 5eea613d65faed103c15f2b18c22d24bf3196b94 Mon Sep 17 00:00:00 2001 From: Michael Kohler Date: Fri, 20 Nov 2026 10:50:41 +0100 Subject: [PATCH] fix(spec/flows): properly clean up storage on wallet connection failures and other smaller fixes --- specification/flows/section/algorithms.html | 105 ++++++++-- specification/flows/section/session-flow.html | 4 +- specification/flows/section/storage.html | 27 +-- specification/flows/section/wallet-setup.html | 187 ++++++++++++++---- 4 files changed, 250 insertions(+), 73 deletions(-) diff --git a/specification/flows/section/algorithms.html b/specification/flows/section/algorithms.html index 706349df..74837855 100644 --- a/specification/flows/section/algorithms.html +++ b/specification/flows/section/algorithms.html @@ -64,6 +64,9 @@

Wallet address request

+
  • + If |details| is null, return failure. +
  • Return |details|.
  • @@ -173,7 +176,7 @@

    Outgoing payment and quote grant request

  • Perform a [=fetch request=] with |request| and with |processResponseConsumeBody| set to - the following steps, given a [=response=] and |response|'s [=request/body=] |responseBody|: + the following steps, given a [=response=] |response| and |response|'s [=response/body=] |responseBody|:
    1. Let |json| be the result of [=extract the JSON fetch response=] from |response| and |responseBody|. @@ -189,6 +192,12 @@

      Outgoing payment and quote grant request

  • +
  • + If |grant| is null, return failure. +
  • +
  • + Return |grant|. +
  • @@ -335,7 +344,7 @@

    Incoming payment grant request

  • Let |grant| be null.
  • Perform a [=fetch request=] with |request| and with |processResponseConsumeBody| set to the following steps, - given a [=response=] and |response|'s [=request/body=] |responseBody|: + given a [=response=] |response| and |response|'s [=response/body=] |responseBody|:
    1. Let |json| be the result of [=extract the JSON fetch response=] from |response| and |responseBody|. @@ -443,27 +452,70 @@

      Continue grant request

    2. Run the [=generate an HTTP message signature=] algorithm on |request| with |accessToken|.
    3. -
    4. Let |grant| be null.
    5. +
    6. Let |result| be failure.
    7. Perform a [=fetch request=] with |request| and with |processResponseConsumeBody| set to the following steps, given a [=response=] |response| with [=response/body=] |responseBody|:
        +
      1. + If |response| is a [=network error=], its [=response/status=] is `429`, or its [=response/status=] + is in the range 500 to 599, inclusive, set |result| to `"retry"` and abort these steps. +
      2. +
      3. + If |response|'s [=response/status=] is not an [=ok status=]: +
          +
        1. + Let |errorJson| be null. +
        2. +
        3. + If |responseBody| is a [=byte sequence=], set |errorJson| to the result of + [=parse JSON bytes to an infra value=] passing |responseBody|. If this throws an exception, + set |errorJson| to null. +

          + An error response is not necessarily JSON, for example an HTML error page from a proxy. +

          +
        4. +
        5. + If |errorJson| is a [=map=] and either |errorJson|["error"] is the string `"too_fast"`, or + |errorJson|["error"] is a [=map=] whose "code" member is the string `"too_fast"`, + set |result| to `"retry"`. +

          + GNAP allows the error to be either a string code or + an object with a `code` member, such as {"error": {"code": "too_fast"}}. +

          +
        6. +
        7. Abort these steps.
        8. +
        +

        + Any other error response, such as a GNAP error with + code `user_denied`, `request_denied`, `invalid_continuation` or `expired`, leaves |result| as failure. +

        +
      4. Let |json| be the result of [=extract the JSON fetch response=] from |response| and |responseBody|.
      5. - Convert |json| to a {{ PendingGrant }} or {{ Grant }}, |grantResponse|. + If |json| has an `access_token` member, convert |json| to a {{ Grant }}, |grantResponse:Grant|. + Otherwise, convert |json|["continue"] to a {{ Continue }}, |grantResponse:Continue|.

        - The continuation request can return either a {{ PendingGrant }} or a {{ Grant }}. + A finalized grant includes an access token. A grant that is still pending only returns a new + continuation handle, and does not necessarily repeat the {{PendingGrant/interact}} member, so + it is not converted to a {{PendingGrant}}.

      6. - If one of the previous two steps threw an exception, return failure. + If one of the previous two steps threw an exception, abort these steps.
      7. -
      8. Set |grant| to |grantResponse|.
      9. +
      10. Set |result| to |grantResponse|.
    8. -
    9. Return |grant|.
    10. +
    11. + Return |result|. +

      + The result is a {{ Grant }} if the grant was finalized, a {{ Continue }} if the grant is still pending, + `"retry"` if the request failed for a transient reason and can be repeated, or failure otherwise. +

      +
    @@ -472,7 +524,8 @@

    Continue grant request

    Cancel grant request

    The cancel grant request, refers to the Open Payments cancel grant request.

    - When asked to send a cancel grant request, given |continueUri|, |accessToken|, perform the following steps. + When asked to send a cancel grant request, given |continueUri|, |accessToken| and an optional + boolean |notifyUser:boolean| (default true), perform the following steps.
    1. Let |uri| be the result of running [=URL parser=] with |continueUri|. @@ -512,7 +565,8 @@

      Cancel grant request

      Perform a [=fetch request=] with |request|, given a [=response=]:
      1. - If {{"NetworkError"}} is thrown, notify the user that the browser could not cancel the grant. + If {{"NetworkError"}} is thrown and |notifyUser| is true, notify the user that the browser could not + cancel the grant.
      2. If the [=status=] is `204`, the grant was successfully canceled and the storage can be cleared. @@ -677,7 +731,7 @@

        Create incoming payment

      3. Perform a [=fetch request=] with |request| and with |processResponseConsumeBody| set to the following steps, - given a [=response=] and |response|'s [=request/body=] |responseBody|: + given a [=response=] |response| and |response|'s [=response/body=] |responseBody|:
        1. Let |json| be the result of [=extract the JSON fetch response=] from |response| and |responseBody|. @@ -839,24 +893,47 @@

          Helper algorithms

          Fetch request

          To perform a fetch request given a [=request=] |request| and - an algorithm |processResponseConsumeBody|, execute the following steps: + an algorithm |processResponseConsumeBody|, perform the following steps:
            +
          1. + Let |done:boolean| be false. +
          2. [=Queue a global task=] on the [=networking task source=] to [=fetch=] |request| - with [=fetch/processResponseEndOfBody=] set to |processResponseConsumeBody|. + with [=fetch/processResponseConsumeBody=] set to the following steps, given a [=response=] |response| + and null, failure, or a [=byte sequence=] |responseBody|: +
              +
            1. + Run |processResponseConsumeBody| given |response| and |responseBody|. +
            2. +
            3. + Set |done| to true. +
            4. +
            +
          3. +
          4. + Wait until |done| is true.
          +

          + Because this algorithm waits for the response to be processed, the calling algorithm can read any value + set by |processResponseConsumeBody| after this algorithm returns. Callers run [=in parallel=], so waiting + does not block the user interface. Returning from |processResponseConsumeBody| only ends those steps, + not the calling algorithm. +

          Extract JSON from fetch response

          -

          To extract the JSON fetch response a [=response=] response: +

          To extract the JSON fetch response given a [=response=] |response| and + null, failure, or a [=byte sequence=] |responseBody|, perform the following steps:

          1. If |response| is a [=network error=] or its [=status=] is not an [=ok status=], throw a new {{"NetworkError"}}.
          2. +
          3. If |responseBody| is null or failure, throw a new {{"NetworkError"}}.
          4. Let |mimeType| be the result of [=header list/extract a MIME type=] from |response|'s [=header list=].
          5. diff --git a/specification/flows/section/session-flow.html b/specification/flows/section/session-flow.html index 34c53936..f2d16891 100644 --- a/specification/flows/section/session-flow.html +++ b/specification/flows/section/session-flow.html @@ -80,10 +80,10 @@

            Session initiation

            Let |websiteWalletAddress:DOMString| be the value of the {{HTMLLinkElement/href}} of |linkElement|.
          6. - Let |websiteWalletDetails:WalletAddressDetails?| be the result of [=send a wallet address request=] with |websiteWalletAddress|. + Let |websiteWalletDetails:WalletAddressDetails| be the result of [=send a wallet address request=] with |websiteWalletAddress|.
          7. - If |websiteWalletDetails| is null, return. + If |websiteWalletDetails| is failure, return.
          8. Let |authKeys:AuthKeys?| be the result of [=get auth keys=]. diff --git a/specification/flows/section/storage.html b/specification/flows/section/storage.html index f2db64a9..7c812381 100644 --- a/specification/flows/section/storage.html +++ b/specification/flows/section/storage.html @@ -89,12 +89,19 @@

            Storage operations

          -

          To store wallet credentials, given |walletAddressDetails:WalletAddressDetails|:

          +

          To store wallet connection, given |walletAddressDetails:WalletAddressDetails|, |grant:Grant| + and |maxRateOfPay:DOMString|:

          1. Let |storage| be the result of [=get storage=].
          2. Set |storage|'s {{Storage/wallet}} to |walletAddressDetails|.
          3. +
          4. Set |storage|'s {{Storage/grant}} to |grant|.
          5. +
          6. Set |storage|'s {{Storage/maxRateOfPay}} to |maxRateOfPay|.
          7. [=Persist storage=] with |storage|.
          +

          + The wallet, grant and max rate of pay are persisted in a single step so that an interruption cannot leave + a partially stored wallet connection. +

          Each invocation of this algorithm establishes a new wallet connection. Implementations that track per-connection payment history SHOULD associate sessions and payments with @@ -103,24 +110,6 @@

          Storage operations

          -
          -

          To store grant credentials, given |grant:Grant|:

          -
            -
          1. Let |storage| be the result of [=get storage=].
          2. -
          3. Set |storage|'s {{Storage/grant}} to |grant|.
          4. -
          5. [=Persist storage=] with |storage|.
          6. -
          -
          - -
          -

          To store max rate of pay, given |maxRateOfPay:DOMString|:

          -
            -
          1. Let |storage| be the result of [=get storage=].
          2. -
          3. Set |storage|'s {{Storage/maxRateOfPay}} to |maxRateOfPay|.
          4. -
          5. [=Persist storage=] with |storage|.
          6. -
          -
          -

          To update grant access token, given |accessToken:DOMString|:

            diff --git a/specification/flows/section/wallet-setup.html b/specification/flows/section/wallet-setup.html index 064aa74f..12620986 100644 --- a/specification/flows/section/wallet-setup.html +++ b/specification/flows/section/wallet-setup.html @@ -40,32 +40,96 @@

            Connecting a wallet

            (3) a renewal monthly flag.

            -

            For every new wallet connection, the browser MUST generate a fresh key pair by - running the [=generate an Ed25519 key pair=] algorithm, replacing any previously stored key pair, and MUST display - the newly generated [=encoded public key JWK=] (representing the [=Ed25519 public key=]) so the user can copy or - upload it to their wallet provider. This key generation and public key - exposure happen before invoking the algorithm below; if no key pair exists at invocation time, the algorithm fails.

            +

            + Only one wallet can be connected at a time, and a connected wallet is disconnected before a new + wallet connection is started. +

            + +
            +

            When the user starts a new wallet connection from the [=setup page=], the browser MUST run the following + steps to start a wallet connection:

            +
              +
            1. + If the result of the [=get user wallet=] algorithm is not null: +
                +
              1. + Ask the user to explicitly confirm that the connected wallet will be disconnected. If the user does not + confirm, return. +
              2. +
              3. Run the [=disconnect a wallet=] algorithm.
              4. +
              +

              + Disconnecting first means the previous grant is cancelled with its authorization server and the + previous connection's wallet, grant and keys are removed from {{Storage}}. A failed wallet setup therefore + never leaves new state next to an old wallet and grant. The previous {{Storage/maxRateOfPay}} may be + retained (see [=clear wallet data=]) until the new connection is stored. +

              +
            2. +
            3. + If the result of the [=get auth keys=] algorithm is null, run the [=generate an Ed25519 key pair=] algorithm. +

              + After the previous step no wallet is connected, so a key pair that still exists here was kept by an + earlier wallet setup that failed before a grant was requested (see [=abort wallet setup=]). It is reused + so that the user does not have to register a new public key with their wallet provider after, for example, + mistyping their [=wallet address=]. +

              +
            4. +
            5. + Display the [=encoded public key JWK=] (representing the [=Ed25519 public key=]) from the result of the + [=get auth keys=] algorithm, so the user can copy or upload it to their wallet provider. +
            6. +
            7. + When the user submits the [=setup page=] with a [=wallet address=] |walletAddress|, a budget |budget| and + a renewal monthly flag |renewMonthly|, run the [=process the wallet setup=] algorithm with |walletAddress|, + |budget| and |renewMonthly|. +
            8. +
            +
            -

            To process the wallet setup, given a string |walletAddress:DOMString| +

            +

            To abort wallet setup, given an optional |continueUri:DOMString| and an optional + |continueAccessToken:DOMString|:

            +
              +
            1. + If |continueUri| and |continueAccessToken| are not null: +
                +
              1. + Run the [=send a cancel grant request=] algorithm with |continueUri|, |continueAccessToken| and false. +

                + This revokes the pending grant with the authorization server so that the user cannot still approve it + after the wallet setup has failed. If the grant is already gone, for example because the user declined + it, the request fails. The failure is ignored and the user is not notified, because the wallet setup + has already failed. +

                +
              2. +
              3. Run the [=clear wallet data=] algorithm.
              4. +
              +
            2. +
            3. Return failure.
            4. +
            +

            + If the wallet setup fails before a grant is requested, for example because the [=wallet address=] cannot be + resolved, {{Storage}} is left unchanged. The key pair is kept and reused by the next [=start a wallet connection=], + so the public key the user has already registered stays valid. Once a grant was requested, the key pair is + removed together with any other state of the failed wallet setup, and the next wallet connection generates a + new key pair that the user has to register with their wallet provider. +

            +

            + Because any previously connected wallet was disconnected before the wallet setup started, this only removes + state created by the failed wallet setup. +

            +
            + +

            To process the wallet setup, given a string |walletAddress:DOMString| (the [=wallet address=] provided by the user), a number |budget:number| (a spending budget requested from the wallet for outgoing payments, expressed in the wallet asset), and a boolean |renewMonthly:boolean| (whether the budget is renewed monthly by the wallet):

              -
            1. If the result of the [=get auth keys=] algorithm is null, return failure.
            2. -
            3. Let |walletAddressDetails:WalletAddressDetails| be the result of the [=send a wallet address request=] algorithm on |walletAddress|.
            4. -
            5. - Let |assetScale:long| be |walletAddressDetails|'s {{WalletAddressDetails/assetScale}}. -
            6. -
            7. - Let |maxRateOfPay:long long| be Math.round(|budget| * Math.pow(10, |assetScale|)). -

              - This converts the user-entered monthly budget in the wallet asset into a [=scaled amount=] integer. - The resulting value is stored as {{Storage/maxRateOfPay}} and used to compute the payment amount and delay. -

              -
            8. - Run the [=store max rate of pay=] algorithm with |maxRateOfPay| serialized as a string. + If the result of the [=get auth keys=] algorithm is null, return the result of running [=abort wallet setup=].
            9. +
            10. Let |walletAddressDetails:WalletAddressDetails| be the result of the [=send a wallet address request=] algorithm on |walletAddress|.
            11. +
            12. If |walletAddressDetails| is failure, return the result of running [=abort wallet setup=].
            13. Let |interval:DOMString| be an ISO 8601 repeating interval if |renewMonthly| is `true`. @@ -84,18 +148,20 @@

              Connecting a wallet

              Since we ask for access to outgoing payments, the user will have to interact with the grant (approve or decline). Currently in Open Payments, only the grants that request access to outgoing payments are interactive.

            14. +
            15. If |pendingGrant| is failure, return the result of running [=abort wallet setup=].
            16. Let |continueUri:DOMString| be |pendingGrant|'s {{PendingGrant/continue}}.{{Continue/uri}} property at which the client instance can make continuation requests.
            17. - Let |continueAccessToken:DOMString| be |pendingGrant|'s {{PendingGrant/continue}}.{{Continue/access_token}}.{{AccessToken/value}} property. + Let |continueAccessToken:DOMString| be |pendingGrant|'s {{PendingGrant/continue}}.{{Continue/access_token}}.{{ContinueAccessToken/value}} property.
            18. Let |redirectUrl:URL| be the result of [=URL parser|parsing=] |pendingGrant|'s {{PendingGrant/interact}}.{{PendingInteract/redirect}} property ([=Redirect URI=]).
            19. - If |redirectUrl| is failure or |redirectUrl|'s [=url/scheme=] is not `https`, return failure. + If |redirectUrl| is failure or |redirectUrl|'s [=url/scheme=] is not `https`, return the result of running + [=abort wallet setup=] with |continueUri| and |continueAccessToken|.
            20. Run the @@ -108,7 +174,12 @@

              Connecting a wallet

            21. - Let |wait:number| be |pendingGrant|'s {{PendingGrant/continue}}.{{Continue/wait}} property. + Let |baseWait:number| be |pendingGrant|'s {{PendingGrant/continue}}.{{Continue/wait}} property if it exists, + or 5 otherwise. If |baseWait| is less than 1, set |baseWait| to 1. Let |wait:number| be |baseWait|. +

              + 5 seconds is the default polling interval defined by GNAP. The lower bound + keeps the browser from sending continuation requests in a tight loop. +

              We cannot use the {{PendingInteract/finish}} redirect method as browser's internal URLs can not be opened from an external source. In the Open Payments scenario, the [=AS=] will have to redirect the user to the internal browser page for Web Monetization to continue the flow.

              @@ -117,31 +188,70 @@

              Connecting a wallet

              to retrieve information about the grant (whether user accepted or rejected the grant).

            22. -
            23. Let |finalizedGrant| be `null`.
            24. +
            25. Let |finalizedGrant:Grant?| be null.
            26. +
            27. Let |retries:number| be 0.
            28. -

              Start polling to get the information about the grant state every |wait| seconds.

              +

              While |finalizedGrant| is null:

                -
              1. Let |interval:number| be result of |wait| multiplied by 1000, as |wait| is defined in seconds.
              2. +
              3. Wait |wait| seconds.
              4. +
              5. Let |result| be the result of running the [=send a continue grant request=] algorithm given |continueUri| and |continueAccessToken|.
              6. - Let |intervalId| be the result of calling {{ WindowOrWorkerGlobalScope/setInterval() }} with |interval| and the following steps as callback: + If |result| is `"retry"`: +
                  +
                1. Increment |retries| by 1.
                2. +
                3. + If |retries| is greater than an [=implementation-defined=] limit, return the result of running + [=abort wallet setup=] with |continueUri| and |continueAccessToken|. +
                4. +
                5. Increase |wait| by 5.
                6. +
                7. [=iteration/Continue=].
                8. +
                +

                + A network error, a server error or a GNAP `too_fast` error does not end the wallet setup, because the user + may still be approving the grant. The browser backs off and tries again. +

              7. -
              8. Let |grant| be the result of running the [=send a continue grant request=] algorithm given |continueUri| and |continueAccessToken|. +
              9. + If |result| is failure, return the result of running [=abort wallet setup=] with + |continueUri| and |continueAccessToken|. +

                This includes the user declining the grant.

                +
              10. +
              11. Set |retries| to 0.
              12. +
              13. If |result| is a {{Grant}}, set |finalizedGrant| to |result|.
              14. +
              15. + Otherwise, if |result| is a {{Continue}}:
                  -
                1. If |grant| is failure (not an [=ok status=]), call {{ WindowOrWorkerGlobalScope/clearInterval(id)|clearInterval(intervalId) }}.
                2. -
                3. If |grant| is of type {{ PendingGrant }}, continue polling.
                4. -
                5. If |grant| is of type {{ Grant }}, {{ WindowOrWorkerGlobalScope/clearInterval(id)|clearInterval(intervalId) }} and set |finalizedGrant| to |grant|.
                6. +
                7. Set |continueUri| to |result|'s {{Continue/uri}}.
                8. +
                9. Set |continueAccessToken| to |result|'s {{Continue/access_token}}.{{ContinueAccessToken/value}}.
                10. +
                11. If |result|'s {{Continue/wait}} exists, set |baseWait| to the greater of |result|'s {{Continue/wait}} and 1.
                12. +
                13. Set |wait| to |baseWait|.
                +

                + Each continuation response replaces the previous continuation handle, including its URI. Any back-off + from earlier retries is dropped, so polling continues at the interval requested by the + authorization server, or the default interval if it did not request one. +

                +
              16. +
              17. + Otherwise, return the result of running [=abort wallet setup=] with |continueUri| and |continueAccessToken|.
              +

              + The algorithm does not continue until the grant is finalized or the wallet setup is aborted. + Implementations run these steps without blocking the user interface. +

            29. -
            30. If |finalizedGrant| is null: -
                -
              1. Run the [=clear wallet data=] algorithm.
              2. -
              3. Return failure.
              4. -
              +
            31. + Let |assetScale:long| be |walletAddressDetails|'s {{WalletAddressDetails/assetScale}}.
            32. -
            33. Run the [=store wallet credentials=] algorithm with |walletAddressDetails|.
            34. -
            35. Run the [=store grant credentials=] algorithm with |finalizedGrant|.
            36. +
            37. + Let |maxRateOfPay:long long| be Math.round(|budget| * Math.pow(10, |assetScale|)). +

              + This converts the user-entered monthly budget in the wallet asset into a [=scaled amount=] integer. + The resulting value is stored as {{Storage/maxRateOfPay}} and used to compute the payment amount and delay. +

              +
            38. +
            39. Run the [=store wallet connection=] algorithm with |walletAddressDetails|, |finalizedGrant| and |maxRateOfPay| serialized as a string.
          @@ -152,7 +262,7 @@

          Disconnecting a wallet

          Disconnecting a wallet revokes the active grant (if any) and clears state from {{Storage}}.

          -

          To disconnect a wallet:

          +

          To disconnect a wallet:

          1. Let |storage:Storage| be the result of the [=get storage=] algorithm.
          2. If |storage|'s {{Storage/grant}} is not null, then: @@ -171,4 +281,5 @@

            Disconnecting a wallet

            Reconnecting will generate a new key pair requiring re-registration of the public key.

          +