1
+/**
2
+ * macOS Keychain store backed by direct Security.framework calls via
3
+ * `bun:ffi`. Structurally this is a TypeScript port of the relevant
4
+ * subset of keyring-rs's `apple-native-keyring-store` crate — which
5
+ * itself delegates to the `security-framework` Rust crate — but we
6
+ * skip the Rust layer and call the C ABI directly from Bun.
7
+ *
8
+ * Why FFI instead of the subprocess `/usr/bin/security` CLI?
9
+ *
10
+ * - **Performance.** A subprocess fork/exec round-trip is ~25ms
11
+ * median and ~150ms p99 on a warm Mac. A direct `SecItemCopyMatching`
12
+ * call is sub-millisecond. For hot-path commands (`composio execute`,
13
+ * `composio run`) this is a 25× improvement per invocation with
14
+ * effectively zero tail.
15
+ * - **Upgrade-stable ACL.** The item's access control is built with
16
+ * `SecAccessCreate` + the "allow-any" pattern (empty trusted apps
17
+ * list, no-prompt selector — mirrors what `security -A` produces),
18
+ * so the ACL does not depend on the composio binary's code
19
+ * signature. `composio upgrade` never triggers a keychain dialog.
20
+ *
21
+ * The allow-any ACL matches the threat model of the subprocess
22
+ * implementation exactly: silent exfil via a plaintext file becomes
23
+ * visible exfil via the Bash tool prompt ("claude wants to run
24
+ * /usr/bin/security find-generic-password …"), but the OS does not
25
+ * gate reads to our binary specifically. Upgrading this to a
26
+ * per-binary ACL requires the `composio` binary to be signed with a
27
+ * stable Developer ID certificate so the ACL's designated
28
+ * requirement can survive self-update — that is a separate
29
+ * operational PR, not handled here. When it lands, the
30
+ * `buildAllowAnyAccess` call in `setSecret` is replaced with a
31
+ * single call to a new `buildComposioOnlyAccess` builder that
32
+ * constructs a `SecAccessRef` with the composio binary in the
33
+ * trusted list. The rest of the module is unchanged.
34
+ *
35
+ * Pointer representation: every CoreFoundation / Security
36
+ * reference is carried as `bigint`, never `number`. Reason: short
37
+ * `CFString` values and other small CF types are represented as
38
+ * **tagged pointers** in CoreFoundation — the string data is packed
39
+ * directly into pointer bits with the high bits set as tag
40
+ * markers, producing addresses above 2^53. JavaScript's `number`
41
+ * type loses precision above that threshold, so a tagged pointer
42
+ * received as `number` cannot be passed back to another FFI call
43
+ * intact. Declaring every pointer arg/return as `FFIType.u64`
44
+ * preserves full 64-bit fidelity via `BigInt`.
45
+ *
46
+ * This module must not be imported from Node — it depends on
47
+ * `bun:ffi`. The platform picker in `macos-security.ts` is
48
+ * responsible for loading this file only when `typeof Bun !==
49
+ * 'undefined'`.
50
+ */
51
+
52
+import { dlopen, FFIType, ptr, toArrayBuffer } from 'bun:ffi';
53
+import type { CredentialStore, EntryModifiers } from '../core/store';
54
+import { CredentialPersistence } from '../core/persistence';
55
+import { KeyringError } from '../core/errors';
56
+import { bytesToUtf8, decodeSecret, encodeSecret, runCommand } from './shared';
57
+
58
+const textEncoder = new TextEncoder();
59
+const textDecoder = new TextDecoder('utf-8');
60
+const SECURITY_BIN = '/usr/bin/security';
61
+
62
+/** Encode a JS string as a NUL-terminated UTF-8 byte array (for dlopen/dlsym). */
63
+function cstr(s: string): Uint8Array {
64
+ return textEncoder.encode(s + '\0');
65
+}
66
+
67
+// -----------------------------------------------------------------------------
68
+// Low-level dlopen / dlsym (used to resolve `kSec*` / `kCF*` extern const
69
+// data symbols that `bun:ffi`'s normal dlopen surface doesn't expose).
70
+// -----------------------------------------------------------------------------
71
+
72
+const LIBSYSTEM = '/usr/lib/libSystem.B.dylib';
73
+const SECURITY_FRAMEWORK = '/System/Library/Frameworks/Security.framework/Security';
74
+const CORE_FOUNDATION = '/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation';
75
+
76
+const RTLD_NOW = 0x2;
77
+
78
+const libSystem = dlopen(LIBSYSTEM, {
79
+ dlopen: { args: [FFIType.ptr, FFIType.i32], returns: FFIType.u64 },
80
+ dlsym: { args: [FFIType.u64, FFIType.ptr], returns: FFIType.u64 },
81
+});
82
+
83
+function dlopenRaw(path: string): bigint {
84
+ const handle = libSystem.symbols.dlopen(cstr(path), RTLD_NOW);
85
+ if (handle === 0n) {
86
+ throw new KeyringError({
87
+ kind: 'PlatformFailure',
88
+ cause: new Error(`dlopen(${path}) failed`),
89
+ });
90
+ }
91
+ return handle;
92
+}
93
+
94
+/**
95
+ * Resolve an extern const CFTypeRef data symbol: `dlsym` returns the
96
+ * address of the storage slot (i.e. a pointer-to-pointer); we
97
+ * dereference one level via `read.ptr` to get the actual CFTypeRef
98
+ * value stored there. The symbol is stable for the process lifetime,
99
+ * so caching the resolved BigInt is safe.
100
+ */
101
+function dlsymCFConstant(handle: bigint, name: string): bigint {
102
+ const addr = libSystem.symbols.dlsym(handle, cstr(name));
103
+ if (addr === 0n) {
104
+ throw new KeyringError({
105
+ kind: 'PlatformFailure',
106
+ cause: new Error(`dlsym(${name}) failed`),
107
+ });
108
+ }
109
+ // read.ptr wants a number address — the storage address from dlsym
110
+ // is a real heap address (never tagged), so it fits in a number.
111
+ // The VALUE we read back, however, may be a tagged pointer, so we
112
+ // must capture it as BigInt. `read.ptr` on bun returns number;
113
+ // instead we use a small helper that reads 8 bytes into a BigInt.
114
+ return read64(Number(addr));
115
+}
116
+
117
+/**
118
+ * Read a 64-bit little-endian value from a process address and
119
+ * return it as BigInt. Used to dereference data-symbol slots (which
120
+ * live at plain heap addresses) without precision loss on the
121
+ * stored value.
122
+ */
123
+function read64(address: number): bigint {
124
+ // `toArrayBuffer(ptr, offset, length)` wraps a raw pointer as an
125
+ // ArrayBuffer view without copying. We use it for read-only access
126
+ // to an 8-byte window, then pull the BigInt out via DataView.
127
+ const ab = toArrayBuffer(address as unknown as never, 0, 8);
128
+ return new DataView(ab).getBigUint64(0, true);
129
+}
130
+
131
+const securityHandle = dlopenRaw(SECURITY_FRAMEWORK);
132
+const coreFoundationHandle = dlopenRaw(CORE_FOUNDATION);
133
+
134
+// -----------------------------------------------------------------------------
135
+// Function bindings (CoreFoundation + Security.framework)
136
+// -----------------------------------------------------------------------------
137
+
138
+const cf = dlopen(CORE_FOUNDATION, {
139
+ CFStringCreateWithBytes: {
140
+ // allocator, bytes, length, encoding, isExternalRepresentation
141
+ args: [FFIType.u64, FFIType.ptr, FFIType.i64, FFIType.u32, FFIType.bool],
142
+ returns: FFIType.u64,
143
+ },
144
+ CFStringGetCString: {
145
+ args: [FFIType.u64, FFIType.ptr, FFIType.i64, FFIType.u32],
146
+ returns: FFIType.bool,
147
+ },
148
+ CFDataCreate: {
149
+ args: [FFIType.u64, FFIType.ptr, FFIType.i64],
150
+ returns: FFIType.u64,
151
+ },
152
+ CFDataGetBytePtr: {
153
+ args: [FFIType.u64],
154
+ returns: FFIType.u64,
155
+ },
156
+ CFDataGetLength: {
157
+ args: [FFIType.u64],
158
+ returns: FFIType.i64,
159
+ },
160
+ CFDictionaryCreateMutable: {
161
+ args: [FFIType.u64, FFIType.i64, FFIType.u64, FFIType.u64],
162
+ returns: FFIType.u64,
163
+ },
164
+ CFDictionaryAddValue: {
165
+ args: [FFIType.u64, FFIType.u64, FFIType.u64],
166
+ returns: FFIType.void,
167
+ },
168
+ CFArrayGetCount: {
169
+ args: [FFIType.u64],
170
+ returns: FFIType.i64,
171
+ },
172
+ CFArrayGetValueAtIndex: {
173
+ args: [FFIType.u64, FFIType.i64],
174
+ returns: FFIType.u64,
175
+ },
176
+ CFRelease: {
177
+ args: [FFIType.u64],
178
+ returns: FFIType.void,
179
+ },
180
+ CFGetTypeID: {
181
+ args: [FFIType.u64],
182
+ returns: FFIType.u64,
183
+ },
184
+});
185
+
186
+const sec = dlopen(SECURITY_FRAMEWORK, {
187
+ SecItemAdd: {
188
+ args: [FFIType.u64, FFIType.u64],
189
+ returns: FFIType.i32,
190
+ },
191
+ SecItemCopyMatching: {
192
+ args: [FFIType.u64, FFIType.u64],
193
+ returns: FFIType.i32,
194
+ },
195
+ SecItemUpdate: {
196
+ args: [FFIType.u64, FFIType.u64],
197
+ returns: FFIType.i32,
198
+ },
199
+ SecItemDelete: {
200
+ args: [FFIType.u64],
201
+ returns: FFIType.i32,
202
+ },
203
+ SecCopyErrorMessageString: {
204
+ args: [FFIType.i32, FFIType.u64],
205
+ returns: FFIType.u64,
206
+ },
207
+});
208
+
209
+// -----------------------------------------------------------------------------
210
+// Constant resolution
211
+// -----------------------------------------------------------------------------
212
+
213
+/** Resolved extern CFTypeRef constants (stable for process lifetime). */
214
+const K = {
215
+ kSecClass: dlsymCFConstant(securityHandle, 'kSecClass'),
216
+ kSecClassGenericPassword: dlsymCFConstant(securityHandle, 'kSecClassGenericPassword'),
217
+ kSecAttrService: dlsymCFConstant(securityHandle, 'kSecAttrService'),
218
+ kSecAttrAccount: dlsymCFConstant(securityHandle, 'kSecAttrAccount'),
219
+ kSecValueData: dlsymCFConstant(securityHandle, 'kSecValueData'),
220
+ kSecReturnData: dlsymCFConstant(securityHandle, 'kSecReturnData'),
221
+ kSecMatchLimit: dlsymCFConstant(securityHandle, 'kSecMatchLimit'),
222
+ kSecMatchLimitOne: dlsymCFConstant(securityHandle, 'kSecMatchLimitOne'),
223
+ kCFBooleanTrue: dlsymCFConstant(coreFoundationHandle, 'kCFBooleanTrue'),
224
+ kCFTypeDictionaryKeyCallBacks: BigInt(
225
+ addressOfSymbol(coreFoundationHandle, 'kCFTypeDictionaryKeyCallBacks')
226
+ ),
227
+ kCFTypeDictionaryValueCallBacks: BigInt(
228
+ addressOfSymbol(coreFoundationHandle, 'kCFTypeDictionaryValueCallBacks')
229
+ ),
230
+} as const;
231
+
232
+/**
233
+ * Return the *address* of a named data symbol (not its dereferenced
234
+ * value). Used for the `kCFType*CallBacks` structs, which are
235
+ * structs in static data rather than pointers — the function wants a
236
+ * pointer TO the struct, not a pointer read out of the symbol slot.
237
+ */
238
+function addressOfSymbol(handle: bigint, name: string): bigint {
239
+ const addr = libSystem.symbols.dlsym(handle, cstr(name));
240
+ if (addr === 0n) {
241
+ throw new KeyringError({
242
+ kind: 'PlatformFailure',
243
+ cause: new Error(`dlsym(${name}) failed`),
244
+ });
245
+ }
246
+ return addr;
247
+}
248
+
249
+/** UTF-8 encoding constant for CFString. */
250
+const kCFStringEncodingUTF8 = 0x08000100;
251
+
252
+// -----------------------------------------------------------------------------
253
+// OSStatus mapping
254
+// -----------------------------------------------------------------------------
255
+
256
+const errSecSuccess = 0;
257
+const errSecItemNotFound = -25300;
258
+const errSecAuthFailed = -25293;
259
+const errSecNotAvailable = -25291;
260
+const errSecReadOnly = -25292;
261
+const errSecNoSuchKeychain = -25294;
262
+const errSecInvalidKeychain = -25295;
263
+const errSecWrPerm = -61;
264
+
265
+const NO_STORAGE_ACCESS_STATUSES = new Set([
266
+ errSecNotAvailable,
267
+ errSecReadOnly,
268
+ errSecNoSuchKeychain,
269
+ errSecInvalidKeychain,
270
+ errSecAuthFailed,
271
+ errSecWrPerm,
272
+]);
273
+
274
+/**
275
+ * Convert an OSStatus into a KeyringError. Uses
276
+ * `SecCopyErrorMessageString` to pull the human-readable description
277
+ * out of the Security framework.
278
+ */
279
+function osStatusToError(status: number, operation: string): KeyringError {
280
+ if (status === errSecItemNotFound) {
281
+ return new KeyringError({ kind: 'NoEntry' });
282
+ }
283
+ const message = osStatusMessage(status) ?? `${operation} failed with OSStatus ${status}`;
284
+ if (NO_STORAGE_ACCESS_STATUSES.has(status)) {
285
+ return new KeyringError({
286
+ kind: 'NoStorageAccess',
287
+ cause: new Error(message),
288
+ });
289
+ }
290
+ return new KeyringError({
291
+ kind: 'PlatformFailure',
292
+ cause: new Error(`${operation}: ${message}`),
293
+ });
294
+}
295
+
296
+function osStatusMessage(status: number): string | null {
297
+ const cfString = sec.symbols.SecCopyErrorMessageString(status, 0n);
298
+ if (cfString === 0n) return null;
299
+ try {
300
+ return cfStringToJs(cfString);
301
+ } finally {
302
+ cf.symbols.CFRelease(cfString);
303
+ }
304
+}
305
+
306
+// -----------------------------------------------------------------------------
307
+// CoreFoundation helpers
308
+// -----------------------------------------------------------------------------
309
+
310
+/**
311
+ * A "retain pool" that releases every CF object pushed into it when
312
+ * `release()` runs. Used to guarantee cleanup across the (potentially
313
+ * many) CF allocations each store operation performs.
314
+ */
315
+class CFPool {
316
+ private readonly refs: bigint[] = [];
317
+
318
+ /** Push a CFTypeRef into the pool and return it unchanged for chaining. */
319
+ retain(ref: bigint): bigint {
320
+ if (ref !== 0n) this.refs.push(ref);
321
+ return ref;
322
+ }
323
+
324
+ release(): void {
325
+ // Release in reverse order of allocation to match object graph.
326
+ for (let i = this.refs.length - 1; i >= 0; i--) {
327
+ cf.symbols.CFRelease(this.refs[i]!);
328
+ }
329
+ this.refs.length = 0;
330
+ }
331
+}
332
+
333
+/** Create a CFString from a JS string (UTF-8 bytes). Throws on allocation failure. */
334
+function cfStringFromJs(pool: CFPool, s: string): bigint {
335
+ const bytes = textEncoder.encode(s);
336
+ const ref = cf.symbols.CFStringCreateWithBytes(
337
+ 0n, // kCFAllocatorDefault
338
+ bytes,
339
+ BigInt(bytes.byteLength),
340
+ kCFStringEncodingUTF8,
341
+ false
342
+ );
343
+ if (ref === 0n) {
344
+ throw new KeyringError({
345
+ kind: 'PlatformFailure',
346
+ cause: new Error('CFStringCreateWithBytes returned NULL'),
347
+ });
348
+ }
349
+ return pool.retain(ref);
350
+}
351
+
352
+/** Read a CFString into a JS UTF-8 string. Only used for error messages. */
353
+function cfStringToJs(cfString: bigint): string {
354
+ const buf = new Uint8Array(4096);
355
+ const ok = cf.symbols.CFStringGetCString(
356
+ cfString,
357
+ buf,
358
+ BigInt(buf.byteLength),
359
+ kCFStringEncodingUTF8
360
+ );
361
+ if (!ok) return '<unrepresentable>';
362
+ const end = buf.indexOf(0);
363
+ return textDecoder.decode(buf.subarray(0, end === -1 ? buf.byteLength : end));
364
+}
365
+
366
+/** Extract raw bytes from a CFData. */
367
+function cfDataToBytes(cfData: bigint): Uint8Array {
368
+ const length = Number(cf.symbols.CFDataGetLength(cfData));
369
+ if (length === 0) return new Uint8Array();
370
+ const bytePtr = cf.symbols.CFDataGetBytePtr(cfData);
371
+ if (bytePtr === 0n) {
372
+ throw new KeyringError({
373
+ kind: 'PlatformFailure',
374
+ cause: new Error('CFDataGetBytePtr returned NULL'),
375
+ });
376
+ }
377
+ // CFData storage is a real heap pointer (never tagged), so the
378
+ // BigInt value fits in JS safe integer range and we can hand it to
379
+ // toArrayBuffer via Number. Copy into JS-owned memory so we don't
380
+ // retain the CFData longer than necessary.
381
+ const view = new Uint8Array(toArrayBuffer(Number(bytePtr) as unknown as never, 0, length));
382
+ return new Uint8Array(view);
383
+}
384
+
385
+/** Build a mutable CFDictionary. */
386
+function cfMutableDict(pool: CFPool): bigint {
387
+ const dict = cf.symbols.CFDictionaryCreateMutable(
388
+ 0n,
389
+ 0n,
390
+ K.kCFTypeDictionaryKeyCallBacks,
391
+ K.kCFTypeDictionaryValueCallBacks
392
+ );
393
+ if (dict === 0n) {
394
+ throw new KeyringError({
395
+ kind: 'PlatformFailure',
396
+ cause: new Error('CFDictionaryCreateMutable returned NULL'),
397
+ });
398
+ }
399
+ return pool.retain(dict);
400
+}
401
+
402
+function cfDictSet(dict: bigint, key: bigint, value: bigint): void {
403
+ cf.symbols.CFDictionaryAddValue(dict, key, value);
404
+}
405
+
406
+// -----------------------------------------------------------------------------
407
+// Store implementation
408
+// -----------------------------------------------------------------------------
409
+
410
+function validateSpecifier(service: string, user: string): void {
411
+ if (service.length === 0) {
412
+ throw new KeyringError({
413
+ kind: 'Invalid',
414
+ param: 'service',
415
+ reason: 'service must be a non-empty string',
416
+ });
417
+ }
418
+ if (user.length === 0) {
419
+ throw new KeyringError({
420
+ kind: 'Invalid',
421
+ param: 'user',
422
+ reason: 'user must be a non-empty string',
423
+ });
424
+ }
425
+ if (service.includes('\0') || user.includes('\0')) {
426
+ throw new KeyringError({
427
+ kind: 'Invalid',
428
+ param: service.includes('\0') ? 'service' : 'user',
429
+ reason: 'must not contain NUL bytes',
430
+ });
431
+ }
432
+}
433
+
434
+function defaultLabel(service: string, user: string): string {
435
+ return `keyring:${user}@${service}`;
436
+}
437
+
438
+export class MacOSSecurityFFIStore implements CredentialStore {
439
+ readonly id = 'macos-security-ffi';
440
+ readonly vendor = 'Apple Security.framework (via bun:ffi SecItem*)';
441
+
442
+ persistence(): CredentialPersistence {
443
+ return CredentialPersistence.UntilDelete;
444
+ }
445
+
446
+ async setSecret(
447
+ service: string,
448
+ user: string,
449
+ secret: Uint8Array,
450
+ modifiers: EntryModifiers
451
+ ): Promise<void> {
452
+ validateSpecifier(service, user);
453
+ if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {
454
+ throw new KeyringError({
455
+ kind: 'NotSupportedByStore',
456
+ operation: `macos keychain domain "${modifiers.keychain}"`,
457
+ });
458
+ }
459
+
460
+ // Writes delegate to `/usr/bin/security add-generic-password -A`
461
+ // (subprocess) because that is the ONLY path that reliably produces
462
+ // a genuine allow-any ACL. The Security.framework APIs
463
+ // (SecAccessCreate + SecACLSetSimpleContents with NULL
464
+ // applicationList + zero selector) should theoretically produce the
465
+ // same result, but in practice the items they produce still trigger
466
+ // the macOS trust dialog ("X wants to access key Y") when read
467
+ // from a different binary. Apple's `security` CLI uses internal
468
+ // codepaths that bypass this limitation.
469
+ //
470
+ // The write happens once per login/migration — its ~25ms cost is
471
+ // irrelevant relative to the network round-trip that follows. The
472
+ // hot path (reads on every `composio execute`) stays on FFI at
473
+ // ~1ms via SecItemCopyMatching.
474
+ const encoded = encodeSecret(secret);
475
+ const label = modifiers.label ?? defaultLabel(service, user);
476
+
477
+ // Delete-then-add pattern instead of `-U` (update-if-exists).
478
+ //
479
+ // `-U` updates the password but PRESERVES the old ACL. If the
480
+ // entry was previously created by the FFI ACL builder (which
481
+ // produces per-binary ACLs — see the long comment block above),
482
+ // the old broken ACL survives the `-U` update and the allow-any
483
+ // flag from `-A` is silently ignored. Deleting first guarantees
484
+ // the new `add-generic-password -A` creates a fresh entry with
485
+ // a genuine allow-any ACL.
486
+ //
487
+ // The delete is best-effort — if the entry doesn't exist yet
488
+ // (first login), the delete fails with errSecItemNotFound (exit
489
+ // 44) and we proceed to the add.
490
+ try {
491
+ await runCommand({
492
+ command: SECURITY_BIN,
493
+ args: ['delete-generic-password', '-a', user, '-s', service],
494
+ });
495
+ } catch {
496
+ // Spawn failure is fine — entry may not exist.
497
+ }
498
+
499
+ // `-A` = allow any application to read without prompting
500
+ // `-l` = human-readable label (shown in Keychain Access)
501
+ // `-w` = password value (on argv — brief `ps` visibility,
502
+ // documented in the package README)
503
+ const args = [
504
+ 'add-generic-password',
505
+ '-A',
506
+ '-a',
507
+ user,
508
+ '-s',
509
+ service,
510
+ '-l',
511
+ label,
512
+ '-w',
513
+ encoded,
514
+ ];
515
+
516
+ let result;
517
+ try {
518
+ result = await runCommand({ command: SECURITY_BIN, args });
519
+ } catch (err) {
520
+ throw new KeyringError({ kind: 'NoStorageAccess', cause: err });
521
+ }
522
+
523
+ if (result.code === 0) return;
524
+
525
+ const stderr = bytesToUtf8(result.stderr).trim();
526
+ throw new KeyringError({
527
+ kind: 'PlatformFailure',
528
+ cause: new Error(stderr || `security add-generic-password failed with exit ${result.code}`),
529
+ });
530
+ }
531
+
532
+ async getSecret(service: string, user: string, modifiers: EntryModifiers): Promise<Uint8Array> {
533
+ validateSpecifier(service, user);
534
+ if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {
535
+ throw new KeyringError({
536
+ kind: 'NotSupportedByStore',
537
+ operation: `macos keychain domain "${modifiers.keychain}"`,
538
+ });
539
+ }
540
+
541
+ const pool = new CFPool();
542
+ try {
543
+ const query = cfMutableDict(pool);
544
+ cfDictSet(query, K.kSecClass, K.kSecClassGenericPassword);
545
+ cfDictSet(query, K.kSecAttrService, cfStringFromJs(pool, service));
546
+ cfDictSet(query, K.kSecAttrAccount, cfStringFromJs(pool, user));
547
+ cfDictSet(query, K.kSecReturnData, K.kCFBooleanTrue);
548
+ cfDictSet(query, K.kSecMatchLimit, K.kSecMatchLimitOne);
549
+
550
+ // SecItemCopyMatching writes a CFTypeRef (here: CFDataRef because
551
+ // kSecReturnData=true, kSecMatchLimit=One) into the 8-byte slot.
552
+ const resultOut = new Uint8Array(8);
553
+ const status = sec.symbols.SecItemCopyMatching(query, BigInt(ptr(resultOut)));
554
+ if (status !== errSecSuccess) {
555
+ throw osStatusToError(status, 'SecItemCopyMatching');
556
+ }
557
+ const cfData = new DataView(resultOut.buffer).getBigUint64(0, true);
558
+ if (cfData === 0n) {
559
+ throw new KeyringError({ kind: 'NoEntry' });
560
+ }
561
+ try {
562
+ const encoded = cfDataToBytes(cfData);
563
+ // Legacy-item compatibility: if this entry was written by a
564
+ // pre-base64 version of the FFI backend, the bytes won't have
565
+ // the `b64:` prefix. `decodeSecret` throws in that case; we
566
+ // fall back to returning the raw bytes so one-time reads of
567
+ // old entries still work (the next setPassword call
568
+ // rewrites them in the canonical format).
569
+ try {
570
+ return decodeSecret(bytesToUtf8(encoded));
571
+ } catch {
572
+ return encoded;
573
+ }
574
+ } finally {
575
+ cf.symbols.CFRelease(cfData);
576
+ }
577
+ } finally {
578
+ pool.release();
579
+ }
580
+ }
581
+
582
+ async deleteCredential(service: string, user: string, modifiers: EntryModifiers): Promise<void> {
583
+ validateSpecifier(service, user);
584
+ if (modifiers.keychain !== undefined && modifiers.keychain !== 'User') {
585
+ throw new KeyringError({
586
+ kind: 'NotSupportedByStore',
587
+ operation: `macos keychain domain "${modifiers.keychain}"`,
588
+ });
589
+ }
590
+
591
+ const pool = new CFPool();
592
+ try {
593
+ const query = cfMutableDict(pool);
594
+ cfDictSet(query, K.kSecClass, K.kSecClassGenericPassword);
595
+ cfDictSet(query, K.kSecAttrService, cfStringFromJs(pool, service));
596
+ cfDictSet(query, K.kSecAttrAccount, cfStringFromJs(pool, user));
597
+
598
+ const status = sec.symbols.SecItemDelete(query);
599
+ if (status !== errSecSuccess) {
600
+ throw osStatusToError(status, 'SecItemDelete');
601
+ }
602
+ } finally {
603
+ pool.release();
604
+ }
605
+ }
606
+}