Skip to content

Commit e1082f4

Browse files
committed
fix(sources): adapt PR #863 to shared archive staging and explicit uploads
2 parents 593aed6 + eb9be4d commit e1082f4

8 files changed

Lines changed: 322 additions & 37 deletions

File tree

‎apps/cli/src/commands/deploy.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ import { exitCommand, rethrowCommandExit } from "../lib/command-exit";
22
/**
33
* `openship deploy` — deploy the current project.
44
*
5-
* Two paths, auto-selected by whether the cwd is a git repository:
5+
* Two paths:
66
* - Git repo → POST /api/deployments (git-source build of the linked project).
7-
* - No git → folder-upload: package the cwd and drive the same pipeline the
8-
* MCP / dashboard folder deploy uses (see the shared SDK source workflow).
7+
* - --folder (or --name outside Git) → stage the current directory through
8+
* the shared SDK source workflow.
99
*
1010
* The git path's controller accepts an allowlist body ({ projectId, branch,
1111
* commitSha, environment, serverId, forceAll, serviceIds, smartRoute, refresh }) and
@@ -44,6 +44,7 @@ export const deployCommand = new Command("deploy")
4444
.option("--service-ids <ids>", "Comma-separated service IDs to deploy (smart routing)")
4545
.option("--smart-route", "Rebuild only services changed since the active deploy")
4646
.option("--refresh", "Re-apply current env to the active deploy (no git pull, no rebuild)")
47+
.option("--folder", "Upload the current folder as source (also works inside a Git repository)")
4748
.option(
4849
"--name <name>",
4950
"Project name for a folder (non-git) deploy (defaults to the directory name)",
@@ -60,14 +61,26 @@ export const deployCommand = new Command("deploy")
6061
exitCommand(1);
6162
}
6263

63-
// Auto-detect: outside a git repo, deploy the folder via the upload flow
64-
// (same pipeline as the MCP / dashboard folder deploy). The git-only flags
65-
// don't apply to a fresh upload, so they force the git path if set.
64+
// Never turn a redeploy from the wrong directory into an implicit upload.
65+
// --name remains an opt-in for existing folder-deploy scripts outside Git.
6666
const inGitRepo = git(["rev-parse", "--is-inside-work-tree"]) === "true";
6767
// --service-ids scopes BOTH a git redeploy and a folder redeploy (so a
6868
// backend-only change doesn't recreate stateful services), so it is NOT
6969
// git-only; commit/smart-route/refresh genuinely need git history.
70-
const gitOnlyFlags = opts.commit || opts.smartRoute || opts.refresh;
70+
const gitOnlyFlags = opts.branch || opts.commit || opts.smartRoute || opts.refresh;
71+
if (opts.folder && gitOnlyFlags) {
72+
err("--folder cannot be combined with --branch, --commit, --smart-route, or --refresh.");
73+
exitCommand(1);
74+
}
75+
const folderUpload = opts.folder || (!inGitRepo && !gitOnlyFlags && opts.name);
76+
const targetProjectId: string | undefined = opts.project || link?.projectId;
77+
if (!inGitRepo && !gitOnlyFlags && !folderUpload && !targetProjectId) {
78+
err(
79+
"No linked project in this directory. Pass --project <id> to redeploy a project. " +
80+
"To upload this directory, pass --folder or --name <name>.",
81+
);
82+
exitCommand(1);
83+
}
7184
const serviceIds: string[] | undefined = opts.serviceIds
7285
? opts.serviceIds
7386
.split(",")
@@ -78,7 +91,7 @@ export const deployCommand = new Command("deploy")
7891
let deploymentId: string | undefined;
7992
let payload: Record<string, unknown> | undefined;
8093

81-
if (!inGitRepo && !gitOnlyFlags) {
94+
if (folderUpload) {
8295
const spinner = isJsonMode() ? null : ora("Deploying folder").start();
8396
try {
8497
const result = await getShipClient().deploy({
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import { runCommand, stubFetch, type FetchStub } from "../helpers/harness";
6+
7+
vi.mock("../../src/lib/config", () => ({
8+
getApiUrl: () => "http://api.test",
9+
getToken: () => "tok",
10+
}));
11+
const gitState = vi.hoisted(() => ({ inRepo: false }));
12+
vi.mock("node:child_process", async (original) => {
13+
const actual = await original<typeof import("node:child_process")>();
14+
return {
15+
...actual,
16+
execFileSync: (...args: Parameters<typeof actual.execFileSync>) => {
17+
if (args[0] === "git") {
18+
if (gitState.inRepo) return Buffer.from("true");
19+
throw new Error("not a Git repository");
20+
}
21+
return actual.execFileSync(...args);
22+
},
23+
};
24+
});
25+
vi.mock("../../src/lib/project-link", () => ({ readProjectLink: () => null }));
26+
27+
describe("deploy requires folder upload opt-in (#853)", () => {
28+
let fetchStub: FetchStub;
29+
beforeEach(() => {
30+
vi.resetModules();
31+
gitState.inRepo = false;
32+
});
33+
afterEach(() => {
34+
fetchStub?.restore();
35+
vi.restoreAllMocks();
36+
});
37+
38+
it.each([
39+
{ flags: ["--folder"], inRepo: true },
40+
{ flags: ["--name", "local-app"], inRepo: false },
41+
])("uploads source with explicit opt-in: $flags", async ({ flags, inRepo }) => {
42+
const sourceDir = mkdtempSync(join(tmpdir(), "openship-folder-command-"));
43+
writeFileSync(join(sourceDir, "index.html"), "site");
44+
vi.spyOn(process, "cwd").mockReturnValue(sourceDir);
45+
gitState.inRepo = inRepo;
46+
fetchStub = stubFetch((req) => {
47+
if (req.url.endsWith("/projects/folder/session")) {
48+
return {
49+
json: {
50+
sessionId: "session-1",
51+
expiresAt: Date.now() + 60_000,
52+
upload: {
53+
url: "/folder-upload",
54+
absoluteUrl: "http://api.test/folder-upload",
55+
method: "POST",
56+
headers: {},
57+
requiresAuth: true,
58+
withCredentials: true,
59+
},
60+
},
61+
};
62+
}
63+
if (req.url.endsWith("/folder-upload")) return { json: { success: true } };
64+
if (req.url.endsWith("/projects/folder/scan/session-1"))
65+
return {
66+
json: {
67+
success: true,
68+
name: "local-app",
69+
stack: "static",
70+
projectType: "app",
71+
packageManager: "npm",
72+
installCommand: "",
73+
buildCommand: "",
74+
startCommand: "",
75+
buildImage: "",
76+
outputDirectory: "",
77+
rootDirectory: "",
78+
},
79+
};
80+
if (req.url.endsWith("/projects/ensure")) {
81+
expect(req.body).toMatchObject({ projectId: "p1", gitProvider: "upload" });
82+
return { json: { success: true, project_id: "p1", created: false } };
83+
}
84+
if (req.url.endsWith("/deployments/build/access")) {
85+
expect(req.body).toMatchObject({
86+
projectId: "p1",
87+
uploadSessionId: "session-1",
88+
serviceIds: ["svc1"],
89+
});
90+
return { json: { success: true, deployment_id: "d1", project_id: "p1" } };
91+
}
92+
throw new Error(`Unexpected endpoint: ${req.url}`);
93+
});
94+
try {
95+
const { deployCommand } = await import("../../src/commands/deploy");
96+
const result = await runCommand(deployCommand, [
97+
...flags,
98+
"--project",
99+
"p1",
100+
"--service-ids",
101+
"svc1",
102+
]);
103+
expect(result.code).toBe(0);
104+
expect(result.out + result.err).toContain("d1");
105+
expect(fetchStub.calls).toHaveLength(5);
106+
} finally {
107+
rmSync(sourceDir, { recursive: true, force: true });
108+
}
109+
});
110+
111+
it("does not provision an upload without a source or project opt-in outside Git", async () => {
112+
fetchStub = stubFetch(() => {
113+
throw new Error("must not send a request");
114+
});
115+
const { deployCommand } = await import("../../src/commands/deploy");
116+
const result = await runCommand(deployCommand, []);
117+
expect(result.code).toBe(1);
118+
expect(result.err).toContain("--folder");
119+
expect(fetchStub.calls).toEqual([]);
120+
});
121+
122+
it("redeploys an explicit project from outside Git without uploading the working directory", async () => {
123+
fetchStub = stubFetch((req) => {
124+
expect(req.url).toBe("http://api.test/api/deployments");
125+
expect(req.body).toMatchObject({ projectId: "p1", serviceIds: ["svc1"] });
126+
expect(req.body).not.toHaveProperty("branch");
127+
return { json: { data: { deployment_id: "dep1", project_id: "p1" } } };
128+
});
129+
const { deployCommand } = await import("../../src/commands/deploy");
130+
expect(
131+
(await runCommand(deployCommand, ["--project", "p1", "--service-ids", "svc1"])).code,
132+
).toBe(0);
133+
expect(fetchStub.calls).toHaveLength(1);
134+
});
135+
136+
it("uses the Git deployment endpoint for an explicit remote branch", async () => {
137+
fetchStub = stubFetch((req) => {
138+
expect(req.url).toBe("http://api.test/api/deployments");
139+
expect(req.body).toMatchObject({ projectId: "p1", branch: "main", serviceIds: ["svc1"] });
140+
return { json: { data: { deployment_id: "dep1", project_id: "p1" } } };
141+
});
142+
const { deployCommand } = await import("../../src/commands/deploy");
143+
const result = await runCommand(deployCommand, [
144+
"--project",
145+
"p1",
146+
"--branch",
147+
"main",
148+
"--service-ids",
149+
"svc1",
150+
]);
151+
expect(result.code).toBe(0);
152+
expect(fetchStub.calls).toHaveLength(1);
153+
});
154+
155+
it("rejects Git-only options with --folder before making requests", async () => {
156+
fetchStub = stubFetch(() => {
157+
throw new Error("must not send a request");
158+
});
159+
const { deployCommand } = await import("../../src/commands/deploy");
160+
const result = await runCommand(deployCommand, ["--folder", "--commit", "abc123"]);
161+
expect(result.code).toBe(1);
162+
expect(result.err).toContain("cannot be combined");
163+
expect(fetchStub.calls).toEqual([]);
164+
});
165+
});

‎apps/web/content/docs/cli/deploy.mdx‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,21 @@ openship deploy --project proj_123 --server srv_123 --watch
2424

2525
## Deploy a folder
2626

27-
From a directory outside a Git repository:
27+
Upload the current directory explicitly, including from a Git checkout:
2828

2929
```bash
30-
openship deploy --name my-site --watch
30+
openship deploy --folder --name my-site --watch
3131
```
3232

33-
The CLI packages that directory and submits it through the source-upload workflow. Inside a Git
34-
repository, it uses the linked project's Git source. `--commit`, `--smart-route`, and `--refresh`
35-
also select the Git path. `--service-ids` works for both Git and folder deployments.
33+
The CLI stages the directory through the shared SDK source workflow. Outside Git, `--name` also
34+
opts into a folder upload for existing scripts. A project ID alone never opts into uploading the
35+
current directory. Use `--project <id>` to redeploy from outside the checkout; the stored branch is
36+
used unless `--branch` is supplied.
37+
38+
`--branch`, `--commit`, `--smart-route`, and `--refresh` select the Git path and cannot be combined
39+
with `--folder`. `--service-ids` works for both paths. Archive staging must remain outside the source
40+
tree: the system temporary directory and its ancestors are refused. Select your project directory,
41+
or set `TMPDIR` outside the source tree.
3642

3743
Native directory deployment requires the directory to be inside `policy.sourceRoots`. See
3844
[folder deployment](/docs/guides/deploy-local-folder) for packaging behavior.

‎apps/web/content/docs/guides/deploy-local-folder.mdx‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -134,23 +134,25 @@ get a live link. 🎉
134134

135135
## CLI
136136

137-
The CLI does the whole thing in one command. When you run `openship deploy` in a folder that **isn't** a git
138-
repository, it automatically packages that folder, uploads it, auto-detects the stack, creates the project
137+
The CLI does the whole thing in one command. Run `openship deploy --folder` to explicitly upload the current
138+
directory. It packages that folder, uploads it, auto-detects the stack, creates the project
139139
(or reuses one that already has the same name), and deploys it — the same pipeline as the browser upload
140140
above.
141141

142142
```bash
143143
# From inside your project folder:
144-
openship deploy --name my-app --watch
144+
openship deploy --folder --name my-app --watch
145145
```
146146

147147
- `--name` sets the project's name (without it, the folder's name is used).
148148
- `--watch` follows the build logs in your terminal until it finishes. Leave it off and Openship prints a
149149
command to follow the logs later.
150150

151151
<Callout title="Deploying inside a git repo?" type="info">
152-
If the folder **is** a git repository, `openship deploy` deploys from git instead of uploading the folder.
153-
To upload the files directly, run it from a folder without a `.git` — or use [Deploy from GitHub](/docs/guides/deploy-from-github) for the git flow.
152+
`--folder` also uploads files directly from a Git checkout. Without it, `openship deploy` in a Git
153+
repository uses the Git flow. Outside Git, `--name` also opts into a folder upload for existing scripts.
154+
Run from your app's source directory: uploading the temporary directory or any ancestor of it is refused
155+
to keep staging archives outside the source tree. If `TMPDIR` is inside your app, set it elsewhere.
154156
</Callout>
155157

156158
### Deploy to the same project again
@@ -164,7 +166,7 @@ with `openship init`:
164166

165167
```bash
166168
openship init # pick a project to link this folder to
167-
openship deploy # from now on, deploys to the linked project
169+
openship deploy --folder # uploads this folder to the linked project
168170
```
169171

170172
`openship init` writes a small `.openship/project.json` file so later commands know which project this folder

‎packages/platform/src/source-files.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** Node filesystem helpers shared by native staging and remote SDK uploads. No engine bootstrap. */
22
import { lstat, mkdir, mkdtemp, readdir, realpath, rm, writeFile } from "node:fs/promises";
33
import { createWriteStream, realpathSync } from "node:fs";
4-
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
4+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
55
import { tmpdir } from "node:os";
66
import { pipeline } from "node:stream/promises";
77
import { create as createTar } from "tar";
@@ -17,6 +17,28 @@ function assertContained(root: string, path: string): void {
1717
throw new ValidationError("Source symlinks must remain inside the selected directory");
1818
}
1919

20+
/** Resolve a not-yet-created staging root through its existing symlink parents. */
21+
async function plannedRealpath(path: string): Promise<string> {
22+
try { return await realpath(path); }
23+
catch (error) {
24+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
25+
return join(await plannedRealpath(dirname(path)), basename(path));
26+
}
27+
}
28+
29+
/** An archive must never discover its own growing output or earlier upload debris. */
30+
export async function assertSourceStagingOutside(directory: string, temporaryRoot = tmpdir()) {
31+
const canonical = await realpath(directory);
32+
const root = await plannedRealpath(resolve(temporaryRoot));
33+
const target = relative(canonical, root);
34+
if (target === "" || (!isAbsolute(target) && target !== ".." && !target.startsWith("../") && !target.startsWith("..\\"))) {
35+
throw new ValidationError(
36+
"Cannot upload the temporary directory or a folder containing it. Select the project's source directory, or set TMPDIR outside it.",
37+
);
38+
}
39+
return { directory: canonical, root };
40+
}
41+
2042
export function sourceFileEntries(source: CodeSource): Array<[string, string | Uint8Array]> | null {
2143
if (source?.type === "directory" && typeof source.path === "string" && source.path.trim()) return null;
2244
if (source?.type !== "files" || !source.files || typeof source.files !== "object" || Array.isArray(source.files))
@@ -90,8 +112,9 @@ export async function prepareSourceDirectory(source: CodeSource, options: { temp
90112

91113
/** A source archive only excludes dependencies, Git metadata and OS noise. Build outputs remain. */
92114
export async function archiveSourceDirectory(directory: string, options: { temporaryRoot?: string; signal?: AbortSignal } = {}) {
93-
const canonical = await validateSourceDirectory(directory, options.signal);
94-
const root = options.temporaryRoot ?? tmpdir();
115+
const staging = await assertSourceStagingOutside(directory, options.temporaryRoot);
116+
const canonical = await validateSourceDirectory(staging.directory, options.signal);
117+
const root = staging.root;
95118
await mkdir(root, { recursive: true, mode: 0o700 });
96119
const temporary = await mkdtemp(join(root, "openship-upload-")), path = join(temporary, "source.tar.gz");
97120
const dispose = () => rm(temporary, { recursive: true, force: true });

‎packages/platform/test/source-archive.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,49 @@ function archive(entries: Array<HeaderData & { content?: string }>) {
2727
}
2828

2929
describe("owned source archives", () => {
30+
it.each(["temporary directory", "ancestor", "symlink"])(
31+
"rejects an archive source containing staging through its %s without touching old files",
32+
async kind => {
33+
const sandbox = await directory(), staging = join(sandbox, "tmp");
34+
await mkdir(staging);
35+
await writeFile(join(staging, "openship-upload-old.tar.gz"), "operator-owned leftover");
36+
const alias = join(sandbox, "tmp-link");
37+
await symlink(staging, alias);
38+
const source = kind === "ancestor" ? sandbox : kind === "symlink" ? alias : staging;
39+
let packed: Awaited<ReturnType<typeof archiveSourceDirectory>> | undefined;
40+
try {
41+
await expect(archiveSourceDirectory(source, { temporaryRoot: staging, signal: AbortSignal.timeout(500) }).then(value => { packed = value; return value; }))
42+
.rejects.toThrow(/temporary directory/);
43+
} finally { await packed?.dispose(); }
44+
expect(await readdir(staging)).toEqual(["openship-upload-old.tar.gz"]);
45+
expect(await readFile(join(staging, "openship-upload-old.tar.gz"), "utf8")).toBe("operator-owned leftover");
46+
},
47+
);
48+
49+
it("resolves symlink parents before creating a new staging directory inside the source", async () => {
50+
const sandbox = await directory(), source = join(sandbox, "source"), alias = join(sandbox, "link");
51+
await mkdir(source);
52+
await symlink(source, alias);
53+
await expect(archiveSourceDirectory(source, { temporaryRoot: join(alias, "new", "tmp") })).rejects.toThrow(/temporary directory/);
54+
expect(await readdir(source)).toEqual([]);
55+
});
56+
57+
it("allows a common path prefix and removes staging after repeated successful archives", async () => {
58+
const sandbox = await directory(), source = join(sandbox, "tmp-project"), staging = join(sandbox, "tmp");
59+
await mkdir(source);
60+
await writeFile(join(source, "index.html"), "source content");
61+
for (let attempt = 0; attempt < 3; attempt++) {
62+
const packed = await archiveSourceDirectory(source, { temporaryRoot: staging });
63+
const destination = await directory();
64+
try {
65+
await extractSourceArchive(packed.path, destination);
66+
expect(await readdir(destination)).toEqual(["index.html"]);
67+
expect(await readFile(join(destination, "index.html"), "utf8")).toBe("source content");
68+
} finally { await packed.dispose(); }
69+
expect(await readdir(staging)).toEqual([]);
70+
}
71+
});
72+
3073
it("packs and extracts files and internal symlinks without a system tar executable", async () => {
3174
const source = await directory(), destination = await directory();
3275
await mkdir(join(source, "dist"));

0 commit comments

Comments
 (0)