From a395bc415a8bbbf01863ffdae989e653e3ca6a31 Mon Sep 17 00:00:00 2001 From: Steven Vandevelde Date: Tue, 20 Aug 2019 19:00:11 +0200 Subject: [PATCH] Add ability to not use encryption --- src/Applications/Brain.elm | 11 ++++ src/Applications/UI.elm | 65 +++++++++---------- src/Applications/UI/Authentication.elm | 90 +++++++++++++------------- src/Applications/UI/Notifications.elm | 2 +- src/Applications/UI/Reply.elm | 1 - src/Javascript/Workers/Brain/user.js | 31 ++++++--- src/Javascript/Workers/brain.js | 20 ++---- src/Javascript/crypto.js | 9 --- src/Library/Alien.elm | 4 ++ src/Library/User/Layer.elm | 1 + 10 files changed, 118 insertions(+), 116 deletions(-) diff --git a/src/Applications/Brain.elm b/src/Applications/Brain.elm index b6b40ea4..1eb42d45 100644 --- a/src/Applications/Brain.elm +++ b/src/Applications/Brain.elm @@ -134,6 +134,7 @@ type Msg ----------------------------------------- -- User layer #2 ----------------------------------------- + | RemoveEncryptionKey | SaveHypaethralDataSlowly (Debouncer.Msg HypaethralBit) | SaveHypaethralData HypaethralBit @@ -247,6 +248,13 @@ update msg model = ----------------------------------------- -- User layer #2 ----------------------------------------- + RemoveEncryptionKey -> + Alien.AuthSecretKey + |> Alien.trigger + |> Brain.Ports.removeCache + |> returnWithModel model + |> andThen saveAllHypaethralData + SaveHypaethralDataSlowly debouncerMsg -> Return3.wieldNested update @@ -542,6 +550,9 @@ translateAlienData tag data = Alien.RedirectToBlockstackSignIn -> Cmd (Brain.Ports.redirectToBlockstackSignIn ()) + Alien.RemoveEncryptionKey -> + RemoveEncryptionKey + Alien.RemoveTracksBySourceId -> data |> Json.decodeValue Json.string diff --git a/src/Applications/UI.elm b/src/Applications/UI.elm index 726d5c82..6fb5f000 100644 --- a/src/Applications/UI.elm +++ b/src/Applications/UI.elm @@ -258,9 +258,9 @@ type Msg -- Authentication ----------------------------------------- | AuthenticationBootFailure String + | MissingSecretKey Json.Decode.Value | NotAuthenticated | RemoteStorageWebfinger RemoteStorage.Attributes (Result Http.Error String) - | SyncUserData ----------------------------------------- -- Children ----------------------------------------- @@ -389,19 +389,17 @@ update msg model = SetIsOnline False -> -- The app went offline, cache everything -- (if caching is supported). - (case model.authentication of + ( { model | isOnline = False } + , case model.authentication of Authentication.Authenticated (Dropbox _) -> - saveAllHypaethralData { sync = True } + Ports.toBrain (Alien.trigger Alien.SyncHypaethralData) Authentication.Authenticated (RemoteStorage _) -> - saveAllHypaethralData { sync = True } + Ports.toBrain (Alien.trigger Alien.SyncHypaethralData) _ -> - identity + Cmd.none ) - ( { model | isOnline = False } - , Cmd.none - ) SetIsOnline True -> andThen @@ -409,10 +407,10 @@ update msg model = -- If we're back online again, sync all the user's data. (case model.authentication of Authentication.Authenticated (Dropbox _) -> - update SyncUserData + syncHypaethralData Authentication.Authenticated (RemoteStorage _) -> - update SyncUserData + syncHypaethralData _ -> return @@ -507,6 +505,13 @@ update msg model = |> showNotification (Notifications.error err) |> andThen (translateReply LoadDefaultBackdrop) + MissingSecretKey json -> + "There seems to be existing data that's encrypted, I will need the passphrase (ie. encryption key) to continue." + |> ShowErrorNotification + |> translateReplyWithModel model + |> andThen (translateReply <| Reply.LoadDefaultBackdrop) + |> andThen (translateReply <| Reply.ToggleLoadingScreen Off) + NotAuthenticated -> -- This is the message we get when the app initially -- finds out we're not authenticated. @@ -547,12 +552,6 @@ update msg model = |> Notifications.error |> showNotificationWithModel model - SyncUserData -> - "Syncing" - |> Notifications.warning - |> showNotificationWithModel model - |> saveAllHypaethralData { sync = True } - ----------------------------------------- -- Children ----------------------------------------- @@ -674,7 +673,7 @@ update msg model = ----------------------------- -- Save all the imported data ----------------------------- - |> saveAllHypaethralData { sync = False } + |> saveAllHypaethralData ----------------------------------------- -- Notifications @@ -861,6 +860,14 @@ showNotificationWithModel model notification = showNotification notification model +syncHypaethralData : Model -> Return Model Msg +syncHypaethralData model = + "Syncing" + |> Notifications.warning + |> showNotificationWithModel model + |> addCommand (Ports.toBrain <| Alien.trigger Alien.SyncHypaethralData) + + updateTracksModel : (Tracks.Model -> Tracks.Model) -> Model -> Model updateTracksModel fn model = { model | tracks = fn model.tracks } @@ -1539,7 +1546,7 @@ translateReply reply model = |> Demo.tape |> LoadHypaethralUserData |> updateWithModel model - |> saveAllHypaethralData { sync = False } + |> saveAllHypaethralData LoadDefaultBackdrop -> Backdrop.Default @@ -1614,15 +1621,9 @@ translateReply reply model = |> Ports.toBrain |> returnWithModel model - SaveTracksFromBrain -> - Alien.SaveTracks - |> Alien.trigger - |> Ports.toBrain - |> returnWithModel model - -saveAllHypaethralData : { sync : Bool } -> Return Model Msg -> Return Model Msg -saveAllHypaethralData { sync } return = +saveAllHypaethralData : Return Model Msg -> Return Model Msg +saveAllHypaethralData return = List.foldl (\( _, bit ) -> case bit of @@ -1642,11 +1643,7 @@ saveAllHypaethralData { sync } return = andThen (translateReply SaveSources) Tracks -> - if sync then - andThen (translateReply SaveTracksFromBrain) - - else - andThen (translateReply SaveTracks) + andThen (translateReply SaveTracks) ) return hypaethralBit.list @@ -1758,11 +1755,7 @@ translateAlienData event = LoadHypaethralUserData event.data Just Alien.MissingSecretKey -> - event.data - |> Json.Decode.decodeValue (Json.Decode.field "alienMethodTag" Alien.tagDecoder) - |> Result.map (\tag -> Authentication.MissingSecretKey tag event.data) - |> Result.map AuthenticationMsg - |> Result.withDefault Bypass + MissingSecretKey event.data Just Alien.NotAuthenticated -> NotAuthenticated diff --git a/src/Applications/UI/Authentication.elm b/src/Applications/UI/Authentication.elm index 72614535..2d152e55 100644 --- a/src/Applications/UI/Authentication.elm +++ b/src/Applications/UI/Authentication.elm @@ -15,12 +15,14 @@ import Html.Events.Extra.Mouse as Mouse import Html.Styled as Html exposing (Html, a, button, em, fromUnstyled, img, span, text) import Html.Styled.Attributes as Attributes exposing (attribute, css, href, placeholder, src, style, target, title, value, width) import Html.Styled.Events exposing (onClick, onSubmit) +import Html.Styled.Ext exposing (onClickStopPropagation) import Http import Json.Decode import Json.Encode import Markdown import Material.Icons exposing (Coloring(..)) import Material.Icons.Action as Icons +import Material.Icons.Alert as Icons import Material.Icons.Av as Icons import Material.Icons.Content as Icons import Material.Icons.Navigation as Icons @@ -150,6 +152,7 @@ type Msg -- Encryption ----------------------------------------- | KeepPassphraseInMemory String + | RemoveEncryptionKey Method | ShowNewEncryptionKeyScreen Method | ShowUpdateEncryptionKeyScreen Method | UpdateEncryptionKey Method String @@ -160,10 +163,6 @@ type Msg | PingIpfsCallback (Result Http.Error ()) | PingOtherIpfs String | PingOtherIpfsCallback String (Result Http.Error ()) - ----------------------------------------- - -- Missing secret key - ----------------------------------------- - | MissingSecretKey Alien.Tag Json.Decode.Value ----------------------------------------- -- More Input ----------------------------------------- @@ -228,7 +227,7 @@ update msg model = ) SignIn method -> - ( Unauthenticated + ( model -- , [ ( "method", encodeMethod method ) , ( "passphrase", Json.Encode.null ) @@ -247,7 +246,7 @@ update msg model = (return model) else - ( Unauthenticated + ( model -- , [ ( "method", encodeMethod method ) , ( "passphrase", Json.Encode.string <| hashPassphrase passphrase ) @@ -279,6 +278,14 @@ update msg model = _ -> return model + RemoveEncryptionKey method -> + Alien.RemoveEncryptionKey + |> Alien.trigger + |> Ports.toBrain + |> returnCommandWithModel (Authenticated method) + |> addReply ForceTracksRerender + |> addReply (ShowSuccessNotification "Saving data without encryption ...") + ShowNewEncryptionKeyScreen method -> return (NewEncryptionKeyScreen method Nothing) @@ -292,14 +299,14 @@ update msg model = (return model) else - ( Authenticated method - , passphrase + passphrase |> hashPassphrase |> Json.Encode.string |> Alien.broadcast Alien.UpdateEncryptionKey |> Ports.toBrain - , [ ForceTracksRerender ] - ) + |> returnCommandWithModel (Authenticated method) + |> addReply ForceTracksRerender + |> addReply (ShowSuccessNotification "Encrypting data with new passphrase ...") ----------------------------------------- -- IPFS @@ -351,29 +358,6 @@ update msg model = |> ShowErrorNotification |> returnReplyWithModel model - ----------------------------------------- - -- Missing secret key - ----------------------------------------- - MissingSecretKey Alien.AuthAnonymous data -> - returnRepliesWithModel - (NewEncryptionKeyScreen Local Nothing) - [ LoadDefaultBackdrop - , ShowStickySuccessNotification """ - Thanks for upgrading from Diffuse V1! - - In this newer version all your __data is encrypted__, for this we'll need a __passphrase__. - """ - , ToggleLoadingScreen Off - ] - - MissingSecretKey _ data -> - data - |> Json.Decode.decodeValue (Json.Decode.field "fallbackError" Json.Decode.string) - |> Result.withDefault "I seem to be missing your encrypted passphrase, please reauthenticate." - |> ShowErrorNotification - |> returnReplyWithModel model - |> addReply LoadDefaultBackdrop - ----------------------------------------- -- More Input ----------------------------------------- @@ -598,17 +582,17 @@ view model = InputScreen method opts -> inputScreen opts - NewEncryptionKeyScreen method Nothing -> - encryptionKeyScreen (SignInWithPassphrase method "") - - NewEncryptionKeyScreen method (Just passphrase) -> - encryptionKeyScreen (SignInWithPassphrase method passphrase) - - UpdateEncryptionKeyScreen method Nothing -> - encryptionKeyScreen (UpdateEncryptionKey method "") + NewEncryptionKeyScreen method pass -> + encryptionKeyScreen + { withEncryption = SignInWithPassphrase method (Maybe.withDefault "" pass) + , withoutEncryption = SignIn method + } - UpdateEncryptionKeyScreen method (Just passphrase) -> - encryptionKeyScreen (UpdateEncryptionKey method passphrase) + UpdateEncryptionKeyScreen method pass -> + encryptionKeyScreen + { withEncryption = UpdateEncryptionKey method (Maybe.withDefault "" pass) + , withoutEncryption = RemoveEncryptionKey method + } Unauthenticated -> choicesScreen @@ -832,11 +816,11 @@ choiceButton { action, icon, infoLink, isLast, label, outOfOrder } = -- ENCRYPTION KEY -encryptionKeyScreen : Msg -> Html Msg -encryptionKeyScreen msg = +encryptionKeyScreen : { withEncryption : Msg, withoutEncryption : Msg } -> Html Msg +encryptionKeyScreen { withEncryption, withoutEncryption } = slab Html.form - [ onSubmit msg ] + [ onSubmit withEncryption ] [ T.flex , T.flex_column ] @@ -856,6 +840,20 @@ encryptionKeyScreen msg = Filled Bypass (text "Continue") + , brick + [ onClickStopPropagation withoutEncryption ] + [ T.f7 + , T.flex + , T.items_center + , T.justify_center + , T.lh_title + , T.mt3 + , T.pointer + , T.white_50 + ] + [ inline [ T.dib, C.lh_0, T.mr2 ] [ fromUnstyled (Icons.warning 13 Inherit) ] + , text "Continue without encryption" + ] ] diff --git a/src/Applications/UI/Notifications.elm b/src/Applications/UI/Notifications.elm index 79b8a46d..f0a3ff82 100644 --- a/src/Applications/UI/Notifications.elm +++ b/src/Applications/UI/Notifications.elm @@ -70,7 +70,7 @@ show notification collection = else Task.perform (\_ -> DismissNotification { id = Notifications.id notification }) - (Process.sleep 5000) + (Process.sleep 7500) ) diff --git a/src/Applications/UI/Reply.elm b/src/Applications/UI/Reply.elm index 347cce2e..9c3d6cb4 100644 --- a/src/Applications/UI/Reply.elm +++ b/src/Applications/UI/Reply.elm @@ -120,4 +120,3 @@ type Reply | SaveSettings | SaveSources | SaveTracks - | SaveTracksFromBrain diff --git a/src/Javascript/Workers/Brain/user.js b/src/Javascript/Workers/Brain/user.js index 036feab4..f6161e63 100644 --- a/src/Javascript/Workers/Brain/user.js +++ b/src/Javascript/Workers/Brain/user.js @@ -146,7 +146,7 @@ app.ports.requestDropbox.subscribe(event => { }) .then(r => r.ok ? r.text() : r.json()) .then(r => r.error ? null : r) - .then(decryptWithSecretKey) + .then(decryptIfNeeded) dataPromise .then( sendJsonData(event) ) @@ -196,7 +196,7 @@ app.ports.requestIpfs.subscribe(event => { fetch(apiOrigin + "/api/v0/files/read?arg=" + path) .then(r => r.ok ? r.text() : r.json()) .then(r => r.Code === 0 ? null : r) - .then(decryptWithSecretKey) + .then(decryptIfNeeded) .then( sendJsonData(event) ) .catch( reportError(event) ) }) @@ -303,11 +303,11 @@ app.ports.requestRemoteStorage.subscribe(event => { : remoteStorage(event) .then(_ => rsClient.getFile(event.data.file)) .then(r => r.data) - .then(decryptWithSecretKey) + .then(decryptIfNeeded) dataPromise .then( sendJsonData(event) ) - .then( reportError(event) ) + .catch( reportError(event) ) }) @@ -353,7 +353,7 @@ app.ports.requestTextile.subscribe(event => { .then(f => f ? Textile.readFile(apiOrigin, f) : null) .then( sendJsonData(event) ) - .then( reportError(event) ) + .catch( reportError(event) ) }) @@ -379,16 +379,27 @@ app.ports.toTextile.subscribe(event => { // 🛠 -function decryptWithSecretKey(encryptedData) { - return encryptedData - ? getSecretKey().then(secretKey => decrypt(secretKey, encryptedData)) - : null +function decryptIfNeeded(data) { + if (typeof data !== "string") { + return Promise.resolve(data) + + } else if (data.startsWith("{") || data.startsWith("[")) { + return Promise.resolve(data) + + } else { + return data + ? getSecretKey().then(secretKey => decrypt(secretKey, data)) + : Promise.resolve(null) + + } } function encryptWithSecretKey(unencryptedData) { return unencryptedData - ? getSecretKey().then(secretKey => encrypt(secretKey, unencryptedData)) + ? getSecretKey() + .then(secretKey => encrypt(secretKey, unencryptedData)) + .catch(_ => unencryptedData) : null } diff --git a/src/Javascript/Workers/brain.js b/src/Javascript/Workers/brain.js index 23f52f2c..e9284093 100644 --- a/src/Javascript/Workers/brain.js +++ b/src/Javascript/Workers/brain.js @@ -91,17 +91,12 @@ function removeCache(key) { function fromCache(key) { - if (isAuthMethodService(key)) { - return getFromIndex({ key: key }) - .then(r => getSecretKey().then(s => [r, s])) - .then(([r, s]) => typeof r === "string" ? decrypt(s, r) : r) - .then(d => typeof d === "string" ? JSON.parse(d) : d) - .then(a => a === undefined ? null : a) - - } else { - return getFromIndex({ key: key }) - - } + return isAuthMethodService(key) + ? getFromIndex({ key: key }) + .then(decryptIfNeeded) + .then(d => typeof d === "string" ? JSON.parse(d) : d) + .then(a => a === undefined ? null : a) + : getFromIndex({ key: key }) } @@ -109,8 +104,7 @@ function toCache(key, data) { if (isAuthMethodService(key)) { const json = JSON.stringify(data) - return getSecretKey() - .then(secretKey => encrypt(secretKey, json)) + return encryptWithSecretKey(json) .then(encryptedData => setInIndex({ key: key, data: encryptedData })) } else { diff --git a/src/Javascript/crypto.js b/src/Javascript/crypto.js index 37922659..49598f3e 100644 --- a/src/Javascript/crypto.js +++ b/src/Javascript/crypto.js @@ -60,15 +60,6 @@ function encrypt(key, string) { function decrypt(key, string) { - if (typeof string !== "string") { - throw("Cannot decrypt a non-string value!") - } - - if (string.trimStart().startsWith("{")) { - // {!} Already decrypted - return string - } - const iv_b64 = string.substring(0, 16) const buf_b64 = string.substring(16) diff --git a/src/Library/Alien.elm b/src/Library/Alien.elm index e257f9d9..7656d7a7 100644 --- a/src/Library/Alien.elm +++ b/src/Library/Alien.elm @@ -41,6 +41,7 @@ type Tag | ImportLegacyData | ProcessSources | RedirectToBlockstackSignIn + | RemoveEncryptionKey | RemoveTracksBySourceId | RemoveTracksFromCache | SaveEnclosedUserData @@ -54,6 +55,7 @@ type Tag | SignOut | StopProcessing | StoreTracksInCache + | SyncHypaethralData | ToCache | UpdateEncryptionKey ----------------------------------------- @@ -93,6 +95,7 @@ enum = , ( "IMPORT_LEGACY_DATA", ImportLegacyData ) , ( "PROCESS_SOURCES", ProcessSources ) , ( "REDIRECT_TO_BLOCKSTACK_SIGN_IN", RedirectToBlockstackSignIn ) + , ( "REMOVE_ENCRYPTION_KEY", RemoveEncryptionKey ) , ( "REMOVE_TRACKS_BY_SOURCE_ID", RemoveTracksBySourceId ) , ( "REMOVE_TRACKS_FROM_CACHE", RemoveTracksFromCache ) , ( "SAVE_ENCLOSED_USER_DATA", SaveEnclosedUserData ) @@ -106,6 +109,7 @@ enum = , ( "SIGN_OUT", SignOut ) , ( "STOP_PROCESSING", StopProcessing ) , ( "STORE_TRACKS_IN_CACHE", StoreTracksInCache ) + , ( "SYNC_HYPAETHRAL_DATA", SyncHypaethralData ) , ( "TO_CACHE", ToCache ) , ( "UPDATE_ENCRYPTION_KEY", UpdateEncryptionKey ) diff --git a/src/Library/User/Layer.elm b/src/Library/User/Layer.elm index 03dc2c31..28657078 100644 --- a/src/Library/User/Layer.elm +++ b/src/Library/User/Layer.elm @@ -15,6 +15,7 @@ Which is stored in the location chosen by the user. -} +import Alien import Dict exposing (Dict) import Enum exposing (Enum) import Equalizer -- knotmirror 0.0.1