diff --git a/keyserver/src/keyserver.js b/keyserver/src/keyserver.js --- a/keyserver/src/keyserver.js +++ b/keyserver/src/keyserver.js @@ -30,6 +30,7 @@ multimediaUploadResponder, uploadDownloadResponder, } from './uploads/uploads.js'; +import { verifyUserLogin } from './user/login.js'; import { initENSCache } from './utils/ens-cache.js'; import { prefetchAllURLFacts, @@ -63,6 +64,13 @@ cluster.fork(); } cluster.on('exit', () => cluster.fork()); + + // Allow login to be optional until staging environment is available + try { + await verifyUserLogin(); + } catch (e) { + console.log('Failed to log into identity service'); + } } else { const server = express(); expressWs(server); diff --git a/keyserver/src/user/login.js b/keyserver/src/user/login.js new file mode 100644 --- /dev/null +++ b/keyserver/src/user/login.js @@ -0,0 +1,196 @@ +// @flow + +import type { Account as OlmAccount } from '@commapp/olm'; +import type { QueryResults } from 'mysql'; +import { getRustAPI } from 'rust-node-addon'; + +import type { OLMOneTimeKeys } from 'lib/types/crypto-types'; +import { getCommConfig } from 'lib/utils/comm-config.js'; +import { ServerError } from 'lib/utils/errors.js'; + +import { SQL, dbQuery } from '../database/database.js'; +import { fetchCallUpdateOlmAccount } from '../updaters/olm-account-updater.js'; +import { validateAccountPrekey } from '../utils/olm-utils.js'; + +type UserCredentials = { +username: string, +password: string }; +type IdentityInfo = { +userId: string, +accessToken: string }; + +const userIDMetadataKey = 'user_id'; +const accessTokenMetadataKey = 'access_token'; + +export type AccountKeysSet = { + +identityKeys: string, + +prekey: string, + +prekeySignature: string, + +oneTimeKey: $ReadOnlyArray, +}; + +function getOneTimeKeyValues(keyBlob: string): $ReadOnlyArray { + const content: OLMOneTimeKeys = JSON.parse(keyBlob); + const keys: $ReadOnlyArray = Object.values(content.curve25519); + return keys; +} + +async function retrieveAccountKeysSet( + account: OlmAccount, +): Promise { + const identityKeys = account.identity_keys(); + + validateAccountPrekey(account); + const prekeyMap = JSON.parse(account.prekey()).curve25519; + let prekey = null; + for (const key in prekeyMap) { + prekey = prekeyMap[key]; + } + const prekeySignature = account.prekey_signature(); + + if (!prekeySignature || !prekey) { + throw new ServerError('Invalid prekey or signature'); + } + + if (getOneTimeKeyValues(account.one_time_keys()).length < 10) { + account.generate_one_time_keys(10); + } + + const oneTimeKey = getOneTimeKeyValues(account.one_time_keys()); + + return { identityKeys, oneTimeKey, prekey, prekeySignature }; +} + +// After register or login is successful +async function markKeysAsPublished(account: OlmAccount) { + account.mark_prekey_as_published(); + account.mark_keys_as_published(); +} + +async function fetchIdentityInfo(): Promise { + const versionQuery = SQL` + SELECT data + FROM metadata + WHERE name IN (${userIDMetadataKey}, ${accessTokenMetadataKey}); + `; + + const [[userId, accessToken]] = await dbQuery(versionQuery); + if (!userId || !accessToken) { + return null; + } + return { userId, accessToken }; +} + +async function saveIdentityInfo(userInfo: IdentityInfo): Promise { + const updateQuery = SQL` + REPLACE INTO metadata (name, data) + VALUES (${userIDMetadataKey}, ${userInfo.userId}), + (${accessTokenMetadataKey}, ${userInfo.accessToken}) + `; + + return dbQuery(updateQuery); +} + +async function verifyUserLogin(): Promise { + const result = await fetchIdentityInfo(); + + if (!result) { + const identityInfo = await registerOrLogin(); + await saveIdentityInfo(identityInfo); + return identityInfo; + } + + return result; +} + +async function registerOrLogin(): Promise { + const rustAPIPromise = getRustAPI(); + + const userInfo = await getCommConfig({ + folder: 'secrets', + name: 'user_credentials', + }); + + if (!userInfo) { + throw new ServerError('Missing user credentials'); + } + + const { + identityKeys: notificationsIdentityKeys, + prekey: notificationsPrekey, + prekeySignature: notificationsPrekeySignature, + oneTimeKey: notificationsOneTimeKey, + } = await fetchCallUpdateOlmAccount('notifications', retrieveAccountKeysSet); + + const contentAccountCallback = async (account: OlmAccount) => { + const { + identityKeys: contentIdentityKeys, + oneTimeKey, + prekey, + prekeySignature, + } = await retrieveAccountKeysSet(account); + + const identityKeysBlob = { + primaryIdentityPublicKeys: JSON.parse(contentIdentityKeys), + notificationIdentityPublicKeys: JSON.parse(notificationsIdentityKeys), + }; + const identityKeysBlobPayload = JSON.stringify(identityKeysBlob); + const signedIdentityKeysBlob = { + payload: identityKeysBlobPayload, + signature: account.sign(identityKeysBlobPayload), + }; + + return { + signedIdentityKeysBlob, + oneTimeKey, + prekey, + prekeySignature, + }; + }; + + const { + signedIdentityKeysBlob, + prekey: contentPrekey, + prekeySignature: contentPrekeySignature, + oneTimeKey: contentOneTimeKey, + } = await fetchCallUpdateOlmAccount('content', contentAccountCallback); + + const rustAPI = await rustAPIPromise; + + try { + const identity_info = await rustAPI.loginUser( + userInfo.username, + userInfo.password, + signedIdentityKeysBlob, + contentPrekey, + contentPrekeySignature, + notificationsPrekey, + notificationsPrekeySignature, + contentOneTimeKey, + notificationsOneTimeKey, + ); + fetchCallUpdateOlmAccount('content', markKeysAsPublished); + fetchCallUpdateOlmAccount('notifications', markKeysAsPublished); + return identity_info; + } catch (e) { + console.log('Failed to log into identity service: ' + e); + try { + const identity_info = await rustAPI.registerUser( + userInfo.username, + userInfo.password, + signedIdentityKeysBlob, + contentPrekey, + contentPrekeySignature, + notificationsPrekey, + notificationsPrekeySignature, + contentOneTimeKey, + notificationsOneTimeKey, + ); + console.log('Finished registration'); + fetchCallUpdateOlmAccount('content', markKeysAsPublished); + fetchCallUpdateOlmAccount('notifications', markKeysAsPublished); + return identity_info; + } catch (err) { + console.log('Failed to register user: ' + err); + throw new Error('Unable to login or register user'); + } + } +} + +export { verifyUserLogin };