@owlmeans/cli-auth 0.1.18-rc.9 → 0.1.18

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 (50) hide show
  1. package/README.md +178 -1
  2. package/agent-meta/manifest.json +3 -3
  3. package/agent-meta/skills/cli-auth/SKILL.md +18 -16
  4. package/build/consts.local.d.ts +2 -0
  5. package/build/consts.local.d.ts.map +1 -0
  6. package/build/consts.local.js +6 -0
  7. package/build/consts.local.js.map +1 -0
  8. package/build/env-file/types.d.ts +45 -0
  9. package/build/env-file/types.d.ts.map +1 -0
  10. package/build/env-file/types.js +2 -0
  11. package/build/env-file/types.js.map +1 -0
  12. package/build/env-file.d.ts +4 -40
  13. package/build/env-file.d.ts.map +1 -1
  14. package/build/env-file.js +71 -99
  15. package/build/env-file.js.map +1 -1
  16. package/build/holder.d.ts +1 -36
  17. package/build/holder.d.ts.map +1 -1
  18. package/build/holder.js +19 -19
  19. package/build/holder.js.map +1 -1
  20. package/build/index.d.ts +3 -0
  21. package/build/index.d.ts.map +1 -1
  22. package/build/index.js.map +1 -1
  23. package/build/lock/types.d.ts +28 -0
  24. package/build/lock/types.d.ts.map +1 -0
  25. package/build/lock/types.js +2 -0
  26. package/build/lock/types.js.map +1 -0
  27. package/build/lock.d.ts +2 -37
  28. package/build/lock.d.ts.map +1 -1
  29. package/build/lock.js +35 -43
  30. package/build/lock.js.map +1 -1
  31. package/build/open-browser.d.ts.map +1 -1
  32. package/build/open-browser.js +1 -5
  33. package/build/open-browser.js.map +1 -1
  34. package/build/types.d.ts +57 -0
  35. package/build/types.d.ts.map +1 -0
  36. package/build/types.js +2 -0
  37. package/build/types.js.map +1 -0
  38. package/package.json +5 -5
  39. package/src/consts.local.ts +5 -0
  40. package/src/env-file/types.ts +45 -0
  41. package/src/env-file.ts +87 -110
  42. package/src/holder.ts +20 -62
  43. package/src/index.ts +3 -0
  44. package/src/lock/types.ts +29 -0
  45. package/src/lock.ts +33 -61
  46. package/src/open-browser.ts +1 -6
  47. package/src/types.ts +58 -0
  48. package/tests/env-file.spec.ts +18 -18
  49. package/tests/holder.spec.ts +4 -6
  50. package/tests/lock.spec.ts +22 -19
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,53 +1,11 @@
1
1
  import { hostname, userInfo } from 'node:os'
2
- import {
3
- discoverAuthorizationServer, OAuthAccessDenied, OAuthError, OAUTH_DEVICE_NAME_MAX,
4
- pollDeviceToken, requestDeviceAuthorization, revokeToken, signInRequired, TokenRejected
5
- } from '@owlmeans/oauth'
6
- import type { AuthorizationServerMetadata, DeviceSignInOutcome } from '@owlmeans/oauth'
2
+ import { OAuthAccessDenied, OAuthError, OAUTH_DEVICE_NAME_MAX, signInRequired, TokenRejected, type AuthorizationServerMetadata, type DeviceSignInOutcome, oauthClientHelper } from '@owlmeans/oauth'
7
3
  import { DEFAULT_WAIT_MS } from './consts.js'
8
- import { readCredentialsFile, resolveEnvFile, setEnvValues } from './env-file.js'
9
- import { claimOrJoinLock, lockPathFor, readLock, releaseLock } from './lock.js'
10
- import type { SignInLockInfo } from './lock.js'
4
+ import { envFileHelper } from './env-file.js'
5
+ import { lockPathFor, makeSignInLockHelper } from './lock.js'
6
+ import type { SignInLockInfo, CliCredentials, CliCredentialsOptions } from './types.js'
11
7
  import { openBrowser } from './open-browser.js'
12
8
 
13
- export interface CliCredentialsOptions {
14
- /** The API origin this credential set is for, and the OAuth `resource` it is scoped to unless
15
- * `resource` says otherwise. */
16
- apiUrl: string
17
- /** This CLI's OAuth `client_id` — a static one the authorization server declared, or an https
18
- * Client ID Metadata Document URL. */
19
- clientId: string
20
- deviceName?: string
21
- resource?: string
22
- scope?: string
23
- /** Which key in `~/.owlmeans` (and the environment) carries the token. */
24
- tokenEnvKey: string
25
- /** Which key records the URL a stored token belongs to. A file naming no URL at all is treated
26
- * as belonging to whichever `apiUrl` is asked for — only an explicit MISMATCH refuses it. */
27
- apiUrlEnvKey: string
28
- env?: NodeJS.ProcessEnv
29
- /** Best-effort progress — "open this URL and enter this code", "signed in", a failure. A host
30
- * wires this to stderr, an MCP `notifications/message`, or nothing at all. */
31
- onNotify?: (message: string) => void
32
- }
33
-
34
- export interface CliCredentials {
35
- /** The token this call site should use right now: the environment, then the bound file value,
36
- * or `null` when neither has one. */
37
- token: () => Promise<string | null>
38
- /** Ensure a usable token exists. Starts or joins a device sign-in when there is none, waits up
39
- * to `waitMs` for it to be approved, and returns the token. The sign-in keeps running in the
40
- * background past that wait — a later `require()` call picks up wherever it left off, rather
41
- * than starting over. */
42
- require: (waitMs?: number) => Promise<string>
43
- /** A 401 happened while presenting `rejectedToken`. A token that came from the FILE is forgotten
44
- * so the next `require()` signs in again; a token that came from the ENVIRONMENT is reported —
45
- * silently trying another identity behind an operator's back is worse than failing loudly. */
46
- invalidate: (rejectedToken: string) => Promise<void>
47
- /** Revoke the current token at the server and remove it from the file. */
48
- signOut: () => Promise<void>
49
- }
50
-
51
9
 
52
10
  const defaultDeviceName = (): string => {
53
11
  let who = 'cli'
@@ -67,14 +25,14 @@ const inFlightByApiUrl = new Map<string, Promise<DeviceSignInOutcome>>()
67
25
  export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials => {
68
26
  const env = opts.env ?? process.env
69
27
  const notify = (message: string): void => opts.onNotify?.(message)
70
- const credentialsPath = resolveEnvFile(env)
71
- const lockPath = lockPathFor(credentialsPath)
28
+ const credentialsPath = envFileHelper.resolveEnvFile(env)
29
+ const lock = makeSignInLockHelper(lockPathFor(credentialsPath))
72
30
 
73
31
  const token = async (): Promise<string | null> => {
74
32
  const envValue = env[opts.tokenEnvKey]
75
33
  if (envValue != null && envValue !== '') return envValue
76
34
 
77
- const file = await readCredentialsFile(env)
35
+ const file = await envFileHelper.readCredentialsFile(env)
78
36
  const boundUrl = file[opts.apiUrlEnvKey]
79
37
  if (boundUrl != null && boundUrl !== '' && boundUrl !== opts.apiUrl) return null
80
38
 
@@ -86,12 +44,12 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
86
44
  /** Start a fresh device authorization, or adopt another live process's own — either way, claim
87
45
  * or join the lock BEFORE requesting one, so the decision and the request agree. */
88
46
  const claimJoinOrStart = async (server: AuthorizationServerMetadata): Promise<{ owner: boolean, info: SignInLockInfo }> => {
89
- const authorization = await requestDeviceAuthorization(server, {
47
+ const authorization = await oauthClientHelper.requestDeviceAuthorization(server, {
90
48
  client_id: opts.clientId, scope: opts.scope, resource: opts.resource ?? opts.apiUrl,
91
49
  device_name: opts.deviceName ?? defaultDeviceName(),
92
50
  })
93
51
 
94
- return await claimOrJoinLock(lockPath, opts.apiUrl, {
52
+ return await lock.claimOrJoinLock(opts.apiUrl, {
95
53
  verificationUri: authorization.verification_uri,
96
54
  verificationUriComplete: authorization.verification_uri_complete,
97
55
  userCode: authorization.user_code,
@@ -112,7 +70,7 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
112
70
  if (existing != null) return existing
113
71
 
114
72
  const promise = (async (): Promise<DeviceSignInOutcome> => {
115
- const server = await discoverAuthorizationServer(opts.apiUrl)
73
+ const server = await oauthClientHelper.discoverAuthorizationServer(opts.apiUrl)
116
74
  const claim = await claimJoinOrStart(server)
117
75
 
118
76
  notify(
@@ -128,19 +86,19 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
128
86
  }
129
87
 
130
88
  try {
131
- const outcome = await pollDeviceToken(server, {
89
+ const outcome = await oauthClientHelper.pollDeviceToken(server, {
132
90
  clientId: opts.clientId, deviceCode: claim.info.deviceCode, interval: claim.info.interval,
133
91
  expiresAt: claim.info.expiresAt,
134
92
  })
135
93
  if (outcome.status === 'authorized') {
136
- await setEnvValues(credentialsPath, { [opts.tokenEnvKey]: outcome.token, [opts.apiUrlEnvKey]: opts.apiUrl })
94
+ await envFileHelper.setEnvValues(credentialsPath, { [opts.tokenEnvKey]: outcome.token, [opts.apiUrlEnvKey]: opts.apiUrl })
137
95
  notify('Signed in.')
138
96
  }
139
97
 
140
98
  return outcome
141
99
  } finally {
142
100
  inFlightByApiUrl.delete(opts.apiUrl)
143
- if (claim.owner) await releaseLock(lockPath, claim.info.nonce)
101
+ if (claim.owner) await lock.releaseLock(claim.info.nonce)
144
102
  }
145
103
  })()
146
104
  inFlightByApiUrl.set(opts.apiUrl, promise)
@@ -170,9 +128,9 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
170
128
  ]).finally(() => clearTimeout(ceiling))
171
129
 
172
130
  if (!raced.settled) {
173
- const lock = await readLock(lockPath)
131
+ const pending = await lock.readLock()
174
132
  throw signInRequired({
175
- url: lock?.verificationUri ?? opts.apiUrl, code: lock?.userCode, expiresAt: lock?.expiresAt,
133
+ url: pending?.verificationUri ?? opts.apiUrl, code: pending?.userCode, expiresAt: pending?.expiresAt,
176
134
  })
177
135
  }
178
136
 
@@ -189,9 +147,9 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
189
147
  },
190
148
 
191
149
  invalidate: async (rejectedToken: string): Promise<void> => {
192
- const file = await readCredentialsFile(env)
150
+ const file = await envFileHelper.readCredentialsFile(env)
193
151
  if (file[opts.tokenEnvKey] === rejectedToken) {
194
- await setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
152
+ await envFileHelper.setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
195
153
  notify('The stored token was refused. Signing in again.')
196
154
 
197
155
  return
@@ -205,11 +163,11 @@ export const makeCliCredentials = (opts: CliCredentialsOptions): CliCredentials
205
163
  const current = await token()
206
164
  if (current == null) return
207
165
 
208
- const server = await discoverAuthorizationServer(opts.apiUrl).catch(() => null)
166
+ const server = await oauthClientHelper.discoverAuthorizationServer(opts.apiUrl).catch(() => null)
209
167
  if (server != null) {
210
- await revokeToken(server, { token: current, clientId: opts.clientId }).catch(() => undefined)
168
+ await oauthClientHelper.revokeToken(server, { token: current, clientId: opts.clientId }).catch(() => undefined)
211
169
  }
212
- await setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
170
+ await envFileHelper.setEnvValues(credentialsPath, { [opts.tokenEnvKey]: undefined })
213
171
  },
214
172
  }
215
173
  }
package/src/index.ts CHANGED
@@ -1,5 +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'
6
+ export type * from './types.js'
4
7
  export * from './open-browser.js'
5
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
+ }
package/src/lock.ts CHANGED
@@ -1,77 +1,49 @@
1
1
  import { randomBytes } from 'node:crypto'
2
2
  import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
3
3
  import { dirname } from 'node:path'
4
-
5
- /**
6
- * What one process tells every other one about the sign-in it is driving — the browser URL and
7
- * code so a SECOND process can show the same "waiting on…" state instead of opening a second
8
- * browser tab for the same API URL.
9
- */
10
- export interface SignInLockInfo {
11
- pid: number
12
- apiUrl: string
13
- verificationUri: string
14
- verificationUriComplete?: string
15
- userCode?: string
16
- /** The device flow's own secret — protected the same way the eventual access token is (mode
17
- * `0600`, same directory as the credentials file), so a joining process can poll the SAME
18
- * pending authorization instead of requesting a second one nobody will ever display. */
19
- deviceCode: string
20
- interval: number
21
- expiresAt: number
22
- /** Proves ownership at release time — a process only clears the lock it itself wrote. */
23
- nonce: string
24
- }
4
+ import type { SignInLockInfo } from './types.js'
5
+ import type { SignInLockClaim, SignInLockDraft, SignInLockHelper } from './lock/types.js'
25
6
 
26
7
  export const lockPathFor = (credentialsPath: string): string => `${credentialsPath}.lock`
27
8
 
28
- export const readLock = async (path: string): Promise<SignInLockInfo | null> => {
29
- try {
30
- return JSON.parse(await readFile(path, 'utf-8')) as SignInLockInfo
31
- } catch {
32
- return null
9
+ export const makeSignInLockHelper = (path: string): SignInLockHelper => {
10
+ const readLock = async (): Promise<SignInLockInfo | null> => {
11
+ try {
12
+ return JSON.parse(await readFile(path, 'utf-8')) as SignInLockInfo
13
+ } catch {
14
+ return null
15
+ }
33
16
  }
34
- }
35
17
 
36
- const isAlive = (pid: number): boolean => {
37
- try {
38
- process.kill(pid, 0)
18
+ const isAlive = (pid: number): boolean => {
19
+ try {
20
+ process.kill(pid, 0)
39
21
 
40
- return true
41
- } catch {
42
- return false
22
+ return true
23
+ } catch {
24
+ return false
25
+ }
43
26
  }
44
- }
45
27
 
46
- /**
47
- * Become the one process driving this API URL's sign-in, or find out somebody else already is.
48
- *
49
- * Best-effort, not a mutual-exclusion guarantee: two processes racing this at the exact same
50
- * instant can both conclude they are the owner, and each then drives its own independent device
51
- * authorization. That costs an extra browser tab, never a corrupted file or a double-spent code —
52
- * this is a convenience for the ordinary case (a person running two terminal tabs), not a
53
- * correctness boundary.
54
- */
55
- export const claimOrJoinLock = async (
56
- path: string, apiUrl: string, info: Omit<SignInLockInfo, 'pid' | 'nonce' | 'apiUrl'>
57
- ): Promise<{ owner: boolean, info: SignInLockInfo }> => {
58
- const existing = await readLock(path)
59
- if (existing != null && existing.apiUrl === apiUrl && existing.expiresAt > Date.now() && isAlive(existing.pid)) {
60
- return { owner: false, info: existing }
61
- }
28
+ const claimOrJoinLock = async (apiUrl: string, info: SignInLockDraft): Promise<SignInLockClaim> => {
29
+ const existing = await readLock()
30
+ if (existing != null && existing.apiUrl === apiUrl && existing.expiresAt > Date.now() && isAlive(existing.pid)) {
31
+ return { owner: false, info: existing }
32
+ }
62
33
 
63
- const mine: SignInLockInfo = { ...info, apiUrl, pid: process.pid, nonce: randomBytes(8).toString('hex') }
64
- await mkdir(dirname(path), { recursive: true })
65
- await writeFile(path, JSON.stringify(mine), { mode: 0o600 })
34
+ const mine: SignInLockInfo = { ...info, apiUrl, pid: process.pid, nonce: randomBytes(8).toString('hex') }
35
+ await mkdir(dirname(path), { recursive: true })
36
+ await writeFile(path, JSON.stringify(mine), { mode: 0o600 })
66
37
 
67
- return { owner: true, info: mine }
68
- }
38
+ return { owner: true, info: mine }
39
+ }
69
40
 
70
- /** Clear the lock, but only the copy of it this process itself wrote — a stale read after
71
- * somebody else has already reclaimed the same path must never delete THEIR lock instead. */
72
- export const releaseLock = async (path: string, nonce: string): Promise<void> => {
73
- const existing = await readLock(path)
74
- if (existing?.nonce === nonce) {
75
- await unlink(path).catch(() => undefined)
41
+ const releaseLock = async (nonce: string): Promise<void> => {
42
+ const existing = await readLock()
43
+ if (existing?.nonce === nonce) {
44
+ await unlink(path).catch(() => undefined)
45
+ }
76
46
  }
47
+
48
+ return { readLock, claimOrJoinLock, releaseLock }
77
49
  }
@@ -1,10 +1,5 @@
1
1
  import { spawn } from 'node:child_process'
2
-
3
- const COMMAND_BY_PLATFORM: Record<string, string> = {
4
- darwin: 'open',
5
- win32: 'start',
6
- linux: 'xdg-open',
7
- }
2
+ import { COMMAND_BY_PLATFORM } from './consts.local.js'
8
3
 
9
4
  /**
10
5
  * Best-effort: open `url` in the person's default browser. `false` on any failure — a CLI whose
package/src/types.ts ADDED
@@ -0,0 +1,58 @@
1
+ export interface CliCredentialsOptions {
2
+ /** The API origin this credential set is for, and the OAuth `resource` it is scoped to unless
3
+ * `resource` says otherwise. */
4
+ apiUrl: string
5
+ /** This CLI's OAuth `client_id` — a static one the authorization server declared, or an https
6
+ * Client ID Metadata Document URL. */
7
+ clientId: string
8
+ deviceName?: string
9
+ resource?: string
10
+ scope?: string
11
+ /** Which key in `~/.owlmeans` (and the environment) carries the token. */
12
+ tokenEnvKey: string
13
+ /** Which key records the URL a stored token belongs to. A file naming no URL at all is treated
14
+ * as belonging to whichever `apiUrl` is asked for — only an explicit MISMATCH refuses it. */
15
+ apiUrlEnvKey: string
16
+ env?: NodeJS.ProcessEnv
17
+ /** Best-effort progress — "open this URL and enter this code", "signed in", a failure. A host
18
+ * wires this to stderr, an MCP `notifications/message`, or nothing at all. */
19
+ onNotify?: (message: string) => void
20
+ }
21
+
22
+ export interface CliCredentials {
23
+ /** The token this call site should use right now: the environment, then the bound file value,
24
+ * or `null` when neither has one. */
25
+ token: () => Promise<string | null>
26
+ /** Ensure a usable token exists. Starts or joins a device sign-in when there is none, waits up
27
+ * to `waitMs` for it to be approved, and returns the token. The sign-in keeps running in the
28
+ * background past that wait — a later `require()` call picks up wherever it left off, rather
29
+ * than starting over. */
30
+ require: (waitMs?: number) => Promise<string>
31
+ /** A 401 happened while presenting `rejectedToken`. A token that came from the FILE is forgotten
32
+ * so the next `require()` signs in again; a token that came from the ENVIRONMENT is reported —
33
+ * silently trying another identity behind an operator's back is worse than failing loudly. */
34
+ invalidate: (rejectedToken: string) => Promise<void>
35
+ /** Revoke the current token at the server and remove it from the file. */
36
+ signOut: () => Promise<void>
37
+ }
38
+
39
+ /**
40
+ * What one process tells every other one about the sign-in it is driving — the browser URL and
41
+ * code so a SECOND process can show the same "waiting on…" state instead of opening a second
42
+ * browser tab for the same API URL.
43
+ */
44
+ export interface SignInLockInfo {
45
+ pid: number
46
+ apiUrl: string
47
+ verificationUri: string
48
+ verificationUriComplete?: string
49
+ userCode?: string
50
+ /** The device flow's own secret — protected the same way the eventual access token is (mode
51
+ * `0600`, same directory as the credentials file), so a joining process can poll the SAME
52
+ * pending authorization instead of requesting a second one nobody will ever display. */
53
+ deviceCode: string
54
+ interval: number
55
+ expiresAt: number
56
+ /** Proves ownership at release time — a process only clears the lock it itself wrote. */
57
+ nonce: string
58
+ }