packages feed

webauthn-client (empty) → 0.1.0.0

raw patch · 8 files changed

+955/−0 lines, 8 filesdep +aesondep +basedep +base64-bytestring

Dependencies added: aeson, base, base64-bytestring, bytestring, crypton, directory, filepath, hspec, http-client, http-client-tls, http-types, temporary, text, unix, webauthn-client

Files

+ CHANGELOG.md view
@@ -0,0 +1,22 @@+# Changelog++All notable changes to this project will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),+and this project adheres to the [Haskell Package Versioning+Policy](https://pvp.haskell.org/).++## [0.1.0.0] - 2026-12-01++### Added++- Software WebAuthn authenticator: P-256 key generation, `fmt: none`+  registration attestation, and ES256 assertion signing.+- Parsing of `PublicKeyCredentialCreationOptions` and+  `PublicKeyCredentialRequestOptions` JSON.+- `Credential` type with JSON instances and owner-only file persistence.+- `WebAuthn.Client.Http`: enrollment and authentication against a relying+  party's options/verify endpoints, with a configurable `Endpoints` record and+  a `exampleEndpoints` adapter.+- Nix flake providing a dev shell with GHC 9.12.4, `cabal-install`, `hlint`+  and `ghcid`, plus `nix build` targets for the library and the test suite.
+ LICENSE view
@@ -0,0 +1,28 @@+BSD 3-Clause License++Copyright (c) 2026, Doug Beardsley++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this+   list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice,+   this list of conditions and the following disclaimer in the documentation+   and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its+   contributors may be used to endorse or promote products derived from+   this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,132 @@+# webauthn-client++A software WebAuthn authenticator and JSON/HTTP client for Haskell.++WebAuthn's client side is normally the browser plus a hardware or platform+authenticator. What a relying party actually verifies, though, is an ES256+signature by the public key it enrolled for the credential, over++```+authData || SHA-256(clientDataJSON)+```++`webauthn-client` performs that same operation with a P-256 keypair the caller+holds. That makes passkey-gated APIs usable from a headless program: a CLI, a+daemon, a test suite, or a service that cannot show a WebAuthn prompt.++## What it is — and is not++It is a **software authenticator**. The private key is generated locally,+enrolled once with the relying party, and stored by you (the library can write+it owner-only with `saveCredentialFile`).++It is **not** a way to use an existing platform passkey (Touch ID, iCloud+Keychain, Windows Hello) or a hardware security key. Those private keys never+leave their authenticator, and are bound to the app/origin that owns them.++Registration uses attestation format `none`: the authenticator makes no+attestation claims, which the WebAuthn specification explicitly permits. A+relying party that *requires* attestation, or that demands a particular AAGUID,+will reject these credentials.++## Quick start++```haskell+{-# LANGUAGE OverloadedStrings #-}++import WebAuthn.Client+import WebAuthn.Client.Http++main :: IO ()+main = do+  let endpoints = exampleEndpoints "https://gateway.example.com:9090"++  -- One-time: redeem an enrollment token for a software credential.+  enrolled <- enroll endpoints [("X-Enroll-Token", token)]+  cred <- case enrolled of+    Left err  -> error (show err)+    Right cred -> pure cred+  saveCredentialFile "gateway-credential.json" cred++  -- Later: sign in and get the relying party's session cookie.+  authenticated <- authenticateWithStore+    endpoints+    (\c -> saveCredentialFile "gateway-credential.json" c)+    cred+  case authenticated of+    Left err -> error (show err)+    Right (sessionToken, _updated) ->+      putStrLn ("session: " <> show sessionToken)+```++## Lower-level API++If your relying party does not follow the conventional options/verify JSON+endpoints, use the pure ceremony functions directly:++```haskell+import WebAuthn.Client++-- registration+(cred, registrationResponseJson) <-+  createRegistration "https://rp.example" "rp.example" challenge++-- authentication+(cred', assertionResponseJson) <- createAssertion cred challenge+```++The response values are ready to be JSON-encoded into the fields a browser+would send (`clientDataJSON`, `attestationObject`/`authenticatorData`,+`signature`, `rawId`), all base64url-encoded as WebAuthn requires.++`assertionParts` exposes the raw `(clientDataJSON, authenticatorData,+Signature)` triple for tests and custom verifiers.++## Credentials and the sign counter++`Credential` is `ToJSON`/`FromJSON`, with the private key as an integer. There+is no hardware sign counter, so the library increments a software counter for+each assertion and stores it in the credential. Persist the *returned*+credential: `authenticateWithStore` calls your store before sending the+assertion, so a lost response can never make the next attempt replay an older+counter.++Treat a stored credential like a password. `saveCredentialFile` writes it with+mode `0600`.++## Configuration++`Endpoints` describes the four URLs and the session-cookie name; there is no+standard for them, so they are configuration rather than a constant.+`exampleEndpoints` is the adapter this package ships and works as a template for+others.++## Development++A Nix flake provides a dev shell with GHC 9.12.4 (matching `tested-with`),+`cabal-install`, `hlint` and `ghcid`, and with this project's dependencies+already registered — so `cabal build` inside the shell uses the Nix-provided+packages instead of resolving against Hackage.++```console+$ nix develop+$ cabal build all+$ cabal test all+```++Without entering a shell:++```console+$ nix build          # the library+$ nix build .#test   # build and run the hspec suite+$ nix flake check    # build the library and run the tests+```++The first invocation downloads a prebuilt GHC and dependency closure from+`cache.iog.io`. `nixConfig` in `flake.nix` requests that cache, but Nix only+honors it for flake configs you trust — either pass `--accept-flake-config`+once, or add the substituter and key to `~/.config/nix/nix.conf`.++## License++BSD-3-Clause.
+ src/WebAuthn/Client.hs view
@@ -0,0 +1,353 @@+{-# LANGUAGE OverloadedStrings #-}++-- | A software WebAuthn authenticator: the client half of a passkey ceremony,+-- as a library.+--+-- WebAuthn's client side is normally the browser plus a hardware or platform+-- authenticator. All the RP actually verifies, though, is an ES256 signature by+-- the public key it enrolled for the credential, over+-- @authData || SHA-256(clientDataJSON)@. This module performs that same+-- operation with a P-256 keypair held by the caller, which makes passkey-gated+-- APIs usable from a headless program.+--+-- The wire formats follow the WebAuthn Level 2 specification and, in+-- particular, the attestation format @none@: this authenticator makes no+-- attestation claims. Relying parties that require attestation, or that demand+-- an AAGUID with a known model, will not accept it — by design.+--+-- == Security+--+-- The private key is the credential. Anyone who can read the stored+-- 'Credential' can sign in exactly as the caller can. Persist it with+-- 'saveCredentialFile' (which sets mode @0600@) or with equivalent care.+module WebAuthn.Client+  ( -- * Credentials+    Credential (..)+  , loadCredentialFile+  , saveCredentialFile+    -- * Ceremony options+  , RegistrationOptions (..)+  , AuthenticationOptions (..)+  , parseRegistrationOptions+  , parseAuthenticationOptions+    -- * Ceremonies+  , createRegistration+  , createAssertion+  , registrationResponse+  , assertionResponse+  , assertionParts+    -- * Encoding helpers+  , b64url+  , unb64url+  , sha256Raw+  ) where++import Control.Exception (SomeException, try)+import Crypto.Hash (Digest, SHA256 (..), hash)+import Crypto.PubKey.ECC.ECDSA+  ( PrivateKey (..), PublicKey (..), Signature (..), sign )+import Crypto.PubKey.ECC.Generate (generate)+import Crypto.PubKey.ECC.Types+  ( CurveName (SEC_p256r1), Point (..), getCurveByName )+import Crypto.Random (getRandomBytes)+import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), object, withObject, (.:), (.=))+import Data.Aeson qualified as A+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Bits (shiftR, (.&.))+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Base64.URL qualified as B64Url+import Data.ByteString.Char8 qualified as BC+import Data.ByteString.Lazy qualified as BL+import Data.Char (isDigit)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import System.Directory (createDirectoryIfMissing, doesFileExist)+import System.FilePath (takeDirectory)+import System.Posix.Files (setFileMode)++-- | An enrolled software credential. The private key is a P-256 scalar; the+-- sign counter is incremented for every assertion.+data Credential = Credential+  { credentialId :: !ByteString+    -- ^ The raw WebAuthn credential id (random, 32 bytes for new credentials).+  , privateKey :: !Integer+    -- ^ The P-256 private scalar.+  , rpId :: !Text+    -- ^ The relying-party id the credential was created for.+  , origin :: !Text+    -- ^ The origin used in @clientDataJSON@ during registration.+  , signCount :: !Int+    -- ^ The last sign counter signed. Assertions use a greater value.+  } deriving stock (Eq, Show)++instance ToJSON Credential where+  toJSON cred = object+    [ "credential_id" .= b64url (credentialId cred)+    , "private_key"   .= privateKey cred+    , "rp_id"         .= rpId cred+    , "origin"        .= origin cred+    , "sign_count"    .= signCount cred+    ]++instance FromJSON Credential where+  parseJSON = withObject "Credential" $ \o -> do+    rawId <- o .: "credential_id"+    cid <- either (fail . T.unpack) pure (unb64url rawId)+    Credential cid+      <$> o .: "private_key"+      <*> o .: "rp_id"+      <*> o .: "origin"+      <*> o .: "sign_count"++-- | Read a credential written by 'saveCredentialFile'. @Right Nothing@ means+-- the file does not exist; @Left@ means it exists but could not be read.+loadCredentialFile :: FilePath -> IO (Either Text (Maybe Credential))+loadCredentialFile path = do+  exists <- doesFileExist path+  if not exists+    then pure (Right Nothing)+    else do+      raw <- BL.readFile path+      pure $ case A.eitherDecode raw of+        Left err -> Left ("could not parse the credential at " <> T.pack path+                           <> ": " <> T.pack err)+        Right cred -> Right (Just cred)++-- | Write a credential owner-only (mode @0600@).+saveCredentialFile :: FilePath -> Credential -> IO (Either Text ())+saveCredentialFile path cred = do+  let write = do+        createDirectoryIfMissing True (takeDirectory path)+        BL.writeFile path (A.encode cred)+        setFileMode path 0o600+  result <- try write+  pure $ case result of+    Left (e :: SomeException) ->+      Left ("could not write the credential at " <> T.pack path <> ": "+             <> T.pack (show e))+    Right () -> Right ()++-- | The fields of a @PublicKeyCredentialCreationOptions@ that a software+-- authenticator needs.+data RegistrationOptions = RegistrationOptions+  { roChallenge :: !Text+  , roRpId :: !Text+  } deriving stock (Eq, Show)++-- | The fields of a @PublicKeyCredentialRequestOptions@ that a software+-- authenticator needs.+data AuthenticationOptions = AuthenticationOptions+  { aoChallenge :: !Text+  , aoRpId :: !Text+  } deriving stock (Eq, Show)++parseRegistrationOptions :: Value -> Either Text RegistrationOptions+parseRegistrationOptions value =+  RegistrationOptions+    <$> stringField value "challenge"+    <*> nestedStringField value "rp" "id"++parseAuthenticationOptions :: Value -> Either Text AuthenticationOptions+parseAuthenticationOptions value =+  AuthenticationOptions+    <$> stringField value "challenge"+    <*> stringField value "rpId"++-- | Generate a keypair and a credential id, and build the+-- @navigator.credentials.create()@ response for @challenge@.+createRegistration+  :: Text        -- ^ origin+  -> Text        -- ^ relying-party id+  -> Text        -- ^ challenge+  -> IO (Credential, Value)+createRegistration originText rpId' challenge = do+  (pub, priv) <- generate (getCurveByName SEC_p256r1)+  credId <- getRandomBytes 32+  let PrivateKey _ d = priv+      cred = Credential+        { credentialId = credId+        , privateKey = d+        , rpId = rpId'+        , origin = originText+        , signCount = 0+        }+  pure (cred, registrationResponse originText rpId' challenge credId (public_q pub))++-- | Build the @navigator.credentials.get()@ response for @challenge@, using and+-- incrementing the credential's sign counter.+createAssertion :: Credential -> Text -> IO (Credential, Value)+createAssertion cred challenge = do+  let counter = signCount cred + 1+      cred' = cred { signCount = counter }+      priv = PrivateKey (getCurveByName SEC_p256r1) (privateKey cred)+  (clientData, authData, sig) <-+    assertionParts (origin cred) (rpId cred) challenge counter priv+  pure (cred', object+    [ "clientDataJSON" .= b64url clientData+    , "authenticatorData" .= b64url authData+    , "signature" .= b64url (encodeDerSig sig)+    , "rawId" .= b64url (credentialId cred)+    ])++-- | The three authenticated pieces of an assertion, so a test or a verifier can+-- check the signature without re-parsing the DER.+assertionParts+  :: Text -> Text -> Text -> Int -> PrivateKey+  -> IO (ByteString, ByteString, Signature)+assertionParts originText rpId' challenge counter priv = do+  let clientData = clientDataJSON "webauthn.get" challenge originText+      authData = sha256Raw (TE.encodeUtf8 rpId')+        <> BS.singleton 0x05             -- UP | UV+        <> beN 4 (fromIntegral counter)+  sig <- sign priv SHA256 (authData <> sha256Raw clientData)+  pure (clientData, authData, sig)++-- | The @clientDataJSON@ for a ceremony.+clientDataJSON :: Text -> Text -> Text -> ByteString+clientDataJSON typ challenge originText = BL.toStrict (A.encode (object+  [ "type" .= typ+  , "challenge" .= challenge+  , "origin" .= originText+  , "crossOrigin" .= False+  ]))++-- | A @navigator.credentials.create()@ response with attestation format+-- @none@.+registrationResponse :: Text -> Text -> Text -> ByteString -> Point -> Value+registrationResponse originText rpId' challenge credId point =+  object+    [ "clientDataJSON" .= b64url clientData+    , "attestationObject" .= b64url attestation+    , "rawId" .= b64url credId+    ]+  where+    clientData = clientDataJSON "webauthn.create" challenge originText+    attestation = cborMap 3+      <> cborText "fmt" <> cborText "none"+      <> cborText "attStmt" <> cborMap 0+      <> cborText "authData" <> cborBytes authData+    authData = sha256Raw (TE.encodeUtf8 rpId')+      <> BS.singleton 0x45              -- UP | UV | AT+      <> beN 4 0                       -- sign counter+      <> BS.replicate 16 0             -- AAGUID+      <> beN 2 (toInteger (BS.length credId)) <> credId+      <> coseKey+    (xc, yc) = BS.splitAt 32 (pointBytes point)+    coseKey = cborMap 5+      <> cborInt 1 <> cborInt 2         -- kty: EC2+      <> cborInt 3 <> cborInt (-7)      -- alg: ES256+      <> cborInt (-1) <> cborInt 1      -- crv: P-256+      <> cborInt (-2) <> cborBytes xc+      <> cborInt (-3) <> cborBytes yc++-- | A @navigator.credentials.get()@ response.+assertionResponse+  :: Text -> Text -> Text -> ByteString -> PrivateKey -> Int+  -> IO Value+assertionResponse originText rpId' challenge credId priv counter = do+  (clientData, authData, sig) <-+    assertionParts originText rpId' challenge counter priv+  pure $ object+    [ "clientDataJSON" .= b64url clientData+    , "authenticatorData" .= b64url authData+    , "signature" .= b64url (encodeDerSig sig)+    , "rawId" .= b64url credId+    ]++-- ---------------------------------------------------------------------------+-- JSON field access+-- ---------------------------------------------------------------------------++stringField :: Value -> Text -> Either Text Text+stringField (Object o) key = case KeyMap.lookup (Key.fromText key) o of+  Just (String s) -> Right s+  _               -> Left ("missing or non-string field \"" <> key <> "\"")+stringField _ _ = Left "expected a JSON object"++nestedStringField :: Value -> Text -> Text -> Either Text Text+nestedStringField (Object o) outer inner = case KeyMap.lookup (Key.fromText outer) o of+  Just value -> stringField value inner+  Nothing    -> Left ("missing field \"" <> outer <> "\"")+nestedStringField _ _ _ = Left "expected a JSON object"++-- ---------------------------------------------------------------------------+-- WebAuthn byte construction+-- ---------------------------------------------------------------------------++sha256Raw :: ByteString -> ByteString+sha256Raw bs = hexToBytes (BC.pack (show (hash bs :: Digest SHA256)))++-- | crypton-1.x's 'Digest' is not a memory 'ByteArrayAccess', so its 'Show'+-- (lowercase hex) is the stable way to get at the raw bytes.+hexToBytes :: ByteString -> ByteString+hexToBytes = BS.pack . pairs . BC.unpack+  where+    pairs (a : b : rest) = fromIntegral (digit a * 16 + digit b) : pairs rest+    pairs _ = []+    digit c+      | isDigit c = fromEnum c - fromEnum '0'+      | c >= 'a' && c <= 'f' = fromEnum c - fromEnum 'a' + 10+      | c >= 'A' && c <= 'F' = fromEnum c - fromEnum 'A' + 10+      | otherwise = 0++cborHeader :: Int -> Int -> ByteString+cborHeader major n+  | n < 24 = BS.singleton (fromIntegral (major * 32 + n))+  | n < 256 = BS.pack [fromIntegral (major * 32 + 24), fromIntegral n]+  | otherwise = BS.pack [ fromIntegral (major * 32 + 25)+                        , fromIntegral (n `div` 256), fromIntegral (n `mod` 256) ]++cborBytes :: ByteString -> ByteString+cborBytes b = cborHeader 2 (BS.length b) <> b++cborText :: ByteString -> ByteString+cborText t = cborHeader 3 (BS.length t) <> t++cborMap :: Int -> ByteString+cborMap = cborHeader 5++cborInt :: Int -> ByteString+cborInt n+  | n >= 0 = cborHeader 0 n+  | otherwise = cborHeader 1 (negate n - 1)++pointBytes :: Point -> ByteString+pointBytes (Point x y) = be32 x <> be32 y+pointBytes PointO       = BS.replicate 64 0++beN :: Int -> Integer -> ByteString+beN width n =+  BS.pack [fromIntegral ((n `shiftR` (8 * i)) .&. 0xff) | i <- [width - 1, width - 2 .. 0]]++be32 :: Integer -> ByteString+be32 = beN 32++-- | DER-encode an ECDSA signature as @SEQUENCE { r INTEGER, s INTEGER }@.+encodeDerSig :: Signature -> ByteString+encodeDerSig (Signature r s) =+  let body = encInt r <> encInt s+  in BS.singleton 0x30 <> encLen (BS.length body) <> body+  where+    encInt n =+      let raw = unsigned n+          padded = case BS.uncons raw of+            Just (b, _) | b >= 0x80 -> BS.cons 0x00 raw+            _                       -> raw+      in BS.singleton 0x02 <> encLen (BS.length padded) <> padded+    unsigned n+      | n < 256 = BS.singleton (fromIntegral n)+      | otherwise = unsigned (n `div` 256) <> BS.singleton (fromIntegral (n `mod` 256))+    encLen n+      | n < 0x80 = BS.singleton (fromIntegral n)+      | otherwise =+          let b = unsigned (toInteger n)+          in BS.singleton (0x80 + fromIntegral (BS.length b)) <> b++b64url :: ByteString -> Text+b64url = TE.decodeUtf8 . B64Url.encodeUnpadded++unb64url :: Text -> Either Text ByteString+unb64url = either (Left . T.pack) Right . B64Url.decodeUnpadded . TE.encodeUtf8
+ src/WebAuthn/Client/Http.hs view
@@ -0,0 +1,201 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Driving a WebAuthn ceremony over the JSON/HTTP conventions that most+-- relying parties use: ask for options, sign them, post the response back.+--+-- The endpoints and the session-cookie name are configuration, because there+-- is no standard for them. 'exampleEndpoints' is the one concrete adapter this+-- package ships, and doubles as an example.+module WebAuthn.Client.Http+  ( Endpoints (..)+  , exampleEndpoints+  , enroll+  , authenticate+  , authenticateWithStore+  , sessionToken+  ) where++import Control.Exception (SomeException, try)+import Data.Aeson (Value (..), object)+import Data.Aeson qualified as A+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString (ByteString)+import Data.ByteString qualified as BS+import Data.ByteString.Lazy qualified as BL+import Data.Maybe (listToMaybe)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Network.HTTP.Client+  ( Manager, RequestBody (..), Response, httpLbs, newManager, parseRequest+  , requestBody, requestHeaders, responseBody, responseHeaders, responseStatus )+import Network.HTTP.Client.TLS (tlsManagerSettings)+import Network.HTTP.Types.Header (Header, HeaderName, hContentType, hSetCookie)+import Network.HTTP.Types.Status (statusCode, statusIsSuccessful)++import WebAuthn.Client+  ( AuthenticationOptions (..), Credential (..), RegistrationOptions (..)+  , createAssertion, createRegistration, parseAuthenticationOptions+  , parseRegistrationOptions )++-- | Where a relying party's WebAuthn JSON endpoints live.+data Endpoints = Endpoints+  { endpointBaseUrl :: !Text+    -- ^ Scheme, host and port, e.g. @https:\/\/gateway.example:9090@.+  , endpointOrigin :: !Text+    -- ^ The origin recorded in @clientDataJSON@, which a reverse proxy may make+    -- different from 'endpointBaseUrl'. Use 'exampleEndpoints' when they match.+  , endpointRegisterOptions :: !Text+    -- ^ Path returning @PublicKeyCredentialCreationOptions@.+  , endpointRegisterVerify :: !Text+    -- ^ Path accepting the registration response.+  , endpointLoginOptions :: !Text+    -- ^ Path returning @PublicKeyCredentialRequestOptions@.+  , endpointLoginVerify :: !Text+    -- ^ Path accepting the assertion response and setting a session cookie.+  , endpointSessionCookie :: !Text+    -- ^ Name of the cookie that carries the resulting session token.+  } deriving stock (Eq, Show)++-- | The auth API used by the shipped adapter.+exampleEndpoints :: Text -> Endpoints+exampleEndpoints baseUrl = Endpoints+  { endpointBaseUrl = baseUrl+  , endpointOrigin = stripTrailingSlash baseUrl+  , endpointRegisterOptions = "/api/auth/register/options"+  , endpointRegisterVerify = "/api/auth/register/verify"+  , endpointLoginOptions = "/api/auth/login/options"+  , endpointLoginVerify = "/api/auth/login/verify"+  , endpointSessionCookie = "session"+  }++-- | Enroll a new credential. The extra headers are sent on both the options and+-- the verify request; some relying parties use them for a one-time enrollment+-- token.+enroll :: Endpoints -> [(HeaderName, ByteString)] -> IO (Either Text Credential)+enroll endpoints extraHeaders = do+  mgr <- newManager tlsManagerSettings+  options <- postJson mgr (url endpoints (endpointRegisterOptions endpoints))+    extraHeaders (object [])+  case options of+    Left err -> pure (Left ("registration options request: " <> err))+    Right (value, _) ->+      case parseRegistrationOptions value of+        Left err -> pure (Left ("registration options: " <> err))+        Right ro -> do+          (cred, response) <-+            createRegistration (originOf endpoints) (roRpId ro) (roChallenge ro)+          verified <- postJson mgr (url endpoints (endpointRegisterVerify endpoints))+            extraHeaders response+          pure $ case verified of+            Left err -> Left ("registration verify request: " <> err)+            Right _ -> Right cred++-- | Log in with an enrolled credential and return the session token and the+-- credential with its advanced sign counter. The caller must persist the+-- returned credential; use 'authenticateWithStore' to make that happen before+-- the assertion is sent.+authenticate :: Endpoints -> Credential -> IO (Either Text (Text, Credential))+authenticate endpoints = authenticateWithStore endpoints (\_ -> pure (Right ()))++-- | 'authenticate' with a persistence hook. The store is called with the+-- incremented credential /before/ the verify request is sent, so a lost+-- response can never make the next attempt replay an older counter.+authenticateWithStore+  :: Endpoints+  -> (Credential -> IO (Either Text ()))+  -> Credential+  -> IO (Either Text (Text, Credential))+authenticateWithStore endpoints store cred = do+  mgr <- newManager tlsManagerSettings+  options <- postJson mgr (url endpoints (endpointLoginOptions endpoints)) []+    (object [])+  case options of+    Left err -> pure (Left ("login options request: " <> err))+    Right (value, _) ->+      case parseAuthenticationOptions value of+        Left err -> pure (Left ("login options: " <> err))+        Right ao -> do+          (cred', response) <- createAssertion cred (aoChallenge ao)+          saved <- store cred'+          case saved of+            Left err -> pure (Left ("could not persist the sign counter: " <> err))+            Right () -> do+              verified <- postJson mgr (url endpoints (endpointLoginVerify endpoints))+                [] response+              pure $ case verified of+                Left err -> Left ("login verify request: " <> err)+                Right (_, headers) ->+                  case sessionToken (endpointSessionCookie endpoints) headers of+                    Just token -> Right (token, cred')+                    Nothing -> Left+                      "the relying party accepted the assertion but set no session cookie"++-- | The value of @cookieName@ in a @Set-Cookie@ response, if present.+sessionToken :: Text -> [Header] -> Maybe Text+sessionToken cookieName headers = listToMaybe+  [ T.takeWhile (/= ';') rest+  | (name, value) <- headers+  , name == hSetCookie+  , let text = TE.decodeUtf8Lenient value+  , Just rest <- [T.stripPrefix (cookieName <> "=") text]+  , not (T.null rest)+  ]++-- ---------------------------------------------------------------------------+-- HTTP plumbing+-- ---------------------------------------------------------------------------++url :: Endpoints -> Text -> String+url endpoints path =+  T.unpack (stripTrailingSlash (endpointBaseUrl endpoints) <> path)++originOf :: Endpoints -> Text+originOf = stripTrailingSlash . endpointOrigin++stripTrailingSlash :: Text -> Text+stripTrailingSlash = T.dropWhileEnd (== '/')++postJson+  :: Manager -> String -> [(HeaderName, ByteString)] -> Value+  -> IO (Either Text (Value, [Header]))+postJson mgr target extra body = do+  req0 <- parseRequest ("POST " <> target)+  let req = req0+        { requestHeaders = (hContentType, "application/json") : extra+        , requestBody = RequestBodyLBS (A.encode body)+        }+  result <- try (httpLbs req mgr)+  pure $ case result of+    Left (e :: SomeException) ->+      Left (T.pack target <> ": " <> T.pack (show e))+    Right resp+      | not (statusIsSuccessful (responseStatus resp)) ->+          Left (responseError resp)+      | otherwise ->+          case A.decode (responseBody resp) of+            Just value -> Right (value, responseHeaders resp)+            Nothing -> Left (T.pack target <> ": response was not JSON")++responseError :: Response BL.ByteString -> Text+responseError resp =+  let code = statusCode (responseStatus resp)+      raw = BL.toStrict (responseBody resp)+      detail = case A.decodeStrict' raw of+        Just (Object o) ->+          case (lookupString "error" o, lookupString "code" o) of+            (Just msg, Just tag) -> msg <> " (" <> tag <> ")"+            (Just msg, Nothing)  -> msg+            _                    -> ""+        _ -> ""+      bodyText = T.strip (TE.decodeUtf8Lenient (BS.take 300 raw))+  in "HTTP " <> T.pack (show code)+       <> (if T.null detail+             then if T.null bodyText then "" else ": " <> bodyText+             else ": " <> detail)++lookupString :: Text -> A.Object -> Maybe Text+lookupString key o = case KeyMap.lookup (Key.fromText key) o of+  Just (String s) -> Just s+  _               -> Nothing
+ test/Spec.hs view
@@ -0,0 +1,8 @@+module Main (main) where++import Test.Hspec (hspec)++import qualified WebAuthn.ClientSpec++main :: IO ()+main = hspec WebAuthn.ClientSpec.spec
+ test/WebAuthn/ClientSpec.hs view
@@ -0,0 +1,131 @@+{-# LANGUAGE OverloadedStrings #-}++module WebAuthn.ClientSpec (spec) where++import Crypto.Hash (SHA256 (..))+import Crypto.PubKey.ECC.ECDSA (PrivateKey (..), verify)+import Crypto.PubKey.ECC.Generate (generate)+import Crypto.PubKey.ECC.Types (CurveName (SEC_p256r1), getCurveByName)+import Data.Aeson qualified as A+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.ByteString qualified as BS+import Data.Text (Text)+import Data.Text qualified as T+import System.FilePath ((</>))+import System.IO.Temp (withSystemTempDirectory)+import Test.Hspec++import WebAuthn.Client++spec :: Spec+spec = describe "WebAuthn.Client" $ do+  describe "base64url" $ do+    it "round-trips arbitrary bytes without padding" $ do+      let raw = BS.pack [0, 1, 2, 250, 251, 252, 253, 254, 255]+      unb64url (b64url raw) `shouldBe` Right raw+      b64url raw `shouldNotSatisfy` T.isInfixOf "="++  describe "options parsing" $ do+    it "reads the registration challenge and rp id" $+      parseRegistrationOptions+        (A.object ["challenge" A..= ("c" :: Text), "rp" A..= A.object ["id" A..= ("example.com" :: Text)]])+        `shouldBe` Right (RegistrationOptions "c" "example.com")++    it "reads the authentication challenge and rp id" $+      parseAuthenticationOptions+        (A.object ["challenge" A..= ("c" :: Text), "rpId" A..= ("example.com" :: Text)])+        `shouldBe` Right (AuthenticationOptions "c" "example.com")++    it "rejects a missing challenge" $+      parseAuthenticationOptions (A.object ["rpId" A..= ("example.com" :: Text)])+        `shouldSatisfy` isLeft++  describe "assertion" $ do+    it "signs authData || SHA-256(clientDataJSON) with ES256" $ do+      (pub, priv) <- generate (getCurveByName SEC_p256r1)+      (clientData, authData, sig) <- assertionParts testOrigin testRpId challenge 7 priv+      verify SHA256 pub sig (authData <> sha256Raw clientData)+        `shouldBe` True++    it "does not verify against a different key" $ do+      (_, priv) <- generate (getCurveByName SEC_p256r1)+      (otherPub, _) <- generate (getCurveByName SEC_p256r1)+      (clientData, authData, sig) <- assertionParts testOrigin testRpId challenge 7 priv+      verify SHA256 otherPub sig (authData <> sha256Raw clientData)+        `shouldBe` False++    it "puts the ceremony, challenge and origin in clientDataJSON" $ do+      (_, priv) <- generate (getCurveByName SEC_p256r1)+      (clientData, _, _) <- assertionParts testOrigin testRpId challenge 1 priv+      let fields = A.decodeStrict clientData :: Maybe A.Value+      (fields >>= \v -> jsonString v "type") `shouldBe` Just "webauthn.get"+      (fields >>= \v -> jsonString v "challenge") `shouldBe` Just challenge+      (fields >>= \v -> jsonString v "origin") `shouldBe` Just testOrigin++    it "increments the sign counter" $ do+      (_, priv) <- generate (getCurveByName SEC_p256r1)+      let PrivateKey _ d = priv+          cred = Credential+            { credentialId = BS.pack [1 .. 16]+            , privateKey = d+            , rpId = testRpId+            , origin = testOrigin+            , signCount = 41+            }+      (cred', response) <- createAssertion cred challenge+      signCount cred' `shouldBe` 42+      case jsonString response "authenticatorData" >>= either (const Nothing) Just . unb64url of+        Nothing -> expectationFailure "authenticatorData is not base64url"+        Just authData -> BS.drop 33 authData `shouldBe` BS.pack [0, 0, 0, 42]++  describe "registration" $ do+    it "returns a credential and a none attestation for it" $ do+      (cred, body) <- createRegistration testOrigin testRpId challenge+      signCount cred `shouldBe` 0+      jsonString body "rawId" `shouldBe` Just (b64url (credentialId cred))+      case jsonString body "attestationObject" >>= either (const Nothing) Just . unb64url of+        Nothing -> expectationFailure "attestationObject is not base64url"+        Just attestation -> do+          BS.take 1 attestation `shouldBe` BS.pack [0xa3]+          attestation `shouldSatisfy` BS.isInfixOf "fmt"+          attestation `shouldSatisfy` BS.isInfixOf "none"++  describe "credential file" $ do+    it "round-trips through JSON" $ do+      let cred = Credential+            { credentialId = BS.pack [9, 8, 7]+            , privateKey = 12345678901234567890+            , rpId = testRpId+            , origin = testOrigin+            , signCount = 3+            }+      (A.decode (A.encode cred) :: Maybe Credential) `shouldBe` Just cred++    it "loads what it saved, and reports a missing file as Nothing" $+      withSystemTempDirectory "webauthn-client" $ \dir -> do+        let path = dir </> "credential.json"+            cred = Credential (BS.pack [1, 2, 3]) 99 testRpId testOrigin 0+        loadCredentialFile path `shouldReturn` Right Nothing+        saveCredentialFile path cred `shouldReturn` Right ()+        loadCredentialFile path `shouldReturn` Right (Just cred)++testOrigin :: Text+testOrigin = "https://gateway.example.com:9090"++testRpId :: Text+testRpId = "gateway.example.com"++challenge :: Text+challenge = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"++jsonString :: A.Value -> Text -> Maybe Text+jsonString (A.Object o) key =+  case KeyMap.lookup (Key.fromText key) o of+    Just (A.String s) -> Just s+    _                 -> Nothing+jsonString _ _ = Nothing++isLeft :: Either a b -> Bool+isLeft (Left _) = True+isLeft (Right _) = False
+ webauthn-client.cabal view
@@ -0,0 +1,80 @@+cabal-version: 3.0+name: webauthn-client+version: 0.1.0.0+synopsis: Software WebAuthn authenticator and JSON/HTTP client+description:+  A software WebAuthn authenticator: the client half of a passkey ceremony.+  WebAuthn relying parties verify an ES256 signature over+  authData || SHA-256(clientDataJSON) by an enrolled public key, so a headless+  program can perform the same ceremony with a keypair it holds. Use this to+  sign in to passkey-gated APIs from a CLI or a service.+  .+  The library builds registration and assertion responses for the standard+  WebAuthn JSON shapes, persists credentials owner-only, and can drive an RP's+  JSON/HTTP endpoints, with a shipped adapter as an example.+license: BSD-3-Clause+license-file: LICENSE+author: Doug Beardsley+maintainer: doug@equitek.ai+category: Web+build-type: Simple+extra-doc-files:+    README.md+    CHANGELOG.md+tested-with: GHC == 9.12.4++source-repository head+  type:     git+  location: https://github.com/mightybyte/webauthn-client.git++common warnings+    default-language: GHC2021+    default-extensions:+        DerivingStrategies+        OverloadedStrings+        ScopedTypeVariables+    ghc-options:+        -Wall -Wcompat -Widentities+        -Wincomplete-uni-patterns+        -Wincomplete-record-updates+        -Wname-shadowing+        -Wpartial-fields+        -Wredundant-constraints++library+    import: warnings+    hs-source-dirs: src+    exposed-modules:+        WebAuthn.Client+        WebAuthn.Client.Http+    build-depends:+        base >= 4.18 && < 5+      , aeson >= 2.0 && < 2.4+      , base64-bytestring >= 1.2 && < 1.3+      , bytestring >= 0.11 && < 0.13+      , crypton >= 1.0 && < 1.2+      , directory >= 1.3 && < 1.4+      , filepath >= 1.4 && < 1.6+      , http-client >= 0.7 && < 0.8+      , http-client-tls >= 0.3 && < 0.5+      , http-types >= 0.12 && < 0.13+      , text >= 2.0 && < 2.2+      , unix >= 2.7 && < 2.9++test-suite webauthn-client-test+    import: warnings+    type: exitcode-stdio-1.0+    main-is: Spec.hs+    hs-source-dirs: test+    other-modules:+        WebAuthn.ClientSpec+    build-depends:+        base >= 4.18 && < 5+      , webauthn-client >= 0.1 && < 0.2+      , aeson >= 2.0 && < 2.4+      , bytestring >= 0.11 && < 0.13+      , crypton >= 1.0 && < 1.2+      , filepath >= 1.4 && < 1.6+      , hspec >= 2.10 && < 2.12+      , temporary >= 1.3 && < 1.4+      , text >= 2.0 && < 2.2