LibreChat/packages/api/src/actions/crypto.ts
Oliver Faust 5e49868f0a
🔑 fix: Decode Action OAuth Credentials After Decryption (#14698)
* 🔑 fix: Decode Action OAuth Credentials After Decryption

Action client credentials are URL-encoded before encryption, but the OAuth
token exchange decrypted them with `decryptV2` alone, sending values like
`abc%40domain.com` to the provider and causing 401s for secrets containing
`@`, `+`, `=`, `/` or `:`. Decoding falls back to the raw decrypted value so
legacy secrets stored before 299cabd6e (which contain an unescaped `%`) still work.

Fixes #14636

* 🔑 fix: Share Action Credential Codec Between Read Paths

The encode-before-encrypt convention had two readers with different
behaviour. `ActionService.decryptSensitiveValue` decoded unconditionally,
so a credential stored before encoding was introduced (299cabd6e, March
2025) containing a stray `%` threw `URIError` and failed every read of the
action, not just the token exchange.

Extract the pair into `packages/api/src/actions/crypto.ts` as the single
implementation and consume it from both `ActionService` and the OAuth token
exchange, so the two paths cannot drift again.

Tests cover the codec against real crypto: reserved characters and literal
percent escapes round-trip, pre-encoding values are returned unchanged, and
a pre-encoding value with a stray `%` no longer throws.

A version marker on newly encrypted values was prototyped and dropped: it
changes the stored format for every action credential while fixing nothing,
since values written by the encoding convention already decode correctly
and pre-encoding values stay unmarked either way.

---------

Co-authored-by: Danny Avila <danny@librechat.ai>
2026-09-01 18:42:28 -04:00

29 lines
1.1 KiB
TypeScript

import { encryptV2, decryptV2 } from '@librechat/data-schemas';
/**
* Encrypts an action credential, encoding it first so that reserved characters (`@`, `+`, `=`,
* `/`, `:`) survive storage.
*/
export async function encryptSensitiveValue(value: string): Promise<string> {
return encryptV2(encodeURIComponent(value));
}
/**
* Decrypts an action credential, reversing the encoding applied by {@link encryptSensitiveValue}.
*
* Encoding before encryption was introduced in 299cabd6e (March 2025). Credentials stored earlier
* were encrypted raw and carry no marker saying so, so a legacy value containing a stray `%` would
* make `decodeURIComponent` throw `URIError`; those are returned as decrypted.
*
* Every reader of these fields must use this helper. Decoding in one read path but not another
* sends different credentials to the provider depending on which path ran.
*/
export async function decryptSensitiveValue(encryptedValue: string): Promise<string> {
const decryptedValue = await decryptV2(encryptedValue);
try {
return decodeURIComponent(decryptedValue);
} catch {
return decryptedValue;
}
}