-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlocal-ops.ts
More file actions
842 lines (767 loc) · 23.4 KB
/
local-ops.ts
File metadata and controls
842 lines (767 loc) · 23.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
/**
* Local Operations Dispatcher
*
* Handles filesystem and shell operations requested by the remote workflow.
* All operations are sandboxed to the workflow's cwd directory.
*/
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { isCancel, select } from "@clack/prompts";
import {
createProject,
getProject,
listOrganizations,
tryGetPrimaryDsn,
} from "../api-client.js";
import { ApiError } from "../errors.js";
import { resolveOrCreateTeam } from "../resolve-team.js";
import { buildProjectUrl } from "../sentry-urls.js";
import { slugify } from "../utils.js";
import {
DEFAULT_COMMAND_TIMEOUT_MS,
MAX_FILE_BYTES,
MAX_OUTPUT_BYTES,
} from "./constants.js";
import { resolveOrgPrefetched } from "./prefetch.js";
import type {
ApplyPatchsetPayload,
CreateSentryProjectPayload,
DirEntry,
FileExistsBatchPayload,
ListDirPayload,
LocalOpPayload,
LocalOpResult,
ReadFilesPayload,
RunCommandsPayload,
WizardOptions,
} from "./types.js";
/** Whitespace characters used for JSON indentation. */
const Indenter = {
SPACE: " ",
TAB: "\t",
} as const;
/** Describes the indentation style of a JSON file. */
type JsonIndent = {
/** The whitespace character used for indentation. */
replacer: (typeof Indenter)[keyof typeof Indenter];
/** How many times the replacer is repeated per indent level. */
length: number;
};
const DEFAULT_JSON_INDENT: JsonIndent = {
replacer: Indenter.SPACE,
length: 2,
};
/** Matches the first indented line in a string to detect whitespace style. */
const INDENT_PATTERN = /^(\s+)/m;
/**
* Detect the indentation style of a JSON string by inspecting the first
* indented line. Returns a default of 2 spaces if no indentation is found.
*/
function detectJsonIndent(content: string): JsonIndent {
const match = content.match(INDENT_PATTERN);
if (!match?.[1]) {
return DEFAULT_JSON_INDENT;
}
const indent = match[1];
if (indent.includes("\t")) {
return { replacer: Indenter.TAB, length: indent.length };
}
return { replacer: Indenter.SPACE, length: indent.length };
}
/** Build the third argument for `JSON.stringify` from a `JsonIndent`. */
function jsonIndentArg(indent: JsonIndent): string {
return indent.replacer.repeat(indent.length);
}
/**
* Pretty-print a JSON string using the given indentation style.
* Returns the original string if it cannot be parsed as valid JSON.
*/
function prettyPrintJson(content: string, indent: JsonIndent): string {
try {
return `${JSON.stringify(JSON.parse(content), null, jsonIndentArg(indent))}\n`;
} catch {
return content;
}
}
/**
* Shell metacharacters that enable chaining, piping, substitution, or redirection.
* All legitimate install commands are simple single commands that don't need these.
*
* Ordering matters for error-message accuracy (not correctness): multi-character
* operators like `&&` and `||` are checked before their single-character prefixes
* (`&`, `|`) so the reported label describes the actual construct the user wrote.
*/
const SHELL_METACHARACTER_PATTERNS: Array<{ pattern: string; label: string }> =
[
{ pattern: ";", label: "command chaining (;)" },
// Check multi-char operators before single `|` / `&` so labels are accurate
{ pattern: "&&", label: "command chaining (&&)" },
{ pattern: "||", label: "command chaining (||)" },
{ pattern: "|", label: "piping (|)" },
{ pattern: "&", label: "background execution (&)" },
{ pattern: "`", label: "command substitution (`)" },
{ pattern: "$(", label: "command substitution ($()" },
{ pattern: "(", label: "subshell/grouping (()" },
{ pattern: ")", label: "subshell/grouping ())" },
{ pattern: "$", label: "variable/command expansion ($)" },
{ pattern: "'", label: "single quote (')" },
{ pattern: '"', label: 'double quote (")' },
{ pattern: "\\", label: "backslash escape (\\)" },
{ pattern: "\n", label: "newline" },
{ pattern: "\r", label: "carriage return" },
{ pattern: ">", label: "redirection (>)" },
{ pattern: "<", label: "redirection (<)" },
// Glob and brace expansion — brace expansion is the real risk
// (e.g. `npm install {evil,@sentry/node}`)
{ pattern: "{", label: "brace expansion ({)" },
{ pattern: "}", label: "brace expansion (})" },
{ pattern: "*", label: "glob expansion (*)" },
{ pattern: "?", label: "glob expansion (?)" },
{ pattern: "#", label: "shell comment (#)" },
];
const WHITESPACE_RE = /\s+/;
/**
* Executables that should never appear in a package install command.
*/
const BLOCKED_EXECUTABLES = new Set([
// Destructive
"rm",
"rmdir",
"del",
// Network/exfil
"curl",
"wget",
"nc",
"ncat",
"netcat",
"socat",
"telnet",
"ftp",
// Privilege escalation
"sudo",
"su",
"doas",
// Permissions
"chmod",
"chown",
"chgrp",
// Process/system
"kill",
"killall",
"pkill",
"shutdown",
"reboot",
"halt",
"poweroff",
// Disk
"dd",
"mkfs",
"fdisk",
"mount",
"umount",
// Remote access
"ssh",
"scp",
"sftp",
// Shells
"bash",
"sh",
"zsh",
"fish",
"csh",
"dash",
// Misc dangerous
"eval",
"exec",
"env",
"xargs",
]);
/**
* Validate a command before execution.
* Returns an error message if the command is unsafe, or undefined if it's OK.
*/
export function validateCommand(command: string): string | undefined {
// Layer 1: Block shell metacharacters
for (const { pattern, label } of SHELL_METACHARACTER_PATTERNS) {
if (command.includes(pattern)) {
return `Blocked command: contains ${label} — "${command}"`;
}
}
// Layer 2: Block environment variable injection (VAR=value cmd)
const firstToken = command.trimStart().split(WHITESPACE_RE)[0];
if (!firstToken) {
return "Blocked command: empty command";
}
if (firstToken.includes("=")) {
return `Blocked command: contains environment variable assignment — "${command}"`;
}
// Layer 3: Block dangerous executables (first token only).
// NOTE: This only checks the primary executable (e.g. "npm"), not
// subcommands. A command like "npm exec -- rm -rf /" passes because
// "npm" is the first token. Comprehensive subcommand parsing across
// package managers is not implemented — commands originate from the
// Sentry API server, and Layer 1 already blocks most injection patterns.
const executable = path.basename(firstToken);
if (BLOCKED_EXECUTABLES.has(executable)) {
return `Blocked command: disallowed executable "${executable}" — "${command}"`;
}
return;
}
/**
* Resolve a path relative to cwd and verify it's inside cwd.
* Rejects path traversal attempts and symlinks that escape the project directory.
*/
function safePath(cwd: string, relative: string): string {
const resolved = path.resolve(cwd, relative);
const normalizedCwd = path.resolve(cwd);
if (
!resolved.startsWith(normalizedCwd + path.sep) &&
resolved !== normalizedCwd
) {
throw new Error(`Path "${relative}" resolves outside project directory`);
}
// Follow symlinks: verify the real path also stays within bounds.
// Resolve cwd through realpathSync too (e.g. macOS /tmp -> /private/tmp).
let realCwd: string;
try {
realCwd = fs.realpathSync(normalizedCwd);
} catch {
// cwd doesn't exist yet — no symlinks to follow
return resolved;
}
// For paths that don't exist yet (create ops), walk up to the nearest
// existing ancestor and check that instead.
let checkPath = resolved;
for (;;) {
try {
const real = fs.realpathSync(checkPath);
if (!real.startsWith(realCwd + path.sep) && real !== realCwd) {
throw new Error(
`Path "${relative}" resolves outside project directory via symlink`
);
}
break;
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
throw err;
}
const parent = path.dirname(checkPath);
if (parent === checkPath) {
break; // filesystem root
}
checkPath = parent;
}
}
return resolved;
}
/**
* Pre-compute directory listing before the first API call.
* Uses the same parameters the server's discover-context step would request.
*/
export function precomputeDirListing(directory: string): DirEntry[] {
const result = listDir({
type: "local-op",
operation: "list-dir",
cwd: directory,
params: { path: ".", recursive: true, maxDepth: 3, maxEntries: 500 },
});
return (result.data as { entries?: DirEntry[] })?.entries ?? [];
}
export async function handleLocalOp(
payload: LocalOpPayload,
options: WizardOptions
): Promise<LocalOpResult> {
try {
// Validate that the remote-supplied cwd is within the user's project directory
const normalizedCwd = path.resolve(payload.cwd);
const normalizedDir = path.resolve(options.directory);
if (
normalizedCwd !== normalizedDir &&
!normalizedCwd.startsWith(normalizedDir + path.sep)
) {
return {
ok: false,
error: `Blocked: cwd "${payload.cwd}" is outside project directory "${options.directory}"`,
};
}
switch (payload.operation) {
case "list-dir":
return await listDir(payload);
case "read-files":
return await readFiles(payload);
case "file-exists-batch":
return await fileExistsBatch(payload);
case "run-commands":
return await runCommands(payload, options.dryRun);
case "apply-patchset":
return await applyPatchset(payload, options.dryRun);
case "create-sentry-project":
return await createSentryProject(payload, options);
default:
return {
ok: false,
error: `Unknown operation: ${
// biome-ignore lint/suspicious/noExplicitAny: payload is of type LocalOpPayload
(payload as any).operation
}`,
};
}
} catch (error) {
return {
ok: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
function listDir(payload: ListDirPayload): LocalOpResult {
const { cwd, params } = payload;
const targetPath = safePath(cwd, params.path);
const maxDepth = params.maxDepth ?? 3;
const maxEntries = params.maxEntries ?? 500;
const recursive = params.recursive ?? false;
const entries: DirEntry[] = [];
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: walking the directory tree is a complex operation
function walk(dir: string, depth: number): void {
if (entries.length >= maxEntries || depth > maxDepth) {
return;
}
let dirEntries: fs.Dirent[];
try {
dirEntries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of dirEntries) {
if (entries.length >= maxEntries) {
return;
}
const relPath = path.relative(cwd, path.join(dir, entry.name));
const type = entry.isDirectory() ? "directory" : "file";
entries.push({ name: entry.name, path: relPath, type });
if (
recursive &&
entry.isDirectory() &&
!entry.name.startsWith(".") &&
entry.name !== "node_modules"
) {
walk(path.join(dir, entry.name), depth + 1);
}
}
}
walk(targetPath, 0);
return { ok: true, data: { entries } };
}
function readFiles(payload: ReadFilesPayload): LocalOpResult {
const { cwd, params } = payload;
const maxBytes = params.maxBytes ?? MAX_FILE_BYTES;
const files: Record<string, string | null> = {};
for (const filePath of params.paths) {
try {
const absPath = safePath(cwd, filePath);
const stat = fs.statSync(absPath);
let content: string;
if (stat.size > maxBytes) {
// Read only up to maxBytes
const buffer = Buffer.alloc(maxBytes);
const fd = fs.openSync(absPath, "r");
try {
fs.readSync(fd, buffer, 0, maxBytes, 0);
} finally {
fs.closeSync(fd);
}
content = buffer.toString("utf-8");
} else {
content = fs.readFileSync(absPath, "utf-8");
}
// Minify JSON files by stripping whitespace/formatting
if (filePath.endsWith(".json")) {
try {
content = JSON.stringify(JSON.parse(content));
} catch {
// Not valid JSON (truncated, JSONC, etc.) — send as-is
}
}
files[filePath] = content;
} catch {
files[filePath] = null;
}
}
return { ok: true, data: { files } };
}
function fileExistsBatch(payload: FileExistsBatchPayload): LocalOpResult {
const { cwd, params } = payload;
const exists: Record<string, boolean> = {};
for (const filePath of params.paths) {
try {
const absPath = safePath(cwd, filePath);
exists[filePath] = fs.existsSync(absPath);
} catch {
exists[filePath] = false;
}
}
return { ok: true, data: { exists } };
}
async function runCommands(
payload: RunCommandsPayload,
dryRun?: boolean
): Promise<LocalOpResult> {
const { cwd, params } = payload;
const timeoutMs = params.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
// Phase 1: Validate ALL commands upfront (including dry-run)
for (const command of params.commands) {
const validationError = validateCommand(command);
if (validationError) {
return { ok: false, error: validationError };
}
}
// Phase 2: Execute (skip in dry-run)
const results: Array<{
command: string;
exitCode: number;
stdout: string;
stderr: string;
}> = [];
for (const command of params.commands) {
if (dryRun) {
results.push({
command,
exitCode: 0,
stdout: "(dry-run: skipped)",
stderr: "",
});
continue;
}
const result = await runSingleCommand(command, cwd, timeoutMs);
results.push(result);
if (result.exitCode !== 0) {
return {
ok: false,
error: `Command "${command}" failed with exit code ${result.exitCode}: ${result.stderr}`,
data: { results },
};
}
}
return { ok: true, data: { results } };
}
// Note: shell: true targets Unix shells. Windows cmd.exe metacharacters
// (%, ^) are not blocked; the CLI assumes a Unix Node.js environment.
function runSingleCommand(
command: string,
cwd: string,
timeoutMs: number
): Promise<{
command: string;
exitCode: number;
stdout: string;
stderr: string;
}> {
return new Promise((resolve) => {
const child = spawn(command, [], {
shell: true,
cwd,
stdio: ["ignore", "pipe", "pipe"],
timeout: timeoutMs,
});
const stdoutChunks: Buffer[] = [];
const stderrChunks: Buffer[] = [];
let stdoutLen = 0;
let stderrLen = 0;
child.stdout.on("data", (chunk: Buffer) => {
if (stdoutLen < MAX_OUTPUT_BYTES) {
stdoutChunks.push(chunk);
stdoutLen += chunk.length;
}
});
child.stderr.on("data", (chunk: Buffer) => {
if (stderrLen < MAX_OUTPUT_BYTES) {
stderrChunks.push(chunk);
stderrLen += chunk.length;
}
});
child.on("error", (err) => {
resolve({
command,
exitCode: 1,
stdout: "",
stderr: err.message,
});
});
child.on("close", (code) => {
const stdout = Buffer.concat(stdoutChunks)
.toString("utf-8")
.slice(0, MAX_OUTPUT_BYTES);
const stderr = Buffer.concat(stderrChunks)
.toString("utf-8")
.slice(0, MAX_OUTPUT_BYTES);
resolve({ command, exitCode: code ?? 1, stdout, stderr });
});
});
}
function applyPatchsetDryRun(payload: ApplyPatchsetPayload): LocalOpResult {
const { cwd, params } = payload;
const applied: Array<{ path: string; action: string }> = [];
for (const patch of params.patches) {
safePath(cwd, patch.path);
if (!["create", "modify", "delete"].includes(patch.action)) {
return {
ok: false,
error: `Unknown patch action: "${patch.action}" for path "${patch.path}"`,
};
}
applied.push({ path: patch.path, action: patch.action });
}
return { ok: true, data: { applied } };
}
/**
* Resolve the final file content for a patch, pretty-printing JSON files
* to preserve readable formatting. For `modify` actions, the existing file's
* indentation style is detected and preserved. For `create` actions, a default
* of 2-space indentation is used.
*/
function resolvePatchContent(
absPath: string,
patch: ApplyPatchsetPayload["params"]["patches"][number]
): string {
if (!patch.path.endsWith(".json")) {
return patch.patch;
}
if (patch.action === "modify") {
const existing = fs.readFileSync(absPath, "utf-8");
return prettyPrintJson(patch.patch, detectJsonIndent(existing));
}
return prettyPrintJson(patch.patch, DEFAULT_JSON_INDENT);
}
function applyPatchset(
payload: ApplyPatchsetPayload,
dryRun?: boolean
): LocalOpResult {
if (dryRun) {
return applyPatchsetDryRun(payload);
}
const { cwd, params } = payload;
// Phase 1: Validate all paths and actions before writing anything
for (const patch of params.patches) {
safePath(cwd, patch.path);
if (!["create", "modify", "delete"].includes(patch.action)) {
return {
ok: false,
error: `Unknown patch action: "${patch.action}" for path "${patch.path}"`,
};
}
}
// Phase 2: Apply patches
const applied: Array<{ path: string; action: string }> = [];
for (const patch of params.patches) {
const absPath = safePath(cwd, patch.path);
switch (patch.action) {
case "create": {
const dir = path.dirname(absPath);
fs.mkdirSync(dir, { recursive: true });
const content = resolvePatchContent(absPath, patch);
fs.writeFileSync(absPath, content, "utf-8");
applied.push({ path: patch.path, action: "create" });
break;
}
case "modify": {
if (!fs.existsSync(absPath)) {
return {
ok: false,
error: `Cannot modify "${patch.path}": file does not exist`,
data: { applied },
};
}
const content = resolvePatchContent(absPath, patch);
fs.writeFileSync(absPath, content, "utf-8");
applied.push({ path: patch.path, action: "modify" });
break;
}
case "delete": {
if (fs.existsSync(absPath)) {
fs.unlinkSync(absPath);
}
applied.push({ path: patch.path, action: "delete" });
break;
}
default:
return {
ok: false,
error: `Unknown patch action: "${patch.action}" for path "${patch.path}"`,
data: { applied },
};
}
}
return { ok: true, data: { applied } };
}
/**
* Resolve the org slug from local config, env vars, or by listing the user's
* organizations from the API as a fallback.
*
* DSN scanning uses the prefetch-aware helper from `./prefetch.ts` — if
* {@link warmOrgDetection} was called earlier (by `init.ts`), the result is
* already cached and returns near-instantly.
*
* `listOrganizations()` uses SQLite caching for near-instant warm lookups
* (populated after `sentry login` or the first API call), so it does not
* need background prefetching.
*
* @returns The org slug on success, or a {@link LocalOpResult} error to return early.
*/
async function resolveOrgSlug(
cwd: string,
yes: boolean
): Promise<string | LocalOpResult> {
const resolved = await resolveOrgPrefetched(cwd);
if (resolved) {
return resolved.org;
}
// Fallback: list user's organizations (SQLite-cached after login/first call)
const orgs = await listOrganizations();
if (orgs.length === 0) {
return {
ok: false,
error: "Not authenticated. Run 'sentry login' first.",
};
}
if (orgs.length === 1 && orgs[0]) {
return orgs[0].slug;
}
// Multiple orgs — interactive selection
if (yes) {
const slugs = orgs.map((o) => o.slug).join(", ");
return {
ok: false,
error: `Multiple organizations found (${slugs}). Set SENTRY_ORG to specify which one.`,
};
}
const selected = await select({
message: "Which organization should the project be created in?",
options: orgs.map((o) => ({
value: o.slug,
label: o.name,
hint: o.slug,
})),
});
if (isCancel(selected)) {
return { ok: false, error: "Organization selection cancelled." };
}
return selected;
}
/**
* Try to fetch an existing project by org + slug. Returns a successful
* LocalOpResult if the project exists, or null if it doesn't (404).
* Other errors are left to propagate.
*/
async function tryGetExistingProject(
orgSlug: string,
projectSlug: string
): Promise<LocalOpResult | null> {
try {
const project = await getProject(orgSlug, projectSlug);
const dsn = await tryGetPrimaryDsn(orgSlug, project.slug);
const url = buildProjectUrl(orgSlug, project.slug);
return {
ok: true,
data: {
orgSlug,
projectSlug: project.slug,
projectId: project.id,
dsn: dsn ?? "",
url,
},
};
} catch (error) {
// 404 means project doesn't exist — fall through to creation
if (error instanceof ApiError && error.status === 404) {
return null;
}
throw error;
}
}
async function createSentryProject(
payload: CreateSentryProjectPayload,
options: WizardOptions
): Promise<LocalOpResult> {
// Use CLI-provided project name if available, otherwise use wizard-detected name
const name = options.project ?? payload.params.name;
const { platform } = payload.params;
const slug = slugify(name);
if (!slug) {
return {
ok: false,
error: `Invalid project name: "${name}" produces an empty slug.`,
};
}
// In dry-run mode, skip all API calls and return placeholder data
if (options.dryRun) {
return {
ok: true,
data: {
orgSlug: options.org ?? "(dry-run)",
projectSlug: slug,
projectId: "(dry-run)",
dsn: "(dry-run)",
url: "(dry-run)",
},
};
}
try {
// 1. Resolve org — skip interactive resolution if explicitly provided via CLI arg
let orgSlug: string;
if (options.org) {
orgSlug = options.org;
} else {
const orgResult = await resolveOrgSlug(payload.cwd, options.yes);
if (typeof orgResult !== "string") {
return orgResult;
}
orgSlug = orgResult;
}
// 2. If both org and project were provided, check if the project already exists.
// This avoids a 409 Conflict from the create API when re-running init on an
// existing Sentry project (e.g., bare slug resolved via resolveProjectBySlug).
if (options.org && options.project) {
const existing = await tryGetExistingProject(orgSlug, slug);
if (existing) {
return existing;
}
}
// 3. Resolve or create team
const team = await resolveOrCreateTeam(orgSlug, {
team: options.team,
autoCreateSlug: slug,
usageHint: "sentry init",
});
// 4. Create project
const project = await createProject(orgSlug, team.slug, {
name,
platform,
});
// 5. Get DSN (best-effort)
const dsn = await tryGetPrimaryDsn(orgSlug, project.slug);
// 6. Build URL
const url = buildProjectUrl(orgSlug, project.slug);
return {
ok: true,
data: {
orgSlug,
projectSlug: project.slug,
projectId: project.id,
dsn: dsn ?? "",
url,
},
};
} catch (error) {
return { ok: false, error: formatLocalOpError(error) };
}
}
/** Format an error from a local-op into a user-facing message string. */
function formatLocalOpError(error: unknown): string {
if (error instanceof ApiError) {
return error.format();
}
if (error instanceof Error) {
return error.message;
}
return String(error);
}