Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 193 lines 6.59 KB
Raw
1 /**
2 * Windows Credential Manager store backed by `advapi32.dll` via `bun:ffi`.
3 *
4 * Each credential is a generic credential (`CRED_TYPE_GENERIC`) whose target
5 * name is `{user}.{service}`, the convention keyring-rs uses on Windows. The
6 * secret is stored as the raw credential blob, which Windows encrypts with
7 * the signed-in user's key; other users of the machine cannot read it.
8 *
9 * There is no subprocess fallback: Windows ships no tool that reads a generic
10 * credential back. This module must not be imported from Node, because it
11 * depends on `bun:ffi`; `createDefaultStore` loads it only under Bun.
12 */
13
14 import { dlopen, FFIType, ptr, toArrayBuffer } from 'bun:ffi';
15 import type { CredentialStore, EntryModifiers } from '../core/store';
16 import { CredentialPersistence } from '../core/persistence';
17 import { KeyringError } from '../core/errors';
18
19 const CRED_TYPE_GENERIC = 1;
20 /** Kept across sign-ins on this machine, and not roamed to other machines. */
21 const CRED_PERSIST_LOCAL_MACHINE = 2;
22 /** `CRED_MAX_CREDENTIAL_BLOB_SIZE` from wincred.h. */
23 const MAX_SECRET_BYTES = 5 * 512;
24 const ERROR_NOT_FOUND = 1168;
25
26 /**
27 * Field offsets of `CREDENTIALW` on 64-bit Windows:
28 *
29 * 0 DWORD Flags
30 * 4 DWORD Type
31 * 8 LPWSTR TargetName
32 * 16 LPWSTR Comment
33 * 24 FILETIME LastWritten
34 * 32 DWORD CredentialBlobSize
35 * 40 LPBYTE CredentialBlob
36 * 48 DWORD Persist
37 * 52 DWORD AttributeCount
38 * 56 PCREDENTIAL_ATTRIBUTEW Attributes
39 * 64 LPWSTR TargetAlias
40 * 72 LPWSTR UserName
41 */
42 const CREDENTIAL_SIZE = 80;
43 const OFFSET_TYPE = 4;
44 const OFFSET_TARGET_NAME = 8;
45 const OFFSET_BLOB_SIZE = 32;
46 const OFFSET_BLOB = 40;
47 const OFFSET_PERSIST = 48;
48 const OFFSET_USER_NAME = 72;
49
50 const advapi32 = dlopen('advapi32.dll', {
51 CredWriteW: { args: [FFIType.ptr, FFIType.u32], returns: FFIType.i32 },
52 CredReadW: {
53 args: [FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.ptr],
54 returns: FFIType.i32,
55 },
56 CredDeleteW: { args: [FFIType.ptr, FFIType.u32, FFIType.u32], returns: FFIType.i32 },
57 CredFree: { args: [FFIType.u64], returns: FFIType.void },
58 });
59
60 const kernel32 = dlopen('kernel32.dll', {
61 GetLastError: { args: [], returns: FFIType.u32 },
62 });
63
64 /** Encode a JS string as a NUL-terminated UTF-16 buffer (`LPCWSTR`). */
65 function wstr(value: string): Uint16Array {
66 const buffer = new Uint16Array(value.length + 1);
67 for (let i = 0; i < value.length; i++) buffer[i] = value.charCodeAt(i);
68 return buffer;
69 }
70
71 function targetName(service: string, user: string): string {
72 return `${user}.${service}`;
73 }
74
75 function validateSpecifier(service: string, user: string): void {
76 for (const [param, value] of [
77 ['service', service],
78 ['user', user],
79 ] as const) {
80 if (value.length === 0) {
81 throw new KeyringError({
82 kind: 'Invalid',
83 param,
84 reason: `${param} must be a non-empty string`,
85 });
86 }
87 if (value.includes('\0')) {
88 throw new KeyringError({ kind: 'Invalid', param, reason: 'must not contain NUL bytes' });
89 }
90 }
91 }
92
93 /**
94 * Map a failed `Cred*` call to a `KeyringError`. A lookup that fails without
95 * an error code is treated as a missing entry: the runtime can reset the
96 * thread's last-error value between the failing call and `GetLastError`.
97 */
98 function lookupError(operation: string): KeyringError {
99 const code = kernel32.symbols.GetLastError();
100 if (code === ERROR_NOT_FOUND || code === 0) {
101 return new KeyringError({ kind: 'NoEntry' });
102 }
103 return platformFailure(operation, code);
104 }
105
106 function platformFailure(operation: string, code: number): KeyringError {
107 return new KeyringError({
108 kind: 'PlatformFailure',
109 cause: new Error(`${operation} failed with Windows error ${code}`),
110 });
111 }
112
113 export class WindowsCredentialFFIStore implements CredentialStore {
114 readonly id = 'windows-credential-ffi';
115 readonly vendor = 'Windows Credential Manager (via bun:ffi Cred*)';
116
117 persistence(): CredentialPersistence {
118 return CredentialPersistence.UntilDelete;
119 }
120
121 async setSecret(
122 service: string,
123 user: string,
124 secret: Uint8Array,
125 _modifiers: EntryModifiers
126 ): Promise<void> {
127 validateSpecifier(service, user);
128 if (secret.byteLength > MAX_SECRET_BYTES) {
129 throw new KeyringError({ kind: 'TooLong', attr: 'secret', limit: MAX_SECRET_BYTES });
130 }
131
132 // These buffers are referenced by address from the struct, so they must
133 // stay alive until CredWriteW returns.
134 const target = wstr(targetName(service, user));
135 const userName = wstr(user);
136 const blob = Uint8Array.from(secret);
137
138 const credential = new Uint8Array(CREDENTIAL_SIZE);
139 const view = new DataView(credential.buffer);
140 view.setUint32(OFFSET_TYPE, CRED_TYPE_GENERIC, true);
141 view.setBigUint64(OFFSET_TARGET_NAME, BigInt(ptr(target)), true);
142 view.setUint32(OFFSET_BLOB_SIZE, blob.byteLength, true);
143 view.setBigUint64(OFFSET_BLOB, blob.byteLength === 0 ? 0n : BigInt(ptr(blob)), true);
144 view.setUint32(OFFSET_PERSIST, CRED_PERSIST_LOCAL_MACHINE, true);
145 view.setBigUint64(OFFSET_USER_NAME, BigInt(ptr(userName)), true);
146
147 // CredWriteW replaces an existing credential with the same target name.
148 const written = advapi32.symbols.CredWriteW(credential, 0);
149 if (written === 0) {
150 throw platformFailure('CredWriteW', kernel32.symbols.GetLastError());
151 }
152 }
153
154 async getSecret(service: string, user: string, _modifiers: EntryModifiers): Promise<Uint8Array> {
155 validateSpecifier(service, user);
156
157 // CredReadW writes a PCREDENTIALW into this 8-byte slot.
158 const credentialOut = new BigUint64Array(1);
159 const found = advapi32.symbols.CredReadW(
160 wstr(targetName(service, user)),
161 CRED_TYPE_GENERIC,
162 0,
163 credentialOut
164 );
165 if (found === 0) {
166 throw lookupError('CredReadW');
167 }
168
169 const credential = credentialOut[0] ?? 0n;
170 try {
171 const view = new DataView(toArrayBuffer(Number(credential) as never, 0, CREDENTIAL_SIZE));
172 const size = view.getUint32(OFFSET_BLOB_SIZE, true);
173 const blob = view.getBigUint64(OFFSET_BLOB, true);
174 if (size === 0 || blob === 0n) return new Uint8Array(0);
175 // Copy: the memory belongs to Windows and is released by CredFree below.
176 return new Uint8Array(toArrayBuffer(Number(blob) as never, 0, size)).slice();
177 } finally {
178 advapi32.symbols.CredFree(credential);
179 }
180 }
181
182 async deleteCredential(service: string, user: string, _modifiers: EntryModifiers): Promise<void> {
183 validateSpecifier(service, user);
184 const deleted = advapi32.symbols.CredDeleteW(
185 wstr(targetName(service, user)),
186 CRED_TYPE_GENERIC,
187 0
188 );
189 if (deleted === 0) {
190 throw lookupError('CredDeleteW');
191 }
192 }
193 }