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
6 changes: 6 additions & 0 deletions apps/cli-docs/src/fragments/commands/wizard.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,9 @@ builds, so those builds fail on machines without the file: set
`SENTRY_AUTH_TOKEN` in CI, or create a `sentry.properties` on each machine.
On self-hosted Sentry, the file also holds the server URL, so set `SENTRY_URL`
in CI too.

The React Native wizard writes the auth token to `.env.sentry-build-plugin` in
the project root and adds that file to `.gitignore` (`@sentry/react-native`
6.3.0 and later). `ios/sentry.properties` and `android/sentry.properties` hold
only the org, project and, on self-hosted Sentry, URL, so commit them. In CI,
set `SENTRY_AUTH_TOKEN`.
181 changes: 159 additions & 22 deletions packages/cli/src/lib/wizard/react-native/react-native-wizard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import { buildProjectIssuesUrl } from "../../sentry-web-urls.js";
import { clack } from "../utils/clack/prompts.js";
import chalk from "chalk";
import { existsSync, readFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { isRegularFile } from "../../fs-utils.js";

import { Sentry } from "../telemetry.js";
import { platform } from "node:os";
Expand All @@ -24,6 +26,7 @@ import {
type CliSetupConfigContent,
abort,
abortIfCancelled,
addDotEnvSentryBuildPluginFile,
addSentryCliConfig,
askFlagQuestion,
confirmContinueIfNoOrDirtyGitRepo,
Expand All @@ -35,11 +38,18 @@ import {
printWelcome,
propertiesCliSetupConfig,
runPrettierIfInstalled,
SENTRY_DOT_ENV_FILE,
SENTRY_PROPERTIES_FILE,
} from "../utils/clack/index.js";
import {
getPackageVersion,
hasPackageInstalled,
} from "../utils/package-json.js";
import {
buildAuthTokenSettingsUrl,
DUMMY_AUTH_TOKEN,
} from "../utils/project-data.js";
import { fulfillsVersionRange } from "../utils/semver.js";
import {
isExpoCNG,
patchExpoAppConfig,
Expand Down Expand Up @@ -113,17 +123,30 @@ export function findAppBuildGradle(): Promise<string | undefined> {

export const RN_SDK_PACKAGE = "@sentry/react-native";
export const RN_SDK_SUPPORTED_RANGE = ">=6.12.0";
/**
* First SDK version whose iOS build scripts and `sentry.gradle` point
* sentry-cli at `.env.sentry-build-plugin` in the React Native root
* (getsentry/sentry-react-native#4281).
*/
const RN_SDK_DOTENV_MIN_VERSION = "6.3.0";

const IOS_SENTRY_PROPERTIES = `ios/${SENTRY_PROPERTIES_FILE}`;
const ANDROID_SENTRY_PROPERTIES = `android/${SENTRY_PROPERTIES_FILE}`;
const AUTH_TOKEN_ENV_VAR = "SENTRY_AUTH_TOKEN";

export const RN_PACKAGE = "react-native";
export const RN_HUMAN_NAME = "React Native";

export const SUPPORTED_RN_RANGE = ">=0.69.0";
export const SUPPORTED_EXPO_RANGE = ">=50.0.0";

export type RNCliSetupConfigContent = Pick<
Required<CliSetupConfigContent>,
"authToken" | "org" | "project" | "url"
>;
/** The auth token, org, project and web URL the wizard writes to config files. */
export interface RNCliSetupConfigContent {
authToken: string;
org: string;
project: string;
url: string;
}

export async function runReactNativeWizard(
params: ReactNativeWizardOptions,
Expand Down Expand Up @@ -230,7 +253,7 @@ Or setup using ${chalk.cyan(
return await abortIfSpotlightNotSupported("React Native");
}

const { selectedProject, authToken, sentryUrl } = projectData;
const { selectedProject, authToken, sentryUrl, selfHosted } = projectData;
const orgSlug = selectedProject.organization.slug;
const projectSlug = selectedProject.slug;
const projectId = selectedProject.id;
Expand Down Expand Up @@ -327,19 +350,7 @@ Or setup using ${chalk.cyan(
`Detected Expo Continuous Native Generation (CNG) setup. Skipping native files patching.`,
);
} else {
if (existsSync("ios")) {
Sentry.setTag("patch-ios", true);
await traceStep("patch-xcode-files", () =>
patchXcodeFiles(cliConfig, rnVersion),
);
}

if (existsSync("android")) {
Sentry.setTag("patch-android", true);
await traceStep("patch-android-files", () =>
patchAndroidFiles(cliConfig),
);
}
await patchNativeFiles({ cliConfig, sdkVersion, rnVersion, selfHosted });
}

await runPrettierIfInstalled({ cwd: undefined });
Expand Down Expand Up @@ -403,14 +414,140 @@ ${chalk.cyan(issuesStreamUrl)}`);
);
}

/**
* Writes `ios/` and `android/sentry.properties` and patches the native
* projects that exist. Builds read the org and project from those files, so
* they stay committed. When the SDK reads `.env.sentry-build-plugin`, the
* auth token goes there, gitignored, instead of into them.
*/
export async function patchNativeFiles({
cliConfig,
sdkVersion,
rnVersion,
selfHosted,
}: {
cliConfig: RNCliSetupConfigContent;
sdkVersion: string | undefined;
rnVersion: string | undefined;
selfHosted: boolean;
}): Promise<void> {
const patchIos = existsSync("ios");
const patchAndroid = existsSync("android");
const propertiesFiles = [
...(patchIos ? [IOS_SENTRY_PROPERTIES] : []),
...(patchAndroid ? [ANDROID_SENTRY_PROPERTIES] : []),
];
if (propertiesFiles.length === 0) {
return;
}

const tokenInDotEnv =
!!sdkVersion &&
fulfillsVersionRange({
version: sdkVersion,
acceptableVersions: `>=${RN_SDK_DOTENV_MIN_VERSION}`,
canBeLatest: true,
});
Sentry.setTag(
"auth-token-location",
tokenInDotEnv ? SENTRY_DOT_ENV_FILE : SENTRY_PROPERTIES_FILE,
);

let propertiesConfig: CliSetupConfigContent = cliConfig;
let filesWithEarlierToken: string[] = [];
let placeholderToken = false;
if (tokenInDotEnv) {
filesWithEarlierToken = propertiesFiles.filter(hasAuthTokenLine);
await addDotEnvSentryBuildPluginFile(cliConfig.authToken);
placeholderToken = await dotEnvHasPlaceholderToken(cliConfig.authToken);
Sentry.setTag("auth-token-placeholder", placeholderToken);
propertiesConfig = {
org: cliConfig.org,
project: cliConfig.project,
url: selfHosted ? cliConfig.url : undefined,
};
}

if (patchIos) {
Sentry.setTag("patch-ios", true);
await traceStep("patch-xcode-files", () =>
patchXcodeFiles(propertiesConfig, rnVersion),
);
}
if (patchAndroid) {
Sentry.setTag("patch-android", true);
await traceStep("patch-android-files", () =>
patchAndroidFiles(propertiesConfig),
);
}

const settingsUrl = chalk.cyan(
buildAuthTokenSettingsUrl(cliConfig.org, cliConfig.url),
);
const files = propertiesFiles.map((file) => chalk.cyan(file)).join(" and ");
const several = propertiesFiles.length > 1;
const envVar = chalk.cyan(AUTH_TOKEN_ENV_VAR);
const dotEnvFile = chalk.cyan(SENTRY_DOT_ENV_FILE);
if (!tokenInDotEnv) {
const reason = sdkVersion
? `${RN_SDK_PACKAGE}@${sdkVersion} doesn't read the token from ${dotEnvFile}`
: `The wizard couldn't detect your ${RN_SDK_PACKAGE} version`;
clack.log.warn(
`${files} ${several ? "hold" : "holds"} your auth token and ${several ? "aren't" : "isn't"} gitignored, since builds read the org and project from ${several ? "them" : "it"}, so committing ${several ? "them" : "it"} commits the token. ${reason}. To keep the token out of git, upgrade ${RN_SDK_PACKAGE} to ${RN_SDK_DOTENV_MIN_VERSION} or later and run the wizard again, or remove the ${chalk.cyan("auth.token")} line and set ${envVar} instead, with a token from:\n${settingsUrl}`,
);
return;
}

const propertiesNote = `The wizard put only the ${propertiesConfig.url ? "org, project and server URL" : "org and project"} in ${files}, so commit ${several ? "those" : "that"}.`;
if (placeholderToken) {
clack.log.warn(
`${dotEnvFile} holds a placeholder auth token (${chalk.cyan(`"${DUMMY_AUTH_TOKEN}"`)}), so Release builds fail at the Sentry upload until you replace it with a token from:\n${settingsUrl}\n${dotEnvFile} is gitignored. ${propertiesNote} In CI, set ${envVar}.`,
);
} else {
clack.log.info(
`The wizard put the auth token in ${dotEnvFile}, which is gitignored. ${propertiesNote} In CI, set ${envVar} to a token from:\n${settingsUrl}`,
);
}
for (const file of filesWithEarlierToken) {
clack.log.warn(
`${chalk.cyan(file)} already has an ${chalk.cyan("auth.token")} line from an earlier setup, so the file may already be committed with the token. The wizard didn't change it. Remove the line, since builds now read the token from ${dotEnvFile}, and if the file was pushed, rotate the token at:\n${settingsUrl}`,
);
}
}

/**
* Whether `.env.sentry-build-plugin` ends up with the placeholder token. The
* file keeps a token it already had, so that one counts, not this run's
* `authToken`. When the file can't be read, `authToken` decides.
*/
async function dotEnvHasPlaceholderToken(authToken: string): Promise<boolean> {
const file = path.join(process.cwd(), SENTRY_DOT_ENV_FILE);
if (!(await isRegularFile(file))) {
return authToken === DUMMY_AUTH_TOKEN;
}
const contents = await readFile(file, "utf8");
const token = /^\s*SENTRY_AUTH_TOKEN\s*=(.*)$/m.exec(contents)?.[1]?.trim();
return token === DUMMY_AUTH_TOKEN;
}

/** Whether `file`, relative to the cwd, has an `auth.token` line. */
function hasAuthTokenLine(file: string): boolean {
return (
existsSync(file) &&
propertiesCliSetupConfig.likelyAlreadyHasAuthToken(
readFileSync(file, "utf8"),
)
);
}

async function patchXcodeFiles(
config: RNCliSetupConfigContent,
config: CliSetupConfigContent,
rnVersion: string | undefined,
) {
await addSentryCliConfig(config, {
...propertiesCliSetupConfig,
name: "source maps and iOS debug files",
filename: "ios/sentry.properties",
filename: IOS_SENTRY_PROPERTIES,
gitignore: false,
});

Expand Down Expand Up @@ -506,11 +643,11 @@ async function patchXcodeFiles(
Sentry.setTag("xcode-project-status", "patched");
}

export async function patchAndroidFiles(config: RNCliSetupConfigContent) {
export async function patchAndroidFiles(config: CliSetupConfigContent) {
await addSentryCliConfig(config, {
...propertiesCliSetupConfig,
name: "source maps and iOS debug files",
filename: "android/sentry.properties",
filename: ANDROID_SENTRY_PROPERTIES,
gitignore: false,
});

Expand Down
5 changes: 3 additions & 2 deletions packages/cli/src/lib/wizard/utils/clack/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ export interface CliSetupConfig {
}

export interface CliSetupConfigContent {
authToken: string;
/** Omit to write the config without an auth token line. */
authToken?: string | undefined;
org?: string | undefined;
project?: string | undefined;
url?: string | undefined;
Expand Down Expand Up @@ -619,7 +620,7 @@ export async function addSentryCliConfig(

if (setupConfig.gitignore) {
await addCliConfigFileToGitIgnore(setupConfig.filename);
} else {
} else if (authToken) {
clack.log.warn(
chalk.yellow("DO NOT commit auth token to your repository!"),
);
Expand Down
Loading
Loading