Skip to content
Open
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
19 changes: 18 additions & 1 deletion src/vault/vault.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,13 +300,30 @@ describe('Vault', () => {

// Decrypt the data
const decrypted = await workos.vault.decrypt(encrypted, associatedData);

// Verify decrypt API call
expect(fetchURL()).toContain('/vault/v1/keys/decrypt');
expect(fetchMethod()).toBe('POST');

// Verify the decrypted text matches the original
expect(decrypted).toBe(originalText);

// Reset fetch
fetch.resetMocks();

// Decrypt with an already known key
const dataKey = {
key: validKey,
id: 'key123',
};
const decryptedLocal = await workos.vault.decrypt(
encrypted,
associatedData,
dataKey,
);
expect(decryptedLocal).toBe(originalText);

// No API calls should be made
expect(fetch.mock.calls.length).toEqual(0);
});
});
});
24 changes: 17 additions & 7 deletions src/vault/vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class Vault {
this.cryptoProvider = workos.getCryptoProvider();
}

private decode(payload: string): Decoded {
async decode(payload: string): Promise<Decoded> {
const inputData = base64ToUint8Array(payload);
// Use 12 bytes for IV (standard for AES-GCM)
const iv = new Uint8Array(inputData.subarray(0, 12));
Expand Down Expand Up @@ -153,10 +153,13 @@ export class Vault {
data: string,
context: KeyContext,
associatedData?: string,
keyPair?: DataKeyPair,
): Promise<string> {
const keyPair = await this.createDataKey({
context,
});
if (keyPair === undefined) {
keyPair = await this.createDataKey({
context,
});
}

// Convert base64 key to Uint8Array
const encoder = new TextEncoder();
Expand Down Expand Up @@ -213,11 +216,18 @@ export class Vault {
}

async decrypt(
encryptedData: string,
encryptedData: string | Decoded,
associatedData?: string,
dataKey?: DataKey,
): Promise<string> {
const decoded = this.decode(encryptedData);
const dataKey = await this.decryptDataKey({ keys: decoded.keys });
const decoded =
typeof encryptedData === 'string'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels strange to me, like two methods are being mixed here. Why not introduce localencrypt/localdecrypt methods that have distinct signatures from encrypt/decrypt?

? await this.decode(encryptedData)
: encryptedData;

if (dataKey === undefined) {
dataKey = await this.decryptDataKey({ keys: decoded.keys });
}

// Convert base64 key to Uint8Array using our cross-runtime utility
const key = base64ToUint8Array(dataKey.key);
Expand Down