diff --git a/counter/auth-vendored/Auth/Common.elm b/counter/auth-vendored/Auth/Common.elm new file mode 100644 index 0000000..4115fe0 --- /dev/null +++ b/counter/auth-vendored/Auth/Common.elm @@ -0,0 +1,301 @@ +module Auth.Common exposing + ( AuthChallengeReason(..) + , AuthCode + , BackendMsg(..) + , ClientId + , Config + , ConfigurationEmailMagicLink + , ConfigurationOAuth + , Error(..) + , Flow(..) + , FrontendMsg(..) + , LogoutEndpointConfig(..) + , Method(..) + , MethodId + , PendingAuth + , PendingEmailAuth + , Provider(..) + , SessionId + , SessionIdString + , State + , ToBackend(..) + , ToFrontend(..) + , Token + , UserInfo + , base64 + , convertBytes + , defaultHttpsUrl + , nothingIfEmpty + , sleepTask + , toBytes + ) + +import Base64.Encode as Base64 +import Browser.Navigation exposing (Key) +import Bytes exposing (Bytes) +import Bytes.Encode as Bytes +import Dict exposing (Dict) +import EmailAddress +import Http +import Json.Decode as Json +import OAuth +import OAuth.AuthorizationCode as OAuth +import Postmark +import Process +import Task exposing (Task) +import Time +import Url exposing (Protocol(..), Url) +import User + + +type alias Config frontendMsg toBackend backendMsg toFrontend frontendModel backendModel = + { toBackend : ToBackend -> toBackend + , toFrontend : ToFrontend -> toFrontend + , backendMsg : BackendMsg -> backendMsg + , sendToFrontend : SessionId -> toFrontend -> Cmd backendMsg + , sendToBackend : toBackend -> Cmd frontendMsg + , methods : List (Method frontendMsg backendMsg frontendModel backendModel) + , renewSession : SessionId -> ClientId -> backendModel -> ( backendModel, Cmd backendMsg ) + } + + +type Method frontendMsg backendMsg frontendModel backendModel + = ProtocolOAuth (ConfigurationOAuth frontendMsg backendMsg frontendModel backendModel) + | ProtocolEmailMagicLink (ConfigurationEmailMagicLink frontendMsg backendMsg frontendModel backendModel) + + +type alias ConfigurationEmailMagicLink frontendMsg backendMsg frontendModel backendModel = + { id : String + , initiateSignin : + SessionId + -> ClientId + -> backendModel + -> { username : Maybe String } + -> Time.Posix + -> ( backendModel, Cmd backendMsg ) + , onFrontendCallbackInit : + frontendModel + -> MethodId + -> Url + -> Key + -> (ToBackend -> Cmd frontendMsg) + -> ( frontendModel, Cmd frontendMsg ) + , onAuthCallbackReceived : + SessionId + -> ClientId + -> Url + -> AuthCode + -> State + -> Time.Posix + -> (BackendMsg -> backendMsg) + -> backendModel + -> ( backendModel, Cmd backendMsg ) + , placeholder : frontendMsg -> backendMsg -> frontendModel -> backendModel -> () + } + + +type alias ConfigurationOAuth frontendMsg backendMsg frontendModel backendModel = + { id : String + , authorizationEndpoint : Url + , tokenEndpoint : Url + , logoutEndpoint : LogoutEndpointConfig + , allowLoginQueryParameters : Bool + , clientId : String + , clientSecret : String + , scope : List String + , getUserInfo : OAuth.AuthenticationSuccess -> Task Error UserInfo + , onFrontendCallbackInit : + frontendModel + -> MethodId + -> Url + -> Key + -> (ToBackend -> Cmd frontendMsg) + -> ( frontendModel, Cmd frontendMsg ) + , placeholder : ( backendModel, backendMsg ) -> () + } + + +type alias SessionIdString = + String + + +type FrontendMsg + = AuthSigninRequested Provider + + +type ToBackend + = AuthSigninInitiated { methodId : MethodId, baseUrl : Url, username : Maybe String } + | AuthCallbackReceived MethodId Url AuthCode State + | AuthRenewSessionRequested + | AuthLogoutRequested + | AuthCheckLoginRequest + | AuthSigInWithToken Int + + +type BackendMsg + = AuthSigninInitiated_ { sessionId : SessionId, clientId : ClientId, methodId : MethodId, baseUrl : Url, now : Time.Posix, username : Maybe String } + | AuthSigninInitiatedDelayed_ SessionId ToFrontend + | AuthCallbackReceived_ SessionId ClientId MethodId Url String String Time.Posix + | AuthSuccess SessionId ClientId MethodId Time.Posix (Result Error ( UserInfo, Maybe Token )) + | AuthRenewSession SessionId ClientId + | AuthLogout SessionId ClientId + | AuthSentLoginEmail Time.Posix EmailAddress.EmailAddress (Result Http.Error Postmark.PostmarkSendResponse) + + +type ToFrontend + = AuthInitiateSignin Url + | AuthError Error + | AuthSessionChallenge AuthChallengeReason + | AuthSignInWithTokenResponse (Result Int User.LoginData) + | ReceivedMessage (Result String String) + + +type AuthChallengeReason + = AuthSessionMissing + | AuthSessionInvalid + | AuthSessionExpired + | AuthSessionLoggedOut + + +type alias Token = + { methodId : MethodId + , token : OAuth.Token + , created : Time.Posix + , expires : Time.Posix + } + + +type LogoutEndpointConfig + = Home { returnPath : String } + | Tenant { url : Url, returnPath : String } + + +type Provider + = EmailMagicLink + | OAuthGithub + | OAuthGoogle + | OAuthAuth0 + + +type Flow + = Idle + | Requested MethodId + | Pending + | Authorized AuthCode String + | Authenticated OAuth.Token + | Done UserInfo + | Errored Error + + +type Error + = ErrStateMismatch + | ErrAuthorization OAuth.AuthorizationError + | ErrAuthentication OAuth.AuthenticationError + | ErrHTTPGetAccessToken + | ErrHTTPGetUserInfo + -- Lazy string error until we classify everything nicely + | ErrAuthString String + + +type alias State = + String + + +type alias MethodId = + String + + +type alias AuthCode = + String + + +type alias UserInfo = + { email : String + , name : Maybe String + , username : Maybe String + } + + +type alias PendingAuth = + { created : Time.Posix + , sessionId : SessionId + , state : String + } + + +type alias PendingEmailAuth = + { created : Time.Posix + , sessionId : SessionId + , username : String + , fullname : String + , token : String + } + + + +-- +-- Helpers +-- + + +toBytes : List Int -> Bytes +toBytes = + List.map Bytes.unsignedInt8 >> Bytes.sequence >> Bytes.encode + + +base64 : Bytes -> String +base64 = + Base64.bytes >> Base64.encode + + +convertBytes : List Int -> { state : String } +convertBytes = + toBytes >> base64 >> (\state -> { state = state }) + + +defaultHttpsUrl : Url +defaultHttpsUrl = + { protocol = Https + , host = "" + , path = "" + , port_ = Nothing + , query = Nothing + , fragment = Nothing + } + + +sleepTask isDev msg = + -- Because in dev the backendmodel is only persisted every 2 seconds, we need to + -- make sure we sleep a little before a redirect otherwise we won't have our + -- persisted state. + (if isDev then + Process.sleep 3000 + + else + Process.sleep 0 + ) + |> Task.perform (always msg) + + +nothingIfEmpty s = + let + trimmed = + String.trim s + in + if trimmed == "" then + Nothing + + else + Just trimmed + + + +-- Lamdera aliases + + +type alias SessionId = + String + + +type alias ClientId = + String diff --git a/counter/auth-vendored/Auth/Flow.elm b/counter/auth-vendored/Auth/Flow.elm new file mode 100644 index 0000000..3bc165d --- /dev/null +++ b/counter/auth-vendored/Auth/Flow.elm @@ -0,0 +1,343 @@ +module Auth.Flow exposing + ( BackendUpdateConfig + , backendUpdate + , errorToString + , findMethod + , init + , methodLoader + , onFrontendLogoutCallback + , setAuthFlow + , setError + , signInRequested + , signOutRequested + , startProviderSignin + , updateFromFrontend + , withCurrentTime + ) + +import Auth.Common exposing (LogoutEndpointConfig(..), MethodId, ToBackend(..)) +import Auth.Method.EmailMagicLink +import Auth.Protocol.OAuth +import Browser.Navigation as Navigation +import Dict exposing (Dict) +import List.Extra as List +import MagicLink.Backend +import Task +import Time +import Types +import Url exposing (Protocol(..), Url) +import Url.Builder exposing (QueryParameter) + + +init : + { frontendModel | authFlow : Auth.Common.Flow, authRedirectBaseUrl : Url } + -> Auth.Common.MethodId + -> Url + -> Navigation.Key + -> (Auth.Common.ToBackend -> Cmd frontendMsg) + -> ( { frontendModel | authFlow : Auth.Common.Flow, authRedirectBaseUrl : Url }, Cmd frontendMsg ) +init model methodId origin navigationKey toBackendFn = + case methodId of + "EmailMagicLink" -> + Auth.Method.EmailMagicLink.onFrontendCallbackInit model methodId origin navigationKey toBackendFn + + "OAuthGithub" -> + Auth.Protocol.OAuth.onFrontendCallbackInit model methodId origin navigationKey toBackendFn + + "OAuthGoogle" -> + Auth.Protocol.OAuth.onFrontendCallbackInit model methodId origin navigationKey toBackendFn + + "OAuthAuth0" -> + Auth.Protocol.OAuth.onFrontendCallbackInit model methodId origin navigationKey toBackendFn + + _ -> + let + clearUrl = + Navigation.replaceUrl navigationKey (Url.toString model.authRedirectBaseUrl) + in + ( { model | authFlow = Auth.Common.Errored <| Auth.Common.ErrAuthString ("Unsupported auth method: " ++ methodId) } + , clearUrl + ) + + +onFrontendLogoutCallback navigationMsg = + navigationMsg + + + +--- updateFromFrontend : { a | asBackendMsg : Auth.Common.BackendMsg -> b } -> Auth.Common.ClientId -> Auth.Common.SessionId -> ToBackend -> e -> ( e, Cmd b ) + + +updateFromFrontend { asBackendMsg } clientId sessionId authToBackend model = + case authToBackend of + Auth.Common.AuthSigInWithToken loginCode -> + MagicLink.Backend.signInWithMagicToken model.time sessionId clientId loginCode model + + Auth.Common.AuthCheckLoginRequest -> + MagicLink.Backend.checkLogin model clientId sessionId + + Auth.Common.AuthSigninInitiated params -> + ( model + , withCurrentTime + (\now -> + asBackendMsg <| + Auth.Common.AuthSigninInitiated_ + { sessionId = sessionId + , clientId = clientId + , methodId = params.methodId + , baseUrl = params.baseUrl + , now = now + , username = params.username + } + ) + ) + + Auth.Common.AuthCallbackReceived methodId receivedUrl code state -> + ( model + , Time.now + |> Task.perform + (\now -> + asBackendMsg <| + Auth.Common.AuthCallbackReceived_ + sessionId + clientId + methodId + receivedUrl + code + state + now + ) + ) + + Auth.Common.AuthRenewSessionRequested -> + ( model + , Time.now + |> Task.perform + (\t -> + asBackendMsg <| + Auth.Common.AuthRenewSession sessionId clientId + ) + ) + + Auth.Common.AuthLogoutRequested -> + ( model + , Time.now + |> Task.perform + (\t -> + asBackendMsg <| + Auth.Common.AuthLogout sessionId clientId + ) + ) + + +type alias BackendUpdateConfig frontendMsg backendMsg toFrontend frontendModel backendModel = + { asToFrontend : Auth.Common.ToFrontend -> toFrontend + , asBackendMsg : Auth.Common.BackendMsg -> backendMsg + , sendToFrontend : Auth.Common.SessionId -> toFrontend -> Cmd backendMsg + , backendModel : { backendModel | pendingAuths : Dict Auth.Common.SessionId Auth.Common.PendingAuth } + , loadMethod : Auth.Common.MethodId -> Maybe (Auth.Common.Method frontendMsg backendMsg frontendModel backendModel) + , handleAuthSuccess : + Auth.Common.SessionId + -> Auth.Common.ClientId + -> Auth.Common.UserInfo + -> MethodId + -> Maybe Auth.Common.Token + -> Time.Posix + -> ( { backendModel | pendingAuths : Dict Auth.Common.SessionId Auth.Common.PendingAuth }, Cmd backendMsg ) + , renewSession : Auth.Common.SessionId -> Auth.Common.ClientId -> backendModel -> ( backendModel, Cmd backendMsg ) + , logout : Auth.Common.SessionId -> Auth.Common.ClientId -> backendModel -> ( backendModel, Cmd backendMsg ) + , isDev : Bool + } + + +backendUpdate : + BackendUpdateConfig + frontendMsg + backendMsg + toFrontend + frontendModel + { backendModel | pendingAuths : Dict Auth.Common.SessionId Auth.Common.PendingAuth } + -> Auth.Common.BackendMsg + -> ( { backendModel | pendingAuths : Dict Auth.Common.SessionId Auth.Common.PendingAuth }, Cmd backendMsg ) +backendUpdate { asToFrontend, asBackendMsg, sendToFrontend, backendModel, loadMethod, handleAuthSuccess, renewSession, logout, isDev } authMsg = + let + authError str = + asToFrontend (Auth.Common.AuthError str) + + withMethod methodId clientId fn = + case loadMethod methodId of + Nothing -> + ( backendModel + , sendToFrontend clientId <| authError (Auth.Common.ErrAuthString <| "Unsupported auth method: " ++ methodId) + ) + + Just method -> + fn method + in + case authMsg of + Auth.Common.AuthSentLoginEmail now emailAddress result -> + --( backendModel, MagicLink.Backend.sendLoginEmail_ (Types.AuthBackendMsg << (Auth.Common.AuthSentLoginEmail now emailAddress)) emailAddress 1234) + ( backendModel, Cmd.none ) + + Auth.Common.AuthSigninInitiated_ { sessionId, clientId, methodId, baseUrl, now, username } -> + withMethod methodId + clientId + (\method -> + case method of + Auth.Common.ProtocolEmailMagicLink config -> + config.initiateSignin sessionId clientId backendModel { username = username } now + + Auth.Common.ProtocolOAuth config -> + Auth.Protocol.OAuth.initiateSignin isDev sessionId baseUrl config asBackendMsg now backendModel + ) + + Auth.Common.AuthSigninInitiatedDelayed_ sessionId initiateMsg -> + ( backendModel, sendToFrontend sessionId (asToFrontend initiateMsg) ) + + Auth.Common.AuthCallbackReceived_ sessionId clientId methodId receivedUrl code state now -> + withMethod methodId + clientId + (\method -> + case method of + Auth.Common.ProtocolEmailMagicLink config -> + config.onAuthCallbackReceived sessionId clientId receivedUrl code state now asBackendMsg backendModel + + Auth.Common.ProtocolOAuth config -> + Auth.Protocol.OAuth.onAuthCallbackReceived sessionId clientId config receivedUrl code state now asBackendMsg backendModel + ) + + Auth.Common.AuthSuccess sessionId clientId methodId now res -> + let + removeSession backendModel_ = + { backendModel_ | pendingAuths = backendModel_.pendingAuths |> Dict.remove sessionId } + in + withMethod methodId + clientId + (\method -> + case res of + Ok ( userInfo, authToken ) -> + handleAuthSuccess sessionId clientId userInfo methodId authToken now + |> Tuple.mapFirst removeSession + + Err err -> + ( backendModel, sendToFrontend sessionId (asToFrontend <| Auth.Common.AuthError err) ) + ) + + Auth.Common.AuthRenewSession sessionId clientId -> + renewSession sessionId clientId backendModel + + Auth.Common.AuthLogout sessionId clientId -> + logout sessionId clientId backendModel + + +signInRequested : + Auth.Common.MethodId + -> { frontendModel | authFlow : Auth.Common.Flow, authRedirectBaseUrl : Url } + -> Maybe String + -> ( { frontendModel | authFlow : Auth.Common.Flow, authRedirectBaseUrl : Url }, Auth.Common.ToBackend ) +signInRequested methodId model username = + ( { model | authFlow = Auth.Common.Requested methodId } + , Auth.Common.AuthSigninInitiated { methodId = methodId, baseUrl = model.authRedirectBaseUrl, username = username } + ) + + +signOutRequested : + Maybe LogoutEndpointConfig + -> List QueryParameter + -> { a | authFlow : Auth.Common.Flow, authLogoutReturnUrlBase : Url } + -> ( { a | authFlow : Auth.Common.Flow, authLogoutReturnUrlBase : Url }, Cmd msg ) +signOutRequested maybeUrlConfig callBackQueries model = + ( { model | authFlow = Auth.Common.Idle } + , case maybeUrlConfig of + Just (Tenant urlConfig) -> + Navigation.load <| + Url.toString urlConfig.url + ++ Url.toString model.authLogoutReturnUrlBase + ++ urlConfig.returnPath + ++ Url.Builder.toQuery callBackQueries + + Just (Home homeUrlConfig) -> + Navigation.load <| + Url.toString model.authLogoutReturnUrlBase + ++ homeUrlConfig.returnPath + ++ Url.Builder.toQuery callBackQueries + + Nothing -> + Navigation.load <| + Url.toString model.authLogoutReturnUrlBase + ++ Url.Builder.toQuery callBackQueries + ) + + +startProviderSignin : + Url + -> { frontendModel | authFlow : Auth.Common.Flow } + -> ( { frontendModel | authFlow : Auth.Common.Flow }, Cmd msg ) +startProviderSignin url model = + ( { model | authFlow = Auth.Common.Pending } + , Navigation.load (Url.toString url) + ) + + +setError : + { frontendModel | authFlow : Auth.Common.Flow } + -> Auth.Common.Error + -> ( { frontendModel | authFlow : Auth.Common.Flow }, Cmd msg ) +setError model err = + setAuthFlow model <| Auth.Common.Errored err + + +setAuthFlow : + { frontendModel | authFlow : Auth.Common.Flow } + -> Auth.Common.Flow + -> ( { frontendModel | authFlow : Auth.Common.Flow }, Cmd msg ) +setAuthFlow model flow = + ( { model | authFlow = flow }, Cmd.none ) + + +errorToString : Auth.Common.Error -> String +errorToString error = + case error of + Auth.Common.ErrStateMismatch -> + "ErrStateMismatch" + + Auth.Common.ErrAuthorization authorizationError -> + "ErrAuthorization" + + Auth.Common.ErrAuthentication authenticationError -> + "ErrAuthentication" + + Auth.Common.ErrHTTPGetAccessToken -> + "ErrHTTPGetAccessToken" + + Auth.Common.ErrHTTPGetUserInfo -> + "ErrHTTPGetUserInfo" + + Auth.Common.ErrAuthString err -> + err + + +withCurrentTime fn = + Time.now |> Task.perform fn + + +methodLoader : List (Auth.Common.Method frontendMsg backendMsg frontendModel backendModel) -> Auth.Common.MethodId -> Maybe (Auth.Common.Method frontendMsg backendMsg frontendModel backendModel) +methodLoader methods methodId = + methods + |> List.find + (\config -> + case config of + Auth.Common.ProtocolEmailMagicLink method -> + method.id == methodId + + Auth.Common.ProtocolOAuth method -> + method.id == methodId + ) + + +findMethod : + Auth.Common.MethodId + -> Auth.Common.Config frontendMsg toBackend backendMsg toFrontend frontendModel backendModel + -> Maybe (Auth.Common.Method frontendMsg backendMsg frontendModel backendModel) +findMethod methodId config = + methodLoader config.methods methodId diff --git a/counter/auth-vendored/Auth/HttpHelpers.elm b/counter/auth-vendored/Auth/HttpHelpers.elm new file mode 100644 index 0000000..e37a1e9 --- /dev/null +++ b/counter/auth-vendored/Auth/HttpHelpers.elm @@ -0,0 +1,143 @@ +module Auth.HttpHelpers exposing (customError, expectJson, httpErrorToString, jsonResolver, parseError) + +import Http +import Json.Decode as D + + +{-| The default Http.expectJson / Http.expectString don't allow you to see any body +returned in an error (i.e. 403) states. The following docs; + +describe our sitution perfectly, so that's that code below, with a modified +Http.BadStatus\_ handler to map it to BadBody String instead of BadStatus Int +so we can actually see the error message. +-} +expectJson : (Result Http.Error a -> msg) -> D.Decoder a -> Http.Expect msg +expectJson toMsg decoder = + Http.expectStringResponse toMsg <| + \response -> + case response of + Http.BadUrl_ url -> + Err (Http.BadUrl url) + + Http.Timeout_ -> + Err Http.Timeout + + Http.NetworkError_ -> + Err Http.NetworkError + + Http.BadStatus_ metadata body -> + Err (Http.BadBody (String.fromInt metadata.statusCode ++ ": " ++ body)) + + Http.GoodStatus_ metadata body -> + case D.decodeString decoder body of + Ok value -> + Ok value + + Err err -> + Err (Http.BadBody (D.errorToString err)) + + + +-- From https://github.com/krisajenkins/remotedata/issues/28 + + +parseError : String -> Maybe String +parseError = + D.decodeString (D.field "error" D.string) >> Result.toMaybe + + +httpErrorToString : Http.Error -> String +httpErrorToString err = + case err of + Http.BadUrl url -> + "HTTP malformed url: " ++ url + + Http.Timeout -> + "HTTP timeout exceeded" + + Http.NetworkError -> + "HTTP network error" + + Http.BadStatus code -> + "Unexpected HTTP response code: " ++ String.fromInt code + + Http.BadBody text -> + "HTTP error: " ++ text + + + +-- httpErrorToStringEffect : Effect.Http.Error -> String +-- httpErrorToStringEffect err = +-- case err of +-- Effect.Http.BadUrl url -> +-- "HTTP malformed url: " ++ url +-- +-- Effect.Http.Timeout -> +-- "HTTP timeout exceeded" +-- +-- Effect.Http.NetworkError -> +-- "HTTP network error" +-- +-- Effect.Http.BadStatus code -> +-- "Unexpected HTTP response code: " ++ String.fromInt code +-- +-- Effect.Http.BadBody text -> +-- "HTTP error: " ++ text + + +customError : String -> Http.Error +customError s = + Http.BadBody <| "Error: " ++ s + + + +-- customErrorEffect : String -> Effect.Http.Error +-- customErrorEffect s = +-- Effect.Http.BadBody <| "Error: " ++ s + + +jsonResolver : D.Decoder a -> Http.Resolver Http.Error a +jsonResolver decoder = + Http.stringResolver <| + \response -> + case response of + Http.GoodStatus_ _ body -> + D.decodeString decoder body + |> Result.mapError D.errorToString + |> Result.mapError Http.BadBody + + Http.BadUrl_ message -> + Err (Http.BadUrl message) + + Http.Timeout_ -> + Err Http.Timeout + + Http.NetworkError_ -> + Err Http.NetworkError + + Http.BadStatus_ metadata body -> + Err (Http.BadBody (String.fromInt metadata.statusCode ++ ": " ++ body)) + + + +-- jsonResolverEffect : D.Decoder a -> Effect.Http.Resolver restriction Effect.Http.Error a +-- jsonResolverEffect decoder = +-- Effect.Http.stringResolver <| +-- \response -> +-- case response of +-- Effect.Http.GoodStatus_ _ body -> +-- D.decodeString decoder body +-- |> Result.mapError D.errorToString +-- |> Result.mapError Effect.Http.BadBody +-- +-- Effect.Http.BadUrl_ message -> +-- Err (Effect.Http.BadUrl message) +-- +-- Effect.Http.Timeout_ -> +-- Err Effect.Http.Timeout +-- +-- Effect.Http.NetworkError_ -> +-- Err Effect.Http.NetworkError +-- +-- Effect.Http.BadStatus_ metadata body -> +-- Err (Effect.Http.BadBody (String.fromInt metadata.statusCode ++ ": " ++ body)) diff --git a/counter/auth-vendored/Auth/Method/EmailMagicLink.elm b/counter/auth-vendored/Auth/Method/EmailMagicLink.elm new file mode 100644 index 0000000..4c45dc5 --- /dev/null +++ b/counter/auth-vendored/Auth/Method/EmailMagicLink.elm @@ -0,0 +1,85 @@ +module Auth.Method.EmailMagicLink exposing + ( callbackUrl + , configuration + , onFrontendCallbackInit + , queryParams + , trigger + ) + +import Auth.Common exposing (..) +import Base64.Encode as Base64 +import Bytes exposing (Bytes) +import Bytes.Encode as Bytes +import Dict exposing (Dict) +import Http +import Json.Decode as Json +import List.Extra as List +import OAuth +import OAuth.AuthorizationCode as OAuth +import Task exposing (Task) +import Time +import Url exposing (Protocol(..), Url) +import Url.Builder +import Url.Parser exposing ((), ()) +import Url.Parser.Query as Query + + +configuration : + { initiateSignin : + SessionId + -> ClientId + -> backendModel + -> { username : Maybe String } + -> Time.Posix + -> ( backendModel, Cmd backendMsg ) + , onAuthCallbackReceived : + SessionId + -> ClientId + -> Url + -> AuthCode + -> State + -> Time.Posix + -> (BackendMsg -> backendMsg) + -> backendModel + -> ( backendModel, Cmd backendMsg ) + } + -> + Method + frontendMsg + backendMsg + { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url } + backendModel +configuration { initiateSignin, onAuthCallbackReceived } = + ProtocolEmailMagicLink + { id = "EmailMagicLink" + , initiateSignin = initiateSignin + , onFrontendCallbackInit = onFrontendCallbackInit + , onAuthCallbackReceived = onAuthCallbackReceived + , placeholder = \frontendMsg backendMsg frontendModel backendModel -> () + } + + +onFrontendCallbackInit frontendModel methodId origin key toBackend = + case origin |> Url.Parser.parse (callbackUrl methodId queryParams) of + Just ( Just token, Just email ) -> + ( { frontendModel | authFlow = Auth.Common.Pending } + , toBackend <| Auth.Common.AuthCallbackReceived methodId origin token email + ) + + _ -> + ( { frontendModel | authFlow = Errored <| ErrAuthString "Missing token and/or email parameters. Please try again." } + , Cmd.none + ) + + +trigger msg = + Time.now |> Task.perform (always msg) + + +callbackUrl methodId = + Url.Parser.s "login" Url.Parser.s methodId Url.Parser.s "callback" + + +queryParams = + -- @TODO why doesn't query params parsing work by itself? + Query.map2 Tuple.pair (Query.string "token") (Query.string "email") diff --git a/counter/auth-vendored/Auth/Method/OAuthAuth0.elm b/counter/auth-vendored/Auth/Method/OAuthAuth0.elm new file mode 100644 index 0000000..17cda85 --- /dev/null +++ b/counter/auth-vendored/Auth/Method/OAuthAuth0.elm @@ -0,0 +1,153 @@ +module Auth.Method.OAuthAuth0 exposing + ( configuration + , getUserInfo + , jwtErrorToString + ) + +import Auth.Common exposing (..) +import Auth.HttpHelpers as HttpHelpers +import Auth.Protocol.OAuth +import Base64.Encode as Base64 +import Bytes exposing (Bytes) +import Bytes.Encode as Bytes +import Dict exposing (Dict) +import Http +import JWT exposing (..) +import JWT.JWS as JWS +import Json.Decode as Json +import OAuth.AuthorizationCode as OAuth +import Task exposing (Task) +import Url exposing (Protocol(..), Url) + + +configuration : + String + -> String + -> String + -> + Method + frontendMsg + backendMsg + { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url } + backendModel +configuration clientId clientSecret appTenant = + ProtocolOAuth + { id = "OAuthAuth0" + , authorizationEndpoint = { defaultHttpsUrl | host = appTenant, path = "/authorize" } + , tokenEndpoint = { defaultHttpsUrl | host = appTenant, path = "/oauth/token" } + , logoutEndpoint = + Tenant + { url = + { defaultHttpsUrl + | host = appTenant + , path = "/v2/logout" + , query = Just ("client_id=" ++ clientId ++ "&returnTo=") + } + , returnPath = "/logout/OAuthAuth0/callback" + } + , allowLoginQueryParameters = True + , clientId = clientId + , clientSecret = clientSecret + , scope = [ "openid email profile" ] + , getUserInfo = getUserInfo + , onFrontendCallbackInit = Auth.Protocol.OAuth.onFrontendCallbackInit + , placeholder = \x -> () + + -- , onAuthCallbackReceived = Debug.todo "onAuthCallbackReceived" + } + + +getUserInfo : + OAuth.AuthenticationSuccess + -> Task Auth.Common.Error UserInfo +getUserInfo authenticationSuccess = + let + extract : String -> Json.Decoder a -> Dict String Json.Value -> Result String a + extract k d v = + Dict.get k v + |> Maybe.map + (\v_ -> + Json.decodeValue d v_ + |> Result.mapError Json.errorToString + ) + |> Maybe.withDefault (Err <| "Key " ++ k ++ " not found") + + extractOptional : a -> String -> Json.Decoder a -> Dict String Json.Value -> Result String a + extractOptional default k d v = + Dict.get k v + |> Maybe.map + (\v_ -> + Json.decodeValue d v_ + |> Result.mapError Json.errorToString + ) + |> Maybe.withDefault (Ok <| default) + + tokenR = + case authenticationSuccess.idJwt of + Nothing -> + Err "Identity JWT missing in authentication response. Please report this issue." + + Just idJwt -> + case JWT.fromString idJwt of + Ok (JWS t) -> + Ok t + + Err err -> + Err <| jwtErrorToString err + + stuff = + tokenR + |> Result.andThen + (\token -> + let + meta = + token.claims.metadata + in + Result.map4 + (\email email_verified given_name family_name -> + { email = email + , email_verified = email_verified + , given_name = given_name + , family_name = family_name + } + ) + (extract "email" Json.string meta) + (extract "email_verified" Json.bool meta) + (extractOptional Nothing "given_name" (Json.string |> Json.nullable) meta) + (extractOptional Nothing "family_name" (Json.string |> Json.nullable) meta) + ) + in + Task.mapError (Auth.Common.ErrAuthString << HttpHelpers.httpErrorToString) <| + case stuff of + Ok result -> + Task.succeed + { email = result.email + , name = + [ Maybe.withDefault "" result.given_name, Maybe.withDefault "" result.family_name ] + |> String.join " " + |> nothingIfEmpty + , username = Nothing + } + + Err err -> + Task.fail (Http.BadBody err) + + +jwtErrorToString err = + case err of + TokenTypeUnknown -> + "Unsupported auth token type." + + JWSError decodeError -> + case decodeError of + JWS.Base64DecodeError -> + "Base64DecodeError" + + JWS.MalformedSignature -> + "MalformedSignature" + + JWS.InvalidHeader jsonError -> + "InvalidHeader: " ++ Json.errorToString jsonError + + JWS.InvalidClaims jsonError -> + "InvalidClaims: " ++ Json.errorToString jsonError diff --git a/counter/auth-vendored/Auth/Method/OAuthGithub.elm b/counter/auth-vendored/Auth/Method/OAuthGithub.elm new file mode 100644 index 0000000..2e74a5a --- /dev/null +++ b/counter/auth-vendored/Auth/Method/OAuthGithub.elm @@ -0,0 +1,132 @@ +module Auth.Method.OAuthGithub exposing + ( GithubEmail + , configuration + , decodeNonEmptyString + , fallbackGetEmailFromEmails + , getUserEmailsTask + , getUserInfo + , getUserInfoTask + ) + +import Auth.Common exposing (..) +import Auth.HttpHelpers as HttpHelpers +import Auth.Protocol.OAuth +import Base64.Encode as Base64 +import Browser.Navigation as Navigation +import Bytes exposing (Bytes) +import Bytes.Encode as Bytes +import Http +import Json.Decode as Json +import Json.Decode.Pipeline exposing (..) +import List.Extra as List +import OAuth +import OAuth.AuthorizationCode as OAuth +import Task exposing (Task) +import Url exposing (Protocol(..), Url) +import Url.Builder + + +configuration : + String + -> String + -> + Method + frontendMsg + backendMsg + { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url } + backendModel +configuration clientId clientSecret = + ProtocolOAuth + { id = "OAuthGithub" + , authorizationEndpoint = { defaultHttpsUrl | host = "github.com", path = "/login/oauth/authorize" } + , tokenEndpoint = { defaultHttpsUrl | host = "github.com", path = "/login/oauth/access_token" } + , logoutEndpoint = Home { returnPath = "/logout/OAuthGithub/callback" } + , allowLoginQueryParameters = True + , clientId = clientId + , clientSecret = clientSecret + , scope = [ "read:user", "user:email" ] + , getUserInfo = getUserInfo + , onFrontendCallbackInit = Auth.Protocol.OAuth.onFrontendCallbackInit + , placeholder = \x -> () + + -- , onAuthCallbackReceived = Debug.todo "onAuthCallbackReceived" + } + + +getUserInfo : + OAuth.AuthenticationSuccess + -> Task Auth.Common.Error UserInfo +getUserInfo authenticationSuccess = + getUserInfoTask authenticationSuccess + |> Task.andThen + (\userInfo -> + if userInfo.email == "" then + fallbackGetEmailFromEmails authenticationSuccess userInfo + + else + Task.succeed userInfo + ) + + +fallbackGetEmailFromEmails : OAuth.AuthenticationSuccess -> UserInfo -> Task Auth.Common.Error UserInfo +fallbackGetEmailFromEmails authenticationSuccess userInfo = + getUserEmailsTask authenticationSuccess + |> Task.andThen + (\userEmails -> + case userEmails |> List.find (\v -> v.primary == True) of + Just record -> + Task.succeed { userInfo | email = record.email } + + Nothing -> + Task.fail <| + HttpHelpers.customError + "Could not retrieve an email from Github profile or emails list." + ) + |> Task.mapError (HttpHelpers.httpErrorToString >> Auth.Common.ErrAuthString) + + +getUserInfoTask : OAuth.AuthenticationSuccess -> Task Auth.Common.Error UserInfo +getUserInfoTask authenticationSuccess = + Http.task + { method = "GET" + , headers = OAuth.useToken authenticationSuccess.token [] + , url = Url.toString { defaultHttpsUrl | host = "api.github.com", path = "/user" } + , body = Http.emptyBody + , resolver = + HttpHelpers.jsonResolver + (Json.succeed UserInfo + |> optional "email" Json.string "" + |> optional "name" decodeNonEmptyString Nothing + |> optional "login" decodeNonEmptyString Nothing + ) + , timeout = Nothing + } + |> Task.mapError (HttpHelpers.httpErrorToString >> Auth.Common.ErrAuthString) + + +decodeNonEmptyString : Json.Decoder (Maybe String) +decodeNonEmptyString = + Json.string |> Json.map nothingIfEmpty + + +type alias GithubEmail = + { primary : Bool, email : String } + + +getUserEmailsTask : OAuth.AuthenticationSuccess -> Task Http.Error (List GithubEmail) +getUserEmailsTask authenticationSuccess = + Http.task + { method = "GET" + , headers = OAuth.useToken authenticationSuccess.token [] + , url = Url.toString { defaultHttpsUrl | host = "api.github.com", path = "/user/emails" } + , body = Http.emptyBody + , resolver = + HttpHelpers.jsonResolver + (Json.list + (Json.map2 GithubEmail + (Json.field "primary" Json.bool) + (Json.field "email" Json.string) + ) + ) + , timeout = Nothing + } diff --git a/counter/auth-vendored/Auth/Method/OAuthGoogle.elm b/counter/auth-vendored/Auth/Method/OAuthGoogle.elm new file mode 100644 index 0000000..bbf7f58 --- /dev/null +++ b/counter/auth-vendored/Auth/Method/OAuthGoogle.elm @@ -0,0 +1,145 @@ +module Auth.Method.OAuthGoogle exposing + ( configuration + , getUserInfo + , jwtErrorToString + ) + +import Auth.Common exposing (..) +import Auth.HttpHelpers as HttpHelpers +import Auth.Protocol.OAuth +import Base64.Encode as Base64 +import Bytes exposing (Bytes) +import Bytes.Encode as Bytes +import Dict exposing (Dict) +import Http +import JWT exposing (..) +import JWT.JWS as JWS +import Json.Decode as Json +import OAuth +import OAuth.AuthorizationCode as OAuth +import Task exposing (Task) +import Url exposing (Protocol(..), Url) +import Url.Builder + + +configuration : + String + -> String + -> + Method + frontendMsg + backendMsg + { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url } + backendModel +configuration clientId clientSecret = + ProtocolOAuth + { id = "OAuthGoogle" + , authorizationEndpoint = { defaultHttpsUrl | host = "accounts.google.com", path = "/o/oauth2/v2/auth" } + , tokenEndpoint = { defaultHttpsUrl | host = "oauth2.googleapis.com", path = "/token" } + , logoutEndpoint = Home { returnPath = "/logout/OAuthGoogle/callback" } + , allowLoginQueryParameters = False + , clientId = clientId + , clientSecret = clientSecret + , scope = [ "openid email profile" ] + , getUserInfo = getUserInfo + , onFrontendCallbackInit = Auth.Protocol.OAuth.onFrontendCallbackInit + , placeholder = \x -> () + + -- , onAuthCallbackReceived = Debug.todo "onAuthCallbackReceived" + } + + +getUserInfo : + OAuth.AuthenticationSuccess + -> Task Auth.Common.Error UserInfo +getUserInfo authenticationSuccess = + let + extract : String -> Json.Decoder a -> Dict String Json.Value -> Result String a + extract k d v = + Dict.get k v + |> Maybe.map + (\v_ -> + Json.decodeValue d v_ + |> Result.mapError Json.errorToString + ) + |> Maybe.withDefault (Err <| "Key " ++ k ++ " not found") + + extractOptional : a -> String -> Json.Decoder a -> Dict String Json.Value -> Result String a + extractOptional default k d v = + Dict.get k v + |> Maybe.map + (\v_ -> + Json.decodeValue d v_ + |> Result.mapError Json.errorToString + ) + |> Maybe.withDefault (Ok <| default) + + tokenR = + case authenticationSuccess.idJwt of + Nothing -> + Err "Identity JWT missing in authentication response. Please report this issue." + + Just idJwt -> + case JWT.fromString idJwt of + Ok (JWS t) -> + Ok t + + Err err -> + Err <| jwtErrorToString err + + stuff = + tokenR + |> Result.andThen + (\token -> + let + meta = + token.claims.metadata + in + Result.map4 + (\email email_verified given_name family_name -> + { email = email + , email_verified = email_verified + , given_name = given_name + , family_name = family_name + } + ) + (extract "email" Json.string meta) + (extract "email_verified" Json.bool meta) + (extract "given_name" Json.string meta) + (extractOptional Nothing "family_name" (Json.string |> Json.nullable) meta) + ) + in + Task.mapError (Auth.Common.ErrAuthString << HttpHelpers.httpErrorToString) <| + case stuff of + Ok result -> + Task.succeed + { email = result.email + , name = + [ result.given_name, Maybe.withDefault "" result.family_name ] + |> String.join " " + |> nothingIfEmpty + , username = Nothing + } + + Err err -> + Task.fail (Http.BadBody err) + + +jwtErrorToString err = + case err of + TokenTypeUnknown -> + "Unsupported auth token type." + + JWSError decodeError -> + case decodeError of + JWS.Base64DecodeError -> + "Base64DecodeError" + + JWS.MalformedSignature -> + "MalformedSignature" + + JWS.InvalidHeader jsonError -> + "InvalidHeader: " ++ Json.errorToString jsonError + + JWS.InvalidClaims jsonError -> + "InvalidClaims: " ++ Json.errorToString jsonError diff --git a/counter/auth-vendored/Auth/Protocol/OAuth.elm b/counter/auth-vendored/Auth/Protocol/OAuth.elm new file mode 100644 index 0000000..01e641a --- /dev/null +++ b/counter/auth-vendored/Auth/Protocol/OAuth.elm @@ -0,0 +1,239 @@ +module Auth.Protocol.OAuth exposing + ( accessTokenRequested + , generateSigninUrl + , initiateSignin + , makeToken + , onAuthCallbackReceived + , onFrontendCallbackInit + , parseAuthenticationResponse + , parseAuthenticationResponseError + , validateCallbackToken + ) + +import Auth.Common exposing (..) +import Auth.HttpHelpers as HttpHelpers +import Browser.Navigation as Navigation +import Dict exposing (Dict) +import Http +import Json.Decode as Json +import OAuth +import OAuth.AuthorizationCode as OAuth +import Process +import SHA1 +import Task exposing (Task) +import Time +import Url exposing (Url) + + +onFrontendCallbackInit : + { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url } + -> Auth.Common.MethodId + -> Url + -> Navigation.Key + -> (Auth.Common.ToBackend -> Cmd frontendMsg) + -> ( { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url }, Cmd frontendMsg ) +onFrontendCallbackInit model methodId origin navigationKey toBackendFn = + let + redirectUri = + { origin | query = Nothing, fragment = Nothing } + + clearUrl = + Navigation.replaceUrl navigationKey (Url.toString model.authRedirectBaseUrl) + in + case OAuth.parseCode origin of + OAuth.Empty -> + ( { model | authFlow = Idle } + , Cmd.none + ) + + OAuth.Success { code, state } -> + let + state_ = + state |> Maybe.withDefault "" + + model_ = + { model | authFlow = Authorized code state_ } + + ( newModel, newCmds ) = + accessTokenRequested model_ methodId code state_ + in + ( newModel + , Cmd.batch [ toBackendFn newCmds, clearUrl ] + ) + + OAuth.Error error -> + ( { model | authFlow = Errored <| ErrAuthorization error } + , clearUrl + ) + + +accessTokenRequested : + { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url } + -> Auth.Common.MethodId + -> OAuth.AuthorizationCode + -> Auth.Common.State + -> ( { frontendModel | authFlow : Flow, authRedirectBaseUrl : Url }, Auth.Common.ToBackend ) +accessTokenRequested model methodId code state = + ( { model | authFlow = Authorized code state } + , AuthCallbackReceived methodId model.authRedirectBaseUrl code state + ) + + +initiateSignin isDev sessionId baseUrl config asBackendMsg now backendModel = + let + signedState = + SHA1.toBase64 <| + SHA1.fromString <| + (String.fromInt <| Time.posixToMillis <| now) + -- @TODO this needs to be user-injected config + ++ "0x3vd7a" + ++ sessionId + + newPendingAuth : PendingAuth + newPendingAuth = + { sessionId = sessionId + , created = now + , state = signedState + } + + url = + generateSigninUrl baseUrl signedState config + in + ( { backendModel + | pendingAuths = backendModel.pendingAuths |> Dict.insert sessionId newPendingAuth + } + , Auth.Common.sleepTask + isDev + (asBackendMsg + (AuthSigninInitiatedDelayed_ + sessionId + (AuthInitiateSignin url) + ) + ) + ) + + +generateSigninUrl : Url -> Auth.Common.State -> Auth.Common.ConfigurationOAuth frontendMsg backendMsg frontendModel backendModel -> Url +generateSigninUrl baseUrl state configuration = + let + queryAdjustedUrl = + -- google auth is an example where, at time of writing, query parameters are not allowed in a login redirect url + if configuration.allowLoginQueryParameters then + baseUrl + + else + { baseUrl | query = Nothing } + + authorization = + { clientId = configuration.clientId + , redirectUri = { queryAdjustedUrl | path = "/login/" ++ configuration.id ++ "/callback" } + , scope = configuration.scope + , state = Just state + , url = configuration.authorizationEndpoint + } + in + authorization + |> OAuth.makeAuthorizationUrl + + +onAuthCallbackReceived sessionId clientId method receivedUrl code state now asBackendMsg backendModel = + ( backendModel + , validateCallbackToken method.clientId method.clientSecret method.tokenEndpoint receivedUrl code + |> Task.andThen + (\authenticationResponse -> + case backendModel.pendingAuths |> Dict.get sessionId of + Just pendingAuth -> + let + authToken = + Just (makeToken method.id authenticationResponse now) + in + if pendingAuth.state == state then + method.getUserInfo + authenticationResponse + |> Task.map (\userInfo -> ( userInfo, authToken )) + + else + Task.fail <| Auth.Common.ErrAuthString "Invalid auth state. Please log in again or report this issue." + + Nothing -> + Task.fail <| Auth.Common.ErrAuthString "Couldn't validate auth, please login again." + ) + |> Task.attempt (Auth.Common.AuthSuccess sessionId clientId method.id now >> asBackendMsg) + ) + + +validateCallbackToken : + String + -> String + -> Url + -> Url + -> OAuth.AuthorizationCode + -> Task Auth.Common.Error OAuth.AuthenticationSuccess +validateCallbackToken clientId clientSecret tokenEndpoint redirectUri code = + let + req = + OAuth.makeTokenRequest (always ()) + { credentials = + { clientId = clientId + , secret = Just clientSecret + } + , code = code + , url = tokenEndpoint + , redirectUri = { redirectUri | query = Nothing, fragment = Nothing } + } + in + { method = req.method + , headers = req.headers ++ [ Http.header "Accept" "application/json" ] + , url = req.url + , body = req.body + , resolver = HttpHelpers.jsonResolver OAuth.defaultAuthenticationSuccessDecoder + , timeout = req.timeout + } + |> Http.task + |> Task.mapError parseAuthenticationResponseError + + +parseAuthenticationResponse : Result Http.Error OAuth.AuthenticationSuccess -> Result Auth.Common.Error OAuth.AuthenticationSuccess +parseAuthenticationResponse res = + case res of + Err (Http.BadBody body) -> + case Json.decodeString OAuth.defaultAuthenticationErrorDecoder body of + Ok error -> + Err <| Auth.Common.ErrAuthentication error + + _ -> + Err Auth.Common.ErrHTTPGetAccessToken + + Err _ -> + Err Auth.Common.ErrHTTPGetAccessToken + + Ok authenticationSuccess -> + Ok authenticationSuccess + + +parseAuthenticationResponseError : Http.Error -> Auth.Common.Error +parseAuthenticationResponseError httpErr = + case httpErr of + Http.BadBody body -> + case Json.decodeString OAuth.defaultAuthenticationErrorDecoder body of + Ok error -> + Auth.Common.ErrAuthentication error + + _ -> + Auth.Common.ErrHTTPGetAccessToken + + _ -> + Auth.Common.ErrHTTPGetAccessToken + + +makeToken : Auth.Common.MethodId -> OAuth.AuthenticationSuccess -> Time.Posix -> Auth.Common.Token +makeToken methodId authenticationSuccess now = + { methodId = methodId + , token = authenticationSuccess.token + , created = now + , expires = + (Time.posixToMillis now + + ((authenticationSuccess.expiresIn |> Maybe.withDefault 0) * 1000) + ) + |> Time.millisToPosix + } diff --git a/counter/auth-vendored/Extra/Maybe.elm b/counter/auth-vendored/Extra/Maybe.elm new file mode 100644 index 0000000..5f7866d --- /dev/null +++ b/counter/auth-vendored/Extra/Maybe.elm @@ -0,0 +1,12 @@ +module Extra.Maybe exposing (andThen2) + +{-| Extra helpers for `Maybe` + +@docs andThen2 + +-} + + +andThen2 : (a -> b -> Maybe c) -> Maybe a -> Maybe b -> Maybe c +andThen2 fn ma mb = + Maybe.andThen identity (Maybe.map2 fn ma mb) diff --git a/counter/auth-vendored/JWT.elm b/counter/auth-vendored/JWT.elm new file mode 100644 index 0000000..0c1dfaf --- /dev/null +++ b/counter/auth-vendored/JWT.elm @@ -0,0 +1,83 @@ +module JWT exposing + ( JWT(..), DecodeError(..), fromString + , VerificationError(..), isValid, validate + ) + +{-| + + +# JWT + +@docs JWT, DecodeError, fromString + + +# Verification + +@docs VerificationError, isValid, validate + +-} + +import JWT.ClaimSet exposing (VerifyOptions) +import JWT.JWS as JWS +import Task exposing (Task) +import Time exposing (Posix) + + +{-| A JSON Web Token. + +Can be either a JWS (signed) or a JWE (encrypted). The latter is not yet implemented. + +-} +type JWT + = JWS JWS.JWS + + +{-| A structured error describing exactly how the decoder failed. +-} +type DecodeError + = TokenTypeUnknown + | JWSError JWS.DecodeError + + +{-| Decode a JWT from string. + + fromString "eyJhbGciOi..." == Ok ... + fromString "" == Err ... + fromString "definitelyNotAJWT" == Err ... + +-} +fromString : String -> Result DecodeError JWT +fromString string = + case String.split "." string of + [ header, claims, signature ] -> + JWS.fromParts header claims signature + |> Result.mapError JWSError + |> Result.map JWS + + -- TODO [ header_, encryptedKey, iv, ciphertext, authenticationTag ] + _ -> + Err TokenTypeUnknown + + +{-| A structured error describing all verification errors. +-} +type VerificationError + = JWSVerificationError JWS.VerificationError + + +{-| Check if the token is valid. +-} +isValid : VerifyOptions -> String -> Posix -> JWT -> Result VerificationError Bool +isValid options key now token = + case token of + JWS token_ -> + JWS.isValid options key now token_ + |> Result.mapError JWSVerificationError + + +{-| A task to check if the token is valid. +-} +validate : VerifyOptions -> String -> JWT -> Task Never (Result VerificationError Bool) +validate options key token = + Time.now + |> Task.andThen ((\now -> isValid options key now token) >> Task.succeed) diff --git a/counter/auth-vendored/JWT/ClaimSet.elm b/counter/auth-vendored/JWT/ClaimSet.elm new file mode 100644 index 0000000..6c1342a --- /dev/null +++ b/counter/auth-vendored/JWT/ClaimSet.elm @@ -0,0 +1,193 @@ +module JWT.ClaimSet exposing + ( ClaimSet + , VerificationError(..) + , VerifyOptions + , decoder + , encoder + , isValid + ) + +import Dict exposing (Dict) +import Json.Decode as Decode +import Json.Decode.Pipeline exposing (custom, optional) +import Json.Encode as Encode +import Time exposing (Posix) + + +type alias ClaimSet = + { iss : Maybe String + , sub : Maybe String + , aud : Maybe String + , exp : Maybe Int + , nbf : Maybe Int + , iat : Maybe Int + , jti : Maybe String + , metadata : Dict String Decode.Value + } + + +decoder : Decode.Decoder ClaimSet +decoder = + Decode.succeed ClaimSet + |> optional "iss" (Decode.maybe Decode.string) Nothing + |> optional "sub" (Decode.maybe Decode.string) Nothing + |> optional "aud" (Decode.maybe Decode.string) Nothing + |> optional "exp" (Decode.maybe Decode.int) Nothing + |> optional "nbf" (Decode.maybe Decode.int) Nothing + |> optional "iat" (Decode.maybe Decode.int) Nothing + |> optional "jti" (Decode.maybe Decode.string) Nothing + |> custom (Decode.dict Decode.value) + + +encoder : ClaimSet -> Encode.Value +encoder claims = + let + metadata = + Dict.toList claims.metadata + |> List.map Just + in + metadata + ++ [ claims.iss |> Maybe.map (\f -> ( "iss", Encode.string f )) + , claims.sub |> Maybe.map (\f -> ( "sub", Encode.string f )) + , claims.aud |> Maybe.map (\f -> ( "aud", Encode.string f )) + , claims.exp |> Maybe.map (\f -> ( "exp", Encode.int f )) + , claims.nbf |> Maybe.map (\f -> ( "nbf", Encode.int f )) + , claims.iat |> Maybe.map (\f -> ( "iat", Encode.int f )) + , claims.jti |> Maybe.map (\f -> ( "jti", Encode.string f )) + ] + |> List.filterMap identity + |> Encode.object + + +type VerificationError + = InvalidIssuer + | InvalidAudience + | InvalidSubject + | InvalidJWTID + | Expired + | NotYetValid + | NotYetIssued + + +type alias VerifyOptions = + { issuer : Maybe String + , audience : Maybe String + , subject : Maybe String + , jwtID : Maybe String + , leeway : Int + } + + +isValid : VerifyOptions -> Posix -> ClaimSet -> Result VerificationError Bool +isValid options now claims = + checkIssuer claims.iss options.issuer + |> Result.andThen + (\_ -> checkAudience claims.aud options.audience) + |> Result.andThen + (\_ -> checkSubject claims.sub options.subject) + |> Result.andThen + (\_ -> checkID claims.jti options.jwtID) + |> Result.andThen + (\_ -> checkExpiration now options.leeway claims.exp) + |> Result.andThen + (\_ -> checkNotBefore now options.leeway claims.nbf) + |> Result.andThen + (\_ -> checkIssuedAt now options.leeway claims.iat) + + +checkIssuer : Maybe String -> Maybe String -> Result VerificationError Bool +checkIssuer claim option = + case option of + Nothing -> + Ok True + + issuer -> + if issuer == claim then + Ok True + + else + Err InvalidIssuer + + +checkAudience : Maybe String -> Maybe String -> Result VerificationError Bool +checkAudience claim option = + case option of + Nothing -> + Ok True + + audience -> + if audience == claim then + Ok True + + else + Err InvalidAudience + + +checkSubject : Maybe String -> Maybe String -> Result VerificationError Bool +checkSubject claim option = + case option of + Nothing -> + Ok True + + subject -> + if subject == claim then + Ok True + + else + Err InvalidSubject + + +checkID : Maybe String -> Maybe String -> Result VerificationError Bool +checkID claim option = + case option of + Nothing -> + Ok True + + jwtID -> + if jwtID == claim then + Ok True + + else + Err InvalidJWTID + + +checkExpiration : Posix -> Int -> Maybe Int -> Result VerificationError Bool +checkExpiration now leeway claim = + case claim of + Nothing -> + Ok True + + Just expiration -> + if Time.posixToMillis now - leeway < expiration * 1000 then + Ok True + + else + Err Expired + + +checkNotBefore : Posix -> Int -> Maybe Int -> Result VerificationError Bool +checkNotBefore now leeway claim = + case claim of + Nothing -> + Ok True + + Just nbf -> + if Time.posixToMillis now + leeway > nbf * 1000 then + Ok True + + else + Err NotYetValid + + +checkIssuedAt : Posix -> Int -> Maybe Int -> Result VerificationError Bool +checkIssuedAt now leeway claim = + case claim of + Nothing -> + Ok True + + Just iat -> + if Time.posixToMillis now + leeway > iat * 1000 then + Ok True + + else + Err NotYetIssued diff --git a/counter/auth-vendored/JWT/JWK.elm b/counter/auth-vendored/JWT/JWK.elm new file mode 100644 index 0000000..346a36a --- /dev/null +++ b/counter/auth-vendored/JWT/JWK.elm @@ -0,0 +1,48 @@ +module JWT.JWK exposing (JWK, decoder, encoder) + +import Json.Decode as Decode +import Json.Decode.Pipeline exposing (optional, required) +import Json.Encode as Encode + + +type alias JWK = + { kty : String + , use : Maybe String + , key_ops : Maybe (List String) + , alg : Maybe String + , kid : Maybe String + , x5u : Maybe String + , x5c : Maybe (List String) + , x5t : Maybe String + , x5t_S256 : Maybe String + } + + +decoder : Decode.Decoder JWK +decoder = + Decode.succeed JWK + |> required "kty" Decode.string + |> optional "use" (Decode.maybe Decode.string) Nothing + |> optional "key_ops" (Decode.maybe <| Decode.list Decode.string) Nothing + |> optional "alg" (Decode.maybe Decode.string) Nothing + |> optional "kid" (Decode.maybe Decode.string) Nothing + |> optional "x5u" (Decode.maybe Decode.string) Nothing + |> optional "x5c" (Decode.maybe <| Decode.list Decode.string) Nothing + |> optional "x5t" (Decode.maybe Decode.string) Nothing + |> optional "x5t#S256" (Decode.maybe Decode.string) Nothing + + +encoder : JWK -> Encode.Value +encoder jwk = + [ jwk.kty |> (\f -> Just ( "kty", Encode.string f )) + , jwk.use |> Maybe.map (\f -> ( "use", Encode.string f )) + , jwk.key_ops |> Maybe.map (\f -> ( "key_ops", Encode.list Encode.string f )) + , jwk.alg |> Maybe.map (\f -> ( "alg", Encode.string f )) + , jwk.kid |> Maybe.map (\f -> ( "kid", Encode.string f )) + , jwk.x5u |> Maybe.map (\f -> ( "x5u", Encode.string f )) + , jwk.x5c |> Maybe.map (\f -> ( "x5c", Encode.list Encode.string f )) + , jwk.x5t |> Maybe.map (\f -> ( "x5t", Encode.string f )) + , jwk.x5t_S256 |> Maybe.map (\f -> ( "x5t#S256", Encode.string f )) + ] + |> List.filterMap identity + |> Encode.object diff --git a/counter/auth-vendored/JWT/JWKSet.elm b/counter/auth-vendored/JWT/JWKSet.elm new file mode 100644 index 0000000..5b29e95 --- /dev/null +++ b/counter/auth-vendored/JWT/JWKSet.elm @@ -0,0 +1,20 @@ +module JWT.JWKSet exposing (JWKSet, fromString, jwkSetDecoder) + +import JWT.JWK as JWK exposing (JWK) +import Json.Decode as Decode + + +type alias JWKSet = + { keys : List JWK } + + +fromString : String -> Result Decode.Error JWKSet +fromString string = + Decode.decodeString jwkSetDecoder string + + +jwkSetDecoder : Decode.Decoder JWKSet +jwkSetDecoder = + Decode.list JWK.decoder + |> Decode.field "keys" + |> Decode.map JWKSet diff --git a/counter/auth-vendored/JWT/JWS.elm b/counter/auth-vendored/JWT/JWS.elm new file mode 100644 index 0000000..0c54519 --- /dev/null +++ b/counter/auth-vendored/JWT/JWS.elm @@ -0,0 +1,190 @@ +module JWT.JWS exposing + ( DecodeError(..) + , Header + , JWS + , VerificationError(..) + , decode + , fromParts + , isValid + ) + +import Base64.Decode as B64Decode +import Base64.Encode as B64Encode +import Bytes exposing (Bytes) +import Bytes.Decode +import Crypto.HMAC +import JWT.ClaimSet as ClaimSet exposing (VerifyOptions) +import JWT.JWK as JWK +import JWT.UrlBase64 as UrlBase64 +import Json.Decode as JDecode +import Json.Decode.Pipeline exposing (optional, required) +import Json.Encode as JEncode +import Result exposing (andThen, map, mapError) +import Time exposing (Posix) +import Word.Bytes + + +type alias JWS = + { signature : List Int + , header : Header + , claims : ClaimSet.ClaimSet + } + + +type alias Header = + { alg : String + , jku : Maybe String + , jwk : Maybe JWK.JWK + , kid : Maybe String + , x5u : Maybe String + , x5c : Maybe (List String) + , x5t : Maybe String + , x5t_S256 : Maybe String + , typ : Maybe String + , cty : Maybe String + , crit : Maybe (List String) + } + + +type DecodeError + = Base64DecodeError + | MalformedSignature + | InvalidHeader JDecode.Error + | InvalidClaims JDecode.Error + + +fromParts : String -> String -> String -> Result DecodeError JWS +fromParts header claims signature = + let + decode_ d part = + UrlBase64.decode (B64Decode.decode d) part + + bytesDecoder len = + Bytes.Decode.loop ( len, [] ) <| + \( n, xs ) -> + if n <= 0 then + Bytes.Decode.succeed (Bytes.Decode.Done xs) + + else + Bytes.Decode.map (\x -> Bytes.Decode.Loop ( n - 1, x :: xs )) Bytes.Decode.unsignedInt8 + + decodeBytes bytes = + Bytes.Decode.decode (bytesDecoder (Bytes.width bytes)) bytes + |> Maybe.map List.reverse + in + case + ( decode_ B64Decode.string header + , decode_ B64Decode.string claims + , decode_ B64Decode.bytes signature + ) + of + ( Ok header_, Ok claims_, Ok signature_ ) -> + case decodeBytes signature_ of + Just sig -> + decode header_ claims_ sig + + Nothing -> + Err MalformedSignature + + _ -> + Err Base64DecodeError + + +decode : String -> String -> List Int -> Result DecodeError JWS +decode header claims signature = + JDecode.decodeString headerDecoder header + |> mapError InvalidHeader + |> andThen + (\header_ -> + JDecode.decodeString ClaimSet.decoder claims + |> mapError InvalidClaims + |> map (JWS signature header_) + ) + + +encodeParts : JWS -> List String +encodeParts token = + [ JEncode.encode 0 <| headerEncoder token.header + , JEncode.encode 0 <| ClaimSet.encoder token.claims + ] + + +headerDecoder : JDecode.Decoder Header +headerDecoder = + JDecode.succeed Header + |> required "alg" JDecode.string + |> optional "jku" (JDecode.maybe JDecode.string) Nothing + |> optional "jwk" (JDecode.maybe JWK.decoder) Nothing + |> optional "kid" (JDecode.maybe JDecode.string) Nothing + |> optional "x5u" (JDecode.maybe JDecode.string) Nothing + |> optional "x5c" (JDecode.maybe <| JDecode.list JDecode.string) Nothing + |> optional "x5t" (JDecode.maybe JDecode.string) Nothing + |> optional "x5t#S256" (JDecode.maybe JDecode.string) Nothing + |> optional "typ" (JDecode.maybe JDecode.string) Nothing + |> optional "cty" (JDecode.maybe JDecode.string) Nothing + |> optional "crit" (JDecode.maybe <| JDecode.list JDecode.string) Nothing + + +headerEncoder : Header -> JEncode.Value +headerEncoder header = + [ header.alg |> (\f -> Just ( "alg", JEncode.string f )) + , header.jku |> Maybe.map (\f -> ( "jku", JEncode.string f )) + , header.jwk |> Maybe.map (\f -> ( "jwk", JWK.encoder f )) + , header.kid |> Maybe.map (\f -> ( "kid", JEncode.string f )) + , header.x5u |> Maybe.map (\f -> ( "x5u", JEncode.string f )) + , header.x5c |> Maybe.map (\f -> ( "x5c", JEncode.list JEncode.string f )) + , header.x5t |> Maybe.map (\f -> ( "x5t", JEncode.string f )) + , header.x5t_S256 |> Maybe.map (\f -> ( "x5t#S256", JEncode.string f )) + , header.typ |> Maybe.map (\f -> ( "typ", JEncode.string f )) + , header.cty |> Maybe.map (\f -> ( "cty", JEncode.string f )) + , header.crit |> Maybe.map (\f -> ( "crit", JEncode.list JEncode.string f )) + ] + |> List.filterMap identity + |> JEncode.object + + +type VerificationError + = UnsupportedAlgorithm + | InvalidSignature + | ClaimSet ClaimSet.VerificationError + + +isValid : VerifyOptions -> String -> Posix -> JWS -> Result VerificationError Bool +isValid options key now token = + checkSignature key token + |> Result.andThen + (\_ -> + ClaimSet.isValid options now token.claims + |> Result.mapError ClaimSet + ) + + +checkSignature : String -> JWS -> Result VerificationError Bool +checkSignature key token = + let + payload = + encodeParts token + |> List.map (\p -> UrlBase64.encode B64Encode.encode (B64Encode.string p)) + |> String.join "." + |> Word.Bytes.fromUTF8 + + detectAlg = + case token.header.alg of + "HS256" -> + Ok Crypto.HMAC.sha256 + + _ -> + Err UnsupportedAlgorithm + + calculated alg = + Crypto.HMAC.digestBytes alg (Word.Bytes.fromUTF8 key) payload + in + detectAlg + |> Result.andThen + (\alg -> + if token.signature == calculated alg then + Ok True + + else + Err InvalidSignature + ) diff --git a/counter/auth-vendored/JWT/LICENSE b/counter/auth-vendored/JWT/LICENSE new file mode 100644 index 0000000..c3f5b52 --- /dev/null +++ b/counter/auth-vendored/JWT/LICENSE @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + + Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +1. Source Code. + +The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + +The Corresponding Source for a work in source code form is that +same work. + +2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + +4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified +it, and giving a relevant date. + +b) The work must carry prominent notices stating that it is +released under this License and any conditions added under section +7. This requirement modifies the requirement in section 4 to +"keep intact all notices". + +c) You must license the entire work, as a whole, under this +License to anyone who comes into possession of a copy. This +License will therefore apply, along with any applicable section 7 +additional terms, to the whole of the work, and all its parts, +regardless of how they are packaged. This License gives no +permission to license the work in any other way, but it does not +invalidate such permission if you have separately received it. + +d) If the work has interactive user interfaces, each must display +Appropriate Legal Notices; however, if the Program has interactive +interfaces that do not display Appropriate Legal Notices, your +work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + +a) Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by the +Corresponding Source fixed on a durable physical medium +customarily used for software interchange. + +b) Convey the object code in, or embodied in, a physical product +(including a physical distribution medium), accompanied by a +written offer, valid for at least three years and valid for as +long as you offer spare parts or customer support for that product +model, to give anyone who possesses the object code either (1) a +copy of the Corresponding Source for all the software in the +product that is covered by this License, on a durable physical +medium customarily used for software interchange, for a price no +more than your reasonable cost of physically performing this +conveying of source, or (2) access to copy the +Corresponding Source from a network server at no charge. + +c) Convey individual copies of the object code with a copy of the +written offer to provide the Corresponding Source. This +alternative is allowed only occasionally and noncommercially, and +only if you received the object code with such an offer, in accord +with subsection 6b. + +d) Convey the object code by offering access from a designated +place (gratis or for a charge), and offer equivalent access to the +Corresponding Source in the same way through the same place at no +further charge. You need not require recipients to copy the +Corresponding Source along with the object code. If the place to +copy the object code is a network server, the Corresponding Source +may be on a different server (operated by you or a third party) +that supports equivalent copying facilities, provided you maintain +clear directions next to the object code saying where to find the +Corresponding Source. Regardless of what server hosts the +Corresponding Source, you remain obligated to ensure that it is +available for as long as needed to satisfy these requirements. + +e) Convey the object code using peer-to-peer transmission, provided +you inform other peers where the object code and Corresponding +Source of the work are being offered to the general public at no +charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the +terms of sections 15 and 16 of this License; or + +b) Requiring preservation of specified reasonable legal notices or +author attributions in that material or in the Appropriate Legal +Notices displayed by works containing it; or + +c) Prohibiting misrepresentation of the origin of that material, or +requiring that modified versions of such material be marked in +reasonable ways as different from the original version; or + +d) Limiting the use for publicity purposes of names of licensors or +authors of the material; or + +e) Declining to grant rights under trademark law for use of some +trade names, trademarks, or service marks; or + +f) Requiring indemnification of licensors and authors of that +material by anyone who conveys the material (or modified versions of +it) with contractual assumptions of liability to the recipient, for +any liability that these contractual assumptions directly impose on +those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + +Copyright (C) + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) +This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. +This is free software, and you are welcome to redistribute it +under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + +You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + +The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/counter/auth-vendored/JWT/UrlBase64.elm b/counter/auth-vendored/JWT/UrlBase64.elm new file mode 100644 index 0000000..410584a --- /dev/null +++ b/counter/auth-vendored/JWT/UrlBase64.elm @@ -0,0 +1,116 @@ +module JWT.UrlBase64 exposing + ( encode, decode + , replaceForUrl, replaceFromUrl + ) + +{-| A couple of functions for use with a base64 encoder and decoder that convert the +base64 alphabet to and from the url alphabet. + +They can be composed with encode and decode in truqu/elm-base64 like this: + + b64e = + UrlBase64.encode Base64.encode + + b64d = + UrlBase64.decode Base64.decode + +Applying these to url base64 converts to and from standard base64 into and out +of the decoders underneath. + + + base64_1 = + b64e "aÿÿ" + + -- Ok "Yf__" + base64_t = + b64e "aÿÿ" |> Result.andThen b64d + + -- Ok "aÿÿ" + base64_2 = + b64e "aÿ" + + -- Ok "Yf8" + base64_u = + b64e "aÿ" |> Result.andThen b64d + + -- Ok "aÿ" + +@docs encode, decode + +-} + +import Maybe as Maybe +import Regex exposing (Regex) + + +replaceForUrl : Regex +replaceForUrl = + Regex.fromString "[\\+/=]" |> Maybe.withDefault Regex.never + + +{-| Expose the given function to the given string and convert the result from +the standard base64 alphabet and trim trailing '=' characters. + +Compose this with a base64 encoder to make a url-base64 encoder. + + b64e = + UrlBase64.encode Base64.encode + +-} +encode : (a -> String) -> a -> String +encode enc t = + let + replaceChar rematch = + case rematch.match of + "+" -> + "-" + + "/" -> + "_" + + _ -> + "" + in + enc t + |> Regex.replace replaceForUrl replaceChar + + +replaceFromUrl : Regex +replaceFromUrl = + Regex.fromString "[-_]" |> Maybe.withDefault Regex.never + + +{-| Expose the given function to the standard base64 alphabet form of the given +string with padding restored. + +Compose this with a base64 decoder to make a url-base64 decoder. + + b64d = + UrlBase64.decode Base64.decode + +-} +decode : (String -> Result err a) -> String -> Result err a +decode dec e = + let + replaceChar rematch = + case rematch.match of + "-" -> + "+" + + _ -> + "/" + + strlen = + String.length e + + hanging = + modBy strlen 4 + + ilen = + if hanging == 0 then + 0 + + else + 4 - hanging + in + dec (Regex.replace replaceFromUrl replaceChar (e ++ String.repeat ilen "=")) diff --git a/counter/auth-vendored/JWT/readme.md b/counter/auth-vendored/JWT/readme.md new file mode 100644 index 0000000..8b67c8a --- /dev/null +++ b/counter/auth-vendored/JWT/readme.md @@ -0,0 +1,5 @@ +Vendored from https://github.com/leojpod/elm-jwt in order to: + +- Expose `JWT.JWS` + +Ideally this will be de-vendored into a regular Elm dependency in future. diff --git a/counter/auth-vendored/OAuth.elm b/counter/auth-vendored/OAuth.elm new file mode 100644 index 0000000..95006d6 --- /dev/null +++ b/counter/auth-vendored/OAuth.elm @@ -0,0 +1,340 @@ +module OAuth exposing + ( Token(..), useToken, tokenToString, tokenFromString + , ErrorCode(..), errorCodeToString, errorCodeFromString + , ResponseType(..), responseTypeToString, GrantType(..), grantTypeToString + , TokenType, TokenString, makeToken, makeRefreshToken + ) + +{-| Utility library to manage client-side OAuth 2.0 authentications + +The library contains a main OAuth module exposing types used accross other modules. In practice, +you'll only need to use one of the additional modules: + + - OAuth.AuthorizationCode: The authorization code grant type is used to obtain both access tokens + and refresh tokens via a redirection-based flow and is optimized for confidential clients + [4.1](https://tools.ietf.org/html/rfc6749#section-4.1). + + - OAuth.AuthorizationCode.PKCE: An extension of the original OAuth 2.0 specification to mitigate + authorization code interception attacks through the use of Proof Key for Code Exchange (PKCE). + + - OAuth.Implicit: The implicit grant type is used to obtain access tokens (it does not support the + issuance of refresh tokens) and is optimized for public clients known to operate a particular + redirection URI [4.2](https://tools.ietf.org/html/rfc6749#section-4.2). + + - OAuth.Password: The resource owner password credentials grant type is suitable in cases where the + resource owner has a trust relationship with the client, such as the device operating system or a + highly privileged application [4.3](https://tools.ietf.org/html/rfc6749#section-4.3) + + - OAuth.ClientCredentials: The client can request an access token using only its client credentials + (or other supported means of authentication) when the client is requesting access to the protected + resources under its control, or those of another resource owner that have been previously arranged + with the authorization server (the method of which is beyond the scope of this specification) + [4.4](https://tools.ietf.org/html/rfc6749#section-4.3). + +In practice, you most probably want to use the +[`OAuth.AuthorizationCode`](http://package.elm-lang.org/packages/truqu/elm-oauth2/latest/OAuth-AuthorizationCode). +If your authorization server supports it, you should look at the PKCE extension in a second-time! + +which is the most commonly +used. + + +## Token + +@docs Token, useToken, tokenToString, tokenFromString + + +## ErrorCode + +@docs ErrorCode, errorCodeToString, errorCodeFromString + + +## Response & Grant types (Advanced) + +The following section can be ignored if you're dealing with a very generic OAuth2.0 implementation. If however, your authorization server does implement some extra features on top of the OAuth2.0 protocol (e.g. OpenID Connect), you will require to tweak response parsers and possibly, response type to cope with these discrepancies. In short, unless you're planning on using `makeTokenRequestWith` or `makeAuthorizationUrlWith`, you most probably won't need any of the functions below. + +@docs ResponseType, responseTypeToString, GrantType, grantTypeToString + + +## Decoders & Parsers Utils (advanced) + +@docs TokenType, TokenString, makeToken, makeRefreshToken + +-} + +import Extra.Maybe as Maybe +import Http as Http + + + +-- +-- Token +-- + + +{-| Describes the type of access token to use. + + - Bearer: Utilized by simply including the access token string in the request + [rfc6750](https://tools.ietf.org/html/rfc6750) + + - Mac: Not supported. + +-} +type Token + = Bearer String + + +{-| Alias for readability +-} +type alias TokenType = + String + + +{-| Alias for readability +-} +type alias TokenString = + String + + +{-| Use a token to authenticate a request. +-} +useToken : Token -> List Http.Header -> List Http.Header +useToken token = + (::) (Http.header "Authorization" (tokenToString token)) + + +{-| Create a token from two string representing a token type and +an actual token value. This is intended to be used in Json decoders +or Query parsers. + +Returns `Nothing` when the token type is `Nothing` +, different from `Just "Bearer"` or when there's no token at all. + +-} +makeToken : Maybe TokenType -> Maybe TokenString -> Maybe Token +makeToken = + Maybe.andThen2 tryMakeToken + + +{-| See `makeToken`, with the subtle difference that a token value may or +may not be there. + +Returns `Nothing` when the token type isn't `"Bearer"`. + +Returns `Just Nothing` or `Just (Just token)` otherwise, depending on whether a token is +present or not. + +-} +makeRefreshToken : TokenType -> Maybe TokenString -> Maybe (Maybe Token) +makeRefreshToken tokenType mToken = + case ( mToken, Maybe.andThen2 tryMakeToken (Just tokenType) mToken ) of + ( Nothing, _ ) -> + Just Nothing + + ( _, Just token ) -> + Just <| Just token + + _ -> + Nothing + + +{-| Internal, attempt to make a Bearer token from a type and a token string +-} +tryMakeToken : TokenType -> TokenString -> Maybe Token +tryMakeToken tokenType token = + case String.toLower tokenType of + "bearer" -> + Just (Bearer token) + + _ -> + Nothing + + +{-| Get the `String` representation of a `Token` to be used in an 'Authorization' header +-} +tokenToString : Token -> String +tokenToString (Bearer t) = + "Bearer " ++ t + + +{-| Parse a token from an 'Authorization' header string. + + tokenFromString (tokenToString token) == Just token + +-} +tokenFromString : String -> Maybe Token +tokenFromString str = + case ( String.left 6 str, String.dropLeft 7 str ) of + ( "Bearer", t ) -> + Just (Bearer t) + + _ -> + Nothing + + + +-- +-- ResponseType / GrandType +-- + + +{-| Describes the desired type of response to an authorization. Use `Code` to ask for an +authorization code and continue with the according flow. Use `Token` to do an implicit +authentication and directly retrieve a `Token` from the authorization. If need be, you may provide a +custom response type should the server returns a non-standard response type. +-} +type ResponseType + = Code + | Token + | CustomResponse String + + +{-| Gets the `String` representation of a `ResponseType`. +-} +responseTypeToString : ResponseType -> String +responseTypeToString r = + case r of + Code -> + "code" + + Token -> + "token" + + CustomResponse str -> + str + + +{-| Describes the desired type of grant to an authentication. +-} +type GrantType + = AuthorizationCode + | Password + | ClientCredentials + | RefreshToken + | CustomGrant String + + +{-| Gets the `String` representation of a `GrantType` +-} +grantTypeToString : GrantType -> String +grantTypeToString g = + case g of + AuthorizationCode -> + "authorization_code" + + Password -> + "password" + + ClientCredentials -> + "client_credentials" + + RefreshToken -> + "refresh_token" + + CustomGrant str -> + str + + + +-- +-- Error +-- + + +{-| Describes an OAuth error response [4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1) + + - `InvalidRequest`: The request is missing a required parameter, includes an invalid parameter value, + includes a parameter more than once, or is otherwise malformed. + + - `UnauthorizedClient`: The client is not authorized to request an authorization code using this + method. + + - `AccessDenied`: The resource owner or authorization server denied the request. + + - `UnsupportedResponseType`: The authorization server does not support obtaining an authorization code + using this method. + + - `InvalidScope`: The requested scope is invalid, unknown, or malformed. + + - `ServerError`: The authorization server encountered an unexpected condition that prevented it from + fulfilling the request. (This error code is needed because a 500 Internal Server Error HTTP status + code cannot be returned to the client via an HTTP redirect.) + + - `TemporarilyUnavailable`: The authorization server is currently unable to handle the request due to + a temporary overloading or maintenance of the server. (This error code is needed because a 503 + Service Unavailable HTTP status code cannot be returned to the client via an HTTP redirect.) + + - `Custom`: Encountered a 'free-string' or custom code not specified by the official RFC but returned + by the authorization server. + +-} +type ErrorCode + = InvalidRequest + | UnauthorizedClient + | AccessDenied + | UnsupportedResponseType + | InvalidScope + | ServerError + | TemporarilyUnavailable + | Custom String + + +{-| Get the `String` representation of an `ErrorCode`. +-} +errorCodeToString : ErrorCode -> String +errorCodeToString err = + case err of + InvalidRequest -> + "invalid_request" + + UnauthorizedClient -> + "unauthorized_client" + + AccessDenied -> + "access_denied" + + UnsupportedResponseType -> + "unsupported_response_type" + + InvalidScope -> + "invalid_scope" + + ServerError -> + "server_error" + + TemporarilyUnavailable -> + "temporarily_unavailable" + + Custom str -> + str + + +{-| Build a string back into an error code. Returns `Custom _` +when the string isn't recognized from the ones specified in the RFC +-} +errorCodeFromString : String -> ErrorCode +errorCodeFromString str = + case str of + "invalid_request" -> + InvalidRequest + + "unauthorized_client" -> + UnauthorizedClient + + "access_denied" -> + AccessDenied + + "unsupported_response_type" -> + UnsupportedResponseType + + "invalid_scope" -> + InvalidScope + + "server_error" -> + ServerError + + "temporarily_unavailable" -> + TemporarilyUnavailable + + _ -> + Custom str diff --git a/counter/auth-vendored/OAuth/AuthorizationCode.elm b/counter/auth-vendored/OAuth/AuthorizationCode.elm new file mode 100644 index 0000000..4771416 --- /dev/null +++ b/counter/auth-vendored/OAuth/AuthorizationCode.elm @@ -0,0 +1,612 @@ +module OAuth.AuthorizationCode exposing + ( makeAuthorizationUrl, Authorization, parseCode, AuthorizationResult, AuthorizationResultWith(..), AuthorizationError, AuthorizationSuccess, AuthorizationCode + , makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + , defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + , makeAuthorizationUrlWith + , makeTokenRequestWith + , defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + , parseCodeWith, Parsers, defaultParsers, defaultCodeParser, defaultErrorParser, defaultAuthorizationSuccessParser, defaultAuthorizationErrorParser + ) + +{-| The authorization code grant type is used to obtain both access +tokens and refresh tokens and is optimized for confidential clients. +Since this is a redirection-based flow, the client must be capable of +interacting with the resource owner's user-agent (typically a web +browser) and capable of receiving incoming requests (via redirection) +from the authorization server. + + +## Quick Start + +To get started, have a look at the [live-demo](https://truqu.github.io/elm-oauth2/auth0/authorization-code/) and its +corresponding [source code](https://github.com/truqu/elm-oauth2/blob/master/examples/providers/auth0/authorization-code/Main.elm). + + +## Overview + + +---------+ +--------+ + | |---(A)- Auth Redirection ------>| | + | | | Auth | + | Browser | | Server | + | | | | + | |<--(B)- Redirection Callback ---| | + +---------+ (w/ Auth Code) +--------+ + ^ | ^ | + | | | | + (A) (B) | | + | | | | + | v | | + +---------+ | | + | |----(C)---- Auth Code ------------+ | + | Elm App | | + | | | + | |<---(D)------ Access Token ------------+ + +---------+ (w/ Optional Refresh Token) + + - (A) The client initiates the flow by directing the resource owner's + user-agent to the authorization endpoint. + + - (B) Assuming the resource owner grants access, the authorization + server redirects the user-agent back to the client including an + authorization code and any local state provided by the client + earlier. + + - (C) The client requests an access token from the authorization + server's token endpoint by including the authorization code + received in the previous step. + + - (D) The authorization server authenticates the client and validates + the authorization code. If valid, the authorization server responds + back with an access token and, optionally, a refresh token. + +After those steps, the client owns a `Token` that can be used to authorize any subsequent +request. + + +## Authorize + +@docs makeAuthorizationUrl, Authorization, parseCode, AuthorizationResult, AuthorizationResultWith, AuthorizationError, AuthorizationSuccess, AuthorizationCode + + +## Authenticate + +@docs makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + + +## JSON Decoders + +@docs defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + + +## Custom Decoders & Parsers (advanced) + + +### Authorize + +@docs makeAuthorizationUrlWith + + +### Authenticate + +@docs makeTokenRequestWith + + +### Json Decoders + +@docs defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + + +### Query Parsers + +@docs parseCodeWith, Parsers, defaultParsers, defaultCodeParser, defaultErrorParser, defaultAuthorizationSuccessParser, defaultAuthorizationErrorParser + +-} + +import Dict as Dict exposing (Dict) +import Http +import Json.Decode as Json +import OAuth exposing (ErrorCode, GrantType(..), ResponseType(..), Token, errorCodeFromString, grantTypeToString) +import OAuth.Internal as Internal exposing (..) +import Url exposing (Url) +import Url.Builder as Builder +import Url.Parser as Url exposing (()) +import Url.Parser.Query as Query + + + +-- +-- Authorize +-- + + +{-| Request configuration for an authorization (Authorization Code & Implicit flows) + + - `clientId` (_REQUIRED_): + The client identifier issues by the authorization server via an off-band mechanism. + + - `url` (_REQUIRED_): + The authorization endpoint to contact the authorization server. + + - `redirectUri` (_OPTIONAL_): + After completing its interaction with the resource owner, the authorization + server directs the resource owner's user-agent back to the client via this + URL. May be already defined on the authorization server itself. + + - `scope` (_OPTIONAL_): + The scope of the access request. + + - `state` (_RECOMMENDED_): + An opaque value used by the client to maintain state between the request + and callback. The authorization server includes this value when redirecting + the user-agent back to the client. The parameter SHOULD be used for preventing + cross-site request forgery. + +-} +type alias Authorization = + { clientId : String + , url : Url + , redirectUri : Url + , scope : List String + , state : Maybe String + } + + +{-| Describes an OAuth error as a result of an authorization request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer in + understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to + provide the client developer with additional information about the error. Values for the + `errorUri` parameter MUST conform to the URI-reference syntax and thus MUST NOT include + characters outside the set `%x21 / %x23-5B / %x5D-7E`. + + - `state` (_REQUIRED if `state` was present in the authorization request_): + The exact value received from the client + +-} +type alias AuthorizationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + , state : Maybe String + } + + +{-| The response obtained as a result of an authorization + + - code (_REQUIRED_): + The authorization code generated by the authorization server. The authorization code MUST expire + shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of + 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an + authorization code is used more than once, the authorization server MUST deny the request and + SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The + authorization code is bound to the client identifier and redirection URI. + + - state (_REQUIRED if `state` was present in the authorization request_): + The exact value received from the client + +-} +type alias AuthorizationSuccess = + { code : AuthorizationCode + , state : Maybe String + } + + +{-| A simple type alias to ease readability of type signatures +-} +type alias AuthorizationCode = + String + + +{-| Describes errors coming from attempting to parse a url after an OAuth redirection +-} +type alias AuthorizationResult = + AuthorizationResultWith AuthorizationError AuthorizationSuccess + + +{-| A parameterized [`AuthorizationResult`](#AuthorizationResult), see [`parseTokenWith`](#parseTokenWith). + + - `Empty`: means there were nothing (related to OAuth 2.0) to parse + - `Error`: a successfully parsed OAuth 2.0 error + - `Success`: a successfully parsed token and response + +-} +type AuthorizationResultWith error success + = Empty + | Error error + | Success success + + +{-| Redirects the resource owner (user) to the resource provider server using the specified +authorization flow. +-} +makeAuthorizationUrl : Authorization -> Url +makeAuthorizationUrl = + makeAuthorizationUrlWith Code Dict.empty + + +{-| Parse the location looking for a parameters set by the resource provider server after +redirecting the resource owner (user). + +Returns `AuthorizationResult Empty` when there's nothing + +-} +parseCode : Url -> AuthorizationResult +parseCode = + parseCodeWith defaultParsers + + + +-- +-- Authenticate +-- + + +{-| Request configuration for an AuthorizationCode authentication + + - `credentials` (_REQUIRED_): + Only the `clientId` is required. Specify a `secret` if a Basic authentication + is required by the resource provider. + + - `code` (_REQUIRED_): + Authorization code from the authorization result + + - `url` (_REQUIRED_): + Token endpoint of the resource provider + + - `redirectUri` (_REQUIRED_): + Redirect Uri to your web server used in the authorization step, provided + here for verification. + +-} +type alias Authentication = + { credentials : Credentials + , code : String + , redirectUri : Url + , url : Url + } + + +{-| The response obtained as a result of an authentication (implicit or not) + + - `token` (_REQUIRED_): + The access token issued by the authorization server. + + - `refreshToken` (_OPTIONAL_): + The refresh token, which can be used to obtain new access tokens using the same authorization + grant as described in [Section 6](https://tools.ietf.org/html/rfc6749#section-6). + + - `expiresIn` (_RECOMMENDED_): + The lifetime in seconds of the access token. For example, the value "3600" denotes that the + access token will expire in one hour from the time the response was generated. If omitted, the + authorization server SHOULD provide the expiration time via other means or document the default + value. + + - `scope` (_OPTIONAL, if identical to the scope requested; otherwise, REQUIRED_): + The scope of the access token as described by [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). + +-} +type alias AuthenticationSuccess = + { token : Token + , refreshToken : Maybe Token + , expiresIn : Maybe Int + , scope : List String + , idJwt : Maybe String + } + + +{-| Describes an OAuth error as a result of a request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer in + understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to + provide the client developer with additional information about the error. Values for the + `errorUri` parameter MUST conform to the URI-reference syntax and thus MUST NOT include + characters outside the set `%x21 / %x23-5B / %x5D-7E`. + +-} +type alias AuthenticationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + } + + +{-| Parts required to build a request. This record is given to [`Http.request`](https://package.elm-lang.org/packages/elm/http/latest/Http#request) +in order to create a new request and may be adjusted at will. +-} +type alias RequestParts a = + { method : String + , headers : List Http.Header + , url : String + , body : Http.Body + , expect : Http.Expect a + , timeout : Maybe Float + , tracker : Maybe String + } + + +{-| Describes at least a `clientId` and if define, a complete set of credentials +with the `secret`. The secret is so-to-speak optional and depends on whether the +authorization server you interact with requires a Basic authentication on top of +the authentication request. Provides it if you need to do so. + + { clientId = "" + , secret = Just "" + } + +-} +type alias Credentials = + { clientId : String + , secret : Maybe String + } + + +{-| Builds a the request components required to get a token from an authorization code + + let req : Http.Request AuthenticationSuccess + req = makeTokenRequest toMsg authentication |> Http.request + +-} +makeTokenRequest : (Result Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg +makeTokenRequest = + makeTokenRequestWith AuthorizationCode defaultAuthenticationSuccessDecoder Dict.empty + + + +-- +-- Custom Decoders & Parsers (advanced) +-- + + +{-| Like [`makeAuthorizationUrl`](#makeAuthorizationUrl), but gives you the ability to specify a +custom response type and extra fields to be set on the query. + + makeAuthorizationUrl : Authorization -> Url + makeAuthorizationUrl = + makeAuthorizationUrlWith Code Dict.empty + +For example, to interact with a service implementing `OpenID+Connect` you may require a different +token type and an extra query parameter as such: + + makeAuthorizationUrlWith + (CustomResponse "code+id_token") + (Dict.fromList [ ( "resource", "001" ) ]) + authorization + +-} +makeAuthorizationUrlWith : ResponseType -> Dict String String -> Authorization -> Url +makeAuthorizationUrlWith responseType extraFields { clientId, url, redirectUri, scope, state } = + Internal.makeAuthorizationUrl + responseType + extraFields + { clientId = clientId + , url = url + , redirectUri = redirectUri + , scope = scope + , state = state + } + + +{-| Like [`makeTokenRequest`](#makeTokenRequest), but gives you the ability to specify custom grant +type and extra fields to be set on the query. + + makeTokenRequest : (Result Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg + makeTokenRequest = + makeTokenRequestWith + AuthorizationCode + defaultAuthenticationSuccessDecoder + Dict.empty + +-} +makeTokenRequestWith : GrantType -> Json.Decoder success -> Dict String String -> (Result Http.Error success -> msg) -> Authentication -> RequestParts msg +makeTokenRequestWith grantType decoder extraFields toMsg { credentials, code, url, redirectUri } = + let + body = + [ Builder.string "grant_type" (grantTypeToString grantType) + , Builder.string "client_id" credentials.clientId + , Builder.string "client_id_secret" (credentials.secret |> Maybe.withDefault "") + , Builder.string "redirect_uri" (makeRedirectUri redirectUri) + , Builder.string "code" code + ] + |> urlAddExtraFields extraFields + |> Builder.toQuery + |> String.dropLeft 1 + + headers = + makeHeaders <| + case credentials.secret of + Nothing -> + Nothing + + Just secret -> + Just { clientId = credentials.clientId, secret = secret } + in + makeRequest decoder toMsg url headers body + + +{-| Like [`parseCode`](#parseCode), but gives you the ability to provide your own custom parsers. + + parseCode : Url -> AuthorizationResultWith AuthorizationError AuthorizationSuccess + parseCode = + parseCodeWith defaultParsers + +-} +parseCodeWith : Parsers error success -> Url -> AuthorizationResultWith error success +parseCodeWith { codeParser, errorParser, authorizationSuccessParser, authorizationErrorParser } url_ = + let + url = + { url_ | path = "/" } + in + case Url.parse (Url.top Query.map2 Tuple.pair codeParser errorParser) url of + Just ( Just code, _ ) -> + parseUrlQuery url Empty (Query.map Success <| authorizationSuccessParser code) + + Just ( _, Just error ) -> + parseUrlQuery url Empty (Query.map Error <| authorizationErrorParser error) + + _ -> + Empty + + +{-| Parsers used in the `parseCode` function. + + - `codeParser`: looks for a `code` string + - `errorParser`: looks for an `error` to build a corresponding `ErrorCode` + - `authorizationSuccessParser`: selected when the `tokenParser` succeeded to parse the remaining parts + - `authorizationErrorParser`: selected when the `errorParser` succeeded to parse the remaining parts + +-} +type alias Parsers error success = + { codeParser : Query.Parser (Maybe String) + , errorParser : Query.Parser (Maybe ErrorCode) + , authorizationSuccessParser : String -> Query.Parser success + , authorizationErrorParser : ErrorCode -> Query.Parser error + } + + +{-| Default parsers according to RFC-6749. +-} +defaultParsers : Parsers AuthorizationError AuthorizationSuccess +defaultParsers = + { codeParser = defaultCodeParser + , errorParser = defaultErrorParser + , authorizationSuccessParser = defaultAuthorizationSuccessParser + , authorizationErrorParser = defaultAuthorizationErrorParser + } + + +{-| Default `code` parser according to RFC-6749. +-} +defaultCodeParser : Query.Parser (Maybe String) +defaultCodeParser = + Query.string "code" + + +{-| Default `error` parser according to RFC-6749. +-} +defaultErrorParser : Query.Parser (Maybe ErrorCode) +defaultErrorParser = + errorParser errorCodeFromString + + +{-| Default response success parser according to RFC-6749. +-} +defaultAuthorizationSuccessParser : String -> Query.Parser AuthorizationSuccess +defaultAuthorizationSuccessParser code = + Query.map (AuthorizationSuccess code) + stateParser + + +{-| Default response error parser according to RFC-6749. +-} +defaultAuthorizationErrorParser : ErrorCode -> Query.Parser AuthorizationError +defaultAuthorizationErrorParser = + authorizationErrorParser + + +{-| Json decoder for a positive response. You may provide a custom response decoder using other decoders +from this module, or some of your own craft. + + defaultAuthenticationSuccessDecoder : Decoder AuthenticationSuccess + defaultAuthenticationSuccessDecoder = + D.map4 AuthenticationSuccess + tokenDecoder + refreshTokenDecoder + expiresInDecoder + scopeDecoder + +-} +defaultAuthenticationSuccessDecoder : Json.Decoder AuthenticationSuccess +defaultAuthenticationSuccessDecoder = + Internal.authenticationSuccessDecoder + + +{-| Json decoder for an error response. + + case res of + Err (Http.BadStatus { body }) -> + case Json.decodeString OAuth.AuthorizationCode.defaultAuthenticationErrorDecoder body of + Ok { error, errorDescription } -> + doSomething + + _ -> + parserFailed + + _ -> + someOtherError + +-} +defaultAuthenticationErrorDecoder : Json.Decoder AuthenticationError +defaultAuthenticationErrorDecoder = + Internal.authenticationErrorDecoder defaultErrorDecoder + + +{-| Json decoder for the `expiresIn` field. +-} +defaultExpiresInDecoder : Json.Decoder (Maybe Int) +defaultExpiresInDecoder = + Internal.expiresInDecoder + + +{-| Json decoder for the `scope` field (space-separated). +-} +defaultScopeDecoder : Json.Decoder (List String) +defaultScopeDecoder = + Internal.scopeDecoder + + +{-| Json decoder for the `scope` field (comma- or space-separated). +-} +lenientScopeDecoder : Json.Decoder (List String) +lenientScopeDecoder = + Internal.lenientScopeDecoder + + +{-| Json decoder for the `access_token` field. +-} +defaultTokenDecoder : Json.Decoder Token +defaultTokenDecoder = + Internal.tokenDecoder + + +{-| Json decoder for the `refresh_token` field. +-} +defaultRefreshTokenDecoder : Json.Decoder (Maybe Token) +defaultRefreshTokenDecoder = + Internal.refreshTokenDecoder + + +{-| Json decoder for the `error` field. +-} +defaultErrorDecoder : Json.Decoder ErrorCode +defaultErrorDecoder = + Internal.errorDecoder errorCodeFromString + + +{-| Json decoder for the `error_description` field. +-} +defaultErrorDescriptionDecoder : Json.Decoder (Maybe String) +defaultErrorDescriptionDecoder = + Internal.errorDescriptionDecoder + + +{-| Json decoder for the `error_uri` field. +-} +defaultErrorUriDecoder : Json.Decoder (Maybe String) +defaultErrorUriDecoder = + Internal.errorUriDecoder diff --git a/counter/auth-vendored/OAuth/AuthorizationCode/PKCE.elm b/counter/auth-vendored/OAuth/AuthorizationCode/PKCE.elm new file mode 100644 index 0000000..cd2173b --- /dev/null +++ b/counter/auth-vendored/OAuth/AuthorizationCode/PKCE.elm @@ -0,0 +1,682 @@ +module OAuth.AuthorizationCode.PKCE exposing + ( CodeVerifier(..), CodeChallenge(..), codeVerifierFromBytes, codeVerifierToString, mkCodeChallenge, codeChallengeToString + , makeAuthorizationUrl, Authorization, parseCode, AuthorizationResult, AuthorizationError, AuthorizationSuccess, AuthorizationCode + , makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + , defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + , makeAuthorizationUrlWith, AuthorizationResultWith(..) + , makeTokenRequestWith + , defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + , parseCodeWith, Parsers, defaultParsers, defaultCodeParser, defaultErrorParser, defaultAuthorizationSuccessParser, defaultAuthorizationErrorParser + ) + +{-| OAuth 2.0 public clients utilizing the Authorization Code Grant are +susceptible to the authorization code interception attack. A possible +mitigation against the threat is to use a technique called Proof Key for +Code Exchange (PKCE, pronounced "pixy") when supported by the target +authorization server. See also [RFC 7636](https://tools.ietf.org/html/rfc7636). + + +## Quick Start + +To get started, have a look at the [live-demo](https://truqu.github.io/elm-oauth2/auth0/pkce/) and its corresponding [source +code](https://github.com/truqu/elm-oauth2/blob/master/examples/providers/auth0/pkce/Main.elm) + + +## Overview + + +-----------------+ + | Auth Server | + +-------+ | +-------------+ | + | |--(1)- Auth Request --->| | | | + | | + code_challenge | | Auth | | + | | | | Endpoint | | + | |<-(2)-- Auth Code ------| | | | + | Elm | | +-------------+ | + | App | | | + | | | +-------------+ | + | |--(3)- Token Request -->| | | | + | | + code_verifier | | Token | | + | | | | Endpoint | | + | |<-(4)- Access Token --->| | | | + +-------+ | +-------------+ | + +-----------------+ + +See also the Authorization Code flow for details about the basic version +of this flow. + + +## Code Verifier / Challenge + +@docs CodeVerifier, CodeChallenge, codeVerifierFromBytes, codeVerifierToString, mkCodeChallenge, codeChallengeToString + + +## Authorize + +@docs makeAuthorizationUrl, Authorization, parseCode, AuthorizationResult, AuthorizationError, AuthorizationSuccess, AuthorizationCode + + +## Authenticate + +@docs makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + + +## JSON Decoders + +@docs defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + + +## Custom Decoders & Parsers (advanced) + + +### Authorize + +@docs makeAuthorizationUrlWith, AuthorizationResultWith + + +### Authenticate + +@docs makeTokenRequestWith + + +### Json Decoders + +@docs defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + + +### Query Parsers + +@docs parseCodeWith, Parsers, defaultParsers, defaultCodeParser, defaultErrorParser, defaultAuthorizationSuccessParser, defaultAuthorizationErrorParser + +-} + +import Base64.Encode as Base64 +import Bytes exposing (Bytes) +import Dict as Dict exposing (Dict) +import Effect.Http +import Internal as Internal exposing (..) +import Json.Decode as Json +import OAuth exposing (ErrorCode, GrantType(..), ResponseType(..), Token, errorCodeFromString) +import OAuth.AuthorizationCode +import SHA256 as SHA256 +import Url exposing (Url) +import Url.Builder as Builder +import Url.Parser as Url exposing (()) +import Url.Parser.Query as Query + + + +-- +-- Code Challenge / Code Verifier +-- + + +{-| An opaque type representing a code verifier. Typically constructed from a high quality entropy. + + case codeVerifierFromBytes entropy of + Nothing -> {- ...-} + Just codeVerifier -> {- ... -} + +-} +type CodeVerifier + = CodeVerifier Base64.Encoder + + +{-| An opaque type representing a code challenge. Typically constructed from a `CodeVerifier`. + + let codeChallenge = mkCodeChallenge codeVerifier + +-} +type CodeChallenge + = CodeChallenge Base64.Encoder + + +{-| Construct a code verifier from a byte sequence generated from a **high quality randomness** source (i.e. cryptographic). + +Ideally, the byte sequence _should be_ 32 or 64 bytes, and it _must be_ at least 32 bytes and at most 90 bytes. + +-} +codeVerifierFromBytes : Bytes -> Maybe CodeVerifier +codeVerifierFromBytes bytes = + if Bytes.width bytes < 32 || Bytes.width bytes > 90 then + Nothing + + else + bytes |> Base64.bytes |> CodeVerifier |> Just + + +{-| Convert a code verifier to its string representation. +-} +codeVerifierToString : CodeVerifier -> String +codeVerifierToString (CodeVerifier str) = + base64UrlEncode str + + +{-| Construct a `CodeChallenge` to send to the authorization server. Upon receiving the authorization code, the client can then +the associated `CodeVerifier` to prove it is the rightful owner of the authorization code. +-} +mkCodeChallenge : CodeVerifier -> CodeChallenge +mkCodeChallenge = + codeVerifierToString >> SHA256.fromString >> SHA256.toBytes >> Base64.bytes >> CodeChallenge + + +{-| Convert a code challenge to its string representation. +-} +codeChallengeToString : CodeChallenge -> String +codeChallengeToString (CodeChallenge str) = + base64UrlEncode str + + +{-| Internal function implementing Base64-URL encoding (i.e. base64 without padding and some unsuitable characters replaced) +-} +base64UrlEncode : Base64.Encoder -> String +base64UrlEncode = + Base64.encode + >> String.replace "=" "" + >> String.replace "+" "-" + >> String.replace "/" "_" + + + +-- +-- Authorize +-- + + +{-| Request configuration for an authorization (Authorization Code & Implicit flows) + + - `clientId` (_REQUIRED_): + The client identifier issues by the authorization server via an off-band mechanism. + + - `url` (_REQUIRED_): + The authorization endpoint to contact the authorization server. + + - `redirectUri` (_OPTIONAL_): + After completing its interaction with the resource owner, the authorization + server directs the resource owner's user-agent back to the client via this + URL. May be already defined on the authorization server itself. + + - `scope` (_OPTIONAL_): + The scope of the access request. + + - `state` (_RECOMMENDED_): + An opaque value used by the client to maintain state between the request + and callback. The authorization server includes this value when redirecting + the user-agent back to the client. The parameter SHOULD be used for preventing + cross-site request forgery. + + - `codeChallenge` (_REQUIRED_): + A challenge derived from the code verifier that is sent in the + authorization request, to be verified against later. + +-} +type alias Authorization = + { clientId : String + , url : Url + , redirectUri : Url + , scope : List String + , state : Maybe String + , codeChallenge : CodeChallenge + } + + +{-| Describes an OAuth error as a result of an authorization request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer in + understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to + provide the client developer with additional information about the error. Values for the + `errorUri` parameter MUST conform to the URI-reference syntax and thus MUST NOT include + characters outside the set `%x21 / %x23-5B / %x5D-7E`. + + - `state` (_REQUIRED if `state` was present in the authorization request_): + The exact value received from the client + +-} +type alias AuthorizationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + , state : Maybe String + } + + +{-| The response obtained as a result of an authorization + + - `code` (_REQUIRED_): + The authorization code generated by the authorization server. The authorization code MUST expire + shortly after it is issued to mitigate the risk of leaks. A maximum authorization code lifetime of + 10 minutes is RECOMMENDED. The client MUST NOT use the authorization code more than once. If an + authorization code is used more than once, the authorization server MUST deny the request and + SHOULD revoke (when possible) all tokens previously issued based on that authorization code. The + authorization code is bound to the client identifier and redirection URI. + + - `state` (_REQUIRED if `state` was present in the authorization request_): + The exact value received from the client + +-} +type alias AuthorizationSuccess = + { code : String + , state : Maybe String + } + + +{-| Describes errors coming from attempting to parse a url after an OAuth redirection +-} +type alias AuthorizationResult = + AuthorizationResultWith AuthorizationError AuthorizationSuccess + + +{-| A parameterized [`AuthorizationResult`](#AuthorizationResult), see [`parseTokenWith`](#parseTokenWith). + + - `Empty`: means there were nothing (related to OAuth 2.0) to parse + - `Error`: a successfully parsed OAuth 2.0 error + - `Success`: a successfully parsed token and response + +-} +type AuthorizationResultWith error success + = Empty + | Error error + | Success success + + +{-| Redirects the resource owner (user) to the resource provider server using the specified +authorization flow. +-} +makeAuthorizationUrl : Authorization -> Url +makeAuthorizationUrl = + makeAuthorizationUrlWith Code Dict.empty + + +{-| Parse the location looking for a parameters set by the resource provider server after +redirecting the resource owner (user). + +Returns `AuthorizationResult Empty` when there's nothing. + +-} +parseCode : Url -> AuthorizationResult +parseCode = + parseCodeWith defaultParsers + + + +-- +-- Authenticate +-- + + +{-| Request configuration for an AuthorizationCode authentication + + - `credentials` (_REQUIRED_): + Only the clientId is required. Specify a secret if a Basic OAuth + is required by the resource provider. + + - `code` (_REQUIRED_): + Authorization code from the authorization result + + - `codeVerifier` (_REQUIRED_): + The code verifier proving you are the rightful recipient of the + access token. + + - `url` (_REQUIRED_): + Token endpoint of the resource provider + + - `redirectUri` (_REQUIRED_): + Redirect Uri to your webserver used in the authorization step, provided + here for verification. + +-} +type alias Authentication = + { credentials : Credentials + , code : String + , codeVerifier : CodeVerifier + , redirectUri : Url + , url : Url + } + + +{-| The response obtained as a result of an authentication (implicit or not) + + - `token` (_REQUIRED_): + The access token issued by the authorization server. + + - `refreshToken` (_OPTIONAL_): + The refresh token, which can be used to obtain new access tokens using the same authorization + grant as described in [Section 6](https://tools.ietf.org/html/rfc6749#section-6). + + - `expiresIn` (_RECOMMENDED_): + The lifetime in seconds of the access token. For example, the value "3600" denotes that the + access token will expire in one hour from the time the response was generated. If omitted, the + authorization server SHOULD provide the expiration time via other means or document the default + value. + + - `scope` (_OPTIONAL, if identical to the scope requested; otherwise, REQUIRED_): + The scope of the access token as described by [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). + +-} +type alias AuthenticationSuccess = + { token : Token + , refreshToken : Maybe Token + , expiresIn : Maybe Int + , scope : List String + } + + +{-| A simple type alias to ease readability of type signatures +-} +type alias AuthorizationCode = + String + + +{-| Describes an OAuth error as a result of a request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer in + understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to + provide the client developer with additional information about the error. Values for the + `errorUri` parameter MUST conform to the URI-reference syntax and thus MUST NOT include + characters outside the set `%x21 / %x23-5B / %x5D-7E`. + +-} +type alias AuthenticationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + } + + +{-| Parts required to build a request. This record is given to [`Http.request`](https://package.elm-lang.org/packages/elm/http/latest/Http#request) +in order to create a new request and may be adjusted at will. +-} +type alias RequestParts a = + { method : String + , headers : List Effect.Http.Header + , url : String + , body : Effect.Http.Body + , expect : Effect.Http.Expect a + , timeout : Maybe Float + , tracker : Maybe String + } + + +{-| Describes at least a `clientId` and if define, a complete set of credentials +with the `secret`. The secret is so-to-speak optional and depends on whether the +authorization server you interact with requires a Basic authentication on top of +the authentication request. Provides it if you need to do so. + + { clientId = "" + , secret = Just "" + } + +-} +type alias Credentials = + { clientId : String + , secret : Maybe String + } + + +{-| Builds a the request components required to get a token from an authorization code + + let req : Http.Request AuthenticationSuccess + req = makeTokenRequest toMsg authentication |> Http.request + +-} +makeTokenRequest : (Result Effect.Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg +makeTokenRequest = + makeTokenRequestWith AuthorizationCode defaultAuthenticationSuccessDecoder Dict.empty + + + +-- +-- Json Decoders +-- + + +{-| Json decoder for a positive response. You may provide a custom response decoder using other decoders +from this module, or some of your own craft. + + defaultAuthenticationSuccessDecoder : Decoder AuthenticationSuccess + defaultAuthenticationSuccessDecoder = + D.map4 AuthenticationSuccess + tokenDecoder + refreshTokenDecoder + expiresInDecoder + scopeDecoder + +-} +defaultAuthenticationSuccessDecoder : Json.Decoder AuthenticationSuccess +defaultAuthenticationSuccessDecoder = + Internal.authenticationSuccessDecoder + + +{-| Json decoder for an errored response. + + case res of + Err (Http.BadStatus { body }) -> + case Json.decodeString OAuth.AuthorizationCode.defaultAuthenticationErrorDecoder body of + Ok { error, errorDescription } -> + doSomething + + _ -> + parserFailed + + _ -> + someOtherError + +-} +defaultAuthenticationErrorDecoder : Json.Decoder AuthenticationError +defaultAuthenticationErrorDecoder = + Internal.authenticationErrorDecoder defaultErrorDecoder + + + +-- +-- Custom Decoders & Parsers (advanced) +-- + + +{-| Like [`makeAuthorizationUrl`](#makeAuthorizationUrl), but gives you the ability to specify a custom response type +and extra fields to be set on the query. + + makeAuthorizationUrl : Authorization -> Url + makeAuthorizationUrl = + makeAuthorizationUrlWith Code Dict.empty + +For example, to interact with a service implementing `OpenID+Connect` you may require a different +token type and an extra query parameter as such: + + makeAuthorizationUrlWith + (CustomResponse "code+id_token") + (Dict.fromList [ ( "resource", "001" ) ]) + authorization + +-} +makeAuthorizationUrlWith : ResponseType -> Dict String String -> Authorization -> Url +makeAuthorizationUrlWith responseType extraFields { clientId, url, redirectUri, scope, state, codeChallenge } = + let + extraInternalFields = + Dict.fromList + [ ( "code_challenge", codeChallengeToString codeChallenge ) + , ( "code_challenge_method", "S256" ) + ] + in + OAuth.AuthorizationCode.makeAuthorizationUrlWith + responseType + (Dict.union extraFields extraInternalFields) + { clientId = clientId + , url = url + , redirectUri = redirectUri + , scope = scope + , state = state + } + + +{-| See [`parseCode`](#parseCode), but gives you the ability to provide your own custom parsers. +-} +parseCodeWith : Parsers error success -> Url -> AuthorizationResultWith error success +parseCodeWith parsers url = + case OAuth.AuthorizationCode.parseCodeWith parsers url of + OAuth.AuthorizationCode.Empty -> + Empty + + OAuth.AuthorizationCode.Success s -> + Success s + + OAuth.AuthorizationCode.Error e -> + Error e + + +{-| Like [`makeTokenRequest`](#makeTokenRequest), but gives you the ability to specify custom grant type and extra +fields to be set on the query. + + makeTokenRequest : (Result Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg + makeTokenRequest = + makeTokenRequestWith + AuthorizationCode + defaultAuthenticationSuccessDecoder + Dict.empty + +-} +makeTokenRequestWith : GrantType -> Json.Decoder success -> Dict String String -> (Result Effect.Http.Error success -> msg) -> Authentication -> RequestParts msg +makeTokenRequestWith grantType decoder extraFields toMsg { credentials, code, codeVerifier, url, redirectUri } = + let + extraInternalFields = + Dict.fromList + [ ( "code_verifier", codeVerifierToString codeVerifier ) + ] + in + OAuth.AuthorizationCode.makeTokenRequestWith + grantType + decoder + (Dict.union extraFields extraInternalFields) + toMsg + { credentials = credentials + , code = code + , url = url + , redirectUri = redirectUri + } + + +{-| Parsers used in the [`parseCode`](#parseCode) function. + + - `codeParser`: looks for a `code` string + - `errorParser`: looks for an `error` to build a corresponding `ErrorCode` + - `authorizationSuccessParser`: selected when the `tokenParser` succeeded to parse the remaining parts + - `authorizationErrorParser`: selected when the `errorParser` succeeded to parse the remaining parts + +-} +type alias Parsers error success = + { codeParser : Query.Parser (Maybe String) + , errorParser : Query.Parser (Maybe ErrorCode) + , authorizationSuccessParser : String -> Query.Parser success + , authorizationErrorParser : ErrorCode -> Query.Parser error + } + + +{-| Default parsers according to RFC-6749. +-} +defaultParsers : Parsers AuthorizationError AuthorizationSuccess +defaultParsers = + { codeParser = defaultCodeParser + , errorParser = defaultErrorParser + , authorizationSuccessParser = defaultAuthorizationSuccessParser + , authorizationErrorParser = defaultAuthorizationErrorParser + } + + +{-| Default `code` parser according to RFC-6749. +-} +defaultCodeParser : Query.Parser (Maybe String) +defaultCodeParser = + Query.string "code" + + +{-| Default `error` parser according to RFC-6749. +-} +defaultErrorParser : Query.Parser (Maybe ErrorCode) +defaultErrorParser = + errorParser errorCodeFromString + + +{-| Default response success parser according to RFC-6749. +-} +defaultAuthorizationSuccessParser : String -> Query.Parser AuthorizationSuccess +defaultAuthorizationSuccessParser code = + Query.map (AuthorizationSuccess code) + stateParser + + +{-| Default response error parser according to RFC-6749. +-} +defaultAuthorizationErrorParser : ErrorCode -> Query.Parser AuthorizationError +defaultAuthorizationErrorParser = + authorizationErrorParser + + +{-| Json decoder for the `expiresIn` field. +-} +defaultExpiresInDecoder : Json.Decoder (Maybe Int) +defaultExpiresInDecoder = + Internal.expiresInDecoder + + +{-| Json decoder for the `scope` field (space-separated). +-} +defaultScopeDecoder : Json.Decoder (List String) +defaultScopeDecoder = + Internal.scopeDecoder + + +{-| Json decoder for the `scope` (comma- or space-separated). +-} +lenientScopeDecoder : Json.Decoder (List String) +lenientScopeDecoder = + Internal.lenientScopeDecoder + + +{-| Json decoder for the `access_token` field. +-} +defaultTokenDecoder : Json.Decoder Token +defaultTokenDecoder = + Internal.tokenDecoder + + +{-| Json decoder for the `refresh_token` field. +-} +defaultRefreshTokenDecoder : Json.Decoder (Maybe Token) +defaultRefreshTokenDecoder = + Internal.refreshTokenDecoder + + +{-| Json decoder for the `error` field. +-} +defaultErrorDecoder : Json.Decoder ErrorCode +defaultErrorDecoder = + Internal.errorDecoder errorCodeFromString + + +{-| Json decoder for the `error_description` field. +-} +defaultErrorDescriptionDecoder : Json.Decoder (Maybe String) +defaultErrorDescriptionDecoder = + Internal.errorDescriptionDecoder + + +{-| Json decoder for the `error_uri` field. +-} +defaultErrorUriDecoder : Json.Decoder (Maybe String) +defaultErrorUriDecoder = + Internal.errorUriDecoder diff --git a/counter/auth-vendored/OAuth/ClientCredentials.elm b/counter/auth-vendored/OAuth/ClientCredentials.elm new file mode 100644 index 0000000..baa75f3 --- /dev/null +++ b/counter/auth-vendored/OAuth/ClientCredentials.elm @@ -0,0 +1,288 @@ +module OAuth.ClientCredentials exposing + ( makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + , defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + , makeTokenRequestWith, defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + ) + +{-| The client can request an access token using only its client +credentials (or other supported means of authentication) when the client is requesting access to +the protected resources under its control, or those of another resource owner that have been +previously arranged with the authorization server (the method of which is beyond the scope of +this specification). + +There's only one step in this process: + + - The client authenticates itself directly using credentials it owns. + +After this step, the client owns a `Token` that can be used to authorize any subsequent +request. + + +## Authenticate + +@docs makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + + +## JSON Decoders + +@docs defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + + +## Custom Decoders & Parsers (advanced) + +@docs makeTokenRequestWith, defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + +-} + +import Dict as Dict exposing (Dict) +import Effect.Http +import Internal as Internal exposing (..) +import Json.Decode as Json +import OAuth exposing (ErrorCode(..), GrantType(..), Token, errorCodeFromString, grantTypeToString) +import Url exposing (Url) +import Url.Builder as Builder + + + +-- +-- Authenticate +-- + + +{-| Request configuration for a ClientCredentials authentication + + - `credentials` (_REQUIRED_): + Credentials needed for Basic authentication. + + - `url` (_REQUIRED_): + The token endpoint to contact the authorization server. + + - `scope` (_OPTIONAL_): + The scope of the access request. + +-} +type alias Authentication = + { credentials : Credentials + , url : Url + , scope : List String + } + + +{-| Describes a couple of client credentials used for Basic authentication + + { clientId = "" + , secret = "" + } + +-} +type alias Credentials = + { clientId : String, secret : String } + + +{-| The response obtained as a result of an authentication (implicit or not) + + - `token` (_REQUIRED_): + The access token issued by the authorization server. + + - `refreshToken` (_OPTIONAL_): + The refresh token, which can be used to obtain new access tokens using the same authorization + grant as described in [Section 6](https://tools.ietf.org/html/rfc6749#section-6). + + - `expiresIn` (_RECOMMENDED_): + The lifetime in seconds of the access token. For example, the value "3600" denotes that the + access token will expire in one hour from the time the response was generated. If omitted, the + authorization server SHOULD provide the expiration time via other means or document the default + value. + + - `scope` (_OPTIONAL, if identical to the scope requested; otherwise, REQUIRED_): + The scope of the access token as described by [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). + +-} +type alias AuthenticationSuccess = + { token : Token + , refreshToken : Maybe Token + , expiresIn : Maybe Int + , scope : List String + } + + +{-| Describes an OAuth error as a result of a request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer + in understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to provide + the client developer with additional information about the error. Values for the `errorUri` + parameter MUST conform to the URI-reference syntax and thus MUST NOT include characters outside + the set `%x21 / %x23-5B / %x5D-7E`. + +-} +type alias AuthenticationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + } + + +{-| Parts required to build a request. This record is given to [`Http.request`](https://package.elm-lang.org/packages/elm/http/latest/Http#request) +in order to create a new request and may be adjusted at will. +-} +type alias RequestParts a = + { method : String + , headers : List Effect.Http.Header + , url : String + , body : Effect.Http.Body + , expect : Effect.Http.Expect a + , timeout : Maybe Float + , tracker : Maybe String + } + + +{-| Builds a the request components required to get a token from client credentials + + let req : Http.Request TokenResponse + req = makeTokenRequest toMsg authentication |> Http.request + +-} +makeTokenRequest : (Result Effect.Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg +makeTokenRequest = + makeTokenRequestWith ClientCredentials defaultAuthenticationSuccessDecoder Dict.empty + + + +-- +-- Json Decoders +-- + + +{-| Json decoder for a positive response. You may provide a custom response decoder using other decoders +from this module, or some of your own craft. + + defaultAuthenticationSuccessDecoder : Decoder AuthenticationSuccess + defaultAuthenticationSuccessDecoder = + D.map4 AuthenticationSuccess + tokenDecoder + refreshTokenDecoder + expiresInDecoder + scopeDecoder + +-} +defaultAuthenticationSuccessDecoder : Json.Decoder AuthenticationSuccess +defaultAuthenticationSuccessDecoder = + Internal.authenticationSuccessDecoder + + +{-| Json decoder for an errored response. + + case res of + Err (Http.BadStatus { body }) -> + case Json.decodeString OAuth.ClientCredentials.defaultAuthenticationErrorDecoder body of + Ok { error, errorDescription } -> + doSomething + + _ -> + parserFailed + + _ -> + someOtherError + +-} +defaultAuthenticationErrorDecoder : Json.Decoder AuthenticationError +defaultAuthenticationErrorDecoder = + Internal.authenticationErrorDecoder defaultErrorDecoder + + + +-- +-- Custom Decoders & Parsers (advanced) +-- + + +{-| Like [`makeTokenRequest`](#makeTokenRequest), but gives you the ability to specify custom grant +type and extra fields to be set on the query. + + makeTokenRequest : (Result Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg + makeTokenRequest = + makeTokenRequestWith ClientCredentials defaultAuthenticationSuccessDecoder Dict.empty + +-} +makeTokenRequestWith : GrantType -> Json.Decoder success -> Dict String String -> (Result Effect.Http.Error success -> msg) -> Authentication -> RequestParts msg +makeTokenRequestWith grantType decoder extraFields toMsg { credentials, scope, url } = + let + body = + [ Builder.string "grant_type" (grantTypeToString grantType) ] + |> urlAddList "scope" scope + |> urlAddExtraFields extraFields + |> Builder.toQuery + |> String.dropLeft 1 + + headers = + makeHeaders <| + Just + { clientId = credentials.clientId + , secret = credentials.secret + } + in + makeRequest decoder toMsg url headers body + + +{-| Json decoder for the `expiresIn` field. +-} +defaultExpiresInDecoder : Json.Decoder (Maybe Int) +defaultExpiresInDecoder = + Internal.expiresInDecoder + + +{-| Json decoder for the `scope` field (space-separated). +-} +defaultScopeDecoder : Json.Decoder (List String) +defaultScopeDecoder = + Internal.scopeDecoder + + +{-| Json decoder for the `scope` field (comma- or space-separated). +-} +lenientScopeDecoder : Json.Decoder (List String) +lenientScopeDecoder = + Internal.lenientScopeDecoder + + +{-| Json decoder for the `access_token` field. +-} +defaultTokenDecoder : Json.Decoder Token +defaultTokenDecoder = + Internal.tokenDecoder + + +{-| Json decoder for the `refresh_token` field. +-} +defaultRefreshTokenDecoder : Json.Decoder (Maybe Token) +defaultRefreshTokenDecoder = + Internal.refreshTokenDecoder + + +{-| Json decoder for the `error` field. +-} +defaultErrorDecoder : Json.Decoder ErrorCode +defaultErrorDecoder = + Internal.errorDecoder errorCodeFromString + + +{-| Json decoder for the `error_description` field. +-} +defaultErrorDescriptionDecoder : Json.Decoder (Maybe String) +defaultErrorDescriptionDecoder = + Internal.errorDescriptionDecoder + + +{-| Json decoder for the `error_uri` field. +-} +defaultErrorUriDecoder : Json.Decoder (Maybe String) +defaultErrorUriDecoder = + Internal.errorUriDecoder diff --git a/counter/auth-vendored/OAuth/Implicit.elm b/counter/auth-vendored/OAuth/Implicit.elm new file mode 100644 index 0000000..d777399 --- /dev/null +++ b/counter/auth-vendored/OAuth/Implicit.elm @@ -0,0 +1,317 @@ +module OAuth.Implicit exposing + ( makeAuthorizationUrl, Authorization, parseToken, AuthorizationResult, AuthorizationResultWith(..), AuthorizationError, AuthorizationSuccess + , makeAuthorizationUrlWith, parseTokenWith, Parsers, defaultParsers, defaultTokenParser, defaultErrorParser, defaultAuthorizationSuccessParser, defaultAuthorizationErrorParser + ) + +{-| **⚠ (DEPRECATED) ⚠ You should probably look into [OAuth.AuthorizationCode](http://package.elm-lang.org/packages/truqu/elm-oauth2/latest/OAuth-AuthorizationCode) instead.** + +The implicit grant type is used to obtain access tokens (it does not +support the issuance of refresh tokens) and is optimized for public clients known to operate a +particular redirection URI. These clients are typically implemented in a browser using a +scripting language such as JavaScript. + + +## Quick Start + +To get started, have a look at the [live-demo](https://truqu.github.io/elm-oauth2/auth0/implicit/) and its +corresponding [source +code](https://github.com/truqu/elm-oauth2/blob/master/examples/providers/auth0/implicit/Main.elm). + + +## Overview + + +---------+ +--------+ + | |---(A)- Auth Redirection ------>| | + | | | Auth | + | Browser | | Server | + | | | | + | |<--(B)- Redirection Callback ---| | + +---------+ w/ Access Token +--------+ + ^ | + | | + (A) (B) + | | + | v + +---------+ + | | + | Elm App | + | | + | | + +---------+ + +After those steps, the client owns a `Token` that can be used to authorize any subsequent +request. + + +## Authorize + +@docs makeAuthorizationUrl, Authorization, parseToken, AuthorizationResult, AuthorizationResultWith, AuthorizationError, AuthorizationSuccess + + +## Custom Parsers (advanced) + +@docs makeAuthorizationUrlWith, parseTokenWith, Parsers, defaultParsers, defaultTokenParser, defaultErrorParser, defaultAuthorizationSuccessParser, defaultAuthorizationErrorParser + +-} + +import Dict as Dict exposing (Dict) +import Internal exposing (..) +import OAuth exposing (ErrorCode(..), ResponseType(..), Token, errorCodeFromString) +import Url exposing (Protocol(..), Url) +import Url.Parser as Url exposing (()) +import Url.Parser.Query as Query + + + +-- +-- Authorize +-- + + +{-| Request configuration for an authorization + + - `clientId` (_REQUIRED_): + The client identifier issues by the authorization server via an off-band mechanism. + + - `url` (_REQUIRED_): + The authorization endpoint to contact the authorization server. + + - `redirectUri` (_OPTIONAL_): + After completing its interaction with the resource owner, the authorization + server directs the resource owner's user-agent back to the client via this + URL. May be already defined on the authorization server itself. + + - `scope` (_OPTIONAL_): + The scope of the access request. + + - `state` (_RECOMMENDED_): + An opaque value used by the client to maintain state between the request + and callback. The authorization server includes this value when redirecting + the user-agent back to the client. The parameter SHOULD be used for preventing + cross-site request forgery. + +-} +type alias Authorization = + { clientId : String + , url : Url + , redirectUri : Url + , scope : List String + , state : Maybe String + } + + +{-| Describes an OAuth error as a result of an authorization request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer in + understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to + provide the client developer with additional information about the error. Values for the + `errorUri` parameter MUST conform to the URI-reference syntax and thus MUST NOT include + characters outside the set `%x21 / %x23-5B / %x5D-7E`. + + - `state` (_REQUIRED if `state` was present in the authorization request_): + The exact value received from the client + +-} +type alias AuthorizationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + , state : Maybe String + } + + +{-| The response obtained as a result of an authentication (implicit or not) + + - `token` (_REQUIRED_): + The access token issued by the authorization server. + + - `refreshToken` (_OPTIONAL_): + The refresh token, which can be used to obtain new access tokens using the same authorization + grant as described in [Section 6](https://tools.ietf.org/html/rfc6749#section-6). + + - `expiresIn` (_RECOMMENDED_): + The lifetime in seconds of the access token. For example, the value "3600" denotes that the + access token will expire in one hour from the time the response was generated. If omitted, the + authorization server SHOULD provide the expiration time via other means or document the default + value. + + - `scope` (_OPTIONAL, if identical to the scope requested; otherwise, REQUIRED_): + The scope of the access token as described by [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). + + - `state` (_REQUIRED if `state` was present in the authorization request_): + The exact value received from the client + +-} +type alias AuthorizationSuccess = + { token : Token + , refreshToken : Maybe Token + , expiresIn : Maybe Int + , scope : List String + , state : Maybe String + } + + +{-| Describes errors coming from attempting to parse a url after an OAuth redirection. +-} +type alias AuthorizationResult = + AuthorizationResultWith AuthorizationError AuthorizationSuccess + + +{-| A parameterized [`AuthorizationResult`](#AuthorizationResult), see [`parseTokenWith`](#parseTokenWith). + + - `Empty`: means there were nothing (related to OAuth 2.0) to parse + - `Error`: a successfully parsed OAuth 2.0 error + - `Success`: a successfully parsed token and response + +-} +type AuthorizationResultWith error success + = Empty + | Error error + | Success success + + +{-| Redirects the resource owner (user) to the resource provider server using the specified +authorization flow. +-} +makeAuthorizationUrl : Authorization -> Url +makeAuthorizationUrl = + makeAuthorizationUrlWith Token Dict.empty + + +{-| Parses the location looking for parameters in the fragment set by the +authorization server after redirecting the resource owner (user). + +Returns `ParseResult Empty` when there's nothing or an invalid Url is passed + +-} +parseToken : Url -> AuthorizationResult +parseToken = + parseTokenWith defaultParsers + + + +-- +-- Custom Parsers (Advanced) +-- + + +{-| Like [`makeAuthorizationUrl`](#makeAuthorizationUrl), but gives you the ability to specify a +custom response type and extra fields to be set on the query. + + makeAuthorizationUrl : Authorization -> Url + makeAuthorizationUrl = + makeAuthorizationUrlWith Token Dict.empty + +For example, to interact with a service implementing `OpenID+Connect` you may require a different +token type and an extra query parameter as such: + + makeAuthorizationUrlWith + (CustomResponse "token+id_token") + (Dict.fromList [ ( "resource", "001" ) ]) + authorization + +-} +makeAuthorizationUrlWith : ResponseType -> Dict String String -> Authorization -> Url +makeAuthorizationUrlWith responseType extraFields { clientId, url, redirectUri, scope, state } = + Internal.makeAuthorizationUrl + responseType + extraFields + { clientId = clientId + , url = url + , redirectUri = redirectUri + , scope = scope + , state = state + } + + +{-| Like [`parseToken`](#parseToken), but gives you the ability to provide your own custom parsers. + +This is especially useful when interacting with authorization servers that don't quite +implement the OAuth2.0 specifications. + + parseToken : Url -> AuthorizationResultWith AuthorizationError AuthorizationSuccess + parseToken = + parseTokenWith defaultParsers + +-} +parseTokenWith : Parsers error success -> Url -> AuthorizationResultWith error success +parseTokenWith { tokenParser, errorParser, authorizationSuccessParser, authorizationErrorParser } url_ = + let + url = + { url_ | path = "/", query = url_.fragment, fragment = Nothing } + in + case Url.parse (Url.top Query.map2 Tuple.pair tokenParser errorParser) url of + Just ( Just accessToken, _ ) -> + parseUrlQuery url Empty (Query.map Success <| authorizationSuccessParser accessToken) + + Just ( _, Just error ) -> + parseUrlQuery url Empty (Query.map Error <| authorizationErrorParser error) + + _ -> + Empty + + +{-| Parsers used in the [`parseToken`](#parseToken) function. + + - `tokenParser`: Looks for an `access_token` and `token_type` to build a `Token` + - `errorParser`: Looks for an `error` to build a corresponding `ErrorCode` + - `authorizationSuccessParser`: Selected when the `tokenParser` succeeded to parse the remaining parts + - `authorizationErrorParser`: Selected when the `errorParser` succeeded to parse the remaining parts + +-} +type alias Parsers error success = + { tokenParser : Query.Parser (Maybe Token) + , errorParser : Query.Parser (Maybe ErrorCode) + , authorizationSuccessParser : Token -> Query.Parser success + , authorizationErrorParser : ErrorCode -> Query.Parser error + } + + +{-| Default parsers according to RFC-6749. +-} +defaultParsers : Parsers AuthorizationError AuthorizationSuccess +defaultParsers = + { tokenParser = defaultTokenParser + , errorParser = defaultErrorParser + , authorizationSuccessParser = defaultAuthorizationSuccessParser + , authorizationErrorParser = defaultAuthorizationErrorParser + } + + +{-| Default `access_token` parser according to RFC-6749. +-} +defaultTokenParser : Query.Parser (Maybe Token) +defaultTokenParser = + tokenParser + + +{-| Default `error` parser according to RFC-6749. +-} +defaultErrorParser : Query.Parser (Maybe ErrorCode) +defaultErrorParser = + errorParser errorCodeFromString + + +{-| Default response success parser according to RFC-6749. +-} +defaultAuthorizationSuccessParser : Token -> Query.Parser AuthorizationSuccess +defaultAuthorizationSuccessParser accessToken = + Query.map3 (AuthorizationSuccess accessToken Nothing) + expiresInParser + scopeParser + stateParser + + +{-| Default response error parser according to RFC-6749. +-} +defaultAuthorizationErrorParser : ErrorCode -> Query.Parser AuthorizationError +defaultAuthorizationErrorParser = + authorizationErrorParser diff --git a/counter/auth-vendored/OAuth/Internal.elm b/counter/auth-vendored/OAuth/Internal.elm new file mode 100644 index 0000000..590fd21 --- /dev/null +++ b/counter/auth-vendored/OAuth/Internal.elm @@ -0,0 +1,413 @@ +module OAuth.Internal exposing + ( AuthenticationError + , AuthenticationSuccess + , Authorization + , AuthorizationError + , RequestParts + , authenticationErrorDecoder + , authenticationSuccessDecoder + , authorizationErrorParser + , decoderFromJust + , decoderFromResult + , errorDecoder + , errorDescriptionDecoder + , errorDescriptionParser + , errorParser + , errorUriDecoder + , errorUriParser + , expiresInDecoder + , expiresInParser + , extractTokenString + , lenientScopeDecoder + , makeAuthorizationUrl + , makeHeaders + , makeRedirectUri + , makeRequest + , parseUrlQuery + , protocolToString + , refreshTokenDecoder + , scopeDecoder + , scopeParser + , spaceSeparatedListParser + , stateParser + , tokenDecoder + , tokenParser + , urlAddExtraFields + , urlAddList + , urlAddMaybe + ) + +import Base64.Encode as Base64 +import Dict as Dict exposing (Dict) +import Http +import Json.Decode as Json +import OAuth exposing (..) +import Url exposing (Protocol(..), Url) +import Url.Builder as Builder exposing (QueryParameter) +import Url.Parser as Url +import Url.Parser.Query as Query + + + +-- +-- Json Decoders +-- + + +{-| Json decoder for a response. You may provide a custom response decoder using other decoders +from this module, or some of your own craft. +-} +authenticationSuccessDecoder : Json.Decoder AuthenticationSuccess +authenticationSuccessDecoder = + Json.map5 AuthenticationSuccess + tokenDecoder + refreshTokenDecoder + expiresInDecoder + scopeDecoder + idJwtDecoder + + +authenticationErrorDecoder : Json.Decoder e -> Json.Decoder (AuthenticationError e) +authenticationErrorDecoder errorCodeDecoder = + Json.map3 AuthenticationError + errorCodeDecoder + errorDescriptionDecoder + errorUriDecoder + + +{-| Json decoder for an expire timestamp +-} +expiresInDecoder : Json.Decoder (Maybe Int) +expiresInDecoder = + Json.maybe <| Json.field "expires_in" Json.int + + +{-| Json decoder for a scope +-} +scopeDecoder : Json.Decoder (List String) +scopeDecoder = + Json.map (Maybe.withDefault []) <| Json.maybe <| Json.field "scope" (Json.list Json.string) + + +{-| ID JWT decoder +-} +idJwtDecoder : Json.Decoder (Maybe String) +idJwtDecoder = + Json.maybe <| Json.field "id_token" Json.string + + +{-| Json decoder for a scope, allowing comma- or space-separated scopes +-} +lenientScopeDecoder : Json.Decoder (List String) +lenientScopeDecoder = + Json.map (Maybe.withDefault []) <| + Json.maybe <| + Json.field "scope" <| + Json.oneOf + [ Json.list Json.string + , Json.map (String.split ",") Json.string + ] + + +{-| Json decoder for an access token +-} +tokenDecoder : Json.Decoder Token +tokenDecoder = + Json.andThen (decoderFromJust "missing or invalid 'access_token' / 'token_type'") <| + Json.map2 makeToken + (Json.field "token_type" Json.string |> Json.map Just) + (Json.field "access_token" Json.string |> Json.map Just) + + +{-| Json decoder for a refresh token +-} +refreshTokenDecoder : Json.Decoder (Maybe Token) +refreshTokenDecoder = + Json.andThen (decoderFromJust "missing or invalid 'refresh_token' / 'token_type'") <| + Json.map2 makeRefreshToken + (Json.field "token_type" Json.string) + (Json.field "refresh_token" Json.string |> Json.maybe) + + +{-| Json decoder for 'error' field +-} +errorDecoder : (String -> a) -> Json.Decoder a +errorDecoder errorCodeFromString = + Json.map errorCodeFromString <| Json.field "error" Json.string + + +{-| Json decoder for 'error\_description' field +-} +errorDescriptionDecoder : Json.Decoder (Maybe String) +errorDescriptionDecoder = + Json.maybe <| Json.field "error_description" Json.string + + +{-| Json decoder for 'error\_uri' field +-} +errorUriDecoder : Json.Decoder (Maybe String) +errorUriDecoder = + Json.maybe <| Json.field "error_uri" Json.string + + +{-| Combinator for JSON decoders to extract values from a `Maybe` or fail +with the given message (when `Nothing` is encountered) +-} +decoderFromJust : String -> Maybe a -> Json.Decoder a +decoderFromJust msg = + Maybe.map Json.succeed >> Maybe.withDefault (Json.fail msg) + + +{-| Combinator for JSON decoders to extact values from a `Result _ _` or fail +with an appropriate message +-} +decoderFromResult : Result String a -> Json.Decoder a +decoderFromResult res = + case res of + Err msg -> + Json.fail msg + + Ok a -> + Json.succeed a + + + +-- +-- Query Parsers +-- + + +authorizationErrorParser : e -> Query.Parser (AuthorizationError e) +authorizationErrorParser errorCode = + Query.map3 (AuthorizationError errorCode) + errorDescriptionParser + errorUriParser + stateParser + + +tokenParser : Query.Parser (Maybe Token) +tokenParser = + Query.map2 makeToken + (Query.string "token_type") + (Query.string "access_token") + + +errorParser : (String -> e) -> Query.Parser (Maybe e) +errorParser errorCodeFromString = + Query.map (Maybe.map errorCodeFromString) + (Query.string "error") + + +expiresInParser : Query.Parser (Maybe Int) +expiresInParser = + Query.int "expires_in" + + +scopeParser : Query.Parser (List String) +scopeParser = + spaceSeparatedListParser "scope" + + +stateParser : Query.Parser (Maybe String) +stateParser = + Query.string "state" + + +errorDescriptionParser : Query.Parser (Maybe String) +errorDescriptionParser = + Query.string "error_description" + + +errorUriParser : Query.Parser (Maybe String) +errorUriParser = + Query.string "error_uri" + + +spaceSeparatedListParser : String -> Query.Parser (List String) +spaceSeparatedListParser param = + Query.map + (\s -> + case s of + Nothing -> + [] + + Just str -> + String.split " " str + ) + (Query.string param) + + +urlAddList : String -> List String -> List QueryParameter -> List QueryParameter +urlAddList param xs qs = + qs + ++ (case xs of + [] -> + [] + + _ -> + [ Builder.string param (String.join " " xs) ] + ) + + +urlAddMaybe : String -> Maybe String -> List QueryParameter -> List QueryParameter +urlAddMaybe param ms qs = + qs + ++ (case ms of + Nothing -> + [] + + Just s -> + [ Builder.string param s ] + ) + + +urlAddExtraFields : Dict String String -> List QueryParameter -> List QueryParameter +urlAddExtraFields extraFields zero = + Dict.foldr (\k v qs -> Builder.string k v :: qs) zero extraFields + + + +-- +-- Smart Constructors +-- + + +makeAuthorizationUrl : ResponseType -> Dict String String -> Authorization -> Url +makeAuthorizationUrl responseType extraFields { clientId, url, redirectUri, scope, state } = + let + query = + [ Builder.string "client_id" clientId + , Builder.string "redirect_uri" (makeRedirectUri redirectUri) + , Builder.string "response_type" (responseTypeToString responseType) + ] + |> urlAddList "scope" scope + |> urlAddMaybe "state" state + |> urlAddExtraFields extraFields + |> Builder.toQuery + |> String.dropLeft 1 + in + case url.query of + Nothing -> + { url | query = Just query } + + Just baseQuery -> + { url | query = Just (baseQuery ++ "&" ++ query) } + + +makeRequest : Json.Decoder success -> (Result Http.Error success -> msg) -> Url -> List Http.Header -> String -> RequestParts msg +makeRequest decoder toMsg url headers body = + { method = "POST" + , headers = headers + , url = Url.toString url + , body = Http.stringBody "application/x-www-form-urlencoded" body + , expect = Http.expectJson toMsg decoder + , timeout = Nothing + , tracker = Nothing + } + + +makeHeaders : Maybe { clientId : String, secret : String } -> List Http.Header +makeHeaders credentials = + credentials + |> Maybe.map (\{ clientId, secret } -> Base64.encode <| Base64.string <| (clientId ++ ":" ++ secret)) + |> Maybe.map (\s -> [ Http.header "Authorization" ("Basic " ++ s) ]) + |> Maybe.withDefault [] + + +makeRedirectUri : Url -> String +makeRedirectUri url = + String.concat + [ protocolToString url.protocol + , "://" + , url.host + , Maybe.withDefault "" (Maybe.map (\i -> ":" ++ String.fromInt i) url.port_) + , url.path + , Maybe.withDefault "" (Maybe.map (\q -> "?" ++ q) url.query) + ] + + + +-- +-- String utilities +-- + + +{-| Gets the `String` representation of an `Protocol` +-} +protocolToString : Protocol -> String +protocolToString protocol = + case protocol of + Http -> + "http" + + Https -> + "https" + + + +-- +-- Utils +-- + + +parseUrlQuery : Url -> a -> Query.Parser a -> a +parseUrlQuery url def parser = + Maybe.withDefault def <| Url.parse (Url.query parser) url + + +{-| Extracts the intrinsic value of a `Token`. Careful with this, we don't have +access to the `Token` constructors, so it's a bit Houwje-Touwje +-} +extractTokenString : Token -> String +extractTokenString = + tokenToString >> String.dropLeft 7 + + + +-- +-- Record Alias Re-Definition +-- + + +type alias RequestParts a = + { method : String + , headers : List Http.Header + , url : String + , body : Http.Body + , expect : Http.Expect a + , timeout : Maybe Float + , tracker : Maybe String + } + + +type alias Authorization = + { clientId : String + , url : Url + , redirectUri : Url + , scope : List String + , state : Maybe String + } + + +type alias AuthorizationError e = + { error : e + , errorDescription : Maybe String + , errorUri : Maybe String + , state : Maybe String + } + + +type alias AuthenticationSuccess = + { token : Token + , refreshToken : Maybe Token + , expiresIn : Maybe Int + , scope : List String + , idJwt : Maybe String + } + + +type alias AuthenticationError e = + { error : e + , errorDescription : Maybe String + , errorUri : Maybe String + } diff --git a/counter/auth-vendored/OAuth/LICENSE b/counter/auth-vendored/OAuth/LICENSE new file mode 100644 index 0000000..b4f56f1 --- /dev/null +++ b/counter/auth-vendored/OAuth/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2017-2019 TruQu + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/counter/auth-vendored/OAuth/Password.elm b/counter/auth-vendored/OAuth/Password.elm new file mode 100644 index 0000000..e0c63fc --- /dev/null +++ b/counter/auth-vendored/OAuth/Password.elm @@ -0,0 +1,293 @@ +module OAuth.Password exposing + ( makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + , defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + , makeTokenRequestWith, defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + ) + +{-| The resource owner password credentials grant type is suitable in +cases where the resource owner has a trust relationship with the +client, such as the device operating system or a highly privileged +application. The authorization server should take special care when +enabling this grant type and only allow it when other flows are not +viable. + +There's only one step in this process: + + - The client authenticates itself directly using the resource owner (user) credentials + +After this step, the client owns a `Token` that can be used to authorize any subsequent +request. + + +## Authenticate + +@docs makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + + +## JSON Decoders + +@docs defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + + +## Custom Decoders & Parsers (advanced) + +@docs makeTokenRequestWith, defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + +-} + +import Dict as Dict exposing (Dict) +import Effect.Http +import Internal as Internal exposing (..) +import Json.Decode as Json +import OAuth exposing (ErrorCode(..), GrantType(..), Token, errorCodeFromString, grantTypeToString) +import Url exposing (Url) +import Url.Builder as Builder + + +{-| Request configuration for a Password authentication + + - `credentials` (_RECOMMENDED_): + Credentials needed for `Basic` authentication, if needed by the + authorization server. + + - `url` (_REQUIRED_): + The token endpoint to contact the authorization server. + + - `scope` (_OPTIONAL_): + The scope of the access request. + + - `password` (_REQUIRED_): + Resource owner's password + + - `username` (_REQUIRED_): + Resource owner's username + +-} +type alias Authentication = + { credentials : Maybe Credentials + , url : Url + , scope : List String + , username : String + , password : String + } + + +{-| Describes at least a `clientId` and if defined, a complete set of credentials +with the `secret`. Optional but may be required by the authorization server you +interact with to perform a 'Basic' authentication on top of the authentication request. + + { clientId = "" + , secret = "" + } + +-} +type alias Credentials = + { clientId : String, secret : String } + + +{-| The response obtained as a result of an authentication: + + - `token` (_REQUIRED_): + The access token issued by the authorization server. + + - `refreshToken` (_OPTIONAL_): + The refresh token, which can be used to obtain new access tokens using the same authorization + grant as described in [Section 6](https://tools.ietf.org/html/rfc6749#section-6). + + - `expiresIn` (_RECOMMENDED_): + The lifetime in seconds of the access token. For example, the value "3600" denotes that the + access token will expire in one hour from the time the response was generated. If omitted, the + authorization server SHOULD provide the expiration time via other means or document the default + value. + + - `scope` (_OPTIONAL, if identical to the scope requested; otherwise, REQUIRED_): + The scope of the access token as described by [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). + +-} +type alias AuthenticationSuccess = + { token : Token + , refreshToken : Maybe Token + , expiresIn : Maybe Int + , scope : List String + } + + +{-| Describes an OAuth error as a result of a request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer in + understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to + provide the client developer with additional information about the error. Values for the + `errorUri` parameter MUST conform to the URI-reference syntax and thus MUST NOT include + characters outside the set `%x21 / %x23-5B / %x5D-7E`. + +-} +type alias AuthenticationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + } + + +{-| Parts required to build a request. This record is given to `Http.request` in order +to create a new request and may be adjusted at will. +-} +type alias RequestParts a = + { method : String + , headers : List Effect.Http.Header + , url : String + , body : Effect.Http.Body + , expect : Effect.Http.Expect a + , timeout : Maybe Float + , tracker : Maybe String + } + + +{-| Builds the request components required to get a token in exchange of the resource owner (user) credentials + + let req : Http.Request TokenResponse + req = makeTokenRequest toMsg authentication |> Http.request + +-} +makeTokenRequest : (Result Effect.Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg +makeTokenRequest = + makeTokenRequestWith Password defaultAuthenticationSuccessDecoder Dict.empty + + + +-- +-- Json Decoders +-- + + +{-| Json decoder for a positive response. You may provide a custom response decoder using other decoders +from this module, or some of your own craft. + + defaultAuthenticationSuccessDecoder : Decoder AuthenticationSuccess + defaultAuthenticationSuccessDecoder = + D.map4 AuthenticationSuccess + tokenDecoder + refreshTokenDecoder + expiresInDecoder + scopeDecoder + +-} +defaultAuthenticationSuccessDecoder : Json.Decoder AuthenticationSuccess +defaultAuthenticationSuccessDecoder = + Internal.authenticationSuccessDecoder + + +{-| Json decoder for an errored response. + + case res of + Err (Http.BadStatus { body }) -> + case Json.decodeString OAuth.Password.defaultAuthenticationErrorDecoder body of + Ok { error, errorDescription } -> + doSomething + + _ -> + parserFailed + + _ -> + someOtherError + +-} +defaultAuthenticationErrorDecoder : Json.Decoder AuthenticationError +defaultAuthenticationErrorDecoder = + Internal.authenticationErrorDecoder defaultErrorDecoder + + + +-- +-- Custom Decoders & Parsers (advanced) +-- + + +{-| Like [`makeTokenRequest`](#makeTokenRequest), but gives you the ability to specify custom grant +type and extra fields to be set on the query. + + makeTokenRequest : (Result Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg + makeTokenRequest = + makeTokenRequestWith Password defaultAuthenticationSuccessDecoder Dict.empty + +-} +makeTokenRequestWith : GrantType -> Json.Decoder success -> Dict String String -> (Result Effect.Http.Error success -> msg) -> Authentication -> RequestParts msg +makeTokenRequestWith grantType decoder extraFields toMsg { credentials, password, scope, url, username } = + let + body = + [ Builder.string "grant_type" (grantTypeToString grantType) + , Builder.string "username" username + , Builder.string "password" password + ] + |> urlAddExtraFields extraFields + |> urlAddList "scope" scope + |> Builder.toQuery + |> String.dropLeft 1 + + headers = + makeHeaders credentials + in + makeRequest decoder toMsg url headers body + + +{-| Json decoder for the `expiresIn` field. +-} +defaultExpiresInDecoder : Json.Decoder (Maybe Int) +defaultExpiresInDecoder = + Internal.expiresInDecoder + + +{-| Json decoder for the `scope` field (space-separated). +-} +defaultScopeDecoder : Json.Decoder (List String) +defaultScopeDecoder = + Internal.scopeDecoder + + +{-| Json decoder for the `scope` field (comma- or space-separated). +-} +lenientScopeDecoder : Json.Decoder (List String) +lenientScopeDecoder = + Internal.lenientScopeDecoder + + +{-| Json decoder for the `access_token` field. +-} +defaultTokenDecoder : Json.Decoder Token +defaultTokenDecoder = + Internal.tokenDecoder + + +{-| Json decoder for the `refresh_token` field. +-} +defaultRefreshTokenDecoder : Json.Decoder (Maybe Token) +defaultRefreshTokenDecoder = + Internal.refreshTokenDecoder + + +{-| Json decoder for the `error` field. +-} +defaultErrorDecoder : Json.Decoder ErrorCode +defaultErrorDecoder = + Internal.errorDecoder errorCodeFromString + + +{-| Json decoder for the `error_description` field. +-} +defaultErrorDescriptionDecoder : Json.Decoder (Maybe String) +defaultErrorDescriptionDecoder = + Internal.errorDescriptionDecoder + + +{-| Json decoder for the `error_uri` field. +-} +defaultErrorUriDecoder : Json.Decoder (Maybe String) +defaultErrorUriDecoder = + Internal.errorUriDecoder diff --git a/counter/auth-vendored/OAuth/Refresh.elm b/counter/auth-vendored/OAuth/Refresh.elm new file mode 100644 index 0000000..a5910df --- /dev/null +++ b/counter/auth-vendored/OAuth/Refresh.elm @@ -0,0 +1,283 @@ +module OAuth.Refresh exposing + ( makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + , defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + , makeTokenRequestWith, defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + ) + +{-| If the authorization server issued a refresh token to the client, the +client may make a refresh request to the token endpoint to obtain a new access token +(and refresh token) from the authorization server. + +There's only one step in this process: + + - The client authenticates itself directly using the previously obtained refresh token + +After this step, the client owns a fresh access `Token` and possibly, a new refresh `Token`. Both +can be used in subsequent requests. + + +## Authenticate + +@docs makeTokenRequest, Authentication, Credentials, AuthenticationSuccess, AuthenticationError, RequestParts + + +## JSON Decoders + +@docs defaultAuthenticationSuccessDecoder, defaultAuthenticationErrorDecoder + + +## Custom Decoders & Parsers (advanced) + +@docs makeTokenRequestWith, defaultExpiresInDecoder, defaultScopeDecoder, lenientScopeDecoder, defaultTokenDecoder, defaultRefreshTokenDecoder, defaultErrorDecoder, defaultErrorDescriptionDecoder, defaultErrorUriDecoder + +-} + +import Dict as Dict exposing (Dict) +import Effect.Http +import Json.Decode as Json +import OAuth exposing (ErrorCode(..), GrantType(..), Token, errorCodeFromString, grantTypeToString) +import OAuth.Internal as Internal exposing (..) +import Url exposing (Url) +import Url.Builder as Builder + + +{-| Request configuration for a Refresh authentication + + - `credentials` (_RECOMMENDED_): + Credentials needed for Basic authentication, if needed by the + authorization server. + + - `url` (_REQUIRED_): + The token endpoint to contact the authorization server. + + - `scope` (_OPTIONAL_): + The scope of the access request. + + - `token` (_REQUIRED_): + Token endpoint of the resource provider + +-} +type alias Authentication = + { credentials : Maybe Credentials + , url : Url + , scope : List String + , token : Token + } + + +{-| Describes a couple of client credentials used for Basic authentication + + { clientId = "" + , secret = "" + } + +-} +type alias Credentials = + { clientId : String, secret : String } + + +{-| The response obtained as a result of an authentication (implicit or not) + + - `token` (_REQUIRED_): + The access token issued by the authorization server. + + - `refreshToken` (_OPTIONAL_): + The refresh token, which can be used to obtain new access tokens using the same authorization + grant as described in [Section 6](https://tools.ietf.org/html/rfc6749#section-6). + + - `expiresIn` (_RECOMMENDED_): + The lifetime in seconds of the access token. For example, the value "3600" denotes that the + access token will expire in one hour from the time the response was generated. If omitted, the + authorization server SHOULD provide the expiration time via other means or document the default + value. + + - `scope` (_OPTIONAL, if identical to the scope requested; otherwise, REQUIRED_): + The scope of the access token as described by [Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3). + +-} +type alias AuthenticationSuccess = + { token : Token + , refreshToken : Maybe Token + , expiresIn : Maybe Int + , scope : List String + } + + +{-| Describes an OAuth error as a result of a request failure + + - `error` (_REQUIRED_): + A single ASCII error code. + + - `errorDescription` (_OPTIONAL_) + Human-readable ASCII text providing additional information, used to assist the client developer in + understanding the error that occurred. Values for the `errorDescription` parameter MUST NOT + include characters outside the set `%x20-21 / %x23-5B / %x5D-7E`. + + - `errorUri` (_OPTIONAL_): + A URI identifying a human-readable web page with information about the error, used to + provide the client developer with additional information about the error. Values for the + `errorUri` parameter MUST conform to the URI-reference syntax and thus MUST NOT include + characters outside the set `%x21 / %x23-5B / %x5D-7E`. + +-} +type alias AuthenticationError = + { error : ErrorCode + , errorDescription : Maybe String + , errorUri : Maybe String + } + + +{-| Parts required to build a request. This record is given to [`Http.request`](https://package.elm-lang.org/packages/elm/http/latest/Http#request) +in order to create a new request and may be adjusted at will. +-} +type alias RequestParts a = + { method : String + , headers : List Effect.Http.Header + , url : String + , body : Effect.Http.Body + , expect : Effect.Http.Expect a + , timeout : Maybe Float + , tracker : Maybe String + } + + +{-| Builds the request components required to refresh a token + + let req : Http.Request TokenResponse + req = makeTokenRequest toMsg reqParts |> Http.request + +-} +makeTokenRequest : (Result Effect.Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg +makeTokenRequest = + makeTokenRequestWith RefreshToken defaultAuthenticationSuccessDecoder Dict.empty + + + +-- +-- Json Decoders +-- + + +{-| Json decoder for a positive response. You may provide a custom response decoder using other decoders +from this module, or some of your own craft. + + defaultAuthenticationSuccessDecoder : Decoder AuthenticationSuccess + defaultAuthenticationSuccessDecoder = + D.map4 AuthenticationSuccess + tokenDecoder + refreshTokenDecoder + expiresInDecoder + scopeDecoder + +-} +defaultAuthenticationSuccessDecoder : Json.Decoder AuthenticationSuccess +defaultAuthenticationSuccessDecoder = + Internal.authenticationSuccessDecoder + + +{-| Json decoder for an errored response. + + case res of + Err (Http.BadStatus { body }) -> + case Json.decodeString OAuth.ClientCredentials.defaultAuthenticationErrorDecoder body of + Ok { error, errorDescription } -> + doSomething + + _ -> + parserFailed + + _ -> + someOtherError + +-} +defaultAuthenticationErrorDecoder : Json.Decoder AuthenticationError +defaultAuthenticationErrorDecoder = + Internal.authenticationErrorDecoder defaultErrorDecoder + + + +-- +-- Custom Decoders & Parsers (advanced) +-- + + +{-| Like [`makeTokenRequest`](#makeTokenRequest), but gives you the ability to specify custom grant +type and extra fields to be set on the query. + + makeTokenRequest : (Result Http.Error AuthenticationSuccess -> msg) -> Authentication -> RequestParts msg + makeTokenRequest = + makeTokenRequestWith RefreshToken defaultAuthenticationSuccessDecoder Dict.empty + +-} +makeTokenRequestWith : GrantType -> Json.Decoder success -> Dict String String -> (Result Effect.Http.Error success -> msg) -> Authentication -> RequestParts msg +makeTokenRequestWith grantType decoder extraFields toMsg { credentials, scope, token, url } = + let + body = + [ Builder.string "grant_type" (grantTypeToString grantType) + , Builder.string "refresh_token" (extractTokenString token) + ] + |> urlAddList "scope" scope + |> urlAddExtraFields extraFields + |> Builder.toQuery + |> String.dropLeft 1 + + headers = + makeHeaders credentials + in + makeRequest decoder toMsg url headers body + + +{-| Json decoder for the `expiresIn` field. +-} +defaultExpiresInDecoder : Json.Decoder (Maybe Int) +defaultExpiresInDecoder = + Internal.expiresInDecoder + + +{-| Json decoder for the `scope` field (space-separated). +-} +defaultScopeDecoder : Json.Decoder (List String) +defaultScopeDecoder = + Internal.scopeDecoder + + +{-| Json decoder for the `scope` field (comma- or space-separated). +-} +lenientScopeDecoder : Json.Decoder (List String) +lenientScopeDecoder = + Internal.lenientScopeDecoder + + +{-| Json decoder for the `access_token` field. +-} +defaultTokenDecoder : Json.Decoder Token +defaultTokenDecoder = + Internal.tokenDecoder + + +{-| Json decoder for the `refresh_token` field. +-} +defaultRefreshTokenDecoder : Json.Decoder (Maybe Token) +defaultRefreshTokenDecoder = + Internal.refreshTokenDecoder + + +{-| Json decoder for the `error` field +-} +defaultErrorDecoder : Json.Decoder ErrorCode +defaultErrorDecoder = + Internal.errorDecoder errorCodeFromString + + +{-| Json decoder for the `error_description` field +-} +defaultErrorDescriptionDecoder : Json.Decoder (Maybe String) +defaultErrorDescriptionDecoder = + Internal.errorDescriptionDecoder + + +{-| Json decoder for the `error_uri` field +-} +defaultErrorUriDecoder : Json.Decoder (Maybe String) +defaultErrorUriDecoder = + Internal.errorUriDecoder diff --git a/counter/auth-vendored/OAuth/readme.md b/counter/auth-vendored/OAuth/readme.md new file mode 100644 index 0000000..4e7be40 --- /dev/null +++ b/counter/auth-vendored/OAuth/readme.md @@ -0,0 +1,6 @@ +Vendored from https://github.com/truqu/elm-oauth2 in order to: + +- Expose idJwt token for Google Auth +- Add [`lamdera/program-test`](https://github.com/lamdera/program-test) support + +Ideally this will be de-vendored into a regular Elm dependency in future. diff --git a/counter/elm.json b/counter/elm.json index 95fffe0..7cab604 100644 --- a/counter/elm.json +++ b/counter/elm.json @@ -1,24 +1,29 @@ { "type": "application", "source-directories": [ - "src" + "src", + "auth-vendored", + "vendor/elm-email" ], "elm-version": "0.19.1", "dependencies": { "direct": { + "chelovek0v/bbase64": "1.0.1", "elm/browser": "1.0.2", + "elm/bytes": "1.0.8", "elm/core": "1.0.5", "elm/html": "1.0.0", "elm/http": "2.0.0", + "elm/json": "1.1.3", + "elm/parser": "1.1.0", + "elm/time": "1.0.0", + "elm/url": "1.0.0", "lamdera/codecs": "1.0.0", "lamdera/core": "1.0.0" }, "indirect": { - "elm/bytes": "1.0.8", "elm/file": "1.0.5", - "elm/json": "1.1.3", - "elm/time": "1.0.0", - "elm/url": "1.0.0", + "elm/regex": "1.0.0", "elm/virtual-dom": "1.0.2" } }, diff --git a/counter/src/MagicLink/Auth.elm b/counter/src/MagicLink/Auth.elm new file mode 100644 index 0000000..204a973 --- /dev/null +++ b/counter/src/MagicLink/Auth.elm @@ -0,0 +1,280 @@ +module MagicLink.Auth exposing + ( backendConfig + , updateFromBackend + , updateFrontend + ) + +import Auth.Common exposing (UserInfo) +import Auth.Flow +import Auth.Method.EmailMagicLink +import Dict exposing (Dict) +import Dict.Extra as Dict +import EmailAddress +import Lamdera exposing (ClientId, SessionId) +import MagicLink.Backend +import MagicLink.Common +import MagicLink.Frontend +import MagicLink.Types +import Route +import Time +import Types exposing (..) +import Url +import User + + +updateFrontend msg model = + case msg of + MagicLink.Types.SubmitEmailForSignIn -> + MagicLink.Frontend.submitEmailForSignin model + + MagicLink.Types.AuthSigninRequested { methodId, email } -> + Auth.Flow.signInRequested methodId model email + |> Tuple.mapSecond (AuthToBackend >> Lamdera.sendToBackend) + + MagicLink.Types.ReceivedSigninCode loginCode -> + MagicLink.Frontend.signInWithCode model loginCode + + MagicLink.Types.CancelSignIn -> + ( { model | route = Route.HomepageRoute }, Cmd.none ) + + MagicLink.Types.CancelSignUp -> + ( { model | signInStatus = MagicLink.Types.NotSignedIn }, Cmd.none ) + + MagicLink.Types.OpenSignUp -> + ( { model | signInStatus = MagicLink.Types.SigningUp }, Cmd.none ) + + MagicLink.Types.TypedEmailInSignInForm email -> + MagicLink.Frontend.enterEmail model email + + MagicLink.Types.SubmitSignUp -> + MagicLink.Frontend.submitSignUp model + + MagicLink.Types.SignOut -> + MagicLink.Frontend.signOut model + + MagicLink.Types.InputRealname str -> + ( { model | realname = str }, Cmd.none ) + + MagicLink.Types.InputUsername str -> + ( { model | username = str }, Cmd.none ) + + MagicLink.Types.InputEmail str -> + ( { model | email = str }, Cmd.none ) + + +updateFromBackend : + Auth.Common.ToFrontend + -> + { a + | authFlow : Auth.Common.Flow + , message : String + , currentUserData : Maybe User.LoginData + , signInState : SignInState + , route : Route.Route + } + -> + ( { a + | authFlow : Auth.Common.Flow + , message : String + , currentUserData : Maybe User.LoginData + , signInState : SignInState + , route : Route.Route + } + , Cmd msg + ) +updateFromBackend authToFrontendMsg model = + case authToFrontendMsg of + Auth.Common.ReceivedMessage result -> + case result of + Ok message -> + ( { model | message = message }, Cmd.none ) + + Err b -> + ( { model | message = "Error: " ++ b }, Cmd.none ) + + Auth.Common.AuthInitiateSignin url -> + Auth.Flow.startProviderSignin url model + + Auth.Common.AuthError err -> + Auth.Flow.setError model err + + Auth.Common.AuthSessionChallenge _ -> + ( model, Cmd.none ) + + Auth.Common.AuthSignInWithTokenResponse result -> + case result of + Ok userData -> + ( { model + | currentUserData = Just userData + , authFlow = + Auth.Common.Done + { email = userData.email + , name = Just userData.name + , username = Just userData.username + } + , signInState = SignedIn + } + |> MagicLink.Frontend.signInWithTokenResponseM userData + , MagicLink.Frontend.signInWithTokenResponseC userData + ) + + Err _ -> + ( model, Cmd.none ) + + +config : Auth.Common.Config FrontendMsg ToBackend BackendMsg ToFrontend LoadedModel BackendModel +config = + { toBackend = AuthToBackend + , toFrontend = AuthToFrontend + , backendMsg = AuthBackendMsg + , sendToFrontend = Lamdera.sendToFrontend + , sendToBackend = Lamdera.sendToBackend + , renewSession = renewSession + , methods = + [ Auth.Method.EmailMagicLink.configuration + { initiateSignin = initiateEmailSignin + , onAuthCallbackReceived = onEmailAuthCallbackReceived + } + ] + } + + +initiateEmailSignin : SessionId -> ClientId -> BackendModel -> { a | username : Maybe String } -> Time.Posix -> ( BackendModel, Cmd BackendMsg ) +initiateEmailSignin sessionId clientId model login now = + case login.username of + Nothing -> + ( model, MagicLink.Common.sendMessage clientId "No username provided." ) + + Just emailString -> + case EmailAddress.fromString emailString of + Nothing -> + ( model, MagicLink.Common.sendMessage clientId "Invalid email address." ) + + Just emailAddress_ -> + case model.users |> Dict.get emailString of + Just user -> + let + ( newModel, loginToken ) = + MagicLink.Backend.getLoginCode now model + + loginCode = + loginToken |> Result.withDefault 31462718 + + -- TODO ^^ bad code! + in + ( { newModel + | pendingEmailAuths = + model.pendingEmailAuths + |> Dict.insert sessionId + { created = now + , sessionId = sessionId + , username = user.username + , fullname = user.fullname + , token = loginCode |> String.fromInt + } + } + , Cmd.batch + [ MagicLink.Backend.sendLoginEmail_ (Auth.Common.AuthSentLoginEmail now emailAddress_ >> AuthBackendMsg) emailAddress_ loginCode + , MagicLink.Common.sendMessage clientId + ("We have sent you a login email at " ++ EmailAddress.toString emailAddress_) + ] + ) + + Nothing -> + ( model, MagicLink.Common.sendMessage clientId "You are not properly registered." ) + + +onEmailAuthCallbackReceived : + Auth.Common.SessionId + -> Auth.Common.ClientId + -> Url.Url + -> Auth.Common.AuthCode + -> Auth.Common.State + -> Time.Posix + -> (Auth.Common.BackendMsg -> BackendMsg) + -> BackendModel + -> ( BackendModel, Cmd BackendMsg ) +onEmailAuthCallbackReceived sessionId clientId receivedUrl code state now asBackendMsg backendModel = + case backendModel.pendingEmailAuths |> Dict.find (\k p -> p.token == code) of + Just ( sessionIdRequester, pendingAuth ) -> + { backendModel | pendingEmailAuths = backendModel.pendingEmailAuths |> Dict.remove sessionIdRequester } + |> findOrRegisterUser + { currentClientId = clientId + , requestingSessionId = pendingAuth.sessionId + , username = pendingAuth.username + , fullname = pendingAuth.fullname + , authTokenM = Nothing + , now = pendingAuth.created + } + + Nothing -> + ( backendModel + , Lamdera.sendToFrontend sessionId + (AuthToFrontend <| Auth.Common.AuthSessionChallenge Auth.Common.AuthSessionMissing) + ) + + +findOrRegisterUser : + { currentClientId : Lamdera.ClientId + , requestingSessionId : Lamdera.SessionId + , username : String -- TODO: alias this + , fullname : String -- TODO: alias this + , authTokenM : Maybe Auth.Common.Token + , now : Time.Posix + } + -> BackendModel + -> ( BackendModel, Cmd BackendMsg ) +findOrRegisterUser params model = + -- TODO : real implementation needed here + ( model, Cmd.none ) + + +backendConfig : BackendModel -> Auth.Flow.BackendUpdateConfig FrontendMsg BackendMsg ToFrontend LoadedModel BackendModel +backendConfig model = + { asToFrontend = AuthToFrontend + , asBackendMsg = AuthBackendMsg + , sendToFrontend = Lamdera.sendToFrontend + , backendModel = model + , loadMethod = Auth.Flow.methodLoader config.methods + , handleAuthSuccess = handleAuthSuccess model + , isDev = True + , renewSession = renewSession + , logout = logout + } + + +logout : SessionId -> ClientId -> BackendModel -> ( BackendModel, Cmd msg ) +logout sessionId _ model = + ( { model | sessions = model.sessions |> Dict.remove sessionId }, Cmd.none ) + + +renewSession : Lamdera.SessionId -> Lamdera.ClientId -> BackendModel -> ( BackendModel, Cmd BackendMsg ) +renewSession _ _ model = + ( model, Cmd.none ) + + +handleAuthSuccess : + BackendModel + -> SessionId + -> ClientId + -> Auth.Common.UserInfo + -> Auth.Common.MethodId + -> Maybe Auth.Common.Token + -> Time.Posix + -> ( BackendModel, Cmd BackendMsg ) +handleAuthSuccess backendModel sessionId clientId userInfo _ _ _ = + -- TODO handle renewing sessions if that is something you need + let + sessionsWithOutThisOne : Dict SessionId UserInfo + sessionsWithOutThisOne = + Dict.removeWhen (\_ { email } -> email == userInfo.email) backendModel.sessions + + newSessions = + Dict.insert sessionId userInfo sessionsWithOutThisOne + in + ( { backendModel | sessions = newSessions } + , Cmd.batch + [ -- renewSession_ user_.id sessionId clientId + Lamdera.sendToFrontend clientId (AuthSuccess userInfo) + ] + ) diff --git a/counter/src/MagicLink/Backend.elm b/counter/src/MagicLink/Backend.elm new file mode 100644 index 0000000..3c5feb6 --- /dev/null +++ b/counter/src/MagicLink/Backend.elm @@ -0,0 +1,376 @@ +module MagicLink.Backend exposing + ( addUser + , checkLogin + , getLoginCode + , requestSignUp + , sendLoginEmail_ + , signInWithMagicToken + ) + +import AssocList +import Auth.Common +import Config +import Dict +import Duration +import Email.Html +import Email.Html.Attributes +import EmailAddress exposing (EmailAddress) +import Hex +import Http +import Id exposing (Id) +import Lamdera exposing (ClientId, SessionId) +import List.Extra +import List.Nonempty +import LocalUUID +import MagicLink.LoginForm +import Postmark +import Quantity +import Sha256 +import String.Nonempty exposing (NonemptyString) +import Time +import Types exposing (BackendModel, BackendMsg, ToFrontend(..)) +import User + + +addUser : BackendModel -> ClientId -> String -> String -> String -> ( BackendModel, Cmd BackendMsg ) +addUser model clientId email realname username = + case EmailAddress.fromString email of + Nothing -> + ( model, Lamdera.sendToFrontend clientId (SignInError <| "Invalid email: " ++ email) ) + + Just validEmail -> + addUser1 model clientId email validEmail realname username + + +checkLogin : BackendModel -> ClientId -> SessionId -> ( BackendModel, Cmd BackendMsg ) +checkLogin model clientId sessionId = + ( model + , if Dict.isEmpty model.users then + Cmd.batch + [ Err Types.Sunny |> CheckSignInResponse |> Lamdera.sendToFrontend clientId + ] + + else + case getUserFromSessionId sessionId model of + Just ( userId, user ) -> + getLoginData userId user model + |> CheckSignInResponse + |> Lamdera.sendToFrontend clientId + + Nothing -> + CheckSignInResponse (Err Types.LoadedBackendData) |> Lamdera.sendToFrontend clientId + ) + + +{-| + + Use magicToken, an Int, to sign in a user. + +-} +signInWithMagicToken : + Time.Posix + -> SessionId + -> ClientId + -> Int + -> BackendModel + -> ( BackendModel, Cmd BackendMsg ) +signInWithMagicToken time sessionId clientId magicToken model = + case Dict.get sessionId model.pendingEmailAuths of + Just pendingAuth -> + handleExistingSession model pendingAuth.username sessionId clientId magicToken + + Nothing -> + handleNoSession model time sessionId clientId magicToken + + +requestSignUp : BackendModel -> ClientId -> String -> String -> String -> ( BackendModel, Cmd BackendMsg ) +requestSignUp model clientId fullname username email = + case model.localUuidData of + Nothing -> + ( model, Lamdera.sendToFrontend clientId (UserSignedIn Nothing) ) + + -- TODO, need to signal & handle error + Just uuidData -> + case EmailAddress.fromString email of + Nothing -> + ( model, Lamdera.sendToFrontend clientId (UserSignedIn Nothing) ) + + Just validEmail -> + let + user = + { fullname = fullname + , username = username + , email = validEmail + , emailString = email + , created_at = model.time + , updated_at = model.time + , id = LocalUUID.extractUUIDAsString uuidData + , roles = [ User.UserRole ] + , recentLoginEmails = [] + , verified = Nothing + } + in + ( { model + | localUuidData = model.localUuidData |> Maybe.map LocalUUID.step + } + |> addNewUser email user + , Lamdera.sendToFrontend clientId (UserSignedIn (Just user)) + ) + + +addNewUser email user model = + { model + | users = Dict.insert email user model.users + , userNameToEmailString = Dict.insert user.username email model.userNameToEmailString + } + + +getUserWithUsername : BackendModel -> User.Username -> Maybe User.User +getUserWithUsername model username = + Dict.get username model.userNameToEmailString + |> Maybe.andThen (\email -> Dict.get email model.users) + + + +-- HELPERS + + +handleExistingSession : BackendModel -> String -> SessionId -> ClientId -> Int -> ( BackendModel, Cmd BackendMsg ) +handleExistingSession model username sessionId clientId magicToken = + case getUserWithUsername model username of + Just user -> + ( { model | users = User.setAsVerified model.time user model.users } + , Cmd.batch + [ Lamdera.sendToFrontend sessionId + (AuthToFrontend <| Auth.Common.AuthSignInWithTokenResponse (Ok <| User.loginDataOfUser user)) + ] + ) + + Nothing -> + ( model, Lamdera.sendToFrontend clientId (AuthToFrontend <| Auth.Common.AuthSignInWithTokenResponse (Err magicToken)) ) + + +handleNoSession : BackendModel -> Time.Posix -> SessionId -> ClientId -> Int -> ( BackendModel, Cmd BackendMsg ) +handleNoSession model time sessionId clientId magicToken = + case AssocList.get sessionId model.pendingLogins of + Just pendingLogin -> + if + (pendingLogin.loginAttempts < MagicLink.LoginForm.maxLoginAttempts) + && (Duration.from pendingLogin.creationTime time |> Quantity.lessThan Duration.hour) + then + if magicToken == pendingLogin.loginCode then + case + Dict.toList model.users + |> List.Extra.find (\( _, user ) -> user.email == pendingLogin.emailAddress) + of + Just ( userId, user ) -> + ( { model + | sessionDict = AssocList.insert sessionId userId model.sessionDict + , pendingLogins = AssocList.remove sessionId model.pendingLogins + , users = User.setAsVerified model.time user model.users + } + , User.loginDataOfUser user + |> Ok + |> (Auth.Common.AuthSignInWithTokenResponse >> AuthToFrontend) + |> Lamdera.sendToFrontend sessionId + ) + + Nothing -> + ( model + , Err magicToken + |> (Auth.Common.AuthSignInWithTokenResponse >> AuthToFrontend) + |> Lamdera.sendToFrontend clientId + ) + + else + ( { model + | pendingLogins = + AssocList.insert + sessionId + { pendingLogin | loginAttempts = pendingLogin.loginAttempts + 1 } + model.pendingLogins + } + , Err magicToken |> (Auth.Common.AuthSignInWithTokenResponse >> AuthToFrontend) |> Lamdera.sendToFrontend clientId + ) + + else + ( model, Err magicToken |> (Auth.Common.AuthSignInWithTokenResponse >> AuthToFrontend) |> Lamdera.sendToFrontend clientId ) + + Nothing -> + ( model, Err magicToken |> (Auth.Common.AuthSignInWithTokenResponse >> AuthToFrontend) |> Lamdera.sendToFrontend clientId ) + + +getLoginData : User.Id -> User.User -> Types.BackendModel -> Result Types.BackendDataStatus User.LoginData +getLoginData userId user_ model = + User.loginDataOfUser user_ |> Ok + + +getUserFromSessionId : SessionId -> BackendModel -> Maybe ( User.Id, User.User ) +getUserFromSessionId sessionId model = + AssocList.get sessionId model.sessionDict + |> Maybe.andThen (\userId -> Dict.get userId model.users |> Maybe.map (Tuple.pair userId)) + + + +-- HELPERS FOR ADDUSER + + +addUser1 : BackendModel -> ClientId -> User.EmailString -> EmailAddress -> String -> String -> ( BackendModel, Cmd BackendMsg ) +addUser1 model clientId emailString emailAddress realname username = + if emailNotRegistered emailString model.users then + case Dict.get username model.users of + Just _ -> + ( model, Lamdera.sendToFrontend clientId (RegistrationError "That username is already registered") ) + + Nothing -> + addUser2 model clientId emailString emailAddress realname username + + else + ( model, Lamdera.sendToFrontend clientId (RegistrationError "That email is already registered") ) + + +addUser2 model clientId emailString emailAddress realname username = + case model.localUuidData of + Nothing -> + ( model, Lamdera.sendToFrontend clientId (UserSignedIn Nothing) ) + + Just uuidData -> + let + user = + { fullname = realname + , username = username + , email = emailAddress + , emailString = emailString + , created_at = model.time + , updated_at = model.time + , id = LocalUUID.extractUUIDAsString uuidData + , roles = [ User.UserRole ] + , recentLoginEmails = [] + , verified = Nothing + } + in + ( { model + | localUuidData = model.localUuidData |> Maybe.map LocalUUID.step + } + |> addNewUser emailString user + , Lamdera.sendToFrontend clientId (UserRegistered user) + ) + + + +-- STUFF + + +emailNotRegistered : User.EmailString -> Dict.Dict String User.User -> Bool +emailNotRegistered email users = + case Dict.get email users of + Nothing -> + True + + Just _ -> + False + + +getLoginCode : Time.Posix -> { a | secretCounter : Int } -> ( { a | secretCounter : Int }, Result () Int ) +getLoginCode time model = + case getUniqueId time model of + ( model2, id ) -> + ( model2, loginCodeFromId id ) + + +loginCodeFromId : Id String -> Result () Int +loginCodeFromId id = + case Id.toString id |> String.left MagicLink.LoginForm.loginCodeLength |> Hex.fromString of + Ok int -> + case String.fromInt int |> String.left MagicLink.LoginForm.loginCodeLength |> String.toInt of + Just int2 -> + Ok int2 + + Nothing -> + Err () + + Err _ -> + Err () + + +getUniqueId : Time.Posix -> { a | secretCounter : Int } -> ( { a | secretCounter : Int }, Id String ) +getUniqueId time model = + ( { model | secretCounter = model.secretCounter + 1 } + , Config.secretKey + ++ ":" + ++ String.fromInt model.secretCounter + ++ ":" + ++ String.fromInt (Time.posixToMillis time) + |> Sha256.sha256 + |> Id.fromString + ) + + +sendLoginEmail_ : + (Result Http.Error Postmark.PostmarkSendResponse -> backendMsg) + -> EmailAddress + -> Int + -> Cmd backendMsg +sendLoginEmail_ msg emailAddress loginCode = + { from = { name = "", email = noReplyEmailAddress } + , to = List.Nonempty.fromElement { name = "", email = emailAddress } + , subject = loginEmailSubject + , body = + Postmark.BodyBoth + (loginEmailContent loginCode) + ("Here is your code " ++ String.fromInt loginCode ++ "\n\nPlease type it in the XXX login page you were previously on.\n\nIf you weren't expecting this email you can safely ignore it.") + , messageStream = "outbound" + } + |> Postmark.sendEmail msg Config.postmarkApiKey + + +loginEmailContent : Int -> Email.Html.Html +loginEmailContent loginCode = + Email.Html.div + [ Email.Html.Attributes.padding "8px" ] + [ Email.Html.div [] [ Email.Html.text "Here is your code." ] + , Email.Html.div + [ Email.Html.Attributes.fontSize "36px" + , Email.Html.Attributes.fontFamily "monospace" + ] + (String.fromInt loginCode + |> String.toList + |> List.map + (\char -> + Email.Html.span + [ Email.Html.Attributes.padding "0px 3px 0px 4px" ] + [ Email.Html.text (String.fromChar char) ] + ) + |> (\a -> + List.take (MagicLink.LoginForm.loginCodeLength // 2) a + ++ [ Email.Html.span + [ Email.Html.Attributes.backgroundColor "black" + , Email.Html.Attributes.padding "0px 4px 0px 5px" + , Email.Html.Attributes.style "vertical-align" "middle" + , Email.Html.Attributes.fontSize "2px" + ] + [] + ] + ++ List.drop (MagicLink.LoginForm.loginCodeLength // 2) a + ) + ) + , Email.Html.text "Please type it in the login page you were previously on." + , Email.Html.br [] [] + , Email.Html.br [] [] + , Email.Html.text "If you weren't expecting this email you can safely ignore it." + ] + + +loginEmailSubject : NonemptyString +loginEmailSubject = + String.Nonempty.NonemptyString 'L' "ogin code" + + +noReplyEmailAddress : EmailAddress +noReplyEmailAddress = + EmailAddress.EmailAddress + { localPart = "hello" + , tags = [] + , domain = "elm-kitchen-sink.lamdera" + , tld = [ "app" ] + } diff --git a/counter/src/MagicLink/Common.elm b/counter/src/MagicLink/Common.elm new file mode 100644 index 0000000..2a4f763 --- /dev/null +++ b/counter/src/MagicLink/Common.elm @@ -0,0 +1,14 @@ +module MagicLink.Common exposing (sendMessage) + +import Auth.Common +import Lamdera +import Types + + + +-- sendMessage : ClientId -> String -> Cmd msg + + +sendMessage clientId message = + Lamdera.sendToFrontend clientId + ((Types.AuthToFrontend << Auth.Common.ReceivedMessage) (Ok message)) diff --git a/counter/src/MagicLink/Frontend.elm b/counter/src/MagicLink/Frontend.elm new file mode 100644 index 0000000..49462ef --- /dev/null +++ b/counter/src/MagicLink/Frontend.elm @@ -0,0 +1,174 @@ +module MagicLink.Frontend exposing + ( enterEmail + , handleRegistrationError + , handleSignInError + , signInWithCode + , signInWithTokenResponseC + , signInWithTokenResponseM + , signOut + , submitEmailForSignin + , submitSignUp + , userRegistered + ) + +import Auth.Common +import Dict +import EmailAddress +import Helper +import Lamdera +import MagicLink.LoginForm +import MagicLink.Types exposing (SigninForm(..)) +import Route exposing (Route(..)) +import Types + exposing + ( AdminDisplay(..) + , FrontendMsg(..) + , LoadedModel + , SignInState(..) + , ToBackend(..) + ) +import User + + +submitEmailForSignin : LoadedModel -> ( LoadedModel, Cmd FrontendMsg ) +submitEmailForSignin model = + case model.signinForm of + EnterEmail signinForm -> + case EmailAddress.fromString signinForm.email of + Just email -> + let + model2 = + { model | signinForm = EnterSigninCode { sentTo = email, loginCode = "", attempts = Dict.empty } } + in + ( model2, Helper.trigger <| AuthFrontendMsg <| MagicLink.Types.AuthSigninRequested { methodId = "EmailMagicLink", email = Just signinForm.email } ) + + Nothing -> + ( { model | signinForm = EnterEmail { signinForm | pressedSubmitEmail = True } }, Cmd.none ) + + EnterSigninCode _ -> + ( model, Cmd.none ) + + +enterEmail : { a | signinForm : SigninForm } -> String -> ( { a | signinForm : SigninForm }, Cmd msg ) +enterEmail model email = + case model.signinForm of + EnterEmail signinForm_ -> + let + signinForm = + { signinForm_ | email = email } + in + ( { model | signinForm = EnterEmail signinForm }, Cmd.none ) + + EnterSigninCode loginCode_ -> + -- TODO: complete this + -- EnterLoginCode{ sentTo : EmailAddress, loginCode : String, attempts : Dict Int LoginCodeStatus } + ( model, Cmd.none ) + + +handleRegistrationError : { a | signInStatus : MagicLink.Types.SignInStatus } -> String -> ( { a | signInStatus : MagicLink.Types.SignInStatus }, Cmd msg ) +handleRegistrationError model str = + ( { model | signInStatus = MagicLink.Types.ErrorNotRegistered str }, Cmd.none ) + + +handleSignInError : { a | loginErrorMessage : Maybe String, signInStatus : MagicLink.Types.SignInStatus } -> String -> ( { a | loginErrorMessage : Maybe String, signInStatus : MagicLink.Types.SignInStatus }, Cmd msg ) +handleSignInError model message = + ( { model | loginErrorMessage = Just message, signInStatus = MagicLink.Types.ErrorNotRegistered message }, Cmd.none ) + + +signInWithTokenResponseM : a -> { b | currentUserData : Maybe a, route : Route } -> { b | currentUserData : Maybe a, route : Route } +signInWithTokenResponseM signInData model = + { model | currentUserData = Just signInData, route = HomepageRoute } + + +signInWithTokenResponseC : User.LoginData -> Cmd msg +signInWithTokenResponseC signInData = + if List.member User.AdminRole signInData.roles then + Lamdera.sendToBackend GetBackendModel + + else + Cmd.none + + +signOut : { a | showTooltip : Bool, signinForm : SigninForm, loginErrorMessage : Maybe b, signInStatus : MagicLink.Types.SignInStatus, currentUserData : Maybe User.LoginData, currentUser : Maybe c, realname : String, username : String, email : String, signInState : SignInState, adminDisplay : AdminDisplay, backendModel : Maybe d, message : String } -> ( { a | showTooltip : Bool, signinForm : SigninForm, loginErrorMessage : Maybe b, signInStatus : MagicLink.Types.SignInStatus, currentUserData : Maybe User.LoginData, currentUser : Maybe c, realname : String, username : String, email : String, signInState : SignInState, adminDisplay : AdminDisplay, backendModel : Maybe d, message : String }, Cmd frontendMsg ) +signOut model = + ( { model + | showTooltip = False + + -- TOKEN + , signinForm = MagicLink.LoginForm.init + , loginErrorMessage = Nothing + , signInStatus = MagicLink.Types.NotSignedIn + + -- USER + , currentUserData = Nothing + , currentUser = Nothing + , realname = "" + , username = "" + , email = "" + , signInState = SignedOut + + -- ADMIN + , adminDisplay = ADUser + + -- + , backendModel = Nothing + , message = "" + } + , Cmd.none + ) + + +submitSignUp : { a | realname : String, username : String, email : String } -> ( { a | realname : String, username : String, email : String }, Cmd frontendMsg ) +submitSignUp model = + ( model, Lamdera.sendToBackend (AddUser model.realname model.username model.email) ) + + +userRegistered : { a | currentUser : Maybe { b | username : String, email : EmailAddress.EmailAddress }, signInStatus : MagicLink.Types.SignInStatus } -> { b | username : String, email : EmailAddress.EmailAddress } -> ( { a | currentUser : Maybe { b | username : String, email : EmailAddress.EmailAddress }, signInStatus : MagicLink.Types.SignInStatus }, Cmd msg ) +userRegistered model user = + ( { model + | currentUser = Just user + , signInStatus = MagicLink.Types.SuccessfulRegistration user.username (EmailAddress.toString user.email) + } + , Cmd.none + ) + + + +-- HELPERS + + +signInWithCode : LoadedModel -> String -> ( LoadedModel, Cmd msg ) +signInWithCode model signInCode = + case model.signinForm of + MagicLink.Types.EnterEmail _ -> + ( model, Cmd.none ) + + EnterSigninCode enterLoginCode -> + case MagicLink.LoginForm.validateLoginCode signInCode of + Ok loginCode -> + if Dict.member loginCode enterLoginCode.attempts then + ( { model + | signinForm = + EnterSigninCode + { enterLoginCode | loginCode = String.left MagicLink.LoginForm.loginCodeLength signInCode } + } + , Cmd.none + ) + + else + ( { model + | signinForm = + EnterSigninCode + { enterLoginCode + | loginCode = String.left MagicLink.LoginForm.loginCodeLength signInCode + , attempts = + Dict.insert loginCode MagicLink.Types.Checking enterLoginCode.attempts + } + } + , Lamdera.sendToBackend ((AuthToBackend << Auth.Common.AuthSigInWithToken) loginCode) + ) + + Err _ -> + ( { model | signinForm = EnterSigninCode { enterLoginCode | loginCode = String.left MagicLink.LoginForm.loginCodeLength signInCode } } + , Cmd.none + ) diff --git a/counter/src/MagicLink/LoginForm.elm b/counter/src/MagicLink/LoginForm.elm new file mode 100644 index 0000000..e5182af --- /dev/null +++ b/counter/src/MagicLink/LoginForm.elm @@ -0,0 +1,261 @@ +module MagicLink.LoginForm exposing + ( init + , loginCodeLength + , maxLoginAttempts + , validateLoginCode + , view + ) + +import Config +import Dict +import Element exposing (Element) +import Element.Background +import Element.Border +import Element.Font +import Element.Input +import EmailAddress exposing (EmailAddress) +import Html.Attributes +import MagicLink.Types exposing (EnterEmail_, EnterLoginCode_, LoginCodeStatus(..), SigninForm(..)) +import Martin +import Route +import Types exposing (FrontendMsg) +import View.MyElement as MyElement + + +validateLoginCode : String -> Result String Int +validateLoginCode text = + if String.any (\char -> Char.isDigit char |> not) text then + Err "Must only contain digits 0-9" + + else if String.length text == loginCodeLength then + case String.toInt text of + Just int -> + Ok int + + Nothing -> + Err "Invalid code" + + else + Err "" + + +loginCodeLength : number +loginCodeLength = + 8 + + +emailInput : msg -> (String -> msg) -> String -> String -> Maybe String -> Element msg +emailInput onSubmit onChange text labelText maybeError = + let + label = + MyElement.label + (Martin.idToString emailInputId) + [ Element.Font.bold ] + (Element.text labelText) + in + Element.column + [ Element.spacing 4 ] + [ Element.column + [] + [ label.element + , Element.Input.email + [ -- Element.Events.onKey Element.Events.enter onSubmit + -- TODO: it is doubtful that the below is correct + MyElement.onEnter onSubmit + , case maybeError of + Just _ -> + Element.Border.color MyElement.errorColor + + Nothing -> + Martin.noAttr + ] + { text = text + , onChange = onChange + , placeholder = Just <| Element.Input.placeholder [] <| Element.text "abc@def.com" + , label = label.id + } + ] + , Maybe.map errorView maybeError |> Maybe.withDefault Element.none + ] + + +errorView : String -> Element msg +errorView errorMessage = + Element.paragraph + [ Element.width Element.shrink + , Element.Font.color MyElement.errorColor + , Element.Font.medium + ] + [ Element.text errorMessage ] + + +view : Types.LoadedModel -> SigninForm -> Element FrontendMsg +view model loginForm = + Element.column + [ Element.padding 16 + , Element.centerX + , Element.centerY + + -- TODO:, Element.widthMax 520 + , Element.spacing 24 + ] + [ case loginForm of + EnterEmail enterEmail2 -> + enterEmailView enterEmail2 + + EnterSigninCode enterLoginCode -> + enterLoginCodeView enterLoginCode + , Element.paragraph + [ Element.Font.center ] + [ Element.text "If you're having trouble logging in, we can be reached at " + , MyElement.emailAddressLink Config.contactEmail + ] + ] + + +enterLoginCodeView : EnterLoginCode_ -> Element FrontendMsg +enterLoginCodeView model = + let + -- label : MyElement.Label + label = + MyElement.label + (Martin.idToString loginCodeInputId) + [] + (Element.column + [ Element.Font.center ] + [ Element.paragraph + [ Element.Font.size 30, Element.Font.bold ] + [ Element.text "Check your email for a code" ] + , Element.paragraph + [ Element.width Element.shrink ] + [ Element.text "An email has been sent to " + , Element.el + [ Element.Font.bold ] + (Element.text (EmailAddress.toString model.sentTo)) + , Element.text " containing a code. Please enter that code here." + ] + ] + ) + in + Element.column + [ Element.spacing 24 ] + [ label.element + , Element.column + [ Element.spacing 6, Element.centerX, Element.width Element.shrink, Element.moveRight 18 ] + [ Element.Input.text + [ -- Element.Font.letterSpacing 26 + Element.paddingEach { left = 6, right = 0, top = 2, bottom = 8 } + , Element.Font.family [ Element.Font.monospace ] + , Element.Font.size 14 + , Html.Attributes.attribute "inputmode" "numeric" |> Element.htmlAttribute + , Html.Attributes.type_ "number" |> Element.htmlAttribute + , Element.Border.width 1 + , Element.Background.color (Element.rgba 0 0 0.2 0) + ] + { onChange = Types.AuthFrontendMsg << MagicLink.Types.ReceivedSigninCode + , text = model.loginCode + , placeholder = Nothing --Just (Element.Input.placeholder [] (Element.text "12345678")) + , label = label.id + } + , if Dict.size model.attempts < maxLoginAttempts then + case validateLoginCode model.loginCode of + Ok loginCode -> + case Dict.get loginCode model.attempts of + Just NotValid -> + errorView "Incorrect code" + + _ -> + Element.paragraph + [] + [ Element.text "Submitting..." ] + + Err error -> + errorView error + + else + Element.text "Too many incorrect attempts. Please refresh the page and try again." + ] + ] + + +emailInputId : Martin.HtmlId +emailInputId = + Martin.HtmlId "loginForm_emailInput" + + +submitEmailButtonId : Martin.HtmlId +submitEmailButtonId = + Martin.HtmlId "loginForm_loginButton" + + +cancelButtonId : Martin.HtmlId +cancelButtonId = + Martin.HtmlId "loginForm_cancelButton" + + +loginCodeInputId : Martin.HtmlId +loginCodeInputId = + Martin.HtmlId "loginForm_loginCodeInput" + + +maxLoginAttempts : number +maxLoginAttempts = + 10 + + +enterEmailView : EnterEmail_ -> Element FrontendMsg +enterEmailView model = + Element.column + [ Element.spacing 16 ] + [ emailInput + (Types.AuthFrontendMsg MagicLink.Types.SubmitEmailForSignIn) + (Types.AuthFrontendMsg << MagicLink.Types.TypedEmailInSignInForm) + model.email + "Enter your email address" + (case ( model.pressedSubmitEmail, validateEmail model.email ) of + ( True, Err error ) -> + Just error + + _ -> + Nothing + ) + , Element.paragraph + [] + [ Element.text "By continuing, you agree to our Terms of Service." + + -- TODO: below, Route,HomepageRoute is a placeholder + , MyElement.routeLinkNewTab Route.HomepageRoute Route.TermsOfServiceRoute + , Element.text "." + ] + , Element.row + [ Element.spacing 16 ] + [ MyElement.secondaryButton [ Martin.elementId cancelButtonId ] (Types.AuthFrontendMsg MagicLink.Types.CancelSignIn) "Cancel" + , MyElement.primaryButton submitEmailButtonId (Types.AuthFrontendMsg MagicLink.Types.SubmitEmailForSignIn) "Sign in" + ] + , if model.rateLimited then + errorView "Too many sign in attempts have been made. Please try again later." + + else + Element.none + ] + + +validateEmail : String -> Result String EmailAddress +validateEmail text = + EmailAddress.fromString text + |> Result.fromMaybe + (if String.isEmpty text then + "Enter your email first" + + else + "Invalid email address" + ) + + +init : SigninForm +init = + EnterEmail + { email = "" + , pressedSubmitEmail = False + , rateLimited = False + } diff --git a/counter/src/MagicLink/Types.elm b/counter/src/MagicLink/Types.elm new file mode 100644 index 0000000..3e4787d --- /dev/null +++ b/counter/src/MagicLink/Types.elm @@ -0,0 +1,69 @@ +module MagicLink.Types exposing + ( EnterEmail_ + , EnterLoginCode_ + , FrontendMsg(..) + , Log + , LogItem(..) + , LoginCodeStatus(..) + , SignInStatus(..) + , SigninForm(..) + ) + +import Auth.Common +import Dict exposing (Dict) +import EmailAddress exposing (EmailAddress) +import Time +import User + + +type FrontendMsg + = SubmitEmailForSignIn + | AuthSigninRequested { methodId : Auth.Common.MethodId, email : Maybe String } + | ReceivedSigninCode String + | CancelSignIn + | CancelSignUp + | OpenSignUp + | TypedEmailInSignInForm String + | SubmitSignUp + | SignOut + | InputRealname String + | InputUsername String + | InputEmail String + + +type SigninForm + = EnterEmail EnterEmail_ + | EnterSigninCode EnterLoginCode_ + + +type SignInStatus + = NotSignedIn + | ErrorNotRegistered String + | SuccessfulRegistration String String + | SigningUp + | SignedIn + + +type LoginCodeStatus + = Checking + | NotValid + + +type LogItem + = LoginsRateLimited User.Id + | FailedToCreateLoginCode Int + + +type alias EnterEmail_ = + { email : String + , pressedSubmitEmail : Bool + , rateLimited : Bool + } + + +type alias EnterLoginCode_ = + { sentTo : EmailAddress, loginCode : String, attempts : Dict Int LoginCodeStatus } + + +type alias Log = + List ( Time.Posix, LogItem ) diff --git a/counter/src/Types.elm b/counter/src/Types.elm index 812f68f..8143a55 100644 --- a/counter/src/Types.elm +++ b/counter/src/Types.elm @@ -1,7 +1,6 @@ module Types exposing (..) import Lamdera exposing (ClientId, SessionId) -import Set exposing (Set) type alias BackendModel = diff --git a/counter/src/User.elm b/counter/src/User.elm new file mode 100644 index 0000000..f7aa8b2 --- /dev/null +++ b/counter/src/User.elm @@ -0,0 +1,77 @@ + module User exposing + ( EmailString + , Id + , LoginData + , Role(..) + , User + , Username + , loginDataOfUser + , setAsVerified + ) + +import Dict +import EmailAddress exposing (EmailAddress) +import Time + + +type alias User = + { id : String + , fullname : String + , username : String + , email : EmailAddress + , emailString : EmailString + , created_at : Time.Posix + , updated_at : Time.Posix + , roles : List Role + , verified : Maybe Time.Posix + , recentLoginEmails : List Time.Posix + } + + +verifyNow : Time.Posix -> User -> User +verifyNow now user = + case user.verified of + Just _ -> + user + + Nothing -> + { user | verified = Just now } + + +setAsVerified : Time.Posix -> User -> Dict.Dict EmailString User -> Dict.Dict EmailString User +setAsVerified now user users = + Dict.insert user.emailString (verifyNow now user) users + + +type alias Username = + String + + +type alias EmailString = + String + + +type alias LoginData = + { username : String + , email : EmailString + , name : String + , roles : List Role + } + + +loginDataOfUser : User -> LoginData +loginDataOfUser user = + { username = user.username + , roles = user.roles + , name = user.fullname + , email = user.emailString + } + + +type Role + = AdminRole + | UserRole + + +type alias Id = + String diff --git a/counter/vendor/elm-email/Email/Html.elm b/counter/vendor/elm-email/Email/Html.elm new file mode 100644 index 0000000..29b5774 --- /dev/null +++ b/counter/vendor/elm-email/Email/Html.elm @@ -0,0 +1,252 @@ +module Email.Html exposing + ( a, b, br, div, font, h1, h2, h3, h4, h5, h6, hr, img, label, li, node, ol, p, span, strong, table, td, text, th, tr, u, ul, Attribute, Html + , inlineGifImg, inlineJpgImg, inlinePngImg + , toHtml + ) + +{-| Only html tags that are supported by major all email clients are listed here. +If you need something not that's included (and potentially not universally supported) use [`node`](#node). + +These sources were used to determine what should be included: + + + + +Open an issue on github if something is missing or incorrectly included. + + +# Html tags + +@docs a, b, br, div, font, h1, h2, h3, h4, h5, h6, hr, img, label, li, node, ol, p, span, strong, table, td, text, th, tr, u, ul, Attribute, Html + + +# Inline images + +@docs inlineGifImg, inlineJpgImg, inlinePngImg + + +# Convert + +@docs toHtml + +-} + +import Bytes exposing (Bytes) +import Html +import Internal + + +{-| -} +type alias Html = + Internal.Html + + +{-| -} +type alias Attribute = + Internal.Attribute + + +{-| Convert a [`Email.Html.Html`](#Html) into normal a [`Html`](https://package.elm-lang.org/packages/elm/html/latest/Html). Useful if you want to preview your email content. +-} +toHtml : Html -> Html.Html msg +toHtml = + Internal.toHtml + + +{-| This allows you to create html tags not included in this module (at the risk of it not rendering correctly in some email clients). +-} +node : String -> List Attribute -> List Html -> Html +node = + Internal.Node + + +{-| -} +div : List Attribute -> List Html -> Html +div = + Internal.Node "div" + + +{-| -} +table : List Attribute -> List Html -> Html +table = + Internal.Node "table" + + +{-| -} +tr : List Attribute -> List Html -> Html +tr = + Internal.Node "tr" + + +{-| -} +td : List Attribute -> List Html -> Html +td = + Internal.Node "td" + + +{-| -} +th : List Attribute -> List Html -> Html +th = + Internal.Node "th" + + +{-| -} +br : List Attribute -> List Html -> Html +br = + Internal.Node "br" + + +{-| -} +hr : List Attribute -> List Html -> Html +hr = + Internal.Node "hr" + + +{-| -} +a : List Attribute -> List Html -> Html +a = + Internal.Node "a" + + +{-| -} +b : List Attribute -> List Html -> Html +b = + Internal.Node "b" + + +{-| -} +font : List Attribute -> List Html -> Html +font = + Internal.Node "font" + + +{-| -} +h1 : List Attribute -> List Html -> Html +h1 = + Internal.Node "h1" + + +{-| -} +h2 : List Attribute -> List Html -> Html +h2 = + Internal.Node "h2" + + +{-| -} +h3 : List Attribute -> List Html -> Html +h3 = + Internal.Node "h3" + + +{-| -} +h4 : List Attribute -> List Html -> Html +h4 = + Internal.Node "h4" + + +{-| -} +h5 : List Attribute -> List Html -> Html +h5 = + Internal.Node "h5" + + +{-| -} +h6 : List Attribute -> List Html -> Html +h6 = + Internal.Node "h6" + + +{-| -} +img : List Attribute -> List Html -> Html +img = + Internal.Node "img" + + +{-| -} +label : List Attribute -> List Html -> Html +label = + Internal.Node "label" + + +{-| -} +li : List Attribute -> List Html -> Html +li = + Internal.Node "li" + + +{-| -} +ol : List Attribute -> List Html -> Html +ol = + Internal.Node "ol" + + +{-| -} +p : List Attribute -> List Html -> Html +p = + Internal.Node "p" + + +{-| -} +span : List Attribute -> List Html -> Html +span = + Internal.Node "span" + + +{-| -} +strong : List Attribute -> List Html -> Html +strong = + Internal.Node "strong" + + +{-| -} +u : List Attribute -> List Html -> Html +u = + Internal.Node "u" + + +{-| -} +ul : List Attribute -> List Html -> Html +ul = + Internal.Node "ul" + + +{-| If you want to embed a png image within the email body, use this function. +The normal approach of using a base64 string as the image src doesn't always work with emails. +-} +inlinePngImg : Bytes -> List Attribute -> List Html -> Html +inlinePngImg content = + { content = content + , imageType = Internal.Png + } + |> Internal.InlineImage + + +{-| If you want to embed a jpg image within the email body, use this function. +The normal approach of using a base64 string as the image src doesn't always with emails. +-} +inlineJpgImg : Bytes -> List Attribute -> List Html -> Html +inlineJpgImg content = + { content = content + , imageType = Internal.Jpeg + } + |> Internal.InlineImage + + +{-| If you want to embed a gif within the email body, use this function. +The normal approach of using a base64 string as the image src doesn't always with emails. + +Note that [some email clients](https://www.caniemail.com/search/?s=gif) won't animate the gif. + +-} +inlineGifImg : Bytes -> List Attribute -> List Html -> Html +inlineGifImg content = + { content = content + , imageType = Internal.Gif + } + |> Internal.InlineImage + + +{-| -} +text : String -> Internal.Html +text = + Internal.TextNode diff --git a/counter/vendor/elm-email/Email/Html/Attributes.elm b/counter/vendor/elm-email/Email/Html/Attributes.elm new file mode 100644 index 0000000..3a27dcc --- /dev/null +++ b/counter/vendor/elm-email/Email/Html/Attributes.elm @@ -0,0 +1,282 @@ +module Email.Html.Attributes exposing (alt, attribute, backgroundColor, border, borderBottom, borderBottomColor, borderBottomStyle, borderBottomWidth, borderColor, borderLeft, borderLeftColor, borderLeftStyle, borderLeftWidth, borderRadius, borderRight, borderRightColor, borderRightStyle, borderRightWidth, borderStyle, borderTop, borderTopColor, borderWidth, color, fontFamily, fontSize, fontStyle, fontVariant, height, href, letterSpacing, lineHeight, padding, paddingBottom, paddingLeft, paddingRight, paddingTop, src, style, textAlign, verticalAlign, width) + +{-| Only html attributes that are supported by all major email clients are listed here. +If you need something not that's included (and potentially not universally supported) use [`attribute`](#attribute) or [`style`](#style). + +These sources were used to determine what should be included: + + + + +Open an issue on github if something is missing or incorrectly included. + + +# Attributes and styles + +@docs alt, attribute, backgroundColor, border, borderBottom, borderBottomColor, borderBottomStyle, borderBottomWidth, borderColor, borderLeft, borderLeftColor, borderLeftStyle, borderLeftWidth, borderRadius, borderRight, borderRightColor, borderRightStyle, borderRightWidth, borderStyle, borderTop, borderTopColor, borderWidth, color, fontFamily, fontSize, fontStyle, fontVariant, height, href, letterSpacing, lineHeight, padding, paddingBottom, paddingLeft, paddingRight, paddingTop, src, style, textAlign, verticalAlign, width + +-} + +import Internal exposing (Attribute(..)) + + +{-| Use this if there's a style you want to add that isn't present in this module. +Note that there's a risk that it isn't supported by some email clients. +-} +style : String -> String -> Attribute +style = + StyleAttribute + + +{-| Use this if there's a attribute you want to add that isn't present in this module. +Note that there's a risk that it isn't supported by some email clients. +-} +attribute : String -> String -> Attribute +attribute = + Attribute + + +{-| -} +backgroundColor : String -> Attribute +backgroundColor = + StyleAttribute "background-color" + + +{-| -} +border : String -> Attribute +border = + StyleAttribute "border" + + +{-| -} +borderRadius : String -> Attribute +borderRadius = + StyleAttribute "border-radius" + + +{-| -} +borderBottom : String -> Attribute +borderBottom = + StyleAttribute "border-bottom" + + +{-| -} +borderBottomColor : String -> Attribute +borderBottomColor = + StyleAttribute "border-bottom-color" + + +{-| -} +borderBottomStyle : String -> Attribute +borderBottomStyle = + StyleAttribute "border-bottom-style" + + +{-| -} +borderBottomWidth : String -> Attribute +borderBottomWidth = + StyleAttribute "border-bottom-width" + + +{-| -} +borderColor : String -> Attribute +borderColor = + StyleAttribute "border-color" + + +{-| -} +borderLeft : String -> Attribute +borderLeft = + StyleAttribute "border-left" + + +{-| -} +borderLeftColor : String -> Attribute +borderLeftColor = + StyleAttribute "border-left-color" + + +{-| -} +borderLeftStyle : String -> Attribute +borderLeftStyle = + StyleAttribute "border-left-style" + + +{-| -} +borderLeftWidth : String -> Attribute +borderLeftWidth = + StyleAttribute "border-left-width" + + +{-| -} +borderRight : String -> Attribute +borderRight = + StyleAttribute "border-right" + + +{-| -} +borderRightColor : String -> Attribute +borderRightColor = + StyleAttribute "border-right-color" + + +{-| -} +borderRightStyle : String -> Attribute +borderRightStyle = + StyleAttribute "border-right-style" + + +{-| -} +borderRightWidth : String -> Attribute +borderRightWidth = + StyleAttribute "border-right-width" + + +{-| -} +borderStyle : String -> Attribute +borderStyle = + StyleAttribute "border-style" + + +{-| -} +borderTop : String -> Attribute +borderTop = + StyleAttribute "border-top" + + +{-| -} +borderTopColor : String -> Attribute +borderTopColor = + StyleAttribute "border-top-color" + + +{-| -} +borderWidth : String -> Attribute +borderWidth = + StyleAttribute "border-width" + + +{-| -} +color : String -> Attribute +color = + StyleAttribute "color" + + +{-| -} +width : String -> Attribute +width = + StyleAttribute "width" + + +{-| -} +maxWidth : String -> Attribute +maxWidth = + StyleAttribute "max-width" + + +{-| -} +minWidth : String -> Attribute +minWidth = + StyleAttribute "min-width" + + +{-| -} +height : String -> Attribute +height = + StyleAttribute "height" + + +{-| -} +padding : String -> Attribute +padding = + StyleAttribute "padding" + + +{-| -} +paddingLeft : String -> Attribute +paddingLeft = + StyleAttribute "padding-left" + + +{-| -} +paddingRight : String -> Attribute +paddingRight = + StyleAttribute "padding-right" + + +{-| -} +paddingBottom : String -> Attribute +paddingBottom = + StyleAttribute "padding-bottom" + + +{-| -} +paddingTop : String -> Attribute +paddingTop = + StyleAttribute "padding-top" + + +{-| -} +lineHeight : String -> Attribute +lineHeight = + StyleAttribute "line-height" + + +{-| -} +fontSize : String -> Attribute +fontSize = + StyleAttribute "font-size" + + +{-| -} +fontFamily : String -> Attribute +fontFamily = + StyleAttribute "font-family" + + +{-| -} +fontStyle : String -> Attribute +fontStyle = + StyleAttribute "font-style" + + +{-| -} +fontVariant : String -> Attribute +fontVariant = + StyleAttribute "font-variant" + + +{-| -} +letterSpacing : String -> Attribute +letterSpacing = + StyleAttribute "letter-spacing" + + +{-| -} +textAlign : String -> Attribute +textAlign = + StyleAttribute "text-align" + + +{-| -} +src : String -> Attribute +src = + Attribute "src" + + +{-| -} +alt : String -> Attribute +alt = + Attribute "alt" + + +{-| -} +href : String -> Attribute +href = + Attribute "href" + + +{-| -} +verticalAlign : String -> Attribute +verticalAlign = + Attribute "vertical-align" diff --git a/counter/vendor/elm-email/EmailAddress.elm b/counter/vendor/elm-email/EmailAddress.elm new file mode 100644 index 0000000..94546ff --- /dev/null +++ b/counter/vendor/elm-email/EmailAddress.elm @@ -0,0 +1,178 @@ +module EmailAddress exposing (EmailAddress(..), fromString, toString) + +{-| + +@docs EmailAddress, fromString, toString + +-} + +-- This code is originally from bellroy/elm-email. I copied the implementation here in order to rename it to EmailAddress, normalize the contents (toLower all the strings), and make it an opaque type. + +import Parser exposing ((|.), (|=), Parser, Step(..), andThen, chompWhile, end, getChompedString, loop, map, oneOf, problem, run, succeed, symbol) + + +{-| The type of an email address +-} +type EmailAddress + = EmailAddress + { localPart : String + , tags : List String + , domain : String + , tld : List String + } + + +{-| Parse an email address from a String. +Note that this will also convert all the characters to lowercase. +This is done because email addresses are case insensitive. +If the email wasn't converted to all lowercase you could end up with this gotcha `Email.fromString a@a.com /= Email.fromString A@a.com` +-} +fromString : String -> Maybe EmailAddress +fromString string = + case run parseEmail string of + Ok result -> + result + + _ -> + Nothing + + +{-| Render Email to a String +-} +toString : EmailAddress -> String +toString (EmailAddress { localPart, tags, domain, tld }) = + String.join "" + [ localPart + , case tags of + [] -> + "" + + _ -> + "+" ++ String.join "+" tags + , "@" + , domain + , "." + , String.join "." tld + ] + + + +-- Parser + + +parseEmail : Parser (Maybe EmailAddress) +parseEmail = + let + split char parser = + loop [] + (\r -> + oneOf + [ succeed (\tld -> Loop (tld :: r)) + |. symbol (String.fromChar char) + |= parser + , succeed () + |> map (\_ -> Done (List.reverse r)) + ] + ) + in + succeed + (\localPart tags domain tlds -> + let + fullLocalPart = + String.join "" + [ localPart + , case tags of + [] -> + "" + + _ -> + "+" ++ String.join "+" tags + ] + in + if String.length fullLocalPart > 64 then + Nothing + + else if List.length tlds < 1 then + Nothing + + else + { localPart = String.toLower localPart + , tags = List.map String.toLower tags + , domain = String.toLower domain + , tld = List.map String.toLower tlds + } + |> EmailAddress + |> Just + ) + |= parseLocalPart + |= split '+' parseLocalPart + |. symbol "@" + |= parseDomain + |= split '.' parseTld + |. end + + +parseLocalPart : Parser String +parseLocalPart = + succeed () + |. chompWhile + (\a -> + (a /= '+') + && (a /= '@') + && (a /= '\\') + && (a /= '"') + ) + |> getChompedString + |> andThen + (\localPart -> + if String.startsWith "." localPart || String.endsWith "." localPart || String.indexes ".." localPart /= [] then + problem "localPart can't start or end with a dot, nor can there be double dots" + + else if String.trim localPart /= localPart then + problem "localPart can't be wrapped with whitespace" + + else + succeed localPart + ) + + +parseDomain : Parser String +parseDomain = + succeed () + |. chompWhile + (\a -> + (Char.isAlphaNum a + || (a == '-') + ) + && (a /= '@') + && (a /= '.') + ) + |> getChompedString + |> andThen + (\a -> + if String.length a < 1 then + problem "Domain has to be atleast 1 character long." + + else + succeed a + ) + + +parseTld : Parser String +parseTld = + succeed () + |. chompWhile + (\a -> + Char.isUpper a + || Char.isLower a + || (a == '-') + ) + |> getChompedString + |> andThen + (\a -> + if String.length a >= 2 then + succeed a + + else + problem "Tld needs to be at least 2 character long." + ) diff --git a/counter/vendor/elm-email/Internal.elm b/counter/vendor/elm-email/Internal.elm new file mode 100644 index 0000000..3ab5173 --- /dev/null +++ b/counter/vendor/elm-email/Internal.elm @@ -0,0 +1,306 @@ +module Internal exposing (Attribute(..), Html(..), ImageType(..), cid, imageExtension, inlineImageName, mimeType, toHtml, toString) + +import Bytes exposing (Bytes) +import Html +import Html.Attributes +import VendoredBase64 + + +type Html + = Node String (List Attribute) (List Html) + | InlineImage { content : Bytes, imageType : ImageType } (List Attribute) (List Html) + | TextNode String + + +type Attribute + = StyleAttribute String String + | Attribute String String + + +toHtml : Html -> Html.Html msg +toHtml html = + case html of + Node tagName attributes children -> + Html.node tagName (List.map toHtmlAttribute attributes) (List.map toHtml children) + + InlineImage { content, imageType } attributes children -> + Html.img + (Html.Attributes.src + ("data:" ++ mimeType imageType ++ ";base64," ++ Maybe.withDefault "" (VendoredBase64.fromBytes content)) + :: List.map toHtmlAttribute attributes + ) + (List.map toHtml children) + + TextNode text -> + Html.text text + + +toHtmlAttribute : Attribute -> Html.Attribute msg +toHtmlAttribute attribute = + case attribute of + StyleAttribute property value -> + Html.Attributes.style property value + + Attribute property value -> + Html.Attributes.attribute property value + + +type alias Acc = + { depth : Int + , stack : List ( String, List Html ) + , result : List String + , inlineImages : List ( String, { content : Bytes, imageType : ImageType } ) + } + + +toString : Html -> ( String, List ( String, { content : Bytes, imageType : ImageType } ) ) +toString html = + let + initialAcc : Acc + initialAcc = + { depth = 0 + , stack = [] + , result = [] + , inlineImages = [] + } + + { result, inlineImages } = + toStringHelper [ html ] initialAcc + in + ( result |> List.reverse |> String.concat, inlineImages ) + + +{-| Copied from hecrj/html-parser +-} +voidElements : List String +voidElements = + [ "area" + , "base" + , "br" + , "col" + , "embed" + , "hr" + , "img" + , "input" + , "link" + , "meta" + , "param" + , "source" + , "track" + , "wbr" + ] + + +toStringHelper : List Html -> Acc -> Acc +toStringHelper tags acc = + case tags of + [] -> + case acc.stack of + [] -> + acc + + ( tagName, cont ) :: rest -> + toStringHelper + cont + { acc + | result = closingTag tagName :: acc.result + , depth = acc.depth - 1 + , stack = rest + } + + (Node tagName attributes children) :: rest -> + if List.any ((==) tagName) voidElements && List.isEmpty children then + toStringHelper rest { acc | result = tag tagName attributes :: acc.result } + + else + toStringHelper + children + { acc + | result = tag tagName attributes :: acc.result + , depth = acc.depth + 1 + , stack = ( tagName, rest ) :: acc.stack + } + + (InlineImage { imageType, content } attributes children) :: rest -> + let + src = + inlineImageName (List.length acc.inlineImages) imageType + + inlineImages = + ( src, { content = content, imageType = imageType } ) :: acc.inlineImages + in + if List.isEmpty children then + toStringHelper + children + { acc + | result = tag "img" (Attribute "src" (cid src) :: attributes) :: acc.result + } + + else + toStringHelper + children + { acc + | result = tag "img" (Attribute "src" (cid src) :: attributes) :: acc.result + , depth = acc.depth + 1 + , stack = ( "img", rest ) :: acc.stack + , inlineImages = inlineImages + } + + (TextNode string) :: rest -> + toStringHelper + rest + { acc | result = escapeHtmlText string :: acc.result } + + +type ImageType + = Jpeg + | Png + | Gif + + +imageExtension : ImageType -> String +imageExtension imageType = + case imageType of + Jpeg -> + "jpeg" + + Png -> + "png" + + Gif -> + "gif" + + +mimeType : ImageType -> String +mimeType imageType = + "image/" ++ imageExtension imageType + + +inlineImageName : Int -> ImageType -> String +inlineImageName count imageType = + "inline-image" ++ String.fromInt count ++ "." ++ imageExtension imageType + + +cid : String -> String +cid filename = + "cid:" ++ filename + + +tag : String -> List Attribute -> String +tag tagName attributes = + "<" ++ String.join " " (tagName :: attributesToString attributes) ++ ">" + + +escapeHtmlText : String -> String +escapeHtmlText = + String.replace "&" "&" + >> String.replace "<" "<" + >> String.replace ">" ">" + + +attributesToString : List Attribute -> List String +attributesToString attrs = + let + ( classes, styles, regular ) = + List.foldl addAttribute ( [], [], [] ) attrs + in + regular + |> withClasses classes + |> withStyles styles + + +escapeStyle : String -> String +escapeStyle text = + String.toList text + |> List.map String.fromChar + |> List.map + (\char -> + case char of + "\"" -> + """ + + "&" -> + "&" + + _ -> + char + ) + |> String.concat + + +withClasses : List String -> List String -> List String +withClasses classes attrs = + case classes of + [] -> + attrs + + _ -> + buildProp "class" (String.join " " (List.map escapeStyle classes)) :: attrs + + +withStyles : List String -> List String -> List String +withStyles styles attrs = + case styles of + [] -> + attrs + + _ -> + buildProp "style" (String.join "; " (List.map escapeStyle styles)) :: attrs + + +type alias AttrAcc = + ( List String, List String, List String ) + + +buildProp : String -> String -> String +buildProp key value = + hyphenate key ++ "=\"" ++ escape value ++ "\"" + + +addAttribute : Attribute -> AttrAcc -> AttrAcc +addAttribute attribute ( classes, styles, attrs ) = + case attribute of + Attribute key value -> + ( classes, styles, buildProp key value :: attrs ) + + StyleAttribute key value -> + ( classes + , (escape key ++ ": " ++ escape value) :: styles + , attrs + ) + + +escape : String -> String +escape = + String.foldl + (\char acc -> + if char == '"' then + acc ++ "\\\"" + + else + acc ++ String.fromChar char + ) + "" + + +hyphenate : String -> String +hyphenate = + String.foldl + (\char acc -> + if Char.isUpper char then + acc ++ "-" ++ String.fromChar (Char.toLower char) + + else + acc ++ String.fromChar char + ) + "" + + +closingTag : String -> String +closingTag tagName = + "" + + +indent : Int -> Int -> String -> String +indent perLevel level x = + String.repeat (perLevel * level) " " ++ x diff --git a/counter/vendor/elm-email/Postmark.elm b/counter/vendor/elm-email/Postmark.elm new file mode 100644 index 0000000..13da248 --- /dev/null +++ b/counter/vendor/elm-email/Postmark.elm @@ -0,0 +1,223 @@ +module Postmark exposing + ( ApiKey + , PostmarkEmailBody(..) + , PostmarkSend + , PostmarkSendResponse + , PostmarkTemplateSend + --, SendEmailError + + , apiKey + , sendEmail + ) + +import Email.Html +import EmailAddress exposing (EmailAddress) +import Http +import Internal +import Json.Decode as D +import Json.Encode as E +import List.Nonempty +import String.Nonempty exposing (NonemptyString) +import Task exposing (Task) + + +endpoint = + "https://api.postmarkapp.com" + + +type ApiKey + = ApiKey String + + +{-| Create an API key from a raw string. +-} +apiKey : String -> ApiKey +apiKey apiKey_ = + ApiKey apiKey_ + + +type PostmarkEmailBody + = BodyHtml Email.Html.Html + | BodyText String + | BodyBoth Email.Html.Html String + + + +-- Plain send + + +type alias PostmarkSend = + { from : { name : String, email : EmailAddress } + , to : List.Nonempty.Nonempty { name : String, email : EmailAddress } + , subject : NonemptyString + , body : PostmarkEmailBody + , messageStream : String + } + + +sendEmailTask : ApiKey -> PostmarkSend -> Task Http.Error PostmarkSendResponse +sendEmailTask (ApiKey token) d = + let + httpBody = + Http.jsonBody <| + E.object <| + [ ( "From", E.string <| emailToString d.from ) + , ( "To", E.string <| emailsToString d.to ) + , ( "Subject", E.string <| String.Nonempty.toString d.subject ) + , ( "MessageStream", E.string d.messageStream ) + ] + ++ bodyToJsonValues d.body + in + Http.task + { method = "POST" + , headers = [ Http.header "X-Postmark-Server-Token" token ] + , url = endpoint ++ "/email" + , body = httpBody + , resolver = jsonResolver decodePostmarkSendResponse + , timeout = Nothing + } + + +sendEmail : (Result Http.Error PostmarkSendResponse -> msg) -> ApiKey -> PostmarkSend -> Cmd msg +sendEmail msg token d = + sendEmailTask token d |> Task.attempt msg + + +emailsToString : List.Nonempty.Nonempty { name : String, email : EmailAddress } -> String +emailsToString nonEmptyEmails = + nonEmptyEmails + |> List.Nonempty.toList + |> List.map emailToString + |> String.join ", " + + +emailToString : { name : String, email : EmailAddress } -> String +emailToString address = + if address.name == "" then + EmailAddress.toString address.email + + else + address.name ++ " <" ++ EmailAddress.toString address.email ++ ">" + + +type alias PostmarkSendResponse = + { to : String + , submittedAt : String + , messageId : String + , errorCode : Int + , message : String + } + + +type SendEmailError + = UnknownError { statusCode : Int, body : String } + | PostmarkError PostmarkSendResponse + | NetworkError + | Timeout + | BadUrl String + + +decodePostmarkSendResponse = + D.map5 PostmarkSendResponse + (D.field "To" D.string) + (D.field "SubmittedAt" D.string) + (D.field "MessageID" D.string) + (D.field "ErrorCode" D.int) + (D.field "Message" D.string) + + + +-- Template send + + +type alias PostmarkTemplateSend = + { token : String + , templateAlias : String + , templateModel : E.Value + , from : String + , to : String + , messageStream : String + } + + +sendTemplateEmail : PostmarkTemplateSend -> Task Http.Error PostmarkTemplateSendResponse +sendTemplateEmail d = + let + httpBody = + Http.jsonBody <| + E.object <| + [ ( "From", E.string d.from ) + , ( "To", E.string d.to ) + , ( "MessageStream", E.string d.messageStream ) + , ( "TemplateAlias", E.string d.templateAlias ) + , ( "TemplateModel", d.templateModel ) + ] + in + Http.task + { method = "POST" + , headers = [ Http.header "X-Postmark-Server-Token" d.token ] + , url = endpoint ++ "/email/withTemplate" + , body = httpBody + , resolver = jsonResolver decodePostmarkTemplateSendResponse + , timeout = Nothing + } + + +type alias PostmarkTemplateSendResponse = + { to : String + , submittedAt : String + , messageId : String + , errorCode : String + , message : String + } + + +decodePostmarkTemplateSendResponse = + D.map5 PostmarkTemplateSendResponse + (D.field "To" D.string) + (D.field "SubmittedAt" D.string) + (D.field "MessageID" D.string) + (D.field "ErrorCode" D.string) + (D.field "Message" D.string) + + + +-- Helpers + + +bodyToJsonValues : PostmarkEmailBody -> List ( String, E.Value ) +bodyToJsonValues body = + case body of + BodyHtml html -> + [ ( "HtmlBody", E.string <| Tuple.first <| Internal.toString html ) ] + + BodyText text -> + [ ( "TextBody", E.string text ) ] + + BodyBoth html text -> + [ ( "HtmlBody", E.string <| Tuple.first <| Internal.toString html ) + , ( "TextBody", E.string text ) + ] + + +jsonResolver : D.Decoder a -> Http.Resolver Http.Error a +jsonResolver decoder = + Http.stringResolver <| + \response -> + case response of + Http.GoodStatus_ _ body -> + D.decodeString decoder body + |> Result.mapError D.errorToString + |> Result.mapError Http.BadBody + + Http.BadUrl_ message -> + Err (Http.BadUrl message) + + Http.Timeout_ -> + Err Http.Timeout + + Http.NetworkError_ -> + Err Http.NetworkError + + Http.BadStatus_ metadata _ -> + Err (Http.BadStatus metadata.statusCode) diff --git a/counter/vendor/elm-email/SendGrid.elm b/counter/vendor/elm-email/SendGrid.elm new file mode 100644 index 0000000..3da5ff4 --- /dev/null +++ b/counter/vendor/elm-email/SendGrid.elm @@ -0,0 +1,510 @@ +module SendGrid exposing (ApiKey, apiKey, textEmail, htmlEmail, addCc, addBcc, addAttachments, sendEmail, sendEmailTask, Email, Error(..), ErrorMessage, ErrorMessage403) + +{-| + +@docs ApiKey, apiKey, textEmail, htmlEmail, addCc, addBcc, addAttachments, sendEmail, sendEmailTask, Email, Error, ErrorMessage, ErrorMessage403 + +-} + +import Bytes exposing (Bytes) +import Dict exposing (Dict) +import Email.Html +import EmailAddress exposing (EmailAddress) +import Http +import Internal +import Json.Decode as JD +import Json.Encode as JE +import List.Nonempty exposing (Nonempty) +import String.Nonempty exposing (NonemptyString) +import Task exposing (Task) +import VendoredBase64 + + +type Content + = TextContent NonemptyString + | HtmlContent String + + +type Disposition + = AttachmentDisposition + | Inline + + +encodeContent : Content -> JE.Value +encodeContent content = + case content of + TextContent text -> + JE.object [ ( "type", JE.string "text/plain" ), ( "value", encodeNonemptyString text ) ] + + HtmlContent html -> + JE.object [ ( "type", JE.string "text/html" ), ( "value", html |> JE.string ) ] + + +encodeEmailAddress : EmailAddress -> JE.Value +encodeEmailAddress = + EmailAddress.toString >> JE.string + + +encodeEmailAndName : { name : String, email : EmailAddress } -> JE.Value +encodeEmailAndName emailAndName = + JE.object [ ( "email", encodeEmailAddress emailAndName.email ), ( "name", JE.string emailAndName.name ) ] + + +encodePersonalization : ( Nonempty EmailAddress, List EmailAddress, List EmailAddress ) -> JE.Value +encodePersonalization ( to, cc, bcc ) = + let + addName = + List.map (\address -> { email = address, name = "" }) + + ccJson = + if List.isEmpty cc then + [] + + else + [ ( "cc", addName cc |> JE.list encodeEmailAndName ) ] + + bccJson = + if List.isEmpty bcc then + [] + + else + [ ( "bcc", addName bcc |> JE.list encodeEmailAndName ) ] + + toJson = + ( "to" + , to + |> List.Nonempty.map (\address -> { email = address, name = "" }) + |> encodeNonemptyList encodeEmailAndName + ) + in + JE.object (toJson :: ccJson ++ bccJson) + + +encodeNonemptyList : (a -> JE.Value) -> Nonempty a -> JE.Value +encodeNonemptyList encoder list = + List.Nonempty.toList list |> JE.list encoder + + +{-| Create an email that contains html. + + import Email + import Email.Html + import List.Nonempty + import String.Nonempty exposing (NonemptyString) + + {-| An email to be sent to a recipient's email address. + -} + email : Email.Email -> SendGrid.Email + email recipient = + SendGrid.htmlEmail + { subject = NonemptyString 'S' "ubject" + , to = List.Nonempty.fromElement recipient + , content = + Email.Html.div + [] + [ Email.Html.text "Hi!" ] + , nameOfSender = "test name" + , emailAddressOfSender = + -- this-can-be-anything@test.com + { localPart = "this-can-be-anything" + , tags = [] + , domain = "test" + , tld = [ "com" ] + } + } + +Note that email clients are quite limited in what html features are supported! +To avoid accidentally using html that's unsupported by some email clients, the `Email.Html` and `Email.Html.Attributes` modules only define tags and attributes with universal support. +You can still use `Email.Html.node` and `Email.Html.Attributes.attribute` if you want something that might not be universally supported though. + +-} +htmlEmail : + { subject : NonemptyString + , content : Email.Html.Html + , to : Nonempty EmailAddress + , nameOfSender : String + , emailAddressOfSender : EmailAddress + } + -> Email +htmlEmail config = + let + ( html, inlineImages ) = + Internal.toString config.content + in + Email + { subject = config.subject + , content = HtmlContent html + , to = config.to + , cc = [] + , bcc = [] + , nameOfSender = config.nameOfSender + , emailAddressOfSender = config.emailAddressOfSender + , attachments = + inlineImages + |> List.map + (Tuple.mapSecond + (\{ imageType, content } -> + { mimeType = Internal.mimeType imageType, content = content, disposition = Inline } + ) + ) + |> Dict.fromList + } + + +{-| Create an email that only contains plain text. + + import Email + import List.Nonempty + import String.Nonempty exposing (NonemptyString) + + {-| An email to be sent to a recipient's email address. + -} + email : Email.Email -> SendGrid.Email + email recipient = + SendGrid.textEmail + { subject = NonemptyString 'S' "ubject" + , to = List.Nonempty.fromElement recipient + , content = NonemptyString 'H' "i!" + , nameOfSender = "test name" + , emailAddressOfSender = + -- this-can-be-anything@test.com + { localPart = "this-can-be-anything" + , tags = [] + , domain = "test" + , tld = [ "com" ] + } + } + +-} +textEmail : + { subject : NonemptyString + , content : NonemptyString + , to : Nonempty EmailAddress + , nameOfSender : String + , emailAddressOfSender : EmailAddress + } + -> Email +textEmail config = + Email + { subject = config.subject + , content = TextContent config.content + , to = config.to + , cc = [] + , bcc = [] + , nameOfSender = config.nameOfSender + , emailAddressOfSender = config.emailAddressOfSender + , attachments = Dict.empty + } + + +{-| Add a list of [CC](https://en.wikipedia.org/wiki/Carbon_copy) recipients. +-} +addCc : List EmailAddress -> Email -> Email +addCc cc (Email email_) = + Email { email_ | cc = email_.cc ++ cc } + + +{-| Add a list of [BCC](https://en.wikipedia.org/wiki/Blind_carbon_copy) recipients. +-} +addBcc : List EmailAddress -> Email -> Email +addBcc bcc (Email email_) = + Email { email_ | bcc = email_.bcc ++ bcc } + + +{-| Attach files to the email. These will usually appear at the bottom of the email. + + import Bytes exposing (Bytes) + import SendGrid + + attachPngImage : String -> Bytes -> Email -> Email + attachPngImage name image email = + SendGrid.addAttachments + (Dict.fromList + [ ( name ++ ".png" + , { content = image + , mimeType = "image/png" + } + ) + ] + ) + email + +If you want to include an image file within the body of your email, use `Email.Html.inlinePngImg`, `Email.Html.inlineJpegImg`, or `Email.Html.inlineGifImg` instead. + +-} +addAttachments : Dict String { content : Bytes, mimeType : String } -> Email -> Email +addAttachments attachments (Email email_) = + Email + { email_ + | attachments = + Dict.union + (Dict.map + (\_ value -> { content = value.content, mimeType = value.mimeType, disposition = AttachmentDisposition }) + attachments + ) + email_.attachments + } + + +{-| -} +type Email + = Email + { subject : NonemptyString + , content : Content + , to : Nonempty EmailAddress + , cc : List EmailAddress + , bcc : List EmailAddress + , nameOfSender : String + , emailAddressOfSender : EmailAddress + , attachments : Dict String Attachment + } + + +type alias Attachment = + { content : Bytes + , mimeType : String + , disposition : Disposition + } + + +encodeDisposition : Disposition -> JE.Value +encodeDisposition disposition = + case disposition of + AttachmentDisposition -> + JE.string "attachment" + + Inline -> + JE.string "inline" + + +encodeAttachment : ( String, Attachment ) -> JE.Value +encodeAttachment ( filename, attachment ) = + JE.object + (( "content", VendoredBase64.fromBytes attachment.content |> Maybe.withDefault "" |> JE.string ) + :: ( "mimeType", JE.string attachment.mimeType ) + :: ( "filename", JE.string filename ) + :: ( "disposition", encodeDisposition attachment.disposition ) + :: (case attachment.disposition of + AttachmentDisposition -> + [] + + Inline -> + [ ( "content_id", JE.string filename ) ] + ) + ) + + +encodeNonemptyString : NonemptyString -> JE.Value +encodeNonemptyString nonemptyString = + String.Nonempty.toString nonemptyString |> JE.string + + +encodeSendEmail : Email -> JE.Value +encodeSendEmail (Email { content, subject, nameOfSender, emailAddressOfSender, to, cc, bcc, attachments }) = + let + attachmentsList = + Dict.toList attachments + in + JE.object + (( "subject", encodeNonemptyString subject ) + :: ( "content", JE.list encodeContent [ content ] ) + :: ( "personalizations", JE.list encodePersonalization [ ( to, cc, bcc ) ] ) + :: ( "from", encodeEmailAndName { name = nameOfSender, email = emailAddressOfSender } ) + :: (case attachmentsList of + _ :: _ -> + [ ( "attachments", JE.list encodeAttachment attachmentsList ) ] + + [] -> + [] + ) + ) + + +{-| A SendGrid API key. In order to send an email you must have one of these (see the readme for how to get one). +-} +type ApiKey + = ApiKey String + + +{-| Create an API key from a raw string (see the readme for how to get one). +-} +apiKey : String -> ApiKey +apiKey apiKey_ = + ApiKey apiKey_ + + +{-| Send an email using the SendGrid API. +-} +sendEmail : (Result Error () -> msg) -> ApiKey -> Email -> Cmd msg +sendEmail msg (ApiKey apiKey_) email_ = + Http.request + { method = "POST" + , headers = [ Http.header "Authorization" ("Bearer " ++ apiKey_) ] + , url = sendGridApiUrl + , body = encodeSendEmail email_ |> Http.jsonBody + , expect = + Http.expectStringResponse msg + (\response -> + case response of + Http.BadUrl_ url -> + BadUrl url |> Err + + Http.Timeout_ -> + Err Timeout + + Http.NetworkError_ -> + Err NetworkError + + Http.BadStatus_ metadata body -> + decodeBadStatus metadata body |> Err + + Http.GoodStatus_ _ _ -> + Ok () + ) + , timeout = Nothing + , tracker = Nothing + } + + +{-| Send an email using the SendGrid API. This is the task version of [sendEmail](#sendEmail). +-} +sendEmailTask : ApiKey -> Email -> Task Error () +sendEmailTask (ApiKey apiKey_) email_ = + Http.task + { method = "POST" + , headers = [ Http.header "Authorization" ("Bearer " ++ apiKey_) ] + , url = sendGridApiUrl + , body = encodeSendEmail email_ |> Http.jsonBody + , resolver = + Http.stringResolver + (\response -> + case response of + Http.BadUrl_ url -> + BadUrl url |> Err + + Http.Timeout_ -> + Err Timeout + + Http.NetworkError_ -> + Err NetworkError + + Http.BadStatus_ metadata body -> + decodeBadStatus metadata body |> Err + + Http.GoodStatus_ _ _ -> + Ok () + ) + , timeout = Nothing + } + + +sendGridApiUrl = + "https://api.sendgrid.com/v3/mail/send" + + +decodeBadStatus : Http.Metadata -> String -> Error +decodeBadStatus metadata body = + let + toErrorCode : (a -> Error) -> Result e a -> Error + toErrorCode errorCode result = + case result of + Ok value -> + errorCode value + + Err _ -> + UnknownError { statusCode = metadata.statusCode, body = body } + in + case metadata.statusCode of + 400 -> + JD.decodeString codecErrorResponse body |> toErrorCode StatusCode400 + + 401 -> + JD.decodeString codecErrorResponse body |> toErrorCode StatusCode401 + + 403 -> + JD.decodeString codec403ErrorResponse body |> toErrorCode StatusCode403 + + 413 -> + JD.decodeString codecErrorResponse body |> toErrorCode StatusCode413 + + _ -> + UnknownError { statusCode = metadata.statusCode, body = body } + + +{-| Possible error codes we might get back when trying to send an email. +Some are just normal HTTP errors and others are specific to the SendGrid API. +-} +type Error + = StatusCode400 (List ErrorMessage) + | StatusCode401 (List ErrorMessage) + | StatusCode403 { errors : List ErrorMessage403, id : Maybe String } + | StatusCode413 (List ErrorMessage) + | UnknownError { statusCode : Int, body : String } + | NetworkError + | Timeout + | BadUrl String + + +{-| The content of a generic SendGrid error. +-} +type alias ErrorMessage = + { field : Maybe String + , message : String + , errorId : Maybe String + } + + +codecErrorResponse : JD.Decoder (List ErrorMessage) +codecErrorResponse = + JD.field "errors" (JD.list codecErrorMessage) + + +{-| The content of a 403 status code error. +-} +type alias ErrorMessage403 = + { message : Maybe String + , field : Maybe String + , help : Maybe String + } + + +codec403Error : JD.Decoder ErrorMessage403 +codec403Error = + JD.map3 ErrorMessage403 + (optionalField "message" JD.string) + (optionalField "field" JD.string) + (optionalField "help" (JD.value |> JD.map (JE.encode 0))) + + +codec403ErrorResponse : JD.Decoder { errors : List ErrorMessage403, id : Maybe String } +codec403ErrorResponse = + JD.map2 (\errors id -> { errors = errors |> Maybe.withDefault [], id = id }) + (optionalField "errors" (JD.list codec403Error)) + (optionalField "id" JD.string) + + +codecErrorMessage : JD.Decoder ErrorMessage +codecErrorMessage = + JD.map3 ErrorMessage + (optionalField "field" JD.string) + (JD.field "message" JD.string) + (optionalField "error_id" JD.string) + + +{-| Borrowed from elm-community/json-extra +-} +optionalField : String -> JD.Decoder a -> JD.Decoder (Maybe a) +optionalField fieldName decoder = + let + finishDecoding json = + case JD.decodeValue (JD.field fieldName JD.value) json of + Ok val -> + -- The field is present, so run the decoder on it. + JD.map Just (JD.field fieldName decoder) + + Err _ -> + -- The field was missing, which is fine! + JD.succeed Nothing + in + JD.value + |> JD.andThen finishDecoding diff --git a/counter/vendor/elm-email/VendoredBase64.elm b/counter/vendor/elm-email/VendoredBase64.elm new file mode 100644 index 0000000..330bab2 --- /dev/null +++ b/counter/vendor/elm-email/VendoredBase64.elm @@ -0,0 +1,548 @@ +module VendoredBase64 exposing (fromBytes, toBytes) + +{-| Vendored from + + +# Conversion + +@docs fromBytes, toBytes + +-} + +import Bitwise +import Bytes exposing (Bytes, Endianness(..)) +import Bytes.Decode as Decode +import Bytes.Encode as Encode exposing (Encoder) + + +{-| Convert a Base64 string to bytes. +If you want more control over the process, you should use [`encoder`](#encoder). + +This function fails (returns `Nothing`) if you give it an invalid Base64 sequence. + +-} +toBytes : String -> Maybe Bytes +toBytes string = + Maybe.map Encode.encode (encoder string) + + +encoder : String -> Maybe Encode.Encoder +encoder string = + encodeChunks string [] + |> Maybe.map (List.reverse >> Encode.sequence) + + +{-| Big picture: + + - read 4 base64 characters + - convert them to 3 bytes (24 bits) + - encode these bytes + +-} +encodeChunks : String -> List Encoder -> Maybe (List Encoder) +encodeChunks input accum = + {- Performance Note + + slice and toList is just as fast as (possibly a little faster than) repeated `String.uncons`, + but this code is much more readable + -} + case String.toList (String.left 4 input) of + [] -> + Just accum + + [ a, b, c, d ] -> + case encodeCharacters a b c d of + Just enc -> + encodeChunks (String.dropLeft 4 input) (enc :: accum) + + Nothing -> + Nothing + + [ a, b, c ] -> + case encodeCharacters a b c '=' of + Nothing -> + Nothing + + Just enc -> + Just (enc :: accum) + + [ a, b ] -> + case encodeCharacters a b '=' '=' of + Nothing -> + Nothing + + Just enc -> + Just (enc :: accum) + + _ -> + Nothing + + +{-| Convert 4 characters to 24 bits (as an Encoder) +-} +encodeCharacters : Char -> Char -> Char -> Char -> Maybe Encoder +encodeCharacters a b c d = + {- Performance notes + + We use bitshifts and other bitwise operators here. They are much faster than the alternatives. + This may not normally matter but this function is called a lot so even small increases + in efficiency are noticable + + Secondly, we combine two `uint8` into one `uint16 BE`. This has no direct speed benefit + (elm/bytes uses a DataView, which only natively supports adding/reading uint8) + but having fewer list items decreases # of encoding steps and allocation, + and is therefore faster. + -} + if isValidChar a && isValidChar b then + let + n1 = + unsafeConvertChar a + + n2 = + unsafeConvertChar b + in + -- `=` is the padding character, and must be special-cased + -- only the `c` and `d` char are allowed to be padding + case d of + '=' -> + case c of + '=' -> + let + n = + Bitwise.or + (Bitwise.shiftLeftBy 18 n1) + (Bitwise.shiftLeftBy 12 n2) + + b1 = + -- masking higher bits is not needed, Encode.unsignedInt8 ignores higher bits + Bitwise.shiftRightBy 16 n + in + Just (Encode.unsignedInt8 b1) + + _ -> + if isValidChar c then + let + n3 = + unsafeConvertChar c + + n = + Bitwise.or + (Bitwise.or (Bitwise.shiftLeftBy 18 n1) (Bitwise.shiftLeftBy 12 n2)) + (Bitwise.shiftLeftBy 6 n3) + + combined = + Bitwise.shiftRightBy 8 n + in + Just (Encode.unsignedInt16 BE combined) + + else + Nothing + + _ -> + if isValidChar c && isValidChar d then + let + n3 = + unsafeConvertChar c + + n4 = + unsafeConvertChar d + + n = + Bitwise.or + (Bitwise.or (Bitwise.shiftLeftBy 18 n1) (Bitwise.shiftLeftBy 12 n2)) + (Bitwise.or (Bitwise.shiftLeftBy 6 n3) n4) + + b3 = + -- Masking the higher bits is not needed: Encode.unsignedInt8 ignores higher bits + n + + combined = + Bitwise.shiftRightBy 8 n + in + Just + (Encode.sequence + [ Encode.unsignedInt16 BE combined + , Encode.unsignedInt8 b3 + ] + ) + + else + Nothing + + else + Nothing + + +{-| is the character a base64 digit? + +The base16 digits are: A-Z, a-z, 0-1, '+' and '/' + +-} +isValidChar : Char -> Bool +isValidChar c = + if Char.isAlphaNum c then + True + + else + case c of + '+' -> + True + + '/' -> + True + + _ -> + False + + +{-| Convert a base64 character/digit to its index + +See also [Wikipedia](https://en.wikipedia.org/wiki/Base64#Base64_table) + +-} +unsafeConvertChar : Char -> Int +unsafeConvertChar char = + {- Performance Note + + Working with the key directly is faster than using e.g. `Char.isAlpha` and `Char.isUpper` + -} + let + key = + Char.toCode char + in + if key >= 65 && key <= 90 then + -- A-Z + key - 65 + + else if key >= 97 && key <= 122 then + -- a-z + (key - 97) + 26 + + else if key >= 48 && key <= 57 then + -- 0-9 + (key - 48) + 26 + 26 + + else + case char of + '+' -> + 62 + + '/' -> + 63 + + _ -> + -1 + + +{-| Convert bytes to a Base64 string. +If you want more control over the process, you should use [`decoder`](#decoder). + +This function should never return `Nothing`, but it uses +[`Bytes.Decode.decode`](https://package.elm-lang.org/packages/elm/bytes/latest/Bytes-Decode#decode), +which returns a `Maybe String`. + +-} +fromBytes : Bytes -> Maybe String +fromBytes bytes = + Decode.decode (decoder (Bytes.width bytes)) bytes + + +decoder : Int -> Decode.Decoder String +decoder width = + Decode.loop { remaining = width, string = "" } loopHelp + + + +-- INTERNALS + + +{-| Base64 uses 6 bits per digit (because 2^6 == 64) +and can nicely store 4 digits in 24 bits, which are 3 bytes. + +The decoding process is thus roughly: + + - read a 3-byte chunk + - extract the 4 6-bit segments + - convert those segments into characters + +But the input does not need to have a multiple of 4 characters, +so at the end of the string some characters can be omitted. +This means there may be 2 or 1 bytes remaining at the end. We have to cover those cases! + +-} +loopHelp : { remaining : Int, string : String } -> Decode.Decoder (Decode.Step { remaining : Int, string : String } String) +loopHelp { remaining, string } = + if remaining >= 18 then + -- Note: this case is heavily optimized. + -- For the general idea of what this function does, the `remaining >= 3` case is more illustrative. + decode18Bytes + |> Decode.map + (\result -> + Decode.Loop + { remaining = remaining - 18 + , string = string ++ result + } + ) + + else if remaining >= 3 then + let + helper a b c = + let + combined = + Bitwise.or (Bitwise.or (Bitwise.shiftLeftBy 16 a) (Bitwise.shiftLeftBy 8 b)) c + in + Decode.Loop + { remaining = remaining - 3 + , string = string ++ bitsToChars combined 0 + } + in + Decode.map3 helper + Decode.unsignedInt8 + Decode.unsignedInt8 + Decode.unsignedInt8 + + else if remaining == 0 then + Decode.succeed (Decode.Done string) + + else if remaining == 2 then + let + helper a b = + let + combined = + Bitwise.or (Bitwise.shiftLeftBy 16 a) (Bitwise.shiftLeftBy 8 b) + in + Decode.Done (string ++ bitsToChars combined 1) + in + Decode.map2 helper + Decode.unsignedInt8 + Decode.unsignedInt8 + + else + -- remaining == 1 + Decode.map (\a -> Decode.Done (string ++ bitsToChars (Bitwise.shiftLeftBy 16 a) 2)) + Decode.unsignedInt8 + + +{-| Mask that can be used to get the lowest 6 bits of a binary number +-} +lowest6BitsMask : Int +lowest6BitsMask = + 63 + + +{-| Turn the decoded bits (at most 24, can be fewer because of padding) into 4 base64 characters. + +(- - - - - - - -)(- - - - - - - -)(- - - - - - - -) +(- - - - - -|- - - - - -|- - - - - -|- - - - - -) + +-} +bitsToChars : Int -> Int -> String +bitsToChars bits missing = + {- Performance Notes + + `String.cons` proved to be the fastest way of combining characters into a string + see also https://github.com/danfishgold/base64-bytes/pull/3#discussion_r342321940 + + The input is 24 bits, which we have to partition into 4 6-bit segments. We achieve this by + shifting to the right by (a multiple of) 6 to remove unwanted bits on the right, then `Bitwise.and` + with `0b111111` (which is 2^6 - 1 or 63) (so, 6 1s) to remove unwanted bits on the left. + + -} + let + -- any 6-bit number is a valid base64 digit, so this is actually safe + p = + unsafeToChar (Bitwise.shiftRightZfBy 18 bits) + + q = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 12 bits) lowest6BitsMask) + + r = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 6 bits) lowest6BitsMask) + + s = + unsafeToChar (Bitwise.and bits lowest6BitsMask) + in + case missing of + -- case `0` is the most common, so put it first. + 0 -> + String.cons p (String.cons q (String.cons r (String.fromChar s))) + + 1 -> + String.cons p (String.cons q (String.cons r "=")) + + 2 -> + String.cons p (String.cons q "==") + + _ -> + "" + + +{-| Base64 index to character/digit +-} +unsafeToChar : Int -> Char +unsafeToChar n = + if n <= 25 then + -- uppercase characters + Char.fromCode (65 + n) + + else if n <= 51 then + -- lowercase characters + Char.fromCode (97 + (n - 26)) + + else if n <= 61 then + -- digit characters + Char.fromCode (48 + (n - 52)) + + else + -- special cases + case n of + 62 -> + '+' + + 63 -> + '/' + + _ -> + '\u{0000}' + + + +-- OPTIMIZED VERSION + + +u32BE : Decode.Decoder Int +u32BE = + Decode.unsignedInt32 Bytes.BE + + +u16BE : Decode.Decoder Int +u16BE = + Decode.unsignedInt16 Bytes.BE + + +{-| A specialized version reading 18 bytes at once +To get a better understanding of what this code does, read the `remainder >= 3` case above. + +This tries to take the biggest step possible within a `Decode.loop` iteration. +The idea is similar to loop-unrolling in languages like c: avoiding jumps gives better performance + +But `Decode.loop` also requires that the accumulator is wrapped in a `Step a b`, i.e. it allocates a `Decode.Loop _` +for every iteration. Allocation is expensive in tight loops like this one. So there is a double reason to limit the number +of iterations: avoiding jumps and avoiding allocation. + +Given that `Decode.map5` is the highest one defined by `elm/bytes` and we need a multiple of 3 bytes, +`4 * 4 + 2 = 18` is the best we can do. + +-} +decode18Bytes : Decode.Decoder String +decode18Bytes = + Decode.map5 decode18Help + u32BE + u32BE + u32BE + u32BE + u16BE + + +{-| Get 18 bytes (4 times 32-bit, one 16-bit) and split them into 3-byte chunks. + +Then convert the 3-byte chunks to characters and produce a string. + +-} +decode18Help : Int -> Int -> Int -> Int -> Int -> String +decode18Help a b c d e = + let + combined1 = + Bitwise.shiftRightZfBy 8 a + + combined2 = + Bitwise.or + (Bitwise.and 0xFF a |> Bitwise.shiftLeftBy 16) + (Bitwise.shiftRightZfBy 16 b) + + combined3 = + Bitwise.or + (Bitwise.and 0xFFFF b |> Bitwise.shiftLeftBy 8) + (Bitwise.shiftRightZfBy 24 c) + + combined4 = + Bitwise.and 0x00FFFFFF c + + combined5 = + Bitwise.shiftRightZfBy 8 d + + combined6 = + Bitwise.or + (Bitwise.and 0xFF d |> Bitwise.shiftLeftBy 16) + e + in + -- the order is counter-intuitive because `String.cons` is used in bitsToCharSpecialized. + "" + |> bitsToCharSpecialized combined6 combined5 combined4 + |> bitsToCharSpecialized combined3 combined2 combined1 + + +{-| A specialized version of bitsToChar that handles 3 24-bit integers at once. + +This was done to limit the number of function calls. When doing bitwise manipulations (which are very efficient), the +overhead of function calls -- something we normally don't really think about -- starts to matter. + +-} +bitsToCharSpecialized : Int -> Int -> Int -> String -> String +bitsToCharSpecialized bits1 bits2 bits3 accum = + let + -- BITS 1 + p = + unsafeToChar (Bitwise.shiftRightZfBy 18 bits1) + + q = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 12 bits1) lowest6BitsMask) + + r = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 6 bits1) lowest6BitsMask) + + s = + unsafeToChar (Bitwise.and bits1 lowest6BitsMask) + + -- BITS 2 + a = + unsafeToChar (Bitwise.shiftRightZfBy 18 bits2) + + b = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 12 bits2) lowest6BitsMask) + + c = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 6 bits2) lowest6BitsMask) + + d = + unsafeToChar (Bitwise.and bits2 lowest6BitsMask) + + -- BITS 3 + x = + unsafeToChar (Bitwise.shiftRightZfBy 18 bits3) + + y = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 12 bits3) lowest6BitsMask) + + z = + unsafeToChar (Bitwise.and (Bitwise.shiftRightZfBy 6 bits3) lowest6BitsMask) + + w = + unsafeToChar (Bitwise.and bits3 lowest6BitsMask) + in + -- Performance: This is the fastest way to create a string from characters. + -- see also https://github.com/danfishgold/base64-bytes/pull/3#discussion_r342321940 + -- cons adds on the left, so characters are added in reverse order. + accum + |> String.cons s + |> String.cons r + |> String.cons q + |> String.cons p + |> String.cons d + |> String.cons c + |> String.cons b + |> String.cons a + |> String.cons w + |> String.cons z + |> String.cons y + |> String.cons x diff --git a/preview/src/ReviewConfig.elm b/preview/src/ReviewConfig.elm index 51b0ade..060df81 100644 --- a/preview/src/ReviewConfig.elm +++ b/preview/src/ReviewConfig.elm @@ -41,11 +41,11 @@ config = , Install.FieldInTypeAlias.makeRule "Types" "FrontendModel" "currentUserData : Maybe User.LoginData" -- Type Frontend, User , Install.FieldInTypeAlias.makeRule "Types" "FrontendModel" "currentUser : Maybe User.User" - , Install.FieldInTypeAlias.makeRule "Types" "FrontendModel" "signInState : SignInState" -- Need to add this type (OR CHANGE CODE) + , Install.FieldInTypeAlias.makeRule "Types" "FrontendModel" "signInState : SignInState" , Install.FieldInTypeAlias.makeRule "Types" "FrontendModel" "realname : String" , Install.FieldInTypeAlias.makeRule "Types" "FrontendModel" "username : String" , Install.FieldInTypeAlias.makeRule "Types" "FrontendModel" "email : String" - -- Type Backend + -- Type BackendModel , Install.FieldInTypeAlias.makeRule "Types" "BackendModel" "pendingAuths : Dict Lamdera.SessionId Auth.Common.PendingAuth" , Install.FieldInTypeAlias.makeRule "Types" "BackendModel" "pendingEmailAuths : Dict Lamdera.SessionId Auth.Common.PendingEmailAuth" , Install.FieldInTypeAlias.makeRule "Types" "BackendModel" "sessions : Dict SessionId Auth.Common.UserInfo" @@ -56,11 +56,27 @@ config = , Install.FieldInTypeAlias.makeRule "Types" "BackendModel" "users: Dict.Dict User.EmailString User.User" , Install.FieldInTypeAlias.makeRule "Types" "BackendModel" "userNameToEmailString : Dict.Dict User.Username User.EmailString" , Install.FieldInTypeAlias.makeRule "Types" "BackendModel" "sessionInfo : Session.SessionInfo" - -- EXPERIMENTAL - , Install.Type.makeRule "Frontend" "Magic" [ "Inactive", "Wizard String", "Spell String Int"] + -- Type ToBackend + , Install.TypeVariant.makeRule "Types" "ToBackend" "AuthToBackend Auth.Common.ToBackend" + , Install.TypeVariant.makeRule "Types" "ToBackend" "AddUser String String String" + , Install.TypeVariant.makeRule "Types" "ToBackend" "RequestSignup String String String" + -- Type BackendMsg + , Install.TypeVariant.makeRule "Types" "BackendMsg" "AuthBackendMsg Auth.Common.BackendMsg" + , Install.TypeVariant.makeRule "Types" "BackendMsg" "AutoLogin SessionId User.LoginData" + -- Type ToFrontend + , Install.TypeVariant.makeRule "Types" "ToFrontend" "AuthToFrontend Auth.Common.ToFrontend" + , Install.TypeVariant.makeRule "Types" "ToFrontend" "AuthSuccess Auth.Common.UserInfo" + , Install.TypeVariant.makeRule "Types" "ToFrontend" "UserInfoMsg (Maybe Auth.Common.UserInfo)" + , Install.TypeVariant.makeRule "Types" "ToFrontend" "CheckSignInResponse (Result BackendDataStatus User.LoginData)" + , Install.TypeVariant.makeRule "Types" "ToFrontend" "GetLoginTokenRateLimited" + , Install.TypeVariant.makeRule "Types" "ToFrontend" "RegistrationError String" + , Install.TypeVariant.makeRule "Types" "ToFrontend" "SignInError String" + , Install.TypeVariant.makeRule "Types" "ToFrontend" "UserSignedIn (Maybe User.User)" ] + + viewFunction = """view model = Html.div [ style "padding" "50px" ]