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
12 changes: 10 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -72,6 +77,7 @@ const KNOWN_ERRORS = [
TabNotFoundError,
SliceVariationNotFoundError,
UnsupportedFileTypeError,
InvalidRepositoryDomainError,
NoSupportedFrameworkError,
ModelExistsError,
SliceNotFoundError,
Expand Down Expand Up @@ -134,7 +140,9 @@ async function main(): Promise<void> {
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;

Expand Down
40 changes: 31 additions & 9 deletions src/lib/prismic/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | undefined>;
Expand Down Expand Up @@ -96,7 +96,7 @@ export async function getRepository(config: RepositoryConfig): Promise<Repositor
const url = new URL("", getRepositoryServiceUrl(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: RepositorySchema,
notFoundMessage: `Repository not found: ${config.repo}`,
Expand All @@ -112,7 +112,7 @@ export async function enableTypeBuilder(
await request(url, {
method: "PATCH",
json: { framework },
headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo },
headers: await getRepositoryHeaders(config),
onUnauthorized: config.onUnauthorized,
notFoundMessage: `Repository not found: ${config.repo}`,
});
Expand Down Expand Up @@ -160,7 +160,7 @@ export async function getCustomTypes(config: CustomTypesConfig): Promise<Dynamic
const url = new URL("customtypes", getCustomTypesServiceUrl(config.host));
if (config.releaseId) url.searchParams.set("release", config.releaseId);
return request<DynamicCustomTypeModel[]>(url, {
headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo },
headers: await getRepositoryHeaders(config),
onUnauthorized: config.onUnauthorized,
notFoundMessage: `Repository not found: ${config.repo}`,
});
Expand All @@ -170,7 +170,7 @@ export async function getSlices(config: CustomTypesConfig): Promise<SharedSliceM
const url = new URL("slices", getCustomTypesServiceUrl(config.host));
if (config.releaseId) url.searchParams.set("release", config.releaseId);
return request<SharedSliceModel[]>(url, {
headers: { Authorization: `Bearer ${await config.getToken()}`, repository: config.repo },
headers: await getRepositoryHeaders(config),
onUnauthorized: config.onUnauthorized,
notFoundMessage: `Repository not found: ${config.repo}`,
});
Expand All @@ -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",
Expand Down Expand Up @@ -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,
});
}
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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<Record<string, string>> {
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(
Expand Down
6 changes: 6 additions & 0 deletions src/lib/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down
6 changes: 6 additions & 0 deletions test/pull.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
11 changes: 11 additions & 0 deletions test/token-create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"');
});
Loading