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
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"@prisma/compute-sdk": "^0.19.0",
"c12": "4.0.0-beta.4",
"@prisma/credentials-store": "^7.7.0",
"@prisma/management-api-sdk": "^1.33.1",
"@prisma/management-api-sdk": "^1.34.0",
"colorette": "^2.0.20",
"commander": "^12.1.0",
"magicast": "^0.3.5",
Expand Down
83 changes: 77 additions & 6 deletions packages/cli/src/lib/auth/auth-ops.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { ManagementApiClient } from "@prisma/management-api-sdk";
import { FileTokenStorage } from "../../adapters/token-storage";
import type { AuthStateResult } from "../../types/auth";
import { SERVICE_TOKEN_ENV_VAR } from "./client";
Expand All @@ -10,7 +11,9 @@ function decodeJwtPayload(token: string): Record<string, unknown> {
try {
const payload = token.split(".")[1];
if (!payload) return {};
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as Record<string, unknown>;
return JSON.parse(
Buffer.from(payload, "base64url").toString("utf8"),
) as Record<string, unknown>;
} catch {
return {};
}
Expand Down Expand Up @@ -60,17 +63,35 @@ export async function readAuthState(env: NodeJS.ProcessEnv): Promise<AuthStateRe
provider: null,
user: null,
workspace: null,
credential: null,
};
}

const client = await requireComputeAuth(env);
const currentPrincipal = await readCurrentPrincipalAuthState(client);
if (currentPrincipal) {
return currentPrincipal;
}

const claims = decodeJwtPayload(tokens.accessToken);
return buildAuthState({ workspaceIdFromCredential: tokens.workspaceId, claims, env });
return buildAuthState({
workspaceIdFromCredential: tokens.workspaceId,
claims,
env,
client,
});
}

async function readServiceTokenAuthState(
token: string,
env: NodeJS.ProcessEnv,
): Promise<AuthStateResult> {
const client = await requireComputeAuth(env);
const currentPrincipal = await readCurrentPrincipalAuthState(client);
if (currentPrincipal) {
return currentPrincipal;
}

const claims = decodeJwtPayload(token);
const workspaceId = workspaceIdFromClaims(claims);

Expand All @@ -84,25 +105,33 @@ async function readServiceTokenAuthState(
provider: null,
user: null,
workspace: null,
credential: null,
};
}

return buildAuthState({ workspaceIdFromCredential: workspaceId, claims, env });
return buildAuthState({
workspaceIdFromCredential: workspaceId,
claims,
env,
client,
});
}

async function buildAuthState({
workspaceIdFromCredential,
claims,
env,
client,
}: {
workspaceIdFromCredential: string;
claims: Record<string, unknown>;
env: NodeJS.ProcessEnv;
client?: ManagementApiClient | null;
}): Promise<AuthStateResult> {
let workspaceId = workspaceIdFromCredential;
let workspaceName = workspaceIdFromCredential;

const client = await requireComputeAuth(env);
client ??= await requireComputeAuth(env);

if (client) {
try {
Expand All @@ -111,7 +140,7 @@ async function buildAuthState({
});
// A 401 from the workspace lookup means the credential the caller
// presented is fundamentally invalid (revoked, wrong signing key,
// expired) surface signed-out state instead of returning a
// expired) - surface signed-out state instead of returning a
// workspace shape that makes a broken token look fine. Other
// statuses (404/5xx/network) keep the silent fallback so transient
// lookup failures do not turn `auth whoami` into a hard error.
Expand All @@ -121,6 +150,7 @@ async function buildAuthState({
provider: null,
user: null,
workspace: null,
credential: null,
};
}
if (data?.data?.id) {
Expand All @@ -131,7 +161,7 @@ async function buildAuthState({
workspaceName = data.data.name;
}
} catch {
// fall through use workspaceId as name
// fall through - use workspaceId as name
}
}

Expand All @@ -144,9 +174,50 @@ async function buildAuthState({
id: workspaceId,
name: workspaceName,
},
credential: null,
};
}

async function readCurrentPrincipalAuthState(
client: ManagementApiClient | null,
): Promise<AuthStateResult | null> {
if (!client) return null;

try {
const { data, response } = await client.GET("/v1/me");

if (response?.status === 401) {
return {
authenticated: false,
provider: null,
user: null,
workspace: null,
credential: null,
};
}

const principal = data?.data;
if (!principal) return null;
if (!principal.credential) return null;

return {
authenticated: true,
provider: null,
user: principal.user
? {
id: principal.user.id,
email: principal.user.email,
name: principal.user.name,
}
: null,
workspace: principal.workspace,
credential: principal.credential,
};
} catch {
return null;
}
}

export async function performLogout(env: NodeJS.ProcessEnv): Promise<void> {
await new FileTokenStorage(env).clearTokens();
}
40 changes: 35 additions & 5 deletions packages/cli/src/presenters/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@ export function renderAuthSuccess(
rows.push({ key: "provider", value: providerLabel(result.provider) });
}

if (result.user) {
rows.push({ key: "user", value: result.user.email });
const userLabel = authUserLabel(result);
if (userLabel) {
rows.push({ key: "user", value: userLabel });
}

if (result.workspace?.name) {
Expand Down Expand Up @@ -58,9 +59,13 @@ export function renderAuthSuccess(
fields: result.authenticated
? [
{ key: "status", value: "signed in", tone: "success" as const },
...(result.user ? [{ key: "user", value: result.user.email }] : []),
...(result.provider ? [{ key: "provider", value: providerLabel(result.provider) }] : []),
...(result.workspace?.name ? [{ key: "workspace", value: result.workspace.name }] : []),
...authUserRows(result),
...(result.provider
? [{ key: "provider", value: providerLabel(result.provider) }]
: []),
...(result.workspace?.name
? [{ key: "workspace", value: result.workspace.name }]
: []),
]
: [{ key: "status", value: "signed out", tone: "dim" as const }],
},
Expand All @@ -79,3 +84,28 @@ function providerLabel(provider: AuthProviderId | null): string {

return "";
}

function authUserLabel(result: AuthStateResult): string | null {
return result.user?.email ?? credentialUserLabel(result);
}

function authUserRows(result: AuthStateResult): Parameters<typeof renderShow>[0]["fields"] {
const userLabel = authUserLabel(result);
return userLabel ? [{ key: "user", value: userLabel }] : [];
}

function credentialUserLabel(result: AuthStateResult): string | null {
if (result.credential?.type === "service_token") {
return result.credential.name
? `<service token: ${result.credential.name}>`
: "<service token>";
}

if (result.credential?.type === "management_token") {
return result.credential.name
? `<management token: ${result.credential.name}>`
: "<management token>";
}

return null;
}
9 changes: 9 additions & 0 deletions packages/cli/src/types/auth.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
export type AuthProviderId = "github" | "google";

export interface AuthUser {
id?: string;
email: string;
name?: string | null;
}

export interface AuthWorkspace {
id: string;
name: string;
}

export interface AuthCredential {
type: "oauth" | "service_token" | "management_token";
id: string | null;
name: string | null;
}

export interface AuthStateResult {
authenticated: boolean;
provider: AuthProviderId | null;
user: AuthUser | null;
workspace: AuthWorkspace | null;
credential: AuthCredential | null;
}
9 changes: 9 additions & 0 deletions packages/cli/src/use-cases/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ async function resolveCurrentAuthState(dependencies: AuthUseCaseDependencies): P
provider: null,
user: null,
workspace: null,
credential: null,
};
}

Expand All @@ -110,15 +111,23 @@ async function resolveCurrentAuthState(dependencies: AuthUseCaseDependencies): P
provider: null,
user: null,
workspace: null,
credential: null,
};
}

return {
authenticated: true,
provider: provider.id,
user: {
id: user.id,
email: user.email,
name: user.name,
},
workspace,
credential: {
type: "oauth",
id: null,
name: null,
},
};
}
Loading
Loading