Credential Management Level 1 describes an imperative API enabling a website to request a user’s credentials from a user agent, and to help the user agent correctly store user credentials for future use. User agents implementing that API prompt the user to select a way to handle a credential request, after which the user agent returns a credential to the originating site. This specification defines capabilities that enable third-party Web applications to handle credential requests and storage.

The Credentials Community Group maintains a list of all bug reports that the group has not yet addressed. This draft highlights some of the pending issues that are still to be discussed in the community group. No decision has been taken on the outcome of these issues including whether they are valid. Pull requests with proposed specification text for outstanding issues are strongly encouraged.

Introduction

The mission of the Credentials Community Group is to explore the creation, storage, presentation, verification, and user control of credentials. Its focus is placed on a verifiable credential (a set of claims) created by an issuer about a subject: a person, group, or thing. It seeks solutions inclusive of approaches such as: self-sovereign identity; presentation of proofs by the bearer; data minimization; and centralized, federated, and decentralized registry and identity systems. Therefore, the Credentials Community Group presents a specification that extends the Credential Management Level 1 API to allow users to designate trusted third party Web applications as handlers for credential requests and credential storage.

A credential repository is a Web application that can handle credential requests and credential storage on behalf of the user. This specification defines a number of new Web platform features to handle credential requests and credential storage:

This specification does not address how software built with operating-system specific mechanisms (e.g., "native mobile apps") handle credential requests and credential storage.

This specification defines one class of products:

Conforming user agent

A user agent MUST behave as described in this specification to be considered conformant. In this specification, user agent means a Web browser or other interactive user agent as defined in [[!HTML5]].

User agents MAY implement algorithms given in this specification in any way desired, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms.

A conforming Credential Handler API user agent MUST also be a conforming implementation of the IDL fragments of this specification, as described in the “Web IDL” specification. [[!WEBIDL-LS]]

Overview of Handling Credential Request and Storage

In this document we envision the following flow for a credential request:

  1. An origin requests permission from the user to handle credential request and storage for a set of supported credential types. For example, a user visiting a digital wallet provider site may be prompted to register a credential handler from that origin. The origin establishes the scope of the permission but the origin's capabilities may evolve without requiring additional user consent.
  2. Credential handlers are defined in service worker code.
  3. During service worker registration, the CredentialManager is used to set:
    • A list of enabled WebCredential types.
    • [Optionally] the conditions under which the handler supports a given WebCredential type; these match play a role in matching computations.
    • Information used in the display of hints supported by the credential handler.
  4. There are two entry points for interaction with a credential handler: when a relying party (aka verifier) calls the [[credential-management-1]] method get() (e.g., when the user pushes a button on a page that requires identity attributes or authentication) with WebCredentialRequestOptions and when an issuer calls the [[credential-management-1]] method store() (e.g., when the user pushes a button to receive a credential) with a WebCredential. In both of these cases, the user agent computes a list of candidate credential hints, comparing the WebCredential types accepted by the relying party with those supported by registered credential handlers. For WebCredential types that support additional filtering, the relying party's specific request and the match information from each credential hint is compared as part of determining whether there is compatibility.
  5. The user agent displays a set of choices to the user: the registered hints of the candidate credential handlers. The user agent displays these choices using information (labels and icons) provided at registration or otherwise available from the Web app.
  6. When the user selects a hint, the user agent fires a CredentialRequestEvent (cf. the user interaction task source) or a CredentialStoreEvent (depending on the method called) in the service worker whose CredentialManager the hint was registered with. The CredentialRequestEvent includes the CredentialRequestOptions (defined in [[!credential-management-1]]), including credential-type-specific options, as well as additional information (e.g., origin and selected hint).
  7. Once activated, the credential handler performs whatever steps are necessary to handle the credential request or handle credential storage, and return an appropriate WebCredential to the relying party or issuer. If interaction with the user is necessary, the credential handler can open a context-specific window for that purpose.
  8. The user agent receives a response asynchronously once the credential handler has finished handling the request. The response is a WebCredential or null if the request was denied.

The origin information of the relying party may be blinded when received via a CredentialRequestEvent.

An origin may implement a credential repository with more than one service worker and therefore multiple credential handlers may be registered per origin. The handler that is invoked is determined by the selection made by the user of a credential hint. The service worker which stored the credential hint with its CredentialManager is the one that will be invoked.

Handling a Credential Request

The logic of a credential handler is driven by the WebCredential types that it supports. Some WebCredential types may require very little processing on the part of the credential handler other than retrieving a WebCredential from its storage and returning it as a response.

In contrast, some Web Credential types, such as VerifiableProfile include a custom query parameter that must be understood and processed by the credential handler in order for it to return an appropriate WebCredential in response. This may involve presenting a user interface to allow the user to make selections. In some cases, a credential handler may need to generate a WebCredential dynamically with the assistance of an issuer or blinding service. It may also need to generate a zero knowledge proof or use some other privacy enhancing cryptographic method.

Therefore, handling a credential request may include numerous interactions: with the user through a new contextual window or other APIs (such as [[!WebCryptoAPI]]) or with other services and origins through web requests or other means.

Once a WebCredential is returned to the relying party website, it is its job to perform whatever verification is appropriate for its type.

This specification does not address the activities that occur between the credential handler accepting the CredentialRequestEvent and the credential handler returning a response. All of the activities which may be required to configure the credential handler and handle the credential request are left to the implementation of the credential handler, including:

Thus, an origin will rely on many other Web technologies defined elsewhere for lifecycle management, security, user authentication, user interaction, and so on.

Handling Credential Storage

The logic of a credential handler is driven by the WebCredential types that it supports. Some WebCredential types may require very little processing on the part of the credential handler other than storing the WebCredential in a database and returning it as a response.

In contrast, some Web Credential types, such as VerifiableProfile may include multiple sub-credentials whereby the user may only elect to store some subset of them, through the use of a user interface provided by the credential handler.

Handling credential storage may include numerous interactions: with the user through a new contextual window or other APIs (such as [[!WebCryptoAPI]]) or with other services and origins through web requests or other means.

The WebCredential that is returned to the issuer website provides information on what was stored by the credential handler, enabling the issuer website to take whatever next actions are appropriate.

This specification does not address the activities that occur between the credential handler accepting the CredentialStoreEvent and the credential handler returning a response. All of the activities which may be required to configure the credential handler and handle credential storage are left to the implementation of the credential handler, including:

Thus, an origin will rely on many other Web technologies defined elsewhere for lifecycle management, security, user authentication, user interaction, and so on.

Structure of a Web Credential Repository

Architecture of a (Web) credential repository as defined in this specification.
A Web credential repository is associated with an origin. Credential handlers respond to CredentialRequestEvents and CredentialStoreEvents. CredentialManagers manage the definition, display, and user selection of CredentialHints. A CredentialHint supports one or more WebCredential types.

Relation to Other Types of Credential Repositories

This specification does not address how third-party mobile credential repository apps interact (through proprietary mechanisms) with user agents, or how user agents themselves provide simple credential repository functionality.

Different types of credential repositories. Credential Handler API
          is for Web apps.
Credential Handler API enables Web apps to handle credential management. Other types of credential repository apps may use other (proprietary) mechanisms.

Registration

Extension to the ServiceWorkerRegistration interface

This specification extends the ServiceWorkerRegistration interface with the addition of a credentialManager attribute.

        partial interface ServiceWorkerRegistration {
          readonly attribute CredentialManager credentialManager;
        };
      

CredentialManager interface

      [SecureContext, Exposed=(Window,Worker)]
      interface CredentialManager {
        [SameObject] readonly attribute CredentialHints hints;
        [Exposed=Window] static Promise<PermissionState> requestPermission();
      };
      

The CredentialManager is used by credential repositories to manage their associated hints and supported WebCredential types.

hints attribute

This attribute allows manipulation of credential hints associated with a service worker (and therefore its credential handler). To be a candidate credential handler, a handler must have at least one registered credential hint to present to the user. That instrument needs to match the WebCredential types and type-specific query information specified by the credential request.

requestPermission() method

The user agent is NOT REQUIRED to prompt the user to grant permission to the origin for each new supported WebCredential type or new credential hint.

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. Let permission be the result of running retrieve the permission state algorithm of the permission associated with credential handler's origin.
  4. If permission is "prompt", ask the user whether allowing adding new credential hints for the current settings object's origin is acceptable. If it is, set permission to "granted", and "denied" otherwise.
  5. Resolve p with permission.

CredentialHints interface

      [SecureContext, Exposed=(Window,Worker)]
      interface CredentialHints {
          Promise<boolean>           delete(DOMString hintKey);
          Promise<CredentialHint>    get(DOMString hintKey);
          Promise<sequence<DOMString>>  keys();
          Promise<boolean>           has(DOMString hintKey);
          Promise<void>              set(DOMString hintKey, CredentialHint hint);
          Promise<void>           clear();
      };
      

The CredentialHints interface represents a collection of credential hints, each uniquely identified by a hintKey. The hintKey identifier will be passed to the credential handler to indicate the CredentialHint selected by the user. A CredentialHint is associated with a context or aspect of the user for which they store certain credentials, similar to a digital version of a physical wallet.

delete() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. If the collection contains a CredentialHint with a matching hintKey, remove it from the collection and resolve p with true.
  4. Otherwise, resolve p with false.

get() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. If the collection contains a CredentialHint with a matching hintKey, resolve p with that CredentialHint.
  4. Otherwise, reject p with a DOMException whose value is "NotFoundError".

keys() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. Resolve p with a Sequence that contains all the hintKeys for the CredentialHints contained in the collection, in original insertion order.

has() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. If the collection contains a CredentialHint with a matching hintKey, resolve p with true.
  4. Otherwise, resolve p with false.

set() method

When called, this method executes the following steps:

  1. Let permission be the result of running retrieving the permission state of the permission associated with credential handler's origin.
  2. If permission is not "granted", then return a Promise rejected with a NotAllowedError.
  3. If the icons member of hint is present, then:
    1. Let convertedIcons be the result of running the convert image objects algorithm passing hint.icons as the argument.
    2. If the convertedIcons is an empty Sequence, then return a Promise rejected with a TypeError.
    3. Set hint.icons to convertedIcons.
  4. Let p be a new promise.
  5. Return p and perform the remaining steps in parallel:
  6. If the icons member of hint is present, then for each icon in hint.icons:
    1. If the user agent wants to display the icon, then:
      1. Let fetchedImage be the result of running the fetching image object passing icon as the argument.
      2. Set icon.[[\fetchedImage]] to fetchedImage.
  7. If the collection contains a CredentialHint with a matching hintKey, replace it with the CredentialHint in hint.
  8. Otherwise, insert the CredentialHint in hint as a new member of the collection and associate it with the key hintKey.
  9. Resolve p.

clear() method

When called, this method executes the following steps:

  1. Let p be a new promise.
  2. Return p and perform the remaining steps in parallel:
  3. Remove all CredentialHints from the collection and resolve p.

CredentialHint dictionary

      dictionary CredentialHint {
        required DOMString name;
        sequence<ImageObject> icons;
        sequence<DOMString> enabledTypes;
        object match;
      };
      
name member
The name member is a string that represents the label for this CredentialHint as it is usually displayed to the user.
icons member
The icons member is an array of image objects that can serve as iconic representations of the credential hint when presented to the user for selection.
enabledTypes member
The enabledTypes member is a list of one or more WebCredential types of the WebCredential types supported by this hint.
match member
The match member is a list of WebCredential-type-specific information that, if present in a credential request or credential storage request, must match in order for this credential hint to be considered compatible. For example, for the VerifiableProfile WebCredential type, this object may consist of an object with one field VerifiableProfile that has a value that is another object with one field id with a string value that is an identifier for an entity for which VerifiableProfiles may be constructed or stored.

ImageObject dictionary

      dictionary ImageObject {
          required USVString src;
          DOMString sizes;
          DOMString type;
      };
      
src member
The src member is used to specify the ImageObject's source. It is a URL from which the user agent can fetch the image’s data.
sizes member
The sizes member is used to specify the ImageObject's sizes. It follows the spec of sizes member in HTML link element, which is a string consisting of an unordered set of unique space-separated tokens which are ASCII case-insensitive that represents the dimensions of an image. Each keyword is either an ASCII case-insensitive match for the string "any", or a value that consists of two valid non-negative integers that do not have a leading U+0030 DIGIT ZERO (0) character and that are separated by a single U+0078 LATIN SMALL LETTER X or U+0058 LATIN CAPITAL LETTER X character. The keywords represent icon sizes in raw pixels (as opposed to CSS pixels). When multiple image objects are available, a user agent MAY use the value to decide which icon is most suitable for a display context (and ignore any that are inappropriate). The parsing steps for the sizes member MUST follow the parsing steps for HTML link element sizes attribute.
type member
The type member is used to specify the ImageObject's MIME type. It is a hint as to the media type of the image. The purpose of this member is to allow a user agent to ignore images of media types it does not support.

Convert image objects

When this algorithm with inputImages parameter is invoked, the user agent must run the following steps:

  1. Let outputImages be an empty Sequence of ImageObject.
  2. For each image in inputImages:
    1. If image.type is not a valid MIME type or the value of type is not a supported media format, then return an empty Sequence of ImageObject.
    2. If image.sizes is not a valid value, then return an empty Sequence of ImageObject.
    3. Let url be the result of parsing image.src with the context object's relevant settings object's API base URL.
    4. If url is failure, then return an empty Sequence of ImageObject.
    5. If url's scheme is not "https", then return an empty Sequence of ImageObject.
    6. Set image.src to url.
    7. Append image to outputImages
  3. Return outputImages.

According to the step 2.3, it is also possible to use the relative url for image.src. The following examples illustrate how relative URL resolution works in different execution contexts.

        <-- In this example, code is located in https://www.example.com/wallet/index.html -->
        <script>

        const hintKey = "c8126178-3bba-4d09-8f00-0771bcfd3b11";
        const { registration } = await navigator.serviceWorker.register("/register/sw.js");
        await registration.credentialManager.credentialHints.set({
          hintKey,
          {
            name: "My social account: pat@example.com",
            enabledTypes: ["VerifiableProfile"],
            icons: [{
              src: "icon/lowres.webp",
              sizes: "48x48",
              type: "image/webp"
            }],
            match: {
              VerifiableProfile: {
                id: 'did:method1:1234-1234-1234-1234'
              }
            }
          });

        const { storedHint } =
          await registration.credentialManager.credentialHints.get(hintKey);

        // storedHint.icons[0].src == "https://www.example.com/wallet/icon/lowres.webp";

        </script>
      

        // In this example, code is located in https://www.example.com/register/sw.js

        const hintKey = "c8126178-3bba-4d09-8f00-0771bcfd3b11";
        await self.registration.credentialManager.credentialHints.set({
          hintKey,
          {
            name: "My social account: pat@example.com",
            enabledTypes: ["VerifiableProfile"],
            icons: [{
              src: "../wallet/icon/lowres.webp",
              sizes: "48x48",
              type: "image/webp"
            }],
            match: {
              VerifiableProfile: {
                id: 'did:method1:1234-1234-1234-1234'
              }
            }
          });

        const { storedHint } =
          await registration.credentialManager.credentialHints.get(hintKey);

        // storedHint.icons[0].src == "https://www.example.com/wallet/icon/lowres.webp";
      

Registration Example

The following example shows how to register a credential handler:

        button.addEventListener("click", async() => {
          if (!window.CredentialManager) {
            return; // not supported, so bail out.
          }

          const result = await CredentialManager.requestPermission();
          if (result !== "granted") {
            return;
          }

          const { registration } =
            await navigator.serviceWorker.register('/sw.js');

          // Excellent, we got it! Let's now set up the user's hints.
          await addInstruments(registration);
        }, { once: true });

        function addHints(registration) {
          return Promise.all([
            registration.credentialManager.hints.set(
              "dc2de27a-ca5e-4fbd-883e-b6ded6c69d4f",
              {
                name: "My social account: pat@example.com",
                enabledTypes: ["VerifiableProfile"],
                icons: [{
                  src: "icon/lowres.webp",
                  sizes: "48x48",
                  type: "image/webp"
                }],
                match: {
                  VerifiableProfile: {
                    id: 'did:method1:1234-1234-1234-1234'
                  }
                }
              }),

            registration.credentialManager.hints.set(
              "c8126178-3bba-4d09-8f00-0771bcfd3b11",
              {
                name: "My business account: pat@business.example.com",
                enabledTypes: ["VerifiableProfile"],
                match: {
                  VerifiableProfile: {
                    id: 'did:method1:1234-1234-1234-1235'
                  }
                }
              }),

            registration.credentialManager.hints.set(
              "new-hint",
              {
                name: "Add a new identity",
                enabledTypes: ["VerifiableProfile"]
              }),
            ]);
          };
     

Origin and Hint Display for Selection

TODO: define matching algorithm here

After applying the matching algorithm, the user agent displays the matching credential hints for the user to make a selection. This specification includes a limited number of display requirements; most user experience details are left to implementers.

Ordering of Credential Hints

The following are examples of credential hint ordering:

Display of Hints

The user agent MUST enable the user to select any displayed hint.

Selection of Credential Handlers

Users agents may wish to enable the user to select individual displayed CredentialHints. The credential handler would receive information about the selected hint and could take action, potentially eliminating an extra click (first open the credential repository app then select the hint).

Invocation

Only when a website invokes the get() and passes a WebCredentialRequestOptions or the store() method and passes a WebCredential, will CredentialHints be presented to the user for selection.

Once the user has selected a CredentialHint, the user agent fires a CredentialRequestEvent (or a CredentialStoreEvent if the Credential Management method called was store()) and uses the subsequent WebCredential as a response.

WebCredential interface

      [SecureContext, Exposed=(Window,Worker)]
      interface WebCredential : Credential {
          readonly attribute USVString dataType;
          readonly attribute object data;
      };
      

Extension to ServiceWorkerGlobalScope

This specification extends the ServiceWorkerGlobalScope interface.

        partial interface ServiceWorkerGlobalScope {
          attribute EventHandler oncredentialrequest;
          attribute EventHandler oncredentialstore;
        };
        

oncredentialrequest attribute

The oncredentialrequest attribute is an event handler whose corresponding event handler event type is CredentialRequestEvent.

oncredentialstore attribute

The oncredentialstore attribute is an event handler whose corresponding event handler event type is CredentialStoreEvent.

The CredentialRequestEvent

The CredentialRequestEvent represents the data and methods available to a Credential Handler after selection by the user. The user agent communicates the WebCredentialRequestOptions to the Credential Handler.

        [Constructor(DOMString type, CredentialRequestEventInit eventInitDict), Exposed=ServiceWorker]
        interface CredentialRequestEvent : ExtendableEvent {
          readonly attribute USVString credentialRequestOrigin;
          readonly attribute object credentialRequestOptions;
          readonly attribute DOMString hintKey;
          Promise<WindowClient?> openWindow(USVString url);
          void respondWith(Promise<WebCredential>handlerResponsePromise);
        };
        

credentialRequestOrigin attribute

This attribute is a string that indicates the origin where the [[!credential-managment-1]] method get() was called.

The origin information of the relying party may be blinded when received via a CredentialRequestEvent. It would be blinded to allow it to still be signed without revealing where the request came from. The user agent would be responsible for indicating the origin of the request via its user interface.

credentialRequestOptions attribute

This attribute contains WebCredentialRequestOptions dictionary containing the WebCredential type and type-specific query that describes the credentials requested by the web site.

hintKey attribute

This attribute indicates the CredentialHint selected by the user. It corresponds to the hintKey provided to the CredentialManager.hints interface during registration.

openWindow() method

This method is used by the credential handler to show a window to the user. When called, it runs the open window algorithm.

respondWith() method

This method is used by the credential handler to provide a WebCredential when the request has been fulfilled. When called, it runs the Respond to Credential Request Algorithm with event and handlerResponsePromise as arguments.

CredentialRequestEventInit dictionary

            dictionary CredentialRequestEventInit : ExtendableEventInit {
              USVString credentialRequestOrigin;
              WebCredentialRequestOptions credentialRequestOptions;
              DOMString hintKey;
            };
          

The credentialRequestOrigin, credentialRequestOptions, and hintKey members share their definitions with those defined for CredentialRequestEvent.

Internal Slots

Instances of CredentialRequestEvent are created with the internal slots in the following table:

Internal Slot Default Value Description (non-normative)
[[\windowClient]] null The currently active WindowClient. This is set if a credential handler is currently showing a window to the user. Otherwise, it is null.
[[\fetchedImage]] undefined This value is a result of fetching image object or a fallback image provided by the user agent.
[[\respondWithCalled]] false YAHO

Handling a CredentialRequestEvent

Upon receiving a credential request by way of get() and subsequent user selection of a credential hint, the user agent MUST run the following steps:

  1. Let registration be the ServiceWorkerRegistration corresponding to the CredentialHint selected by the user.
  2. If registration is not found, reject the Promise that was created by get() with a DOMException whose value is "InvalidStateError" and terminate these steps.
  3. Invoke the handle functional event algorithm with a ServiceWorkerRegistration of registration and callbackSteps set to the following steps:
    1. Set global to the global object that was provided as an argument.
    2. Create a trusted event, e, that uses the CredentialRequestEvent interface, with the event type credentialrequest, which does not bubble, cannot be canceled, and has no default action.
    3. Set the credentialRequestOrigin attribute of e to the origin of the context where get() was called.
    4. Set the credentialRequestOptions attributes of e to the options passed to get().
    5. Set the hintKey attribute of e to the hintKey of the selected CredentialHint.
    6. Dispatch e to global.
    7. Wait for all of the promises in the extend lifetime promises of e to resolve.
    8. If the credential handler has not provided a WebCredential or null, reject the Promise that was created by get() with a DOMException whose value "OperationError".

The CredentialStoreEvent

The CredentialStoreEvent represents the data and methods available to a Credential Handler after selection by the user. The user agent communicates the WebCredential to be stored to the Credential Handler.

        [Constructor(DOMString type, CredentialStoreEventInit eventInitDict), Exposed=ServiceWorker]
        interface CredentialStoreEvent : ExtendableEvent {
          readonly attribute USVString credentialRequestOrigin;
          readonly attribute object credential;
          readonly attribute DOMString hintKey;
          Promise<WindowClient?> openWindow(USVString url);
          void respondWith(Promise<WebCredential>handlerResponsePromise);
        };
        

credentialRequestOrigin attribute

This attribute is a string that indicates the origin where the [[!credential-managment-1]] method store() was called.

credential attribute

This attribute contains WebCredential dictionary containing the specific credential information that the web site is requesting the user to store.

hintKey attribute

This attribute indicates the CredentialHint selected by the user. It corresponds to the hintKey provided to the CredentialManager.hints interface during registration.

openWindow() method

This method is used by the credential handler to show a window to the user. When called, it runs the open window algorithm.

respondWith() method

This method is used by the credential handler to provide a WebCredential when the storage request has been fulfilled. When called, it runs the Respond to Store Credential Algorithm with event and handlerResponsePromise as arguments.

CredentialStoreEventInit dictionary

            dictionary CredentialStoreEventInit : ExtendableEventInit {
              USVString credentialRequestOrigin;
              WebCredential credential;
              DOMString hintKey;
            };
          

The credentialRequestOrigin, credential, and hintKey members share their definitions with those defined for CredentialStoreEvent.

Internal Slots

Instances of CredentialStoreEvent are created with the internal slots in the following table:

Internal Slot Default Value Description (non-normative)
[[\windowClient]] null The currently active WindowClient. This is set if a credential handler is currently showing a window to the user. Otherwise, it is null.
[[\fetchedImage]] undefined This value is a result of fetching image object or a fallback image provided by the user agent.
[[\respondWithCalled]] false YAHO

Handling a CredentialStoreEvent

Upon receiving a credential storage request by way of store() and subsequent user selection of a credential hint, the user agent MUST run the following steps:

  1. Let registration be the ServiceWorkerRegistration corresponding to the CredentialHint selected by the user.
  2. If registration is not found, reject the Promise that was created by store() with a DOMException whose value is "InvalidStateError" and terminate these steps.
  3. Invoke the handle functional event algorithm with a ServiceWorkerRegistration of registration and callbackSteps set to the following steps:
    1. Set global to the global object that was provided as an argument.
    2. Create a trusted event, e, that uses the CredentialStoreEvent interface, with the event type credentialstore, which does not bubble, cannot be canceled, and has no default action.
    3. Set the credentialRequestOrigin attribute of e to the origin of the context where store() was called.
    4. Set the credential attributes of e to the options passed to store().
    5. Set the hintKey attribute of e to the hintKey of the selected CredentialHint.
    6. Dispatch e to global.
    7. Wait for all of the promises in the extend lifetime promises of e to resolve.
    8. If the credential handler has not provided a WebCredential or null, reject the Promise that was created by store() with a DOMException whose value "OperationError".

Windows

An invoked credential handler may or may not need to display information about itself or request user input. Some examples of potential credential handler display include:

A credential handler that requires visual display and user interaction, may call openWindow() to display a page to the user.

Since user agents know that this method is connected to the CredentialRequestEvent or a CredentialStoreEvent, they SHOULD render the window in a way that is consistent with the flow and not confusing to the user. The resulting window client is bound to the tab/window that initiated the request. A single credential handler SHOULD NOT be allowed to open more than one client window using this method.

Open Window Algorithm

This algorithm resembles the Open Window Algorithm in the Service Workers specification and mirrors the one provided in the Payment Handler API specification.

Should we refer to the Service Workers specification instead of copying their steps?

  1. Let event be this CredentialRequestEvent or CredentialStoreEvent.
  2. Let url be the result of parsing the url argument.
  3. If the url parsing throws an exception, return a Promise rejected with that exception.
  4. If url is about:blank, return a Promise rejected with a TypeError.
  5. If url's origin is not the same as the service worker's origin associated with the credential handler, return a Promise resolved with null.
  6. If this algorithm is not triggered by user activation, return a Promise rejected with a InvalidAccessError.
  7. Let promise be a new Promise.
  8. Return promise and perform the remaining steps in parallel:
  9. If event.[[\windowClient]] is not null, then:
    1. If event.[[\windowClient]].visibilityState is not "unloaded", reject promise with a DOMException whose name is "InvalidStateError" and abort these steps.
  10. Let newContext be a new top-level browsing context.
  11. Navigate newContext to url, with exceptions enabled and replacement enabled.
  12. If the navigation throws an exception, reject promise with that exception and abort these steps.
  13. If the origin of newContext is not the same as the service worker client origin associated with the credential handler, then:
    1. Resolve promise with null.
    2. Abort these steps.
  14. Let client be the result of running the create window client algorithm with newContext as the argument.
  15. Set event.[[\windowClient]] to client.
  16. Resolve promise with client.

Example of handling the CredentialRequestEvent or the CredentialStoreEvent

This example shows how to write a service worker that listens to the CredentialRequestEvent and the CredentialStoreEvent. When a CredentialRequestEvent or CredentialStoreEvent is received, the service worker opens a window to interact with the user.

      self.addEventListener('credentialrequest', function(e) {
        e.respondWith(new Promise(function(resolve, reject) {
          self.addEventListener('message', listener = function(e) {
            self.removeEventListener('message', listener);
            if (e.data.hasOwnProperty('name')) {
              reject(e.data);
            } else {
              resolve(e.data);
            }
          });

          e.openWindow("https://www.example.com/wallet/get")
          .then(function(windowClient) {
            windowClient.postMessage(e.data);
          })
          .catch(function(err) {
            reject(err);
          });
        }));
      });

      self.addEventListener('credentialstore', function(e) {
        e.respondWith(new Promise(function(resolve, reject) {
          self.addEventListener('message', listener = function(e) {
            self.removeEventListener('message', listener);
            if (e.data.hasOwnProperty('name')) {
              reject(e.data);
            } else {
              resolve(e.data);
            }
          });

          e.openWindow("https://www.example.com/wallet/store")
          .then(function(windowClient) {
            windowClient.postMessage(e.data);
          })
          .catch(function(err) {
            reject(err);
          });
        }));
      });
      

Using the simple scheme described above, a trivial HTML page that is loaded into the credential handler window might include the following script:

<script>
window.addEventListener("message", function(e) {
  var credentialRequestOptions = event.data.credentialRequestOptions;

  // TODO: process the query found in the request options and present
  // choices to the user
  // await ...

  e.source.postMessage({
    type: 'response',
    credential: {
      dataType: 'VerifiableProfile',
      data: {
        '@context': 'https://w3id.org/credentials/v1',
        // ...
        signature: { ... }
      }
    }
  });
  window.close();
});
</script>
      

Response

CredentialHandlerResponse dictionary

The CredentialHandlerResponse is conveyed using the following dictionary:
          dictionary CredentialHandlerResponse {
          DOMString dataType;
          object data;
          };
        

dataType attribute

The WebCredential type for the credential that the user selected to fulfill the request.

data attribute

A JSON-serializable object that provides a WebCredential type specific message used by the relying party to authenticate the user.

The user agent receives a successful response from the credential handler through resolution of the Promise provided to the respondWith() function of the corresponding CredentialRequestEvent interface. The application is expected to resolve the Promise with a CredentialHandlerResponse instance containing the response. In case of user cancellation or error, the application may signal failure by rejecting the Promise.

If the Promise is rejected, the user agent MUST run the credential repository failure algorithm. The exact details of this algorithm are left to implementers. Acceptable behaviors include, but are not limited to:

  • Letting the user try again, with the same credential handler or with a different one.
  • Rejecting the Promise that was created by get() or store().

Respond to Credential Request Algorithm

When this algorithm is invoked with event and handlerResponsePromise parameters, the user agent MUST run the following steps:

  1. If event's dispatch flag is unset, then throw an "InvalidStateError" DOMException and abort these steps.
  2. If event.[[\respondWithCalled]] is true, throw an "InvalidStateError" DOMException and abort these steps.
  3. Set event.[[\respondWithCalled]] to true.
  4. Set the event's stop propagation flag and event's stop immediate propagation flag.
  5. Add handlerResponsePromise to the event's extend lifetime promises
  6. Increment the event's pending promises count by one.
  7. Upon rejection of handlerResponsePromise:
    1. Run the credential repository failure algorithm and terminate these steps.
  8. Upon fulfillment of handlerResponsePromise:
    1. Let handlerResponse be the result of converting value to a CredentialHandlerResponse dictionary. If this throws an exception, run the credential repository failure algorithm and terminate these steps.
    2. If handlerResponse.dataType is not present or not set to one of the keys from event.credentialRequestOptions (TODO: or the dataType for WebCredential for storage), run the credential repository failure algorithm and terminate these steps.
    3. If handlerResponse.data is not present or not JSON-serializable, run the credential repository failure algorithm and terminate these steps.
    4. Let serializeDataType be the result of StructuredSerialize with handlerResponse.dataType. Rethrow any exceptions.
    5. Let serializeData be the result of StructuredSerialize with handlerResponse.data. Rethrow any exceptions.
    6. TODO: integrate with credential management algorithms... or an algorithm defining the creation of a WebCredential
      1. Let dataType be the result of StructuredDeserialize with serializeDataType. Rethrow any exceptions.
      2. Let data be the result of StructuredDeserialize with serializeData. Rethrow any exceptions.
      3. If any exception occurs in any of the above steps, then run the credential repository failure algorithm and terminate these steps.
      4. Assign dataType to associated WebCredential's credential.dataType.
      5. Assign data to associated WebCredential's credential.data.
  9. Upon fulfillment or rejection of handlerResponsePromise, queue a microtask to perform the following steps:
    1. Decrement the event's pending promises count by one.
    2. Let registration be the context object's relevant global object's associated service worker's containing service worker registration.
    3. If registration’s uninstalling flag is set, invoke Try Clear Registration with registration.
    4. If registration is not null, invoke Try Activate with registration.

The following example shows how to respond to a credential request:

      credentialRequestEvent.respondWith(new Promise(function(accept,reject) {
        /* ... processing may occur here ... */
        accept({
          dataType: "VerifiableProfile",
          data: {
            "@context": "https://w3id.org/credentials/v1",
            // ...
           }
        });
      }));
          

Security and Privacy Considerations

Information about the User Environment

User Consent Before Sending Credentials

Secure Communications

Credential Repository Authenticity

Data Validation

Private Browsing Mode

Dependencies

This specification relies on several other underlying specifications.

Credential Management API
get(), and store() are defined by the Credential Management Level 1 specification [[!credential-management-1]].
ECMA-262 6th Edition, The ECMAScript 2015 Language Specification
The terms Promise, internal slot, TypeError, and JSON.stringify are defined by [[!ECMA-262-2015]].

The term JSON-serialize applied to a given object means to run the algorithm specified by the original value of the JSON.stringify function on the supplied object, passing the supplied object as the sole argument, and return the resulting string. This can throw an exception.

HTML5
The terms global object, top-level browsing context, structured clone, event handler, event handler event type, trusted event, and user interaction task source are defined by [[!HTML5]].
RFC6454
The term origin is defined in [[!RFC6454]].
Writing Promise-Using Specifications
The terms upon fulfillment and upon rejection are defined by [[!PROMISES-GUIDE]].
DOM
The term fires (an event), dispatch flag, stop propagation flag, and stop immediate propagation flag are defined in [[!DOM4]].
Web IDL

When this specification says to throw an error, the user agent must throw an error as described in [[!WEBIDL]]. When this occurs in a sub-algorithm, this results in termination of execution of the sub-algorithm and all ancestor algorithms until one is reached that explicitly describes procedures for catching exceptions.

The algorithm for converting an ECMAScript value to a dictionary is defined by [[!WEBIDL]].

DOMException and the following DOMException types from [[!WEBIDL-LS]] are used:

  • "InvalidAccessError"
  • "InvalidStateError"
  • "NotAllowedError"
  • "NotFoundError"
  • "OperationError"
  • "SecurityError"
Secure Contexts
The term secure context is defined by the Secure Contexts specification [[!SECURE-CONTEXTS]].
Service Workers
The terms service worker, service worker client, ServiceWorkerRegistration, ServiceWorkerGlobalScope, handle functional event, extend lifetime promises,pending promises count, containing service worker registration, uninstalling flag, Try Clear Registration, Try Activate, and scope URL are defined in [[!SERVICE-WORKERS]].

Acknowledgements

The authors would like to acknowledge the editors and authors of the Payment Request and Payment Handler specifications as this specification has been largely influenced by their design and language.

TODO