@cortexkit/common-auth 0.14.1 → 0.14.2

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.
@@ -35,8 +35,16 @@ type BrowserExec = (file: string, args: string[], options: {
35
35
  stdio: 'ignore';
36
36
  timeout: number;
37
37
  }) => unknown;
38
+ type BrowserSpawn = (file: string, args: string[], options: {
39
+ stdio: 'ignore';
40
+ windowsHide: true;
41
+ }) => {
42
+ pid?: number;
43
+ unref(): void;
44
+ on(event: 'error', listener: () => void): unknown;
45
+ };
38
46
  /** Opens a URL with the platform's opener; false when that fails. */
39
- export declare function openBrowserForMenu(url: string, platform?: NodeJS.Platform, execFileSync?: BrowserExec): boolean;
47
+ export declare function openBrowserForMenu(url: string, platform?: NodeJS.Platform, execFileSync?: BrowserExec, spawn?: BrowserSpawn): boolean;
40
48
  /**
41
49
  * Runs a login for the menu: a browser login first and, when no browser can
42
50
  * be opened, a device-code login instead, so a headless machine can still
@@ -1,12 +1,32 @@
1
- import { execFileSync as defaultExecFileSync } from 'node:child_process';
1
+ import { execFileSync as defaultExecFileSync, spawn as defaultSpawn, } from 'node:child_process';
2
2
  /** Opens a URL with the platform's opener; false when that fails. */
3
- export function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync) {
3
+ export function openBrowserForMenu(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
4
4
  try {
5
5
  if (platform === 'win32') {
6
- execFileSync('cmd', ['/c', 'start', '', url], {
7
- stdio: 'ignore',
8
- timeout: 3000,
9
- });
6
+ // Start-Process opens the URL with its associated app. Base64 UTF-16LE
7
+ // keeps cmd from parsing the URL; Microsoft documents both options:
8
+ // https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.5
9
+ // https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_powershell_exe?view=powershell-5.1#-encodedcommand-base64encodedcommand
10
+ // PowerShell is launched without waiting for it: a cold Windows
11
+ // PowerShell start took about 6 s on a Windows Server 2022 runner, and a
12
+ // waiting caller with a short timeout killed it before the browser
13
+ // opened. It is not detached: a detached PowerShell has no console and
14
+ // never ran the command on any Windows runner.
15
+ const command = `Start-Process '${url.replaceAll("'", "''")}'`;
16
+ const child = spawn('powershell.exe', [
17
+ '-NoProfile',
18
+ '-NonInteractive',
19
+ '-WindowStyle',
20
+ 'Hidden',
21
+ '-EncodedCommand',
22
+ Buffer.from(command, 'utf16le').toString('base64'),
23
+ ], { stdio: 'ignore', windowsHide: true });
24
+ // A failed launch reports asynchronously; without a listener it would
25
+ // become an uncaught exception after this function has returned.
26
+ child.on('error', () => { });
27
+ child.unref();
28
+ // Node leaves pid undefined when the process could not be started.
29
+ return child.pid !== undefined;
10
30
  }
11
31
  else {
12
32
  execFileSync(platform === 'darwin' ? 'open' : 'xdg-open', [url], {
@@ -1,3 +1,4 @@
1
+ import { combineAbortSignals } from '../util/any-signal.js';
1
2
  import { isWithinCacheKeepWindow } from './window.js';
2
3
  const DEFAULT_TTL_MS = 5 * 60_000;
3
4
  const DEFAULT_MAX_IDLE_WARM_MS = 60 * 60_000;
@@ -350,10 +351,11 @@ export class CacheKeepManager {
350
351
  return;
351
352
  if (this.retireIfExpired(sessionKey, target))
352
353
  return;
353
- const signal = AbortSignal.any([
354
+ const combined = combineAbortSignals([
354
355
  AbortSignal.timeout(this.warmTimeoutMs),
355
356
  this.abortController.signal,
356
357
  ]);
358
+ const signal = combined.signal;
357
359
  let response;
358
360
  let text = '';
359
361
  try {
@@ -368,6 +370,9 @@ export class CacheKeepManager {
368
370
  });
369
371
  return;
370
372
  }
373
+ finally {
374
+ combined.dispose();
375
+ }
371
376
  if (!this.isCurrent(sessionKey, target))
372
377
  return;
373
378
  if (!response.ok) {
@@ -1,4 +1,5 @@
1
1
  import { createLogger } from '../logger/index.js';
2
+ import { combineAbortSignals } from '../util/any-signal.js';
2
3
  import { ClaustrumScopedCustody, decideScopedRetryAfter401, } from './custody.js';
3
4
  import { ClaustrumConsumerError } from './errors.js';
4
5
  import { acceptVaultRoute, declineVaultRoute, readVaultRoster, recordVaultQuota, refreshVaultRoster, vaultRoutingRows, } from './roster.js';
@@ -32,30 +33,33 @@ export class ClaustrumConsumer {
32
33
  return (await this.#options.isCustodyActive?.()) ?? true;
33
34
  }
34
35
  #wait(pending, signal) {
35
- const combined = AbortSignal.any([
36
+ const combined = combineAbortSignals([
36
37
  this.#shutdown.signal,
37
38
  ...(signal ? [signal] : []),
38
39
  ]);
39
40
  return new Promise((resolve, reject) => {
40
- const cleanup = () => combined.removeEventListener('abort', abort);
41
+ const cleanup = () => {
42
+ combined.signal.removeEventListener('abort', abort);
43
+ combined.dispose();
44
+ };
41
45
  const abort = () => {
42
46
  cleanup();
43
- reject(combined.reason);
47
+ reject(combined.signal.reason);
44
48
  };
45
- combined.addEventListener('abort', abort, { once: true });
49
+ combined.signal.addEventListener('abort', abort, { once: true });
46
50
  // Observe the operation even after cancellation: shared metadata work may
47
51
  // finish for other callers, and a late connection must still be closed.
48
52
  pending.then((value) => {
49
53
  cleanup();
50
- if (combined.aborted)
51
- reject(combined.reason);
54
+ if (combined.signal.aborted)
55
+ reject(combined.signal.reason);
52
56
  else
53
57
  resolve(value);
54
58
  }, (error) => {
55
59
  cleanup();
56
60
  reject(error);
57
61
  });
58
- if (combined.aborted)
62
+ if (combined.signal.aborted)
59
63
  abort();
60
64
  });
61
65
  }
@@ -181,13 +185,23 @@ export class ClaustrumConsumer {
181
185
  configured.credentialId !== observed.credentialId ||
182
186
  configured.accountIdentity !== observed.accountIdentity)
183
187
  throw new ClaustrumConsumerError('route-unavailable', 'Claustrum route is disabled, removed or changed');
184
- return (await this.#wait(this.#getCustody(), signal)).authorize({
185
- credentialId: configured.credentialId,
186
- credentialType: configured.credentialType,
187
- ...(configured.accountIdentity !== undefined && {
188
- accountIdentity: configured.accountIdentity,
189
- }),
190
- }, AbortSignal.any([this.#shutdown.signal, ...(signal ? [signal] : [])]));
188
+ const custody = await this.#wait(this.#getCustody(), signal);
189
+ const combined = combineAbortSignals([
190
+ this.#shutdown.signal,
191
+ ...(signal ? [signal] : []),
192
+ ]);
193
+ try {
194
+ return await custody.authorize({
195
+ credentialId: configured.credentialId,
196
+ credentialType: configured.credentialType,
197
+ ...(configured.accountIdentity !== undefined && {
198
+ accountIdentity: configured.accountIdentity,
199
+ }),
200
+ }, combined.signal);
201
+ }
202
+ finally {
203
+ combined.dispose();
204
+ }
191
205
  }
192
206
  async reportFailure(attempt, status, source) {
193
207
  this.#assertOpen();
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Combine abort signals without relying on `AbortSignal.any`, which is missing
3
+ * from early Node 20 releases. Call `dispose` when the operation using the
4
+ * combined signal settles so long-lived source signals do not retain listeners.
5
+ */
6
+ export declare function combineAbortSignals(signals: readonly AbortSignal[]): {
7
+ signal: AbortSignal;
8
+ dispose: () => void;
9
+ };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Combine abort signals without relying on `AbortSignal.any`, which is missing
3
+ * from early Node 20 releases. Call `dispose` when the operation using the
4
+ * combined signal settles so long-lived source signals do not retain listeners.
5
+ */
6
+ export function combineAbortSignals(signals) {
7
+ const controller = new AbortController();
8
+ const listeners = [];
9
+ let disposed = false;
10
+ const dispose = () => {
11
+ if (disposed)
12
+ return;
13
+ disposed = true;
14
+ for (const { source, listener } of listeners) {
15
+ source.removeEventListener('abort', listener);
16
+ }
17
+ listeners.length = 0;
18
+ };
19
+ const abort = (reason) => {
20
+ if (disposed || controller.signal.aborted)
21
+ return;
22
+ controller.abort(reason);
23
+ dispose();
24
+ };
25
+ const alreadyAborted = signals.find((signal) => signal.aborted);
26
+ if (alreadyAborted) {
27
+ controller.abort(alreadyAborted.reason);
28
+ return { signal: controller.signal, dispose };
29
+ }
30
+ for (const source of signals) {
31
+ if (controller.signal.aborted)
32
+ break;
33
+ const listener = () => abort(source.reason);
34
+ listeners.push({ source, listener });
35
+ source.addEventListener('abort', listener, { once: true });
36
+ // Cover a source that aborts after the initial check but before its listener
37
+ // is installed.
38
+ if (source.aborted)
39
+ abort(source.reason);
40
+ }
41
+ return { signal: controller.signal, dispose };
42
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/common-auth",
3
- "version": "0.14.1",
3
+ "version": "0.14.2",
4
4
  "description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
5
5
  "license": "MIT",
6
6
  "repository": {