import { existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, } from "node:fs"; import { join } from "node:path"; import type { CredentialInputs } from "@neon-internals/cli-core/auth_selection"; import { writeSecretFile } from "@neon-internals/cli-core/secure_file"; import { getAuthContext } from "../auth_context.js"; import { type Context, readContextFile } from "../context.js"; import { ClaimableClient } from "./api.js"; const FILE_PREFIX = "claimable-credential."; const FILE_SUFFIX = ".json"; const PROJECT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u; export type StoredClaimableCredentials = { version: 1; origin: string; registrationId: string; projectId: string; branchId: string; identityAssertion: string; expiresAt: string; assertionExpires?: number; }; const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); const nonEmptyString = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0; const assertProjectId = (projectId: string): void => { if (!PROJECT_ID.test(projectId)) { throw new Error(`Invalid Claimable Neon project ID "${projectId}".`); } }; export const claimableCredentialsPath = ( configDir: string, projectId: string, ): string => { assertProjectId(projectId); return join(configDir, `${FILE_PREFIX}${projectId}${FILE_SUFFIX}`); }; const parseStoredCredentials = ( value: unknown, path: string, expectedProjectId?: string, ): StoredClaimableCredentials => { if ( !isRecord(value) || value.version !== 1 || !nonEmptyString(value.origin) || !nonEmptyString(value.registrationId) || !nonEmptyString(value.projectId) || !nonEmptyString(value.branchId) || !nonEmptyString(value.identityAssertion) || !nonEmptyString(value.expiresAt) ) { throw new Error( `${path} does not contain a valid Claimable Neon credential. Delete it and run \`neon claim create\` again.`, ); } assertProjectId(value.projectId); if ( expectedProjectId !== undefined && value.projectId !== expectedProjectId ) { throw new Error( `${path} belongs to a different Claimable Neon project. Delete it and run \`neon claim create\` again.`, ); } const assertionExpires = optionalUnixSeconds(value.assertionExpires, path); return { version: 1, origin: value.origin, registrationId: value.registrationId, projectId: value.projectId, branchId: value.branchId, identityAssertion: value.identityAssertion, expiresAt: value.expiresAt, ...(assertionExpires === undefined ? {} : { assertionExpires }), }; }; const optionalUnixSeconds = ( value: unknown, path: string, ): number | undefined => { if (value === undefined) return undefined; if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) { throw new Error( `${path} does not contain a valid Claimable Neon credential. Delete it and run \`neon claim create\` again.`, ); } return value; }; export const assertionHasExpired = ( credentials: StoredClaimableCredentials, now = Date.now(), ): boolean => credentials.assertionExpires !== undefined && credentials.assertionExpires * 1000 <= now; export const writeClaimableCredentials = ( configDir: string, credentials: StoredClaimableCredentials, ): void => { mkdirSync(configDir, { recursive: true }); const path = claimableCredentialsPath(configDir, credentials.projectId); writeSecretFile(path, JSON.stringify(credentials)); }; export const readClaimableCredentials = ( configDir: string, projectId: string, ): StoredClaimableCredentials | null => { const path = claimableCredentialsPath(configDir, projectId); if (!existsSync(path)) return null; let parsed: unknown; try { parsed = JSON.parse(readFileSync(path, "utf8")); } catch { throw new Error( `${path} is not valid JSON, so the Claimable Neon credential cannot be read. Delete it and run \`neon claim create\` again.`, ); } return parseStoredCredentials(parsed, path, projectId); }; export const listClaimableCredentials = ( configDir: string, ): StoredClaimableCredentials[] => { if (!existsSync(configDir)) return []; return readdirSync(configDir) .filter( (name) => name.startsWith(FILE_PREFIX) && name.endsWith(FILE_SUFFIX), ) .sort() .map((name) => { const path = join(configDir, name); let parsed: unknown; try { parsed = JSON.parse(readFileSync(path, "utf8")); } catch { throw new Error( `${path} is not valid JSON, so the Claimable Neon credential cannot be listed. Delete it and run \`neon claim create\` again.`, ); } return parseStoredCredentials(parsed, path); }) .sort((left, right) => left.projectId.localeCompare(right.projectId)); }; export const removeClaimableCredentials = ( configDir: string, projectId: string, ): void => { const path = claimableCredentialsPath(configDir, projectId); try { unlinkSync(path); } catch (error) { if ( isRecord(error) && typeof error.code === "string" && error.code === "ENOENT" ) { return; } throw error; } }; export const readLinkedClaimableCredentials = ( configDir: string, context: Context, ): StoredClaimableCredentials | null => { if (!nonEmptyString(context.projectId)) return null; // A regular `.neon` project id that this regex would reject never had an assertion file. if (!PROJECT_ID.test(context.projectId)) return null; return readClaimableCredentials(configDir, context.projectId); }; export const claimableCredentialsExist = ( configDir: string, projectId: string, ): boolean => { if (!PROJECT_ID.test(projectId)) return false; return existsSync(claimableCredentialsPath(configDir, projectId)); }; export const shouldUseClaimableCredentials = ( inputs: CredentialInputs, profileFlag: string | undefined, context: Context, configDir: string, ): boolean => inputs.apiKeyFlag.trim() === "" && inputs.apiKeyEnv.trim() === "" && inputs.profileEnv.trim() === "" && (profileFlag === undefined || profileFlag.trim() === "") && readLinkedClaimableCredentials(configDir, context) !== null; /** Management API base URL the CLI uses for a Claimable Neon origin. */ export const claimableApiHost = (origin: string): string => `${new ClaimableClient(origin).origin}/v1`; /** * Whether this invocation is talking to Claimable Neon, so env resolve must not * mint credentials or pull services that require claim. * * Auth source wins so a same-process checkout that rewrote `.neon` still skips * minting. A credential file plus a production API host is an account override * and is not claimable. */ export const isClaimableEnvTarget = (props: { apiHost: string; contextFile: string; configDir: string; }): boolean => { const source = getAuthContext()?.source; if (source === "claimable") return true; if (source !== undefined) return false; if (props.configDir.trim() === "") return false; const stored = readLinkedClaimableCredentials( props.configDir, readContextFile(props.contextFile), ); if (stored === null) return false; return ( props.apiHost.trim().replace(/\/+$/, "") === claimableApiHost(stored.origin) ); };