MCPcopy Create free account
hub / github.com/MoonshotAI/kimi-code / FileTokenStorage

Class FileTokenStorage

packages/oauth/src/storage.ts:41–138  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

39}
40
41export class FileTokenStorage implements TokenStorage {
42 private readonly dir: string;
43
44 constructor(dir: string) {
45 this.dir = dir;
46 }
47
48 private ensureDir(): void {
49 mkdirSync(this.dir, { recursive: true, mode: 0o700 });
50 // recursive=true with mode only applies on initial create; tighten after
51 // the fact in case an existing dir had looser permissions.
52 try {
53 chmodSync(this.dir, 0o700);
54 } catch {
55 // best-effort; Windows / read-only FS may refuse
56 }
57 }
58
59 private pathFor(name: string): string {
60 // Guard against path traversal: caller-provided names (from config.toml
61 // or slash commands) must not escape the credentials dir. `basename`
62 // strips any `..` or `/` segments; if the sanitized value differs from
63 // the input we refuse the request entirely rather than silently
64 // writing to a different file than the caller asked for.
65 const safe = basename(name);
66 if (safe.length === 0 || safe !== name || safe.startsWith('.')) {
67 throw new Error(`Invalid token name: "${name}"`);
68 }
69 return join(this.dir, `${safe}.json`);
70 }
71
72 async load(name: string): Promise<TokenInfo | undefined> {
73 const file = this.pathFor(name);
74 let raw: string;
75 try {
76 raw = readFileSync(file, 'utf-8');
77 } catch {
78 return undefined;
79 }
80 let parsed: unknown;
81 try {
82 parsed = JSON.parse(raw);
83 } catch {
84 return undefined;
85 }
86 if (!isRecord(parsed)) return undefined;
87 return tokenFromWire(parsed as Partial<TokenInfoWire>);
88 }
89
90 async save(name: string, token: TokenInfo): Promise<void> {
91 this.ensureDir();
92 const target = this.pathFor(name);
93 const tmp = `${target}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;
94 const data = Buffer.from(`${JSON.stringify(tokenToWire(token), null, 2)}\n`, 'utf-8');
95 const fd = openSync(tmp, 'w', 0o600);
96 try {
97 let written = 0;
98 while (written < data.length) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected