diff --git a/src/index.ts b/src/index.ts index 97a0155f..9b22526f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -20,7 +20,11 @@ import { detectAgent } from "./lib/ai"; import { DeviceFlowError } from "./lib/auth0"; import { CommandError } from "./lib/command"; import { MissingPackageJson } from "./lib/packageJson"; -import { getUserProfile, UnsupportedFileTypeError } from "./lib/prismic/client"; +import { + getUserProfile, + InvalidRepositoryDomainError, + UnsupportedFileTypeError, +} from "./lib/prismic/client"; import { InvalidEnvironmentError } from "./lib/prismic/environments"; import { FieldExistsError, @@ -47,6 +51,7 @@ import { } from "./lib/sentry"; import { genTaskId, isTaskId } from "./lib/task-id"; import { initUpdateNotifier } from "./lib/update-notifier"; +import { isSubdomain } from "./lib/url"; import { InvalidLegacySliceMachineConfigError, InvalidPrismicConfigError, @@ -72,6 +77,7 @@ const KNOWN_ERRORS = [ TabNotFoundError, SliceVariationNotFoundError, UnsupportedFileTypeError, + InvalidRepositoryDomainError, NoSupportedFrameworkError, ModelExistsError, SliceNotFoundError, @@ -134,7 +140,9 @@ async function main(): Promise { return; } - const repo = typeof repoValue === "string" ? repoValue : undefined; + // A value that isn't a domain, such as a list of names, can't be a + // repository, so analytics leave it out. + const repo = typeof repoValue === "string" && isSubdomain(repoValue) ? repoValue : undefined; const userIntent = typeof intentValue === "string" ? intentValue : undefined; const taskId = typeof taskIdValue === "string" ? taskIdValue : undefined; diff --git a/src/lib/prismic/client.ts b/src/lib/prismic/client.ts index 90b6aaec..b9075455 100644 --- a/src/lib/prismic/client.ts +++ b/src/lib/prismic/client.ts @@ -4,7 +4,7 @@ import type { DynamicCustomTypeModel, SharedSliceModel } from "@prismicio/types- import * as z from "zod/mini"; import { request, type RequestOptions } from "../request"; -import { appendTrailingSlash } from "../url"; +import { appendTrailingSlash, isSubdomain } from "../url"; type Config = { getToken: () => Promise; @@ -96,7 +96,7 @@ export async function getRepository(config: RepositoryConfig): Promise(url, { - headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo }, + headers: await getRepositoryHeaders(config), onUnauthorized: config.onUnauthorized, notFoundMessage: `Repository not found: ${config.repo}`, }); @@ -170,7 +170,7 @@ export async function getSlices(config: CustomTypesConfig): Promise(url, { - headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo }, + headers: await getRepositoryHeaders(config), onUnauthorized: config.onUnauthorized, notFoundMessage: `Repository not found: ${config.repo}`, }); @@ -191,7 +191,7 @@ export async function bulkUpdateModels( await request(url, { method: "POST", json: { changes }, - headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo }, + headers: await getRepositoryHeaders(config), onUnauthorized: config.onUnauthorized, notFoundMessage: `Repository not found: ${config.repo}`, unknownErrorMessage: "Failed to update models", @@ -226,7 +226,7 @@ export async function deleteSliceScreenshots( await request(url, { method: "POST", json: { sliceId }, - headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo }, + headers: await getRepositoryHeaders(config), onUnauthorized: config.onUnauthorized, }); } @@ -272,7 +272,7 @@ async function getScreenshotUploadForm( const url = new URL("presigned-url", getScreenshotServiceUrl(config.host)); url.searchParams.set("repository", config.repo); return request(url, { - headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo }, + headers: await getRepositoryHeaders(config), onUnauthorized: config.onUnauthorized, schema: ScreenshotPresignedUrlResponseSchema, }); @@ -804,7 +804,29 @@ export async function setRepositoryName( } function getRepositoryDomainUrl(repo: string, host: string): URL { - return new URL(`https://${repo}.${host}/`); + return new URL(`https://${getRepositoryDomain(repo)}.${host}/`); +} + +async function getRepositoryHeaders(config: RepositoryConfig): Promise> { + const repository = getRepositoryDomain(config.repo); + return { Authorization: `Bearer ${await config.getToken()}`, repository }; +} + +// A value that isn't a subdomain, such as a list of names, can't go in a URL +// or a header. +function getRepositoryDomain(repo: string): string { + if (!isSubdomain(repo)) throw new InvalidRepositoryDomainError(repo); + return repo; +} + +export class InvalidRepositoryDomainError extends Error { + name = "InvalidRepositoryDomainError"; + + constructor(repo: string) { + super( + `Check your repository domain: ${JSON.stringify(repo)}. Pass one repository domain per command, such as "my-repo".`, + ); + } } export async function checkIsDomainAvailable( diff --git a/src/lib/url.ts b/src/lib/url.ts index 2058deae..edda4bbb 100644 --- a/src/lib/url.ts +++ b/src/lib/url.ts @@ -7,6 +7,12 @@ export function appendTrailingSlash(url: string | URL): URL { return newURL; } +// One DNS label: 1-63 letters, digits, or hyphens, with no hyphen at either end. +// Check the raw string: URL parsing drops newlines and tabs without an error. +export function isSubdomain(value: string): boolean { + return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(value); +} + export function relativePathname(a: URL, b: URL): string { return relative(fileURLToPath(a), fileURLToPath(b)); } diff --git a/test/pull.test.ts b/test/pull.test.ts index a6285659..5c434fce 100644 --- a/test/pull.test.ts +++ b/test/pull.test.ts @@ -32,6 +32,12 @@ it("supports --help", { concurrent: false }, async ({ expect, prismic }) => { expect(stdout).toContain("prismic docs view cli#pull-models-from-prismic"); }); +it("errors when --repo is not a domain", { concurrent: false }, async ({ expect, prismic }) => { + const { stderr, exitCode } = await prismic("pull", ["--repo", "repo-a\nrepo-b"]); + expect(exitCode).toBe(1); + expect(stderr).toContain('Check your repository domain: "repo-a\\nrepo-b"'); +}); + it( "pulls slices and custom types from remote", { concurrent: false }, diff --git a/test/token-create.test.ts b/test/token-create.test.ts index 2cb8fde2..e58a180f 100644 --- a/test/token-create.test.ts +++ b/test/token-create.test.ts @@ -123,3 +123,14 @@ it("errors when combining --write and --allow-releases", async ({ expect, prismi expect(exitCode).toBe(1); expect(stderr).toContain("--allow-releases is only valid for access tokens"); }); + +it("errors when --repo is not a domain", async ({ expect, prismic }) => { + const { stderr, exitCode } = await prismic("token", [ + "create", + "--write", + "--repo", + "repo-a\nrepo-b", + ]); + expect(exitCode).toBe(1); + expect(stderr).toContain('Check your repository domain: "repo-a\\nrepo-b"'); +});