@owlmeans/cli-auth 0.1.18-rc.14 → 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.
Files changed (50) hide show
  1. package/README.md +1 -1
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/cli-auth/SKILL.md +17 -15
  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 +4 -4
  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/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
+ }
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
2
2
  import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
- import { loadOwlmeansEnv, parseEnv, readCredentialsFile, resolveEnvFile, setEnvValues } from '../src/env-file.js'
5
+ import { envFileHelper } from '../src/env-file.js'
6
6
  import { ENV_CREDENTIALS_FILE } from '../src/consts.js'
7
7
 
8
8
  let dir: string
@@ -12,21 +12,21 @@ afterEach(async () => { await rm(dir, { recursive: true, force: true }) })
12
12
 
13
13
  describe('resolveEnvFile', () => {
14
14
  test('defaults to ~/.owlmeans', () => {
15
- expect(resolveEnvFile({})).toMatch(/\.owlmeans$/)
15
+ expect(envFileHelper.resolveEnvFile({})).toMatch(/\.owlmeans$/)
16
16
  })
17
17
 
18
18
  test('honors OWLMEANS_CREDENTIALS', () => {
19
- expect(resolveEnvFile({ [ENV_CREDENTIALS_FILE]: '/custom/path' })).toBe('/custom/path')
19
+ expect(envFileHelper.resolveEnvFile({ [ENV_CREDENTIALS_FILE]: '/custom/path' })).toBe('/custom/path')
20
20
  })
21
21
 
22
22
  test('ignores an empty override', () => {
23
- expect(resolveEnvFile({ [ENV_CREDENTIALS_FILE]: '' })).toMatch(/\.owlmeans$/)
23
+ expect(envFileHelper.resolveEnvFile({ [ENV_CREDENTIALS_FILE]: '' })).toMatch(/\.owlmeans$/)
24
24
  })
25
25
  })
26
26
 
27
27
  describe('parseEnv', () => {
28
28
  test('reads KEY=VALUE, quotes, comments and export prefixes', () => {
29
- const parsed = parseEnv([
29
+ const parsed = envFileHelper.parseEnv([
30
30
  '# a comment', '', 'FOO=bar', 'export BAZ=qux', 'QUOTED="has spaces"', "SINGLE='also quoted'",
31
31
  ].join('\n'))
32
32
  expect(parsed).toEqual({ FOO: 'bar', BAZ: 'qux', QUOTED: 'has spaces', SINGLE: 'also quoted' })
@@ -36,22 +36,22 @@ describe('parseEnv', () => {
36
36
  describe('loadOwlmeansEnv', () => {
37
37
  test('the environment wins over the file', async () => {
38
38
  const path = join(dir, '.owlmeans')
39
- await setEnvValues(path, { VIABLE_API_TOKEN: 'from-file' })
39
+ await envFileHelper.setEnvValues(path, { VIABLE_API_TOKEN: 'from-file' })
40
40
 
41
- const merged = await loadOwlmeansEnv({ [ENV_CREDENTIALS_FILE]: path, VIABLE_API_TOKEN: 'from-env' })
41
+ const merged = await envFileHelper.loadOwlmeansEnv({ [ENV_CREDENTIALS_FILE]: path, VIABLE_API_TOKEN: 'from-env' })
42
42
  expect(merged.VIABLE_API_TOKEN).toBe('from-env')
43
43
  })
44
44
 
45
45
  test('an empty environment value does not shadow the file', async () => {
46
46
  const path = join(dir, '.owlmeans')
47
- await setEnvValues(path, { VIABLE_API_TOKEN: 'from-file' })
47
+ await envFileHelper.setEnvValues(path, { VIABLE_API_TOKEN: 'from-file' })
48
48
 
49
- const merged = await loadOwlmeansEnv({ [ENV_CREDENTIALS_FILE]: path, VIABLE_API_TOKEN: '' })
49
+ const merged = await envFileHelper.loadOwlmeansEnv({ [ENV_CREDENTIALS_FILE]: path, VIABLE_API_TOKEN: '' })
50
50
  expect(merged.VIABLE_API_TOKEN).toBe('from-file')
51
51
  })
52
52
 
53
53
  test('a missing file is not an error', async () => {
54
- const merged = await loadOwlmeansEnv({ [ENV_CREDENTIALS_FILE]: join(dir, 'nope') })
54
+ const merged = await envFileHelper.loadOwlmeansEnv({ [ENV_CREDENTIALS_FILE]: join(dir, 'nope') })
55
55
  expect(merged.VIABLE_API_TOKEN).toBeUndefined()
56
56
  })
57
57
  })
@@ -59,7 +59,7 @@ describe('loadOwlmeansEnv', () => {
59
59
  describe('setEnvValues', () => {
60
60
  test('creates the file with mode 0600', async () => {
61
61
  const path = join(dir, '.owlmeans')
62
- const result = await setEnvValues(path, { A: '1' })
62
+ const result = await envFileHelper.setEnvValues(path, { A: '1' })
63
63
  expect(result.insecurePermissions).toBe(false)
64
64
 
65
65
  const info = await stat(path)
@@ -70,7 +70,7 @@ describe('setEnvValues', () => {
70
70
  const path = join(dir, '.owlmeans')
71
71
  await Bun.write(path, '# a note\nKEEP=1\nCHANGE=old\n')
72
72
 
73
- await setEnvValues(path, { CHANGE: 'new' })
73
+ await envFileHelper.setEnvValues(path, { CHANGE: 'new' })
74
74
  const content = await readFile(path, 'utf-8')
75
75
  expect(content).toContain('# a note')
76
76
  expect(content).toContain('KEEP=1')
@@ -81,26 +81,26 @@ describe('setEnvValues', () => {
81
81
  test('appends a key that was not there before', async () => {
82
82
  const path = join(dir, '.owlmeans')
83
83
  await Bun.write(path, 'A=1\n')
84
- await setEnvValues(path, { B: '2' })
84
+ await envFileHelper.setEnvValues(path, { B: '2' })
85
85
 
86
- const parsed = await readCredentialsFile({ [ENV_CREDENTIALS_FILE]: path })
86
+ const parsed = await envFileHelper.readCredentialsFile({ [ENV_CREDENTIALS_FILE]: path })
87
87
  expect(parsed).toEqual({ A: '1', B: '2' })
88
88
  })
89
89
 
90
90
  test('an undefined value removes the key rather than writing it', async () => {
91
91
  const path = join(dir, '.owlmeans')
92
92
  await Bun.write(path, 'A=1\nB=2\n')
93
- await setEnvValues(path, { A: undefined })
93
+ await envFileHelper.setEnvValues(path, { A: undefined })
94
94
 
95
- const parsed = await readCredentialsFile({ [ENV_CREDENTIALS_FILE]: path })
95
+ const parsed = await envFileHelper.readCredentialsFile({ [ENV_CREDENTIALS_FILE]: path })
96
96
  expect(parsed).toEqual({ B: '2' })
97
97
  })
98
98
 
99
99
  test('a concurrent rewrite never leaves a half-written file — the temp file lands atomically', async () => {
100
100
  const path = join(dir, '.owlmeans')
101
101
  await Promise.all([
102
- setEnvValues(path, { A: '1' }),
103
- setEnvValues(path, { B: '2' }),
102
+ envFileHelper.setEnvValues(path, { A: '1' }),
103
+ envFileHelper.setEnvValues(path, { B: '2' }),
104
104
  ])
105
105
  // Whichever write landed last, the file must be one complete, parseable write — never a
106
106
  // truncated interleaving of the two.
@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
5
  import { makeCliCredentials } from '../src/holder.js'
6
- import { readCredentialsFile } from '../src/env-file.js'
6
+ import { envFileHelper } from '../src/env-file.js'
7
7
  import { ENV_CREDENTIALS_FILE } from '../src/consts.js'
8
8
 
9
9
  const originalFetch = globalThis.fetch
@@ -100,16 +100,14 @@ describe('token()', () => {
100
100
  })
101
101
 
102
102
  test('refuses a file token bound to a different API URL', async () => {
103
- const { setEnvValues } = await import('../src/env-file.js')
104
- await setEnvValues(credentialsPath, { VIABLE_API_TOKEN: 'vib_other', VIABLE_API_URL: 'https://other.example.com' })
103
+ await envFileHelper.setEnvValues(credentialsPath, { VIABLE_API_TOKEN: 'vib_other', VIABLE_API_URL: 'https://other.example.com' })
105
104
 
106
105
  const credentials = makeCliCredentials(opts())
107
106
  expect(await credentials.token()).toBeNull()
108
107
  })
109
108
 
110
109
  test('accepts a file token when no URL was ever recorded', async () => {
111
- const { setEnvValues } = await import('../src/env-file.js')
112
- await setEnvValues(credentialsPath, { VIABLE_API_TOKEN: 'vib_no-url-recorded' })
110
+ await envFileHelper.setEnvValues(credentialsPath, { VIABLE_API_TOKEN: 'vib_no-url-recorded' })
113
111
 
114
112
  const credentials = makeCliCredentials(opts())
115
113
  expect(await credentials.token()).toBe('vib_no-url-recorded')
@@ -154,7 +152,7 @@ describe('require()', () => {
154
152
  expect(notifications.some(m => m.includes('CODE-1'))).toBe(true)
155
153
  expect(notifications).toContain('Signed in.')
156
154
 
157
- const file = await readCredentialsFile({ [ENV_CREDENTIALS_FILE]: credentialsPath })
155
+ const file = await envFileHelper.readCredentialsFile({ [ENV_CREDENTIALS_FILE]: credentialsPath })
158
156
  expect(file.VIABLE_API_TOKEN).toBe('vib_new-token')
159
157
  expect(file.VIABLE_API_URL).toBe(ISSUER)
160
158
  })
@@ -2,14 +2,17 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
2
2
  import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
3
3
  import { tmpdir } from 'node:os'
4
4
  import { join } from 'node:path'
5
- import { claimOrJoinLock, readLock, releaseLock } from '../src/lock.js'
5
+ import { makeSignInLockHelper } from '../src/lock.js'
6
+ import type { SignInLockHelper } from '../src/lock/types.js'
6
7
 
7
8
  let dir: string
8
9
  let path: string
10
+ let lock: SignInLockHelper
9
11
 
10
12
  beforeEach(async () => {
11
13
  dir = await mkdtemp(join(tmpdir(), 'cli-auth-lock-'))
12
14
  path = join(dir, '.owlmeans.lock')
15
+ lock = makeSignInLockHelper(path)
13
16
  })
14
17
  afterEach(async () => { await rm(dir, { recursive: true, force: true }) })
15
18
 
@@ -20,33 +23,33 @@ const info = (overrides: Record<string, unknown> = {}) => ({
20
23
 
21
24
  describe('claimOrJoinLock', () => {
22
25
  test('claims an absent lock', async () => {
23
- const claim = await claimOrJoinLock(path, 'https://api.example.com', info())
26
+ const claim = await lock.claimOrJoinLock('https://api.example.com', info())
24
27
  expect(claim.owner).toBe(true)
25
28
  expect(claim.info.apiUrl).toBe('https://api.example.com')
26
29
  expect(claim.info.pid).toBe(process.pid)
27
30
 
28
- expect(await readLock(path)).toEqual(claim.info)
31
+ expect(await lock.readLock()).toEqual(claim.info)
29
32
  })
30
33
 
31
34
  test('joins a live lock for the same API URL instead of overwriting it', async () => {
32
- const first = await claimOrJoinLock(path, 'https://api.example.com', info({ userCode: 'FIRST-CODE' }))
35
+ const first = await lock.claimOrJoinLock('https://api.example.com', info({ userCode: 'FIRST-CODE' }))
33
36
  expect(first.owner).toBe(true)
34
37
 
35
- const second = await claimOrJoinLock(path, 'https://api.example.com', info({ userCode: 'SECOND-CODE' }))
38
+ const second = await lock.claimOrJoinLock('https://api.example.com', info({ userCode: 'SECOND-CODE' }))
36
39
  expect(second.owner).toBe(false)
37
40
  expect(second.info.userCode).toBe('FIRST-CODE')
38
41
  })
39
42
 
40
43
  test('reclaims a lock for a different API URL', async () => {
41
- await claimOrJoinLock(path, 'https://one.example.com', info())
42
- const claim = await claimOrJoinLock(path, 'https://two.example.com', info())
44
+ await lock.claimOrJoinLock('https://one.example.com', info())
45
+ const claim = await lock.claimOrJoinLock('https://two.example.com', info())
43
46
  expect(claim.owner).toBe(true)
44
47
  expect(claim.info.apiUrl).toBe('https://two.example.com')
45
48
  })
46
49
 
47
50
  test('reclaims an expired lock', async () => {
48
- await claimOrJoinLock(path, 'https://api.example.com', info({ expiresAt: Date.now() - 1 }))
49
- const claim = await claimOrJoinLock(path, 'https://api.example.com', info())
51
+ await lock.claimOrJoinLock('https://api.example.com', info({ expiresAt: Date.now() - 1 }))
52
+ const claim = await lock.claimOrJoinLock('https://api.example.com', info())
50
53
  expect(claim.owner).toBe(true)
51
54
  })
52
55
 
@@ -55,31 +58,31 @@ describe('claimOrJoinLock', () => {
55
58
  await writeFile(path, JSON.stringify({
56
59
  ...info(), apiUrl: 'https://api.example.com', pid: 999_999, nonce: 'stale',
57
60
  }))
58
- const claim = await claimOrJoinLock(path, 'https://api.example.com', info())
61
+ const claim = await lock.claimOrJoinLock('https://api.example.com', info())
59
62
  expect(claim.owner).toBe(true)
60
63
  })
61
64
  })
62
65
 
63
66
  describe('releaseLock', () => {
64
67
  test('removes only the lock this process itself wrote', async () => {
65
- const claim = await claimOrJoinLock(path, 'https://api.example.com', info())
66
- await releaseLock(path, claim.info.nonce)
67
- expect(await readLock(path)).toBeNull()
68
+ const claim = await lock.claimOrJoinLock('https://api.example.com', info())
69
+ await lock.releaseLock(claim.info.nonce)
70
+ expect(await lock.readLock()).toBeNull()
68
71
  })
69
72
 
70
73
  test('never removes a lock somebody else has since claimed', async () => {
71
- const first = await claimOrJoinLock(path, 'https://one.example.com', info())
72
- await claimOrJoinLock(path, 'https://two.example.com', info()) // reclaims the path, new nonce
74
+ const first = await lock.claimOrJoinLock('https://one.example.com', info())
75
+ await lock.claimOrJoinLock('https://two.example.com', info()) // reclaims the path, new nonce
73
76
 
74
- await releaseLock(path, first.info.nonce)
75
- expect((await readLock(path))?.apiUrl).toBe('https://two.example.com')
77
+ await lock.releaseLock(first.info.nonce)
78
+ expect((await lock.readLock())?.apiUrl).toBe('https://two.example.com')
76
79
  })
77
80
  })
78
81
 
79
82
  describe('readLock', () => {
80
83
  test('answers null for a missing or malformed file', async () => {
81
- expect(await readLock(path)).toBeNull()
84
+ expect(await lock.readLock()).toBeNull()
82
85
  await writeFile(path, 'not json')
83
- expect(await readLock(path)).toBeNull()
86
+ expect(await lock.readLock()).toBeNull()
84
87
  })
85
88
  })