diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..5fe2459 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + # Keeps the SHA-pinned actions in .github/workflows up to date, including their version comments + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + github-actions: + patterns: ["*"] diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..7fe280c --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,49 @@ +name: Test + +on: + pull_request: + push: + branches: [main] + +# Actions are pinned to commit SHAs (the version is in the trailing comment) so a moved tag can't +# change what runs +permissions: + contents: read + +jobs: + e2e: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # Installs the tools pinned in mise.toml (and mise.lock), so Node matches local development + - uses: jdx/mise-action@d5574b52816a478f9d4e6529a3f6ff17a8a36785 # v5.2.8 + with: + version: 2026.9.15 + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.npm + key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }} + restore-keys: npm-${{ runner.os }}- + - run: npm ci + - id: playwright-version + run: echo "version=$(npx playwright --version | awk '{print $2}')" >> "$GITHUB_OUTPUT" + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + id: playwright-browsers-cache + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ steps.playwright-version.outputs.version }} + # System libraries live outside the cached path, so they're installed on every run + - run: npx playwright install --with-deps chromium + if: steps.playwright-browsers-cache.outputs.cache-hit != 'true' + - run: npx playwright install-deps chromium + if: steps.playwright-browsers-cache.outputs.cache-hit == 'true' + - run: npm test + # On failure, keep Playwright's traces (recorded on the first retry) for debugging with + # `npx playwright show-trace` + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: failure() + with: + name: playwright-traces + path: test-results diff --git a/.gitignore b/.gitignore index 144349f..a1507db 100644 --- a/.gitignore +++ b/.gitignore @@ -70,3 +70,7 @@ _site .wrangler .dev.vars + +# Playwright +test-results +playwright-report diff --git a/README.md b/README.md index 1de8b83..27f0a05 100644 --- a/README.md +++ b/README.md @@ -57,9 +57,9 @@ Preview versions are served from a `*-tools-passkeys-dev.passkeydeveloper.worker ### Deployment -The site is a Cloudflare Worker serving the built `_site/` directory as static assets (see `wrangler.jsonc`). It is not a Pages project. In Cloudflare, connect the repository under Workers & Pages as a Worker (Workers Builds) with build command `npm run build`, deploy command `npx wrangler deploy`, and non-production branch deploy command `npx wrangler versions upload`. +The site is a Cloudflare Worker serving the built `_site/` directory as static assets (see `wrangler.jsonc`). It is not a Pages project. In Cloudflare, connect the repository under Workers & Pages as a Worker (Workers Builds) with build command `npm run build`, deploy command `npx wrangler deploy`, and, for non-production branches, preview command `npx wrangler preview` (Worker Previews; the older `npx wrangler versions upload` fails the Workers Builds Worker check once previews are enabled). -To deploy by hand, run `npm run deploy`. `npm run preview` uploads a version without promoting it and prints its preview URL. +To deploy by hand, run `npm run deploy`. `npm run preview` creates a Preview deployment without promoting anything and prints its preview URL. ## Structure diff --git a/package-lock.json b/package-lock.json index e4a82f8..f26fefa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "devDependencies": { "@11ty/eleventy": "^3.1.5", "@cloudflare/workers-types": "^5.20261103.1", + "@playwright/test": "^1.65.0", "@quasibit/eleventy-plugin-sitemap": "^2.2.0", "eleventy-plugin-metagen": "^1.8.4", "luxon": "^3.7.2", @@ -1393,6 +1394,22 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@playwright/test": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.0.tgz", + "integrity": "sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.65.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@poppinss/colors": { "version": "4.1.6", "resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz", @@ -3098,6 +3115,35 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz", + "integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", + "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/please-upgrade-node": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz", diff --git a/package.json b/package.json index 0f1104e..2a65173 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "devDependencies": { "@11ty/eleventy": "^3.1.5", "@cloudflare/workers-types": "^5.20261103.1", + "@playwright/test": "^1.65.0", "@quasibit/eleventy-plugin-sitemap": "^2.2.0", "eleventy-plugin-metagen": "^1.8.4", "luxon": "^3.7.2", @@ -13,13 +14,13 @@ "wrangler": "^4.157.0" }, "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", + "test": "playwright test", "dev": "npm run build && wrangler dev", "build": "npx @11ty/eleventy", "build:watch": "npx @11ty/eleventy --watch", "typecheck": "tsc --noEmit", "deploy": "npm run typecheck && npm run build && wrangler deploy", - "preview": "npm run typecheck && npm run build && wrangler versions upload", + "preview": "npm run typecheck && npm run build && wrangler preview", "watch": "npx @11ty/eleventy --watch" }, "repository": { diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..fbede4c --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,27 @@ +import { defineConfig, devices } from '@playwright/test'; + +const PORT = 8090; + +export default defineConfig({ + testDir: 'tests', + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + // A test that only passes on retry is still a failure; the retry exists to capture a trace + failOnFlakyTests: !!process.env.CI, + reporter: process.env.CI ? 'github' : 'list', + use: { + // `localhost` is a secure context, which WebAuthn requires + baseURL: `http://localhost:${PORT}`, + trace: 'on-first-retry', + }, + // The virtual authenticator is driven through the Chrome DevTools Protocol + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], + // Only the static site is served; the API is mocked per test (see tests/helpers.ts) because the + // real one needs the webauthnapi-passkeys-dev Worker + webServer: { + command: `npx @11ty/eleventy --serve --quiet --port=${PORT}`, + url: `http://localhost:${PORT}`, + reuseExistingServer: !process.env.CI, + }, +}); diff --git a/src/_includes/layouts/base.njk b/src/_includes/layouts/base.njk index f12eebb..9e1fb99 100644 --- a/src/_includes/layouts/base.njk +++ b/src/_includes/layouts/base.njk @@ -48,5 +48,14 @@ {% endfor %} {% endif %} + {% if extra_modules %} + {% for script in extra_modules %} + + {% endfor %} + {% endif %} + {# Deferred so it runs after module scripts, which have registered their `alpine:init` listeners #} + {% if alpine %} + + {% endif %} diff --git a/src/assets/js/random-username-gen.2.0.2.esm.js b/src/assets/js/random-username-gen.2.0.2.esm.js new file mode 100644 index 0000000..3803ef5 --- /dev/null +++ b/src/assets/js/random-username-gen.2.0.2.esm.js @@ -0,0 +1,214 @@ +/** + * Downloaded from https://esm.unpkg.com/random-username-gen@2.0.2/src/esm/index.js + */ +// unpkg-package:/src/esm/adjectives.js +var adjectives = [ + "fast", + "smart", + "strong", + "brave", + "curious", + "fierce", + "gentle", + "happy", + "lazy", + "mysterious", + "bold", + "calm", + "determined", + "eager", + "fearless", + "graceful", + "honest", + "intelligent", + "jovial", + "kind", + "lively", + "modest", + "noble", + "optimistic", + "patient", + "quick", + "reliable", + "sincere", + "talented", + "unique", + "valiant", + "wise", + "youthful", + "zealous", + "adventurous", + "careful", + "confident", + "dynamic", + "enthusiastic", + "forgiving", + "gregarious", + "helpful", + "imaginative", + "joyful", + "knowledgeable", + "loving", + "nurturing", + "observant", + "persistent", + "quiet", + "resourceful", + "sensitive", + "thoughtful", + "vigorous", + "warm", + "appreciative", + "caring", + "considerate", + "diligent", + "energetic", + "friendly", + "hardworking", + "humorous", + "innovative", + "jolly", + "keen", + "loyal", + "mindful", + "obedient", + "polite", + "resilient", + "respectful", + "supportive", + "trustworthy", + "versatile", + "witty", + "affectionate", + "charming", + "courageous", + "devoted", + "endearing", + "fun", + "happy-go-lucky", + "humble", + "inspiring", + "jubilant", + "kindhearted", + "lighthearted", + "magnanimous", + "openhearted", + "passionate", + "radiant", + "reflective", + "sympathetic", + "truthful", + "vibrant", + "wonderful", + "ambitious", + "cheerful", + "creative", + "discerning", + "encouraging", + "generous" +]; + +// unpkg-package:/src/esm/nouns.js +var nouns = [ + "tiger", + "eagle", + "shark", + "lion", + "bear", + "wolf", + "fox", + "jaguar", + "whale", + "giraffe", + "panther", + "dolphin", + "elephant", + "rhinoceros", + "crocodile", + "penguin", + "octopus", + "falcon", + "hippopotamus", + "koala", + "gorilla", + "kangaroo", + "zebra", + "tortoise", + "otter", + "chimpanzee", + "mongoose", + "leopard", + "raccoon", + "sloth", + "buffalo", + "deer", + "seahorse", + "owl", + "flamingo", + "gecko", + "iguana", + "turtle", + "cobra", + "rabbit", + "cheetah", + "meerkat", + "parrot", + "platypus", + "anteater", + "chameleon", + "gazelle", + "lemur", + "mole", + "orangutan", + "peacock", + "porcupine", + "starfish", + "warthog", + "albatross", + "beaver", + "dove", + "hamster", + "lizard", + "manatee", + "panda", + "polar" +]; + +// ../src/esm/index.js +function getRandomElement(arr) { + return arr[Math.floor(Math.random() * arr.length)]; +} +function generateRandomUsername(userInput, options = {}) { + const { + length = 50, + separator = "-", + wordList = "default", + ensureUnique = false + } = options; + let wordLists = { + default: { + adjectives, + nouns + } + }; + if (!wordLists[wordList]) { + throw new Error(`Invalid word list: ${wordList}`); + } + const { adjectives: adjectives2, nouns: nouns2 } = wordLists[wordList]; + const uniqueSuffix = ensureUnique ? Date.now().toString(36) : ""; + let username; + do { + const randomAdjective = getRandomElement(adjectives2); + const randomNoun = getRandomElement(nouns2); + const randomNumber = Math.floor(Math.random() * 1e3); + username = `${userInput}${separator}${randomAdjective}${separator}${randomNoun}${separator}${randomNumber}${uniqueSuffix}`.substr(0, length); + } while (ensureUnique && !isUsernameUnique(username)); + return username; +} +function isUsernameUnique(username) { + return true; +} +var esm_default = generateRandomUsername; +export { + esm_default as default +}; diff --git a/src/assets/js/simplewebauthn-browser.14.0.0.esm.min.js b/src/assets/js/simplewebauthn-browser.14.0.0.esm.min.js new file mode 100644 index 0000000..8e781f9 --- /dev/null +++ b/src/assets/js/simplewebauthn-browser.14.0.0.esm.min.js @@ -0,0 +1,631 @@ +/** + * Downloaded from https://esm.unpkg.com/@simplewebauthn/browser@14.0.0 + */ + +// unpkg-package:/esm/helpers/bufferToBase64URLString.js +function bufferToBase64URLString(buffer) { + const bytes = new Uint8Array(buffer); + let str = ""; + for (const charCode of bytes) { + str += String.fromCharCode(charCode); + } + const base64String = btoa(str); + return base64String.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} + +// unpkg-package:/esm/helpers/base64URLStringToBuffer.js +function base64URLStringToBuffer(base64URLString) { + const base64 = base64URLString.replace(/-/g, "+").replace(/_/g, "/"); + const padLength = (4 - base64.length % 4) % 4; + const padded = base64.padEnd(base64.length + padLength, "="); + const binary = atob(padded); + const buffer = new ArrayBuffer(binary.length); + const bytes = new Uint8Array(buffer); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return buffer; +} + +// unpkg-package:/esm/helpers/browserSupportsWebAuthn.js +function browserSupportsWebAuthn() { + return _browserSupportsWebAuthnInternals.stubThis(globalThis?.PublicKeyCredential !== void 0 && typeof globalThis.PublicKeyCredential === "function"); +} +var _browserSupportsWebAuthnInternals = { + stubThis: (value) => value +}; + +// unpkg-package:/esm/helpers/toPublicKeyCredentialDescriptor.js +function toPublicKeyCredentialDescriptor(descriptor) { + const { id } = descriptor; + return { + ...descriptor, + id: base64URLStringToBuffer(id), + transports: descriptor.transports, + type: descriptor.type + }; +} + +// unpkg-package:/esm/helpers/isValidDomain.js +function isValidDomain(hostname) { + return ( + // Consider localhost valid as well since it's okay wrt Secure Contexts + hostname === "localhost" || // Support punycode (ACE) or ascii labels and domains + /^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(hostname) + ); +} + +// unpkg-package:/esm/helpers/webAuthnError.js +var WebAuthnError = class extends Error { + constructor({ message, code, cause, name }) { + super(message, { cause }); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = name ?? cause.name; + this.code = code; + } +}; + +// unpkg-package:/esm/helpers/identifyRegistrationError.js +function identifyRegistrationError({ error, options }) { + const { publicKey } = options; + if (!publicKey) { + throw Error("options was missing required publicKey property"); + } + if (error.name === "AbortError") { + if (options.signal instanceof AbortSignal) { + return new WebAuthnError({ + message: "Registration ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", + cause: error + }); + } + } else if (error.name === "ConstraintError") { + if (publicKey.authenticatorSelection?.requireResidentKey === true) { + return new WebAuthnError({ + message: "Discoverable credentials were required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT", + cause: error + }); + } else if ( + // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 + options.mediation === "conditional" && publicKey.authenticatorSelection?.userVerification === "required" + ) { + return new WebAuthnError({ + message: "User verification was required during automatic registration but it could not be performed", + code: "ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE", + cause: error + }); + } else if (publicKey.authenticatorSelection?.userVerification === "required") { + return new WebAuthnError({ + message: "User verification was required but no available authenticator supported it", + code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT", + cause: error + }); + } + } else if (error.name === "InvalidStateError") { + return new WebAuthnError({ + message: "The authenticator was previously registered", + code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", + cause: error + }); + } else if (error.name === "NotAllowedError") { + return new WebAuthnError({ + message: error.message, + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } else if (error.name === "NotSupportedError") { + const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === "public-key"); + if (validPubKeyCredParams.length === 0) { + return new WebAuthnError({ + message: 'No entry in pubKeyCredParams was of type "public-key"', + code: "ERROR_MALFORMED_PUBKEYCREDPARAMS", + cause: error + }); + } + return new WebAuthnError({ + message: "No available authenticator supported any of the specified pubKeyCredParams algorithms", + code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG", + cause: error + }); + } else if (error.name === "SecurityError") { + const effectiveDomain = globalThis.location.hostname; + if (!isValidDomain(effectiveDomain)) { + return new WebAuthnError({ + message: `${globalThis.location.hostname} is an invalid domain`, + code: "ERROR_INVALID_DOMAIN", + cause: error + }); + } else if (publicKey.rp.id !== effectiveDomain) { + return new WebAuthnError({ + message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`, + code: "ERROR_INVALID_RP_ID", + cause: error + }); + } + } else if (error.name === "TypeError") { + if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) { + return new WebAuthnError({ + message: "User ID was not between 1 and 64 characters", + code: "ERROR_INVALID_USER_ID_LENGTH", + cause: error + }); + } + } else if (error.name === "UnknownError") { + return new WebAuthnError({ + message: "The authenticator was unable to process the specified options, or could not create a new credential", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", + cause: error + }); + } + return error; +} + +// unpkg-package:/esm/helpers/webAuthnAbortService.js +var BaseWebAuthnAbortService = class { + constructor() { + Object.defineProperty(this, "controller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } + createNewAbortSignal() { + if (this.controller) { + const abortError = new Error("Cancelling existing WebAuthn API call for new one"); + abortError.name = "AbortError"; + this.controller.abort(abortError); + } + const newController = new AbortController(); + this.controller = newController; + return newController.signal; + } + cancelCeremony() { + if (this.controller) { + const abortError = new Error("Manually cancelling existing WebAuthn API call"); + abortError.name = "AbortError"; + this.controller.abort(abortError); + this.controller = void 0; + } + } +}; +var WebAuthnAbortService = new BaseWebAuthnAbortService(); + +// unpkg-package:/esm/helpers/toAuthenticatorAttachment.js +var attachments = ["cross-platform", "platform"]; +function toAuthenticatorAttachment(attachment) { + if (!attachment) { + return; + } + if (attachments.indexOf(attachment) < 0) { + return; + } + return attachment; +} + +// unpkg-package:/esm/methods/startRegistration.js +async function startRegistration(options) { + if (!options.optionsJSON && options.challenge) { + console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."); + options = { optionsJSON: options }; + } + const { optionsJSON, useAutoRegister = false } = options; + if (!browserSupportsWebAuthn()) { + throw new Error("WebAuthn is not supported in this browser"); + } + const publicKey = { + ...optionsJSON, + challenge: base64URLStringToBuffer(optionsJSON.challenge), + user: { + ...optionsJSON.user, + id: base64URLStringToBuffer(optionsJSON.user.id) + }, + excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor) + }; + const createOptions = {}; + if (useAutoRegister) { + createOptions.mediation = "conditional"; + } + createOptions.publicKey = publicKey; + createOptions.signal = WebAuthnAbortService.createNewAbortSignal(); + let credential; + try { + credential = await navigator.credentials.create( + // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+ + createOptions + ); + } catch (err) { + throw identifyRegistrationError({ error: err, options: createOptions }); + } + if (!credential) { + throw new Error("Registration was not completed"); + } + const { id, rawId, response, type } = credential; + let transports = void 0; + if (typeof response.getTransports === "function") { + transports = response.getTransports(); + } + let responsePublicKeyAlgorithm = void 0; + if (typeof response.getPublicKeyAlgorithm === "function") { + try { + responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm(); + } catch (error) { + warnOnBrokenImplementation("getPublicKeyAlgorithm()", error); + } + } + let responsePublicKey = void 0; + if (typeof response.getPublicKey === "function") { + try { + const _publicKey = response.getPublicKey(); + if (_publicKey !== null) { + responsePublicKey = bufferToBase64URLString(_publicKey); + } + } catch (error) { + warnOnBrokenImplementation("getPublicKey()", error); + } + } + let responseAuthenticatorData; + if (typeof response.getAuthenticatorData === "function") { + try { + responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData()); + } catch (error) { + warnOnBrokenImplementation("getAuthenticatorData()", error); + } + } + return { + id, + rawId: bufferToBase64URLString(rawId), + response: { + attestationObject: bufferToBase64URLString(response.attestationObject), + clientDataJSON: bufferToBase64URLString(response.clientDataJSON), + transports, + publicKeyAlgorithm: responsePublicKeyAlgorithm, + publicKey: responsePublicKey, + authenticatorData: responseAuthenticatorData + }, + type, + clientExtensionResults: credential.getClientExtensionResults(), + authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment) + }; +} +function warnOnBrokenImplementation(methodName, cause) { + console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them. +`, cause); +} + +// unpkg-package:/esm/helpers/browserSupportsWebAuthnAutofill.js +function browserSupportsWebAuthnAutofill() { + if (!browserSupportsWebAuthn()) { + return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false))); + } + const globalPublicKeyCredential = globalThis.PublicKeyCredential; + if (globalPublicKeyCredential?.isConditionalMediationAvailable === void 0) { + return _browserSupportsWebAuthnAutofillInternals.stubThis(new Promise((resolve) => resolve(false))); + } + return _browserSupportsWebAuthnAutofillInternals.stubThis(globalPublicKeyCredential.isConditionalMediationAvailable()); +} +var _browserSupportsWebAuthnAutofillInternals = { + stubThis: (value) => value +}; + +// unpkg-package:/esm/helpers/identifyAuthenticationError.js +function identifyAuthenticationError({ error, options }) { + const { publicKey } = options; + if (!publicKey) { + throw Error("options was missing required publicKey property"); + } + if (error.name === "AbortError") { + if (options.signal instanceof AbortSignal) { + return new WebAuthnError({ + message: "Authentication ceremony was sent an abort signal", + code: "ERROR_CEREMONY_ABORTED", + cause: error + }); + } + } else if (error.name === "NotAllowedError") { + return new WebAuthnError({ + message: error.message, + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); + } else if (error.name === "SecurityError") { + const effectiveDomain = globalThis.location.hostname; + if (!isValidDomain(effectiveDomain)) { + return new WebAuthnError({ + message: `${globalThis.location.hostname} is an invalid domain`, + code: "ERROR_INVALID_DOMAIN", + cause: error + }); + } else if (publicKey.rpId !== effectiveDomain) { + return new WebAuthnError({ + message: `The RP ID "${publicKey.rpId}" is invalid for this domain`, + code: "ERROR_INVALID_RP_ID", + cause: error + }); + } + } else if (error.name === "UnknownError") { + return new WebAuthnError({ + message: "The authenticator was unable to process the specified options, or could not create a new assertion signature", + code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", + cause: error + }); + } + return error; +} + +// unpkg-package:/esm/methods/startAuthentication.js +async function startAuthentication(options) { + if (!options.optionsJSON && options.challenge) { + console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."); + options = { optionsJSON: options }; + } + const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true } = options; + if (!browserSupportsWebAuthn()) { + throw new Error("WebAuthn is not supported in this browser"); + } + let allowCredentials; + if (optionsJSON.allowCredentials?.length !== 0) { + allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor); + } + const publicKey = { + ...optionsJSON, + challenge: base64URLStringToBuffer(optionsJSON.challenge), + allowCredentials + }; + const getOptions = {}; + if (useBrowserAutofill) { + if (!await browserSupportsWebAuthnAutofill()) { + throw Error("Browser does not support WebAuthn autofill"); + } + const eligibleInputs = document.querySelectorAll("input[autocomplete$='webauthn']"); + if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) { + throw Error('No with "webauthn" as the only or last value in its `autocomplete` attribute was detected'); + } + getOptions.mediation = "conditional"; + publicKey.allowCredentials = []; + } + getOptions.publicKey = publicKey; + getOptions.signal = WebAuthnAbortService.createNewAbortSignal(); + let credential; + try { + credential = await navigator.credentials.get( + // TODO: Newer versions of Deno require this casting, revisit once we're using Deno 2.6+ + getOptions + ); + } catch (err) { + throw identifyAuthenticationError({ error: err, options: getOptions }); + } + if (!credential) { + throw new Error("Authentication was not completed"); + } + const { id, rawId, response, type } = credential; + let userHandle = void 0; + if (response.userHandle) { + userHandle = bufferToBase64URLString(response.userHandle); + } + return { + id, + rawId: bufferToBase64URLString(rawId), + response: { + authenticatorData: bufferToBase64URLString(response.authenticatorData), + clientDataJSON: bufferToBase64URLString(response.clientDataJSON), + signature: bufferToBase64URLString(response.signature), + userHandle + }, + type, + clientExtensionResults: credential.getClientExtensionResults(), + authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment) + }; +} + +// unpkg-package:/esm/helpers/identifySignalError.js +function identifySignalError({ error, options }) { + if (error.name === "SecurityError") { + const effectiveDomain = globalThis.location.hostname; + if (!isValidDomain(effectiveDomain)) { + return new WebAuthnError({ + message: `"${globalThis.location.hostname}" is an invalid domain`, + code: "ERROR_INVALID_DOMAIN", + cause: error + }); + } + return new WebAuthnError({ + message: `The browser does not support Related Origins to enable signals for RP ID "${options.rpID}" on domain "${globalThis.location.hostname}"`, + code: "ERROR_INVALID_RP_ID", + cause: error + }); + } + if (options.signalName === "unknownCredential") { + if (error.name === "TypeError") { + return new WebAuthnError({ + message: "credentialID is an invalid base64url string", + code: "ERROR_SIGNAL_INVALID_ARGUMENT", + cause: error + }); + } + } else if (options.signalName === "allAcceptedCredentials") { + if (error.name === "TypeError") { + return new WebAuthnError({ + message: "userID, or an entry in allAcceptedCredentialIDs, is an invalid base64url string", + code: "ERROR_SIGNAL_INVALID_ARGUMENT", + cause: error + }); + } + } else if (options.signalName === "currentUserDetails") { + if (error.name === "TypeError") { + return new WebAuthnError({ + message: "userID is an invalid base64url string", + code: "ERROR_SIGNAL_INVALID_ARGUMENT", + cause: error + }); + } + } + return new WebAuthnError({ + message: error.message, + code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", + cause: error + }); +} + +// unpkg-package:/esm/methods/sendSignal.js +async function sendSignal(opts) { + const { signalName } = opts; + if (signalName === "unknownCredential") { + return _callSignalUnknownCredential(opts); + } else if (signalName === "allAcceptedCredentials") { + return _callSignalAllAcceptedCredentials(opts); + } else if (signalName === "currentUserDetails") { + return _callSignalCurrentUserDetails(opts); + } + throw new Error(`Received unrecognized signalName "${opts.signalName}"`); +} +async function _callSignalUnknownCredential(opts) { + const globalPublicKeyCredential = globalThis.PublicKeyCredential; + if (typeof globalPublicKeyCredential.signalUnknownCredential !== "function") { + throw new Error("This browser does not support PublicKeyCredential.signalUnknownCredential()"); + } + try { + await globalPublicKeyCredential.signalUnknownCredential({ + rpId: opts.rpID, + credentialId: opts.credentialID + }); + } catch (err) { + throw identifySignalError({ error: err, options: opts }); + } + return void 0; +} +async function _callSignalAllAcceptedCredentials(opts) { + const globalPublicKeyCredential = globalThis.PublicKeyCredential; + if (typeof globalPublicKeyCredential.signalAllAcceptedCredentials !== "function") { + throw new Error("This browser does not support PublicKeyCredential.signalAllAcceptedCredentials()"); + } + try { + await globalPublicKeyCredential.signalAllAcceptedCredentials({ + rpId: opts.rpID, + userId: opts.userID, + allAcceptedCredentialIds: opts.allAcceptedCredentialIDs + }); + } catch (err) { + throw identifySignalError({ error: err, options: opts }); + } + return void 0; +} +async function _callSignalCurrentUserDetails(opts) { + const globalPublicKeyCredential = globalThis.PublicKeyCredential; + if (typeof globalPublicKeyCredential.signalCurrentUserDetails !== "function") { + throw new Error("This browser does not support PublicKeyCredential.signalCurrentUserDetails()"); + } + try { + await globalPublicKeyCredential.signalCurrentUserDetails({ + rpId: opts.rpID, + userId: opts.userID, + name: opts.userName, + displayName: opts.userDisplayName ?? "" + }); + } catch (err) { + throw identifySignalError({ error: err, options: opts }); + } + return void 0; +} + +// unpkg-package:/esm/helpers/getBrowserCapabilities.js +async function getBrowserCapabilities() { + if (typeof PublicKeyCredential.getClientCapabilities === "function") { + const capabilities = await PublicKeyCredential.getClientCapabilities(); + let _userVerifyingPlatformAuthenticator = mapCapabilityToEnum(capabilities.userVerifyingPlatformAuthenticator); + if (_userVerifyingPlatformAuthenticator === "unknown" && typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable === "function") { + const isUVPAA = await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); + if (isUVPAA) { + _userVerifyingPlatformAuthenticator = "supported"; + } else { + _userVerifyingPlatformAuthenticator = "unsupported"; + } + } + let _conditionalGet = mapCapabilityToEnum(capabilities.conditionalGet); + if (_conditionalGet === "unknown" && typeof PublicKeyCredential.isConditionalMediationAvailable === "function") { + const isCMA = await PublicKeyCredential.isConditionalMediationAvailable(); + if (isCMA) { + _conditionalGet = "supported"; + } else { + _conditionalGet = "unsupported"; + } + } + return _getBrowserCapabilitiesInternals.stubThis({ + conditionalCreate: mapCapabilityToEnum(capabilities.conditionalCreate), + conditionalGet: _conditionalGet, + hybridTransport: mapCapabilityToEnum(capabilities.hybridTransport), + passkeyPlatformAuthenticator: mapCapabilityToEnum(capabilities.passkeyPlatformAuthenticator), + userVerifyingPlatformAuthenticator: _userVerifyingPlatformAuthenticator, + relatedOrigins: mapCapabilityToEnum(capabilities.relatedOrigins), + signalAllAcceptedCredentials: mapCapabilityToEnum(capabilities.signalAllAcceptedCredentials), + signalCurrentUserDetails: mapCapabilityToEnum(capabilities.signalCurrentUserDetails), + signalUnknownCredential: mapCapabilityToEnum(capabilities.signalUnknownCredential) + }); + } + return _getBrowserCapabilitiesInternals.stubThis({ + conditionalCreate: "unknown", + conditionalGet: "unknown", + hybridTransport: "unknown", + passkeyPlatformAuthenticator: "unknown", + userVerifyingPlatformAuthenticator: "unknown", + relatedOrigins: "unknown", + signalAllAcceptedCredentials: "unknown", + signalCurrentUserDetails: "unknown", + signalUnknownCredential: "unknown" + }); +} +function mapCapabilityToEnum(value) { + if (value === true) { + return "supported"; + } else if (value === false) { + return "unsupported"; + } else if (typeof value === "undefined") { + return "unknown"; + } else { + throw new Error("Unexpected capability value:", value); + } +} +var _getBrowserCapabilitiesInternals = { + stubThis: (value) => value +}; + +// unpkg-package:/esm/helpers/browserSupportsPasskeys.js +async function browserSupportsPasskeys() { + if (!browserSupportsWebAuthn()) { + return new Promise((resolve) => resolve(false)); + } + const capabilities = await getBrowserCapabilities(); + const { passkeyPlatformAuthenticator, userVerifyingPlatformAuthenticator, hybridTransport } = capabilities; + return passkeyPlatformAuthenticator === "supported" || hybridTransport === "supported" || userVerifyingPlatformAuthenticator === "supported"; +} + +// unpkg-package:/esm/helpers/platformAuthenticatorIsAvailable.js +function platformAuthenticatorIsAvailable() { + if (!browserSupportsWebAuthn()) { + return new Promise((resolve) => resolve(false)); + } + return PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable(); +} +export { + WebAuthnAbortService, + WebAuthnError, + _browserSupportsWebAuthnAutofillInternals, + _browserSupportsWebAuthnInternals, + _getBrowserCapabilitiesInternals, + base64URLStringToBuffer, + browserSupportsPasskeys, + browserSupportsWebAuthn, + browserSupportsWebAuthnAutofill, + bufferToBase64URLString, + getBrowserCapabilities, + platformAuthenticatorIsAvailable, + sendSignal, + startAuthentication, + startRegistration +}; diff --git a/src/assets/js/simplewebauthn-browser.14.0.0.umd.min.js b/src/assets/js/simplewebauthn-browser.14.0.0.umd.min.js deleted file mode 100644 index 66f6ddc..0000000 --- a/src/assets/js/simplewebauthn-browser.14.0.0.umd.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/* [@simplewebauthn/browser@14.0.0] */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).SimpleWebAuthnBrowser={})}(this,(function(e){"use strict";function t(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function n(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,"="),i=atob(r),o=new ArrayBuffer(i.length),a=new Uint8Array(o);for(let e=0;ee};function o(e){const{id:t}=e;return{...e,id:n(t),transports:e.transports,type:e.type}}function a(e){return"localhost"===e||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}class s extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}}const l=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}},c=["cross-platform","platform"];function u(e){if(e&&!(c.indexOf(e)<0))return e}function d(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function p(){if(!r())return h.stubThis(new Promise((e=>e(!1))));const e=globalThis.PublicKeyCredential;return void 0===e?.isConditionalMediationAvailable?h.stubThis(new Promise((e=>e(!1)))):h.stubThis(e.isConditionalMediationAvailable())}const h={stubThis:e=>e};function f({error:e,options:t}){if("SecurityError"===e.name){return a(globalThis.location.hostname)?new s({message:`The browser does not support Related Origins to enable signals for RP ID "${t.rpID}" on domain "${globalThis.location.hostname}"`,code:"ERROR_INVALID_RP_ID",cause:e}):new s({message:`"${globalThis.location.hostname}" is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}if("unknownCredential"===t.signalName){if("TypeError"===e.name)return new s({message:"credentialID is an invalid base64url string",code:"ERROR_SIGNAL_INVALID_ARGUMENT",cause:e})}else if("allAcceptedCredentials"===t.signalName){if("TypeError"===e.name)return new s({message:"userID, or an entry in allAcceptedCredentialIDs, is an invalid base64url string",code:"ERROR_SIGNAL_INVALID_ARGUMENT",cause:e})}else if("currentUserDetails"===t.signalName&&"TypeError"===e.name)return new s({message:"userID is an invalid base64url string",code:"ERROR_SIGNAL_INVALID_ARGUMENT",cause:e});return new s({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}async function g(){if("function"==typeof PublicKeyCredential.getClientCapabilities){const e=await PublicKeyCredential.getClientCapabilities();let t=w(e.userVerifyingPlatformAuthenticator);if("unknown"===t&&"function"==typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable){t=await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()?"supported":"unsupported"}let n=w(e.conditionalGet);if("unknown"===n&&"function"==typeof PublicKeyCredential.isConditionalMediationAvailable){n=await PublicKeyCredential.isConditionalMediationAvailable()?"supported":"unsupported"}return b.stubThis({conditionalCreate:w(e.conditionalCreate),conditionalGet:n,hybridTransport:w(e.hybridTransport),passkeyPlatformAuthenticator:w(e.passkeyPlatformAuthenticator),userVerifyingPlatformAuthenticator:t,relatedOrigins:w(e.relatedOrigins),signalAllAcceptedCredentials:w(e.signalAllAcceptedCredentials),signalCurrentUserDetails:w(e.signalCurrentUserDetails),signalUnknownCredential:w(e.signalUnknownCredential)})}return b.stubThis({conditionalCreate:"unknown",conditionalGet:"unknown",hybridTransport:"unknown",passkeyPlatformAuthenticator:"unknown",userVerifyingPlatformAuthenticator:"unknown",relatedOrigins:"unknown",signalAllAcceptedCredentials:"unknown",signalCurrentUserDetails:"unknown",signalUnknownCredential:"unknown"})}function w(e){if(!0===e)return"supported";if(!1===e)return"unsupported";if(void 0===e)return"unknown";throw new Error("Unexpected capability value:",e)}const b={stubThis:e=>e};e.WebAuthnAbortService=l,e.WebAuthnError=s,e._browserSupportsWebAuthnAutofillInternals=h,e._browserSupportsWebAuthnInternals=i,e._getBrowserCapabilitiesInternals=b,e.base64URLStringToBuffer=n,e.browserSupportsPasskeys=async function(){if(!r())return new Promise((e=>e(!1)));const e=await g(),{passkeyPlatformAuthenticator:t,userVerifyingPlatformAuthenticator:n,hybridTransport:i}=e;return"supported"===t||"supported"===i||"supported"===n},e.browserSupportsWebAuthn=r,e.browserSupportsWebAuthnAutofill=p,e.bufferToBase64URLString=t,e.getBrowserCapabilities=g,e.platformAuthenticatorIsAvailable=function(){return r()?PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():new Promise((e=>e(!1)))},e.sendSignal=async function(e){const{signalName:t}=e;if("unknownCredential"===t)return async function(e){const t=globalThis.PublicKeyCredential;if("function"!=typeof t.signalUnknownCredential)throw new Error("This browser does not support PublicKeyCredential.signalUnknownCredential()");try{await t.signalUnknownCredential({rpId:e.rpID,credentialId:e.credentialID})}catch(t){throw f({error:t,options:e})}return}(e);if("allAcceptedCredentials"===t)return async function(e){const t=globalThis.PublicKeyCredential;if("function"!=typeof t.signalAllAcceptedCredentials)throw new Error("This browser does not support PublicKeyCredential.signalAllAcceptedCredentials()");try{await t.signalAllAcceptedCredentials({rpId:e.rpID,userId:e.userID,allAcceptedCredentialIds:e.allAcceptedCredentialIDs})}catch(t){throw f({error:t,options:e})}return}(e);if("currentUserDetails"===t)return async function(e){const t=globalThis.PublicKeyCredential;if("function"!=typeof t.signalCurrentUserDetails)throw new Error("This browser does not support PublicKeyCredential.signalCurrentUserDetails()");try{await t.signalCurrentUserDetails({rpId:e.rpID,userId:e.userID,name:e.userName,displayName:e.userDisplayName??""})}catch(t){throw f({error:t,options:e})}return}(e);throw new Error(`Received unrecognized signalName "${e.signalName}"`)},e.startAuthentication=async function(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:i,useBrowserAutofill:c=!1,verifyBrowserAutofillInput:d=!0}=e;if(!r())throw new Error("WebAuthn is not supported in this browser");let h;0!==i.allowCredentials?.length&&(h=i.allowCredentials?.map(o));const f={...i,challenge:n(i.challenge),allowCredentials:h},g={};if(c){if(!await p())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&d)throw Error('No with "webauthn" as the only or last value in its `autocomplete` attribute was detected');g.mediation="conditional",f.allowCredentials=[]}let w;g.publicKey=f,g.signal=l.createNewAbortSignal();try{w=await navigator.credentials.get(g)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new s({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new s({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!a(t))return new s({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new s({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new s({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:g})}if(!w)throw new Error("Authentication was not completed");const{id:b,rawId:A,response:R,type:m}=w;let y;return R.userHandle&&(y=t(R.userHandle)),{id:b,rawId:t(A),response:{authenticatorData:t(R.authenticatorData),clientDataJSON:t(R.clientDataJSON),signature:t(R.signature),userHandle:y},type:m,clientExtensionResults:w.getClientExtensionResults(),authenticatorAttachment:u(w.authenticatorAttachment)}},e.startRegistration=async function(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});const{optionsJSON:i,useAutoRegister:c=!1}=e;if(!r())throw new Error("WebAuthn is not supported in this browser");const p={...i,challenge:n(i.challenge),user:{...i.user,id:n(i.user.id)},excludeCredentials:i.excludeCredentials?.map(o)},h={};let f;c&&(h.mediation="conditional"),h.publicKey=p,h.signal=l.createNewAbortSignal();try{f=await navigator.credentials.create(h)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new s({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===n.authenticatorSelection?.requireResidentKey)return new s({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("conditional"===t.mediation&&"required"===n.authenticatorSelection?.userVerification)return new s({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if("required"===n.authenticatorSelection?.userVerification)return new s({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new s({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new s({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===n.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new s({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new s({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=globalThis.location.hostname;if(!a(t))return new s({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new s({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new s({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new s({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:h})}if(!f)throw new Error("Registration was not completed");const{id:g,rawId:w,response:b,type:A}=f;let R,m,y,E;if("function"==typeof b.getTransports&&(R=b.getTransports()),"function"==typeof b.getPublicKeyAlgorithm)try{m=b.getPublicKeyAlgorithm()}catch(e){d("getPublicKeyAlgorithm()",e)}if("function"==typeof b.getPublicKey)try{const e=b.getPublicKey();null!==e&&(y=t(e))}catch(e){d("getPublicKey()",e)}if("function"==typeof b.getAuthenticatorData)try{E=t(b.getAuthenticatorData())}catch(e){d("getAuthenticatorData()",e)}return{id:g,rawId:t(w),response:{attestationObject:t(b.attestationObject),clientDataJSON:t(b.clientDataJSON),transports:R,publicKeyAlgorithm:m,publicKey:y,authenticatorData:E},type:A,clientExtensionResults:f.getClientExtensionResults(),authenticatorAttachment:u(f.authenticatorAttachment)}}})); diff --git a/src/assets/js/webauthn-demo.js b/src/assets/js/webauthn-demo.js index ba88719..12d5d61 100644 --- a/src/assets/js/webauthn-demo.js +++ b/src/assets/js/webauthn-demo.js @@ -1,9 +1,10 @@ -const { +import { browserSupportsWebAuthn, startRegistration, startAuthentication, browserSupportsWebAuthnAutofill, -} = SimpleWebAuthnBrowser; +} from './simplewebauthn-browser.14.0.0.esm.min.js'; +import generateRandomUsername from './random-username-gen.2.0.2.esm.js'; // The API is served by the same Worker as the page, in development (`wrangler dev`) and production const API = '/api/v1'; @@ -305,8 +306,10 @@ document.addEventListener('alpine:init', () => { } = this.options; if (!this.username) { - this.showErrorAlert('Please enter a username to register'); - return; + // The generator always prefixes its input and a separator; with no input, drop the + // leading separator + this.username = generateRandomUsername('').replace(/^-/, ''); + this._saveUsername(this.username); } const registrationOptionsJSON = await postJSON('/registration/options', { diff --git a/src/index.njk b/src/index.njk index 7aeb617..f36adc9 100644 --- a/src/index.njk +++ b/src/index.njk @@ -2,11 +2,11 @@ layout: layouts/base.njk title: Passkey Developer Tools description: A collection of developer tools for passkeys and WebAuthn! +alpine: true extra_scripts: - - /assets/js/simplewebauthn-browser.14.0.0.umd.min.js - /assets/js/ordered-checkbox-list.js +extra_modules: - /assets/js/webauthn-demo.js - - /assets/js/alpinejs.3.17.5.min.js ---
diff --git a/src/profile/index.njk b/src/profile/index.njk index 9a17996..6b54edb 100644 --- a/src/profile/index.njk +++ b/src/profile/index.njk @@ -3,9 +3,9 @@ layout: layouts/base.njk title: Your Passkeys | Passkey Developer Tools description: The passkeys registered for the signed-in demo user. eleventyExcludeFromCollections: true +alpine: true extra_scripts: - /assets/js/profile.js - - /assets/js/alpinejs.3.17.5.min.js ---