xonecas.io
64875
Mc

mini-coder / files

mini-coder / src / auth.ts

2.9 KB
1import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2import { dirname, join } from "node:path";
3import type { AuthOperationOptions, Credential, CredentialInfo, CredentialStore } from "@earendil-works/pi-ai";
4
5/** The `auth.json` layout: one credential per provider id. */
6type AuthFile = Record<string, Credential>;
7
8function readFile(path: string): AuthFile {
9  try {
10    return JSON.parse(readFileSync(path, "utf8")) as AuthFile;
11  } catch (error) {
12    if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
13    throw error;
14  }
15}
16
17/** Write the whole file atomically: temp file, then rename over the target. */
18function writeFile(path: string, data: AuthFile): void {
19  mkdirSync(dirname(path), { recursive: true });
20  const temp = join(dirname(path), `.${process.pid}.${Date.now()}.tmp`);
21  writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`);
22  renameSync(temp, path);
23}
24
25/**
26 * File-backed `CredentialStore` over `auth.json`. Writes are serialized per
27 * provider through an in-process promise chain, so `modify` and `delete` on
28 * the same provider never interleave.
29 */
30export function createCredentialStore(path: string): CredentialStore {
31  const chains = new Map<string, Promise<unknown>>();
32
33  function enqueue<T>(providerId: string, task: () => Promise<T>, options?: AuthOperationOptions): Promise<T> {
34    options?.signal?.throwIfAborted();
35    const previous = chains.get(providerId) ?? Promise.resolve();
36    const queued = (async () => {
37      await previous.catch(() => {});
38      options?.signal?.throwIfAborted();
39      return await task();
40    })();
41    const tail = queued.catch(() => {});
42    chains.set(providerId, tail);
43    void tail.then(() => {
44      if (chains.get(providerId) === tail) chains.delete(providerId);
45    });
46    return queued;
47  }
48
49  return {
50    async read(providerId, options): Promise<Credential | undefined> {
51      options?.signal?.throwIfAborted();
52      return readFile(path)[providerId];
53    },
54    async list(options): Promise<readonly CredentialInfo[]> {
55      options?.signal?.throwIfAborted();
56      return Object.entries(readFile(path)).map(([providerId, credential]) => ({ providerId, type: credential.type }));
57    },
58    modify(providerId, fn, options): Promise<Credential | undefined> {
59      return enqueue(
60        providerId,
61        async () => {
62          const data = readFile(path);
63          const next = await fn(data[providerId]);
64          options?.signal?.throwIfAborted();
65          if (next !== undefined) data[providerId] = next;
66          writeFile(path, data);
67          return next ?? data[providerId];
68        },
69        options,
70      );
71    },
72    delete(providerId, options): Promise<void> {
73      return enqueue(
74        providerId,
75        async () => {
76          const data = readFile(path);
77          delete data[providerId];
78          writeFile(path, data);
79        },
80        options,
81      );
82    },
83  };
84}