Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ export default () => {
// Clear keys file
ipcMain.handle(
createChannelName('clear'),
async (_e, userId: string, organizationId?: string) => {
async (_e, userId: string, decryptPassword: string | null, organizationId?: string) => {
try {
await deleteSecretHashes(userId, organizationId);
await deleteSecretHashes(userId, decryptPassword, organizationId);
return true;
} catch {
return false;
Expand Down
18 changes: 10 additions & 8 deletions front-end/src/main/services/localUser/keyPairs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const logger = createLogger('main.localUser.keyPairs');
//Get stored key pairs
export const getKeyPairs = async (
user_id: string,
decryptPassword: string | null,
Comment thread
jbair06 marked this conversation as resolved.
organization_id?: string | null,
): Promise<KeyPair[]> => {
const prisma = getPrismaClient();
Expand All @@ -23,7 +24,7 @@ export const getKeyPairs = async (
user_id,
};

await extendWhere(where, organization_id);
await extendWhere(where, decryptPassword, organization_id);

return prisma.keyPair.findMany({
where,
Expand Down Expand Up @@ -71,7 +72,7 @@ export const changeDecryptionPassword = async (
) => {
const prisma = getPrismaClient();

const keyPairs = await getKeyPairs(userId);
const keyPairs = await getKeyPairs(userId, oldPassword);

for (let i = 0; i < keyPairs.length; i++) {
const keyPair = keyPairs[i];
Expand All @@ -89,7 +90,7 @@ export const changeDecryptionPassword = async (
});
}

return await getKeyPairs(userId);
return await getKeyPairs(userId, newPassword);
};

// Decrypt user's private key
Expand Down Expand Up @@ -141,6 +142,7 @@ export const decryptPrivateKey = async (
// Delete encrypted private keys
export const deleteEncryptedPrivateKeys = async (
user_id: string,
decryptPassword: string | null,
organization_id?: string | null,
) => {
const prisma = getPrismaClient();
Expand All @@ -149,7 +151,7 @@ export const deleteEncryptedPrivateKeys = async (
user_id,
};

await extendWhere(where, organization_id);
await extendWhere(where, decryptPassword, organization_id);

await prisma.keyPair.updateMany({
where,
Expand All @@ -160,14 +162,14 @@ export const deleteEncryptedPrivateKeys = async (
};

// Clear user's keys
export const deleteSecretHashes = async (user_id: string, organization_id?: string | null) => {
export const deleteSecretHashes = async (user_id: string, decryptPassword: string | null, organization_id?: string | null) => {
const prisma = getPrismaClient();

const where: Prisma.KeyPairWhereInput = {
user_id,
};

await extendWhere(where, organization_id);
await extendWhere(where, decryptPassword, organization_id);

await prisma.keyPair.deleteMany({
where,
Expand Down Expand Up @@ -215,7 +217,7 @@ export const updateIndex = async (keyPairId: string, index: number) => {
});
};

async function extendWhere(where: Prisma.KeyPairWhereInput, organization_id?: string | null) {
async function extendWhere(where: Prisma.KeyPairWhereInput, decryptPassword: string | null, organization_id?: string | null) {
if (organization_id !== undefined) {
if (organization_id === null) {
where.organization_id = null;
Expand All @@ -225,7 +227,7 @@ async function extendWhere(where: Prisma.KeyPairWhereInput, organization_id?: st
const organization = await getOrganization(organization_id);

if (organization) {
const tokenPayload = await getCurrentUser(organization.serverUrl);
const tokenPayload = await getCurrentUser(organization.serverUrl, decryptPassword);

where.organization_id = organization.id;

Expand Down
116 changes: 94 additions & 22 deletions front-end/src/main/services/localUser/organizationCredentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,45 @@ import { login } from '@main/services/organization/auth';
import { getUseKeychainClaim } from '@main/services/localUser/claim';

import { createLogger } from '@main/modules/logger';
import { decrypt, encrypt, isLegacyBlob } from '@main/utils/crypto';
import {
decrypt,
encrypt,
isClearTextToken,
isLegacyBlob,
} from '@main/utils/crypto';

const logger = createLogger('main.organizationCredentials');

/* Returns the organization that the user is connected to */
export const getOrganizationTokens = async (user_id: string) => {
export const getOrganizationTokens = async (user_id: string, decryptPassword: string | null) => {
const prisma = getPrismaClient();

try {
const orgs = await prisma.organizationCredentials.findMany({
where: { user_id },
select: {
id: true,
organization_id: true,
jwtToken: true,
},
});
const result: { organization_id: string; jwtToken: string | null }[] = [];
for (const o of orgs) {
result.push({
organization_id: o.organization_id,
jwtToken: await decryptMigrateJwtToken(o, decryptPassword),
});
}
return result;

return orgs || [];
} catch (error) {
logger.error('Failed to get organization tokens', { error });
return [];
}
};

/* Returns the organizations that the user should sign into */
export const organizationsToSignIn = async (user_id: string) => {
export const organizationsToSignIn = async (user_id: string, decryptPassword: string | null) => {
const prisma = getPrismaClient();

try {
Expand All @@ -47,7 +60,7 @@ export const organizationsToSignIn = async (user_id: string) => {
const finalCredentials: typeof credentials = [];

for (let i = 0; i < credentials.length; i++) {
if (await organizationCredentialsInvalid(credentials[i]))
if (await organizationCredentialsInvalid(credentials[i], decryptPassword))
finalCredentials.push(credentials[i]);
}

Expand All @@ -59,7 +72,7 @@ export const organizationsToSignIn = async (user_id: string) => {
};

/* Returns whether the user should sign in a specific organization */
export const shouldSignInOrganization = async (user_id: string, organization_id: string) => {
export const shouldSignInOrganization = async (user_id: string, organization_id: string, decryptPassword: string | null) => {
const prisma = getPrismaClient();

try {
Expand All @@ -70,31 +83,31 @@ export const shouldSignInOrganization = async (user_id: string, organization_id:
},
});

return await organizationCredentialsInvalid(org);
return await organizationCredentialsInvalid(org, decryptPassword);
} catch {
return true;
}
};

/* Returns the access token of a user for an organization */
export const getAccessToken = async (serverUrl: string) => {
export const getAccessToken = async (serverUrl: string, decryptPassword: string | null) => {
const prisma = getPrismaClient();

try {
const credentials = await prisma.organizationCredentials.findFirst({
where: { organization: { serverUrl } },
});
if (!credentials) return null;
return credentials.jwtToken || null;
return await decryptMigrateJwtToken(credentials, decryptPassword);
} catch (error) {
logger.error('Failed to get access token', { error });
return null;
}
};

/* Returns the current user of an organization */
export const getCurrentUser = async (organizationServerUrl: string) => {
const token = await getAccessToken(organizationServerUrl);
export const getCurrentUser = async (organizationServerUrl: string, decryptPassword: string | null) => {
const token = await getAccessToken(organizationServerUrl, decryptPassword);
if (!token) return null;

try {
Expand All @@ -105,6 +118,7 @@ export const getCurrentUser = async (organizationServerUrl: string) => {
}
};


/* Returns credentials for organization */
export const getOrganizationCredentials = async (
organization_id: string,
Expand All @@ -120,11 +134,13 @@ export const getOrganizationCredentials = async (

if (!credentials) return null;

const password = await decryptData(credentials.password, decryptPassword, credentials.id);
const password = await decryptMigratePassword(credentials, decryptPassword);
const jwtToken = await decryptMigrateJwtToken(credentials, decryptPassword);

return {
...credentials,
password,
jwtToken,
};
} catch (error) {
logger.error('Failed to get organization credentials', { error });
Expand Down Expand Up @@ -178,6 +194,7 @@ export const addOrganizationCredentials = async (

try {
password = await encryptData(password, encryptPassword);
jwtToken = await encryptData(jwtToken, encryptPassword);
Comment thread
jbair06 marked this conversation as resolved.

await prisma.organizationCredentials.create({
data: {
Expand Down Expand Up @@ -213,6 +230,10 @@ export const updateOrganizationCredentials = async (
password = await encryptData(password, encryptPassword);
}

if (jwtToken && !passwordIsEncrypted) {
Comment thread
jbair06 marked this conversation as resolved.
jwtToken = await encryptData(jwtToken, encryptPassword);
}

const credentials = await prisma.organizationCredentials.findFirst({
where: { user_id, organization_id },
});
Expand Down Expand Up @@ -258,7 +279,7 @@ export const deleteOrganizationCredentials = async (organization_id: string, use
export const tryAutoSignIn = async (user_id: string, decryptPassword: string | null) => {
const prisma = getPrismaClient();

const invalidCredentials = await organizationsToSignIn(user_id);
const invalidCredentials = await organizationsToSignIn(user_id, decryptPassword);

const failedLogins: Organization[] = [];

Expand All @@ -267,7 +288,10 @@ export const tryAutoSignIn = async (user_id: string, decryptPassword: string | n

let password = '';
try {
password = await decryptData(invalidCredential.password, decryptPassword, invalidCredential.id);
password = await decryptMigratePassword(
invalidCredential,
decryptPassword,
);
} catch {
throw new Error('Incorrect decryption password');
}
Expand All @@ -278,10 +302,11 @@ export const tryAutoSignIn = async (user_id: string, decryptPassword: string | n
invalidCredential.email,
password,
);
const encryptedAccessToken = await encryptData(accessToken, decryptPassword);

await prisma.organizationCredentials.update({
where: { id: invalidCredential.id },
data: { jwtToken: accessToken },
data: { jwtToken: encryptedAccessToken },
});
} catch {
failedLogins.push(invalidCredential.organization);
Expand Down Expand Up @@ -348,8 +373,7 @@ async function encryptData(data: string, encryptPassword?: string | null) {
/* Decrypt data */
export async function decryptData(
data: string,
decryptPassword?: string | null,
credentialId?: string,
decryptPassword: string | null,
) {
// if no data was stored (password cleared), just return empty string
if (data.length === 0) {
Expand All @@ -361,11 +385,32 @@ export async function decryptData(
const buffer = Buffer.from(data, 'base64');
return safeStorage.decryptString(buffer);
} else if (decryptPassword) {
const decrypted = await decrypt(data, decryptPassword);
if (isLegacyBlob(data) && credentialId) {
return decrypt(data, decryptPassword);
} else {
throw new Error('Password is required to decrypt sensitive');
}
}

/* Decrypt credentials password. Update its encryption if needed. */
export async function decryptMigratePassword(
credential: { id: string, password: string },
decryptPassword: string | null,
) {
// if password was cleared, just return empty string
if (credential.password.length === 0) {
return '';
}

const useKeychain = await getUseKeychainClaim();
if (useKeychain) {
const buffer = Buffer.from(credential.password, 'base64');
return safeStorage.decryptString(buffer);
} else if (decryptPassword) {
const decrypted = await decrypt(credential.password, decryptPassword);
if (isLegacyBlob(credential.password)) {
try {
await getPrismaClient().organizationCredentials.update({
where: { id: credentialId },
where: { id: credential.id },
data: { password: await encrypt(decrypted, decryptPassword) },
});
} catch {
Expand All @@ -378,15 +423,42 @@ export async function decryptData(
}
}

/* Decrypt credentials JWT token. Update its encryption if needed. */
export async function decryptMigrateJwtToken(
credential: { id: string; jwtToken: string | null},
decryptPassword: string | null,
) {
// if token is null, returns null
if (credential.jwtToken === null) {
return null;
}

if (isClearTextToken(credential.jwtToken)) {
// JWT token is not encrypted => we encrypt it
try {
await getPrismaClient().organizationCredentials.update({
where: { id: credential.id },
data: { jwtToken: await encryptData(credential.jwtToken, decryptPassword) },
});
} catch {
// migration failure is non-fatal
}
return credential.jwtToken;
} else {
return decryptData(credential.jwtToken, decryptPassword);
}
}

/* Validate organization credentials */
export async function organizationCredentialsInvalid(
org?: (OrganizationCredentials & { organization: Organization }) | null,
org: (OrganizationCredentials & { organization: Organization }) | null,
decryptPassword: string | null,
) {
if (!org) return true;

if (org.password.length === 0 || org.email.length === 0) return true;

const token = await getAccessToken(org.organization.serverUrl);
const token = await getAccessToken(org.organization.serverUrl, decryptPassword);
if (!token) return true;

try {
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/main/services/localUser/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export const signTransaction = async (
transaction.freezeWith(client);
}

const keyPairs = await getKeyPairs(userId);
const keyPairs = await getKeyPairs(userId, userPassword);

const useKeychain = await getUseKeychainClaim();

Expand Down
4 changes: 4 additions & 0 deletions front-end/src/main/utils/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ export function isLegacyBlob(data: string) {
return !data.startsWith(BLOB_V2_PREFIX);
}

export function isClearTextToken(jwtData: string): boolean {
return /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/.test(jwtData);
}

export async function encrypt(data: string, password: string): Promise<string> {
const iv = crypto.randomBytes(16);
const salt = crypto.randomBytes(64);
Expand Down
Loading
Loading