Skip to content

Commit a399bbd

Browse files
committed
feat(vite): allow cleartext HTTP to the dev server in Android debug HMR builds
A Vite HMR app on Android loads its code from the dev server over plain HTTP, which Android blocks by default from API 28. For a debug build with HMR on and the Vite bundler, the native prepare now writes a debug source set manifest (platforms/android/app/src/debug/AndroidManifest.xml) with android:usesCleartextTraffic="true" and tools:replace for it. An app that ships its own debug manifest in App_Resources gets the attribute added to the copied file instead. App_Resources is never modified. Any other prepare (release, --no-hmr, another bundler) removes the file the CLI wrote. The Android project's change check compares the wanted state with the native project and marks app resources changed when they differ, so switching rebuilds the app. A networkSecurityConfig of the app's own takes precedence over the attribute and has to allow the dev host itself.
1 parent 8aad4ea commit a399bbd

5 files changed

Lines changed: 273 additions & 2 deletions

File tree

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

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,14 @@ import {
4646
} from "../definitions/gradle";
4747
import { IInjector } from "../common/definitions/yok";
4848
import { injector } from "../common/yok";
49+
import { IProjectChangesInfo } from "../definitions/project-changes";
50+
import {
51+
DEV_CLEARTEXT_MARKER,
52+
devCleartextManifest,
53+
hasDevCleartext,
54+
needsDevCleartext,
55+
withDevCleartext,
56+
} from "./android/dev-cleartext-manifest";
4957
import { INotConfiguredEnvOptions } from "../common/definitions/commands";
5058

5159
interface NativeDependency {
@@ -845,8 +853,60 @@ export class AndroidProjectService
845853
await adb.executeShellCommand(["rm", "-rf", deviceRootPath]);
846854
}
847855

848-
public async checkForChanges(): Promise<void> {
849-
// Nothing android specific to check yet.
856+
public async checkForChanges(
857+
changesInfo: IProjectChangesInfo,
858+
prepareData: IPrepareData,
859+
projectData: IProjectData,
860+
): Promise<void> {
861+
const manifestPath = this.getDebugManifestPath(projectData);
862+
const current = this.$fs.exists(manifestPath)
863+
? this.$fs.readText(manifestPath)
864+
: null;
865+
// The build is what carries the permission, so a change has to rebuild.
866+
if (
867+
needsDevCleartext(projectData, prepareData) !== hasDevCleartext(current)
868+
) {
869+
changesInfo.appResourcesChanged = true;
870+
}
871+
}
872+
873+
/**
874+
* Lets a Vite HMR debug build fetch its code from the dev server over
875+
* plain HTTP, through the debug source set's manifest in the native
876+
* project. Runs after `prepareAppResources`, which restores the app's own
877+
* debug manifest, if any, from App_Resources.
878+
*/
879+
public prepareDevServerAccess(
880+
projectData: IProjectData,
881+
prepareData: IPrepareData,
882+
): void {
883+
const manifestPath = this.getDebugManifestPath(projectData);
884+
const current = this.$fs.exists(manifestPath)
885+
? this.$fs.readText(manifestPath)
886+
: null;
887+
if (!needsDevCleartext(projectData, prepareData)) {
888+
if (current !== null && current.includes(DEV_CLEARTEXT_MARKER)) {
889+
this.$fs.deleteFile(manifestPath);
890+
}
891+
return;
892+
}
893+
if (hasDevCleartext(current)) {
894+
return;
895+
}
896+
this.$fs.writeFile(
897+
manifestPath,
898+
current === null ? devCleartextManifest() : withDevCleartext(current),
899+
);
900+
}
901+
902+
private getDebugManifestPath(projectData: IProjectData): string {
903+
return path.join(
904+
this.getPlatformData(projectData).projectRoot,
905+
this.$options.hostProjectModuleName,
906+
constants.SRC_DIR,
907+
"debug",
908+
constants.MANIFEST_FILE_NAME,
909+
);
850910
}
851911

852912
public getDeploymentTarget(projectData: IProjectData): semver.SemVer {
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { IProjectData } from "../../definitions/project";
2+
3+
/**
4+
* Identifies a debug manifest whose cleartext permission the CLI wrote, so a
5+
* later prepare that doesn't need it can take it out again.
6+
*/
7+
export const DEV_CLEARTEXT_MARKER =
8+
"nativescript-cli: cleartext HTTP to the Vite dev server (debug HMR runs only)";
9+
10+
const TOOLS_NS = 'xmlns:tools="http://schemas.android.com/tools"';
11+
const CLEARTEXT_ATTRIBUTE = "android:usesCleartextTraffic";
12+
13+
/**
14+
* A Vite HMR app loads its code from the dev server over plain HTTP, which
15+
* Android blocks by default from API 28.
16+
*/
17+
export function needsDevCleartext(
18+
projectData: Pick<IProjectData, "bundler">,
19+
prepareData: { hmr?: boolean; release?: boolean },
20+
): boolean {
21+
return (
22+
projectData.bundler === "vite" && !!prepareData.hmr && !prepareData.release
23+
);
24+
}
25+
26+
export function hasDevCleartext(manifest: string | null): boolean {
27+
return !!manifest && manifest.includes(DEV_CLEARTEXT_MARKER);
28+
}
29+
30+
/** The debug source set's manifest when the app ships none of its own. */
31+
export function devCleartextManifest(): string {
32+
return [
33+
'<?xml version="1.0" encoding="utf-8"?>',
34+
`<!-- ${DEV_CLEARTEXT_MARKER} -->`,
35+
`<manifest xmlns:android="http://schemas.android.com/apk/res/android" ${TOOLS_NS}>`,
36+
`\t<application ${CLEARTEXT_ATTRIBUTE}="true" tools:replace="${CLEARTEXT_ATTRIBUTE}" />`,
37+
"</manifest>",
38+
"",
39+
].join("\n");
40+
}
41+
42+
/**
43+
* The app's own debug manifest with the permission added. `tools:replace`
44+
* lets it win over a main manifest that sets the attribute itself.
45+
*/
46+
export function withDevCleartext(manifest: string): string {
47+
let result = manifest;
48+
const manifestTag = /<manifest\b[^>]*>/.exec(result);
49+
if (!manifestTag) {
50+
return result;
51+
}
52+
if (!manifestTag[0].includes("xmlns:tools=")) {
53+
const withTools = manifestTag[0].replace(
54+
/^<manifest\b/,
55+
`<manifest ${TOOLS_NS}`,
56+
);
57+
result = result.replace(manifestTag[0], withTools);
58+
}
59+
60+
const applicationTag = /<application\b[^>]*?(\/?)>/.exec(result);
61+
if (!applicationTag) {
62+
result = result.replace(
63+
/<\/manifest>/,
64+
`\t<application ${CLEARTEXT_ATTRIBUTE}="true" tools:replace="${CLEARTEXT_ATTRIBUTE}" />\n</manifest>`,
65+
);
66+
} else {
67+
let tag = applicationTag[0];
68+
const value = new RegExp(`${CLEARTEXT_ATTRIBUTE}\\s*=\\s*"[^"]*"`);
69+
tag = value.test(tag)
70+
? tag.replace(value, `${CLEARTEXT_ATTRIBUTE}="true"`)
71+
: tag.replace(
72+
/^<application\b/,
73+
`<application ${CLEARTEXT_ATTRIBUTE}="true"`,
74+
);
75+
const replace = /tools:replace\s*=\s*"([^"]*)"/.exec(tag);
76+
if (!replace) {
77+
tag = tag.replace(
78+
/^<application\b/,
79+
`<application tools:replace="${CLEARTEXT_ATTRIBUTE}"`,
80+
);
81+
} else if (
82+
!replace[1]
83+
.split(",")
84+
.map((name) => name.trim())
85+
.includes(CLEARTEXT_ATTRIBUTE)
86+
) {
87+
tag = tag.replace(
88+
replace[0],
89+
`tools:replace="${replace[1]},${CLEARTEXT_ATTRIBUTE}"`,
90+
);
91+
}
92+
result = result.replace(applicationTag[0], tag);
93+
}
94+
95+
return result.replace(
96+
/(<manifest\b)/,
97+
`<!-- ${DEV_CLEARTEXT_MARKER} -->\n$1`,
98+
);
99+
}

‎lib/services/bundler/bundler.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,14 @@ declare global {
156156
*/
157157
prepareAppResources(projectData: IProjectData): void;
158158

159+
/**
160+
* Lets a dev build reach the bundler's dev server. Runs after `prepareAppResources`.
161+
*/
162+
prepareDevServerAccess?(
163+
projectData: IProjectData,
164+
prepareData: TPrepareData,
165+
): void;
166+
159167
/**
160168
* Defines if current platform is prepared (i.e. if <project dir>/platforms/<platform> dir exists).
161169
* @param {string} projectRoot The project directory (path where root's package.json is located).

‎lib/services/platform/prepare-native-platform-service.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ export class PrepareNativePlatformService
5050

5151
if (!this.$options.hostProjectPath) {
5252
platformData.platformProjectService.prepareAppResources(projectData);
53+
platformData.platformProjectService.prepareDevServerAccess?.(
54+
projectData,
55+
prepareData
56+
);
5357
}
5458

5559
if (hasChangesRequirePrepare || this.$options.hostProjectPath) {
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import { assert } from "chai";
2+
import {
3+
DEV_CLEARTEXT_MARKER,
4+
devCleartextManifest,
5+
hasDevCleartext,
6+
needsDevCleartext,
7+
withDevCleartext,
8+
} from "../../../lib/services/android/dev-cleartext-manifest";
9+
10+
describe("dev-cleartext-manifest", () => {
11+
describe("needsDevCleartext", () => {
12+
it("is true only for Vite debug HMR runs", () => {
13+
assert.isTrue(
14+
needsDevCleartext({ bundler: "vite" }, { hmr: true, release: false }),
15+
);
16+
assert.isFalse(
17+
needsDevCleartext({ bundler: "vite" }, { hmr: true, release: true }),
18+
);
19+
assert.isFalse(
20+
needsDevCleartext({ bundler: "vite" }, { hmr: false, release: false }),
21+
);
22+
assert.isFalse(
23+
needsDevCleartext(
24+
{ bundler: "webpack" },
25+
{ hmr: true, release: false },
26+
),
27+
);
28+
});
29+
});
30+
31+
describe("devCleartextManifest", () => {
32+
it("permits cleartext and overrides a main manifest's value", () => {
33+
const manifest = devCleartextManifest();
34+
assert.include(manifest, 'android:usesCleartextTraffic="true"');
35+
assert.include(manifest, 'tools:replace="android:usesCleartextTraffic"');
36+
assert.include(
37+
manifest,
38+
'xmlns:tools="http://schemas.android.com/tools"',
39+
);
40+
assert.isTrue(hasDevCleartext(manifest));
41+
});
42+
});
43+
44+
describe("hasDevCleartext", () => {
45+
it("only recognizes a manifest the CLI marked", () => {
46+
assert.isFalse(hasDevCleartext(null));
47+
assert.isFalse(
48+
hasDevCleartext(
49+
'<manifest><application android:usesCleartextTraffic="true"/></manifest>',
50+
),
51+
);
52+
});
53+
});
54+
55+
describe("withDevCleartext", () => {
56+
it("adds the attribute, tools:replace and the tools namespace to the app's debug manifest", () => {
57+
const result = withDevCleartext(
58+
[
59+
'<?xml version="1.0" encoding="utf-8"?>',
60+
'<manifest xmlns:android="http://schemas.android.com/apk/res/android">',
61+
'\t<application android:debuggable="true">',
62+
'\t\t<activity android:name="a.B"/>',
63+
"\t</application>",
64+
"</manifest>",
65+
].join("\n"),
66+
);
67+
assert.include(result, 'xmlns:tools="http://schemas.android.com/tools"');
68+
assert.match(
69+
result,
70+
/<application tools:replace="android:usesCleartextTraffic" android:usesCleartextTraffic="true" android:debuggable="true">/,
71+
);
72+
assert.include(result, '<activity android:name="a.B"/>');
73+
assert.include(result, DEV_CLEARTEXT_MARKER);
74+
assert.match(result, /^<\?xml/);
75+
});
76+
77+
it("turns an explicit false into true and extends an existing tools:replace", () => {
78+
const result = withDevCleartext(
79+
'<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"><application android:usesCleartextTraffic="false" tools:replace="android:label"/></manifest>',
80+
);
81+
assert.include(result, 'android:usesCleartextTraffic="true"');
82+
assert.notInclude(result, 'usesCleartextTraffic="false"');
83+
assert.include(
84+
result,
85+
'tools:replace="android:label,android:usesCleartextTraffic"',
86+
);
87+
assert.equal(result.match(/xmlns:tools=/g).length, 1);
88+
});
89+
90+
it("adds an application element when the manifest has none", () => {
91+
const result = withDevCleartext(
92+
'<manifest xmlns:android="http://schemas.android.com/apk/res/android">\n\t<uses-permission android:name="x"/>\n</manifest>',
93+
);
94+
assert.match(
95+
result,
96+
/<application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic" \/>\n<\/manifest>/,
97+
);
98+
});
99+
});
100+
});

0 commit comments

Comments
 (0)