-
Notifications
You must be signed in to change notification settings - Fork 0
refactor: call credits endpoint for key validation #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Turanic
merged 3 commits into
main
from
ada/refactor/callCreditsEndpointForKeyValidation
Jun 5, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import { CREDITS_URL, verifyApiKey } from '../credits'; | ||
|
|
||
| function mockFetchResponse(response: Partial<Response> & { json?: () => Promise<unknown> }): void { | ||
| jest.spyOn(globalThis, 'fetch').mockResolvedValue(response as Response); | ||
| } | ||
|
|
||
| describe('verifyApiKey', () => { | ||
| afterEach(() => { | ||
| jest.restoreAllMocks(); | ||
| }); | ||
|
|
||
| it('returns the credit balance when verification succeeds', async () => { | ||
| mockFetchResponse({ | ||
| json: async () => ({ balance: 123.456 }), | ||
| ok: true, | ||
| status: 200, | ||
| statusText: 'OK', | ||
| }); | ||
|
|
||
| await expect(verifyApiKey('test-api-key')).resolves.toEqual({ | ||
| balance: 123.456, | ||
| ok: true, | ||
| }); | ||
| expect(globalThis.fetch).toHaveBeenCalledWith(CREDITS_URL, { | ||
| headers: { | ||
| Authorization: 'Bearer test-api-key', | ||
| }, | ||
| }); | ||
| }); | ||
|
|
||
| it('returns invalid when the API rejects the key', async () => { | ||
| mockFetchResponse({ | ||
| ok: false, | ||
| status: 401, | ||
| statusText: 'Unauthorized', | ||
| }); | ||
|
|
||
| await expect(verifyApiKey('bad-key')).resolves.toEqual({ | ||
| ok: false, | ||
| reason: 'invalid', | ||
| status: 401, | ||
| }); | ||
| }); | ||
|
|
||
| it('returns network when fetch throws', async () => { | ||
| jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('network down')); | ||
|
|
||
| await expect(verifyApiKey('test-api-key')).resolves.toEqual({ | ||
| message: 'network down', | ||
| ok: false, | ||
| reason: 'network', | ||
| }); | ||
| }); | ||
| }); |
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,7 +12,7 @@ import { dirname, join } from 'node:path'; | |
|
|
||
| const CONFIG_DIR_NAME = '.linkup'; | ||
| const KEY_PREFIX = 'api_key='; | ||
| const MIN_API_KEY_LENGTH = 10; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remark: This length is now only used to print a masked api key. No normalisation is needed anymore, as the credits endpoint perform all the validation. |
||
| const MASKED_API_KEY_MIN_LENGTH = 10; | ||
|
|
||
| export type ConfigSource = 'env' | 'file' | 'none'; | ||
|
|
||
|
|
@@ -23,7 +23,7 @@ export type ResolvedConfig = { | |
| configPath: string; | ||
| }; | ||
|
|
||
| export function getConfigDir(): string { | ||
| function getConfigDir(): string { | ||
| return join(homedir(), CONFIG_DIR_NAME); | ||
| } | ||
|
|
||
|
|
@@ -88,25 +88,7 @@ export function getApiKey(configPath: string = getConfigPath()): string | null { | |
| return resolveConfig(configPath).apiKey; | ||
| } | ||
|
|
||
| export function validateApiKey(apiKey: string): string | null { | ||
| const normalized = apiKey.trim(); | ||
| if (!normalized || normalized.length < MIN_API_KEY_LENGTH || /[\r\n]/.test(apiKey)) { | ||
| return `Invalid API key: must be at least ${MIN_API_KEY_LENGTH} characters and single-line.`; | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| function normalizeApiKeyForSave(apiKey: string): string { | ||
| const validationError = validateApiKey(apiKey); | ||
| if (validationError) { | ||
| throw new Error(validationError); | ||
| } | ||
| return apiKey.trim(); | ||
| } | ||
|
|
||
| export function saveApiKey(apiKey: string, configPath: string = getConfigPath()): void { | ||
| const normalizedApiKey = normalizeApiKeyForSave(apiKey); | ||
|
|
||
| const dirMode = 0o700; | ||
| const fileMode = 0o600; | ||
| const dir = dirname(configPath); | ||
|
|
@@ -115,7 +97,7 @@ export function saveApiKey(apiKey: string, configPath: string = getConfigPath()) | |
|
|
||
| const tmpPath = `${configPath}.tmp`; | ||
| try { | ||
| writeFileSync(tmpPath, `${KEY_PREFIX}${normalizedApiKey}\n`, { | ||
| writeFileSync(tmpPath, `${KEY_PREFIX}${apiKey.trim()}\n`, { | ||
| encoding: 'utf8', | ||
| mode: fileMode, | ||
| }); | ||
|
|
@@ -148,5 +130,5 @@ export function maskApiKey(key: string): string { | |
| if (key.length > minLength) { | ||
| return `${key.slice(0, prefixLength)}...${key.slice(-suffixLength)}`; | ||
| } | ||
| return '*'.repeat(Math.max(key.length, MIN_API_KEY_LENGTH)); | ||
| return '*'.repeat(Math.max(key.length, MASKED_API_KEY_MIN_LENGTH)); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| export const CREDITS_URL = 'https://api.linkup.so/v1/credits/balance'; | ||
|
|
||
| type VerifyApiKeyResult = | ||
| | { ok: true; balance: number } | ||
| | { ok: false; reason: 'invalid'; status: number } | ||
| | { ok: false; reason: 'network'; message: string }; | ||
|
|
||
| function formatNetworkError(error: unknown): string { | ||
| return error instanceof Error ? error.message : String(error); | ||
| } | ||
|
|
||
| function readBalance(data: unknown): number { | ||
| if ( | ||
| typeof data === 'object' && | ||
| data !== null && | ||
| 'balance' in data && | ||
| typeof data.balance === 'number' | ||
| ) { | ||
| return data.balance; | ||
| } | ||
|
|
||
| throw new Error('Credits endpoint returned an invalid response'); | ||
| } | ||
|
|
||
| export async function verifyApiKey(apiKey: string): Promise<VerifyApiKeyResult> { | ||
| try { | ||
| const response = await fetch(CREDITS_URL, { | ||
| headers: { | ||
| Authorization: `Bearer ${apiKey}`, | ||
| }, | ||
| }); | ||
|
|
||
| if (response.ok) { | ||
| return { balance: readBalance(await response.json()), ok: true }; | ||
| } | ||
|
|
||
| if (response.status === 401 || response.status === 403) { | ||
| return { ok: false, reason: 'invalid', status: response.status }; | ||
| } | ||
|
|
||
| return { | ||
| message: `Credits endpoint returned ${response.status} ${response.statusText}`, | ||
| ok: false, | ||
| reason: 'network', | ||
| }; | ||
| } catch (error) { | ||
| return { | ||
| message: formatNetworkError(error), | ||
| ok: false, | ||
| reason: 'network', | ||
| }; | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remark: Those checks are not needed anymore as the api key is now fully validated from the credits endpoint. See the new tests in credits.test.ts and auth-config.integration.test.ts