import { isOsx } from './isOsx'; import { isWindows } from './isWindows'; import { log } from './log'; // The three keystore call sites (getTokenFromKeystore, storeToken, removeToken) // use a module-style surface: `keytar.getPassword(service, account)` etc. // @napi-rs/keyring instead exposes an entry-object API // (`new AsyncEntry(service, account).getPassword()`). This adapter is the single // boundary that translates between the two, so those call sites stay unchanged. // // The adapter deliberately uses the library's *secret* API (setSecret/getSecret, // raw bytes) rather than its *password* API (setPassword/getPassword, strings). // On Windows those are not equivalent, and the difference broke token storage // outright — see the encodeSecret/decodeSecret notes below. export interface Keystore { getPassword(service: string, account: string): Promise; setPassword( service: string, account: string, password: string ): Promise; deletePassword(service: string, account: string): Promise; } // @napi-rs/keyring's AsyncEntry.getSecret() resolves `Uint8Array | undefined` // per its type declarations (on macOS it returns null at runtime, normalized by // the `== null` check below); it never resolves `false`. A missing credential is // instead signalled by rejecting with a NoEntry error on some platforms/ // versions. Treat that error as "no entry" so a read resolves undefined and a // delete is a no-op — matching keytar's contract. (deletePassword()/ // deleteCredential() separately resolves a boolean for whether an entry // existed; this adapter discards it — see the deletePassword note below.) function isNoEntryError(err: unknown): boolean { // Primary, reliable signal: the library's own error code. const code = (err as { code?: unknown })?.code; if (typeof code === 'string' && /noentry/i.test(code)) { return true; } // Fallback for platforms/versions that surface "missing" only as a message. // Kept deliberately narrow to keychain/entry phrasings (napi-rs' "No matching // entry…" and macOS' "could not be found in the keychain") so an unrelated // failure — e.g. an IO "file not found" — is NOT misclassified as a no-op and // silently swallowed. const message = err instanceof Error ? err.message : String(err); const matchedByMessage = /no (matching )?entry|could not be found in the keychain/i.test(message); if (matchedByMessage) { // This heuristic is English-only. Log when the message path (not the // reliable `.code` path) is what classified the error, so a locale-related // misclassification is diagnosable with `-v` rather than silent. log(`keystore: treating error as no-entry via message match: ${message}`); } return matchedByMessage; } // Encode a token for storage as raw bytes. // // Why not the library's setPassword(): on Windows, keyring's set_password() // converts the string to UTF-16 before writing, then validates the *doubled* // length against Credential Manager's CRED_MAX_CREDENTIAL_BLOB_SIZE (2560 // bytes). That caps a password at 1280 characters. ALKS refresh tokens are // ~1700 characters, so every Windows `alks developer configure` failed with // "Value of 'password encoded as UTF-16' is longer than the platform limit of // 2560 chars" and fell through to the plaintext-file prompt. // // setSecret() writes the bytes we hand it verbatim, so an ASCII token costs one // byte per character and the full 2560-byte budget is usable — which is exactly // what keytar did before it was replaced. On macOS and Linux this is a no-op: // keyring's macOS set_password() already stores `password.as_bytes()`, and its // Linux set_password() literally delegates to set_secret(). So UTF-8 bytes are // the one representation that is correct on all three platforms *and* byte- // compatible with every token keytar previously stored. function encodeSecret(token: string): Buffer { return Buffer.from(token, 'utf8'); } // True if `bytes` is ASCII text encoded as UTF-16LE (every high byte NUL). // ALKS tokens are printable ASCII and so contain no NUL bytes when UTF-8 // encoded, which makes this test unambiguous rather than a guess. function isUtf16LeAscii(bytes: Uint8Array): boolean { if (bytes.length === 0 || bytes.length % 2 !== 0) { return false; } for (let i = 1; i < bytes.length; i += 2) { if (bytes[i] !== 0x00) { return false; } } return true; } // Decode a stored secret back to a token. // // Windows Credential Manager stores whatever bytes it is handed, so this // credential can have been written by any of three encoders: // keytar (<= 4.0.2) UTF-8 bytes // alks 4.1.0 UTF-16LE bytes (its setPassword doubled them) // this version UTF-8 bytes // Sniffing UTF-16LE means a token stored by 4.1.0 still reads back correctly // instead of as NUL-laced junk. This also repairs the reverse of the 4.1.0 bug: // its getPassword() decoded keytar's UTF-8 blobs as UTF-16, silently returning // mojibake — no throw, so getTokenFromKeystore never fell back and the CLI just // failed to authenticate with no usable explanation. function decodeSecret(bytes: Uint8Array): string { if (isUtf16LeAscii(bytes)) { log('keystore: decoding secret written as UTF-16LE by a prior version'); return Buffer.from(bytes).toString('utf16le'); } return Buffer.from(bytes).toString('utf8'); } export async function getKeytar(): Promise { let keyring: typeof import('@napi-rs/keyring'); try { keyring = await import('@napi-rs/keyring'); } catch (err) { // Surface the real cause (e.g. a native-binding load failure) instead of // masking it behind a generic message — future breakage should be // self-diagnosing without needing `-v`. log(`failed to import @napi-rs/keyring: ${err}`); const cause = err instanceof Error ? err.message : String(err); if (!isOsx() && !isWindows()) { // see https://github.com/Brooooooklyn/keyring-node — Linux uses libsecret throw new Error( `Unable to load the OS keychain library (@napi-rs/keyring): ${cause}. On Linux, ensure libsecret is installed (e.g. libsecret-1-0 / libsecret-devel), then reinstall this tool with 'npm install -g alks'.` ); } throw new Error( `Unable to load the OS keychain library (@napi-rs/keyring): ${cause}. Try reinstalling this cli with 'npm install -g alks'.` ); } const { AsyncEntry } = keyring; return { async getPassword(service, account) { const entry = new AsyncEntry(service, account); try { const secret = await entry.getSecret(); // An absent credential can surface as null/undefined rather than a // NoEntry rejection (the binding's macOS behavior), so normalize both. return secret == null ? undefined : decodeSecret(secret); } catch (err) { if (isNoEntryError(err)) { return undefined; } throw err; } }, async setPassword(service, account, password) { const entry = new AsyncEntry(service, account); await entry.setSecret(encodeSecret(password)); }, async deletePassword(service, account) { const entry = new AsyncEntry(service, account); try { // deletePassword() resolves a boolean for whether an entry existed. We // deliberately discard it: callers (e.g. removeToken) only need the // delete not to throw, matching keytar's no-op-on-missing contract. await entry.deletePassword(); } catch (err) { if (isNoEntryError(err)) { return; } throw err; } }, }; }