diff --git a/src/auth.ts b/src/auth.ts index b637796..36c20f1 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -23,6 +23,7 @@ const CredentialsSchema = z.looseObject({ type Credentials = z.infer; export async function getToken(): Promise { + if (env.PRISMIC_TOKEN) return env.PRISMIC_TOKEN; const credentials = await readCredentials(); return credentials?.token; } @@ -34,6 +35,7 @@ export async function getHost(): Promise { } export async function refreshToken(): Promise { + if (env.PRISMIC_TOKEN) return; const token = await getToken(); if (!token) return; const host = await getHost(); diff --git a/src/commands/init.ts b/src/commands/init.ts index 3c0d05c..a436274 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -4,7 +4,7 @@ import { getAdapter } from "../adapters"; import { createLoginSession, getHost, getToken } from "../auth"; import { getCustomTypes, getSlices } from "../clients/custom-types"; import { getProfile } from "../clients/user"; -import { DEFAULT_PRISMIC_HOST } from "../env"; +import { DEFAULT_PRISMIC_HOST, env } from "../env"; import { openBrowser } from "../lib/browser"; import { CommandError, createCommand, type CommandConfig } from "../lib/command"; import { diffArrays } from "../lib/diff"; @@ -76,6 +76,11 @@ export default createCommand(config, async ({ values }) => { profile = await getProfile({ token, host }); } catch (error) { if (error instanceof UnauthorizedRequestError || error instanceof ForbiddenRequestError) { + if (env.PRISMIC_TOKEN) { + throw new CommandError( + "PRISMIC_TOKEN is invalid or expired. Unset it to log in with a browser, or replace it with a valid token.", + ); + } console.info("Not logged in. Starting login..."); const { email } = await createLoginSession({ onReady: (url) => { diff --git a/src/env.ts b/src/env.ts index e239fd5..bd26798 100644 --- a/src/env.ts +++ b/src/env.ts @@ -15,6 +15,7 @@ const Env = z.object({ PRISMIC_SENTRY_ENVIRONMENT: z.optional(z.string()), PRISMIC_SENTRY_ENABLED: z.optional(z.stringbool()), PRISMIC_HOST: z.optional(z.string()), + PRISMIC_TOKEN: z.optional(z.string()), PRISMIC_DOCS_HOST: z.optional(z.string()), PRISMIC_CONFIG_DIR: z.optional(z.string()), PRISMIC_TYPE_BUILDER_ENABLED: z.optional(z.stringbool()), diff --git a/test/whoami.test.ts b/test/whoami.test.ts index 7fcdae7..fabebf2 100644 --- a/test/whoami.test.ts +++ b/test/whoami.test.ts @@ -18,3 +18,13 @@ it("fails when not logged in", async ({ expect, prismic, logout }) => { const { exitCode } = await prismic("whoami"); expect(exitCode).not.toBe(0); }); + +it("uses PRISMIC_TOKEN env var when set", async ({ expect, prismic, login, logout, token }) => { + const { email } = await login(); + await logout(); + const { stdout, exitCode } = await prismic("whoami", [], { + nodeOptions: { env: { PRISMIC_TOKEN: token } }, + }); + expect(exitCode).toBe(0); + expect(stdout).toContain(email); +});