Skip to content

Commit 430ea82

Browse files
committed
feat(linux): pack release apps into app.nsbundle
Release builds pack app/ with the runtime's ns-bundle (sealed with linux.sourceProtect / --source-protect, per-build key unless --source-protect-key-hex or NS_LINUX_BUNDLE_KEY), unpack linux.bundleUnpack globs, and patch the executable's fuses. Bundling failures fall back to the plain folder; failed source protection fails the build.
1 parent 5adb7c2 commit 430ea82

5 files changed

Lines changed: 327 additions & 2 deletions

File tree

‎lib/data/build-data.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,14 @@ export class IOSBuildData extends BuildData implements IiOSBuildData {
4747

4848
export class LinuxBuildData extends BuildData {
4949
public arch?: string;
50+
public sourceProtect?: boolean;
51+
public sourceProtectKeyHex?: string;
5052

5153
constructor(projectDir: string, platform: string, data: any) {
5254
super(projectDir, platform, data);
5355
this.arch = data.arch;
56+
this.sourceProtect = data.sourceProtect;
57+
this.sourceProtectKeyHex = data.sourceProtectKeyHex;
5458
}
5559
}
5660

‎lib/definitions/project.d.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,33 @@ interface INsConfigIOS extends INsConfigPlaform {
144144

145145
interface INSConfigVisionOS extends INsConfigIOS {}
146146

147-
interface INsConfigLinux extends INsConfigPlaform {}
147+
interface INsConfigLinux extends INsConfigPlaform {
148+
/**
149+
* Release builds ship the app folder as one read-only archive, app.nsbundle (default true).
150+
*/
151+
bundle?: boolean;
152+
/**
153+
* Globs of app files written next to the bundle (app.nsbundle.unpacked) for code that opens
154+
* them by path. Default `["fonts/**"]`; native addons (.node, .so) are always unpacked.
155+
*/
156+
bundleUnpack?: string[];
157+
/**
158+
* Encrypt the bundle with a per-build key embedded in the executable. Release builds only;
159+
* overridable with --source-protect / --no-source-protect.
160+
*/
161+
sourceProtect?: boolean;
162+
/** Release build switches baked into the executable. */
163+
fuses?: {
164+
/** Check app.nsbundle against the hash in the executable (default: on when bundled). */
165+
bundleIntegrity?: boolean;
166+
/** Only run the app from app.nsbundle (default: on when bundled). */
167+
onlyLoadAppFromBundle?: boolean;
168+
/** Allow `--inspect` (default off). */
169+
inspector?: boolean;
170+
/** Honor runtime flags and environment overrides such as NS_METADATA (default off). */
171+
envOverrides?: boolean;
172+
};
173+
}
148174

149175
interface INsConfigWindows extends INsConfigPlaform {
150176
/**

‎lib/services/linux-app-bundle.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import * as path from "path";
2+
import * as fs from "fs";
3+
import { IChildProcess } from "../common/declarations";
4+
5+
/** `linux` options of nativescript.config that shape release packaging. */
6+
export interface LinuxBundleConfig {
7+
bundle?: boolean;
8+
bundleUnpack?: string[];
9+
sourceProtect?: boolean;
10+
fuses?: {
11+
bundleIntegrity?: boolean;
12+
onlyLoadAppFromBundle?: boolean;
13+
inspector?: boolean;
14+
envOverrides?: boolean;
15+
};
16+
}
17+
18+
export interface LinuxBundleOptions {
19+
/** staged folder: the executable, app/ */
20+
stage: string;
21+
executable: string;
22+
/** runtime package tools (ns-bundle) */
23+
toolsDir: string;
24+
config: LinuxBundleConfig;
25+
/** --source-protect / --no-source-protect */
26+
sourceProtect?: boolean;
27+
/** --source-protect-key-hex or $NS_LINUX_BUNDLE_KEY */
28+
keyHex?: string;
29+
}
30+
31+
const onOff = (on: boolean) => (on ? "on" : "off");
32+
33+
/**
34+
* Release packaging: app/ into app.nsbundle (sealed for source protection) and the executable's
35+
* fuses. Bundling problems only warn; failed source protection throws, so sources never ship readable by mistake.
36+
*/
37+
export class LinuxAppBundler {
38+
constructor(
39+
private $childProcess: IChildProcess,
40+
private $logger: ILogger,
41+
) {}
42+
43+
public async pack(options: LinuxBundleOptions): Promise<void> {
44+
const { stage, executable, toolsDir, config } = options;
45+
const seal = options.sourceProtect ?? config.sourceProtect ?? false;
46+
const bundle = seal || config.bundle !== false;
47+
const tool = process.env.NS_BUNDLE_TOOL || path.join(toolsDir, "ns-bundle");
48+
const fuses = config.fuses ?? {};
49+
const fuseArgs = (bundled: boolean) =>
50+
(
51+
[
52+
["bundleIntegrity", fuses.bundleIntegrity ?? bundled],
53+
["onlyLoadAppFromBundle", fuses.onlyLoadAppFromBundle ?? bundled],
54+
["inspector", fuses.inspector ?? false],
55+
["envOverrides", fuses.envOverrides ?? false],
56+
] as [string, boolean][]
57+
).flatMap(([name, on]) => ["--fuse", `${name}=${onOff(on)}`]);
58+
59+
if (!fs.existsSync(tool)) {
60+
const message = `This Linux runtime has no ns-bundle tool (${tool}), the app ships as a plain folder.`;
61+
if (seal) {
62+
throw new Error(`Source protection failed: ${message}`);
63+
}
64+
if (bundle) {
65+
this.$logger.warn(message);
66+
}
67+
return;
68+
}
69+
70+
if (!bundle) {
71+
try {
72+
await this.run(tool, ["fuses", executable, ...fuseArgs(false)], stage);
73+
} catch (e) {
74+
this.$logger.warn(`Couldn't set the runtime fuses: ${e.message}`);
75+
}
76+
return;
77+
}
78+
79+
const app = path.join(stage, "app");
80+
const output = path.join(stage, "app.nsbundle");
81+
const unpacked = `${output}.unpacked`;
82+
const args = [
83+
"pack",
84+
"--input",
85+
app,
86+
"--output",
87+
output,
88+
"--exe",
89+
executable,
90+
];
91+
if (config.bundleUnpack) {
92+
args.push("--no-default-unpack");
93+
for (const glob of config.bundleUnpack) {
94+
args.push("--unpack", glob);
95+
}
96+
}
97+
if (seal) {
98+
args.push("--seal");
99+
if (options.keyHex) {
100+
args.push("--key-hex", options.keyHex);
101+
}
102+
}
103+
args.push(...fuseArgs(true));
104+
// the tool only patches the executable once the bundle is written
105+
const pristine = fs.readFileSync(executable);
106+
try {
107+
const result = await this.run(tool, args, stage);
108+
this.$logger.info(result.stdout.trim());
109+
} catch (e) {
110+
for (const p of [output, unpacked]) {
111+
fs.rmSync(p, { recursive: true, force: true });
112+
}
113+
fs.writeFileSync(executable, pristine);
114+
if (seal) {
115+
throw new Error(`Source protection failed: ${e.message}`);
116+
}
117+
this.$logger.warn(
118+
`Couldn't pack app.nsbundle, the app ships as a plain folder: ${e.message}`,
119+
);
120+
return;
121+
}
122+
// app/ is served from the bundle; as a link to the unpacked files, paths native
123+
// code builds from the app folder (fonts, addons) still open
124+
fs.rmSync(app, { recursive: true, force: true });
125+
fs.symlinkSync(path.basename(unpacked), app);
126+
this.$logger.info(
127+
`Packed the app into ${output}${seal ? " (source protected)" : ""}.`,
128+
);
129+
}
130+
131+
private async run(command: string, args: string[], cwd: string) {
132+
const result = await this.$childProcess.spawnFromEvent(
133+
command,
134+
args,
135+
"close",
136+
{ cwd },
137+
{ throwError: false },
138+
);
139+
if (result.exitCode !== 0) {
140+
throw new Error(
141+
`${path.basename(command)} failed (exit code ${result.exitCode}): ${(result.stderr || result.stdout).trim()}`,
142+
);
143+
}
144+
return result;
145+
}
146+
}

‎lib/services/linux-project-service.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
nativeUnitName,
3232
writeTypingsIndex,
3333
} from "./linux-native-code";
34+
import { LinuxAppBundler } from "./linux-app-bundle";
3435

3536
/** App_Resources/Linux files consumed by the build (desktop entry, icon, AppStream, metadata filters). */
3637
const BUILD_INPUTS = [
@@ -60,7 +61,7 @@ const RUNTIME_ARCH: Record<string, string> = {
6061
* tools/<x64|arm64>/ metadata generator for app / plugin native code
6162
*
6263
* Native code (see linux-native-code.ts) is built into `lib/` and `metadata/`
63-
* next to the executable.
64+
* next to the executable. Release builds pack app/ into app.nsbundle (linux-app-bundle.ts).
6465
*/
6566
export class LinuxProjectService
6667
extends projectServiceBaseLib.PlatformProjectServiceBase
@@ -268,6 +269,22 @@ export class LinuxProjectService
268269

269270
await this.buildNativeCode(projectData, stage, release);
270271

272+
// debug builds keep the plain app/ for LiveSync and HMR
273+
if (release) {
274+
const options = this.$options as any;
275+
await new LinuxAppBundler(this.$childProcess, this.$logger).pack({
276+
stage,
277+
executable,
278+
toolsDir: this.toolsDir(projectData, arch),
279+
config: projectData.nsConfig?.linux ?? {},
280+
sourceProtect: buildConfig?.sourceProtect ?? options.sourceProtect,
281+
keyHex:
282+
buildConfig?.sourceProtectKeyHex ||
283+
options.sourceProtectKeyHex ||
284+
process.env.NS_LINUX_BUNDLE_KEY,
285+
});
286+
}
287+
271288
this.stageDesktopEntry(stage, projectData, release);
272289

273290
if (release) {

‎test/services/linux-app-bundle.ts‎

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import * as fs from "fs";
2+
import * as os from "os";
3+
import * as path from "path";
4+
import { assert } from "chai";
5+
import { LinuxAppBundler } from "../../lib/services/linux-app-bundle";
6+
import * as stubs from "../stubs";
7+
8+
/** Fakes ns-bundle: `pack` writes the bundle and patches the executable. */
9+
function fakeTool(exitCode = 0) {
10+
const calls: string[][] = [];
11+
return {
12+
calls,
13+
spawnFromEvent: async (_command: string, args: string[]) => {
14+
calls.push(args);
15+
if (exitCode === 0 && args[0] === "pack") {
16+
const output = args[args.indexOf("--output") + 1];
17+
fs.writeFileSync(output, "NSB2");
18+
fs.mkdirSync(`${output}.unpacked/fonts`, { recursive: true });
19+
fs.writeFileSync(args[args.indexOf("--exe") + 1], "patched");
20+
} else if (args[0] === "pack") {
21+
// a failed run may leave a half patched executable
22+
fs.writeFileSync(args[args.indexOf("--exe") + 1], "half");
23+
}
24+
return { exitCode, stdout: "ok", stderr: exitCode ? "boom" : "" };
25+
},
26+
};
27+
}
28+
29+
describe("linuxAppBundle", () => {
30+
let root: string;
31+
let stage: string;
32+
let executable: string;
33+
let toolsDir: string;
34+
35+
beforeEach(() => {
36+
root = fs.mkdtempSync(path.join(os.tmpdir(), "ns-linux-bundle-"));
37+
stage = path.join(root, "stage");
38+
toolsDir = path.join(root, "tools");
39+
executable = path.join(stage, "app-exe");
40+
fs.mkdirSync(path.join(stage, "app"), { recursive: true });
41+
fs.writeFileSync(path.join(stage, "app", "bundle.js"), "");
42+
fs.writeFileSync(executable, "runtime");
43+
fs.mkdirSync(toolsDir);
44+
fs.writeFileSync(path.join(toolsDir, "ns-bundle"), "");
45+
});
46+
47+
afterEach(() => fs.rmSync(root, { recursive: true, force: true }));
48+
49+
const pack = (proc: any, extra: any = {}) =>
50+
new LinuxAppBundler(proc, new stubs.LoggerStub()).pack({
51+
stage,
52+
executable,
53+
toolsDir,
54+
config: {},
55+
...extra,
56+
});
57+
58+
it("bundles by default and links app/ to the unpacked files", async () => {
59+
const proc = fakeTool();
60+
await pack(proc);
61+
const [args] = proc.calls;
62+
assert.equal(args[0], "pack");
63+
assert.notInclude(args, "--seal");
64+
assert.includeMembers(args, [
65+
"bundleIntegrity=on",
66+
"onlyLoadAppFromBundle=on",
67+
"inspector=off",
68+
"envOverrides=off",
69+
]);
70+
assert.equal(
71+
fs.readlinkSync(path.join(stage, "app")),
72+
"app.nsbundle.unpacked",
73+
);
74+
});
75+
76+
it("seals with the given key and unpack globs", async () => {
77+
const proc = fakeTool();
78+
await pack(proc, {
79+
sourceProtect: true,
80+
keyHex: "ab".repeat(32),
81+
config: { bundleUnpack: ["data/**"], fuses: { inspector: true } },
82+
});
83+
const [args] = proc.calls;
84+
assert.includeMembers(args, [
85+
"--seal",
86+
"--key-hex",
87+
"ab".repeat(32),
88+
"--no-default-unpack",
89+
"data/**",
90+
"inspector=on",
91+
]);
92+
});
93+
94+
it("only sets fuses with bundle: false", async () => {
95+
const proc = fakeTool();
96+
await pack(proc, { config: { bundle: false } });
97+
assert.equal(proc.calls[0][0], "fuses");
98+
assert.includeMembers(proc.calls[0], [
99+
"bundleIntegrity=off",
100+
"inspector=off",
101+
]);
102+
assert.isTrue(fs.statSync(path.join(stage, "app")).isDirectory());
103+
});
104+
105+
it("keeps the plain folder when bundling fails", async () => {
106+
await pack(fakeTool(1));
107+
assert.isTrue(fs.statSync(path.join(stage, "app")).isDirectory());
108+
assert.isFalse(fs.existsSync(path.join(stage, "app.nsbundle")));
109+
assert.equal(fs.readFileSync(executable, "utf8"), "runtime");
110+
});
111+
112+
it("fails the build when source protection fails", async () => {
113+
let error: Error;
114+
await pack(fakeTool(1), { sourceProtect: true }).catch((e) => (error = e));
115+
assert.match(error.message, /Source protection failed/);
116+
assert.equal(fs.readFileSync(executable, "utf8"), "runtime");
117+
fs.rmSync(path.join(toolsDir, "ns-bundle"));
118+
error = undefined;
119+
await pack(fakeTool(), {
120+
config: { sourceProtect: true },
121+
}).catch((e) => (error = e));
122+
assert.match(error.message, /no ns-bundle/);
123+
// a plain release still builds without the tool
124+
await pack(fakeTool());
125+
});
126+
127+
it("lets --no-source-protect override the config", async () => {
128+
const proc = fakeTool();
129+
await pack(proc, { sourceProtect: false, config: { sourceProtect: true } });
130+
assert.notInclude(proc.calls[0], "--seal");
131+
});
132+
});

0 commit comments

Comments
 (0)