@cortexkit/common-auth 0.14.2 → 0.16.0

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.
Files changed (64) hide show
  1. package/README.md +4 -4
  2. package/dist/claustrum/consumer.d.ts +33 -3
  3. package/dist/claustrum/consumer.js +96 -1
  4. package/dist/claustrum/custody.d.ts +4 -1
  5. package/dist/claustrum/enrollment.d.ts +3 -2
  6. package/dist/claustrum/enrollment.js +84 -42
  7. package/dist/claustrum/index.d.ts +2 -1
  8. package/dist/claustrum/index.js +5 -3
  9. package/dist/claustrum/insula.d.ts +69 -0
  10. package/dist/claustrum/insula.js +152 -0
  11. package/dist/claustrum/roster.d.ts +13 -0
  12. package/dist/claustrum/roster.js +28 -2
  13. package/dist/dump/index.d.ts +4 -3
  14. package/dist/dump/index.js +39 -12
  15. package/dist/fs/atomic-write.d.ts +5 -0
  16. package/dist/fs/atomic-write.js +21 -0
  17. package/dist/fs/index.d.ts +2 -0
  18. package/dist/fs/index.js +1 -0
  19. package/dist/fs/private-files.d.ts +66 -0
  20. package/dist/fs/private-files.js +302 -0
  21. package/dist/fs/refresh-file-lock.d.ts +1 -1
  22. package/dist/fs/refresh-file-lock.js +254 -37
  23. package/dist/fs/with-lock.d.ts +3 -0
  24. package/dist/fs/with-lock.js +4 -0
  25. package/dist/logger/engine.d.ts +6 -8
  26. package/dist/logger/engine.js +126 -11
  27. package/dist/pi-slot/slot.d.ts +2 -0
  28. package/dist/pi-slot/slot.js +34 -6
  29. package/dist/rpc/port-file.js +30 -8
  30. package/dist/rpc/rpc-client.js +15 -1
  31. package/dist/rpc/rpc-server.js +8 -3
  32. package/dist/setup/command-runner.d.ts +4 -0
  33. package/dist/setup/command-runner.js +49 -0
  34. package/dist/setup/command.d.ts +3 -0
  35. package/dist/setup/command.js +188 -0
  36. package/dist/setup/config-write.d.ts +11 -0
  37. package/dist/setup/config-write.js +60 -0
  38. package/dist/setup/detect.d.ts +6 -0
  39. package/dist/setup/detect.js +224 -0
  40. package/dist/setup/enroll.d.ts +4 -0
  41. package/dist/setup/enroll.js +70 -0
  42. package/dist/setup/index.d.ts +5 -0
  43. package/dist/setup/index.js +4 -0
  44. package/dist/setup/paths.d.ts +11 -0
  45. package/dist/setup/paths.js +33 -0
  46. package/dist/setup/process-fence.d.ts +41 -0
  47. package/dist/setup/process-fence.js +177 -0
  48. package/dist/setup/prompts.d.ts +4 -0
  49. package/dist/setup/prompts.js +26 -0
  50. package/dist/setup/register.d.ts +11 -0
  51. package/dist/setup/register.js +130 -0
  52. package/dist/setup/types.d.ts +93 -0
  53. package/dist/setup/types.js +1 -0
  54. package/dist/sidebar-file/sidebar-file.d.ts +5 -4
  55. package/dist/sidebar-file/sidebar-file.js +17 -8
  56. package/dist/store/mutate.js +2 -2
  57. package/dist/store/pool.d.ts +1 -0
  58. package/dist/store/pool.js +3 -0
  59. package/dist/store/refresh-lock.d.ts +4 -0
  60. package/dist/store/refresh-lock.js +5 -0
  61. package/dist/tui-prefs/tui-preferences.js +6 -4
  62. package/dist/tui-prefs/watcher.d.ts +3 -0
  63. package/dist/tui-prefs/watcher.js +26 -10
  64. package/package.json +14 -3
package/README.md CHANGED
@@ -11,16 +11,16 @@ Shared libraries for the CortexKit auth plugins for OpenCode and Pi: openai-auth
11
11
 
12
12
  A passing safety test proves little until it has been seen to fail. [`mutations.toml`](mutations.toml) is the checked-in catalogue: each row deliberately breaks one guard in `src/` (or a CI scan script) and names the Bun test that must fail because of it, so a guard cannot silently stop guarding. A row earns its place by guarding a silent, costly failure: lock exclusion, crash safety, credential loss or leakage, a single-use token used twice, misattributed quota, a wire contract, data loss. Style and cosmetics do not.
13
13
 
14
- The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/0c99c7e16d8ae22b6e114136b6b7b68be6f1394e/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
14
+ The pinned [`ckdev-mutate`](https://github.com/cortexkit/commons/tree/9d6b663dac487bb982c7bfd18a96eee2292164ad/crates/cortexkit-mutate) runner replays it from a clean tree. It installs and builds first (fixtures import `dist/`), checks each named test passes, applies the break, rebuilds, requires the test to fail, and restores the source byte for byte:
15
15
 
16
16
  ```sh
17
- cargo install --locked --git https://github.com/cortexkit/commons --rev 0c99c7e16d8ae22b6e114136b6b7b68be6f1394e cortexkit-mutate
18
- ckdev-mutate check
17
+ cargo install --locked --git https://github.com/cortexkit/commons --rev 9d6b663dac487bb982c7bfd18a96eee2292164ad cortexkit-mutate
18
+ ckdev-mutate check --strict
19
19
  ckdev-mutate run --all
20
20
  ckdev-mutate run --diff origin/main
21
21
  ckdev-mutate run --only fs-lock-try-once-refuses-held-lock
22
22
  ```
23
23
 
24
- Every row must report CAUGHT. Replay with the Bun version CI pins (1.3.14): the row `rpc-declared-oversize-413-half-closes` guards the RPC server's workaround for Bun 1.3.14 reusing a connection the server refused with 413. Bun 1.4.2 never reuses it, so that row survives there. Rows are command rows: `{test}` is a Bun `-t` filter, a regular expression over the full test name (describe names and test name joined by spaces), so ids are anchored, escaped, and spell each space `\s`. CI replays the rows a pull request's diff selects, the full catalogue on every push to main, and the full catalogue with `--broad` nightly. Never `git checkout` a file while a replay runs: it removes the mutation and fakes a survivor.
24
+ Every row must report CAUGHT. Replay with the Bun version CI pins (1.3.14): the row `rpc-declared-oversize-413-half-closes` guards the RPC server's workaround for Bun 1.3.14 reusing a connection the server refused with 413. Bun 1.4.2 never reuses it, so that row survives there. Rows are command rows: `{test}` is a Bun `-t` filter, a regular expression over the full test name (describe names and test name joined by spaces), so ids are anchored, escaped, and spell each space `\s`. The shared `scripts/list-bun-tests.mjs` asks Bun's JUnit reporter to list every discovered test as skipped with a never-matching selector, then reconstructs full names from nested describe suites and filters them with the row's JavaScript regular expression. It does not duplicate Bun's test-name formatting or run test bodies. `ckdev-mutate check --strict` verifies each active command row's `expect_red` selects a discovered test. CI replays the rows a pull request's diff selects, the full catalogue on every push to main, and the full catalogue with `--broad` nightly. Never `git checkout` a file while a replay runs: it removes the mutation and fakes a survivor.
25
25
 
26
26
  Licensed under MIT; see [LICENSE](LICENSE).
@@ -3,8 +3,9 @@ import type { QuotaObservation } from '../quota/index.js';
3
3
  import type { RoutingRow } from '../routing/index.js';
4
4
  import { type ClaustrumFamily, type ClaustrumScopedAttempt, type ClaustrumScopedClient, type IdentityParser } from './custody.js';
5
5
  import { type ClaustrumLogger } from './errors.js';
6
+ import { type InsulaQuotaOptions } from './insula.js';
6
7
  import { type AccountMapper, type QuotaReceipt, type VaultRosterFile } from './roster.js';
7
- export interface ClaustrumConsumerOptions {
8
+ export interface ClaustrumConsumerOptions<Q = QuotaObservation> {
8
9
  /**
9
10
  * The roster file: one row per vault account (route id, credential id,
10
11
  * account identity, state, quota), plus the accounts the user declined. It
@@ -45,6 +46,8 @@ export interface ClaustrumConsumerOptions {
45
46
  clearTimeoutImpl?: typeof clearTimeout;
46
47
  now?: () => number;
47
48
  logger?: ClaustrumLogger;
49
+ /** Optional background quota source. In-band readings still use recordQuota. */
50
+ insula?: InsulaQuotaOptions<Q>;
48
51
  }
49
52
  export interface SendOptions {
50
53
  /**
@@ -63,15 +66,34 @@ export interface SendOptions {
63
66
  * never are. It never enrolls: a missing token is an error here, and setup
64
67
  * is where enrollment happens.
65
68
  */
66
- export declare class ClaustrumConsumer {
69
+ export declare class ClaustrumConsumer<Q = QuotaObservation> {
67
70
  #private;
68
- constructor(options: ClaustrumConsumerOptions);
71
+ constructor(options: ClaustrumConsumerOptions<Q>);
69
72
  /** The last committed roster this instance saw, without any I/O. */
70
73
  snapshot(): VaultRosterFile | undefined;
71
74
  /** Rows for `/routing`, from the last committed roster. */
72
75
  routingRows(): RoutingRow[];
73
76
  refresh(): Promise<VaultRosterFile | undefined>;
74
77
  start(): void;
78
+ /**
79
+ * Fetch on a background tick, at most once per minute across projects with
80
+ * the same daemon and enrollment token path. Admission must use the cache
81
+ * instead, so an optional quota daemon never delays a provider request.
82
+ */
83
+ refreshInsulaQuota(): Promise<void>;
84
+ /**
85
+ * Cache-only, for unknown-quota admission with a served receipt. Undefined
86
+ * means poll the provider normally. Only get_scoped's asserted account_id
87
+ * joins insula; parsed identities and display metadata cannot substitute.
88
+ * Background polling should use cachedInsulaQuotaForRoute instead.
89
+ */
90
+ cachedInsulaQuota(receipt: Pick<ClaustrumScopedAttempt, 'assertedAccountIdentity'>): Promise<Q | undefined>;
91
+ /**
92
+ * Background cache lookup without fetching a credential. Re-read the roster
93
+ * so a peer's account replacement invalidates the old route immediately.
94
+ * A route without a known provider account cannot join an insula entry.
95
+ */
96
+ cachedInsulaQuotaForRoute(routeId: string): Promise<Q | undefined>;
75
97
  /**
76
98
  * Authorize one physical send on a vault route. The roster file is re-read
77
99
  * first, so a decline committed by another process applies before the next
@@ -98,5 +120,13 @@ export declare class ClaustrumConsumer {
98
120
  * (see `recordVaultQuota`), so a reading for a replaced account is dropped.
99
121
  */
100
122
  recordQuota(routeId: string, observation: QuotaObservation, attempt: QuotaReceipt): Promise<boolean>;
123
+ /**
124
+ * Store a background observation that belongs to an account rather than to
125
+ * a served credential (an insula reading from `cachedInsulaQuotaForRoute`).
126
+ * It lands only while the route is still bound to that known account, so no
127
+ * credential fetch is needed and a replaced account's reading is dropped.
128
+ * The in-memory roster is reloaded from the file, without a vault call.
129
+ */
130
+ recordAccountQuota(routeId: string, accountIdentity: string, observation: QuotaObservation): Promise<boolean>;
101
131
  close(): void;
102
132
  }
@@ -1,8 +1,10 @@
1
1
  import { createLogger } from '../logger/index.js';
2
2
  import { combineAbortSignals } from '../util/any-signal.js';
3
3
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
4
+ import { readClaustrumEnrollmentToken } from './enrollment.js';
4
5
  import { ClaustrumConsumerError } from './errors.js';
5
- import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
6
+ import { acquireInsulaQuotaSource } from './insula.js';
7
+ import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
6
8
  /**
7
9
  * One plugin host's view of its vault accounts. It turns vault credentials
8
10
  * into rows for `/routing`, authorizes each physical send with the vault, and
@@ -21,6 +23,7 @@ export class ClaustrumConsumer {
21
23
  #roster;
22
24
  #timer;
23
25
  #started = false;
26
+ #insula;
24
27
  constructor(options) {
25
28
  this.#options = options;
26
29
  this.#logger = options.logger ?? createLogger('claustrum');
@@ -84,6 +87,9 @@ export class ClaustrumConsumer {
84
87
  now: this.#options.now,
85
88
  logger: this.#logger,
86
89
  });
90
+ if (this.#options.insula && client.insula) {
91
+ this.#insula = acquireInsulaQuotaSource(client.insula, this.#options.tokenPath);
92
+ }
87
93
  return this.#custody;
88
94
  })
89
95
  .finally(() => {
@@ -109,6 +115,8 @@ export class ClaustrumConsumer {
109
115
  this.#roster = undefined;
110
116
  this.#custody?.close();
111
117
  this.#custody = undefined;
118
+ this.#insula?.release();
119
+ this.#insula = undefined;
112
120
  return undefined;
113
121
  }
114
122
  const custody = await this.#getCustody();
@@ -145,6 +153,7 @@ export class ClaustrumConsumer {
145
153
  const tick = async () => {
146
154
  try {
147
155
  await this.refresh();
156
+ await this.refreshInsulaQuota();
148
157
  }
149
158
  catch (error) {
150
159
  if (!this.#shutdown.signal.aborted)
@@ -163,6 +172,72 @@ export class ClaustrumConsumer {
163
172
  };
164
173
  void tick();
165
174
  }
175
+ /**
176
+ * Fetch on a background tick, at most once per minute across projects with
177
+ * the same daemon and enrollment token path. Admission must use the cache
178
+ * instead, so an optional quota daemon never delays a provider request.
179
+ */
180
+ async refreshInsulaQuota() {
181
+ if (!this.#options.insula ||
182
+ this.#shutdown.signal.aborted ||
183
+ !(await this.#active()))
184
+ return;
185
+ try {
186
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
187
+ await this.#getCustody();
188
+ await this.#insula?.source.refresh((this.#options.now ?? Date.now)());
189
+ }
190
+ catch {
191
+ // An optional source must never prevent the plugin's own quota poll.
192
+ }
193
+ }
194
+ /**
195
+ * Cache-only, for unknown-quota admission with a served receipt. Undefined
196
+ * means poll the provider normally. Only get_scoped's asserted account_id
197
+ * joins insula; parsed identities and display metadata cannot substitute.
198
+ * Background polling should use cachedInsulaQuotaForRoute instead.
199
+ */
200
+ async cachedInsulaQuota(receipt) {
201
+ if (!this.#options.insula ||
202
+ this.#shutdown.signal.aborted ||
203
+ !(await this.#active()))
204
+ return undefined;
205
+ try {
206
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
207
+ return this.#normalizeInsulaQuota(receipt.assertedAccountIdentity);
208
+ }
209
+ catch {
210
+ return undefined;
211
+ }
212
+ }
213
+ /**
214
+ * Background cache lookup without fetching a credential. Re-read the roster
215
+ * so a peer's account replacement invalidates the old route immediately.
216
+ * A route without a known provider account cannot join an insula entry.
217
+ */
218
+ async cachedInsulaQuotaForRoute(routeId) {
219
+ if (!this.#options.insula ||
220
+ this.#shutdown.signal.aborted ||
221
+ !(await this.#active()))
222
+ return undefined;
223
+ try {
224
+ await readClaustrumEnrollmentToken(this.#options.tokenPath);
225
+ const roster = await readVaultRoster(this.#options.rosterPath);
226
+ const row = roster?.rows.find((entry) => entry.routeId === routeId);
227
+ return this.#normalizeInsulaQuota(row?.accountIdentity);
228
+ }
229
+ catch {
230
+ return undefined;
231
+ }
232
+ }
233
+ #normalizeInsulaQuota(accountIdentity) {
234
+ if (!this.#options.insula || !accountIdentity)
235
+ return undefined;
236
+ const current = this.#insula?.source.current(this.#options.insula.provider, accountIdentity, (this.#options.now ?? Date.now)());
237
+ return current
238
+ ? this.#options.insula.normalize(current.entry, current.context)
239
+ : undefined;
240
+ }
166
241
  /**
167
242
  * Authorize one physical send on a vault route. The roster file is re-read
168
243
  * first, so a decline committed by another process applies before the next
@@ -285,6 +360,24 @@ export class ClaustrumConsumer {
285
360
  this.#roster = await readVaultRoster(this.#options.rosterPath);
286
361
  return kept;
287
362
  }
363
+ /**
364
+ * Store a background observation that belongs to an account rather than to
365
+ * a served credential (an insula reading from `cachedInsulaQuotaForRoute`).
366
+ * It lands only while the route is still bound to that known account, so no
367
+ * credential fetch is needed and a replaced account's reading is dropped.
368
+ * The in-memory roster is reloaded from the file, without a vault call.
369
+ */
370
+ async recordAccountQuota(routeId, accountIdentity, observation) {
371
+ this.#assertOpen();
372
+ const kept = await recordVaultAccountQuota(this.#options.rosterPath, {
373
+ routeId,
374
+ accountIdentity,
375
+ observation,
376
+ });
377
+ if (kept)
378
+ this.#roster = await readVaultRoster(this.#options.rosterPath);
379
+ return kept;
380
+ }
288
381
  close() {
289
382
  if (this.#shutdown.signal.aborted)
290
383
  return;
@@ -293,6 +386,8 @@ export class ClaustrumConsumer {
293
386
  (this.#options.clearTimeoutImpl ?? clearTimeout)(this.#timer);
294
387
  this.#timer = undefined;
295
388
  this.#custody?.close();
389
+ this.#insula?.release();
390
+ this.#insula = undefined;
296
391
  this.#roster = undefined;
297
392
  }
298
393
  }
@@ -1,6 +1,9 @@
1
1
  import { type ClaustrumClient, type ClaustrumReporterSource, type EnrollmentTokenFile } from '@cortexkit/claustrum-client';
2
2
  import { type ClaustrumLogger } from './errors.js';
3
- export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'>;
3
+ import type { InsulaUsageTransport } from './insula.js';
4
+ export type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
5
+ insula?: InsulaUsageTransport;
6
+ };
4
7
  /** The two credential types a plugin's family can hold; routing differs by type. */
5
8
  export type VaultCredentialType = 'oauth' | 'api_key';
6
9
  /**
@@ -97,8 +97,9 @@ export interface EnrollmentAncestorOptions {
97
97
  groupPath?: string;
98
98
  }
99
99
  /**
100
- * Protect setup writes from directory replacement. Group write access is safe
101
- * only when local account records prove that the effective user's group is private.
100
+ * Protect setup writes from directory replacement. On POSIX, group write access
101
+ * is safe only when local records prove the effective user's group is private;
102
+ * sticky ancestors are accepted. Windows uses the shared safe-parent policy.
102
103
  */
103
104
  export declare function refuseWritableAncestor(parent: string, options?: EnrollmentAncestorOptions): Promise<void>;
104
105
  export declare function readClaustrumEnrollmentStatus(paths: ClaustrumEnrollmentPaths, proposedName: string): Promise<ClaustrumEnrollmentStatus>;
@@ -4,6 +4,7 @@ import { chmod, mkdir, open, readFile, realpath, rename, stat, unlink, } from 'n
4
4
  import { basename, dirname, extname, isAbsolute, join, resolve, } from 'node:path';
5
5
  import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile, } from '@cortexkit/claustrum-client';
6
6
  import { acquireRefreshFileLock } from '../fs/index.js';
7
+ import { ensurePrivateDirectory as ensureWindowsDirectory, PrivateFileError, readPrivateText, verifySafeDirectory, windowsPrivateFiles, writePrivateAtomic, } from '../fs/private-files.js';
7
8
  import { ClaustrumConsumerError } from './errors.js';
8
9
  const ENROLLMENT_SCHEMA = 1;
9
10
  const ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
@@ -198,6 +199,21 @@ function parseSecretJson(text) {
198
199
  }
199
200
  }
200
201
  async function readBoundedJson(path) {
202
+ if (windowsPrivateFiles) {
203
+ try {
204
+ await ensureWindowsDirectory(dirname(path));
205
+ const text = await readPrivateText(path, true);
206
+ if (Buffer.byteLength(text) > ENROLLMENT_FILE_MAX_BYTES) {
207
+ throw new ClaustrumConsumerError('unsafe-file', 'Claustrum enrollment file is too large');
208
+ }
209
+ return parseSecretJson(text);
210
+ }
211
+ catch (error) {
212
+ if (error.code === 'ENOENT')
213
+ return undefined;
214
+ throw error;
215
+ }
216
+ }
201
217
  let descriptor;
202
218
  try {
203
219
  // O_NOFOLLOW: a symlink planted at the path must not redirect a secret read.
@@ -267,52 +283,76 @@ async function isPrivateGroup(uid, gid, options) {
267
283
  return false;
268
284
  }
269
285
  }
286
+ function ancestorPolicyOptions(options) {
287
+ if (!options.passwdPath && !options.groupPath)
288
+ return undefined;
289
+ return {
290
+ fs: {
291
+ readFile: (path) => readFile(path === '/etc/passwd'
292
+ ? (options.passwdPath ?? path)
293
+ : path === '/etc/group'
294
+ ? (options.groupPath ?? path)
295
+ : path),
296
+ },
297
+ };
298
+ }
270
299
  /**
271
- * Protect setup writes from directory replacement. Group write access is safe
272
- * only when local account records prove that the effective user's group is private.
300
+ * Protect setup writes from directory replacement. On POSIX, group write access
301
+ * is safe only when local records prove the effective user's group is private;
302
+ * sticky ancestors are accepted. Windows uses the shared safe-parent policy.
273
303
  */
274
304
  export async function refuseWritableAncestor(parent, options = {}) {
275
- const uid = process.geteuid?.();
276
- if (uid === undefined)
277
- return;
278
- const gid = process.getegid?.();
279
- let component;
280
- try {
281
- component = await realpath(parent);
282
- }
283
- catch {
284
- return;
285
- }
286
- // Load lazily, once per traversal: account changes take effect on the next write.
287
- let privateGroup;
288
- for (;;) {
289
- const metadata = await stat(component).catch(() => undefined);
290
- if (metadata &&
291
- (metadata.mode & 0o022) !== 0 &&
292
- (metadata.mode & 0o1000) === 0) {
293
- if (privateGroup === undefined) {
294
- privateGroup =
295
- gid !== undefined && (await isPrivateGroup(uid, gid, options));
296
- }
297
- if ((metadata.mode & 0o002) !== 0 ||
298
- metadata.uid !== uid ||
299
- metadata.gid !== gid ||
300
- !privateGroup) {
301
- throw new ClaustrumConsumerError('unsafe-file', `Claustrum enrollment path has a writable ancestor: ${component}. Another user could replace it. Run: chmod g-w,o-w ${component}`);
302
- }
305
+ if (!windowsPrivateFiles) {
306
+ const uid = process.geteuid?.();
307
+ if (uid === undefined)
308
+ return;
309
+ const gid = process.getegid?.();
310
+ let component;
311
+ try {
312
+ component = await realpath(parent);
303
313
  }
304
- const next = dirname(component);
305
- if (next === component)
314
+ catch {
306
315
  return;
307
- component = next;
316
+ }
317
+ // Load lazily, once per traversal: account changes take effect on the next write.
318
+ let privateGroup;
319
+ for (;;) {
320
+ const metadata = await stat(component).catch(() => undefined);
321
+ if (metadata &&
322
+ (metadata.mode & 0o022) !== 0 &&
323
+ (metadata.mode & 0o1000) === 0) {
324
+ if (privateGroup === undefined) {
325
+ privateGroup =
326
+ gid !== undefined && (await isPrivateGroup(uid, gid, options));
327
+ }
328
+ if ((metadata.mode & 0o002) !== 0 ||
329
+ metadata.uid !== uid ||
330
+ metadata.gid !== gid ||
331
+ !privateGroup) {
332
+ throw new ClaustrumConsumerError('unsafe-file', `Claustrum enrollment path has a writable ancestor: ${component}. Another user could replace it. Run: chmod g-w,o-w ${component}`);
333
+ }
334
+ }
335
+ const next = dirname(component);
336
+ if (next === component)
337
+ return;
338
+ component = next;
339
+ }
340
+ }
341
+ try {
342
+ await verifySafeDirectory(parent, ancestorPolicyOptions(options));
343
+ }
344
+ catch (error) {
345
+ if (!(error instanceof PrivateFileError))
346
+ throw error;
347
+ throw new ClaustrumConsumerError('unsafe-file', `Claustrum enrollment parent refused: ${error.path} (${error.reason ?? error.code}). Use a folder that other users cannot write or replace.`);
308
348
  }
309
349
  }
310
- /**
311
- * Create the enrollment directory owner-only (0700), and tighten it to 0700
312
- * when it already exists with group or other bits, so the token and the
313
- * request secret never sit in a directory another account can list.
314
- */
315
- async function ensurePrivateDirectory(directory) {
350
+ /** POSIX tightens the enrollment directory to 0700; Windows verifies safe ancestry without modifying existing parents. */
351
+ async function ensurePrivateDirectory(directory, options = {}) {
352
+ if (windowsPrivateFiles) {
353
+ await ensureWindowsDirectory(directory, false, ancestorPolicyOptions(options));
354
+ return;
355
+ }
316
356
  await mkdir(directory, { recursive: true, mode: 0o700 });
317
357
  const metadata = await stat(directory);
318
358
  const uid = process.geteuid?.();
@@ -324,12 +364,14 @@ async function ensurePrivateDirectory(directory) {
324
364
  }
325
365
  async function writeStateAtomic(path, state, ancestorOptions = {}) {
326
366
  const parent = dirname(path);
327
- await ensurePrivateDirectory(parent);
367
+ await ensurePrivateDirectory(parent, ancestorOptions);
328
368
  await refuseWritableAncestor(parent, ancestorOptions);
329
369
  const bytes = `${JSON.stringify(state)}\n`;
330
370
  if (Buffer.byteLength(bytes) > ENROLLMENT_FILE_MAX_BYTES) {
331
371
  throw new ClaustrumConsumerError('invalid-state', 'Claustrum enrollment state is too large');
332
372
  }
373
+ if (windowsPrivateFiles)
374
+ return writePrivateAtomic(path, bytes);
333
375
  const temporary = join(parent, `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`);
334
376
  let descriptor;
335
377
  let created = false;
@@ -496,7 +538,7 @@ export class ClaustrumEnrollmentManager {
496
538
  return statusFromState(blocked);
497
539
  }
498
540
  async reconcile() {
499
- await ensurePrivateDirectory(dirname(this.#paths.statePath));
541
+ await ensurePrivateDirectory(dirname(this.#paths.statePath), this.#ancestorOptions);
500
542
  const lock = await acquireRefreshFileLock({
501
543
  name: 'ceremony',
502
544
  path: this.#paths.statePath,
@@ -616,7 +658,7 @@ export class ClaustrumEnrollmentManager {
616
658
  }
617
659
  // The vault returns the token exactly once: it reaches disk before the
618
660
  // pending metadata (and its secret) is replaced.
619
- await ensurePrivateDirectory(dirname(this.#paths.tokenPath));
661
+ await ensurePrivateDirectory(dirname(this.#paths.tokenPath), this.#ancestorOptions);
620
662
  await refuseWritableAncestor(dirname(this.#paths.tokenPath), this.#ancestorOptions);
621
663
  await this.#writeTokenFile(this.#paths.tokenPath, {
622
664
  token: outcome.token,
@@ -6,8 +6,9 @@ export { type AccountIdentitySource, type ClaustrumFamily, type ClaustrumScopedA
6
6
  export { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentConnection, type ClaustrumEnrollmentDisconnectResult, ClaustrumEnrollmentManager, type ClaustrumEnrollmentPaths, type ClaustrumEnrollmentResetResult, type ClaustrumEnrollmentStatus, classifyEnrollmentError, connectClaustrumEnrollmentClient, disconnectClaustrumEnrollment, type EnrollmentDisposition, enrollmentAuthority, enrollmentName, getClaustrumEnrollmentPaths, hostEnrollmentPaths, RETRYABLE_ENROLLMENT_CODES, readClaustrumEnrollmentStatus, readClaustrumEnrollmentToken, resetClaustrumEnrollmentState, TERMINAL_ENROLLMENT_CODES, } from './enrollment.js';
7
7
  export { ClaustrumConsumerError, type ClaustrumConsumerFailureKind, type ClaustrumLogger, } from './errors.js';
8
8
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, type HostSlotContent, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
9
+ export type { InsulaQuotaContext, InsulaQuotaOptions, InsulaUsageEntry, InsulaUsageTransport, InsulaUsageWindow, } from './insula.js';
9
10
  export { acceptAccount, type DeclinedAccount, declineAccount, isDeclined, } from './interlock.js';
10
- export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, readVaultRoster, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
11
+ export { type AccountMapper, acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, type MutateVaultRosterOptions, mutateVaultRoster, type ProjectionOptions, projectVaultRoster, type QuotaReceipt, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, type VaultPrimary, type VaultPrimaryBinding, type VaultPrimaryUnavailableReason, type VaultRosterFile, type VaultRosterLockContext, type VaultRosterRow, vaultRoutingRows, } from './roster.js';
11
12
  /**
12
13
  * Connect the client that lists and fetches this consumer's vault credentials
13
14
  * on the request path. `connectionFile` is required: this library
@@ -4,6 +4,7 @@
4
4
  // declined-account interlock and the host-slot guard. Needs the optional
5
5
  // peer `@cortexkit/claustrum-client`.
6
6
  import { ClaustrumClient, } from '@cortexkit/claustrum-client';
7
+ import { insulaUsageTransport } from './insula.js';
7
8
  export { ClaustrumCredentialError, } from '@cortexkit/claustrum-client';
8
9
  export { ClaustrumConsumer, } from './consumer.js';
9
10
  export { ClaustrumScopedCustody, decideScopedRetryAfter401, isScopedCredentialRotation, SERVING_MARGIN_MS, } from './custody.js';
@@ -11,12 +12,13 @@ export { ClaustrumEnrollmentManager, classifyEnrollmentError, connectClaustrumEn
11
12
  export { ClaustrumConsumerError, } from './errors.js';
12
13
  export { assertHostSlotMatchesMode, assertNotCustodyPlaceholder, CUSTODY_PLACEHOLDER_PREFIX, classifyHostSlot, custodyPlaceholder, custodyPlaceholderKey, isCustodyPlaceholder, isCustodyPlaceholderValue, } from './host-slot.js';
13
14
  export { acceptAccount, declineAccount, isDeclined, } from './interlock.js';
14
- export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
15
+ export { acceptVaultRoute, DEFAULT_ROUTE_PREFIX, declineVaultRoute, mutateVaultRoster, projectVaultRoster, readVaultRoster, recordVaultAccountQuota, recordVaultQuota, refreshVaultRoster, resolveVaultPrimary, vaultRoutingRows, } from './roster.js';
15
16
  /**
16
17
  * Connect the client that lists and fetches this consumer's vault credentials
17
18
  * on the request path. `connectionFile` is required: this library
18
19
  * reads no environment, so the plugin resolves the vault's connection file.
19
20
  */
20
- export function connectClaustrumScopedClient(options) {
21
- return ClaustrumClient.connect(options);
21
+ export async function connectClaustrumScopedClient(options) {
22
+ const client = await ClaustrumClient.connect(options);
23
+ return Object.assign(client, { insula: insulaUsageTransport(options) });
22
24
  }
@@ -0,0 +1,69 @@
1
+ import type { ClaustrumClientOptions } from '@cortexkit/claustrum-client';
2
+ /** Insula's window fields are open: plugins choose which limits they understand. */
3
+ export interface InsulaUsageWindow {
4
+ usedPercent: number;
5
+ rawUsedPercent?: number;
6
+ resetsAt?: string;
7
+ windowMinutes?: number;
8
+ windowKind?: string;
9
+ [field: string]: unknown;
10
+ }
11
+ export interface InsulaUsageEntry {
12
+ provider: string;
13
+ account?: string;
14
+ fetchedAt?: string;
15
+ source?: string;
16
+ stale?: unknown;
17
+ errorClass?: unknown;
18
+ usage?: {
19
+ primary?: InsulaUsageWindow;
20
+ secondary?: InsulaUsageWindow;
21
+ tertiary?: InsulaUsageWindow;
22
+ extraRateWindows?: Array<{
23
+ id?: string;
24
+ title?: string;
25
+ window?: InsulaUsageWindow;
26
+ }>;
27
+ [field: string]: unknown;
28
+ };
29
+ [field: string]: unknown;
30
+ }
31
+ export interface InsulaQuotaContext {
32
+ /** Milliseconds since the epoch, parsed from the producer's fetchedAt. */
33
+ fetchedAt: number;
34
+ source?: string;
35
+ }
36
+ export interface InsulaQuotaOptions<Q> {
37
+ provider: 'codex' | 'claude' | 'antigravity';
38
+ /**
39
+ * Set every converted window's reading time to context.fetchedAt, not poll
40
+ * time. Return undefined for entries the plugin cannot use. Antigravity can
41
+ * receive its own sidebar reading back from insula: accept it only from the
42
+ * vault or when fetchedAt is newer than the plugin's last reading.
43
+ */
44
+ normalize: (entry: InsulaUsageEntry, context: InsulaQuotaContext) => Q | undefined;
45
+ }
46
+ /** Optional transport for custom scoped clients; getUsage must not retry refusals. */
47
+ export interface InsulaUsageTransport {
48
+ connectionFile: string;
49
+ getUsage(): Promise<unknown>;
50
+ }
51
+ /** Constructing this transport opens no connection; getUsage opens one per call. */
52
+ export declare function insulaUsageTransport(options: ClaustrumClientOptions & {
53
+ connectionFile: string;
54
+ }): InsulaUsageTransport;
55
+ export declare class InsulaQuotaSource {
56
+ #private;
57
+ private readonly transport;
58
+ private readonly key;
59
+ constructor(transport: InsulaUsageTransport, key: string);
60
+ refresh(now: number): Promise<void>;
61
+ current(provider: string, accountId: string, now: number): {
62
+ entry: InsulaUsageEntry;
63
+ context: InsulaQuotaContext;
64
+ } | undefined;
65
+ }
66
+ export declare function acquireInsulaQuotaSource(transport: InsulaUsageTransport, tokenPath: string): {
67
+ source: InsulaQuotaSource;
68
+ release(): void;
69
+ };