@owlmeans/cli-auth 0.1.18-rc.15 → 0.1.18-rc.16

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.
package/build/lock.d.ts CHANGED
@@ -1,20 +1,4 @@
1
- import type { SignInLockInfo } from './types.js';
1
+ import type { SignInLockHelper } from './lock/types.js';
2
2
  export declare const lockPathFor: (credentialsPath: string) => string;
3
- export declare const readLock: (path: string) => Promise<SignInLockInfo | null>;
4
- /**
5
- * Become the one process driving this API URL's sign-in, or find out somebody else already is.
6
- *
7
- * Best-effort, not a mutual-exclusion guarantee: two processes racing this at the exact same
8
- * instant can both conclude they are the owner, and each then drives its own independent device
9
- * authorization. That costs an extra browser tab, never a corrupted file or a double-spent code —
10
- * this is a convenience for the ordinary case (a person running two terminal tabs), not a
11
- * correctness boundary.
12
- */
13
- export declare const claimOrJoinLock: (path: string, apiUrl: string, info: Omit<SignInLockInfo, 'pid' | 'nonce' | 'apiUrl'>) => Promise<{
14
- owner: boolean;
15
- info: SignInLockInfo;
16
- }>;
17
- /** Clear the lock, but only the copy of it this process itself wrote — a stale read after
18
- * somebody else has already reclaimed the same path must never delete THEIR lock instead. */
19
- export declare const releaseLock: (path: string, nonce: string) => Promise<void>;
3
+ export declare const makeSignInLockHelper: (path: string) => SignInLockHelper;
20
4
  //# sourceMappingURL=lock.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"lock.d.ts","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAEhD,eAAO,MAAM,WAAW,oBAAqB,MAAM,KAAG,MAAmC,CAAA;AAEzF,eAAO,MAAM,QAAQ,SAAgB,MAAM,KAAG,OAAO,CAAC,cAAc,GAAG,IAAI,CAM1E,CAAA;AAYD;;;;;;;;GAQG;AACH,eAAO,MAAM,eAAe,SACpB,MAAM,UAAU,MAAM,QAAQ,IAAI,CAAC,cAAc,EAAE,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC,KACnF,OAAO,CAAC;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,cAAc,CAAA;CAAE,CAWlD,CAAA;AAED;6FAC6F;AAC7F,eAAO,MAAM,WAAW,SAAgB,MAAM,SAAS,MAAM,KAAG,OAAO,CAAC,IAAI,CAK3E,CAAA"}
1
+ {"version":3,"file":"lock.d.ts","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAoC,gBAAgB,EAAE,MAAM,iBAAiB,CAAA;AAEzF,eAAO,MAAM,WAAW,oBAAqB,MAAM,KAAG,MAAmC,CAAA;AAEzF,eAAO,MAAM,oBAAoB,SAAU,MAAM,KAAG,gBAwCnD,CAAA"}
package/build/lock.js CHANGED
@@ -2,48 +2,40 @@ import { randomBytes } from 'node:crypto';
2
2
  import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
3
3
  import { dirname } from 'node:path';
4
4
  export const lockPathFor = (credentialsPath) => `${credentialsPath}.lock`;
5
- export const readLock = async (path) => {
6
- try {
7
- return JSON.parse(await readFile(path, 'utf-8'));
8
- }
9
- catch {
10
- return null;
11
- }
12
- };
13
- const isAlive = (pid) => {
14
- try {
15
- process.kill(pid, 0);
16
- return true;
17
- }
18
- catch {
19
- return false;
20
- }
21
- };
22
- /**
23
- * Become the one process driving this API URL's sign-in, or find out somebody else already is.
24
- *
25
- * Best-effort, not a mutual-exclusion guarantee: two processes racing this at the exact same
26
- * instant can both conclude they are the owner, and each then drives its own independent device
27
- * authorization. That costs an extra browser tab, never a corrupted file or a double-spent code —
28
- * this is a convenience for the ordinary case (a person running two terminal tabs), not a
29
- * correctness boundary.
30
- */
31
- export const claimOrJoinLock = async (path, apiUrl, info) => {
32
- const existing = await readLock(path);
33
- if (existing != null && existing.apiUrl === apiUrl && existing.expiresAt > Date.now() && isAlive(existing.pid)) {
34
- return { owner: false, info: existing };
35
- }
36
- const mine = { ...info, apiUrl, pid: process.pid, nonce: randomBytes(8).toString('hex') };
37
- await mkdir(dirname(path), { recursive: true });
38
- await writeFile(path, JSON.stringify(mine), { mode: 0o600 });
39
- return { owner: true, info: mine };
40
- };
41
- /** Clear the lock, but only the copy of it this process itself wrote — a stale read after
42
- * somebody else has already reclaimed the same path must never delete THEIR lock instead. */
43
- export const releaseLock = async (path, nonce) => {
44
- const existing = await readLock(path);
45
- if (existing?.nonce === nonce) {
46
- await unlink(path).catch(() => undefined);
47
- }
5
+ export const makeSignInLockHelper = (path) => {
6
+ const readLock = async () => {
7
+ try {
8
+ return JSON.parse(await readFile(path, 'utf-8'));
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ };
14
+ const isAlive = (pid) => {
15
+ try {
16
+ process.kill(pid, 0);
17
+ return true;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ };
23
+ const claimOrJoinLock = async (apiUrl, info) => {
24
+ const existing = await readLock();
25
+ if (existing != null && existing.apiUrl === apiUrl && existing.expiresAt > Date.now() && isAlive(existing.pid)) {
26
+ return { owner: false, info: existing };
27
+ }
28
+ const mine = { ...info, apiUrl, pid: process.pid, nonce: randomBytes(8).toString('hex') };
29
+ await mkdir(dirname(path), { recursive: true });
30
+ await writeFile(path, JSON.stringify(mine), { mode: 0o600 });
31
+ return { owner: true, info: mine };
32
+ };
33
+ const releaseLock = async (nonce) => {
34
+ const existing = await readLock();
35
+ if (existing?.nonce === nonce) {
36
+ await unlink(path).catch(() => undefined);
37
+ }
38
+ };
39
+ return { readLock, claimOrJoinLock, releaseLock };
48
40
  };
49
41
  //# sourceMappingURL=lock.js.map
package/build/lock.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lock.js","sourceRoot":"","sources":["../src/lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kB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zD,MAAM,QAAQ,GAAG,MAAM,QAAQ,EAAE,CAAA;QACjC,IAAI,QAAQ,EAAE,KAAK,KAAK,KAAK,EAAE,CAAC;YAC9B,MAAM,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAA;QAC3C,CAAC;IACH,CAAC,CAAA;IAED,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,WAAW,EAAE,CAAA;AACnD,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owlmeans/cli-auth",
3
- "version": "0.1.18-rc.15",
3
+ "version": "0.1.18-rc.16",
4
4
  "license": "MIT",
5
5
  "description": "OAuth device-authorization sign-in for a command-line tool: a dotenv-style ~/.owlmeans credentials file (overridable, environment always wins), a cross-process sign-in lock so several invocations converge on one browser round trip, a browser opener, and a small credential holder a CLI wraps its API calls with.",
6
6
  "type": "module",
@@ -23,8 +23,8 @@
23
23
  }
24
24
  },
25
25
  "dependencies": {
26
- "@owlmeans/error": "^0.1.18-rc.37",
27
- "@owlmeans/oauth": "^0.1.18-rc.15"
26
+ "@owlmeans/error": "^0.1.18-rc.38",
27
+ "@owlmeans/oauth": "^0.1.18-rc.16"
28
28
  },
29
29
  "devDependencies": {
30
30
  "@owlmeans/dep-config": "workspace:*",
@@ -0,0 +1,45 @@
1
+ export interface SetEnvValuesResult {
2
+ /** The file is readable by somebody other than its owner — reported, never silently tightened. */
3
+ insecurePermissions: boolean
4
+ }
5
+
6
+ /** The dotenv-style `~/.owlmeans` credentials file, with the process environment layered over it. */
7
+ export interface EnvFileHelper {
8
+ /**
9
+ * Where the credentials file lives: `OWLMEANS_CREDENTIALS`, or `~/.owlmeans`.
10
+ *
11
+ * A CLI that talks to more than one deployment (a staging environment, a self-hosted instance)
12
+ * points this at a different file per deployment — the file is never merged with another one, and
13
+ * a token it holds is meaningless anywhere but the API URL it was signed in against.
14
+ */
15
+ resolveEnvFile: (env?: NodeJS.ProcessEnv) => string
16
+ /**
17
+ * Parse a dotenv-shaped body: `KEY=value`, an optional `export ` prefix, `#` comments, one level
18
+ * of quoting. Deliberately small — a dotenv library would add a dependency for a format this
19
+ * package itself writes, and this is the one shape it ever needs to read back.
20
+ */
21
+ parseEnv: (content: string) => Record<string, string>
22
+ /** The credentials file's values alone, with no environment overlay — what a token is bound to. */
23
+ readCredentialsFile: (env?: NodeJS.ProcessEnv) => Promise<Record<string, string>>
24
+ /**
25
+ * The file, with the process environment layered over it — environment wins, but an environment
26
+ * value that is the EMPTY STRING is treated as unset.
27
+ *
28
+ * The empty-string rule exists because a harness config commonly expands an unset shell variable
29
+ * to `''` (`${VIABLE_API_TOKEN:-}`), and a literal empty override must not shadow a real value the
30
+ * file holds — that would make "I have not set this" indistinguishable from "I am overriding this
31
+ * to nothing", and the file is always the more deliberate of the two.
32
+ */
33
+ loadOwlmeansEnv: (env?: NodeJS.ProcessEnv) => Promise<Record<string, string>>
34
+ /**
35
+ * Replace the named keys in the credentials file, keeping every other line — comments, a key this
36
+ * call did not touch, blank lines — exactly where they were. An `undefined` value removes the key.
37
+ *
38
+ * Written atomically (a temp file in the same directory, then a rename) so a process killed
39
+ * mid-write never leaves a half-written credentials file behind, and created with mode `0600`
40
+ * because this file can hold a live access token. An existing file that is readable by anyone but
41
+ * its owner is reported back rather than silently tightened — permissions someone else set on
42
+ * purpose are theirs to change.
43
+ */
44
+ setEnvValues: (path: string, values: Record<string, string | undefined>) => Promise<SetEnvValuesResult>
45
+ }
package/src/env-file.ts CHANGED
@@ -3,121 +3,98 @@ import { chmod, mkdir, readFile, rename, stat, writeFile } from 'node:fs/promise
3
3
  import { homedir } from 'node:os'
4
4
  import { dirname, join } from 'node:path'
5
5
  import { DEFAULT_CREDENTIALS_FILENAME, ENV_CREDENTIALS_FILE } from './consts.js'
6
-
7
- /**
8
- * Where the credentials file lives: `OWLMEANS_CREDENTIALS`, or `~/.owlmeans`.
9
- *
10
- * A CLI that talks to more than one deployment (a staging environment, a self-hosted instance)
11
- * points this at a different file per deployment — the file is never merged with another one, and
12
- * a token it holds is meaningless anywhere but the API URL it was signed in against.
13
- */
14
- export const resolveEnvFile = (env: NodeJS.ProcessEnv = process.env): string =>
15
- env[ENV_CREDENTIALS_FILE] != null && env[ENV_CREDENTIALS_FILE] !== ''
16
- ? env[ENV_CREDENTIALS_FILE]
17
- : join(homedir(), DEFAULT_CREDENTIALS_FILENAME)
18
-
19
- /**
20
- * Parse a dotenv-shaped body: `KEY=value`, an optional `export ` prefix, `#` comments, one level
21
- * of quoting. Deliberately small — a dotenv library would add a dependency for a format this
22
- * package itself writes, and this is the one shape it ever needs to read back.
23
- */
24
- export const parseEnv = (content: string): Record<string, string> => {
25
- const values: Record<string, string> = {}
26
- for (const raw of content.split('\n')) {
27
- const line = raw.trim()
28
- if (line === '' || line.startsWith('#')) continue
29
-
30
- const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line)
31
- if (match == null) continue
32
-
33
- let value = match[2].trim()
34
- if ((value.startsWith('"') && value.endsWith('"') && value.length > 1)
35
- || (value.startsWith("'") && value.endsWith("'") && value.length > 1)) {
36
- value = value.slice(1, -1)
6
+ import type { EnvFileHelper, SetEnvValuesResult } from './env-file/types.js'
7
+
8
+ export const createEnvFileHelper = (): EnvFileHelper => {
9
+ const resolveEnvFile = (env: NodeJS.ProcessEnv = process.env): string =>
10
+ env[ENV_CREDENTIALS_FILE] != null && env[ENV_CREDENTIALS_FILE] !== ''
11
+ ? env[ENV_CREDENTIALS_FILE]
12
+ : join(homedir(), DEFAULT_CREDENTIALS_FILENAME)
13
+
14
+ const parseEnv = (content: string): Record<string, string> => {
15
+ const values: Record<string, string> = {}
16
+ for (const raw of content.split('\n')) {
17
+ const line = raw.trim()
18
+ if (line === '' || line.startsWith('#')) continue
19
+
20
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line)
21
+ if (match == null) continue
22
+
23
+ let value = match[2].trim()
24
+ if ((value.startsWith('"') && value.endsWith('"') && value.length > 1)
25
+ || (value.startsWith("'") && value.endsWith("'") && value.length > 1)) {
26
+ value = value.slice(1, -1)
27
+ }
28
+ values[match[1]] = value
37
29
  }
38
- values[match[1]] = value
30
+
31
+ return values
39
32
  }
40
33
 
41
- return values
42
- }
34
+ const readFileIfPresent = async (path: string): Promise<string> =>
35
+ await readFile(path, 'utf-8').catch(() => '')
43
36
 
44
- const readFileIfPresent = async (path: string): Promise<string> =>
45
- await readFile(path, 'utf-8').catch(() => '')
46
-
47
- /**
48
- * The credentials file's values alone, with no environment overlay — what a token is bound to.
49
- */
50
- export const readCredentialsFile = async (env: NodeJS.ProcessEnv = process.env): Promise<Record<string, string>> =>
51
- parseEnv(await readFileIfPresent(resolveEnvFile(env)))
52
-
53
- /**
54
- * The file, with the process environment layered over it — environment wins, but an environment
55
- * value that is the EMPTY STRING is treated as unset.
56
- *
57
- * The empty-string rule exists because a harness config commonly expands an unset shell variable
58
- * to `''` (`${VIABLE_API_TOKEN:-}`), and a literal empty override must not shadow a real value the
59
- * file holds — that would make "I have not set this" indistinguishable from "I am overriding this
60
- * to nothing", and the file is always the more deliberate of the two.
61
- */
62
- export const loadOwlmeansEnv = async (env: NodeJS.ProcessEnv = process.env): Promise<Record<string, string>> => {
63
- const file = await readCredentialsFile(env)
64
- const fromEnv: Record<string, string> = {}
65
- Object.entries(env).forEach(([key, value]) => {
66
- if (value != null && value !== '') fromEnv[key] = value
67
- })
68
-
69
- return { ...file, ...fromEnv }
70
- }
37
+ const readCredentialsFile = async (env: NodeJS.ProcessEnv = process.env): Promise<Record<string, string>> =>
38
+ parseEnv(await readFileIfPresent(resolveEnvFile(env)))
39
+
40
+ const loadOwlmeansEnv = async (env: NodeJS.ProcessEnv = process.env): Promise<Record<string, string>> => {
41
+ const file = await readCredentialsFile(env)
42
+ const fromEnv: Record<string, string> = {}
43
+ Object.entries(env).forEach(([key, value]) => {
44
+ if (value != null && value !== '') fromEnv[key] = value
45
+ })
71
46
 
72
- /**
73
- * Replace the named keys in the credentials file, keeping every other line — comments, a key this
74
- * call did not touch, blank lines — exactly where they were.
75
- *
76
- * Written atomically (a temp file in the same directory, then a rename) so a process killed
77
- * mid-write never leaves a half-written credentials file behind, and created with mode `0600`
78
- * because this file can hold a live access token. An existing file that is readable by anyone but
79
- * its owner is reported back rather than silently tightened — permissions someone else set on
80
- * purpose are theirs to change.
81
- */
82
- export const setEnvValues = async (
83
- path: string, values: Record<string, string | undefined>
84
- ): Promise<{ insecurePermissions: boolean }> => {
85
- const existing = await readFileIfPresent(path)
86
- const lines = existing === '' ? [] : existing.split('\n')
87
- const claimed = new Set<string>()
88
-
89
- const rewritten = lines.map(line => {
90
- const trimmed = line.trim()
91
- const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(trimmed)
92
- if (match == null || !(match[1] in values)) return line
93
-
94
- claimed.add(match[1])
95
- const value = values[match[1]]
96
-
97
- return value == null ? null : `${match[1]}=${value}`
98
- }).filter((line): line is string => line != null)
99
-
100
- Object.entries(values).forEach(([key, value]) => {
101
- if (claimed.has(key) || value == null) return
102
- rewritten.push(`${key}=${value}`)
103
- })
104
-
105
- const body = `${rewritten.join('\n').replace(/\n+$/, '')}\n`
106
-
107
- await mkdir(dirname(path), { recursive: true })
108
- const tmp = join(dirname(path), `.${DEFAULT_CREDENTIALS_FILENAME}.${randomBytes(6).toString('hex')}.tmp`)
109
- await writeFile(tmp, body, { mode: 0o600 })
110
- await rename(tmp, path)
111
- await chmod(path, 0o600).catch(() => undefined)
112
-
113
- let insecurePermissions = false
114
- try {
115
- const info = await stat(path)
116
- insecurePermissions = (info.mode & 0o077) !== 0
117
- } catch {
118
- // Nothing to report if the stat itself fails right after a successful write — unusual enough
119
- // that guessing at a permission problem would be noise.
47
+ return { ...file, ...fromEnv }
120
48
  }
121
49
 
122
- return { insecurePermissions }
50
+ const setEnvValues = async (
51
+ path: string, values: Record<string, string | undefined>
52
+ ): Promise<SetEnvValuesResult> => {
53
+ const existing = await readFileIfPresent(path)
54
+ const lines = existing === '' ? [] : existing.split('\n')
55
+ const claimed = new Set<string>()
56
+
57
+ const rewritten = lines.map(line => {
58
+ const trimmed = line.trim()
59
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(trimmed)
60
+ if (match == null || !(match[1] in values)) return line
61
+
62
+ claimed.add(match[1])
63
+ const value = values[match[1]]
64
+
65
+ return value == null ? null : `${match[1]}=${value}`
66
+ }).filter((line): line is string => line != null)
67
+
68
+ Object.entries(values).forEach(([key, value]) => {
69
+ if (claimed.has(key) || value == null) return
70
+ rewritten.push(`${key}=${value}`)
71
+ })
72
+
73
+ const body = `${rewritten.join('\n').replace(/\n+$/, '')}\n`
74
+
75
+ await mkdir(dirname(path), { recursive: true })
76
+ const tmp = join(dirname(path), `.${DEFAULT_CREDENTIALS_FILENAME}.${randomBytes(6).toString('hex')}.tmp`)
77
+ await writeFile(tmp, body, { mode: 0o600 })
78
+ await rename(tmp, path)
79
+ await chmod(path, 0o600).catch(() => undefined)
80
+
81
+ let insecurePermissions = false
82
+ try {
83
+ const info = await stat(path)
84
+ insecurePermissions = (info.mode & 0o077) !== 0
85
+ } catch {
86
+ // Nothing to report if the stat itself fails right after a successful write — unusual enough
87
+ // that guessing at a permission problem would be noise.
88
+ }
89
+
90
+ return { insecurePermissions }
91
+ }
92
+
93
+ return { resolveEnvFile, parseEnv, readCredentialsFile, loadOwlmeansEnv, setEnvValues }
123
94
  }
95
+
96
+ export const envFileHelper = createEnvFileHelper()
97
+
98
+ /** @deprecated compat:factory-refactor — use `envFileHelper.loadOwlmeansEnv(…)` */
99
+ export const loadOwlmeansEnv = async (env: NodeJS.ProcessEnv = process.env): Promise<Record<string, string>> =>
100
+ await envFileHelper.loadOwlmeansEnv(env)
package/src/holder.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { hostname, userInfo } from 'node:os'
2
- import { discoverAuthorizationServer, OAuthAccessDenied, OAuthError, OAUTH_DEVICE_NAME_MAX, pollDeviceToken, requestDeviceAuthorization, revokeToken, signInRequired, TokenRejected, type AuthorizationServerMetadata, type DeviceSignInOutcome } from '@owlmeans/oauth'
2
+ import { OAuthAccessDenied, OAuthError, OAUTH_DEVICE_NAME_MAX, signInRequired, TokenRejected, type AuthorizationServerMetadata, type DeviceSignInOutcome, oauthClientHelper } from '@owlmeans/oauth'
3
3
  import { DEFAULT_WAIT_MS } from './consts.js'
4
- import { readCredentialsFile, resolveEnvFile, setEnvValues } from './env-file.js'
5
- import { claimOrJoinLock, lockPathFor, readLock, releaseLock } from './lock.js'
4
+ import { envFileHelper } from './env-file.js'
5
+ import { lockPathFor, makeSignInLockHelper } from './lock.js'
6
6
  import type { SignInLockInfo, CliCredentials, CliCredentialsOptions } from './types.js'
7
7
  import { openBrowser } from './open-browser.js'
8
8
 
@@ -25,14 +25,14 @@ const inFlightByApiUrl = new Map<string, Promise<DeviceSignInOutcome>>()
25
25
  export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials => {
26
26
  const env = opts.env ?? process.env
27
27
  const notify = (message: string): void => opts.onNotify?.(message)
28
- const credentialsPath = resolveEnvFile(env)
29
- const lockPath = lockPathFor(credentialsPath)
28
+ const credentialsPath = envFileHelper.resolveEnvFile(env)
29
+ const lock = makeSignInLockHelper(lockPathFor(credentialsPath))
30
30
 
31
31
  const token = async (): Promise<string | null> => {
32
32
  const envValue = env[opts.tokenEnvKey]
33
33
  if (envValue != null && envValue !== '') return envValue
34
34
 
35
- const file = await readCredentialsFile(env)
35
+ const file = await envFileHelper.readCredentialsFile(env)
36
36
  const boundUrl = file[opts.apiUrlEnvKey]
37
37
  if (boundUrl != null && boundUrl !== '' && boundUrl !== opts.apiUrl) return null
38
38
 
@@ -44,12 +44,12 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
44
44
  /** Start a fresh device authorization, or adopt another live process's own — either way, claim
45
45
  * or join the lock BEFORE requesting one, so the decision and the request agree. */
46
46
  const claimJoinOrStart = async (server: AuthorizationServerMetadata): Promise<{ owner: boolean, info: SignInLockInfo }> => {
47
- const authorization = await requestDeviceAuthorization(server, {
47
+ const authorization = await oauthClientHelper.requestDeviceAuthorization(server, {
48
48
  client_id: opts.clientId, scope: opts.scope, resource: opts.resource ?? opts.apiUrl,
49
49
  device_name: opts.deviceName ?? defaultDeviceName(),
50
50
  })
51
51
 
52
- return await claimOrJoinLock(lockPath, opts.apiUrl, {
52
+ return await lock.claimOrJoinLock(opts.apiUrl, {
53
53
  verificationUri: authorization.verification_uri,
54
54
  verificationUriComplete: authorization.verification_uri_complete,
55
55
  userCode: authorization.user_code,
@@ -70,7 +70,7 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
70
70
  if (existing != null) return existing
71
71
 
72
72
  const promise = (async (): Promise<DeviceSignInOutcome> => {
73
- const server = await discoverAuthorizationServer(opts.apiUrl)
73
+ const server = await oauthClientHelper.discoverAuthorizationServer(opts.apiUrl)
74
74
  const claim = await claimJoinOrStart(server)
75
75
 
76
76
  notify(
@@ -86,19 +86,19 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
86
86
  }
87
87
 
88
88
  try {
89
- const outcome = await pollDeviceToken(server, {
89
+ const outcome = await oauthClientHelper.pollDeviceToken(server, {
90
90
  clientId: opts.clientId, deviceCode: claim.info.deviceCode, interval: claim.info.interval,
91
91
  expiresAt: claim.info.expiresAt,
92
92
  })
93
93
  if (outcome.status === 'authorized') {
94
- await setEnvValues(credentialsPath, { [opts.tokenEnvKey]: outcome.token, [opts.apiUrlEnvKey]: opts.apiUrl })
94
+ await envFileHelper.setEnvValues(credentialsPath, { [opts.tokenEnvKey]: outcome.token, [opts.apiUrlEnvKey]: opts.apiUrl })
95
95
  notify('Signed in.')
96
96
  }
97
97
 
98
98
  return outcome
99
99
  } finally {
100
100
  inFlightByApiUrl.delete(opts.apiUrl)
101
- if (claim.owner) await releaseLock(lockPath, claim.info.nonce)
101
+ if (claim.owner) await lock.releaseLock(claim.info.nonce)
102
102
  }
103
103
  })()
104
104
  inFlightByApiUrl.set(opts.apiUrl, promise)
@@ -128,9 +128,9 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
128
128
  ]).finally(() => clearTimeout(ceiling))
129
129
 
130
130
  if (!raced.settled) {
131
- const lock = await readLock(lockPath)
131
+ const pending = await lock.readLock()
132
132
  throw signInRequired({
133
- url: lock?.verificationUri ?? opts.apiUrl, code: lock?.userCode, expiresAt: lock?.expiresAt,
133
+ url: pending?.verificationUri ?? opts.apiUrl, code: pending?.userCode, expiresAt: pending?.expiresAt,
134
134
  })
135
135
  }
136
136
 
@@ -147,9 +147,9 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
147
147
  },
148
148
 
149
149
  invalidate: async (rejectedToken: string): Promise<void> => {
150
- const file = await readCredentialsFile(env)
150
+ const file = await envFileHelper.readCredentialsFile(env)
151
151
  if (file[opts.tokenEnvKey] === rejectedToken) {
152
- await setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
152
+ await envFileHelper.setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
153
153
  notify('The stored token was refused. Signing in again.')
154
154
 
155
155
  return
@@ -163,11 +163,11 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
163
163
  const current = await token()
164
164
  if (current == null) return
165
165
 
166
- const server = await discoverAuthorizationServer(opts.apiUrl).catch(() => null)
166
+ const server = await oauthClientHelper.discoverAuthorizationServer(opts.apiUrl).catch(() => null)
167
167
  if (server != null) {
168
- await revokeToken(server, { token: current, clientId: opts.clientId }).catch(() => undefined)
168
+ await oauthClientHelper.revokeToken(server, { token: current, clientId: opts.clientId }).catch(() => undefined)
169
169
  }
170
- await setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
170
+ await envFileHelper.setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
171
171
  },
172
172
  }
173
173
  }
package/src/index.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export * from './consts.js'
2
2
  export * from './env-file.js'
3
+ export type * from './env-file/types.js'
3
4
  export * from './lock.js'
5
+ export type * from './lock/types.js'
4
6
  export type * from './types.js'
5
7
  export * from './open-browser.js'
6
8
  export * from './holder.js'
@@ -0,0 +1,29 @@
1
+ import type { SignInLockInfo } from '../types.js'
2
+
3
+ /** What the claiming process states about the sign-in; the lock adds who it is and its nonce. */
4
+ export interface SignInLockDraft extends Omit<SignInLockInfo, 'pid' | 'nonce' | 'apiUrl'> {}
5
+
6
+ export interface SignInLockClaim {
7
+ /** This process wrote the lock and drives the sign-in. */
8
+ owner: boolean
9
+ info: SignInLockInfo
10
+ }
11
+
12
+ /** The cross-process sign-in lock at one path. */
13
+ export interface SignInLockHelper {
14
+ /** The lock as written, or `null` for a missing or malformed file. */
15
+ readLock: () => Promise<SignInLockInfo | null>
16
+ /**
17
+ * Become the one process driving this API URL's sign-in, or find out somebody else already is.
18
+ *
19
+ * Best-effort, not a mutual-exclusion guarantee: two processes racing this at the exact same
20
+ * instant can both conclude they are the owner, and each then drives its own independent device
21
+ * authorization. That costs an extra browser tab, never a corrupted file or a double-spent code —
22
+ * this is a convenience for the ordinary case (a person running two terminal tabs), not a
23
+ * correctness boundary.
24
+ */
25
+ claimOrJoinLock: (apiUrl: string, info: SignInLockDraft) => Promise<SignInLockClaim>
26
+ /** Clear the lock, but only the copy of it this process itself wrote — a stale read after
27
+ * somebody else has already reclaimed the same path must never delete THEIR lock instead. */
28
+ releaseLock: (nonce: string) => Promise<void>
29
+ }