Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,12 @@
"node": ">=20.18.1"
},
"dependencies": {
"@doist/cli-core": "0.16.1",
"@doist/cli-core": "0.19.0",
"chalk": "5.6.2",
"commander": "14.0.2",
"marked": "18.0.3",
"marked-terminal-renderer": "2.2.0",
"oauth4webapi": "3.8.6",
"open": "10.2.0",
"undici": "7.22.0"
},
Expand Down
98 changes: 79 additions & 19 deletions src/__tests__/api.test.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,34 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('../lib/auth.js', () => ({
getApiToken: async () => 'test-token',
getBaseUrl: async () => 'https://test.outline.com',
const authMocks = vi.hoisted(() => ({
getApiToken: vi.fn(async () => 'test-token'),
getBaseUrl: vi.fn(async () => 'https://test.outline.com'),
proactiveRefresh: vi.fn(async () => undefined),
reactiveRefresh: vi.fn(async () => false),
}))

vi.mock('../lib/auth.js', () => authMocks)

vi.mock('../transport/fetch-with-retry.js', () => ({
fetchWithRetry: vi.fn(),
}))

describe('apiRequest', () => {
beforeEach(() => {
delete process.env.OUTLINE_API_TOKEN
authMocks.getApiToken.mockReset().mockResolvedValue('test-token')
authMocks.getBaseUrl.mockReset().mockResolvedValue('https://test.outline.com')
authMocks.proactiveRefresh.mockReset().mockResolvedValue(undefined)
authMocks.reactiveRefresh.mockReset().mockResolvedValue(false)
})

afterEach(() => {
vi.clearAllMocks()
vi.unstubAllEnvs()
})

it('uses fetchWithRetry for API requests', async () => {
const mockResponse = {
ok: true,
json: async () => ({ data: { id: '123' } }),
}
const mockResponse = { ok: true, json: async () => ({ data: { id: '123' } }) }
const { fetchWithRetry } = await import('../transport/fetch-with-retry.js')
;(fetchWithRetry as ReturnType<typeof vi.fn>).mockResolvedValue(mockResponse)

Expand All @@ -41,10 +51,7 @@ describe('apiRequest', () => {
it('returns data and pagination', async () => {
const mockResponse = {
ok: true,
json: async () => ({
data: [{ id: '1' }],
pagination: { offset: 0, limit: 25 },
}),
json: async () => ({ data: [{ id: '1' }], pagination: { offset: 0, limit: 25 } }),
}
const { fetchWithRetry } = await import('../transport/fetch-with-retry.js')
;(fetchWithRetry as ReturnType<typeof vi.fn>).mockResolvedValue(mockResponse)
Expand All @@ -59,18 +66,15 @@ describe('apiRequest', () => {
it('throws on non-ok response with API message', async () => {
const mockResponse = {
ok: false,
status: 401,
statusText: 'Unauthorized',
json: async () => ({
error: 'auth_required',
message: 'Authentication required',
}),
status: 500,
statusText: 'Internal Server Error',
json: async () => ({ error: 'server_error', message: 'Server exploded' }),
}
const { fetchWithRetry } = await import('../transport/fetch-with-retry.js')
;(fetchWithRetry as ReturnType<typeof vi.fn>).mockResolvedValue(mockResponse)

const { apiRequest } = await import('../lib/api.js')
await expect(apiRequest('auth.info')).rejects.toThrow('Authentication required')
await expect(apiRequest('documents.list')).rejects.toThrow('Server exploded')
})

it('throws generic message when no API error body', async () => {
Expand All @@ -90,4 +94,60 @@ describe('apiRequest', () => {
'API error: 500 Internal Server Error',
)
})

it('force-refreshes and retries once when a managed token gets a 401', async () => {
const { fetchWithRetry } = await import('../transport/fetch-with-retry.js')
const f = fetchWithRetry as ReturnType<typeof vi.fn>
f.mockResolvedValueOnce({
ok: false,
status: 401,
statusText: 'Unauthorized',
json: async () => ({}),
})
f.mockResolvedValueOnce({ ok: true, json: async () => ({ data: { id: 'ok' } }) })
authMocks.reactiveRefresh.mockResolvedValueOnce(true)
authMocks.getApiToken
.mockResolvedValueOnce('stale-token')
.mockResolvedValueOnce('rotated-token')

const { apiRequest } = await import('../lib/api.js')
const result = await apiRequest('documents.info', { id: 'abc' })

expect(result.data).toEqual({ id: 'ok' })
expect(authMocks.reactiveRefresh).toHaveBeenCalledTimes(1)
expect(f).toHaveBeenCalledTimes(2)
const retryHeaders = f.mock.calls[1][0].options.headers as Record<string, string>
expect(retryHeaders.Authorization).toBe('Bearer rotated-token')
})

it('proactively refreshes a managed token and uses the rotated token (no extra store read)', async () => {
const { fetchWithRetry } = await import('../transport/fetch-with-retry.js')
const f = fetchWithRetry as ReturnType<typeof vi.fn>
f.mockResolvedValue({ ok: true, json: async () => ({ data: {} }) })
authMocks.proactiveRefresh.mockResolvedValueOnce('rotated-proactive')

const { apiRequest } = await import('../lib/api.js')
await apiRequest('documents.list')

expect(authMocks.proactiveRefresh).toHaveBeenCalledTimes(1)
// The proactive token is reused — no fallback read of getApiToken.
expect(authMocks.getApiToken).not.toHaveBeenCalled()
const headers = f.mock.calls[0][0].options.headers as Record<string, string>
expect(headers.Authorization).toBe('Bearer rotated-proactive')
})

it('does not refresh when OUTLINE_API_TOKEN is set (unmanaged token)', async () => {
Comment thread
scottlovegrove marked this conversation as resolved.
vi.stubEnv('OUTLINE_API_TOKEN', 'env-tok')
const { fetchWithRetry } = await import('../transport/fetch-with-retry.js')
;(fetchWithRetry as ReturnType<typeof vi.fn>).mockResolvedValue({
ok: true,
json: async () => ({ data: {} }),
})

const { apiRequest } = await import('../lib/api.js')
await apiRequest('documents.list')

expect(authMocks.proactiveRefresh).not.toHaveBeenCalled()
expect(authMocks.reactiveRefresh).not.toHaveBeenCalled()
})
})
5 changes: 5 additions & 0 deletions src/__tests__/auth-command.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ vi.mock('../lib/auth.js', () => ({
getOAuthClientId: async () => undefined,
getActiveTokenSource: async () =>
process.env.OUTLINE_API_TOKEN ? ('env' as const) : ('secure-store' as const),
// status resolves the live token for the selected account via this; echo
// the snapshot token back (no refresh in these command-surface tests).
refreshedTokenForStatus: async (_account: unknown, fallback: string) => fallback,
}))

vi.mock('../lib/api.js', () => ({ apiRequest: vi.fn() }))
Expand Down Expand Up @@ -118,6 +121,8 @@ describe('auth status subcommand', () => {
const program = await buildProgram()
await program.parseAsync(['node', 'ol', 'auth', 'status'])

// status probes auth.info with the (account-scoped) live token resolved
// for the selected account.
expect(apiRequest).toHaveBeenCalledWith(
'auth.info',
{},
Expand Down
Loading
Loading