@mnemonik/shared 7.55.1 → 7.57.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,505 @@
1
+ import { dirname, join, resolve } from 'node:path';
2
+ import { chmod, mkdir } from 'node:fs/promises';
3
+ import {
4
+ atomicWriteText,
5
+ canonicalizeConfigTargets,
6
+ installerConfigLockPath,
7
+ readTextIfExists,
8
+ withFileLocks,
9
+ } from './settingsIo.js';
10
+
11
+ const PROXY_TOKEN_PATTERN = /^pxt_[a-f0-9]{32}$/;
12
+
13
+ export type ClaudeBaseUrlState = { kind: 'absent' } | { kind: 'value'; value: string };
14
+
15
+ export type ClaudeProxyStatus = 'on' | 'off' | 'custom' | 'not-paired' | 'invalid';
16
+
17
+ export interface ClaudeProxySettingsOptions {
18
+ homeDir?: string;
19
+ settingsPath?: string;
20
+ configPath?: string;
21
+ }
22
+
23
+ export type ClaudeProxyPairingConfig = Record<string, unknown> & {
24
+ server: string;
25
+ proxyToken: string;
26
+ };
27
+
28
+ export interface ClaudeProxyMutationResult {
29
+ changed: boolean;
30
+ handoffCleanupUnconfirmed: boolean;
31
+ }
32
+
33
+ export interface ClaudeProxyOffResult extends ClaudeProxyMutationResult {
34
+ outcome: 'disabled' | 'already-off';
35
+ }
36
+
37
+ export interface ClaudeProxyOnResult extends ClaudeProxyMutationResult {
38
+ outcome: 'enabled' | 'already-on';
39
+ }
40
+
41
+ interface ClaudeProxyPaths {
42
+ settingsPath: string;
43
+ configPath: string;
44
+ lockPath: string;
45
+ configLockPath: string;
46
+ }
47
+
48
+ interface ClaudeProxyBasePaths {
49
+ homeDir: string;
50
+ configPath: string;
51
+ }
52
+
53
+ interface ParsedSettings {
54
+ raw: string | null;
55
+ value: Record<string, unknown>;
56
+ baseUrl: ClaudeBaseUrlState;
57
+ }
58
+
59
+ interface PairedProxyConfig {
60
+ raw: string;
61
+ value: Record<string, unknown>;
62
+ server: string;
63
+ proxyToken: string;
64
+ previousProxyToken: string | null;
65
+ proxyUrl: string;
66
+ }
67
+
68
+ export class ClaudeProxyConflictError extends Error {
69
+ constructor() {
70
+ super('Claude Code already has a base URL that does not match this paired device.');
71
+ this.name = 'ClaudeProxyConflictError';
72
+ }
73
+ }
74
+
75
+ export class ClaudeProxySettingsError extends Error {
76
+ constructor() {
77
+ super('Claude settings are invalid or unreadable.');
78
+ this.name = 'ClaudeProxySettingsError';
79
+ }
80
+ }
81
+
82
+ export class ClaudeProxyNotPairedError extends Error {
83
+ constructor() {
84
+ super('This device is not paired with Mnemonik. Run pairing first.');
85
+ this.name = 'ClaudeProxyNotPairedError';
86
+ }
87
+ }
88
+
89
+ function resolveHomeDirectory(
90
+ env: Partial<Record<'HOME' | 'USERPROFILE', string | undefined>> = process.env
91
+ ): string {
92
+ const home = env.HOME?.trim() || env.USERPROFILE?.trim();
93
+ if (!home) throw new ClaudeProxyNotPairedError();
94
+ return resolve(home);
95
+ }
96
+
97
+ function resolveBasePaths(options: ClaudeProxySettingsOptions): ClaudeProxyBasePaths {
98
+ const homeDir = resolve(options.homeDir ?? resolveHomeDirectory());
99
+ const configPath = resolve(options.configPath ?? join(homeDir, '.mnemonik', 'config.json'));
100
+ return { homeDir, configPath };
101
+ }
102
+
103
+ async function resolvePaths(
104
+ options: ClaudeProxySettingsOptions,
105
+ basePaths = resolveBasePaths(options)
106
+ ): Promise<ClaudeProxyPaths> {
107
+ const requestedSettingsPath = resolve(
108
+ options.settingsPath ?? join(basePaths.homeDir, '.claude', 'settings.json')
109
+ );
110
+ const [settingsPath, configPath] = await canonicalizeConfigTargets([
111
+ requestedSettingsPath,
112
+ basePaths.configPath,
113
+ ]);
114
+ if (!settingsPath || !configPath) throw new ClaudeProxySettingsError();
115
+ const runtimeParent = join(basePaths.homeDir, '.mnemonik', 'hooks');
116
+ return {
117
+ settingsPath,
118
+ configPath,
119
+ lockPath: installerConfigLockPath(settingsPath, runtimeParent),
120
+ configLockPath: installerConfigLockPath(configPath, runtimeParent),
121
+ };
122
+ }
123
+
124
+ function isRecord(value: unknown): value is Record<string, unknown> {
125
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
126
+ }
127
+
128
+ function parseSettingsRaw(raw: string | null): ParsedSettings {
129
+ if (raw === null) return { raw: null, value: {}, baseUrl: { kind: 'absent' } };
130
+
131
+ let parsed: unknown;
132
+ try {
133
+ parsed = JSON.parse(raw);
134
+ } catch {
135
+ throw new ClaudeProxySettingsError();
136
+ }
137
+ if (!isRecord(parsed)) throw new ClaudeProxySettingsError();
138
+ if (parsed.env === undefined) return { raw, value: parsed, baseUrl: { kind: 'absent' } };
139
+ if (!isRecord(parsed.env)) throw new ClaudeProxySettingsError();
140
+ const baseUrl = parsed.env.ANTHROPIC_BASE_URL;
141
+ if (baseUrl === undefined) return { raw, value: parsed, baseUrl: { kind: 'absent' } };
142
+ if (typeof baseUrl !== 'string' || baseUrl.length === 0) {
143
+ throw new ClaudeProxySettingsError();
144
+ }
145
+ return { raw, value: parsed, baseUrl: { kind: 'value', value: baseUrl } };
146
+ }
147
+
148
+ async function readSettings(settingsPath: string): Promise<ParsedSettings> {
149
+ try {
150
+ return parseSettingsRaw(await readTextIfExists(settingsPath));
151
+ } catch (error) {
152
+ if (error instanceof ClaudeProxySettingsError) throw error;
153
+ throw new ClaudeProxySettingsError();
154
+ }
155
+ }
156
+
157
+ export function buildClaudeProxyUrl(server: string, proxyToken: string): string {
158
+ const trimmedServer = server.trim();
159
+ if (!trimmedServer || !PROXY_TOKEN_PATTERN.test(proxyToken)) {
160
+ throw new ClaudeProxyNotPairedError();
161
+ }
162
+ const proxyUrl = `${trimmedServer.replace(/\/$/, '')}/proxy/${proxyToken}`;
163
+ try {
164
+ const parsed = new URL(proxyUrl);
165
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
166
+ throw new ClaudeProxyNotPairedError();
167
+ }
168
+ } catch (error) {
169
+ if (error instanceof ClaudeProxyNotPairedError) throw error;
170
+ throw new ClaudeProxyNotPairedError();
171
+ }
172
+ return proxyUrl;
173
+ }
174
+
175
+ function parsePairedProxyConfig(raw: string | null): PairedProxyConfig | null {
176
+ if (raw === null) return null;
177
+ let parsed: unknown;
178
+ try {
179
+ parsed = JSON.parse(raw);
180
+ } catch {
181
+ return null;
182
+ }
183
+ if (!isRecord(parsed) || typeof parsed.server !== 'string') return null;
184
+ if (typeof parsed.proxyToken !== 'string') return null;
185
+ const previousProxyToken = parsed.previousProxyToken;
186
+ if (
187
+ previousProxyToken !== undefined &&
188
+ (typeof previousProxyToken !== 'string' || !PROXY_TOKEN_PATTERN.test(previousProxyToken))
189
+ ) {
190
+ return null;
191
+ }
192
+ try {
193
+ const normalizedPreviousToken =
194
+ previousProxyToken && previousProxyToken !== parsed.proxyToken ? previousProxyToken : null;
195
+ return {
196
+ raw,
197
+ value: parsed,
198
+ server: parsed.server,
199
+ proxyToken: parsed.proxyToken,
200
+ previousProxyToken: normalizedPreviousToken,
201
+ proxyUrl: buildClaudeProxyUrl(parsed.server, parsed.proxyToken),
202
+ };
203
+ } catch {
204
+ return null;
205
+ }
206
+ }
207
+
208
+ async function readPairedProxyConfig(configPath: string): Promise<PairedProxyConfig | null> {
209
+ try {
210
+ return parsePairedProxyConfig(await readTextIfExists(configPath));
211
+ } catch {
212
+ return null;
213
+ }
214
+ }
215
+
216
+ function managedProxyTokenForUrl(baseUrl: string, config: PairedProxyConfig): string | null {
217
+ if (matchesProxyUrlForToken(baseUrl, config.server, config.proxyToken)) {
218
+ return config.proxyToken;
219
+ }
220
+ if (
221
+ config.previousProxyToken &&
222
+ matchesProxyUrlForToken(baseUrl, config.server, config.previousProxyToken)
223
+ ) {
224
+ return config.previousProxyToken;
225
+ }
226
+ return null;
227
+ }
228
+
229
+ function matchesProxyUrlForToken(baseUrl: string, server: string, proxyToken: string): boolean {
230
+ return (
231
+ baseUrl === buildClaudeProxyUrl(server, proxyToken) ||
232
+ baseUrl === `${server}/proxy/${proxyToken}`
233
+ );
234
+ }
235
+
236
+ function matchesManagedProxyUrl(baseUrl: string, config: PairedProxyConfig): boolean {
237
+ return managedProxyTokenForUrl(baseUrl, config) !== null;
238
+ }
239
+
240
+ function serializeConfig(config: Record<string, unknown>): string {
241
+ return `${JSON.stringify(config, null, 2)}\n`;
242
+ }
243
+
244
+ async function clearPreviousProxyToken(
245
+ paths: ClaudeProxyPaths,
246
+ config: PairedProxyConfig,
247
+ expectedProxyToken: string
248
+ ): Promise<void> {
249
+ if (config.proxyToken !== expectedProxyToken || config.previousProxyToken === null) return;
250
+ const nextConfig = { ...config.value };
251
+ delete nextConfig.previousProxyToken;
252
+ await atomicWriteText(paths.configPath, serializeConfig(nextConfig), config.raw, { mode: 0o600 });
253
+ await chmod(paths.configPath, 0o600);
254
+ }
255
+
256
+ async function tryClearPreviousProxyToken(
257
+ paths: ClaudeProxyPaths,
258
+ config: PairedProxyConfig,
259
+ expectedProxyToken: string
260
+ ): Promise<boolean> {
261
+ try {
262
+ await clearPreviousProxyToken(paths, config, expectedProxyToken);
263
+ return false;
264
+ } catch {
265
+ return true;
266
+ }
267
+ }
268
+
269
+ function withProxyLocks<T>(paths: ClaudeProxyPaths, action: () => Promise<T>): Promise<T> {
270
+ return withFileLocks([paths.lockPath, paths.configLockPath], action);
271
+ }
272
+
273
+ function setBaseUrl(
274
+ settings: Record<string, unknown>,
275
+ next: ClaudeBaseUrlState
276
+ ): Record<string, unknown> {
277
+ const updated = { ...settings };
278
+ if (next.kind === 'value') {
279
+ const env = isRecord(settings.env) ? { ...settings.env } : {};
280
+ env.ANTHROPIC_BASE_URL = next.value;
281
+ updated.env = env;
282
+ return updated;
283
+ }
284
+
285
+ if (!isRecord(settings.env)) return updated;
286
+ const env = { ...settings.env };
287
+ delete env.ANTHROPIC_BASE_URL;
288
+ if (Object.keys(env).length === 0) delete updated.env;
289
+ else updated.env = env;
290
+ return updated;
291
+ }
292
+
293
+ function serializeSettings(settings: Record<string, unknown>): string {
294
+ return `${JSON.stringify(settings, null, 2)}\n`;
295
+ }
296
+
297
+ async function writeBaseUrl(
298
+ settingsPath: string,
299
+ settings: ParsedSettings,
300
+ next: ClaudeBaseUrlState
301
+ ): Promise<void> {
302
+ await atomicWriteText(
303
+ settingsPath,
304
+ serializeSettings(setBaseUrl(settings.value, next)),
305
+ settings.raw
306
+ );
307
+ }
308
+
309
+ async function pairedConfigOrThrow(configPath: string): Promise<PairedProxyConfig> {
310
+ const config = await readPairedProxyConfig(configPath);
311
+ if (!config) throw new ClaudeProxyNotPairedError();
312
+ return config;
313
+ }
314
+
315
+ export async function stageClaudeProxyPairingConfig(
316
+ nextConfig: ClaudeProxyPairingConfig,
317
+ options: ClaudeProxySettingsOptions = {}
318
+ ): Promise<void> {
319
+ const nextProxyUrl = buildClaudeProxyUrl(nextConfig.server, nextConfig.proxyToken);
320
+ const basePaths = resolveBasePaths(options);
321
+ await mkdir(dirname(basePaths.configPath), { recursive: true, mode: 0o700 });
322
+ await chmod(dirname(basePaths.configPath), 0o700);
323
+ const paths = await resolvePaths(options, basePaths);
324
+ await withProxyLocks(paths, async () => {
325
+ const currentRaw = await readTextIfExists(paths.configPath);
326
+ const currentConfig = parsePairedProxyConfig(currentRaw);
327
+ const settings = await readSettings(paths.settingsPath);
328
+ let previousProxyToken: string | null = null;
329
+
330
+ if (settings.baseUrl.kind === 'value') {
331
+ if (!currentConfig) throw new ClaudeProxyConflictError();
332
+ previousProxyToken = managedProxyTokenForUrl(settings.baseUrl.value, currentConfig);
333
+ if (!previousProxyToken) throw new ClaudeProxyConflictError();
334
+ if (settings.baseUrl.value === nextProxyUrl) {
335
+ previousProxyToken = null;
336
+ } else if (
337
+ !matchesProxyUrlForToken(settings.baseUrl.value, nextConfig.server, previousProxyToken)
338
+ ) {
339
+ throw new ClaudeProxyConflictError();
340
+ } else if (previousProxyToken === nextConfig.proxyToken) {
341
+ previousProxyToken = null;
342
+ }
343
+ }
344
+
345
+ const serializedConfig = { ...nextConfig };
346
+ delete serializedConfig.previousProxyToken;
347
+ if (previousProxyToken) serializedConfig.previousProxyToken = previousProxyToken;
348
+ await atomicWriteText(paths.configPath, serializeConfig(serializedConfig), currentRaw, {
349
+ mode: 0o600,
350
+ });
351
+ await chmod(paths.configPath, 0o600);
352
+ });
353
+ }
354
+
355
+ export async function assertClaudeProxyCanBeConfigured(
356
+ options: ClaudeProxySettingsOptions = {}
357
+ ): Promise<void> {
358
+ const paths = await resolvePaths(options);
359
+ return withProxyLocks(paths, async () => {
360
+ const config = await readPairedProxyConfig(paths.configPath);
361
+ const settings = await readSettings(paths.settingsPath);
362
+ if (
363
+ settings.baseUrl.kind === 'value' &&
364
+ (!config || !matchesManagedProxyUrl(settings.baseUrl.value, config))
365
+ ) {
366
+ throw new ClaudeProxyConflictError();
367
+ }
368
+ });
369
+ }
370
+
371
+ export async function configureClaudeProxy(
372
+ server: string,
373
+ proxyToken: string,
374
+ options: ClaudeProxySettingsOptions = {}
375
+ ): Promise<ClaudeProxyMutationResult> {
376
+ const proxyUrl = buildClaudeProxyUrl(server, proxyToken);
377
+ const paths = await resolvePaths(options);
378
+ return withProxyLocks(paths, async () => {
379
+ const config = await pairedConfigOrThrow(paths.configPath);
380
+ if (config.proxyToken !== proxyToken || config.proxyUrl !== proxyUrl) {
381
+ throw new ClaudeProxyConflictError();
382
+ }
383
+ const settings = await readSettings(paths.settingsPath);
384
+ let changed = false;
385
+ if (settings.baseUrl.kind === 'value') {
386
+ if (!matchesManagedProxyUrl(settings.baseUrl.value, config)) {
387
+ throw new ClaudeProxyConflictError();
388
+ }
389
+ if (settings.baseUrl.value !== proxyUrl) {
390
+ await writeBaseUrl(paths.settingsPath, settings, { kind: 'value', value: proxyUrl });
391
+ changed = true;
392
+ }
393
+ } else {
394
+ await writeBaseUrl(paths.settingsPath, settings, { kind: 'value', value: proxyUrl });
395
+ changed = true;
396
+ }
397
+ const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(paths, config, proxyToken);
398
+ return { changed, handoffCleanupUnconfirmed };
399
+ });
400
+ }
401
+
402
+ export async function turnClaudeProxyOff(
403
+ options: ClaudeProxySettingsOptions = {}
404
+ ): Promise<ClaudeProxyOffResult> {
405
+ const basePaths = resolveBasePaths(options);
406
+ await pairedConfigOrThrow(basePaths.configPath);
407
+ const paths = await resolvePaths(options, basePaths);
408
+ return withProxyLocks(paths, async () => {
409
+ const config = await pairedConfigOrThrow(paths.configPath);
410
+ const settings = await readSettings(paths.settingsPath);
411
+ if (settings.baseUrl.kind === 'absent') {
412
+ const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
413
+ paths,
414
+ config,
415
+ config.proxyToken
416
+ );
417
+ return { changed: false, outcome: 'already-off', handoffCleanupUnconfirmed };
418
+ }
419
+ if (!matchesManagedProxyUrl(settings.baseUrl.value, config)) {
420
+ throw new ClaudeProxyConflictError();
421
+ }
422
+ await writeBaseUrl(paths.settingsPath, settings, { kind: 'absent' });
423
+ const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
424
+ paths,
425
+ config,
426
+ config.proxyToken
427
+ );
428
+ return { changed: true, outcome: 'disabled', handoffCleanupUnconfirmed };
429
+ });
430
+ }
431
+
432
+ export async function turnClaudeProxyOn(
433
+ options: ClaudeProxySettingsOptions = {}
434
+ ): Promise<ClaudeProxyOnResult> {
435
+ const basePaths = resolveBasePaths(options);
436
+ await pairedConfigOrThrow(basePaths.configPath);
437
+ const paths = await resolvePaths(options, basePaths);
438
+ return withProxyLocks(paths, async () => {
439
+ const config = await pairedConfigOrThrow(paths.configPath);
440
+ const settings = await readSettings(paths.settingsPath);
441
+ if (settings.baseUrl.kind === 'value') {
442
+ if (settings.baseUrl.value === config.proxyUrl) {
443
+ const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
444
+ paths,
445
+ config,
446
+ config.proxyToken
447
+ );
448
+ return { changed: false, outcome: 'already-on', handoffCleanupUnconfirmed };
449
+ }
450
+ if (!matchesManagedProxyUrl(settings.baseUrl.value, config)) {
451
+ throw new ClaudeProxyConflictError();
452
+ }
453
+ }
454
+ await writeBaseUrl(paths.settingsPath, settings, {
455
+ kind: 'value',
456
+ value: config.proxyUrl,
457
+ });
458
+ const handoffCleanupUnconfirmed = await tryClearPreviousProxyToken(
459
+ paths,
460
+ config,
461
+ config.proxyToken
462
+ );
463
+ return { changed: true, outcome: 'enabled', handoffCleanupUnconfirmed };
464
+ });
465
+ }
466
+
467
+ export async function getClaudeProxyStatus(
468
+ options: ClaudeProxySettingsOptions = {}
469
+ ): Promise<ClaudeProxyStatus> {
470
+ try {
471
+ const basePaths = resolveBasePaths(options);
472
+ if (!(await readPairedProxyConfig(basePaths.configPath))) return 'not-paired';
473
+ const paths = await resolvePaths(options, basePaths);
474
+ return await withProxyLocks(paths, async () => {
475
+ const config = await readPairedProxyConfig(paths.configPath);
476
+ if (!config) return 'not-paired';
477
+ const settings = await readSettings(paths.settingsPath);
478
+ if (settings.baseUrl.kind === 'absent') return 'off';
479
+ return matchesManagedProxyUrl(settings.baseUrl.value, config) ? 'on' : 'custom';
480
+ });
481
+ } catch {
482
+ return 'invalid';
483
+ }
484
+ }
485
+
486
+ export function formatClaudeProxyStatus(status: ClaudeProxyStatus): string {
487
+ switch (status) {
488
+ case 'on':
489
+ return 'Mnemonik proxy is on and correctly configured.';
490
+ case 'off':
491
+ return 'Mnemonik proxy is off.';
492
+ case 'custom':
493
+ return 'Claude Code has a base URL that does not match this paired device.';
494
+ case 'not-paired':
495
+ return 'This device is not paired with Mnemonik.';
496
+ case 'invalid':
497
+ return 'Claude settings are invalid or unreadable.';
498
+ }
499
+ }
500
+
501
+ export function formatClaudeProxyCleanupWarning(result: ClaudeProxyMutationResult): string | null {
502
+ return result.handoffCleanupUnconfirmed
503
+ ? 'Mnemonik could not confirm cleanup of the saved token handoff. The next proxy-changing command will check and retry it.'
504
+ : null;
505
+ }
package/src/index.ts CHANGED
@@ -58,3 +58,5 @@ export {
58
58
  MCP_PRECHECK_TIMEOUT_MS,
59
59
  withHookTimeout,
60
60
  } from './hookTimeouts.js';
61
+ export * from './settingsIo.js';
62
+ export * from './claudeProxySettings.js';