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

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/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
+ }
package/src/lock.ts CHANGED
@@ -2,56 +2,48 @@ 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
  import type { SignInLockInfo } from './types.js'
5
+ import type { SignInLockClaim, SignInLockDraft, SignInLockHelper } from './lock/types.js'
5
6
 
6
7
  export const lockPathFor = (credentialsPath: string): string => `${credentialsPath}.lock`
7
8
 
8
- export const readLock = async (path: string): Promise<SignInLockInfo | null> => {
9
- try {
10
- return JSON.parse(await readFile(path, 'utf-8')) as SignInLockInfo
11
- } catch {
12
- 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
+ }
13
16
  }
14
- }
15
17
 
16
- const isAlive = (pid: number): boolean => {
17
- try {
18
- process.kill(pid, 0)
18
+ const isAlive = (pid: number): boolean => {
19
+ try {
20
+ process.kill(pid, 0)
19
21
 
20
- return true
21
- } catch {
22
- return false
22
+ return true
23
+ } catch {
24
+ return false
25
+ }
23
26
  }
24
- }
25
27
 
26
- /**
27
- * Become the one process driving this API URL's sign-in, or find out somebody else already is.
28
- *
29
- * Best-effort, not a mutual-exclusion guarantee: two processes racing this at the exact same
30
- * instant can both conclude they are the owner, and each then drives its own independent device
31
- * authorization. That costs an extra browser tab, never a corrupted file or a double-spent code —
32
- * this is a convenience for the ordinary case (a person running two terminal tabs), not a
33
- * correctness boundary.
34
- */
35
- export const claimOrJoinLock = async (
36
- path: string, apiUrl: string, info: Omit<SignInLockInfo, 'pid' | 'nonce' | 'apiUrl'>
37
- ): Promise<{ owner: boolean, info: SignInLockInfo }> => {
38
- const existing = await readLock(path)
39
- if (existing != null && existing.apiUrl === apiUrl && existing.expiresAt > Date.now() && isAlive(existing.pid)) {
40
- return { owner: false, info: existing }
41
- }
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
+ }
42
33
 
43
- const mine: SignInLockInfo = { ...info, apiUrl, pid: process.pid, nonce: randomBytes(8).toString('hex') }
44
- await mkdir(dirname(path), { recursive: true })
45
- 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 })
46
37
 
47
- return { owner: true, info: mine }
48
- }
38
+ return { owner: true, info: mine }
39
+ }
49
40
 
50
- /** Clear the lock, but only the copy of it this process itself wrote — a stale read after
51
- * somebody else has already reclaimed the same path must never delete THEIR lock instead. */
52
- export const releaseLock = async (path: string, nonce: string): Promise<void> => {
53
- const existing = await readLock(path)
54
- if (existing?.nonce === nonce) {
55
- 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
+ }
56
46
  }
47
+
48
+ return { readLock, claimOrJoinLock, releaseLock }
57
49
  }
@@ -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
  })