@sketric/favstash-mcp 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ import {
2
+ mkdir,
3
+ readFile,
4
+ writeFile,
5
+ rename,
6
+ unlink,
7
+ chmod,
8
+ lstat,
9
+ } from "node:fs/promises";
10
+ import {
11
+ randomUUID,
12
+ randomBytes,
13
+ createCipheriv,
14
+ createDecipheriv,
15
+ } from "node:crypto";
16
+ import path from "node:path";
17
+ import lockfile from "proper-lockfile";
18
+ import { configDirectory, endpointId } from "./config.js";
19
+
20
+ export async function privateDirectory(directory) {
21
+ await mkdir(directory, { recursive: true, mode: 0o700 });
22
+ const stat = await lstat(directory);
23
+ if (!stat.isDirectory() || stat.isSymbolicLink())
24
+ throw new Error(
25
+ "FavStash configuration directory must be a real directory.",
26
+ );
27
+ await chmod(directory, 0o700);
28
+ }
29
+
30
+ export async function atomicJson(file, value) {
31
+ const temporary = `${file}.${randomUUID()}.tmp`;
32
+ try {
33
+ await writeFile(temporary, JSON.stringify(value, null, 2) + "\n", {
34
+ mode: 0o600,
35
+ flag: "wx",
36
+ });
37
+ await rename(temporary, file);
38
+ } finally {
39
+ await unlink(temporary).catch(() => {});
40
+ }
41
+ }
42
+
43
+ async function jsonFile(file) {
44
+ try {
45
+ const stat = await lstat(file);
46
+ if (!stat.isFile() || stat.isSymbolicLink())
47
+ throw new Error("FavStash credential files must be regular files.");
48
+ if (process.platform !== "win32" && stat.mode & 0o077)
49
+ throw new Error(
50
+ "FavStash credential file is not private. Set its permissions to 600.",
51
+ );
52
+ return JSON.parse(await readFile(file, "utf8"));
53
+ } catch (error) {
54
+ if (error.code === "ENOENT") return undefined;
55
+ throw error;
56
+ }
57
+ }
58
+
59
+ export function credentialStore(
60
+ url,
61
+ {
62
+ directory = configDirectory(),
63
+ keyringLoader = () => import("@napi-rs/keyring"),
64
+ } = {},
65
+ ) {
66
+ const id = endpointId(url);
67
+ const file = path.join(directory, `${id}.json`);
68
+ async function entry(account = id) {
69
+ try {
70
+ const { Entry } = await keyringLoader();
71
+ return new Entry("FavStash CLI", account);
72
+ } catch {
73
+ throw new Error(
74
+ "OS credential store unavailable. Install its platform dependency, or explicitly use favstash auth login --credential-store file on a private machine.",
75
+ );
76
+ }
77
+ }
78
+ return {
79
+ async prepare(mode) {
80
+ await privateDirectory(directory);
81
+ if (!["keychain", "file"].includes(mode))
82
+ throw new Error("Credential store must be keychain or file.");
83
+ if (mode === "keychain") {
84
+ const probe = await entry(`probe-${randomUUID()}`);
85
+ try {
86
+ probe.setPassword("storage-check");
87
+ probe.deletePassword();
88
+ } catch {
89
+ throw new Error(
90
+ "OS credential store is locked or unavailable. Unlock it, or explicitly select --credential-store file.",
91
+ );
92
+ }
93
+ }
94
+ },
95
+ async read() {
96
+ const data = await jsonFile(file);
97
+ if (!data) return undefined;
98
+ if (data.endpoint !== url)
99
+ throw new Error("Credential endpoint mismatch.");
100
+ if (data.storage === "file") return data;
101
+ if (data.storage !== "keychain")
102
+ throw new Error("Unknown credential store.");
103
+ const secret = (await entry()).getPassword();
104
+ if (!secret)
105
+ throw new Error(
106
+ "OS credential was removed. Run favstash auth login again.",
107
+ );
108
+ const decipher = createDecipheriv(
109
+ "aes-256-gcm",
110
+ Buffer.from(secret, "base64"),
111
+ Buffer.from(data.iv, "base64"),
112
+ );
113
+ decipher.setAAD(Buffer.from(url));
114
+ decipher.setAuthTag(Buffer.from(data.tag, "base64"));
115
+ const state = JSON.parse(
116
+ Buffer.concat([
117
+ decipher.update(Buffer.from(data.encrypted, "base64")),
118
+ decipher.final(),
119
+ ]).toString("utf8"),
120
+ );
121
+ if (state.endpoint !== url)
122
+ throw new Error("Credential endpoint mismatch.");
123
+ return state;
124
+ },
125
+ async write(state) {
126
+ await privateDirectory(directory);
127
+ if (state.storage === "keychain") {
128
+ // Keep only a small encryption key in the OS store (Windows credentials
129
+ // have a size limit). The session file is authenticated ciphertext.
130
+ const credential = await entry();
131
+ let secret = credential.getPassword();
132
+ if (!secret) {
133
+ secret = randomBytes(32).toString("base64");
134
+ credential.setPassword(secret);
135
+ }
136
+ const iv = randomBytes(12);
137
+ const cipher = createCipheriv(
138
+ "aes-256-gcm",
139
+ Buffer.from(secret, "base64"),
140
+ iv,
141
+ );
142
+ cipher.setAAD(Buffer.from(url));
143
+ const encrypted = Buffer.concat([
144
+ cipher.update(JSON.stringify(state), "utf8"),
145
+ cipher.final(),
146
+ ]);
147
+ await atomicJson(file, {
148
+ endpoint: url,
149
+ storage: "keychain",
150
+ iv: iv.toString("base64"),
151
+ tag: cipher.getAuthTag().toString("base64"),
152
+ encrypted: encrypted.toString("base64"),
153
+ });
154
+ } else if (state.storage === "file") {
155
+ const previous = await jsonFile(file);
156
+ await atomicJson(file, state);
157
+ // Commit the new session before dropping an old encryption key.
158
+ if (previous?.storage === "keychain") {
159
+ try {
160
+ (await entry()).deletePassword();
161
+ } catch {
162
+ /* An unused encryption key is safer than losing the new session. */
163
+ }
164
+ }
165
+ } else throw new Error("Unknown credential store.");
166
+ },
167
+ async clear({ bestEffortKeychain = false } = {}) {
168
+ const data = await jsonFile(file);
169
+ if (data?.storage === "keychain") {
170
+ try {
171
+ (await entry()).deletePassword();
172
+ } catch (error) {
173
+ // Explicit local-only logout must work even after the OS store has
174
+ // become unavailable. Removing the ciphertext removes the session;
175
+ // an orphaned encryption key cannot recover it.
176
+ if (!bestEffortKeychain) throw error;
177
+ }
178
+ }
179
+ await unlink(file).catch((error) => {
180
+ if (error.code !== "ENOENT") throw error;
181
+ });
182
+ },
183
+ async locked(operation) {
184
+ await privateDirectory(directory);
185
+ const release = await lockfile.lock(file, {
186
+ realpath: false,
187
+ stale: 30_000,
188
+ update: 5_000,
189
+ retries: { retries: 50, minTimeout: 100, maxTimeout: 200 },
190
+ });
191
+ try {
192
+ return await operation();
193
+ } finally {
194
+ await release();
195
+ }
196
+ },
197
+ };
198
+ }