protocol

package
v0.18.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2026 License: BSD-3-Clause Imports: 40 Imported by: 315

Documentation

Overview

Package protocol contains data structures and validation functionality outlined in the Web Authentication specification (https://www.w3.org/TR/webauthn). The data structures here attempt to conform as much as possible to their definitions, but some structs (like those that are used as part of validation steps) contain additional fields that help us unpack and validate the data we unmarshall. When implementing this library, most developers will primarily be using the API outlined in the webauthn package.

Index

Constants

View Source
const (
	Verified verifiedBootState = iota
	SelfSigned
	Unverified
	Failed
)
View Source
const (
	// KM_ORIGIN_GENERATED means generated in keymaster. Should not exist outside the TEE.
	KM_ORIGIN_GENERATED = iota

	// KM_ORIGIN_DERIVED means derived inside keymaster. Likely exists off-device.
	KM_ORIGIN_DERIVED

	// KM_ORIGIN_IMPORTED means imported into keymaster. Existed as clear text in Android.
	KM_ORIGIN_IMPORTED

	// KM_ORIGIN_UNKNOWN means keymaster did not record origin.  This value can only be seen on keys in a keymaster0
	// implementation. The keymaster0 adapter uses this value to document the fact that it is unknown whether the key
	// was generated inside or imported into keymaster.
	KM_ORIGIN_UNKNOWN
)
View Source
const (
	// KM_PURPOSE_ENCRYPT is usable with RSA, EC and AES keys.
	KM_PURPOSE_ENCRYPT = iota

	// KM_PURPOSE_DECRYPT is usable with RSA, EC and AES keys.
	KM_PURPOSE_DECRYPT

	// KM_PURPOSE_SIGN is usable with RSA, EC and HMAC keys.
	KM_PURPOSE_SIGN

	// KM_PURPOSE_VERIFY is usable with RSA, EC and HMAC keys.
	KM_PURPOSE_VERIFY

	// KM_PURPOSE_DERIVE_KEY is usable with EC keys.
	KM_PURPOSE_DERIVE_KEY

	// KM_PURPOSE_WRAP is usable with wrapped keys.
	KM_PURPOSE_WRAP
)
View Source
const (
	// MinimumChallengeLength defines the minimum length of the challenge.
	MinimumChallengeLength = 16

	// DefaultChallengeLength defines the default length of the challenge.
	DefaultChallengeLength = 32
)
View Source
const (
	// MinimumUserHandleLength defines the minimum length of the user handle, i.e. the user entity id. A client
	// throws a TypeError when the length of the user handle falls outside these bounds.
	//
	// Specification: §5.1.3. Create a New Credential (https://www.w3.org/TR/webauthn-3/#sctn-createCredential)
	MinimumUserHandleLength = 1

	// MaximumUserHandleLength defines the maximum length of the user handle, i.e. the user entity id.
	//
	// Specification: §5.4.3. User Account Parameters for Credential Generation (https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialuserentity)
	MaximumUserHandleLength = 64
)
View Source
const (
	// ExtensionAppID is the FIDO AppID Extension identifier. It is used during authentication to allow credentials
	// registered via the legacy FIDO U2F JavaScript API to be used with WebAuthn.
	//
	// Specification: §10.1.1. FIDO AppID Extension (https://www.w3.org/TR/webauthn-3/#sctn-appid-extension)
	ExtensionAppID = "appid"

	// ExtensionAppIDExclude is the FIDO AppID Exclusion Extension identifier. It is used during registration to
	// exclude credentials previously registered via the legacy FIDO U2F JavaScript API.
	//
	// Specification: §10.1.2. FIDO AppID Exclusion Extension (https://www.w3.org/TR/webauthn-3/#sctn-appid-exclude-extension)
	ExtensionAppIDExclude = "appidExclude"

	// ExtensionCredProps is the Credential Properties Extension identifier. It is used during registration to
	// request that the client report properties of the newly created credential.
	//
	// Specification: §10.1.3. Credential Properties Extension (https://www.w3.org/TR/webauthn-3/#sctn-authenticator-credential-properties-extension)
	ExtensionCredProps = "credProps"

	// ExtensionPRF is the Pseudo-random function Extension identifier. It is used during registration and
	// authentication to evaluate a PRF scoped to the credential.
	//
	// Specification: §10.1.4. Pseudo-random function extension (https://www.w3.org/TR/webauthn-3/#prf-extension)
	ExtensionPRF = "prf"

	// ExtensionLargeBlob is the Large blob storage Extension identifier. It is used during registration to request
	// support, and during authentication to read or write opaque data associated with a credential.
	//
	// Specification: §10.1.5. Large blob storage extension (https://www.w3.org/TR/webauthn-3/#sctn-large-blob-extension)
	ExtensionLargeBlob = "largeBlob"

	// ExtensionRemoteClientDataJSON is the Remote Client Data JSON Extension identifier. It is set by a remote
	// desktop web client, not by a Relying Party. A Relying Party receiving this output should understand that the
	// local client delegated every RP ID and origin check to a remote host.
	//
	// This extension is not defined by WebAuthn Level 3. It exists only in the Editor's Draft and is modelled here
	// ahead of ratification, so its definition may change before it is published in a Recommendation.
	//
	// Specification: §10.1.6. Remote Client Data JSON extension (https://w3c.github.io/webauthn/#sctn-remote-client-data-json-extension)
	ExtensionRemoteClientDataJSON = "remoteClientDataJSON"
)
View Source
const (
	// ExtensionCredentialProtectionPolicy requests a credential protection policy at registration.
	ExtensionCredentialProtectionPolicy = "credentialProtectionPolicy"

	// ExtensionEnforceCredentialProtectionPolicy requires that the requested credential protection policy is
	// honoured, failing the ceremony if the authenticator cannot satisfy it.
	ExtensionEnforceCredentialProtectionPolicy = "enforceCredentialProtectionPolicy"

	// ExtensionCredProtect is the credProtect extension's authenticator-output identifier, carried in the
	// authenticator data's extension outputs. It is deliberately distinct from
	// ExtensionCredentialProtectionPolicy, which is the client-facing input identifier used by the
	// create() extensions member; authenticators echo this abbreviated identifier, not that one.
	ExtensionCredProtect = "credProtect"

	// ExtensionMinPinLength requests the authenticator's current minimum PIN length at registration.
	ExtensionMinPinLength = "minPinLength"

	// ExtensionCredBlob requests that a small blob is stored with the credential at registration.
	ExtensionCredBlob = "credBlob"

	// ExtensionGetCredBlob requests the blob stored with the credential at authentication.
	ExtensionGetCredBlob = "getCredBlob"

	// ExtensionLargeBlobKey is the CTAP largeBlobKey extension identifier. It is deliberately NOT modelled by
	// this library: it has no client extension input and no client extension output, so there is nothing for a
	// Relying Party to send or receive. CTAP 2.1 §12.3 states "Client extension input / output / processing:
	// None" and that the extension "is not suitable to be directly exposed to RPs". The key itself is returned
	// as the largeBlobKey (0x05) member of the CTAP response structure, not as a client extension and not as an
	// authenticator data extension, and it is driven by the client platform rather than the Relying Party.
	//
	// Do not add a typed member or a dedicated functional option for this. A caller with a non-browser CTAP
	// client that genuinely needs to set it can use webauthn.WithExtension with this identifier, which routes it
	// through the untyped extension inputs verbatim.
	ExtensionLargeBlobKey = "largeBlobKey"

	// ExtensionHMACCreateSecret requests that the authenticator provisions an HMAC secret at registration.
	ExtensionHMACCreateSecret = "hmacCreateSecret"

	// ExtensionHMACGetSecret requests evaluation of the HMAC secret at authentication.
	ExtensionHMACGetSecret = "hmacGetSecret"

	// ExtensionHMACSecret is the CTAP hmac-secret extension's authenticator-output identifier. It is carried in
	// the authenticator data's extension outputs, as a boolean at registration and as a byte string at
	// authentication. It is deliberately distinct from ExtensionHMACCreateSecret and ExtensionHMACGetSecret,
	// which are the client-facing input identifiers used by the create()/get() extensions member; authenticators
	// echo this hyphenated identifier, not those, in their extension outputs.
	ExtensionHMACSecret = "hmac-secret"

	// ExtensionUVM requests the user verification methods used for the operation.
	ExtensionUVM = "uvm"
)

The following extension identifiers are defined by CTAP 2.1 and CTAP 2.2 and registered in the IANA "WebAuthn Extension Identifiers" registry established by RFC8809. They are not defined by WebAuthn Level 3, however several clients forward them as extension inputs.

Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

View Source
const (
	// WellKnownPathWebAuthn is the path of the well-known resource a Relying Party serves to declare the origins
	// related to its Relying Party ID. A client fetches it from https://<rpid>/.well-known/webauthn when the origin
	// of a ceremony does not match the Relying Party ID directly.
	//
	// Specification: §5.11. Related Origin Requests (https://www.w3.org/TR/webauthn-3/#sctn-related-origins)
	WellKnownPathWebAuthn = "/.well-known/webauthn"

	// MaximumRelatedOriginLabels is the number of distinct registrable domain labels a client processes when it reads
	// the well-known resource. A client stops adding labels once it has seen this many, so origins whose label falls
	// outside the budget are silently ignored; this is the limit [NewRelatedOrigins] holds the origins to.
	//
	// Specification: §5.11. Related Origin Requests (https://www.w3.org/TR/webauthn-3/#sctn-related-origins)
	MaximumRelatedOriginLabels = 5
)
View Source
const (
	// OpaqueOriginPrefixAndroidAPKKeyHash is the prefix of the opaque origin a client on Android conveys for a native
	// application. The remainder is the base64url encoding, without padding, of the SHA-1 digest of the signing
	// certificate of the APK.
	OpaqueOriginPrefixAndroidAPKKeyHash = "android:apk-key-hash:"

	// OpaqueOriginPrefixAndroidAPKKeyHashSHA256 is the prefix of the opaque origin a client on Android conveys for a
	// native application when the digest of the signing certificate of the APK is taken with SHA-256 rather than the
	// SHA-1 of [OpaqueOriginPrefixAndroidAPKKeyHash].
	OpaqueOriginPrefixAndroidAPKKeyHashSHA256 = "android:apk-key-hash-sha256:"

	// OpaqueOriginPrefixAndroidAPKKeyID is the prefix of the opaque origin a client on Android conveys for a native
	// application when it identifies the signing key of the APK by its id rather than by a digest of the signing
	// certificate.
	OpaqueOriginPrefixAndroidAPKKeyID = "android:apk-key-id:"

	// OpaqueOriginPrefixIOSBundleID is the prefix of the opaque origin a client on iOS conveys for a native
	// application. The remainder is the bundle identifier of the application.
	OpaqueOriginPrefixIOSBundleID = "ios:bundle-id:"

	// OpaqueOriginPrefixIOSBundleKey is the prefix of the opaque origin a client on iOS conveys for a native
	// application when it identifies the application by its signing key rather than by the bundle identifier of
	// [OpaqueOriginPrefixIOSBundleID].
	OpaqueOriginPrefixIOSBundleKey = "ios:bundle-key:"

	// OpaqueOriginPrefixChromeExtension is the prefix of the origin a Chromium based browser conveys for an extension.
	// The remainder is the id of the extension.
	OpaqueOriginPrefixChromeExtension = "chrome-extension://"

	// OpaqueOriginPrefixMozExtension is the prefix of the origin Firefox conveys for an extension. The remainder is
	// the id the browser assigned the extension for the profile it is installed in, which differs between
	// installations of the same extension.
	OpaqueOriginPrefixMozExtension = "moz-extension://"

	// OpaqueOriginPrefixFile is the origin a browser conveys for a document loaded from the local file system. A file
	// origin has no host to serialize, so this is a complete origin rather than a prefix and a client conveys it
	// exactly as it is given here; see [IsKnownOpaqueOrigin].
	OpaqueOriginPrefixFile = "file://"

	// OpaqueOriginPrefixMSAppX is the prefix of the origin a client conveys for a Windows application package. The
	// remainder is the package identity of the application.
	OpaqueOriginPrefixMSAppX = "ms-appx://"
)
View Source
const ChallengeLength = DefaultChallengeLength

ChallengeLength - Length of bytes to generate for a challenge.

View Source
const ClientCapabilityExtensionPrefix = "extension:"

ClientCapabilityExtensionPrefix is prepended to an extension identifier to name the capability under which a client reports support for that extension. Build such a capability with ExtensionClientCapability and take one apart with ClientCapability.Extension rather than concatenating this constant directly.

Specification: §5.1.7. Availability of client capabilities (https://www.w3.org/TR/webauthn-3/#sctn-getClientCapabilities)

Variables

View Source
var (
	ErrBadRequest = &Error{
		Type:    "invalid_request",
		Details: "Error reading the request data",
	}
	ErrPolicyRestriction = &Error{
		Type:    "policy_restriction",
		Details: "Policy restriction prevented the operation from completing",
	}
	ErrChallengeMismatch = &Error{
		Type:    "challenge_mismatch",
		Details: "Stored challenge and received challenge do not match",
	}
	ErrParsingData = &Error{
		Type:    "parse_error",
		Details: "Error parsing the authenticator response",
	}
	ErrAuthData = &Error{
		Type:    "auth_data",
		Details: "Error verifying the authenticator data",
	}
	ErrVerification = &Error{
		Type:    "verification_error",
		Details: "Error validating the authenticator response",
	}
	ErrAttestation = &Error{
		Type:    "attestation_error",
		Details: "Error validating the attestation data provided",
	}
	ErrInvalidAttestation = &Error{
		Type:    "invalid_attestation",
		Details: "Invalid attestation data",
	}
	ErrMetadata = &Error{
		Type:    "invalid_metadata",
		Details: "",
	}
	ErrAttestationFormat = &Error{
		Type:    "invalid_attestation",
		Details: "Invalid attestation format",
	}
	ErrAttestationCertificate = &Error{
		Type:    "invalid_certificate",
		Details: "Invalid attestation certificate",
	}
	ErrAssertionSignature = &Error{
		Type:    "invalid_signature",
		Details: "Assertion Signature against auth data and client hash is not valid",
	}
	ErrUnsupportedKey = &Error{
		Type:    "invalid_key_type",
		Details: "Unsupported Public Key Type",
	}
	ErrUnsupportedAlgorithm = &Error{
		Type:    "unsupported_key_algorithm",
		Details: "Unsupported public key algorithm",
	}
	ErrNotSpecImplemented = &Error{
		Type:    "spec_unimplemented",
		Details: "This field is not yet supported by the WebAuthn spec",
	}
	ErrNotImplemented = &Error{
		Type:    "not_implemented",
		Details: "This field is not yet supported by this library",
	}
)

Functions

func DefaultRelatedOriginLabeler added in v0.18.0

func DefaultRelatedOriginLabeler(origin string) (label string, err error)

DefaultRelatedOriginLabeler derives the registrable domain label of an origin by taking the leading label of the last two labels of its host. An IP address literal, and a host of a single label such as localhost, is its own label.

This is exact when the public suffix of the host is a single label, which covers https://example.com and https://www.example.com alike, and it is deliberately imprecise otherwise: the public suffix of https://example.co.uk is two labels, so this returns 'co' where the registrable domain label is 'example'. The effect is to over-count against MaximumRelatedOriginLabels, which rejects a set of origins a client would have accepted rather than serving one a client would truncate.

A deployment which lists origins under a multi-label public suffix should count labels exactly by passing a labeler backed by a public suffix list to NewRelatedOriginsWithLabeler; this module does not depend on such a list so that consumers who do not need one do not carry it:

labeler := func(origin string) (label string, err error) {
	uri, err := url.Parse(origin)
	if err != nil {
		return "", err
	}

	domain, err := publicsuffix.EffectiveTLDPlusOne(uri.Hostname())
	if err != nil {
		return "", err
	}

	label, _, _ = strings.Cut(domain, ".")

	return label, nil
}

func FullyQualifiedOrigin

func FullyQualifiedOrigin(rawOrigin string) (fqOrigin string, err error)

FullyQualifiedOrigin returns the origin per the HTML spec: (scheme)://(host)[:(port)].

A known opaque origin which carries no authority component, i.e. one a client conveys for a native application such as 'android:apk-key-hash:...' or the origin of a document loaded from the local file system, has no such serialization and is returned unaltered so it can be compared byte for byte. The opaque origins which do carry an authority, such as the origin of a browser extension, are serialized in the usual way.

func IsAttestationFormatString added in v0.17.0

func IsAttestationFormatString(s string) bool

IsAttestationFormatString reports whether s is one of the WebAuthn-defined attestation statement format identifiers. Used to detect and migrate records from prior releases which stored the format string in the AttestationType field.

func IsKnownOpaqueOrigin added in v0.18.0

func IsKnownOpaqueOrigin(origin string) bool

IsKnownOpaqueOrigin returns true when the origin is opaque per IsOpaqueOrigin and additionally carries one of the prefixes of OpaqueOriginPrefixes followed by at least one character, or is one of the few such prefixes which is a complete origin in itself, i.e. OpaqueOriginPrefixFile. Those are the forms a client is known to convey for a native application, a browser extension, or a document loaded from the local file system, which are the only opaque origins a Relying Party can meaningfully accept: an opaque origin is matched by simple string comparison against a value the Relying Party configured, so a value no client ever produces can only ever fail to match.

The prefix is matched case-sensitively, as the whole value is, because a client conveys these origins in the form given here and the origin as a whole is compared byte for byte.

func IsOpaqueOrigin added in v0.18.0

func IsOpaqueOrigin(origin string) bool

IsOpaqueOrigin returns true when the origin is not one a RelatedOrigins document can express, i.e. anything which is not an absolute http or https URL with a host component. An opaque origin is matched by simple string comparison rather than by the origin equality semantics of IsOriginInHaystack, and a client never resolves one through the well-known resource, so a Relying Party which accepts an opaque origin such as 'android:apk-key-hash:...' declares it separately from the origins it serves at WellKnownPathWebAuthn.

This says nothing about whether a client conveys the origin; see IsKnownOpaqueOrigin for that.

Specification: §5.11. Related Origin Requests (https://www.w3.org/TR/webauthn-3/#sctn-related-origins)

func IsOpaqueOriginInHaystack added in v0.18.0

func IsOpaqueOriginInHaystack(needle string, haystack []string) bool

IsOpaqueOriginInHaystack checks if the needle is in the haystack of opaque origins, i.e. the origins for which IsOpaqueOrigin returns true, using simple string comparison as defined in RFC3986 Section 6.2.1.

This is deliberately not IsOriginInHaystack: an opaque origin has no scheme and host to normalize, so there is no case folding and no port normalization to apply to it, and the value a client conveys for one is compared byte for byte or not at all. Routing the opaque origins through this function rather than through IsOriginInHaystack keeps that true of a value which merely resembles a URL, such as an http origin which has no host or whose port is out of range; both are opaque, and neither may be matched with the leniency an origin with a host is matched with.

See (Simple String Comparison Definition): https://datatracker.ietf.org/doc/html/rfc3986#section-6.2.1

func IsOriginInHaystack added in v0.14.0

func IsOriginInHaystack(needle string, haystack []string) bool

IsOriginInHaystack checks if the needle is in the haystack using the mechanism to determine origin equality defined in HTML5 Section 5.3 and RFC3986 Section 6.2.1.

Specifically if the needle value has the 'http://' or 'https://' prefix (case-insensitive) and can be parsed as a URL; we check each item in the haystack to see if it matches the same rules, and then if the scheme and host (with a normalized port) components match case-insensitively then they're considered a match.

If the needle value does not have the 'http://' or 'https://' prefix (case-insensitive) or can't be parsed as a URL equality is determined using simple string comparison.

It is important to note that this function completely ignores Apple Associated Domains entirely as Apple is using an unassigned Well-Known URI in breech of Well-Known Uniform Resource Identifiers (RFC8615).

See (Origin Definition): https://www.w3.org/TR/2011/WD-html5-20110525/origin-0.html

See (Simple String Comparison Definition): https://datatracker.ietf.org/doc/html/rfc3986#section-6.2.1

See (Apple Associated Domains): https://developer.apple.com/documentation/xcode/supporting-associated-domains

See (IANA Well Known URI Assignments): https://www.iana.org/assignments/well-known-uris/well-known-uris.xhtml

See (Well-Known Uniform Resource Identifiers): https://datatracker.ietf.org/doc/html/rfc8615

func OpaqueOriginPrefixes added in v0.18.0

func OpaqueOriginPrefixes() []string

OpaqueOriginPrefixes returns the prefixes of the opaque origins this library knows a client conveys, i.e. those which IsKnownOpaqueOrigin accepts.

func RegisterAttestationFormat

func RegisterAttestationFormat(format AttestationFormat, handler attestationFormatValidationHandler)

RegisterAttestationFormat is a method to register attestation formats with the library. Generally using one of the locally registered attestation formats is enough.

func ResidentKeyNotRequired added in v0.2.0

func ResidentKeyNotRequired() *bool

ResidentKeyNotRequired - Do not require that the private key be resident to the client device.

func ResidentKeyRequired

func ResidentKeyRequired() *bool

ResidentKeyRequired - Require that the key be private key resident to the client device.

func ValidateRPID added in v0.16.0

func ValidateRPID(value string) (err error)

ValidateRPID performs non-exhaustive checks to ensure the string is most likely a domain string as relying-party ID's are required to be. Effectively this is localhost or a domain of two or more labels. The relying-party ID must not contain scheme, port, path, query, or fragment components, and must not be an IP address: §5.4.2 defines it as a valid domain string, which an address literal is not, and a client rejects one.

No IDNA normalization is performed, so a value carrying non-ASCII characters is rejected rather than converted. A Relying Party ID is hashed verbatim to compare against the rpIdHash an authenticator reports, while a client normalizes the value it was handed, so a name which is not already in its ASCII form can never produce a matching hash. Callers serving an internationalized domain must apply IDNA themselves and configure the resulting A-label.

See: https://www.w3.org/TR/webauthn/#rp-id

Types

type AllAcceptedCredentialsUser added in v0.16.0

type AllAcceptedCredentialsUser interface {
	WebAuthnID() []byte
	WebAuthnCredentialIDs() [][]byte
}

AllAcceptedCredentialsUser is an interface that can be implemented by a user to provide information about their accepted credentials.

type AndroidKeyAuthorizationScope added in v0.18.0

type AndroidKeyAuthorizationScope int

AndroidKeyAuthorizationScope selects the authorization lists of the Android key attestation certificate extension which the §8.4 origin and purpose requirements are evaluated against.

§8.4 assigns this choice to the Relying Party: "For the following, use only the teeEnforced authorization list if the RP wants to accept only keys from a trusted execution environment, otherwise use the union of teeEnforced and softwareEnforced."

Specification: §8.4. Android Key Attestation Statement Format (https://www.w3.org/TR/webauthn/#sctn-android-key-attestation)

const (
	// AndroidKeyAuthorizationScopeDefault is the zero value of [AndroidKeyAuthorizationScope] and has no matching
	// rule in §8.4. It evaluates as [AndroidKeyAuthorizationScopeTEEEnforced] wherever it is used. webauthn.Config
	// rewrites it to that explicit constant during validation, so a Relying Party can tell an unset field apart
	// from a deliberate choice of the same scope.
	AndroidKeyAuthorizationScopeDefault AndroidKeyAuthorizationScope = iota

	// AndroidKeyAuthorizationScopeTEEEnforced evaluates the origin and purpose requirements against the teeEnforced
	// authorization list alone, accepting only keys generated within a trusted execution environment.
	AndroidKeyAuthorizationScopeTEEEnforced

	// AndroidKeyAuthorizationScopeUnion evaluates the origin and purpose requirements against the union of the
	// teeEnforced and softwareEnforced authorization lists, which additionally accepts software backed keys.
	AndroidKeyAuthorizationScopeUnion
)

type AndroidKeyPolicy added in v0.18.0

type AndroidKeyPolicy struct {
	// AuthorizationScope selects the authorization lists of the attestation certificate extension which the origin
	// and purpose requirements are evaluated against.
	AuthorizationScope AndroidKeyAuthorizationScope
}

AndroidKeyPolicy configures the Android Key Attestation Statement Format verification procedure.

Specification: §8.4. Android Key Attestation Statement Format (https://www.w3.org/TR/webauthn/#sctn-android-key-attestation)

type AppleAnonymousAttestation

type AppleAnonymousAttestation struct {
	Nonce []byte `asn1:"tag:1,explicit"`
}

AppleAnonymousAttestation represents the attestation format for Apple, who have not yet published a schema for the extension (as of JULY 2021.)

type AttestationFormat added in v0.11.0

type AttestationFormat string

AttestationFormat is an internal representation of the relevant inputs for registration.

Specification: §5.4 Options for Credential Creation (https://w3c.github.io/webauthn/#dom-publickeycredentialcreationoptions-attestationformats) Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

const (
	// AttestationFormatPacked is the "packed" attestation statement format is a WebAuthn-optimized format for
	// attestation. It uses a very compact but still extensible encoding method. This format is implementable by
	// authenticators with limited resources (i.e., secure elements).
	AttestationFormatPacked AttestationFormat = "packed"

	// AttestationFormatTPM is the TPM attestation statement format returns an attestation statement in the same format
	// as the packed attestation statement format, although the rawData and signature fields are computed differently.
	AttestationFormatTPM AttestationFormat = "tpm"

	// AttestationFormatAndroidKey is the attestation statement format for platform authenticators on versions "N", and
	// later, which may provide this proprietary "hardware attestation" statement.
	AttestationFormatAndroidKey AttestationFormat = "android-key"

	// AttestationFormatAndroidSafetyNet is the attestation statement format that Android-based platform authenticators
	// MAY produce an attestation statement based on the Android SafetyNet API.
	AttestationFormatAndroidSafetyNet AttestationFormat = "android-safetynet"

	// AttestationFormatFIDOUniversalSecondFactor is the attestation statement format that is used with FIDO U2F
	// authenticators.
	AttestationFormatFIDOUniversalSecondFactor AttestationFormat = "fido-u2f"

	// AttestationFormatApple is the attestation statement format that is used with Apple devices' platform
	// authenticators.
	AttestationFormatApple AttestationFormat = "apple"

	// AttestationFormatCompound is used to pass multiple, self-contained attestation statements in a single ceremony.
	AttestationFormatCompound AttestationFormat = "compound"

	// AttestationFormatNone is the attestation statement format that is used to replace any authenticator-provided
	// attestation statement when a WebAuthn Relying Party indicates it does not wish to receive attestation information.
	AttestationFormatNone AttestationFormat = none
)

type AttestationObject

type AttestationObject struct {
	// The authenticator data, including the newly created public key. See [AuthenticatorData] for more info.
	AuthData AuthenticatorData

	// The byteform version of the authenticator data, used in part for signature validation.
	RawAuthData []byte `json:"authData"`

	// The format of the Attestation data.
	Format string `json:"fmt"`

	// The attestation statement data sent back if attestation is requested.
	AttStatement map[string]any `json:"attStmt,omitempty"`

	// SubStatements holds the sub-statements of a compound attestation statement, which §8.9 encodes as an array
	// rather than as the map every other format uses for its attestation statement. It is populated by
	// [AttestationObject.UnmarshalCBOR] when, and only when, Format is "compound", and for such an attestation
	// AttStatement is empty because the wire format carries no map to put there.
	//
	// Specification: §8.9. Compound Attestation Statement Format (https://www.w3.org/TR/webauthn-3/#sctn-compound-attestation)
	SubStatements []NonCompoundAttestationObject `json:"-"`

	// Type is the attestation type as conveyed by the authenticator, one of the values defined by
	// [metadata.AuthenticatorAttestationType] (i.e. "basic_full", "basic_surrogate", "attca", "anonca", "none").
	// It is populated as a side-effect of a successful [AttestationObject.VerifyAttestation]; before that the field
	// is empty. This field is excluded from serialization because the attestation object wire format does not carry
	// this value; it is derived by the format-specific verifier.
	Type string `json:"-"`
}

AttestationObject is the raw attestationObject.

Authenticators SHOULD also provide some form of attestation, if possible. If an authenticator does, the basic requirement is that the authenticator can produce, for each credential public key, an attestation statement verifiable by the WebAuthn Relying Party. Typically, this attestation statement contains a signature by an attestation private key over the attested credential public key and a challenge, as well as a certificate or similar data providing provenance information for the attestation public key, enabling the Relying Party to make a trust decision. However, if an attestation key pair is not available, then the authenticator MAY either perform self attestation of the credential public key with the corresponding credential private key, or otherwise perform no attestation. All this information is returned by authenticators any time a new public key credential is generated, in the overall form of an attestation object.

Specification: §6.5. Attestation (https://www.w3.org/TR/webauthn/#sctn-attestation)

func (*AttestationObject) UnmarshalCBOR added in v0.18.0

func (a *AttestationObject) UnmarshalCBOR(data []byte) (err error)

UnmarshalCBOR implements the CBOR unmarshalling of an attestation object, decoding the attestation statement according to the attestation statement format the object declares.

Every format defined by §8 other than compound encodes its attestation statement as a map, which is decoded into AttestationObject.AttStatement. The compound format encodes an array of sub-statements instead, which is decoded into AttestationObject.SubStatements. A single field cannot hold both, and the shape is not self-describing to the decoder, hence the two passes.

AttestationObject.AuthData is not populated here; it is unmarshalled from AttestationObject.RawAuthData by the response parser, which is also where the attested credential data is required to be present.

The receiver is zeroed first so that decoding into one which already holds an attestation object replaces it rather than adding to it. Only one of the two statement members is written by any given object, the statement is not written at all by an object which carries none, and AttestationObject.AuthData and AttestationObject.Type are populated after decoding rather than during it, so without this every one of them could outlive the object it describes. Decoding a map into a non-nil map merges into it, so a statement decoded over another would otherwise inherit the members the new one does not carry.

Specification: §8.9. Compound Attestation Statement Format (https://www.w3.org/TR/webauthn-3/#sctn-compound-attestation)

func (*AttestationObject) Verify

func (a *AttestationObject) Verify(relyingPartyID string, clientDataHash []byte, userVerificationRequired bool, userPresenceRequired bool, mds metadata.Provider, credParams []CredentialParameter, policy AttestationPolicy, signature SignaturePolicy) (err error)

Verify performs Steps 13 through 19 of registration verification.

Steps 13 through 15 are verified against the auth data. These steps are identical to 15 through 18 for assertion so we handle them with AuthData.

func (*AttestationObject) VerifyAttestation added in v0.11.0

func (a *AttestationObject) VerifyAttestation(clientDataHash []byte, mds metadata.Provider, policy AttestationPolicy, signature SignaturePolicy) (err error)

VerifyAttestation only verifies the attestation object excluding the AuthData values. If you wish to also verify the AuthData values you should use [Verify].

The policy carries the Relying Party decisions which §8 leaves to the Relying Party. Its zero value selects the most restrictive behavior available. See AttestationPolicy.

type AttestationPolicy added in v0.18.0

type AttestationPolicy struct {
	// AndroidKey configures the Android Key Attestation Statement Format verification procedure.
	AndroidKey AndroidKeyPolicy

	// Compound configures the Compound Attestation Statement Format verification procedure.
	Compound CompoundPolicy
}

AttestationPolicy carries the Relying Party policy decisions which §8 of the specification delegates to the Relying Party rather than fixing. The zero value selects the most restrictive behavior available for each policy it carries.

type AttestedCredentialData

type AttestedCredentialData struct {
	// AAGUID is the 16-byte Authenticator Attestation GUID, a unique identifier indicating the type of the
	// authenticator (i.e. make and model).
	AAGUID []byte `json:"aaguid"`

	// CredentialID is the credential identifier whose length is prepended as a 16-bit unsigned big-endian integer.
	CredentialID []byte `json:"credential_id"`

	// CredentialPublicKey is the CBOR-encoded credential public key using the COSE_Key format defined in
	// Section 7 of [RFC9052].
	CredentialPublicKey []byte `json:"public_key"`
}

AttestedCredentialData is a variable-length byte array added to the authenticator data when generating an attestation object for a credential.

Specification: §6.5.2. Attested Credential Data (https://www.w3.org/TR/webauthn/#sctn-attested-credential-data)

type AuthenticationExtensions

type AuthenticationExtensions struct {
	// AppID is the FIDO AppID Extension input. Authentication only.
	AppID string `json:"appid,omitempty"`

	// AppIDExclude is the FIDO AppID Exclusion Extension input. Registration only.
	AppIDExclude string `json:"appidExclude,omitempty"`

	// CredProps requests the Credential Properties Extension. Registration only.
	CredProps bool `json:"credProps,omitempty"`

	// PRF is the Pseudo-random function Extension input. It is a pointer because an empty dictionary is a
	// meaningful input for this extension and only this extension: a Relying Party sends "prf":{} at registration
	// to ask whether the pseudo-random function is available for the credential being created, and the client
	// answers with the 'enabled' output. A value type combined with omitzero cannot express the difference between
	// an absent member and a member present but empty, so a non-nil pointer to a zero value is what carries the
	// bare availability probe.
	PRF *PRFInputs `json:"prf,omitempty"`

	// LargeBlob is the Large blob storage Extension input.
	LargeBlob LargeBlobInputs `json:"largeBlob,omitzero"`

	// RemoteClientDataJSON is the Remote Client Data JSON Extension input. This member is set by a remote desktop
	// web client and a Relying Party should not normally set it. See [ExtensionRemoteClientDataJSON], which records
	// that this extension is not yet ratified.
	RemoteClientDataJSON string `json:"remoteClientDataJSON,omitempty"`

	// CredentialProtectionPolicy is the CTAP credProtect policy. Registration only.
	CredentialProtectionPolicy CredentialProtectionPolicy `json:"credentialProtectionPolicy,omitempty"`

	// EnforceCredentialProtectionPolicy requires the credProtect policy is honoured. Registration only.
	EnforceCredentialProtectionPolicy bool `json:"enforceCredentialProtectionPolicy,omitempty"`

	// MinPinLength requests the authenticator minimum PIN length. Registration only.
	MinPinLength bool `json:"minPinLength,omitempty"`

	// CredBlob is the blob to store with the credential. Registration only.
	CredBlob URLEncodedBase64 `json:"credBlob,omitempty"`

	// GetCredBlob requests the blob stored with the credential. Authentication only.
	GetCredBlob bool `json:"getCredBlob,omitempty"`

	// HMACCreateSecret requests provisioning of the CTAP hmac-secret. Registration only.
	HMACCreateSecret bool `json:"hmacCreateSecret,omitempty"`

	// HMACGetSecret requests evaluation of the CTAP hmac-secret. Authentication only.
	HMACGetSecret HMACGetSecretInputs `json:"hmacGetSecret,omitzero"`

	// UVM requests the user verification methods used for the operation.
	UVM bool `json:"uvm,omitempty"`

	// Extra carries extension inputs this library does not model. Entries are merged into the top-level object
	// when marshalling and unrecognised members are collected here when unmarshalling. An entry whose key matches
	// a modelled extension is an error, as the intent would be ambiguous.
	Extra map[string]any `json:"-"`
}

AuthenticationExtensions represents the AuthenticationExtensionsClientInputs IDL. It contains additional parameters requesting additional processing by the client and authenticator.

Members are marshalled in the AuthenticationExtensionsClientInputsJSON form, i.e. buffer sources are base64url encoded strings, which is the form consumed by PublicKeyCredential.parseCreationOptionsFromJSON().

A JSON member whose key matches a modelled name only by case (e.g. "CredProps" for "credProps") is bound to that modelled field, not collected into AuthenticationExtensions.Extra: encoding/json resolves the case-insensitive match during the first decoding pass, before UnmarshalJSON ever sees the untyped member map. If such a member's value has the wrong type for the modelled field, unmarshalling fails outright rather than falling back to Extra. encoding/json (v1, the only version this module may use) offers no way to defer that binding.

Specification: §5.7.1. Authentication Extensions Client Inputs (https://www.w3.org/TR/webauthn-3/#iface-authentication-extensions-client-inputs)

Specification: §10.1. Client Extensions (https://www.w3.org/TR/webauthn-3/#sctn-defined-client-extensions)

func ParseAuthenticationExtensions added in v0.18.0

func ParseAuthenticationExtensions(in map[string]any) (out AuthenticationExtensions, err error)

ParseAuthenticationExtensions converts a map of extension inputs into typed fields. Recognised identifiers whose values have the wrong type return an error and unrecognised identifiers are placed in AuthenticationExtensions.Extra.

This is the only supported ingress for the untyped map form; no functional option accepts a map, so the coercion is an explicit and fallible step the caller owns.

func (AuthenticationExtensions) IsZero added in v0.18.0

func (e AuthenticationExtensions) IsZero() bool

IsZero returns true when no extension input is set. It is used by the encoding/json omitzero tag option so a Relying Party that requests no extensions does not send an empty extensions member to the client.

It is defined in terms of AuthenticationExtensions.Requested so the two cannot disagree about what "set" means. Requested does not allocate for a zero value, so neither does this.

func (AuthenticationExtensions) Map added in v0.18.0

func (e AuthenticationExtensions) Map() (out map[string]any, err error)

Map returns the inputs in their untyped map form, equivalent to the marshalled JSON object. It exists so callers migrating from the previous map-based representation can adapt existing logging, storage, or conformance code incrementally.

func (AuthenticationExtensions) MarshalJSON added in v0.18.0

func (e AuthenticationExtensions) MarshalJSON() (data []byte, err error)

MarshalJSON implements the json.Marshaler interface, merging AuthenticationExtensions.Extra into the top-level object. Marshalling always routes through a map so the key ordering does not depend on whether Extra is populated.

func (AuthenticationExtensions) Requested added in v0.18.0

func (e AuthenticationExtensions) Requested() (names []string)

Requested returns the extension identifiers present in these inputs, in specification order followed by the sorted AuthenticationExtensions.Extra keys. It returns nil rather than an empty slice when no extension is requested, so the result survives a round trip through an encoding that elides empty collections.

The result is stored in SessionExtensions and drives the unsolicited output check performed by AuthenticationExtensionsClientOutputs.Verify.

func (AuthenticationExtensions) Session added in v0.18.0

Session returns the subset of these inputs that must be persisted in the session for the finish step of the ceremony to verify the extension outputs.

Extra is cloned so the persisted session and the live options do not share a backing map; mutating the inputs after the begin step must not retroactively change what the finish step verifies against.

The clone is shallow. A value inside Extra which is itself a reference type stays shared with the inputs, so a Relying Party which mutates a nested map or slice after the begin step does change what the finish step sees. Extra holds Relying Party data rather than anything an attacker supplies, and a deep clone of an arbitrary value cannot be done without either reflection or a serialisation round trip, so the boundary is documented instead of widened. Persisting the session, as a Relying Party is required to do between the two steps, is itself a serialisation and does not carry the sharing with it.

func (*AuthenticationExtensions) UnmarshalJSON added in v0.18.0

func (e *AuthenticationExtensions) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON implements the json.Unmarshaler interface, collecting unrecognised members into AuthenticationExtensions.Extra.

func (AuthenticationExtensions) Validate added in v0.18.0

func (e AuthenticationExtensions) Validate(c CeremonyType) (err error)

Validate reports whether these inputs are internally consistent and applicable to the given ceremony. Every problem found is reported, joined with errors.Join, rather than only the first.

Registration-only members are rejected during authentication and authentication-only members are rejected during registration. A ceremony which is neither CreateCeremony nor AssertCeremony is treated as a registration, so an unexpected value fails closed rather than admitting the authentication-only members unchecked.

Members the IDL marks required must also be non-empty when the dictionary containing them is present: the 'first' value of a PRF 'eval' and of every 'evalByCredential' entry, and the 'salt1' value of an 'hmacGetSecret'. Without these the member would be marshalled as a JSON null.

type AuthenticationExtensionsClientOutputs

type AuthenticationExtensionsClientOutputs struct {
	// AppID indicates the FIDO AppID Extension was acted upon.
	AppID *bool `json:"appid,omitempty"`

	// AppIDExclude indicates the FIDO AppID Exclusion Extension was acted upon.
	AppIDExclude *bool `json:"appidExclude,omitempty"`

	// CredProps reports the properties of a newly created credential.
	CredProps *CredentialPropertiesOutput `json:"credProps,omitempty"`

	// PRF reports the availability and results of the pseudo-random function extension.
	PRF *PRFOutputs `json:"prf,omitempty"`

	// LargeBlob reports large blob support at registration, or the read or written blob at authentication.
	LargeBlob *LargeBlobOutputs `json:"largeBlob,omitempty"`

	// RemoteClientDataJSON indicates the Remote Client Data JSON Extension was acted upon, which means the local
	// client delegated every Relying Party ID and origin check to a remote host. See
	// [ExtensionRemoteClientDataJSON], which records that this extension is not yet ratified.
	RemoteClientDataJSON *bool `json:"remoteClientDataJSON,omitempty"`

	// HMACCreateSecret indicates the CTAP hmac-secret was provisioned at registration.
	HMACCreateSecret *bool `json:"hmacCreateSecret,omitempty"`

	// HMACGetSecret reports the CTAP hmac-secret evaluation results.
	HMACGetSecret *HMACGetSecretOutputs `json:"hmacGetSecret,omitempty"`

	// Extra carries extension outputs this library does not model.
	Extra map[string]any `json:"-"`
	// contains filtered or unexported fields
}

AuthenticationExtensionsClientOutputs represents the AuthenticationExtensionsClientOutputs IDL, returned by the client after a create() or get() call.

Every modelled member is a pointer so an absent value is distinguishable from a false or empty one; the unsolicited output check performed by AuthenticationExtensionsClientOutputs.Verify depends on that distinction.

A JSON member whose key matches a modelled name only by case (e.g. "AppID" for "appid") is bound to that modelled field, not collected into AuthenticationExtensionsClientOutputs.Extra: encoding/json resolves the case-insensitive match during the first decoding pass, before UnmarshalJSON ever sees the untyped member map. If such a member's value has the wrong type for the modelled field, unmarshalling fails outright rather than falling back to Extra. encoding/json (v1, the only version this module may use) offers no way to defer that binding.

Specification: §5.9. Authentication Extensions Client Outputs (https://www.w3.org/TR/webauthn-3/#iface-authentication-extensions-client-outputs)

func (AuthenticationExtensionsClientOutputs) IsZero added in v0.18.0

IsZero returns true when no extension output is set. It is used by the encoding/json omitzero tag option so a ParsedPublicKeyCredential or PublicKeyCredential whose client reported no extension output does not marshal an empty clientExtensionResults member.

It is defined in terms of AuthenticationExtensionsClientOutputs.Present so the two cannot disagree about what "set" means.

func (AuthenticationExtensionsClientOutputs) Map added in v0.18.0

func (o AuthenticationExtensionsClientOutputs) Map() (out map[string]any, err error)

Map returns the outputs in their untyped map form, equivalent to the marshalled JSON object.

func (AuthenticationExtensionsClientOutputs) MarshalJSON added in v0.18.0

func (o AuthenticationExtensionsClientOutputs) MarshalJSON() (data []byte, err error)

MarshalJSON implements the json.Marshaler interface, merging AuthenticationExtensionsClientOutputs.Extra into the top-level object.

func (AuthenticationExtensionsClientOutputs) Present added in v0.18.0

func (o AuthenticationExtensionsClientOutputs) Present() (names []string)

Present returns the extension identifiers present in these outputs, in specification order followed by the sorted AuthenticationExtensionsClientOutputs.Extra keys.

A modelled member the client returned as JSON null is present: it leaves the typed field nil, but the client did return the member, and the unsolicited output check must treat it the same as the unmodelled null it would otherwise be inconsistent with.

func (*AuthenticationExtensionsClientOutputs) UnmarshalJSON added in v0.18.0

func (o *AuthenticationExtensionsClientOutputs) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON implements the json.Unmarshaler interface, collecting unrecognised members into AuthenticationExtensionsClientOutputs.Extra.

func (AuthenticationExtensionsClientOutputs) Verify added in v0.18.0

Verify checks these client extension outputs against the extensions recorded in the session.

Two rules are enforced. First, every present output must correspond to an extension the Relying Party requested; keys of AuthenticationExtensionsClientOutputs.Extra participate on equal terms with the modelled members. This subsumes ceremony applicability, because an output that cannot be requested for a ceremony cannot have been requested at all. Second, a registration that required large blob support must have received it.

Every problem found is reported rather than only the first. The result is an Error whose details name every problem and whose cause is the errors.Join of them, so errors.As and errors.Is reach each one individually.

A ceremony which is neither CreateCeremony nor AssertCeremony is treated as a registration, so an unexpected value fails closed against the required large blob support assertion rather than skipping it.

The appid value path is not handled here; see ParsedPublicKeyCredential.GetAppID.

Specification: §7.1. Registering a New Credential (https://www.w3.org/TR/webauthn-3/#sctn-registering-a-new-credential)

Specification: §7.2. Verifying an Authentication Assertion (https://www.w3.org/TR/webauthn-3/#sctn-verifying-assertion)

type AuthenticatorAssertionResponse

type AuthenticatorAssertionResponse struct {
	AuthenticatorResponse

	AuthenticatorData URLEncodedBase64 `json:"authenticatorData"`
	Signature         URLEncodedBase64 `json:"signature"`
	UserHandle        URLEncodedBase64 `json:"userHandle,omitempty"`
}

The AuthenticatorAssertionResponse contains the raw authenticator assertion data and is parsed into ParsedAssertionResponse.

type AuthenticatorAttachment

type AuthenticatorAttachment string

AuthenticatorAttachment represents the IDL enum of the same name, and is used as part of the Authenticator Selection Criteria.

This enumeration’s values describe authenticators' attachment modalities. Relying Parties use this to express a preferred authenticator attachment modality when calling navigator.credentials.create() to create a credential.

If this member is present, eligible authenticators are filtered to only authenticators attached with the specified §5.4.5 Authenticator Attachment Enumeration (enum AuthenticatorAttachment). The value SHOULD be a member of AuthenticatorAttachment but client platforms MUST ignore unknown values, treating an unknown value as if the member does not exist.

Specification: §5.4.4. Authenticator Selection Criteria (https://www.w3.org/TR/webauthn/#dom-authenticatorselectioncriteria-authenticatorattachment)

Specification: §5.4.5. Authenticator Attachment Enumeration (https://www.w3.org/TR/webauthn/#enum-attachment)

const (
	// Platform represents a platform authenticator is attached using a client device-specific transport, called
	// platform attachment, and is usually not removable from the client device. A public key credential bound to a
	// platform authenticator is called a platform credential.
	Platform AuthenticatorAttachment = "platform"

	// CrossPlatform represents a roaming authenticator is attached using cross-platform transports, called
	// cross-platform attachment. Authenticators of this class are removable from, and can "roam" among, client devices.
	// A public key credential bound to a roaming authenticator is called a roaming credential.
	CrossPlatform AuthenticatorAttachment = "cross-platform"
)

type AuthenticatorAttestationResponse

type AuthenticatorAttestationResponse struct {
	// The byte slice of clientDataJSON, which becomes CollectedClientData.
	AuthenticatorResponse

	Transports []string `json:"transports,omitempty"`

	AuthenticatorData URLEncodedBase64 `json:"authenticatorData"`

	PublicKey URLEncodedBase64 `json:"publicKey"`

	PublicKeyAlgorithm int64 `json:"publicKeyAlgorithm"`

	// AttestationObject is the byte slice version of attestationObject.
	// This attribute contains an attestation object, which is opaque to, and
	// cryptographically protected against tampering by, the client. The
	// attestation object contains both authenticator data and an attestation
	// statement. The former contains the AAGUID, a unique credential ID, and
	// the credential public key. The contents of the attestation statement are
	// determined by the attestation statement format used by the authenticator.
	// It also contains any additional information that the Relying Party's server
	// requires to validate the attestation statement, as well as to decode and
	// validate the authenticator data along with the JSON-serialized client data.
	AttestationObject URLEncodedBase64 `json:"attestationObject"`
}

AuthenticatorAttestationResponse is the initial unpacked 'response' object received by the relying party. This contains the clientDataJSON object, which will be marshalled into CollectedClientData, and the 'attestationObject', which contains information about the authenticator, and the newly minted public key credential. The information in both objects are used to verify the authenticity of the ceremony and new credential.

See: https://www.w3.org/TR/webauthn/#typedefdef-publickeycredentialjson

func (*AuthenticatorAttestationResponse) Parse

Parse the values returned in the authenticator response and perform attestation verification Step 8. This returns a fully decoded struct with the data put into a format that can be used to verify the user and credential that was created.

type AuthenticatorData

type AuthenticatorData struct {
	RPIDHash []byte                         `json:"rpid"`
	Flags    AuthenticatorFlags             `json:"flags"`
	Counter  uint32                         `json:"sign_count"`
	AttData  AttestedCredentialData         `json:"att_data"`
	ExtData  []byte                         `json:"ext_data"`
	Ext      *AuthenticatorExtensionOutputs `json:"ext,omitempty"`
}

AuthenticatorData represents the IDL with the same name.

The authenticator data structure encodes contextual bindings made by the authenticator. These bindings are controlled by the authenticator itself, and derive their trust from the WebAuthn Relying Party's assessment of the security properties of the authenticator. In one extreme case, the authenticator may be embedded in the client, and its bindings may be no more trustworthy than the client data. At the other extreme, the authenticator may be a discrete entity with high-security hardware and software, connected to the client over a secure channel. In both cases, the Relying Party receives the authenticator data in the same format, and uses its knowledge of the authenticator to make trust decisions.

The authenticator data has a compact but extensible encoding. This is desired since authenticators can be devices with limited capabilities and low power requirements, with much simpler software stacks than the client platform.

Specification: §6.1. Authenticator Data (https://www.w3.org/TR/webauthn/#sctn-authenticator-data)

func (*AuthenticatorData) Unmarshal

func (a *AuthenticatorData) Unmarshal(rawAuthData []byte) (err error)

Unmarshal will take the raw Authenticator Data and marshals it into AuthenticatorData for further validation. The authenticator data has a compact but extensible encoding. This is desired since authenticators can be devices with limited capabilities and low power requirements, with much simpler software stacks than the client platform. The authenticator data structure is a byte array of 37 bytes or more, and is laid out in this table: https://www.w3.org/TR/webauthn/#table-authData

func (*AuthenticatorData) Verify

func (a *AuthenticatorData) Verify(rpIdHash []byte, appIDHash []byte, userVerificationRequired bool, userPresenceRequired bool) (err error)

Verify on AuthenticatorData handles Steps 13 through 15 & 17 for Registration and Steps 15 through 18 for Assertion.

A non-empty appIDHash replaces rpIdHash as the sole expected value rather than being accepted alongside it. It must therefore only be supplied when the FIDO AppID Extension was requested by the Relying Party and the client reported having acted on it, which for an assertion is what ParsedPublicKeyCredential.GetAppID determines from the session data. Callers with no appid in play, such as registration, pass nil.

Specification: §10.1.1. FIDO AppID Extension (https://www.w3.org/TR/webauthn-3/#sctn-appid-extension)

type AuthenticatorExtensionOutputs added in v0.18.0

type AuthenticatorExtensionOutputs struct {
	// CredProtect is the credential protection policy applied to the credential. Registration only.
	CredProtect *CredentialProtectionPolicy `json:"credProtect,omitempty"`

	// MinPinLength is the authenticator's current minimum PIN length. Registration only.
	MinPinLength *uint `json:"minPinLength,omitempty"`

	// CredBlobSet reports whether the requested blob was stored. Registration only.
	CredBlobSet *bool `json:"-"`

	// CredBlob is the blob stored with the credential. Authentication only.
	CredBlob []byte `json:"credBlob,omitempty"`

	// HMACSecret reports whether the hmac-secret was provisioned. Registration only.
	HMACSecret *bool `json:"-"`

	// HMACSecretOutput is the encrypted hmac-secret output. Authentication only.
	HMACSecretOutput []byte `json:"-"`

	// UVM reports the user verification methods used for the operation.
	UVM []UserVerificationMethod `json:"uvm,omitempty"`

	// Extra carries authenticator extension outputs this library does not model, and the values of modelled
	// extensions that arrived with an unexpected type.
	Extra map[string]any `json:"-"`
}

AuthenticatorExtensionOutputs is the decoded form of the extension outputs carried in the authenticator data. WebAuthn Level 3 defines no authenticator extensions; every member below is defined by CTAP 2.1 or CTAP 2.2 and registered in the IANA "WebAuthn Extension Identifiers" registry.

Specification: §6.1. Authenticator Data (https://www.w3.org/TR/webauthn-3/#sctn-authenticator-data)

Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

func ParseAuthenticatorExtensionOutputs added in v0.18.0

func ParseAuthenticatorExtensionOutputs(data []byte) (out *AuthenticatorExtensionOutputs, err error)

ParseAuthenticatorExtensionOutputs decodes the CBOR extension outputs from the authenticator data.

A structurally invalid encoding is an error, as the data is signed and malformation indicates something is genuinely wrong. A recognised identifier carrying an unexpected type is preserved in AuthenticatorExtensionOutputs.Extra without an error, so a single non-conforming authenticator cannot fail every ceremony it participates in.

func (*AuthenticatorExtensionOutputs) Verify added in v0.18.0

Verify checks these authenticator extension outputs against the extensions recorded in the session.

A nil receiver is valid and means the authenticator returned no extension outputs at all, which is itself a failure when a credential protection policy was requested with enforcement.

Two rules are enforced, both of which apply only to registration. The credProtect policy must be honoured when enforcement was requested, and a blob submitted for storage with the credential must actually have been stored. Every problem found is reported rather than only the first, matching AuthenticationExtensionsClientOutputs.Verify.

CTAP requires the client to fail the ceremony when 'enforceCredentialProtectionPolicy' is set and the authenticator cannot honour the requested policy, but the Relying Party is the only party that can confirm this independently, and unlike the client extension outputs the authenticator data is signed, so the values checked here are covered by the attestation signature.

The applied policy is compared as at-least-as-strict rather than equal, because an authenticator is permitted to apply a stricter policy than the one requested, for instance where its own default exceeds the request.

A ceremony which is neither CreateCeremony nor AssertCeremony is treated as a registration, matching AuthenticationExtensionsClientOutputs.Verify, so an unexpected value fails closed rather than skipping the assertions.

Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

type AuthenticatorFlags

type AuthenticatorFlags byte

AuthenticatorFlags A byte of information returned during during ceremonies in the authenticatorData that contains bits that give us information about the whether the user was present and/or verified during authentication, and whether there is attestation or extension data present. Bit 0 is the least significant bit.

Specification: §6.1. Authenticator Data - Flags (https://www.w3.org/TR/webauthn/#flags)

const (
	// FlagUserPresent Bit 00000001 in the byte sequence. Tells us if user is present. Also referred to as the UP flag.
	FlagUserPresent AuthenticatorFlags = 1 << iota // Referred to as UP.

	// FlagRFU1 is a reserved for future use flag.
	FlagRFU1

	// FlagUserVerified Bit 00000100 in the byte sequence. Tells us if user is verified
	// by the authenticator using a biometric or PIN. Also referred to as the UV flag.
	FlagUserVerified

	// FlagBackupEligible Bit 00001000 in the byte sequence. Tells us if a backup is eligible for device. Also referred
	// to as the BE flag.
	FlagBackupEligible // Referred to as BE.

	// FlagBackupState Bit 00010000 in the byte sequence. Tells us if a backup state for device. Also referred to as the
	// BS flag.
	FlagBackupState

	// FlagRFU2 is a reserved for future use flag.
	FlagRFU2

	// FlagAttestedCredentialData Bit 01000000 in the byte sequence. Indicates whether
	// the authenticator added attested credential data. Also referred to as the AT flag.
	FlagAttestedCredentialData

	// FlagHasExtensions Bit 10000000 in the byte sequence. Indicates if the authenticator data has extensions. Also
	// referred to as the ED flag.
	FlagHasExtensions
)

The bits that do not have flags are reserved for future use.

func (AuthenticatorFlags) HasAttestedCredentialData

func (flag AuthenticatorFlags) HasAttestedCredentialData() bool

HasAttestedCredentialData returns if the AT flag was set.

func (AuthenticatorFlags) HasBackupEligible added in v0.6.0

func (flag AuthenticatorFlags) HasBackupEligible() bool

HasBackupEligible returns if the BE flag was set.

func (AuthenticatorFlags) HasBackupState added in v0.6.0

func (flag AuthenticatorFlags) HasBackupState() bool

HasBackupState returns if the BS flag was set.

func (AuthenticatorFlags) HasExtensions

func (flag AuthenticatorFlags) HasExtensions() bool

HasExtensions returns if the ED flag was set.

func (AuthenticatorFlags) HasUserPresent added in v0.7.2

func (flag AuthenticatorFlags) HasUserPresent() bool

HasUserPresent returns if the UP flag was set.

func (AuthenticatorFlags) HasUserVerified added in v0.7.2

func (flag AuthenticatorFlags) HasUserVerified() bool

HasUserVerified returns if the UV flag was set.

func (AuthenticatorFlags) UserPresent

func (flag AuthenticatorFlags) UserPresent() bool

UserPresent returns if the UP flag was set.

func (AuthenticatorFlags) UserVerified

func (flag AuthenticatorFlags) UserVerified() bool

UserVerified returns if the UV flag was set.

type AuthenticatorResponse

type AuthenticatorResponse struct {
	// From the spec https://www.w3.org/TR/webauthn/#dom-authenticatorresponse-clientdatajson
	// This attribute contains a JSON serialization of the client data passed to the authenticator
	// by the client in its call to either create() or get().
	ClientDataJSON URLEncodedBase64 `json:"clientDataJSON"`
}

AuthenticatorResponse represents the IDL with the same name.

Authenticators respond to Relying Party requests by returning an object derived from the AuthenticatorResponse interface

Specification: §5.2. Authenticator Responses (https://www.w3.org/TR/webauthn/#iface-authenticatorresponse)

type AuthenticatorSelection

type AuthenticatorSelection struct {
	// AuthenticatorAttachment If this member is present, eligible authenticators are filtered to only
	// authenticators attached with the specified AuthenticatorAttachment enum.
	AuthenticatorAttachment AuthenticatorAttachment `json:"authenticatorAttachment,omitempty"`

	// RequireResidentKey this member describes the Relying Party's requirements regarding resident
	// credentials. If the parameter is set to true, the authenticator MUST create a client-side-resident
	// public key credential source when creating a public key credential.
	RequireResidentKey *bool `json:"requireResidentKey,omitempty"`

	// ResidentKey this member describes the Relying Party's requirements regarding resident
	// credentials per Webauthn Level 2.
	ResidentKey ResidentKeyRequirement `json:"residentKey,omitempty"`

	// UserVerification This member describes the Relying Party's requirements regarding user verification for
	// the create() operation. Eligible authenticators are filtered to only those capable of satisfying this
	// requirement.
	UserVerification UserVerificationRequirement `json:"userVerification,omitempty"`
}

AuthenticatorSelection represents the AuthenticatorSelectionCriteria IDL.

WebAuthn Relying Parties may use the AuthenticatorSelectionCriteria dictionary to specify their requirements regarding authenticator attributes.

Specification: §5.4.4. Authenticator Selection Criteria (https://www.w3.org/TR/webauthn/#dictionary-authenticatorSelection)

func (AuthenticatorSelection) IsZero added in v0.18.0

func (s AuthenticatorSelection) IsZero() bool

IsZero returns true when no authenticator selection criteria are set. It is used by the encoding/json omitzero tag option so a Relying Party that expresses no criteria does not send an empty authenticatorSelection member to the client, which omitempty cannot do for a struct value.

type AuthenticatorTransport

type AuthenticatorTransport string

AuthenticatorTransport represents the IDL enum with the same name.

Authenticators may implement various transports for communicating with clients. This enumeration defines hints as to how clients might communicate with a particular authenticator in order to obtain an assertion for a specific credential. Note that these hints represent the WebAuthn Relying Party's best belief as to how an authenticator may be reached. A Relying Party will typically learn of the supported transports for a public key credential via getTransports().

Specification: §5.8.4. Authenticator Transport Enumeration (https://www.w3.org/TR/webauthn/#enumdef-authenticatortransport)

const (
	// USB indicates the respective authenticator can be contacted over removable USB.
	USB AuthenticatorTransport = "usb"

	// NFC indicates the respective authenticator can be contacted over Near Field Communication (NFC).
	NFC AuthenticatorTransport = "nfc"

	// BLE indicates the respective authenticator can be contacted over Bluetooth Smart (Bluetooth Low Energy / BLE).
	BLE AuthenticatorTransport = "ble"

	// SmartCard indicates the respective authenticator can be contacted over ISO/IEC 7816 smart card with contacts.
	//
	// WebAuthn Level 3.
	SmartCard AuthenticatorTransport = "smart-card"

	// Hybrid indicates the respective authenticator can be contacted using a combination of (often separate)
	// data-transport and proximity mechanisms. This supports, for example, authentication on a desktop computer using
	// a smartphone.
	//
	// WebAuthn Level 3.
	Hybrid AuthenticatorTransport = "hybrid"

	// Internal indicates the respective authenticator is contacted using a client device-specific transport, i.e., it
	// is a platform authenticator. These authenticators are not removable from the client device.
	Internal AuthenticatorTransport = "internal"
)

type CeremonyType

type CeremonyType string

CeremonyType represents the type of WebAuthn ceremony being performed.

Specification: §5.8.1. Client Data Used in WebAuthn Signatures (https://www.w3.org/TR/webauthn/#dom-collectedclientdata-type)

const (
	// CreateCeremony is the ceremony type for credential registration ("webauthn.create").
	CreateCeremony CeremonyType = "webauthn.create"

	// AssertCeremony is the ceremony type for authentication assertion ("webauthn.get").
	AssertCeremony CeremonyType = "webauthn.get"
)

type ClientCapabilities added in v0.18.0

type ClientCapabilities map[ClientCapability]bool

ClientCapabilities represents the record a client returns from PublicKeyCredential.getClientCapabilities(), which maps a capability to whether the client currently supports it.

It is a map rather than a struct so a capability this release does not model, including every extension key, survives a round trip through the Relying Party's own transport rather than being dropped on the way in.

Read it with ClientCapabilities.Supported rather than by indexing. A key which is absent from the record is not the same as a key reported false: the specification allows no assumption about the availability of a feature the client did not mention, and indexing a Go map cannot express that difference.

Specification: §5.1.7. Availability of client capabilities (https://www.w3.org/TR/webauthn-3/#sctn-getClientCapabilities)

func (ClientCapabilities) Extension added in v0.18.0

func (c ClientCapabilities) Extension(identifier string) (supported, reported bool)

Extension reports whether the client stated support for the extension with the given identifier, under the same two value contract as ClientCapabilities.Supported. The identifier is resolved with ExtensionClientCapability, so an argument which already carries ClientCapabilityExtensionPrefix is accepted as it stands.

An empty identifier reports nothing, since the prefix alone names no extension.

func (ClientCapabilities) Supported added in v0.18.0

func (c ClientCapabilities) Supported(capability ClientCapability) (supported, reported bool)

Supported reports whether the client stated support for the given capability, and whether it mentioned the capability at all. A reported value of false means the client stated it does not support the capability; a reported value of false with ok false means the client said nothing, which licenses no conclusion either way.

type ClientCapability added in v0.18.0

type ClientCapability string

ClientCapability represents an entry of the ClientCapability enumeration, which names a capability a client may report through PublicKeyCredential.getClientCapabilities(). A Relying Party typically has the client send the result to the server so it can pick a ceremony the client can actually complete, for example offering conditional mediation only where it is available.

The IDL types the keys of the reported record as DOMString rather than as this enumeration, so a value which is not one of the constants below is not an error: a client may report a capability ratified after this release, and it also reports one key per supported extension, named by ExtensionClientCapability. Values are therefore deliberately not validated, which is the same call PublicKeyCredentialHints makes for the same reason.

What a client reports is advisory. It is a statement by software the Relying Party does not control, sent over a channel the Relying Party does not control, so it belongs in flow selection and never in a security decision. The ceremony verification steps are what establish security properties.

WebAuthn Level 3.

Specification: §5.8.7. Client Capability Enumeration (https://www.w3.org/TR/webauthn-3/#enum-clientCapability)

const (
	// ClientCapabilityConditionalCreate indicates the client supports conditionally mediated registration, i.e. a
	// create() call with a mediation of conditional.
	ClientCapabilityConditionalCreate ClientCapability = "conditionalCreate"

	// ClientCapabilityConditionalGet indicates the client supports conditionally mediated authentication, i.e. a
	// get() call with a mediation of conditional, which is what backs autofill of a passkey.
	ClientCapabilityConditionalGet ClientCapability = "conditionalGet"

	// ClientCapabilityHybridTransport indicates the client supports the hybrid transport, i.e. using a nearby
	// device such as a phone as an authenticator.
	ClientCapabilityHybridTransport ClientCapability = "hybridTransport"

	// ClientCapabilityPasskeyPlatformAuthenticator indicates a passkey capable platform authenticator is available,
	// whether attached to the client device or reachable over the hybrid transport.
	ClientCapabilityPasskeyPlatformAuthenticator ClientCapability = "passkeyPlatformAuthenticator"

	// ClientCapabilityUserVerifyingPlatformAuthenticator indicates a user verifying platform authenticator is
	// available on the client device.
	ClientCapabilityUserVerifyingPlatformAuthenticator ClientCapability = "userVerifyingPlatformAuthenticator"

	// ClientCapabilityRelatedOrigins indicates the client supports Related Origin Requests, i.e. that it will read
	// the document a Relying Party serves at [WellKnownPathWebAuthn].
	//
	// Specification: §5.11. Related Origin Requests (https://www.w3.org/TR/webauthn-3/#sctn-related-origins)
	ClientCapabilityRelatedOrigins ClientCapability = "relatedOrigins"

	// ClientCapabilitySignalAllAcceptedCredentials indicates the client supports the
	// signalAllAcceptedCredentials() method.
	ClientCapabilitySignalAllAcceptedCredentials ClientCapability = "signalAllAcceptedCredentials"

	// ClientCapabilitySignalCurrentUserDetails indicates the client supports the signalCurrentUserDetails() method.
	ClientCapabilitySignalCurrentUserDetails ClientCapability = "signalCurrentUserDetails"

	// ClientCapabilitySignalUnknownCredential indicates the client supports the signalUnknownCredential() method.
	ClientCapabilitySignalUnknownCredential ClientCapability = "signalUnknownCredential"
)

func ExtensionClientCapability added in v0.18.0

func ExtensionClientCapability(identifier string) ClientCapability

ExtensionClientCapability returns the capability under which a client reports support for the extension with the given identifier, for example ExtensionPRF becoming "extension:prf".

An identifier which already carries ClientCapabilityExtensionPrefix is returned unchanged rather than prefixed twice, so a caller which passes a key read straight out of a record gets the key back. An empty identifier, with or without the prefix, yields an empty capability: the prefix alone names no extension.

func (ClientCapability) Extension added in v0.18.0

func (c ClientCapability) Extension() (identifier string, ok bool)

Extension reports whether this capability names an extension, and if so the identifier of that extension. It is the inverse of ExtensionClientCapability, and is how a Relying Party walking a whole record tells the extension keys apart from the capabilities of ClientCapabilities.

The bare prefix with no identifier after it names no extension and reports false.

type CollectedClientData

type CollectedClientData struct {
	// Type contains the string "webauthn.create" when creating new credentials, and "webauthn.get" when getting an
	// assertion from an existing credential. The purpose of this member is to prevent certain types of signature
	// confusion attacks (where an attacker substitutes one legitimate signature for another).
	Type CeremonyType `json:"type"`

	// Challenge contains the base64url encoding of the challenge provided by the Relying Party.
	Challenge string `json:"challenge"`

	// Origin contains the fully qualified origin of the requester, as provided to the authenticator by the client.
	Origin string `json:"origin"`

	// TopOrigin contains the fully qualified top-level origin of the requester when the client is cross-origin.
	// This is only present when CrossOrigin is true.
	//
	// WebAuthn Level 3.
	TopOrigin string `json:"topOrigin,omitempty"`

	// CrossOrigin indicates whether the calling context is an iframe that is not same-origin with its ancestor.
	//
	// WebAuthn Level 3.
	CrossOrigin bool `json:"crossOrigin,omitempty"`

	// TokenBinding contains information about the state of the Token Binding protocol.
	//
	// WebAuthn Level 3 removes this member from the CollectedClientData dictionary. It is retained because a client
	// implementing Level 1 or Level 2 may still include it, and a member present in the client data has to be
	// modelled to be validated; it is not something a Relying Party should expect to receive.
	//
	// Deprecated: removed from the CollectedClientData dictionary by WebAuthn Level 3.
	TokenBinding *TokenBinding `json:"tokenBinding,omitempty"`

	// Hint is an opaque field that may be added by the client. Chromium-based browsers include this field to remind
	// implementers not to perform string comparison on the clientDataJSON.
	Hint string `json:"new_keys_may_be_added_here,omitempty"`
}

CollectedClientData represents the contextual bindings of both the WebAuthn Relying Party and the client. It is a key-value mapping whose keys are strings. Values can be any type that has a valid encoding in JSON. Its structure is defined by the following Web IDL.

Specification: §5.8.1. Client Data Used in WebAuthn Signatures (https://www.w3.org/TR/webauthn/#dictdef-collectedclientdata)

func (*CollectedClientData) Verify

func (c *CollectedClientData) Verify(storedChallenge string, ceremony CeremonyType, rpOrigins, rpOpaqueOrigins, rpTopOrigins []string, rpTopOriginsVerify TopOriginVerificationMode, allowCrossOrigin bool) (err error)

Verify handles steps 3 through 6 of verifying the registering client data of a new credential and steps 7 through 10 of verifying an authentication assertion See https://www.w3.org/TR/webauthn/#registering-a-new-credential and https://www.w3.org/TR/webauthn/#verifying-assertion

Note: the rpTopOriginsVerify parameter does not accept the TopOriginVerificationMode value of TopOriginDefaultVerificationMode as it's expected this value is updated by the config validation process.

The rpOpaqueOrigins parameter carries the origins which are not http or https tuple origins, i.e. those for which IsOpaqueOrigin returns true. They widen the set the ceremony origin is matched against, and only that set; the Top Origin is deliberately never matched against them as a Top Origin is by definition the origin of a top-level browsing context. They are matched by IsOpaqueOriginInHaystack, i.e. by simple string comparison, never by the origin equality semantics applied to the rpOrigins parameter.

type CompoundPolicy added in v0.18.0

type CompoundPolicy struct {
	// SubStatementScope selects the sub-statements of the compound attestation which must be verified for the
	// attestation to be accepted.
	SubStatementScope CompoundSubStatementScope
}

CompoundPolicy configures the Compound Attestation Statement Format verification procedure.

Specification: §8.9. Compound Attestation Statement Format (https://www.w3.org/TR/webauthn-3/#sctn-compound-attestation)

type CompoundSubStatementScope added in v0.18.0

type CompoundSubStatementScope int

CompoundSubStatementScope selects the sub-statements of a compound attestation which must be verified for the attestation to be accepted.

§8.9 assigns this choice to the Relying Party: the handling of a sub-statement which fails verification, and the number of sub-statements which must succeed, are matters of Relying Party policy.

The scope applies only to the outcome of the verification procedures. The syntax of the compound statement itself is not a matter of policy, so a statement which doesn't satisfy the §8.9 CDDL, nests a compound sub-statement, or names a format this library doesn't implement is rejected under every scope.

Specification: §8.9. Compound Attestation Statement Format (https://www.w3.org/TR/webauthn-3/#sctn-compound-attestation)

const (
	// CompoundSubStatementScopeDefault is the zero value of [CompoundSubStatementScope] and has no matching rule in
	// §8.9. It evaluates as [CompoundSubStatementScopeAll] wherever it is used. webauthn.Config rewrites it to that
	// explicit constant during validation, so a Relying Party can tell an unset field apart from a deliberate choice
	// of the same scope.
	CompoundSubStatementScopeDefault CompoundSubStatementScope = iota

	// CompoundSubStatementScopeAll requires every sub-statement to be verified, and rejects the attestation on the
	// first sub-statement which fails.
	CompoundSubStatementScopeAll

	// CompoundSubStatementScopeAny requires a single sub-statement to be verified, and rejects the attestation only
	// when none of them can be. A sub-statement is verified when its format's verification procedure succeeds and
	// the trust path it produces is accepted by the Metadata Service, so a failure of either is tolerated provided
	// another sub-statement satisfies both.
	CompoundSubStatementScopeAny
)

type ConveyancePreference

type ConveyancePreference string

ConveyancePreference is the type representing the AttestationConveyancePreference IDL.

WebAuthn Relying Parties may use AttestationConveyancePreference to specify their preference regarding attestation conveyance during credential generation.

Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#enum-attestation-convey)

const (
	// PreferNoAttestation is a ConveyancePreference value.
	//
	// This value indicates that the Relying Party is not interested in authenticator attestation. For example, in order
	// to potentially avoid having to obtain user consent to relay identifying information to the Relying Party, or to
	// save a round trip to an Attestation CA or Anonymization CA.
	//
	// This is the default value.
	//
	// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-none)
	PreferNoAttestation ConveyancePreference = none

	// PreferIndirectAttestation is a ConveyancePreference value.
	//
	// This value indicates that the Relying Party prefers an attestation conveyance yielding verifiable attestation
	// statements, but allows the client to decide how to obtain such attestation statements. The client MAY replace the
	// authenticator-generated attestation statements with attestation statements generated by an Anonymization CA, in
	// order to protect the user’s privacy, or to assist Relying Parties with attestation verification in a
	// heterogeneous ecosystem.
	//
	// Note: There is no guarantee that the Relying Party will obtain a verifiable attestation statement in this case.
	// For example, in the case that the authenticator employs self attestation.
	//
	// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-indirect)
	PreferIndirectAttestation ConveyancePreference = "indirect"

	// PreferDirectAttestation is a ConveyancePreference value.
	//
	// This value indicates that the Relying Party wants to receive the attestation statement as generated by the
	// authenticator.
	//
	// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-direct)
	PreferDirectAttestation ConveyancePreference = "direct"

	// PreferEnterpriseAttestation is a ConveyancePreference value.
	//
	// This value indicates that the Relying Party wants to receive an attestation statement that may include uniquely
	// identifying information. This is intended for controlled deployments within an enterprise where the organization
	// wishes to tie registrations to specific authenticators. User agents MUST NOT provide such an attestation unless
	// the user agent or authenticator configuration permits it for the requested RP ID.
	//
	// If permitted, the user agent SHOULD signal to the authenticator (at invocation time) that enterprise
	// attestation is requested, and convey the resulting AAGUID and attestation statement, unaltered, to the Relying
	// Party.
	//
	// Specification: §5.4.7. Attestation Conveyance Preference Enumeration (https://www.w3.org/TR/webauthn/#dom-attestationconveyancepreference-enterprise)
	PreferEnterpriseAttestation ConveyancePreference = "enterprise"
)

type Credential

type Credential struct {
	// ID is The credential’s identifier. The requirements for the
	// identifier are distinct for each type of credential. It might
	// represent a username for username/password tuples, for example.
	ID string `json:"id"`
	// Type is the value of the object’s interface object's [[type]] slot,
	// which specifies the credential type represented by this object.
	// This should be type "public-key" for Webauthn credentials.
	Type string `json:"type"`
}

Credential is the basic credential type from the Credential Management specification that is inherited by WebAuthn's PublicKeyCredential type.

Specification: Credential Management §2.2. The Credential Interface (https://www.w3.org/TR/credential-management/#credential)

type CredentialAssertion

type CredentialAssertion struct {
	Response  PublicKeyCredentialRequestOptions `json:"publicKey"`
	Mediation CredentialMediationRequirement    `json:"mediation,omitempty"`
}

CredentialAssertion is the top-level request object for credential assertion (login). It wraps PublicKeyCredentialRequestOptions and an optional mediation requirement. This is the object that should be serialized and sent to the client to initiate the navigator.credentials.get() call.

Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dictionary-assertion-options)

type CredentialAssertionResponse

type CredentialAssertionResponse struct {
	PublicKeyCredential

	AssertionResponse AuthenticatorAssertionResponse `json:"response"`
}

The CredentialAssertionResponse is the raw response returned to the Relying Party from an authenticator when we request a credential for login/assertion.

func (CredentialAssertionResponse) Parse added in v0.8.2

Parse validates and parses the CredentialAssertionResponse into a ParsedCredentialAssertionData. Most implementations should use ParseCredentialRequestResponse, ParseCredentialRequestResponseBody, or ParseCredentialRequestResponseBytes instead of calling this method directly.

type CredentialCreation

type CredentialCreation struct {
	Response  PublicKeyCredentialCreationOptions `json:"publicKey"`
	Mediation CredentialMediationRequirement     `json:"mediation,omitempty"`
}

CredentialCreation is the top-level request object for credential registration. It wraps PublicKeyCredentialCreationOptions and an optional mediation requirement. This is the object that should be serialized and sent to the client to initiate the navigator.credentials.create() call.

Specification: §5.4. Options for Credential Creation (https://www.w3.org/TR/webauthn/#dictionary-makecredentialoptions)

type CredentialCreationResponse

type CredentialCreationResponse struct {
	PublicKeyCredential

	AttestationResponse AuthenticatorAttestationResponse `json:"response"`
}

CredentialCreationResponse is the raw response returned to the Relying Party from the client for a credential registration ceremony. It contains the AuthenticatorAttestationResponse which holds the attestation object and client data.

Specification: §5.4. Options for Credential Creation (https://www.w3.org/TR/webauthn/#sctn-credentialcreationoptions-extension)

func (CredentialCreationResponse) Parse added in v0.8.2

Parse validates and parses the CredentialCreationResponse into a ParsedCredentialCreationData. This receiver is unlikely to be expressly guaranteed under the versioning policy. Users looking for this guarantee should see ParseCredentialCreationResponseBody instead, and this receiver should only be used if that function is inadequate for their use case.

type CredentialDescriptor

type CredentialDescriptor struct {
	// The valid credential types.
	Type CredentialType `json:"type"`

	// CredentialID The ID of a credential to allow/disallow.
	CredentialID URLEncodedBase64 `json:"id"`

	// The authenticator transports that can be used.
	Transport []AuthenticatorTransport `json:"transports,omitempty"`

	// AttestationType is the attestation type from the originating Credential (one of "basic_full",
	// "basic_surrogate", "attca", "anonca", "ecdaa", "none"). Used internally only; not serialized.
	AttestationType string `json:"-"`

	// AttestationFormat is the attestation statement format from the originating Credential (one of "packed",
	// "tpm", "android-key", "android-safetynet", "fido-u2f", "apple", "compound", "none"). Used internally only;
	// not serialized. Prior releases overloaded [CredentialDescriptor.AttestationType] with this value; callers
	// that construct descriptors directly should populate this field instead.
	AttestationFormat string `json:"-"`
}

CredentialDescriptor represents the PublicKeyCredentialDescriptor IDL.

This dictionary contains the attributes that are specified by a caller when referring to a public key credential as an input parameter to the create() or get() methods. It mirrors the fields of the PublicKeyCredential object returned by the latter methods.

Specification: §5.10.3. Credential Descriptor (https://www.w3.org/TR/webauthn/#credential-dictionary)

func (CredentialDescriptor) SignalUnknownCredential added in v0.16.0

func (c CredentialDescriptor) SignalUnknownCredential(rpid string) *SignalUnknownCredential

type CredentialEntity

type CredentialEntity struct {
	// A human-palatable name for the entity. Its function depends on what the PublicKeyCredentialEntity represents:
	//
	// When inherited by PublicKeyCredentialRpEntity it is a human-palatable identifier for the Relying Party,
	// intended only for display. For example, "ACME Corporation", "Wonderful Widgets, Inc." or "ОАО Примертех".
	//
	// When inherited by PublicKeyCredentialUserEntity, it is a human-palatable identifier for a user account. It is
	// intended only for display, i.e., aiding the user in determining the difference between user accounts with similar
	// displayNames. For example, "alexm", "alex.p.mueller@example.com" or "+14255551234".
	Name string `json:"name"`
}

CredentialEntity represents the PublicKeyCredentialEntity IDL and it describes a user account, or a WebAuthn Relying Party with which a public key credential is associated.

Specification: §5.4.1. Public Key Entity Description (https://www.w3.org/TR/webauthn/#dictionary-pkcredentialentity)

type CredentialMediationRequirement added in v0.12.0

type CredentialMediationRequirement string

CredentialMediationRequirement represents mediation requirements for clients. When making a request via get(options) or create(options), developers can set a case-by-case requirement for user mediation by choosing the appropriate CredentialMediationRequirement enum value.

See https://www.w3.org/TR/credential-management-1/#mediation-requirements

const (
	// MediationDefault lets the browser choose the mediation flow completely as if it wasn't specified at all.
	MediationDefault CredentialMediationRequirement = ""

	// MediationSilent indicates user mediation is suppressed for the given operation. If the operation can be performed
	// without user involvement, wonderful. If user involvement is necessary, then the operation will return null rather
	// than involving the user.
	MediationSilent CredentialMediationRequirement = "silent"

	// MediationOptional indicates if credentials can be handed over for a given operation without user mediation, they
	// will be. If user mediation is required, then the user agent will involve the user in the decision.
	MediationOptional CredentialMediationRequirement = "optional"

	// MediationConditional indicates for get(), discovered credentials are presented to the user in a non-modal dialog
	// along with an indication of the origin which is requesting credentials. If the user makes a gesture outside of
	// the dialog, the dialog closes without resolving or rejecting the Promise returned by the get() method and without
	// causing a user-visible error condition. If the user makes a gesture that selects a credential, that credential is
	// returned to the caller. The prevent silent access flag is treated as being true regardless of its actual value:
	// the conditional behavior always involves user mediation of some sort if applicable credentials are discovered.
	MediationConditional CredentialMediationRequirement = "conditional"

	// MediationRequired indicates the user agent will not hand over credentials without user mediation, even if the
	// prevent silent access flag is unset for an origin.
	MediationRequired CredentialMediationRequirement = "required"
)

type CredentialParameter

type CredentialParameter struct {
	Type      CredentialType                       `json:"type" msg:"typ,omitempty"`
	Algorithm webauthncose.COSEAlgorithmIdentifier `json:"alg" msg:"alg,omitempty"`
}

CredentialParameter is the credential type and algorithm that the relying party wants the authenticator to create.

func (*CredentialParameter) DecodeMsg added in v0.16.2

func (z *CredentialParameter) DecodeMsg(dc *msgp.Reader) (err error)

DecodeMsg implements msgp.Decodable

func (CredentialParameter) EncodeMsg added in v0.16.2

func (z CredentialParameter) EncodeMsg(en *msgp.Writer) (err error)

EncodeMsg implements msgp.Encodable

func (CredentialParameter) MarshalMsg added in v0.16.2

func (z CredentialParameter) MarshalMsg(b []byte) (o []byte, err error)

MarshalMsg implements msgp.Marshaler

func (CredentialParameter) Msgsize added in v0.16.2

func (z CredentialParameter) Msgsize() (s int)

Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message

func (*CredentialParameter) UnmarshalMsg added in v0.16.2

func (z *CredentialParameter) UnmarshalMsg(bts []byte) (o []byte, err error)

UnmarshalMsg implements msgp.Unmarshaler

type CredentialPropertiesOutput added in v0.18.0

type CredentialPropertiesOutput struct {
	// RK reports whether the created credential is a client-side discoverable credential. A false value is
	// meaningful and distinct from the client not reporting the property at all.
	RK *bool `json:"rk,omitempty"`
}

CredentialPropertiesOutput represents the CredentialPropertiesOutput IDL. The editor's draft defines no member other than rk.

Specification: §10.1.3. Credential Properties Extension (https://www.w3.org/TR/webauthn-3/#sctn-authenticator-credential-properties-extension)

type CredentialProtectionPolicy added in v0.18.0

type CredentialProtectionPolicy string

CredentialProtectionPolicy represents the credential protection policy values of the CTAP credProtect extension.

Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

const (
	// CredentialProtectionPolicyUserVerificationOptional is credProtect value 0x01.
	CredentialProtectionPolicyUserVerificationOptional CredentialProtectionPolicy = "userVerificationOptional"

	// CredentialProtectionPolicyUserVerificationOptionalWithCredentialIDList is credProtect value 0x02.
	CredentialProtectionPolicyUserVerificationOptionalWithCredentialIDList CredentialProtectionPolicy = "userVerificationOptionalWithCredentialIDList"

	// CredentialProtectionPolicyUserVerificationRequired is credProtect value 0x03.
	CredentialProtectionPolicyUserVerificationRequired CredentialProtectionPolicy = "userVerificationRequired"
)

func (CredentialProtectionPolicy) Value added in v0.18.0

func (p CredentialProtectionPolicy) Value() (value uint64, ok bool)

Value returns the CTAP credProtect integer value of this policy, reporting false for a policy this library does not recognise. The values increase with strictness, so an applied policy satisfies a requested one when its value is greater than or equal to the requested value.

The lookup walks [credentialProtectionPolicies] rather than duplicating it in the opposite direction so the two representations cannot disagree.

type CredentialType

type CredentialType string

CredentialType represents the PublicKeyCredentialType IDL and is used with the CredentialDescriptor IDL.

This enumeration defines the valid credential types. It is an extension point; values can be added to it in the future, as more credential types are defined. The values of this enumeration are used for versioning the Authentication Assertion and attestation structures according to the type of the authenticator.

Currently one credential type is defined, namely "public-key".

Specification: §5.8.2. Credential Type Enumeration (https://www.w3.org/TR/webauthn/#enumdef-publickeycredentialtype)

Specification: §5.8.3. Credential Descriptor (https://www.w3.org/TR/webauthn/#dictionary-credential-descriptor)

const (
	// PublicKeyCredentialType - Currently one credential type is defined, namely "public-key".
	PublicKeyCredentialType CredentialType = "public-key"
)

type CurrentUserDetailsUser added in v0.18.0

type CurrentUserDetailsUser interface {
	WebAuthnID() []byte
	WebAuthnName() string
	WebAuthnDisplayName() string
}

CurrentUserDetailsUser is an interface that can be implemented by a user to provide the details a Relying Party signals after they change. It is a subset of github.com/go-webauthn/webauthn/webauthn.User, which therefore satisfies it without any additional method.

type ECDSASignatureEncoding added in v0.18.0

type ECDSASignatureEncoding int

ECDSASignatureEncoding selects the ASN.1 encodings which are accepted for an ECDSA signature.

The specification requires a signature to be valid under the algorithm the ceremony names, and the registered ECDSA algorithms are defined over the DER encoding. Some authenticators nonetheless emit a signature whose integers carry the padding BER permits and DER forbids, which a conforming verifier rejects. Tolerating that encoding is a deviation from the specification rather than a choice it delegates, so it's offered here as a Relying Party decision with the conforming behavior as the default.

const (
	// ECDSASignatureEncodingDefault is the zero value of [ECDSASignatureEncoding]. It evaluates as
	// [ECDSASignatureEncodingDER] wherever it is used. webauthn.Config rewrites it to that explicit constant during
	// validation, so a Relying Party can tell an unset field apart from a deliberate choice of the same encoding.
	ECDSASignatureEncodingDefault ECDSASignatureEncoding = iota

	// ECDSASignatureEncodingDER accepts only the DER encoding, which is the encoding the specification requires.
	ECDSASignatureEncodingDER

	// ECDSASignatureEncodingBER additionally accepts a signature whose integers are encoded under BER, by decoding
	// it and re-encoding the two integers it carries as DER before verification. Verification itself is unchanged:
	// the same signature over the same data by the same key is required, and only the encoding the verifier is
	// handed differs.
	//
	// The relaxation is confined to the minimal encoding requirement DER places on an INTEGER. A signature which is
	// not a SEQUENCE of exactly two positive integers, which carries a non-minimal or indefinite length, or which
	// has trailing data is rejected under this encoding as it is under [ECDSASignatureEncodingDER]. A signature
	// which cannot be decoded fails the ceremony rather than being passed on to be verified unchanged.
	//
	// This is insecure and not recommended. Accepting a non-DER signature makes the encoding of a signature
	// malleable, in that byte sequences which are not equal verify against the same message, and it accepts an
	// authenticator which does not conform to the specification. Select it only where a population of
	// authenticators known to emit such signatures has to be supported.
	ECDSASignatureEncodingBER
)

type Error

type Error struct {
	// Short name for the type of error that has occurred.
	Type string `json:"type"`

	// Additional details about the error.
	Details string `json:"error"`

	// Information to help debug the error.
	DevInfo string `json:"debug"`

	// Inner error.
	Err error `json:"-"`
}

Error is a struct that describes specific error conditions in a structured format.

func ValidateMetadata added in v0.11.0

func ValidateMetadata(ctx context.Context, mds metadata.Provider, aaguid uuid.UUID, attestationType, attestationFormat string, x5cs []any) (protoErr *Error)

ValidateMetadata validates the metadata for the given authenticator.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap added in v0.12.0

func (e *Error) Unwrap() error

func (*Error) WithDetails

func (e *Error) WithDetails(details string) *Error

func (*Error) WithError added in v0.12.0

func (e *Error) WithError(err error) *Error

func (*Error) WithInfo

func (e *Error) WithInfo(info string) *Error

type ErrorUnknownCredential added in v0.16.0

type ErrorUnknownCredential struct {
	Err *Error
}

ErrorUnknownCredential is a special Error which signals the fact the provided credential is unknown. The reason this specific error type is useful is so that the relying-party can send a signal to the Authenticator that the credential has been removed.

func (*ErrorUnknownCredential) Error added in v0.16.0

func (e *ErrorUnknownCredential) Error() string

func (*ErrorUnknownCredential) Unwrap added in v0.16.0

func (e *ErrorUnknownCredential) Unwrap() error

func (*ErrorUnknownCredential) WithDetails added in v0.16.0

func (e *ErrorUnknownCredential) WithDetails(details string) *ErrorUnknownCredential

func (*ErrorUnknownCredential) WithError added in v0.16.0

func (*ErrorUnknownCredential) WithInfo added in v0.16.0

type HMACGetSecretInputs added in v0.18.0

type HMACGetSecretInputs struct {
	Salt1 URLEncodedBase64 `json:"salt1"`
	Salt2 URLEncodedBase64 `json:"salt2,omitempty"`
}

HMACGetSecretInputs represents the inputs of the CTAP hmac-secret extension during authentication.

Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

func (HMACGetSecretInputs) IsZero added in v0.18.0

func (i HMACGetSecretInputs) IsZero() bool

IsZero returns true when no salt is set. It is used by the encoding/json omitzero tag option.

type HMACGetSecretOutputs added in v0.18.0

type HMACGetSecretOutputs struct {
	// Output1 is the HMAC secret evaluated over the first salt.
	Output1 URLEncodedBase64 `json:"output1,omitempty"`

	// Output2 is the HMAC secret evaluated over the second salt, present only when a second salt was supplied.
	Output2 URLEncodedBase64 `json:"output2,omitempty"`
}

HMACGetSecretOutputs represents the outputs of the CTAP hmac-secret extension during authentication.

Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

type LargeBlobInputs added in v0.18.0

type LargeBlobInputs struct {
	Support LargeBlobSupport `json:"support,omitempty"`
	Read    bool             `json:"read,omitempty"`
	Write   URLEncodedBase64 `json:"write,omitempty"`
}

LargeBlobInputs represents the AuthenticationExtensionsLargeBlobInputsJSON IDL. Support is only valid during registration; Read and Write are only valid during authentication and are mutually exclusive.

Specification: §10.1.5. Large blob storage extension (https://www.w3.org/TR/webauthn-3/#sctn-large-blob-extension)

func (LargeBlobInputs) IsZero added in v0.18.0

func (i LargeBlobInputs) IsZero() bool

IsZero returns true when no large blob input is set. It is used by the encoding/json omitzero tag option.

type LargeBlobOutputs added in v0.18.0

type LargeBlobOutputs struct {
	// Supported reports whether the created credential supports large blob storage. It is only present at
	// registration, in answer to the 'support' input. A false value is meaningful and distinct from the client
	// not reporting support at all; [AuthenticationExtensionsClientOutputs.Verify] rejects both when support was
	// requested as required.
	Supported *bool `json:"supported,omitempty"`

	// Blob is the stored blob, present at authentication in answer to a 'read' input.
	Blob URLEncodedBase64 `json:"blob,omitempty"`

	// Written reports whether the blob supplied by a 'write' input was stored. A false value is meaningful and
	// distinct from the client not reporting the outcome at all.
	Written *bool `json:"written,omitempty"`
}

LargeBlobOutputs represents the AuthenticationExtensionsLargeBlobOutputsJSON IDL.

Specification: §10.1.5. Large blob storage extension (https://www.w3.org/TR/webauthn-3/#sctn-large-blob-extension)

type LargeBlobSupport added in v0.18.0

type LargeBlobSupport string

LargeBlobSupport represents the LargeBlobSupport IDL enumeration used by the large blob storage extension during registration.

Specification: §10.1.5. Large blob storage extension (https://www.w3.org/TR/webauthn-3/#sctn-large-blob-extension)

const (
	// LargeBlobSupportRequired indicates the credential MUST support the large blob storage extension. The client
	// fails the ceremony when no eligible authenticator supports it.
	LargeBlobSupportRequired LargeBlobSupport = "required"

	// LargeBlobSupportPreferred indicates the credential SHOULD support the large blob storage extension.
	LargeBlobSupportPreferred LargeBlobSupport = "preferred"
)

type NonCompoundAttestationObject added in v0.16.0

type NonCompoundAttestationObject struct {
	// The format of the Attestation data.
	Format string `json:"fmt"`

	// The attestation statement data sent back if attestation is requested.
	AttStatement map[string]any `json:"attStmt,omitempty"`
}

NonCompoundAttestationObject is a subset of AttestationObject used within compound attestation statements. Each sub-statement in a compound attestation has its own format and attestation statement but shares authenticator data with the parent.

Specification: §8.9. Compound Attestation Statement Format (https://www.w3.org/TR/webauthn-3/#sctn-compound-attestation)

type PRFInputs added in v0.18.0

type PRFInputs struct {
	Eval             PRFValues            `json:"eval,omitzero"`
	EvalByCredential map[string]PRFValues `json:"evalByCredential,omitempty"`
}

PRFInputs represents the AuthenticationExtensionsPRFInputsJSON IDL.

Every member is optional. A zero value is the bare availability probe, i.e. the "prf":{} input a Relying Party sends at registration to learn whether the pseudo-random function is available for the credential; the client answers with the 'enabled' output. This is why AuthenticationExtensions.PRF is a pointer while its LargeBlobInputs and HMACGetSecretInputs siblings are not.

EvalByCredential is only valid during authentication; the client throws a NotSupportedError when it is present during registration. Its keys are base64url encoded credential IDs which MUST each match an entry of the allowed credentials.

Specification: §10.1.4. Pseudo-random function extension (https://www.w3.org/TR/webauthn-3/#prf-extension)

func (PRFInputs) IsZero added in v0.18.0

func (i PRFInputs) IsZero() bool

IsZero returns true when no PRF input is set. It is used by the encoding/json omitzero tag option.

type PRFOutputs added in v0.18.0

type PRFOutputs struct {
	// Enabled reports whether the pseudo-random function is available for the credential. It is the answer to the
	// bare "prf":{} input a Relying Party sends at registration. A false value is meaningful and distinct from
	// the client not reporting availability at all.
	Enabled *bool `json:"enabled,omitempty"`

	// Results carries the outputs of evaluating the pseudo-random function over the requested salts. Second is
	// only set when a second salt was supplied.
	Results *PRFValues `json:"results,omitempty"`
}

PRFOutputs represents the AuthenticationExtensionsPRFOutputsJSON IDL.

Specification: §10.1.4. Pseudo-random function extension (https://www.w3.org/TR/webauthn-3/#prf-extension)

type PRFValues added in v0.18.0

type PRFValues struct {
	First  URLEncodedBase64 `json:"first"`
	Second URLEncodedBase64 `json:"second,omitempty"`
}

PRFValues represents the AuthenticationExtensionsPRFValuesJSON IDL. The byte values are conveyed to the client base64url encoded.

Specification: §10.1.4. Pseudo-random function extension (https://www.w3.org/TR/webauthn-3/#prf-extension)

func (PRFValues) IsZero added in v0.18.0

func (v PRFValues) IsZero() bool

IsZero returns true when no PRF value is set. It is used by the encoding/json omitzero tag option.

type ParsedAssertionResponse

type ParsedAssertionResponse struct {
	CollectedClientData CollectedClientData
	AuthenticatorData   AuthenticatorData
	Signature           []byte
	UserHandle          []byte
}

ParsedAssertionResponse is the parsed form of AuthenticatorAssertionResponse.

type ParsedAttestationResponse

type ParsedAttestationResponse struct {
	CollectedClientData CollectedClientData
	AttestationObject   AttestationObject
	Transports          []AuthenticatorTransport
}

ParsedAttestationResponse is the parsed version of AuthenticatorAttestationResponse.

type ParsedCredential

type ParsedCredential struct {
	ID   string `cbor:"id"`
	Type string `cbor:"type"`
}

ParsedCredential is the parsed PublicKeyCredential interface, inherits from Credential, and contains the attributes that are returned to the caller when a new credential is created, or a new assertion is requested.

type ParsedCredentialAssertionData

type ParsedCredentialAssertionData struct {
	ParsedPublicKeyCredential

	Response ParsedAssertionResponse
	Raw      CredentialAssertionResponse
}

The ParsedCredentialAssertionData is the parsed CredentialAssertionResponse that has been marshalled into a format that allows us to verify the client and authenticator data inside the response.

func ParseCredentialRequestResponse

func ParseCredentialRequestResponse(response *http.Request) (*ParsedCredentialAssertionData, error)

ParseCredentialRequestResponse parses a login/assertion response from a *http.Request. The request body is automatically drained and closed after parsing.

This is the standard entry point when using net/http. For implementations that don't use net/http, see ParseCredentialRequestResponseBody (accepts an io.Reader) or ParseCredentialRequestResponseBytes (accepts a []byte).

func ParseCredentialRequestResponseBody

func ParseCredentialRequestResponseBody(body io.Reader) (par *ParsedCredentialAssertionData, err error)

ParseCredentialRequestResponseBody parses a login/assertion response from an io.Reader. The caller is responsible for closing the reader if applicable.

This is the framework-agnostic variant of ParseCredentialRequestResponse. For a *http.Request use ParseCredentialRequestResponse instead. For raw bytes use ParseCredentialRequestResponseBytes.

func ParseCredentialRequestResponseBytes added in v0.11.0

func ParseCredentialRequestResponseBytes(data []byte) (par *ParsedCredentialAssertionData, err error)

ParseCredentialRequestResponseBytes parses a login/assertion response from raw bytes.

See also ParseCredentialRequestResponse (for *http.Request) and ParseCredentialRequestResponseBody (for io.Reader).

func (*ParsedCredentialAssertionData) Verify

func (p *ParsedCredentialAssertionData) Verify(storedChallenge string, relyingPartyID, appID string, rpOrigins, rpOpaqueOrigins, rpTopOrigins []string, rpTopOriginsVerify TopOriginVerificationMode, allowCrossOrigin, verifyUser, verifyUserPresence bool, credentialBytes []byte, signature SignaturePolicy) error

Verify the remaining elements of the assertion data by following the steps outlined in the referenced specification documentation. It's important to note that the credentialBytes field is the CBOR representation of the credential.

Specification: §7.2 Verifying an Authentication Assertion (https://www.w3.org/TR/webauthn/#sctn-verifying-assertion)

type ParsedCredentialCreationData

type ParsedCredentialCreationData struct {
	ParsedPublicKeyCredential

	Response ParsedAttestationResponse
	Raw      CredentialCreationResponse
}

ParsedCredentialCreationData is the parsed form of CredentialCreationResponse. It is the result of parsing the raw response from the authenticator and can be used with ParsedCredentialCreationData.Verify to complete the registration ceremony verification.

func ParseCredentialCreationResponse

func ParseCredentialCreationResponse(request *http.Request) (*ParsedCredentialCreationData, error)

ParseCredentialCreationResponse parses a registration/attestation response from a *http.Request. The request body is automatically drained and closed after parsing.

This is the standard entry point when using net/http. For implementations that don't use net/http, see ParseCredentialCreationResponseBody (accepts an io.Reader) or ParseCredentialCreationResponseBytes (accepts a []byte).

func ParseCredentialCreationResponseBody

func ParseCredentialCreationResponseBody(body io.Reader) (pcc *ParsedCredentialCreationData, err error)

ParseCredentialCreationResponseBody parses a registration/attestation response from an io.Reader. The caller is responsible for closing the reader if applicable.

This is the framework-agnostic variant of ParseCredentialCreationResponse. For a *http.Request use ParseCredentialCreationResponse instead. For raw bytes use ParseCredentialCreationResponseBytes.

func ParseCredentialCreationResponseBytes added in v0.11.0

func ParseCredentialCreationResponseBytes(data []byte) (pcc *ParsedCredentialCreationData, err error)

ParseCredentialCreationResponseBytes parses a registration/attestation response from raw bytes.

See also ParseCredentialCreationResponse (for *http.Request) and ParseCredentialCreationResponseBody (for io.Reader).

func (*ParsedCredentialCreationData) Verify

func (pcc *ParsedCredentialCreationData) Verify(storedChallenge string, relyingPartyID string, rpOrigins, rpOpaqueOrigins, rpTopOrigins []string, rpTopOriginsVerify TopOriginVerificationMode, allowCrossOrigin, verifyUser, verifyUserPresence bool, mds metadata.Provider, credParams []CredentialParameter, policy AttestationPolicy, signature SignaturePolicy) (clientDataHash []byte, err error)

Verify the Client and Attestation data.

Specification: §7.1. Registering a New Credential (https://www.w3.org/TR/webauthn/#sctn-registering-a-new-credential)

type ParsedPublicKeyCredential

type ParsedPublicKeyCredential struct {
	ParsedCredential

	RawID                   []byte                                `json:"rawId"`
	ClientExtensionResults  AuthenticationExtensionsClientOutputs `json:"clientExtensionResults,omitzero"`
	AuthenticatorAttachment AuthenticatorAttachment               `json:"authenticatorAttachment,omitempty"`
}

ParsedPublicKeyCredential is the parsed form of PublicKeyCredential with typed fields.

func (ParsedPublicKeyCredential) GetAppID

func (ppkc ParsedPublicKeyCredential) GetAppID(session SessionExtensions, credentialAttestationFormat string) (appID string, err error)

GetAppID determines the Relying Party ID to use for a credential registered through the legacy FIDO U2F JavaScript API. It returns an empty string when the FIDO AppID Extension does not apply, and the session's appid when it does.

The checks performed, in order:

  1. If the client did not report the appid extension output, or reported it as false, return an empty string.
  2. If the credential's attestation format is not "fido-u2f" it is assumed not to be a FIDO U2F credential, so return an empty string.
  3. If the session data has no appid, return an error; the client indicates it acted on an extension the Relying Party did not request.
  4. Return the session's appid.

A client output whose appid member is not a boolean is rejected when the response is parsed rather than here.

A non-empty return value becomes the sole expected rpIdHash for the assertion. The specification requires the Relying Party to expect the hash of the AppID and not the hash of the RP ID once the client reports the extension was acted upon, so the RP ID hash is not accepted as an alternative; see AuthenticatorData.Verify.

Specification: §10.1.1. FIDO AppID Extension (https://www.w3.org/TR/webauthn-3/#sctn-appid-extension)

type PublicKeyCredential

type PublicKeyCredential struct {
	Credential

	RawID                   URLEncodedBase64                      `json:"rawId"`
	ClientExtensionResults  AuthenticationExtensionsClientOutputs `json:"clientExtensionResults,omitzero"`
	AuthenticatorAttachment string                                `json:"authenticatorAttachment,omitempty"`
}

PublicKeyCredential represents the IDL of the same name and contains the raw response returned to the Relying Party from the client's call to navigator.credentials.create() or navigator.credentials.get().

Specification: §5.1. PublicKeyCredential Interface (https://www.w3.org/TR/webauthn/#iface-pkcredential)

type PublicKeyCredentialCreationOptions

type PublicKeyCredentialCreationOptions struct {
	RelyingParty           RelyingPartyEntity         `json:"rp"`
	User                   UserEntity                 `json:"user"`
	Challenge              URLEncodedBase64           `json:"challenge"`
	Parameters             []CredentialParameter      `json:"pubKeyCredParams,omitempty"`
	Timeout                int                        `json:"timeout,omitempty"`
	CredentialExcludeList  []CredentialDescriptor     `json:"excludeCredentials,omitempty"`
	AuthenticatorSelection AuthenticatorSelection     `json:"authenticatorSelection,omitzero"`
	Hints                  []PublicKeyCredentialHints `json:"hints,omitempty"`
	Attestation            ConveyancePreference       `json:"attestation,omitempty"`
	AttestationFormats     []AttestationFormat        `json:"attestationFormats,omitempty"`
	Extensions             AuthenticationExtensions   `json:"extensions,omitzero"`

	// Origin binds the ceremony to the single origin the response must declare. Used internally only; not
	// serialized, as the origin is not a member of the IDL and is never conveyed to the client. It is recorded in
	// the [github.com/go-webauthn/webauthn/webauthn.SessionData] instead, which the Finish step verifies the
	// collected client data against in place of the configured origins.
	Origin string `json:"-"`
}

PublicKeyCredentialCreationOptions represents the IDL of the same name.

In order to create a Credential via create(), the caller specifies a few parameters in a PublicKeyCredentialCreationOptions object.

WebAuthn Level 3: hints,attestationFormats.

Specification: §5.4. Options for Credential Creation (https://www.w3.org/TR/webauthn/#dictionary-makecredentialoptions)

type PublicKeyCredentialHints added in v0.11.0

type PublicKeyCredentialHints string

PublicKeyCredentialHints represents an entry of the hints member, which conveys the Relying Party's belief about how the user will satisfy the request, in descending order of preference.

The IDL types the hints member as a sequence of strings rather than as this enumeration, and requires clients to ignore values they do not recognise, so values are deliberately not validated against the constants below: a Relying Party may send a hint ratified after this release, or one a particular user agent understands. Clients also ignore the second and later appearances of a repeated hint.

Hints may contradict the authenticator attachment and the transports of the allowed credentials. Where they do, a client which implements hints gives the hints precedence; see PublicKeyCredentialHints.AuthenticatorAttachment for how a registration ceremony pairs the two for the benefit of clients which do not.

WebAuthn Level 3.

Specification: §5.8.7. User-agent Hints Enumeration (https://www.w3.org/TR/webauthn-3/#enum-hints)

const (
	// PublicKeyCredentialHintSecurityKey is a PublicKeyCredentialHint that indicates that the Relying Party believes
	// that users will satisfy this request with a physical security key. For example, an enterprise Relying Party may
	// set this hint if they have issued security keys to their employees and will only accept those authenticators for
	// registration and authentication.
	//
	// For compatibility with older user agents, when this hint is used in PublicKeyCredentialCreationOptions, the
	// authenticatorAttachment SHOULD be set to cross-platform.
	PublicKeyCredentialHintSecurityKey PublicKeyCredentialHints = "security-key"

	// PublicKeyCredentialHintClientDevice is a PublicKeyCredentialHint that indicates that the Relying Party believes
	// that users will satisfy this request with a platform authenticator attached to the client device.
	//
	// For compatibility with older user agents, when this hint is used in PublicKeyCredentialCreationOptions, the
	// authenticatorAttachment SHOULD be set to platform.
	PublicKeyCredentialHintClientDevice PublicKeyCredentialHints = "client-device"

	// PublicKeyCredentialHintHybrid is a PublicKeyCredentialHint that indicates that the Relying Party believes that
	// users will satisfy this request with general-purpose authenticators such as smartphones. For example, a consumer
	// Relying Party may believe that only a small fraction of their customers possesses dedicated security keys. This
	// option also implies that the local platform authenticator should not be promoted in the UI.
	//
	// For compatibility with older user agents, when this hint is used in PublicKeyCredentialCreationOptions, the
	// authenticatorAttachment SHOULD be set to cross-platform.
	PublicKeyCredentialHintHybrid PublicKeyCredentialHints = "hybrid"
)

func (PublicKeyCredentialHints) AuthenticatorAttachment added in v0.18.0

func (h PublicKeyCredentialHints) AuthenticatorAttachment() AuthenticatorAttachment

AuthenticatorAttachment returns the authenticator attachment a Relying Party using this hint during registration SHOULD also set, so user agents which predate hints filter authenticators consistently with the hint. An identifier this library does not model, which includes any hint ratified after this release, returns an empty value rather than a guess.

A user agent which does implement hints gives them precedence over the authenticator attachment, so pairing the two cannot narrow a ceremony such a user agent would otherwise honour.

Specification: §5.8.7. User-agent Hints Enumeration (https://www.w3.org/TR/webauthn-3/#enum-hints)

type PublicKeyCredentialRequestOptions

type PublicKeyCredentialRequestOptions struct {
	Challenge          URLEncodedBase64            `json:"challenge"`
	Timeout            int                         `json:"timeout,omitempty"`
	RelyingPartyID     string                      `json:"rpId,omitempty"`
	AllowedCredentials []CredentialDescriptor      `json:"allowCredentials,omitempty"`
	UserVerification   UserVerificationRequirement `json:"userVerification,omitempty"`
	Hints              []PublicKeyCredentialHints  `json:"hints,omitempty"`
	Extensions         AuthenticationExtensions    `json:"extensions,omitzero"`

	// Origin binds the ceremony to the single origin the response must declare. Used internally only; not
	// serialized, as the origin is not a member of the IDL and is never conveyed to the client. It is recorded in
	// the [github.com/go-webauthn/webauthn/webauthn.SessionData] instead, which the Finish step verifies the
	// collected client data against in place of the configured origins.
	Origin string `json:"-"`
}

The PublicKeyCredentialRequestOptions dictionary supplies get() with the data it needs to generate an assertion. Its challenge member MUST be present, while its other members are OPTIONAL.

WebAuthn Level 3: hints.

Specification: §5.5. Options for Assertion Generation (https://www.w3.org/TR/webauthn/#dictionary-assertion-options)

func (*PublicKeyCredentialRequestOptions) GetAllowedCredentialIDs

func (a *PublicKeyCredentialRequestOptions) GetAllowedCredentialIDs() [][]byte

type RelatedOriginLabeler added in v0.18.0

type RelatedOriginLabeler func(origin string) (label string, err error)

RelatedOriginLabeler derives the registrable domain label of an origin, which is the unit a client counts against MaximumRelatedOriginLabels. Origins which share a label cost only one between them, which is what lets a Relying Party list the same brand across many country code top level domains cheaply.

DefaultRelatedOriginLabeler is used when none is supplied. Supply your own to count labels exactly for a deployment which uses a multi-label public suffix; see that function for why the default cannot.

type RelatedOrigins added in v0.18.0

type RelatedOrigins struct {
	Origins []string `json:"origins"`
}

RelatedOrigins is the document a Relying Party serves at WellKnownPathWebAuthn to declare which origins may run ceremonies against its Relying Party ID.

Build one with NewRelatedOrigins, which validates and normalizes the origins, then serve it with whichever of RelatedOrigins.Bytes, RelatedOrigins.WriteTo or RelatedOrigins.WriteResponse suits the surrounding code. The type is also an http.Handler, so it can be mounted on a router directly:

related, err := protocol.NewRelatedOrigins("https://example.com", "https://example.com.au")
if err != nil {
	return err
}

mux.Handle(protocol.WellKnownPathWebAuthn, related)

A [WebAuthn.RelatedOrigins] method in the webauthn package builds this from the configured origins.

Specification: §5.11. Related Origin Requests (https://www.w3.org/TR/webauthn-3/#sctn-related-origins)

func NewRelatedOrigins added in v0.18.0

func NewRelatedOrigins(origins ...string) (related *RelatedOrigins, err error)

NewRelatedOrigins validates the given origins and returns the RelatedOrigins document which declares them, using DefaultRelatedOriginLabeler to count the registrable domain labels. See NewRelatedOriginsWithLabeler for the validation performed and for supplying a labeler of your own.

func NewRelatedOriginsWithLabeler added in v0.18.0

func NewRelatedOriginsWithLabeler(labeler RelatedOriginLabeler, origins ...string) (related *RelatedOrigins, err error)

NewRelatedOriginsWithLabeler validates the given origins and returns the RelatedOrigins document which declares them, counting registrable domain labels with the given RelatedOriginLabeler. A nil labeler selects DefaultRelatedOriginLabeler.

Each origin must be an absolute http or https URL with a host. Every origin is normalized to its scheme and host alone, with a default port and any path, query, fragment or userinfo removed, and origins which normalize to the same value are collapsed to one. The order the origins were given in is otherwise preserved.

An error is returned when the origins carry more than MaximumRelatedOriginLabels distinct labels, because a client stops processing at that point and the excess origins would be ignored in production without any signal that they had been.

func (RelatedOrigins) Bytes added in v0.18.0

func (r RelatedOrigins) Bytes() (data []byte, err error)

Bytes returns the encoded well-known document.

func (RelatedOrigins) MarshalJSON added in v0.18.0

func (r RelatedOrigins) MarshalJSON() (data []byte, err error)

MarshalJSON implements the json.Marshaler interface, encoding an absent origin list as an empty array rather than as null so that the document is always the shape a client parses.

func (RelatedOrigins) ServeHTTP added in v0.18.0

func (r RelatedOrigins) ServeHTTP(w http.ResponseWriter, request *http.Request)

ServeHTTP implements the http.Handler interface so the document can be mounted on a router at WellKnownPathWebAuthn directly. The resource is read only, so a request with a method other than GET or HEAD is answered with a status of 405 and an Allow header.

func (RelatedOrigins) WriteResponse added in v0.18.0

func (r RelatedOrigins) WriteResponse(w http.ResponseWriter) (err error)

WriteResponse writes the encoded well-known document to the given http.ResponseWriter along with the headers which describe it, responding with a status of 200. No caching headers are set; the caching policy of the resource is left to the Relying Party.

Use RelatedOrigins.ServeHTTP instead to have the request method handled as well.

func (RelatedOrigins) WriteTo added in v0.18.0

func (r RelatedOrigins) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes the encoded well-known document to the given io.Writer, implementing the io.WriterTo interface.

type RelyingPartyEntity

type RelyingPartyEntity struct {
	CredentialEntity

	// A unique identifier for the Relying Party entity, which sets the RP ID.
	ID string `json:"id"`
}

The RelyingPartyEntity represents the PublicKeyCredentialRpEntity IDL and is used to supply additional Relying Party attributes when creating a new credential.

Specification: §5.4.2. Relying Party Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dictionary-rp-credential-params)

type ResidentKeyRequirement added in v0.2.0

type ResidentKeyRequirement string

ResidentKeyRequirement represents the IDL of the same name.

This enumeration’s values describe the Relying Party's requirements for client-side discoverable credentials (formerly known as resident credentials or resident keys).

Specifies the extent to which the Relying Party desires to create a client-side discoverable credential. For historical reasons the naming retains the deprecated “resident” terminology. The value SHOULD be a member of ResidentKeyRequirement but client platforms MUST ignore unknown values, treating an unknown value as if the member does not exist. If no value is given then the effective value is required if requireResidentKey is true or discouraged if it is false or absent.

Specification: §5.4.4. Authenticator Selection Criteria (https://www.w3.org/TR/webauthn/#dom-authenticatorselectioncriteria-residentkey)

Specification: §5.4.6. Resident Key Requirement Enumeration (https://www.w3.org/TR/webauthn/#enumdef-residentkeyrequirement)

const (
	// ResidentKeyRequirementDiscouraged indicates the Relying Party prefers creating a server-side credential, but will
	// accept a client-side discoverable credential. This is the default.
	ResidentKeyRequirementDiscouraged ResidentKeyRequirement = "discouraged"

	// ResidentKeyRequirementPreferred indicates to the client we would prefer a discoverable credential.
	ResidentKeyRequirementPreferred ResidentKeyRequirement = "preferred"

	// ResidentKeyRequirementRequired indicates the Relying Party requires a client-side discoverable credential, and is
	// prepared to receive an error if a client-side discoverable credential cannot be created.
	ResidentKeyRequirementRequired ResidentKeyRequirement = "required"
)

type SafetyNetResponse

type SafetyNetResponse struct {
	Nonce                      string `json:"nonce"`
	TimestampMs                int64  `json:"timestampMs"`
	ApkPackageName             string `json:"apkPackageName"`
	ApkDigestSha256            string `json:"apkDigestSha256"`
	CtsProfileMatch            bool   `json:"ctsProfileMatch"`
	ApkCertificateDigestSha256 []any  `json:"apkCertificateDigestSha256"`
	BasicIntegrity             bool   `json:"basicIntegrity"`
}

type ServerResponse

type ServerResponse struct {
	// Status indicates whether the operation succeeded or failed.
	Status ServerResponseStatus `json:"status"`

	// Message provides additional details about an error if Status is "failed".
	Message string `json:"errorMessage"`
}

ServerResponse is a response from a FIDO conformance server.

type ServerResponseStatus

type ServerResponseStatus string

ServerResponseStatus is the status code returned by a FIDO conformance server.

const (
	// StatusOk indicates the server operation was successful.
	StatusOk ServerResponseStatus = "ok"

	// StatusFailed indicates the server operation failed.
	StatusFailed ServerResponseStatus = "failed"
)

type SessionExtensions added in v0.18.0

type SessionExtensions struct {
	// Requested lists the extension identifiers the Relying Party asked for, as reported by
	// [AuthenticationExtensions.Requested]. An extension output whose identifier is absent from this list was not
	// solicited.
	Requested []string `json:"requested,omitempty"`

	// AppID is the FIDO AppID Extension input, required to determine the Relying Party ID of a credential
	// registered through the legacy FIDO U2F JavaScript API.
	AppID string `json:"appid,omitempty"`

	// AppIDExclude is the FIDO AppID Exclusion Extension input.
	AppIDExclude string `json:"appidExclude,omitempty"`

	// LargeBlob is the large blob support requirement requested at registration. A value of
	// [LargeBlobSupportRequired] is asserted against the extension output.
	LargeBlob LargeBlobSupport `json:"largeBlob,omitempty"`

	// LargeBlobRead records that a large blob read was requested at authentication.
	LargeBlobRead bool `json:"largeBlobRead,omitempty"`

	// LargeBlobWrite records that a large blob write was requested at authentication. Only the intent is recorded;
	// the payload itself is excluded because it can be large and has no verification role beyond this flag.
	LargeBlobWrite bool `json:"largeBlobWrite,omitempty"`

	// CredentialProtectionPolicy is the CTAP credProtect policy requested at registration. It is asserted against
	// the authenticator extension output when EnforceCredentialProtectionPolicy is set.
	CredentialProtectionPolicy CredentialProtectionPolicy `json:"credentialProtectionPolicy,omitempty"`

	// EnforceCredentialProtectionPolicy records that the requested credential protection policy must be honoured.
	EnforceCredentialProtectionPolicy bool `json:"enforceCredentialProtectionPolicy,omitempty"`

	// CredBlob records that a blob was submitted for storage with the credential at registration. As with
	// LargeBlobWrite only the intent is recorded, because the blob is Relying Party data with no verification role
	// beyond this flag.
	CredBlob bool `json:"credBlob,omitempty"`

	// Extra carries the inputs of extensions this library does not model, so a Relying Party can verify the
	// outputs of its own extensions. Whatever is placed here is persisted verbatim; keep it small.
	Extra map[string]any `json:"extra,omitempty"`
}

SessionExtensions is the subset of AuthenticationExtensions a Relying Party must persist between the begin and finish steps of a ceremony in order to verify the extension outputs it receives.

The per-ceremony PRF salts and the large blob write payload are deliberately excluded. The salts are secrets with no verification role and the payload can be large; both are represented by their identifier in Requested.

func (SessionExtensions) IsZero added in v0.18.0

func (e SessionExtensions) IsZero() bool

IsZero returns true when nothing needs to be persisted. It is used by the encoding/json omitzero tag option.

type SignalAllAcceptedCredentials added in v0.16.0

type SignalAllAcceptedCredentials struct {
	AllAcceptedCredentialIDs []URLEncodedBase64 `json:"allAcceptedCredentialIds"`
	RPID                     string             `json:"rpId"`
	UserID                   URLEncodedBase64   `json:"userId"`
}

SignalAllAcceptedCredentials is a struct which represents the CDDL of the same name.

func NewSignalAllAcceptedCredentials added in v0.16.0

func NewSignalAllAcceptedCredentials(rpid string, user AllAcceptedCredentialsUser) *SignalAllAcceptedCredentials

NewSignalAllAcceptedCredentials creates a new SignalAllAcceptedCredentials struct that can simply be encoded with json.Marshal.

A nil user, including a nil pointer carried in a non-nil interface, yields a nil result.

type SignalCurrentUserDetails added in v0.16.0

type SignalCurrentUserDetails struct {
	DisplayName string           `json:"displayName"`
	Name        string           `json:"name"`
	RPID        string           `json:"rpId"`
	UserID      URLEncodedBase64 `json:"userId"`
}

SignalCurrentUserDetails is a struct which represents the CDDL of the same name.

func NewSignalCurrentUserDetails added in v0.18.0

func NewSignalCurrentUserDetails(rpid string, user CurrentUserDetailsUser) *SignalCurrentUserDetails

NewSignalCurrentUserDetails creates a new SignalCurrentUserDetails struct that can simply be encoded with json.Marshal. It is the counterpart of NewSignalAllAcceptedCredentials for the signal a Relying Party sends after the name or display name of a user account changes.

A github.com/go-webauthn/webauthn/webauthn.User satisfies CurrentUserDetailsUser as it stands, so the user value the ceremony methods already take can be passed straight through.

A nil user, including a nil pointer carried in a non-nil interface, yields a nil result.

type SignalUnknownCredential added in v0.16.0

type SignalUnknownCredential struct {
	CredentialID URLEncodedBase64 `json:"credentialId"`
	RPID         string           `json:"rpId"`
}

SignalUnknownCredential is a struct which represents the CDDL of the same name.

type SignaturePolicy added in v0.18.0

type SignaturePolicy struct {
	// ECDSAEncoding selects the ASN.1 encodings which are accepted for an ECDSA signature.
	ECDSAEncoding ECDSASignatureEncoding
}

SignaturePolicy carries the Relying Party policy decisions for verifying the signatures of a ceremony. It applies to the attestation signature of a registration and to the assertion signature of an authentication alike, as an authenticator which deviates from the specification in how it encodes one generally does so in both. The zero value selects the behavior the specification requires.

type TokenBinding deprecated

type TokenBinding struct {
	Status TokenBindingStatus `json:"status"`
	ID     string             `json:"id,omitempty"`
}

TokenBinding contains information about the state of the Token Binding protocol used when communicating with the Relying Party. Its absence indicates that the client doesn't support token binding.

Specification: §5.8.1. Client Data Used in WebAuthn Signatures (https://www.w3.org/TR/webauthn/#dom-collectedclientdata-tokenbinding)

Deprecated: WebAuthn Level 3 removes the tokenBinding member from the CollectedClientData dictionary; see CollectedClientData.TokenBinding.

type TokenBindingStatus deprecated

type TokenBindingStatus string

TokenBindingStatus represents the state of Token Binding between the client and the Relying Party.

Deprecated: WebAuthn Level 3 removes the tokenBinding member from the CollectedClientData dictionary; see CollectedClientData.TokenBinding.

const (
	// Present indicates token binding was used when communicating with the
	// Relying Party. In this case, the id member MUST be present.
	Present TokenBindingStatus = "present"

	// Supported indicates the client supports token binding, but it was not
	// negotiated when communicating with the Relying Party.
	Supported TokenBindingStatus = "supported"

	// NotSupported indicates token binding not supported
	// when communicating with the Relying Party.
	//
	// This value is accepted but has not been a member of the TokenBindingStatus enumeration since WebAuthn Level 1,
	// which is why it is not rejected: a client which still sends it is behaving as an older level of the
	// specification allowed, and failing the ceremony over an advisory member would serve no purpose.
	NotSupported TokenBindingStatus = "not-supported"
)

type TopOriginVerificationMode added in v0.11.0

type TopOriginVerificationMode int

TopOriginVerificationMode determines how the Relying Party validates the topOrigin field in CollectedClientData. This is relevant for cross-origin iframe scenarios where the top-level browsing context's origin differs from the embedded origin making the WebAuthn API call.

WebAuthn Level 3.

const (
	// TopOriginDefaultVerificationMode is the zero value of [TopOriginVerificationMode] and has no matching rule in
	// the verifier; passing it directly to [CollectedClientData.Verify] returns an "unknown Top Origin verification
	// mode" error. High-level callers using [webauthn.Config] have this value coerced to
	// [TopOriginExplicitVerificationMode] by config validation, which is the recommended default.
	TopOriginDefaultVerificationMode TopOriginVerificationMode = iota

	// TopOriginAutoVerificationMode accepts the Top Origin if it matches any entry in either the allowed Top Origins
	// list or the allowed Origins list. The two lists are unioned (RPTopOrigins ∪ RPOrigins). This is the most
	// permissive of the three active modes and should only be used when an RP deliberately wants cross-origin and
	// same-origin embeddings to share an allow-list.
	TopOriginAutoVerificationMode

	// TopOriginImplicitVerificationMode accepts the Top Origin only if it matches an entry in the allowed Origins
	// list (RPOrigins). The RPTopOrigins list is ignored in this mode.
	TopOriginImplicitVerificationMode

	// TopOriginExplicitVerificationMode accepts the Top Origin only if it matches an entry in the allowed Top Origins
	// list (RPTopOrigins). The RPOrigins list is ignored in this mode. This is the strictest mode and the one
	// [webauthn.Config] coerces the zero value to.
	TopOriginExplicitVerificationMode
)

type URLEncodedBase64

type URLEncodedBase64 []byte

URLEncodedBase64 represents a byte slice holding URL-encoded base64 data. When fields of this type are unmarshalled from JSON, the data is base64 decoded into a byte slice.

func CreateChallenge

func CreateChallenge() (challenge URLEncodedBase64, err error)

CreateChallenge creates a new challenge that should be signed and returned by the authenticator. The spec recommends using at least 16 bytes with 100 bits of entropy. We use 32 bytes.

func (URLEncodedBase64) MarshalJSON

func (e URLEncodedBase64) MarshalJSON() ([]byte, error)

MarshalJSON base64 encodes a non URL-encoded value, storing the result in the provided byte slice.

func (URLEncodedBase64) String added in v0.6.0

func (e URLEncodedBase64) String() string

func (*URLEncodedBase64) UnmarshalJSON

func (e *URLEncodedBase64) UnmarshalJSON(data []byte) error

UnmarshalJSON base64 decodes a URL-encoded value, storing the result in the provided byte slice.

type UnsolicitedOutputPolicy added in v0.18.0

type UnsolicitedOutputPolicy int

UnsolicitedOutputPolicy determines how a client extension output that the Relying Party did not request is handled during the finish step of a ceremony.

const (
	// UnsolicitedOutputPolicyReject fails the ceremony when the client returns an extension output the Relying
	// Party did not request. This is the zero value and therefore the default.
	UnsolicitedOutputPolicyReject UnsolicitedOutputPolicy = iota

	// UnsolicitedOutputPolicyIgnore accepts and ignores extension outputs the Relying Party did not request. Use
	// this only when a client is known to return outputs unprompted.
	UnsolicitedOutputPolicyIgnore
)

type UserEntity

type UserEntity struct {
	CredentialEntity
	// A human-palatable name for the user account, intended only for display.
	// For example, "Alex P. Müller" or "田中 倫". The Relying Party SHOULD let
	// the user choose this, and SHOULD NOT restrict the choice more than necessary.
	DisplayName string `json:"displayName"`

	// ID is the user handle of the user account entity. To ensure secure operation,
	// authentication and authorization decisions MUST be made on the basis of this id
	// member, not the displayName nor name members. See Section 6.1 of
	// [RFC8266](https://www.w3.org/TR/webauthn/#biblio-rfc8266).
	ID any `json:"id"`
}

The UserEntity represents the PublicKeyCredentialUserEntity IDL and is used to supply additional user account attributes when creating a new credential.

Specification: §5.4.3 User Account Parameters for Credential Generation (https://www.w3.org/TR/webauthn/#dictdef-publickeycredentialuserentity)

type UserVerificationMethod added in v0.18.0

type UserVerificationMethod struct {
	UserVerificationMethod uint32 `json:"userVerificationMethod"`
	KeyProtectionType      uint32 `json:"keyProtectionType"`
	MatcherProtectionType  uint32 `json:"matcherProtectionType"`
}

UserVerificationMethod is a single entry of the CTAP uvm extension output.

Registry: https://www.iana.org/assignments/webauthn/webauthn.xhtml

type UserVerificationRequirement

type UserVerificationRequirement string

UserVerificationRequirement is a representation of the UserVerificationRequirement IDL enum.

A WebAuthn Relying Party may require user verification for some of its operations but not for others, and may use this type to express its needs.

Specification: §5.8.6. User Verification Requirement Enumeration (https://www.w3.org/TR/webauthn/#enum-userVerificationRequirement)

const (
	// VerificationRequired User verification is required to create/release a credential.
	VerificationRequired UserVerificationRequirement = "required"

	// VerificationPreferred User verification is preferred to create/release a credential.
	VerificationPreferred UserVerificationRequirement = "preferred" // This is the default.

	// VerificationDiscouraged The authenticator should not verify the user for the credential.
	VerificationDiscouraged UserVerificationRequirement = "discouraged"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL