Skip to content
Open
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
16 changes: 14 additions & 2 deletions cli/auth/login/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,22 @@ export const registerAuthLogin = (program: Command) => {
const sessionToken = getSessionToken()
const tscircuitHandle = cliConfig.get("tscircuitHandle")
if (sessionToken) {
const account = await fetchAccount()
const savedHandle = process.env.TSCIRCUIT_TOKEN
? undefined
: tscircuitHandle?.trim() || undefined
const account = savedHandle ? null : await fetchAccount({ sessionToken })
const resolvedHandle =
savedHandle ||
account?.tscircuit_handle?.trim() ||
account?.account_id?.trim()
const accountDisplay = savedHandle
? kleur.bold(`@${savedHandle}`)
: resolvedHandle
? kleur.underline(`@${resolvedHandle}`)
: null
console.log(
kleur.yellow(
`Already logged in as ${tscircuitHandle ? kleur.bold(`@${tscircuitHandle}`) : kleur.underline(`@${account?.tscircuit_handle ?? account?.account_id}`)}! Use ${kleur.cyan("tsci logout")} to switch accounts.`,
`${accountDisplay ? `Already logged in as ${accountDisplay}` : "Already logged in"}! Use ${kleur.cyan("tsci logout")} to switch accounts.`,
),
)
return
Expand Down
26 changes: 20 additions & 6 deletions cli/auth/whoami/register.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Command } from "commander"
import { cliConfig, getSessionToken } from "lib/cli-config"
import { fetchAccount } from "lib/registry-api/fetch-account"
import { type Account, fetchAccount } from "lib/registry-api/fetch-account"
import kleur from "kleur"

const formatDate = (date: string | undefined): string | null => {
Expand All @@ -20,25 +20,39 @@ export const registerAuthWhoami = (program: Command) => {
.command("whoami")
.description("Show information about the current authenticated user")
.action(async () => {
if (!getSessionToken()) {
const sessionToken = getSessionToken()
if (!sessionToken) {
console.log(kleur.yellow("You need to log in to access this."))
return
}

const account = await fetchAccount()
let account: Account | null
try {
account = await fetchAccount({ sessionToken, throwOnError: true })
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error)
console.error(
kleur.red(`Failed to fetch account details: ${errorMessage}`),
)
process.exitCode = 1
return
}

const isEnvToken = Boolean(process.env.TSCIRCUIT_TOKEN)

console.log(kleur.bold().green("\nLogged in user:\n"))
console.log(
` ${kleur.cyan("TscHandle:")} @${kleur.white(account?.tscircuit_handle ?? kleur.dim("(not set)"))}`,
` ${kleur.cyan("TscHandle:")} @${kleur.white(account?.tscircuit_handle?.trim() || kleur.dim("(not set)"))}`,
)
console.log(
` ${kleur.cyan("Account ID:")} ${kleur.white(account?.account_id ?? cliConfig.get("accountId") ?? kleur.dim("(unknown)"))}`,
` ${kleur.cyan("Account ID:")} ${kleur.white(account?.account_id ?? (isEnvToken ? undefined : cliConfig.get("accountId")) ?? kleur.dim("(unknown)"))}`,
)
console.log(
` ${kleur.cyan("Email:")} ${kleur.white(account?.email ?? kleur.dim("(unknown)"))}`,
)
console.log(
` ${kleur.cyan("Session ID:")} ${kleur.white(cliConfig.get("sessionId") ?? kleur.dim("(unknown)"))}`,
` ${kleur.cyan("Session ID:")} ${kleur.white((isEnvToken ? undefined : cliConfig.get("sessionId")) ?? kleur.dim("(unknown)"))}`,
)
console.log(
` ${kleur.cyan("Personal Org:")} ${kleur.white(account?.personal_org_id ?? kleur.dim("(unknown)"))}`,
Expand Down
2 changes: 1 addition & 1 deletion lib/registry-api/endpoint-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface EndpointResponse {
account: {
account_id: string
github_username: string | null
tscircuit_handle: string
tscircuit_handle: string | null
personal_org_id: string
created_at: string
email: string
Expand Down
62 changes: 53 additions & 9 deletions lib/registry-api/fetch-account.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,72 @@
import { cliConfig, getSessionToken } from "lib/cli-config"
import { getRegistryApiKy } from "./get-ky"
import type { EndpointResponse } from "./endpoint-types"
import { getRegistryApiKy } from "./get-ky"

export type Account = EndpointResponse["accounts/get"]["account"]

export const fetchAccount = async (): Promise<Account | null> => {
export type FetchAccountOptions = {
sessionToken?: string
throwOnError?: boolean
}

const extractAccountFromResponse = (response: unknown): Account => {
if (!response || typeof response !== "object" || Array.isArray(response)) {
throw new Error(
"Invalid response from registry API: missing account details",
)
}

const account = (response as { account?: unknown }).account
if (account && typeof account === "object" && !Array.isArray(account)) {
return account as Account
}

const apiError = (response as { error?: unknown }).error
if (apiError && typeof apiError === "object" && !Array.isArray(apiError)) {
const { error_code, message } = apiError as {
error_code?: unknown
message?: unknown
}
const parts = [error_code, message].filter(
(part): part is string => typeof part === "string" && part.length > 0,
)
if (parts.length > 0) {
throw new Error(`Invalid response from registry API: ${parts.join(": ")}`)
}
}

throw new Error("Invalid response from registry API: missing account details")
}

export const fetchAccount = async (
options?: FetchAccountOptions,
): Promise<Account | null> => {
if (process.env.TSCI_SKIP_ACCOUNT_FETCH === "true") return null

const sessionToken = getSessionToken()
const sessionToken = options?.sessionToken ?? getSessionToken()
if (!sessionToken) return null

const accountId =
process.env.TSCIRCUIT_TOKEN ||
(options?.sessionToken &&
options.sessionToken !== cliConfig.get("sessionToken"))
? undefined
: cliConfig.get("accountId")

try {
const ky = getRegistryApiKy({ sessionToken })
const { account } = await ky
const response = await ky
.post<EndpointResponse["accounts/get"]>("accounts/get", {
json: {
account_id: process.env.TSCIRCUIT_TOKEN
? undefined
: cliConfig.get("accountId"),
account_id: accountId,
},
})
.json()
return account
} catch {
return extractAccountFromResponse(response)
} catch (error) {
if (options?.throwOnError) {
throw error
}
return null
}
}
29 changes: 25 additions & 4 deletions lib/shared/push-snippet.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { cliConfig, getSessionToken } from "lib/cli-config"
import { fetchAccount } from "lib/registry-api/fetch-account"
import { type Account, fetchAccount } from "lib/registry-api/fetch-account"
import { getRegistryApiKy } from "lib/registry-api/get-ky"
import * as fs from "node:fs"
import * as path from "node:path"
Expand Down Expand Up @@ -181,9 +181,30 @@ export const pushSnippet = async ({
}

const ky = getRegistryApiKy({ sessionToken })
const currentUsername = process.env.TSCIRCUIT_TOKEN
? (await fetchAccount())?.tscircuit_handle
: cliConfig.get("tscircuitHandle")
let currentUsername: string | null | undefined
if (process.env.TSCIRCUIT_TOKEN) {
let account: Account | null
try {
account = await fetchAccount({
sessionToken,
throwOnError: true,
})
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error)
onError(`Could not verify your account for publishing: ${errorMessage}`)
return onExit(1)
}
if (!account) {
onError(
"Could not verify your account for publishing: account lookup was skipped",
)
return onExit(1)
}
currentUsername = account.tscircuit_handle?.trim()
} else {
currentUsername = cliConfig.get("tscircuitHandle")?.trim()
}
if (!currentUsername) {
onError("You need to set your tscircuit handle to publish packages")
return onExit(1)
Expand Down
Loading
Loading