Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

replace security CLI keychain calls with bun:ffi

Raine Virta3c938943aba7
diff --git a/src/keychain.ts b/src/keychain.ts
new file mode 100644
index 0000000..1da28a9
--- /dev/null
+++ b/src/keychain.ts
@@ -0,0 +1,135 @@
+import { dlopen, FFIType, ptr, toArrayBuffer } from "bun:ffi"
+
+const errSecSuccess = 0
+const errSecItemNotFound = -25300
+const errSecDuplicateItem = -25299
+
+function readPtr(buf: Uint8Array): number {
+ return Number(new DataView(buf.buffer, buf.byteOffset).getBigUint64(0, true))
+}
+
+let _sym: ReturnType<typeof loadLib>["symbols"] | undefined
+
+function sym() {
+ if (!_sym) _sym = loadLib().symbols
+ return _sym
+}
+
+function loadLib() {
+ return dlopen("/System/Library/Frameworks/Security.framework/Security", {
+ SecKeychainAddGenericPassword: {
+ args: [FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.ptr],
+ returns: FFIType.i32,
+ },
+ SecKeychainFindGenericPassword: {
+ args: [FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.ptr],
+ returns: FFIType.i32,
+ },
+ SecKeychainItemModifyAttributesAndData: {
+ args: [FFIType.ptr, FFIType.ptr, FFIType.u32, FFIType.ptr],
+ returns: FFIType.i32,
+ },
+ SecKeychainItemFreeContent: {
+ args: [FFIType.ptr, FFIType.ptr],
+ returns: FFIType.i32,
+ },
+ SecKeychainItemDelete: {
+ args: [FFIType.ptr],
+ returns: FFIType.i32,
+ },
+ CFRelease: {
+ args: [FFIType.ptr],
+ returns: FFIType.void,
+ },
+ } as const)
+}
+
+export function keychainGet(service: string, account: string): string | undefined {
+ const svc = Buffer.from(service)
+ const acc = Buffer.from(account)
+ const lenBuf = new Uint8Array(4)
+ const dataBuf = new Uint8Array(8)
+
+ const s = sym().SecKeychainFindGenericPassword(
+ null,
+ svc.byteLength, ptr(svc),
+ acc.byteLength, ptr(acc),
+ ptr(lenBuf), ptr(dataBuf),
+ null,
+ ) as number
+
+ if (s === errSecItemNotFound) return undefined
+ if (s !== errSecSuccess) throw keychainError("read", s)
+
+ const dataPtr = readPtr(dataBuf)
+ const dataLen = new DataView(lenBuf.buffer).getUint32(0, true)
+ const result = Buffer.from(toArrayBuffer(dataPtr, 0, dataLen)).toString("utf8")
+ sym().SecKeychainItemFreeContent(null, dataPtr)
+ return result
+}
+
+export function keychainSet(service: string, account: string, password: string): void {
+ const svc = Buffer.from(service)
+ const acc = Buffer.from(account)
+ const pwd = Buffer.from(password)
+ const itemBuf = new Uint8Array(8)
+
+ let s = sym().SecKeychainAddGenericPassword(
+ null,
+ svc.byteLength, ptr(svc),
+ acc.byteLength, ptr(acc),
+ pwd.byteLength, ptr(pwd),
+ ptr(itemBuf),
+ ) as number
+
+ if (s === errSecSuccess) {
+ const ref = readPtr(itemBuf)
+ if (ref) sym().CFRelease(ref)
+ return
+ }
+
+ if (s !== errSecDuplicateItem) throw keychainError("add", s)
+
+ // Item exists — find it and update in place
+ const itemBuf2 = new Uint8Array(8)
+ s = sym().SecKeychainFindGenericPassword(
+ null,
+ svc.byteLength, ptr(svc),
+ acc.byteLength, ptr(acc),
+ null, null,
+ ptr(itemBuf2),
+ ) as number
+ if (s !== errSecSuccess) throw keychainError("find for update", s)
+
+ const itemRef = readPtr(itemBuf2)
+ s = sym().SecKeychainItemModifyAttributesAndData(itemRef, null, pwd.byteLength, ptr(pwd)) as number
+ sym().CFRelease(itemRef)
+ if (s !== errSecSuccess) throw keychainError("update", s)
+}
+
+export function keychainDelete(service: string, account: string): void {
+ const svc = Buffer.from(service)
+ const acc = Buffer.from(account)
+ const itemBuf = new Uint8Array(8)
+
+ const s = sym().SecKeychainFindGenericPassword(
+ null,
+ svc.byteLength, ptr(svc),
+ acc.byteLength, ptr(acc),
+ null, null,
+ ptr(itemBuf),
+ ) as number
+
+ if (s === errSecItemNotFound) return
+ if (s !== errSecSuccess) throw keychainError("find for delete", s)
+
+ const itemRef = readPtr(itemBuf)
+ sym().SecKeychainItemDelete(itemRef)
+ sym().CFRelease(itemRef)
+}
+
+function keychainError(op: string, code: number): Error {
+ const err = new Error(`Keychain ${op} failed: ${code}`) as Error & { code: number }
+ err.code = code
+ return err
+}
diff --git a/src/providers/codex/auth/token-store.ts b/src/providers/codex/auth/token-store.ts
index ae85d48..5f1b479 100644
--- a/src/providers/codex/auth/token-store.ts
+++ b/src/providers/codex/auth/token-store.ts
@@ -1,6 +1,7 @@
import { mkdir, readFile, writeFile, chmod, unlink, rename } from "node:fs/promises"
import { dirname, join } from "node:path"
import { homedir } from "node:os"
+import { keychainGet, keychainSet, keychainDelete } from "../../../keychain.ts"
export interface StoredAuth {
access: string
@@ -16,10 +17,7 @@ const KEYCHAIN_ACCOUNT = "auth"
export async function loadAuth(): Promise<StoredAuth | undefined> {
if (process.platform === "darwin") {
- const raw = await readKeychain().catch((err: Error & { code?: number }) => {
- if (err.code === 44) return undefined
- throw err
- })
+ const raw = keychainGet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT)
if (!raw) return undefined
return JSON.parse(raw) as StoredAuth
}
@@ -35,37 +33,19 @@ export async function loadAuth(): Promise<StoredAuth | undefined> {
export async function saveAuth(auth: StoredAuth): Promise<void> {
if (process.platform === "darwin") {
- await runSecurity([
- "add-generic-password",
- "-U",
- "-a",
- KEYCHAIN_ACCOUNT,
- "-s",
- KEYCHAIN_SERVICE,
- "-w",
- JSON.stringify(auth),
- ])
+ keychainSet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT, JSON.stringify(auth))
return
}
await mkdir(dirname(FILE), { recursive: true })
const tmp = `${FILE}.${process.pid}.${Date.now()}.tmp`
await writeFile(tmp, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 0o600 })
- try {
- await chmod(tmp, 0o600)
- } catch {
- // best-effort; mode in writeFile options usually suffices
- }
await rename(tmp, FILE)
}
export async function clearAuth(): Promise<void> {
if (process.platform === "darwin") {
- await runSecurity(["delete-generic-password", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE]).catch(
- (err: Error & { code?: number }) => {
- if (err.code !== 44) throw err
- },
- )
+ keychainDelete(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT)
return
}
@@ -79,26 +59,3 @@ export async function clearAuth(): Promise<void> {
export function authPath(): string {
return process.platform === "darwin" ? "macOS Keychain" : FILE
}
-
-async function readKeychain(): Promise<string> {
- const { stdout } = await runSecurity(["find-generic-password", "-w", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE])
- return stdout.trim()
-}
-
-async function runSecurity(args: string[]): Promise<{ stdout: string; stderr: string }> {
- const proc = Bun.spawn(["security", ...args], {
- stdout: "pipe",
- stderr: "pipe",
- })
- const [stdout, stderr, exitCode] = await Promise.all([
- new Response(proc.stdout).text(),
- new Response(proc.stderr).text(),
- proc.exited,
- ])
- if (exitCode !== 0) {
- const err = new Error(stderr.trim() || `security exited with ${exitCode}`) as Error & { code?: number }
- err.code = exitCode
- throw err
- }
- return { stdout, stderr }
-}
diff --git a/src/providers/kimi/auth/token-store.ts b/src/providers/kimi/auth/token-store.ts
index cf7878e..72eaed2 100644
--- a/src/providers/kimi/auth/token-store.ts
+++ b/src/providers/kimi/auth/token-store.ts
@@ -1,6 +1,7 @@
-import { mkdir, readFile, writeFile, chmod, unlink, rename } from "node:fs/promises"
+import { mkdir, readFile, writeFile, unlink, rename } from "node:fs/promises"
import { dirname, join } from "node:path"
import { homedir } from "node:os"
+import { keychainGet, keychainSet, keychainDelete } from "../../../keychain.ts"
export interface StoredAuth {
access: string
@@ -17,10 +18,7 @@ const KEYCHAIN_ACCOUNT = "auth"
export async function loadAuth(): Promise<StoredAuth | undefined> {
if (process.platform === "darwin") {
- const raw = await readKeychain().catch((err: Error & { code?: number }) => {
- if (err.code === 44) return undefined
- throw err
- })
+ const raw = keychainGet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT)
if (!raw) return undefined
return JSON.parse(raw) as StoredAuth
}
@@ -36,35 +34,19 @@ export async function loadAuth(): Promise<StoredAuth | undefined> {
export async function saveAuth(auth: StoredAuth): Promise<void> {
if (process.platform === "darwin") {
- await runSecurity([
- "add-generic-password",
- "-U",
- "-a",
- KEYCHAIN_ACCOUNT,
- "-s",
- KEYCHAIN_SERVICE,
- "-w",
- JSON.stringify(auth),
- ])
+ keychainSet(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT, JSON.stringify(auth))
return
}
await mkdir(dirname(FILE), { recursive: true })
const tmp = `${FILE}.${process.pid}.${Date.now()}.tmp`
await writeFile(tmp, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 0o600 })
- try {
- await chmod(tmp, 0o600)
- } catch {}
await rename(tmp, FILE)
}
export async function clearAuth(): Promise<void> {
if (process.platform === "darwin") {
- await runSecurity(["delete-generic-password", "-a", KEYCHAIN_ACCOUNT, "-s", KEYCHAIN_SERVICE]).catch(
- (err: Error & { code?: number }) => {
- if (err.code !== 44) throw err
- },
- )
+ keychainDelete(KEYCHAIN_SERVICE, KEYCHAIN_ACCOUNT)
return
}
@@ -78,32 +60,3 @@ export async function clearAuth(): Promise<void> {
export function authPath(): string {
return process.platform === "darwin" ? "macOS Keychain" : FILE
}
-
-async function readKeychain(): Promise<string> {
- const { stdout } = await runSecurity([
- "find-generic-password",
- "-w",
- "-a",
- KEYCHAIN_ACCOUNT,
- "-s",
- KEYCHAIN_SERVICE,
- ])
- return stdout.trim()
-}
-
-async function runSecurity(args: string[]): Promise<{ stdout: string; stderr: string }> {
- const proc = Bun.spawn(["security", ...args], { stdout: "pipe", stderr: "pipe" })
- const [stdout, stderr, exitCode] = await Promise.all([
- new Response(proc.stdout).text(),
- new Response(proc.stderr).text(),
- proc.exited,
- ])
- if (exitCode !== 0) {
- const err = new Error(stderr.trim() || `security exited with ${exitCode}`) as Error & {
- code?: number
- }
- err.code = exitCode
- throw err
- }
- return { stdout, stderr }
-}