stack/packages/stack-cli/src/lib/auth.ts
2026-04-22 18:58:27 -07:00

104 lines
2.7 KiB
TypeScript

import { readConfigValue } from "./config.js";
import { AuthError } from "./errors.js";
export const DEFAULT_API_URL = "https://api.stack-auth.com";
export const DEFAULT_DASHBOARD_URL = "https://app.stack-auth.com";
export const DEFAULT_PUBLISHABLE_CLIENT_KEY = process.env.STACK_CLI_PUBLISHABLE_CLIENT_KEY ?? "pck_9bbqvqsbh0gdb6smk11d71qg4ktc4rz8ya7cc69yndm7g";
type Flags = {
projectId?: string,
};
export type LoginConfig = {
apiUrl: string,
dashboardUrl: string,
};
export type SessionAuth = LoginConfig & {
refreshToken: string,
};
export type ProjectAuthWithRefreshToken = SessionAuth & {
projectId: string,
};
export type ProjectAuthWithSecretServerKey = LoginConfig & {
projectId: string,
secretServerKey: string,
};
export type ProjectAuth = (ProjectAuthWithRefreshToken | ProjectAuthWithSecretServerKey) & {
projectId: string,
};
function resolveApiUrl(): string {
return process.env.STACK_API_URL
?? readConfigValue("STACK_API_URL")
?? DEFAULT_API_URL;
}
function resolveDashboardUrl(): string {
return process.env.STACK_DASHBOARD_URL
?? readConfigValue("STACK_DASHBOARD_URL")
?? DEFAULT_DASHBOARD_URL;
}
function resolveRefreshToken(): string {
const token = process.env.STACK_CLI_REFRESH_TOKEN
?? readConfigValue("STACK_CLI_REFRESH_TOKEN");
if (!token) {
throw new AuthError("Not logged in. Run `stack login` first.");
}
return token;
}
function resolveSecretServerKey(): string | null {
return process.env.STACK_SECRET_SERVER_KEY ?? null;
}
function resolveProjectId(flags: Flags): string {
const projectId = flags.projectId ?? process.env.STACK_PROJECT_ID;
if (!projectId) {
throw new AuthError("No project ID specified. Use --project-id or set STACK_PROJECT_ID.");
}
return projectId;
}
export function resolveLoginConfig(flags: Flags): LoginConfig {
return {
apiUrl: resolveApiUrl(),
dashboardUrl: resolveDashboardUrl(),
};
}
export function resolveSessionAuth(flags: Flags): SessionAuth {
return {
...resolveLoginConfig(flags),
refreshToken: resolveRefreshToken(),
};
}
export function resolveAuth(flags: Flags): ProjectAuth {
const secretServerKey = resolveSecretServerKey();
if (secretServerKey) {
return {
...resolveLoginConfig(flags),
projectId: resolveProjectId(flags),
secretServerKey,
};
}
return {
...resolveSessionAuth(flags),
projectId: resolveProjectId(flags),
};
}
export function isProjectAuthWithSecretServerKey(auth: ProjectAuth): auth is ProjectAuthWithSecretServerKey {
return "secretServerKey" in auth;
}
export function isProjectAuthWithRefreshToken(auth: ProjectAuth): auth is ProjectAuthWithRefreshToken {
return "refreshToken" in auth;
}