@hot-updater/android-helper 1.2.0-rc.3 → 1.2.0-rc.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +657 -778
- package/dist/index.d.cts +143 -123
- package/dist/index.d.mts +143 -123
- package/dist/index.mjs +648 -771
- package/package.json +5 -4
package/dist/index.mjs
CHANGED
|
@@ -4,122 +4,40 @@ import fs from "fs";
|
|
|
4
4
|
import { ExecaError, execa } from "execa";
|
|
5
5
|
import os from "os";
|
|
6
6
|
import JSZip from "jszip";
|
|
7
|
+
import { createRequire } from "module";
|
|
8
|
+
import { SANDBOX_ACTIVITY, SANDBOX_APPLICATION_ID_SUFFIX, SANDBOX_META_DATA, SANDBOX_URL_SCHEME_META_DATA, sandboxChannelOf, sandboxUrlSchemeOf } from "@hot-updater/protocol/native-artifact";
|
|
9
|
+
import { XMLParser } from "fast-xml-parser";
|
|
7
10
|
import crypto from "crypto";
|
|
8
11
|
import { pipeline } from "stream/promises";
|
|
9
12
|
import { createInflateRaw } from "zlib";
|
|
10
|
-
|
|
11
|
-
|
|
13
|
+
//#region src/utils/gradlePhase.ts
|
|
14
|
+
/** `> Task :app:compileReleaseKotlin`, with an outcome such as `UP-TO-DATE`. */
|
|
15
|
+
const TASK = /^> Task (:\S+)/;
|
|
16
|
+
const CONFIGURE = /^> Configure project (:\S*)/;
|
|
17
|
+
/**
|
|
18
|
+
* Reads the phase of a Gradle build from its plain console output: the
|
|
19
|
+
* task it runs, after how many it has run, such as
|
|
20
|
+
* `312 tasks · :app:mergeReleaseResources`.
|
|
21
|
+
*/
|
|
22
|
+
const createGradlePhaseReader = () => {
|
|
23
|
+
let tasks = 0;
|
|
24
|
+
return (line) => {
|
|
25
|
+
const task = TASK.exec(line)?.[1];
|
|
26
|
+
if (task) {
|
|
27
|
+
tasks += 1;
|
|
28
|
+
return `${tasks} task${tasks === 1 ? "" : "s"} · ${task}`;
|
|
29
|
+
}
|
|
30
|
+
const project = CONFIGURE.exec(line)?.[1];
|
|
31
|
+
if (project) return `Configuring ${project}`;
|
|
32
|
+
if (line.startsWith("Starting a Gradle Daemon")) return "Starting the Gradle daemon";
|
|
33
|
+
if (line.startsWith("Downloading https://services.gradle.org/")) return "Downloading Gradle";
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
//#endregion
|
|
12
37
|
//#region src/utils/createGradleLogger.ts
|
|
13
38
|
const createGradleLogger = ({ logPrefix }) => new BuildLogger({
|
|
14
39
|
logPrefix,
|
|
15
|
-
|
|
16
|
-
"error:",
|
|
17
|
-
"Error:",
|
|
18
|
-
"ERROR:",
|
|
19
|
-
"> Task :",
|
|
20
|
-
"BUILD FAILED",
|
|
21
|
-
"BUILD SUCCESSFUL",
|
|
22
|
-
"FAILURE: Build failed with an exception.",
|
|
23
|
-
"* What went wrong:",
|
|
24
|
-
"Execution failed for task",
|
|
25
|
-
"Could not resolve",
|
|
26
|
-
"Failed to",
|
|
27
|
-
"Unable to load script",
|
|
28
|
-
"Metro encountered an error",
|
|
29
|
-
"React Native CLI",
|
|
30
|
-
"Android resource compilation failed",
|
|
31
|
-
"Duplicate class",
|
|
32
|
-
"Program type already present",
|
|
33
|
-
"actionable tasks:",
|
|
34
|
-
"Deprecated Gradle features were used",
|
|
35
|
-
":app:configureCMake",
|
|
36
|
-
":app:buildCMake",
|
|
37
|
-
":app:compileDebugKotlin",
|
|
38
|
-
":app:compileReleaseKotlin",
|
|
39
|
-
":app:compileDebugJavaWithJavac",
|
|
40
|
-
":app:compileReleaseJavaWithJavac",
|
|
41
|
-
":app:mergeDebugResources",
|
|
42
|
-
":app:mergeReleaseResources",
|
|
43
|
-
":app:processDebugResources",
|
|
44
|
-
":app:processReleaseResources",
|
|
45
|
-
":app:packageDebug",
|
|
46
|
-
":app:packageRelease",
|
|
47
|
-
":app:assembleDebug",
|
|
48
|
-
":app:assembleRelease"
|
|
49
|
-
],
|
|
50
|
-
progressStages: [
|
|
51
|
-
[
|
|
52
|
-
"buildKotlinToolingMetadata",
|
|
53
|
-
"generateAutolinkingNewArchitectureFiles",
|
|
54
|
-
"generateAutolinkingPackageList",
|
|
55
|
-
"generateCodegenSchemaFromJavaScript",
|
|
56
|
-
"generateCodegenArtifactsFromSchema",
|
|
57
|
-
"generateReactNativeEntryPoint"
|
|
58
|
-
],
|
|
59
|
-
[
|
|
60
|
-
"createBundleReleaseJsAndAssets",
|
|
61
|
-
"bundleReleaseJsAndAssets",
|
|
62
|
-
"bundleDebugJsAndAssets"
|
|
63
|
-
],
|
|
64
|
-
[
|
|
65
|
-
"generateReleaseResValues",
|
|
66
|
-
"generateDebugResValues",
|
|
67
|
-
"generateReleaseResources",
|
|
68
|
-
"generateDebugResources",
|
|
69
|
-
"mergeReleaseResources",
|
|
70
|
-
"mergeDebugResources"
|
|
71
|
-
],
|
|
72
|
-
[
|
|
73
|
-
"processReleaseResources",
|
|
74
|
-
"processDebugResources",
|
|
75
|
-
"processReleaseManifest",
|
|
76
|
-
"processDebugManifest",
|
|
77
|
-
"processDebugMainManifest",
|
|
78
|
-
"parseReleaseLocalResources",
|
|
79
|
-
"parseDebugLocalResources"
|
|
80
|
-
],
|
|
81
|
-
["compileReleaseKotlin", "compileDebugKotlin"],
|
|
82
|
-
["compileReleaseJavaWithJavac", "compileDebugJavaWithJavac"],
|
|
83
|
-
[
|
|
84
|
-
/configureCMake\w+\[/,
|
|
85
|
-
/buildCMake\w+\[/,
|
|
86
|
-
"mergeReleaseJniLibFolders",
|
|
87
|
-
"mergeDebugJniLibFolders",
|
|
88
|
-
"mergeReleaseNativeLibs",
|
|
89
|
-
"mergeDebugNativeLibs"
|
|
90
|
-
],
|
|
91
|
-
[
|
|
92
|
-
"desugarReleaseFileDependencies",
|
|
93
|
-
"desugarDebugFileDependencies",
|
|
94
|
-
"dexBuilderRelease",
|
|
95
|
-
"dexBuilderDebug",
|
|
96
|
-
"mergeDexRelease",
|
|
97
|
-
"mergeExtDexRelease",
|
|
98
|
-
"mergeExtDexDebug",
|
|
99
|
-
"mergeProjectDexRelease",
|
|
100
|
-
"mergeProjectDexDebug",
|
|
101
|
-
"mergeLibDexRelease",
|
|
102
|
-
"mergeLibDexDebug",
|
|
103
|
-
"mergeDebugGlobalSynthetics",
|
|
104
|
-
"mergeReleaseGlobalSynthetics",
|
|
105
|
-
"transformClassesWithDex"
|
|
106
|
-
],
|
|
107
|
-
[
|
|
108
|
-
"compressReleaseAssets",
|
|
109
|
-
"compressDebugAssets",
|
|
110
|
-
"optimizeReleaseResources",
|
|
111
|
-
"mergeReleaseAssets",
|
|
112
|
-
"mergeDebugAssets"
|
|
113
|
-
],
|
|
114
|
-
[
|
|
115
|
-
"packageRelease",
|
|
116
|
-
"packageDebug",
|
|
117
|
-
"assembleRelease",
|
|
118
|
-
"assembleDebug"
|
|
119
|
-
],
|
|
120
|
-
["bundleRelease", "bundleDebug"],
|
|
121
|
-
["BUILD SUCCESSFUL", /\d+ actionable tasks:/]
|
|
122
|
-
],
|
|
40
|
+
createPhaseReader: createGradlePhaseReader,
|
|
123
41
|
failureSummary: {
|
|
124
42
|
lines: [
|
|
125
43
|
/^e: /,
|
|
@@ -173,26 +91,54 @@ function getTaskNames(moduleName, tasks) {
|
|
|
173
91
|
* Get gradle wrapper command based on platform
|
|
174
92
|
*/
|
|
175
93
|
const getGradleWrapper = () => process.platform.startsWith("win") ? "gradlew.bat" : "./gradlew";
|
|
94
|
+
/** A variable a POSIX shell can't name, as the signing environment's are. */
|
|
95
|
+
const isShellName = (name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
|
|
96
|
+
/**
|
|
97
|
+
* The command that runs the wrapper with `env`. The wrapper's `#!/bin/sh` is
|
|
98
|
+
* dash on Debian and Ubuntu, which silently drops a variable whose name isn't
|
|
99
|
+
* a shell name, such as `ORG_GRADLE_PROJECT_android.injected.signing.store.file`:
|
|
100
|
+
* the build then signs with the project's own config. bash keeps them.
|
|
101
|
+
*/
|
|
102
|
+
const gradleCommand = (env) => {
|
|
103
|
+
const wrapper = getGradleWrapper();
|
|
104
|
+
return wrapper === "./gradlew" && Object.keys(env ?? {}).some((name) => !isShellName(name)) ? ["bash", [wrapper]] : [wrapper, []];
|
|
105
|
+
};
|
|
176
106
|
/**
|
|
177
107
|
* Run gradle build with specified tasks and arguments
|
|
178
108
|
*/
|
|
179
|
-
async function runGradle(
|
|
109
|
+
async function runGradle(args) {
|
|
110
|
+
const logFilePath = await runGradleTasks(args);
|
|
111
|
+
return {
|
|
112
|
+
...await findBuildDirectory({
|
|
113
|
+
androidProjectPath: args.androidProjectPath,
|
|
114
|
+
moduleName: args.appModuleName,
|
|
115
|
+
tasks: args.tasks
|
|
116
|
+
}),
|
|
117
|
+
logFilePath
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Runs tasks that leave no artifact to find, and returns the build log, or null. */
|
|
121
|
+
async function runGradleTasks({ tasks, logPrefix, args, env, androidProjectPath, appModuleName, logHeader = [] }) {
|
|
180
122
|
const gradleArgs = getTaskNames(appModuleName, tasks);
|
|
181
123
|
gradleArgs.push("-x", "lint");
|
|
182
124
|
if (args.extraParams) gradleArgs.push(...args.extraParams);
|
|
183
|
-
p.log.info([
|
|
184
|
-
"Gradle build",
|
|
185
|
-
`Project ${path.relative(getCwd(), androidProjectPath) || "."}`,
|
|
186
|
-
`App module ${appModuleName}`,
|
|
187
|
-
`Tasks ${tasks.join(", ")}`,
|
|
188
|
-
"Command",
|
|
189
|
-
formatCommand([path.basename(getGradleWrapper()), ...gradleArgs])
|
|
190
|
-
].join("\n"));
|
|
191
125
|
if ("port" in args && args.port != null) gradleArgs.push(`-PreactNativeDevServerPort=${args.port}`);
|
|
192
126
|
const logger = createGradleLogger({ logPrefix });
|
|
193
|
-
await logger.start(
|
|
127
|
+
await logger.start({
|
|
128
|
+
title: `Building ${tasks.join(", ")}`,
|
|
129
|
+
header: [
|
|
130
|
+
...logHeader,
|
|
131
|
+
`Project ${path.relative(getCwd(), androidProjectPath) || "."}`,
|
|
132
|
+
`App module ${appModuleName}`,
|
|
133
|
+
`Tasks ${tasks.join(", ")}`,
|
|
134
|
+
`$ ${formatCommand([path.basename(getGradleWrapper()), ...gradleArgs])}`,
|
|
135
|
+
""
|
|
136
|
+
]
|
|
137
|
+
});
|
|
138
|
+
let logFilePath = null;
|
|
194
139
|
try {
|
|
195
|
-
const
|
|
140
|
+
const [command, prefix] = gradleCommand(env);
|
|
141
|
+
const gradle = execa(command, [...prefix, ...gradleArgs], {
|
|
196
142
|
cwd: androidProjectPath,
|
|
197
143
|
env,
|
|
198
144
|
all: true,
|
|
@@ -202,11 +148,13 @@ async function runGradle({ tasks, logPrefix, args, env, androidProjectPath, appM
|
|
|
202
148
|
const [gradleResult, loggingResult] = await Promise.allSettled([gradle, outputStream ? logger.processStream(outputStream) : void 0]);
|
|
203
149
|
if (gradleResult.status === "rejected") throw gradleResult.reason;
|
|
204
150
|
if (loggingResult.status === "rejected") throw loggingResult.reason;
|
|
205
|
-
logger.stop();
|
|
151
|
+
logger.stop(`Built ${tasks.join(", ")}`);
|
|
152
|
+
logFilePath = logger.logFilePath;
|
|
206
153
|
} catch (e) {
|
|
207
154
|
logger.writeError(e);
|
|
208
|
-
|
|
209
|
-
|
|
155
|
+
const reason = describeFailure(e);
|
|
156
|
+
logger.stop(`Build failed · ${reason.replace(/\.$/, "")}`, false);
|
|
157
|
+
throw new BuildFailedError(`Build failed: ${reason}`, {
|
|
210
158
|
logPath: logger.logPath,
|
|
211
159
|
summary: logger.failureSummary,
|
|
212
160
|
cause: e
|
|
@@ -214,11 +162,7 @@ async function runGradle({ tasks, logPrefix, args, env, androidProjectPath, appM
|
|
|
214
162
|
} finally {
|
|
215
163
|
await logger.close();
|
|
216
164
|
}
|
|
217
|
-
return
|
|
218
|
-
androidProjectPath,
|
|
219
|
-
moduleName: appModuleName,
|
|
220
|
-
tasks
|
|
221
|
-
});
|
|
165
|
+
return logFilePath;
|
|
222
166
|
}
|
|
223
167
|
/**
|
|
224
168
|
* Find the build output directory and artifact path
|
|
@@ -511,20 +455,336 @@ const readBuiltVersionCode = async ({ artifactPath, androidProjectPath }) => {
|
|
|
511
455
|
}
|
|
512
456
|
};
|
|
513
457
|
//#endregion
|
|
458
|
+
//#region src/utils/sandboxManifest.ts
|
|
459
|
+
const MAIN = "android.intent.action.MAIN";
|
|
460
|
+
const LAUNCHER = "android.intent.category.LAUNCHER";
|
|
461
|
+
const SHORTCUTS = "android.app.shortcuts";
|
|
462
|
+
const ANDROID = "android:";
|
|
463
|
+
const asArray = (value) => value === void 0 || value === null || value === "" ? [] : Array.isArray(value) ? value : [value];
|
|
464
|
+
const attribute = (element, name) => {
|
|
465
|
+
const value = element[`${ANDROID}${name}`];
|
|
466
|
+
return typeof value === "string" ? value : void 0;
|
|
467
|
+
};
|
|
468
|
+
const filtersOf = (component) => asArray(component["intent-filter"]).map((filter) => ({
|
|
469
|
+
actions: asArray(filter["action"]),
|
|
470
|
+
categories: asArray(filter["category"]),
|
|
471
|
+
data: asArray(filter["data"]),
|
|
472
|
+
attributes: Object.fromEntries(Object.entries(filter).filter(([name]) => name.startsWith(ANDROID)))
|
|
473
|
+
}));
|
|
474
|
+
const opensAsLauncher = ({ actions, categories }) => actions.some((action) => attribute(action, "name") === MAIN) && categories.some((category) => attribute(category, "name") === LAUNCHER);
|
|
475
|
+
/** Task settings a sandbox activity can't share a task with: what, and how to fix it. */
|
|
476
|
+
const taskRefusal = (name, activity) => {
|
|
477
|
+
const launchMode = attribute(activity, "launchMode");
|
|
478
|
+
if (launchMode === "singleInstance" || launchMode === "singleInstancePerTask") return `Sandbox builds don't support launchMode ${launchMode} on the launcher ${name}.\nUse singleTask or the default launch mode.`;
|
|
479
|
+
if (attribute(activity, "taskAffinity") !== void 0) return `Sandbox builds don't support taskAffinity on the launcher ${name}.\nRemove it from this build variant.`;
|
|
480
|
+
const documents = attribute(activity, "documentLaunchMode");
|
|
481
|
+
if (documents !== void 0 && documents !== "none") return `Sandbox builds don't support documentLaunchMode ${documents} on the launcher ${name}.\nRemove it from this build variant.`;
|
|
482
|
+
return null;
|
|
483
|
+
};
|
|
484
|
+
/**
|
|
485
|
+
* The launcher entry of a variant's merged manifest, which already holds what
|
|
486
|
+
* its flavors, build type and libraries declare. It refuses what a sandbox
|
|
487
|
+
* build can't take over: none or several entries, a filter it can't move whole,
|
|
488
|
+
* and task settings its activity can't share a task with.
|
|
489
|
+
*/
|
|
490
|
+
const resolveSandboxLauncher = (mergedManifest) => {
|
|
491
|
+
const application = new XMLParser({
|
|
492
|
+
ignoreAttributes: false,
|
|
493
|
+
attributeNamePrefix: ""
|
|
494
|
+
}).parse(mergedManifest)?.manifest?.application;
|
|
495
|
+
const activities = asArray(application?.["activity"]);
|
|
496
|
+
const aliases = asArray(application?.["activity-alias"]);
|
|
497
|
+
const entries = [...activities.map((element) => ({
|
|
498
|
+
kind: "activity",
|
|
499
|
+
element
|
|
500
|
+
})), ...aliases.map((element) => ({
|
|
501
|
+
kind: "activity-alias",
|
|
502
|
+
element
|
|
503
|
+
}))].flatMap(({ kind, element }) => {
|
|
504
|
+
const filters = filtersOf(element).filter(opensAsLauncher);
|
|
505
|
+
return filters.length === 0 ? [] : [{
|
|
506
|
+
kind,
|
|
507
|
+
element,
|
|
508
|
+
filters
|
|
509
|
+
}];
|
|
510
|
+
});
|
|
511
|
+
const names = entries.map(({ element }) => attribute(element, "name") ?? "?");
|
|
512
|
+
if (entries.length === 0) throw new Error("A sandbox build needs a launcher, and this variant's manifest has none.\nAdd a MAIN + LAUNCHER intent filter to an activity.");
|
|
513
|
+
if (entries.length > 1) throw new Error(`A sandbox build needs one launcher, and this variant has ${names.length}: ${names.join(", ")}.\nKeep one for this build variant.`);
|
|
514
|
+
const { kind, element, filters } = entries[0];
|
|
515
|
+
const name = names[0];
|
|
516
|
+
if (filters.length > 1) throw new Error(`The launcher ${name} has ${filters.length} MAIN + LAUNCHER filters, and a sandbox build can move one.\nKeep one for this build variant.`);
|
|
517
|
+
if (attribute(element, "enabled") === "false") throw new Error(`The launcher ${name} is disabled in the manifest, and a sandbox build can't tell when it would open.\nEnable it for this build variant.`);
|
|
518
|
+
const targetActivity = kind === "activity-alias" ? attribute(element, "targetActivity") : void 0;
|
|
519
|
+
const activity = kind === "activity" ? element : activities.find((item) => attribute(item, "name") === targetActivity);
|
|
520
|
+
if (activity === void 0) throw new Error(`The launcher ${name} targets ${targetActivity ?? "no activity"}, which this variant's manifest doesn't declare.\nFix its android:targetActivity.`);
|
|
521
|
+
const refusal = taskRefusal(name, activity);
|
|
522
|
+
if (refusal !== null) throw new Error(refusal);
|
|
523
|
+
const launcherProcess = attribute(activity, "process");
|
|
524
|
+
if (launcherProcess !== void 0 && launcherProcess !== attribute(application ?? {}, "process")) throw new Error(`Sandbox builds run the launcher in the application's process, and ${name} sets android:process ${launcherProcess}.\nRemove it, or set the same android:process on <application>, for this build variant.`);
|
|
525
|
+
const shortcuts = asArray(element["meta-data"]).find((item) => attribute(item, "name") === SHORTCUTS);
|
|
526
|
+
const label = attribute(element, "label");
|
|
527
|
+
const icon = attribute(element, "icon");
|
|
528
|
+
const roundIcon = attribute(element, "roundIcon");
|
|
529
|
+
const shortcutsResource = shortcuts && attribute(shortcuts, "resource");
|
|
530
|
+
return {
|
|
531
|
+
kind,
|
|
532
|
+
name,
|
|
533
|
+
...targetActivity === void 0 ? {} : { targetActivity },
|
|
534
|
+
filter: filters[0],
|
|
535
|
+
...label === void 0 ? {} : { label },
|
|
536
|
+
...icon === void 0 ? {} : { icon },
|
|
537
|
+
...roundIcon === void 0 ? {} : { roundIcon },
|
|
538
|
+
...shortcutsResource === void 0 ? {} : { shortcuts: shortcutsResource }
|
|
539
|
+
};
|
|
540
|
+
};
|
|
541
|
+
const COMPONENTS = [
|
|
542
|
+
"activity",
|
|
543
|
+
"activity-alias",
|
|
544
|
+
"service",
|
|
545
|
+
"receiver"
|
|
546
|
+
];
|
|
547
|
+
/**
|
|
548
|
+
* The URL schemes a variant's merged manifest declares in its components'
|
|
549
|
+
* intent filters, in lower case: a sandbox build registers none of them.
|
|
550
|
+
*/
|
|
551
|
+
const declaredUrlSchemes = (mergedManifest) => {
|
|
552
|
+
const application = new XMLParser({
|
|
553
|
+
ignoreAttributes: false,
|
|
554
|
+
attributeNamePrefix: ""
|
|
555
|
+
}).parse(mergedManifest)?.manifest?.application;
|
|
556
|
+
return COMPONENTS.flatMap((component) => asArray(application?.[component])).flatMap((element) => filtersOf(element).flatMap(({ data }) => data.flatMap((item) => {
|
|
557
|
+
const scheme = attribute(item, "scheme");
|
|
558
|
+
return scheme === void 0 ? [] : [scheme.toLowerCase()];
|
|
559
|
+
})));
|
|
560
|
+
};
|
|
561
|
+
const xml = (text) => text.replace(/&/gu, "&").replace(/"/gu, """).replace(/</gu, "<").replace(/>/gu, ">");
|
|
562
|
+
const attributesOf = (element) => Object.entries(element).filter(([, value]) => typeof value === "string").map(([name, value]) => ` ${name}="${xml(value)}"`).join("");
|
|
563
|
+
/** A launcher filter, element by element: the merger matches a filter by content. */
|
|
564
|
+
const filterXml = ({ actions, categories, data, attributes }, extra = "") => [
|
|
565
|
+
`<intent-filter${attributesOf(attributes)}${extra}>`,
|
|
566
|
+
...actions.map((item) => ` <action${attributesOf(item)} />`),
|
|
567
|
+
...categories.map((item) => ` <category${attributesOf(item)} />`),
|
|
568
|
+
...data.map((item) => ` <data${attributesOf(item)} />`),
|
|
569
|
+
"</intent-filter>"
|
|
570
|
+
].map((line) => ` ${line}`).join("\n");
|
|
571
|
+
const optional = (name, value) => value === void 0 ? "" : ` android:${name}="${xml(value)}"`;
|
|
572
|
+
/**
|
|
573
|
+
* The manifest a sandbox build overlays on the app's. `tools:replace` wins over
|
|
574
|
+
* a channel the app's manifest sets, as an Expo project's does. The launcher's
|
|
575
|
+
* filter, label, icon and static shortcuts move to the sandbox's activity, which
|
|
576
|
+
* also takes the links of `urlScheme`, which its `<meta-data>` names for the
|
|
577
|
+
* build to read; the rest of the app's activity stays, so its own links still
|
|
578
|
+
* reach it.
|
|
579
|
+
* The dev server is plain http, which a project's network security config can
|
|
580
|
+
* still refuse: the screen then says so.
|
|
581
|
+
*/
|
|
582
|
+
const sandboxManifestOverlay = ({ channel, urlScheme, launcher }) => `<?xml version="1.0" encoding="utf-8"?>
|
|
583
|
+
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
|
|
584
|
+
<application android:usesCleartextTraffic="true" tools:replace="android:usesCleartextTraffic">
|
|
585
|
+
<meta-data android:name="com.hotupdater.CHANNEL" android:value="${xml(channel)}" tools:replace="android:value" />
|
|
586
|
+
<meta-data android:name="${SANDBOX_META_DATA}" android:value="true" />
|
|
587
|
+
<activity android:name="${SANDBOX_ACTIVITY}" android:exported="true" android:launchMode="singleTop" android:theme="@style/HotUpdaterSandboxTheme" android:configChanges="density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:enableOnBackInvokedCallback="true"${optional("label", launcher.label)}${optional("icon", launcher.icon)}${optional("roundIcon", launcher.roundIcon)}>
|
|
588
|
+
${filterXml(launcher.filter)}
|
|
589
|
+
<intent-filter>
|
|
590
|
+
<action android:name="android.intent.action.VIEW" />
|
|
591
|
+
<category android:name="android.intent.category.DEFAULT" />
|
|
592
|
+
<category android:name="android.intent.category.BROWSABLE" />
|
|
593
|
+
<data android:scheme="${xml(urlScheme)}" />
|
|
594
|
+
</intent-filter>
|
|
595
|
+
<meta-data android:name="com.hotupdater.sandbox.HOST_ACTIVITY" android:value="${xml(launcher.name)}" />
|
|
596
|
+
<meta-data android:name="${SANDBOX_URL_SCHEME_META_DATA}" android:value="${xml(urlScheme)}" />${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" android:resource="${xml(launcher.shortcuts)}" />`}
|
|
597
|
+
</activity>
|
|
598
|
+
<${launcher.kind} android:name="${xml(launcher.name)}"${optional("targetActivity", launcher.targetActivity)}>
|
|
599
|
+
${filterXml(launcher.filter, " tools:node=\"remove\"")}${launcher.shortcuts === void 0 ? "" : `\n <meta-data android:name="${SHORTCUTS}" tools:node="remove" />`}
|
|
600
|
+
</${launcher.kind}>
|
|
601
|
+
<activity android:name="com.hotupdater.HotUpdaterSandboxRelaunchActivity" android:excludeFromRecents="true" android:exported="false" android:launchMode="singleTask" android:noHistory="true" android:process=":hotupdater_restart" android:theme="@android:style/Theme.NoDisplay" />
|
|
602
|
+
<provider android:name="com.hotupdater.HotUpdaterSandboxProcess" android:authorities="\${applicationId}.hotupdater.sandbox" android:exported="false" />
|
|
603
|
+
</application>
|
|
604
|
+
</manifest>
|
|
605
|
+
`;
|
|
606
|
+
/** Newest first: the manifest of the task that ran last, under `directory`. */
|
|
607
|
+
const manifestsUnder = (directory) => {
|
|
608
|
+
if (!fs.existsSync(directory)) return [];
|
|
609
|
+
return fs.readdirSync(directory, { recursive: true }).map(String).filter((file) => path.basename(file) === "AndroidManifest.xml").map((file) => path.join(directory, file)).sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
|
|
610
|
+
};
|
|
611
|
+
/** The Gradle task that merges a variant's manifest. */
|
|
612
|
+
const mergeManifestTask = (variant) => `process${variant.charAt(0).toUpperCase()}${variant.slice(1)}MainManifest`;
|
|
613
|
+
/**
|
|
614
|
+
* The manifest the merge task of `variant` wrote: AGP 7 and 8 keep it under
|
|
615
|
+
* `build/intermediates/merged_manifest`, in a directory per variant.
|
|
616
|
+
*/
|
|
617
|
+
const readMergedManifest = ({ androidProjectPath, appModuleName, variant }) => {
|
|
618
|
+
const variantDirectory = `${variant.charAt(0).toLowerCase()}${variant.slice(1)}`;
|
|
619
|
+
const intermediates = path.join(androidProjectPath, appModuleName, "build/intermediates");
|
|
620
|
+
const [manifest] = ["merged_manifest", "merged_manifests"].flatMap((name) => manifestsUnder(path.join(intermediates, name, variantDirectory)));
|
|
621
|
+
if (manifest === void 0) throw new Error(`Couldn't find the merged manifest of ${variant} under android/${appModuleName}/build/intermediates.\nBuild the variant once, then try again.`);
|
|
622
|
+
return fs.readFileSync(manifest, "utf-8");
|
|
623
|
+
};
|
|
624
|
+
//#endregion
|
|
625
|
+
//#region src/utils/sandboxGradle.ts
|
|
626
|
+
const UNSUPPORTED_DSL = `Sandbox builds don't support AGP 9's default DSL yet.
|
|
627
|
+
Set android.newDsl=false in android/gradle.properties.`;
|
|
628
|
+
/** The message when the build type has a manifest the overlay would replace. */
|
|
629
|
+
const ownManifest = (manifest) => `A sandbox build can't merge with ${manifest}.\nMove what it declares to src/main/AndroidManifest.xml.`;
|
|
630
|
+
/** The message when no project compiled the SDK from source, which a dev server needs. */
|
|
631
|
+
const PREBUILT_SDK = `This app takes @hot-updater/react-native as a prebuilt AAR, and a sandbox build compiles the SDK from source.
|
|
632
|
+
Add the SDK's autolinked project to this build instead of the AAR.`;
|
|
633
|
+
/** Text as a single-quoted Groovy string. */
|
|
634
|
+
const groovyString = (text) => `'${text.replace(/\\/gu, "\\\\").replace(/'/gu, "\\'").replace(/\n/gu, "\\n")}'`;
|
|
635
|
+
/**
|
|
636
|
+
* The init script of one sandbox build, so no project file changes: on the app
|
|
637
|
+
* module, it appends the sandbox's suffix to defaultConfig, where AGP puts any
|
|
638
|
+
* flavor's and build type's after it, and adds `overlay` to the variant's build
|
|
639
|
+
* type. It runs in `finalizeDsl`, after the project's own settings.
|
|
640
|
+
*/
|
|
641
|
+
const sandboxInitScript = ({ appModuleName, variant, overlay, minVersionCode }) => `// Written by hot-updater for one sandbox build.
|
|
642
|
+
def appModule = ${groovyString(`:${appModuleName}`)}
|
|
643
|
+
def variant = ${groovyString(variant.toLowerCase())}
|
|
644
|
+
def overlay = new File(${groovyString(overlay)})
|
|
645
|
+
def minVersionCode = ${minVersionCode ?? "null"}
|
|
646
|
+
allprojects { project ->
|
|
647
|
+
if (project.path != appModule) return
|
|
648
|
+
// In this build alone: an init script also runs for React Native's included
|
|
649
|
+
// Gradle plugin. The SDK's sandbox script sets this on the project it compiles.
|
|
650
|
+
gradle.taskGraph.whenReady {
|
|
651
|
+
if (!gradle.rootProject.ext.has('hotUpdaterSandboxSdkProject')) {
|
|
652
|
+
throw new GradleException(${groovyString(PREBUILT_SDK)})
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
project.plugins.withId('com.android.application') {
|
|
656
|
+
def components = project.extensions.getByName('androidComponents')
|
|
657
|
+
if (components.pluginVersion.major >= 9 && project.findProperty('android.newDsl')?.toString() != 'false') {
|
|
658
|
+
throw new GradleException(${groovyString(UNSUPPORTED_DSL)})
|
|
659
|
+
}
|
|
660
|
+
components.finalizeDsl { dsl ->
|
|
661
|
+
def buildType = dsl.buildTypes.collect { it.name }
|
|
662
|
+
.findAll { variant.endsWith(it.toLowerCase()) }
|
|
663
|
+
.max { it.length() }
|
|
664
|
+
if (buildType == null) {
|
|
665
|
+
throw new GradleException("No build type of \${project.path} builds variant \${variant}.")
|
|
666
|
+
}
|
|
667
|
+
def manifest = dsl.sourceSets.getByName(buildType).manifest
|
|
668
|
+
def own = manifest.srcFile
|
|
669
|
+
if (own.exists()) {
|
|
670
|
+
throw new GradleException(${groovyString(ownManifest("@MANIFEST@"))}.replace('@MANIFEST@', 'android/' + project.rootDir.toPath().relativize(own.toPath())))
|
|
671
|
+
}
|
|
672
|
+
dsl.defaultConfig.applicationIdSuffix = (dsl.defaultConfig.applicationIdSuffix ?: '') + ${groovyString(SANDBOX_APPLICATION_ID_SUFFIX)}
|
|
673
|
+
manifest.srcFile(overlay)
|
|
674
|
+
if (minVersionCode != null) {
|
|
675
|
+
dsl.defaultConfig.versionCode = Math.max(dsl.defaultConfig.versionCode ?: 0, minVersionCode)
|
|
676
|
+
dsl.productFlavors.each { flavor ->
|
|
677
|
+
if (flavor.versionCode != null) flavor.versionCode = Math.max(flavor.versionCode, minVersionCode)
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
`;
|
|
684
|
+
/**
|
|
685
|
+
* Runs `build` with the Gradle arguments of a scheme: none for a normal one. A
|
|
686
|
+
* sandbox scheme's attach the SDK's sandbox layer and name the init script,
|
|
687
|
+
* written outside the project with its manifest overlay, and removed after.
|
|
688
|
+
* Kotlin compiles from scratch, since the sandbox layer's sources come and go.
|
|
689
|
+
* `readEffectiveManifest` is the variant's merged manifest before the overlay,
|
|
690
|
+
* which the overlay takes the launcher from.
|
|
691
|
+
*/
|
|
692
|
+
const withSandboxGradleArgs = async (scheme, readEffectiveManifest, build, { minVersionCode } = {}) => {
|
|
693
|
+
if (!scheme.sandbox) return build([]);
|
|
694
|
+
if (!scheme.packageName) throw new Error(`The sandbox scheme ${scheme.hotUpdaterSchemeName} sets no packageName, which its URL scheme comes from.\nSet packageName on the scheme.`);
|
|
695
|
+
const effectiveManifest = await readEffectiveManifest();
|
|
696
|
+
const launcher = resolveSandboxLauncher(effectiveManifest);
|
|
697
|
+
const urlScheme = scheme.sandboxUrlScheme ?? sandboxUrlSchemeOf(scheme.packageName);
|
|
698
|
+
if (declaredUrlSchemes(effectiveManifest).includes(urlScheme.toLowerCase())) throw new Error(`The sandbox scheme ${scheme.hotUpdaterSchemeName} registers URL scheme ${urlScheme}, which the app registers itself.\nSet sandbox.urlScheme to a scheme the app doesn't register.`);
|
|
699
|
+
const directory = await fs.promises.mkdtemp(path.join(os.tmpdir(), "hot-updater-sandbox-"));
|
|
700
|
+
try {
|
|
701
|
+
const overlay = path.join(directory, "AndroidManifest.xml");
|
|
702
|
+
const initScript = path.join(directory, "sandbox.init.gradle");
|
|
703
|
+
await fs.promises.writeFile(overlay, sandboxManifestOverlay({
|
|
704
|
+
channel: sandboxChannelOf(scheme.hotUpdaterSchemeName),
|
|
705
|
+
urlScheme,
|
|
706
|
+
launcher
|
|
707
|
+
}));
|
|
708
|
+
await fs.promises.writeFile(initScript, sandboxInitScript({
|
|
709
|
+
appModuleName: scheme.appModuleName,
|
|
710
|
+
variant: scheme.variant,
|
|
711
|
+
overlay,
|
|
712
|
+
...minVersionCode === void 0 ? {} : { minVersionCode }
|
|
713
|
+
}));
|
|
714
|
+
return await build([
|
|
715
|
+
"--init-script",
|
|
716
|
+
initScript,
|
|
717
|
+
`-PhotUpdaterSandbox=${scheme.hotUpdaterSchemeName}`,
|
|
718
|
+
"-Pkotlin.incremental=false"
|
|
719
|
+
]);
|
|
720
|
+
} finally {
|
|
721
|
+
await fs.promises.rm(directory, {
|
|
722
|
+
recursive: true,
|
|
723
|
+
force: true
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
/** The major version of the Android Gradle Plugin the project pins, or null. */
|
|
728
|
+
const readAgpMajor = (androidProjectPath) => {
|
|
729
|
+
const rootBuild = ["build.gradle", "build.gradle.kts"].map((file) => path.join(androidProjectPath, file)).filter((file) => fs.existsSync(file)).map((file) => fs.readFileSync(file, "utf-8")).join("\n");
|
|
730
|
+
const pinned = /com\.android\.tools\.build:gradle:(\d+)/u.exec(rootBuild);
|
|
731
|
+
if (pinned) return Number(pinned[1]);
|
|
732
|
+
try {
|
|
733
|
+
const manifest = createRequire(path.join(androidProjectPath, "package.json")).resolve("react-native/package.json");
|
|
734
|
+
const catalog = fs.readFileSync(path.join(path.dirname(manifest), "gradle/libs.versions.toml"), "utf-8");
|
|
735
|
+
const agp = /^\s*agp\s*=\s*"(\d+)/mu.exec(catalog);
|
|
736
|
+
return agp ? Number(agp[1]) : null;
|
|
737
|
+
} catch {
|
|
738
|
+
return null;
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
/**
|
|
742
|
+
* Why a sandbox build of a scheme can't work, read from the project's files
|
|
743
|
+
* before anything is built, or null. The init script checks again, with what
|
|
744
|
+
* Gradle actually resolved.
|
|
745
|
+
*/
|
|
746
|
+
const findSandboxGradleBlocker = ({ variant = "Release", appModuleName = "app" }) => {
|
|
747
|
+
const androidProjectPath = path.join(getCwd(), "android");
|
|
748
|
+
if (!fs.existsSync(androidProjectPath)) return null;
|
|
749
|
+
const properties = path.join(androidProjectPath, "gradle.properties");
|
|
750
|
+
const newDsl = fs.existsSync(properties) ? /^\s*android\.newDsl\s*=\s*(\S+)/mu.exec(fs.readFileSync(properties, "utf-8"))?.[1] : void 0;
|
|
751
|
+
if (newDsl === "true" || newDsl === void 0 && (readAgpMajor(androidProjectPath) ?? 0) >= 9) return UNSUPPORTED_DSL;
|
|
752
|
+
const buildType = /([A-Z]?[a-z0-9]+)$/u.exec(variant)?.[1]?.toLowerCase();
|
|
753
|
+
const manifest = `${appModuleName}/src/${buildType}/AndroidManifest.xml`;
|
|
754
|
+
return buildType && fs.existsSync(path.join(androidProjectPath, manifest)) ? ownManifest(`android/${manifest}`) : null;
|
|
755
|
+
};
|
|
756
|
+
//#endregion
|
|
514
757
|
//#region src/buildAndroid.ts
|
|
515
|
-
const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials }) => {
|
|
758
|
+
const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), credentials, logHeader, minVersionCode }) => {
|
|
516
759
|
const androidProjectPath = path.join(getCwd(), "android");
|
|
517
|
-
const
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
760
|
+
const env = await resolveGradleSigningEnv({
|
|
761
|
+
schemeConfig,
|
|
762
|
+
credentials
|
|
763
|
+
});
|
|
764
|
+
const result = await withSandboxGradleArgs(schemeConfig, async () => {
|
|
765
|
+
await runGradleTasks({
|
|
766
|
+
args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`] },
|
|
767
|
+
env,
|
|
768
|
+
appModuleName: schemeConfig.appModuleName,
|
|
769
|
+
tasks: [mergeManifestTask(schemeConfig.variant)],
|
|
770
|
+
logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-manifest`,
|
|
771
|
+
androidProjectPath,
|
|
772
|
+
logHeader
|
|
773
|
+
});
|
|
774
|
+
return readMergedManifest({
|
|
775
|
+
androidProjectPath,
|
|
776
|
+
appModuleName: schemeConfig.appModuleName,
|
|
777
|
+
variant: schemeConfig.variant
|
|
778
|
+
});
|
|
779
|
+
}, (sandboxArgs) => runGradle({
|
|
780
|
+
args: { extraParams: [`-PMIN_BUNDLE_ID=${minBundleId}`, ...sandboxArgs] },
|
|
781
|
+
env,
|
|
523
782
|
appModuleName: schemeConfig.appModuleName,
|
|
524
783
|
tasks: schemeConfig.aab ? [`bundle${schemeConfig.variant}`] : [`assemble${schemeConfig.variant}`],
|
|
525
784
|
logPrefix: `android-${schemeConfig.hotUpdaterSchemeName}-build`,
|
|
526
|
-
androidProjectPath
|
|
527
|
-
|
|
785
|
+
androidProjectPath,
|
|
786
|
+
logHeader
|
|
787
|
+
}), minVersionCode === void 0 ? {} : { minVersionCode });
|
|
528
788
|
return {
|
|
529
789
|
...result,
|
|
530
790
|
builtApp: await readBuiltApp({
|
|
@@ -534,6 +794,105 @@ const buildAndroid = async ({ schemeConfig, minBundleId = createMinBundleId(), c
|
|
|
534
794
|
};
|
|
535
795
|
};
|
|
536
796
|
//#endregion
|
|
797
|
+
//#region src/device.ts
|
|
798
|
+
/** The SDK's adb, or the one on the PATH without an SDK in the environment. */
|
|
799
|
+
const adbPath = () => {
|
|
800
|
+
const sdk = process.env["ANDROID_HOME"] || process.env["ANDROID_SDK_ROOT"];
|
|
801
|
+
const executable = process.platform.startsWith("win") ? "adb.exe" : "adb";
|
|
802
|
+
const fromSdk = sdk && path.join(sdk, "platform-tools", executable);
|
|
803
|
+
return fromSdk && fs.existsSync(fromSdk) ? fromSdk : executable;
|
|
804
|
+
};
|
|
805
|
+
const adb = async (args) => {
|
|
806
|
+
try {
|
|
807
|
+
return (await execa(adbPath(), args)).stdout;
|
|
808
|
+
} catch (error) {
|
|
809
|
+
const { code, stderr, stdout, shortMessage } = error;
|
|
810
|
+
if (code === "ENOENT") throw new Error("adb isn't installed.\nInstall Android platform-tools, or set ANDROID_HOME.");
|
|
811
|
+
throw new Error(stderr?.trim() || stdout?.trim() || shortMessage || String(error));
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
/** What `adb devices` lists. */
|
|
815
|
+
const listAdbDevices = async () => (await adb(["devices"])).split("\n").slice(1).map((line) => line.trim().split(/\s+/u)).flatMap(([serial, state]) => serial && state ? [{
|
|
816
|
+
serial,
|
|
817
|
+
state
|
|
818
|
+
}] : []);
|
|
819
|
+
/**
|
|
820
|
+
* The device to install on: `serial`, as adb's own `ANDROID_SERIAL` names it
|
|
821
|
+
* too, or else the only one that takes commands.
|
|
822
|
+
*/
|
|
823
|
+
const selectAdbDevice = (devices, serial = process.env["ANDROID_SERIAL"] || void 0) => {
|
|
824
|
+
if (serial !== void 0) {
|
|
825
|
+
const device = devices.find((candidate) => candidate.serial === serial);
|
|
826
|
+
if (device === void 0) throw new Error(`${serial} isn't connected.\nList them: adb devices`);
|
|
827
|
+
if (device.state !== "device") throw new Error(`${serial} is ${device.state}.\nList them: adb devices`);
|
|
828
|
+
return device;
|
|
829
|
+
}
|
|
830
|
+
const ready = devices.filter(({ state }) => state === "device");
|
|
831
|
+
const [only] = ready;
|
|
832
|
+
if (only === void 0) throw new Error("No Android device or emulator is connected.\nStart an emulator or connect a phone, then run this again.");
|
|
833
|
+
if (ready.length > 1) throw new Error([
|
|
834
|
+
`${ready.length} Android devices are connected:`,
|
|
835
|
+
...ready.map(({ serial }) => ` ${serial}`),
|
|
836
|
+
"Pick one with --device <serial>."
|
|
837
|
+
].join("\n"));
|
|
838
|
+
return only;
|
|
839
|
+
};
|
|
840
|
+
/** A failure adb reports for an install another install of the app stands in the way of. */
|
|
841
|
+
const NEEDS_UNINSTALL = /^INSTALL_FAILED_(UPDATE_INCOMPATIBLE|VERSION_DOWNGRADE)\b/u;
|
|
842
|
+
const LAUNCHER_CATEGORY = "android.intent.category.LAUNCHER";
|
|
843
|
+
/** An application ID's form, checked before it reaches the device's shell. */
|
|
844
|
+
const APP_ID = /^[A-Za-z][A-Za-z0-9_.]*$/u;
|
|
845
|
+
/** `<application ID>/<activity>`, as `resolve-activity --brief` prints it. */
|
|
846
|
+
const ACTIVITY = /^[A-Za-z0-9_.]+\/[A-Za-z0-9_.$]+$/u;
|
|
847
|
+
/**
|
|
848
|
+
* Installs an APK on a device, and opens its launcher activity. `appId` is
|
|
849
|
+
* the APK's own application ID, whatever suffix its build gave it.
|
|
850
|
+
*/
|
|
851
|
+
const installOnAndroidDevice = async ({ serial, apkPath, appId }) => {
|
|
852
|
+
if (!APP_ID.test(appId)) throw new Error(`The APK's application ID isn't valid: ${appId}`);
|
|
853
|
+
try {
|
|
854
|
+
await adb([
|
|
855
|
+
"-s",
|
|
856
|
+
serial,
|
|
857
|
+
"install",
|
|
858
|
+
"-r",
|
|
859
|
+
apkPath
|
|
860
|
+
]);
|
|
861
|
+
} catch (error) {
|
|
862
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
863
|
+
const failure = /Failure \[([^\]]+)\]/u.exec(message)?.[1] ?? message;
|
|
864
|
+
throw new Error(NEEDS_UNINSTALL.test(failure) ? `The installed ${appId} can't be replaced: ${failure}\nUninstall it: adb -s ${serial} uninstall ${appId}` : `adb couldn't install the APK: ${failure}`);
|
|
865
|
+
}
|
|
866
|
+
const activity = (await adb([
|
|
867
|
+
"-s",
|
|
868
|
+
serial,
|
|
869
|
+
"shell",
|
|
870
|
+
"cmd",
|
|
871
|
+
"package",
|
|
872
|
+
"resolve-activity",
|
|
873
|
+
"--brief",
|
|
874
|
+
"-c",
|
|
875
|
+
LAUNCHER_CATEGORY,
|
|
876
|
+
appId
|
|
877
|
+
])).trim().split("\n").at(-1)?.trim();
|
|
878
|
+
if (activity === void 0 || !ACTIVITY.test(activity)) throw new Error(`${appId} is installed, and has no launcher activity to open.`);
|
|
879
|
+
const started = await adb([
|
|
880
|
+
"-s",
|
|
881
|
+
serial,
|
|
882
|
+
"shell",
|
|
883
|
+
"am",
|
|
884
|
+
"start",
|
|
885
|
+
"-a",
|
|
886
|
+
"android.intent.action.MAIN",
|
|
887
|
+
"-c",
|
|
888
|
+
LAUNCHER_CATEGORY,
|
|
889
|
+
"-n",
|
|
890
|
+
`'${activity}'`
|
|
891
|
+
]);
|
|
892
|
+
const error = /^Error: .*$/mu.exec(started)?.[0];
|
|
893
|
+
if (error !== void 0) throw new Error(`${appId} is installed, and didn't open. ${error}`);
|
|
894
|
+
};
|
|
895
|
+
//#endregion
|
|
537
896
|
//#region src/uploadToPlay.ts
|
|
538
897
|
const API_URL = "https://androidpublisher.googleapis.com";
|
|
539
898
|
/** Where Google serves resumable upload sessions, as its docs show both. */
|
|
@@ -637,7 +996,7 @@ const explain = (error, packageName) => {
|
|
|
637
996
|
if (status === 401 || /does not have permission/i.test(apiMessage)) return new Error([
|
|
638
997
|
`The Play service account can't release ${packageName}.`,
|
|
639
998
|
"Invite its email in Play Console (Users and permissions) to release to",
|
|
640
|
-
"testing tracks, and enable the Google Play Android Developer API."
|
|
999
|
+
"testing tracks (Release to production for production), and enable the Google Play Android Developer API."
|
|
641
1000
|
].join("\n"), { cause: error });
|
|
642
1001
|
if (/package not found/i.test(apiMessage)) return new Error(`Google Play has no app ${packageName}.\nCreate it in Play Console and upload its first .aab there.`, { cause: error });
|
|
643
1002
|
if (/version code .*(already been used|already used)/i.test(apiMessage)) return new PlayVersionCodeUsedError({ cause: error });
|
|
@@ -646,7 +1005,8 @@ const explain = (error, packageName) => {
|
|
|
646
1005
|
/**
|
|
647
1006
|
* Requests to the Google Play Developer API for `packageName`, as the
|
|
648
1007
|
* service account: each carries an access token, exchanged for a signed
|
|
649
|
-
* assertion and replaced well before it expires.
|
|
1008
|
+
* assertion and replaced well before it expires. `checkPlayAccess`
|
|
1009
|
+
* checks a key's access with it too.
|
|
650
1010
|
*/
|
|
651
1011
|
const createPlayClient = ({ json, packageName, fetch }) => {
|
|
652
1012
|
const account = readServiceAccount(json);
|
|
@@ -695,11 +1055,69 @@ const createPlayClient = ({ json, packageName, fetch }) => {
|
|
|
695
1055
|
};
|
|
696
1056
|
};
|
|
697
1057
|
/**
|
|
698
|
-
*
|
|
699
|
-
*
|
|
700
|
-
|
|
1058
|
+
* Play Console's page that invites `email` as a user. `_` stands for the
|
|
1059
|
+
* developer account the browser is signed in to, so no ID is needed.
|
|
1060
|
+
*/
|
|
1061
|
+
const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
|
|
1062
|
+
const readClientEmail = (json) => {
|
|
1063
|
+
try {
|
|
1064
|
+
const { client_email } = JSON.parse(json);
|
|
1065
|
+
return typeof client_email === "string" ? client_email : "";
|
|
1066
|
+
} catch {
|
|
1067
|
+
return "";
|
|
1068
|
+
}
|
|
1069
|
+
};
|
|
1070
|
+
/**
|
|
1071
|
+
* Checks once whether the service account's key reaches `packageName`: it
|
|
1072
|
+
* opens an edit of the app and deletes it again, which changes nothing.
|
|
1073
|
+
* Throws only for what says nothing about access, such as a network error.
|
|
1074
|
+
*/
|
|
1075
|
+
const checkPlayAccess = async ({ serviceAccount: { json }, packageName, fetch = globalThis.fetch }) => {
|
|
1076
|
+
const email = readClientEmail(json);
|
|
1077
|
+
const refused = (error) => ({
|
|
1078
|
+
status: "refused",
|
|
1079
|
+
email,
|
|
1080
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
1081
|
+
});
|
|
1082
|
+
let play;
|
|
1083
|
+
try {
|
|
1084
|
+
play = createPlayClient({
|
|
1085
|
+
json,
|
|
1086
|
+
packageName,
|
|
1087
|
+
fetch
|
|
1088
|
+
});
|
|
1089
|
+
} catch (error) {
|
|
1090
|
+
return refused(error);
|
|
1091
|
+
}
|
|
1092
|
+
try {
|
|
1093
|
+
await play.authorization();
|
|
1094
|
+
} catch (error) {
|
|
1095
|
+
if (error instanceof TypeError) throw error;
|
|
1096
|
+
return refused(error);
|
|
1097
|
+
}
|
|
1098
|
+
const edits = `${API_URL}${play.app}/edits`;
|
|
1099
|
+
try {
|
|
1100
|
+
const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits, {});
|
|
1101
|
+
if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${encodeURIComponent(edit.id)}`).catch(() => {});
|
|
1102
|
+
return { status: "ready" };
|
|
1103
|
+
} catch (error) {
|
|
1104
|
+
if (error instanceof GooglePlayError) {
|
|
1105
|
+
if (error.status === 401 || error.status === 403) return {
|
|
1106
|
+
status: "denied",
|
|
1107
|
+
email
|
|
1108
|
+
};
|
|
1109
|
+
if (error.status === 404) return {
|
|
1110
|
+
status: "not-found",
|
|
1111
|
+
email
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
throw error;
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
/**
|
|
1118
|
+
* Reads the app in an edit it then deletes, changing nothing.
|
|
701
1119
|
*/
|
|
702
|
-
const
|
|
1120
|
+
const readInEdit = async ({ packageName, serviceAccount: { json }, fetch }, read) => {
|
|
703
1121
|
const { app, request } = createPlayClient({
|
|
704
1122
|
json,
|
|
705
1123
|
packageName,
|
|
@@ -713,8 +1131,7 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
|
|
|
713
1131
|
}
|
|
714
1132
|
const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
|
|
715
1133
|
try {
|
|
716
|
-
|
|
717
|
-
return releases.some(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
|
|
1134
|
+
return await read(request, edit);
|
|
718
1135
|
} catch (error) {
|
|
719
1136
|
throw explain(error, packageName);
|
|
720
1137
|
} finally {
|
|
@@ -722,6 +1139,44 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
|
|
|
722
1139
|
}
|
|
723
1140
|
};
|
|
724
1141
|
/**
|
|
1142
|
+
* The status of the selected track's release holding `versionCode`, defaulting
|
|
1143
|
+
* to internal testing, such as
|
|
1144
|
+
* `completed` or `draft`, or null when the track doesn't hold it: never
|
|
1145
|
+
* uploaded, or replaced by a newer release, which testers get instead.
|
|
1146
|
+
*/
|
|
1147
|
+
const readPlayTrackRelease = ({ versionCode, track = INTERNAL_TRACK, packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
|
|
1148
|
+
packageName,
|
|
1149
|
+
serviceAccount,
|
|
1150
|
+
fetch
|
|
1151
|
+
}, async (request, edit) => {
|
|
1152
|
+
const { releases = [] } = await request(`Reading the ${track} track`, "GET", `${edit}/tracks/${encodeURIComponent(track)}`);
|
|
1153
|
+
const release = releases.find(({ versionCodes = [] }) => versionCodes.includes(String(versionCode)));
|
|
1154
|
+
return release ? release.status ?? "completed" : null;
|
|
1155
|
+
});
|
|
1156
|
+
/**
|
|
1157
|
+
* Whether Google Play's internal testing track already releases the
|
|
1158
|
+
* `.aab`'s version code, as when a reused native build was uploaded before.
|
|
1159
|
+
*/
|
|
1160
|
+
const findPlayInternalRelease = async (options) => await readPlayTrackRelease(options) !== null;
|
|
1161
|
+
/**
|
|
1162
|
+
* The highest version code Google Play has taken for the app, on any track,
|
|
1163
|
+
* or null with none: a new `.aab` needs one above it.
|
|
1164
|
+
*/
|
|
1165
|
+
const readPlayHighestVersionCode = ({ packageName, serviceAccount, fetch = globalThis.fetch }) => readInEdit({
|
|
1166
|
+
packageName,
|
|
1167
|
+
serviceAccount,
|
|
1168
|
+
fetch
|
|
1169
|
+
}, async (request, edit) => {
|
|
1170
|
+
const { bundles = [] } = await request("Reading the app's bundles", "GET", `${edit}/bundles`);
|
|
1171
|
+
const codes = bundles.flatMap(({ versionCode }) => versionCode ?? []);
|
|
1172
|
+
return codes.length > 0 ? Math.max(...codes) : null;
|
|
1173
|
+
});
|
|
1174
|
+
/**
|
|
1175
|
+
* The link that opts a tester in to the app's testing tracks. A build on the
|
|
1176
|
+
* internal track installs through it, for the testers Play Console lists.
|
|
1177
|
+
*/
|
|
1178
|
+
const playTestingUrl = (packageName) => `https://play.google.com/apps/testing/${encodeURIComponent(packageName)}`;
|
|
1179
|
+
/**
|
|
725
1180
|
* The common name of every Android debug certificate: Android Studio's and
|
|
726
1181
|
* the Android Gradle plugin's (`CN=Android Debug, O=Android, C=US`), and React
|
|
727
1182
|
* Native's template `debug.keystore` (`CN=Android Debug, OU=Android,
|
|
@@ -749,12 +1204,13 @@ const assertPlaySigned = async (aabPath) => {
|
|
|
749
1204
|
].join("\n"));
|
|
750
1205
|
};
|
|
751
1206
|
/**
|
|
752
|
-
* Uploads an `.aab` to Google Play
|
|
1207
|
+
* Uploads or promotes an `.aab` to a Google Play track with the Google
|
|
753
1208
|
* Play Developer API: it opens an edit, uploads the bundle, releases its
|
|
754
|
-
* version code to the
|
|
1209
|
+
* version code to the selected track, and commits the edit, which it
|
|
755
1210
|
* deletes again when any step fails. The service account stays in memory.
|
|
756
1211
|
*/
|
|
757
|
-
const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3 }) => {
|
|
1212
|
+
const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fetch = globalThis.fetch, commitRetryDelayMs = 2e3, track = "internal", rollout = 100, existingVersionCode }) => {
|
|
1213
|
+
if (!Number.isInteger(rollout) || rollout < 1 || rollout > 100 || track === "internal" && rollout < 100) throw new Error(track === "internal" && rollout < 100 ? "Play internal testing does not support staged rollout." : "Rollout must be an integer from 1 to 100.");
|
|
758
1214
|
const { app, authorization, request } = createPlayClient({
|
|
759
1215
|
json,
|
|
760
1216
|
packageName,
|
|
@@ -768,20 +1224,28 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
|
|
|
768
1224
|
}
|
|
769
1225
|
const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
|
|
770
1226
|
try {
|
|
771
|
-
p.log.info(
|
|
772
|
-
const versionCode = await uploadBundle({
|
|
1227
|
+
p.log.info(`${existingVersionCode === void 0 ? "Uploading" : "Promoting"} ${packageName} to Google Play`);
|
|
1228
|
+
const versionCode = existingVersionCode ?? await uploadBundle({
|
|
773
1229
|
aabPath,
|
|
774
1230
|
sessionUrl: `${API_URL}/upload${app}/edits/${encodeURIComponent(editId)}/bundles?uploadType=resumable`,
|
|
775
1231
|
authorization,
|
|
776
1232
|
fetch
|
|
777
1233
|
});
|
|
1234
|
+
const existingRelease = (existingVersionCode === void 0 ? void 0 : await request("Reading the Google Play track", "GET", `${edit}/tracks/${track}`))?.releases?.find((release) => release.versionCodes?.includes(String(versionCode)));
|
|
778
1235
|
const release = async (status) => {
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
1236
|
+
const updatedRelease = {
|
|
1237
|
+
...existingRelease,
|
|
1238
|
+
versionCodes: existingRelease?.versionCodes ?? [String(versionCode)],
|
|
1239
|
+
status
|
|
1240
|
+
};
|
|
1241
|
+
if (status === "inProgress") updatedRelease.userFraction = rollout / 100;
|
|
1242
|
+
else {
|
|
1243
|
+
delete updatedRelease.userFraction;
|
|
1244
|
+
delete updatedRelease.countryTargeting;
|
|
1245
|
+
}
|
|
1246
|
+
await request(`Releasing to the ${track} track`, "PUT", `${edit}/tracks/${track}`, {
|
|
1247
|
+
track,
|
|
1248
|
+
releases: [updatedRelease]
|
|
785
1249
|
});
|
|
786
1250
|
await commit({
|
|
787
1251
|
request,
|
|
@@ -790,10 +1254,11 @@ const uploadToPlay = async ({ aabPath, packageName, serviceAccount: { json }, fe
|
|
|
790
1254
|
});
|
|
791
1255
|
};
|
|
792
1256
|
try {
|
|
793
|
-
|
|
1257
|
+
const status = rollout < 100 ? "inProgress" : "completed";
|
|
1258
|
+
await release(status);
|
|
794
1259
|
return {
|
|
795
1260
|
versionCode,
|
|
796
|
-
status
|
|
1261
|
+
status
|
|
797
1262
|
};
|
|
798
1263
|
} catch (error) {
|
|
799
1264
|
if (!(error instanceof GooglePlayError) || !DRAFT_APP_ERRORS.some((message) => error.apiMessage.includes(message))) throw error;
|
|
@@ -825,7 +1290,7 @@ const commit = async ({ request, edit, retryDelayMs }) => {
|
|
|
825
1290
|
if (!(error instanceof GooglePlayError) || error.status >= 500 || error.status === 429) throw new Error([
|
|
826
1291
|
"Google Play didn't confirm the release.",
|
|
827
1292
|
error instanceof Error ? error.message : String(error),
|
|
828
|
-
"Check
|
|
1293
|
+
"Check the release in Play Console before you upload it again."
|
|
829
1294
|
].join("\n"), { cause: error });
|
|
830
1295
|
if (error.status !== 400) throw error;
|
|
831
1296
|
if (!changesNotSentForReview && error.apiMessage.includes(NEEDS_CHANGES_NOT_SENT_FOR_REVIEW)) {
|
|
@@ -1064,617 +1529,29 @@ const extractBuiltInBundle = async ({ artifactPath, outputPath }) => {
|
|
|
1064
1529
|
await (entry.method === 8 ? pipeline(source, createInflateRaw(), fs.createWriteStream(outputPath)) : pipeline(source, fs.createWriteStream(outputPath)));
|
|
1065
1530
|
};
|
|
1066
1531
|
//#endregion
|
|
1067
|
-
//#region src/
|
|
1068
|
-
/**
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
this.consumer = body.consumer;
|
|
1532
|
+
//#region src/playTracks.ts
|
|
1533
|
+
/** Google Play destinations and their API tracks. */
|
|
1534
|
+
const PLAY_TRACKS = {
|
|
1535
|
+
"play-internal": {
|
|
1536
|
+
track: "internal",
|
|
1537
|
+
label: "Play internal",
|
|
1538
|
+
name: "Google Play internal testing"
|
|
1539
|
+
},
|
|
1540
|
+
"play-closed": {
|
|
1541
|
+
track: "alpha",
|
|
1542
|
+
label: "Play closed",
|
|
1543
|
+
name: "Google Play closed testing"
|
|
1544
|
+
},
|
|
1545
|
+
"play-open": {
|
|
1546
|
+
track: "beta",
|
|
1547
|
+
label: "Play open",
|
|
1548
|
+
name: "Google Play open testing"
|
|
1549
|
+
},
|
|
1550
|
+
"play-production": {
|
|
1551
|
+
track: "production",
|
|
1552
|
+
label: "Play production",
|
|
1553
|
+
name: "Google Play production"
|
|
1090
1554
|
}
|
|
1091
1555
|
};
|
|
1092
|
-
/** Google's error body, `{ error: { code, status, message, details } }`. */
|
|
1093
|
-
const readError = async (action, response) => {
|
|
1094
|
-
let error;
|
|
1095
|
-
try {
|
|
1096
|
-
error = (await response.json()).error;
|
|
1097
|
-
} catch {}
|
|
1098
|
-
const details = Array.isArray(error?.details) ? error.details : [];
|
|
1099
|
-
const info = details.filter((detail) => typeof detail.reason === "string");
|
|
1100
|
-
return new GoogleApiError(action, response.status, {
|
|
1101
|
-
...typeof error?.status === "string" ? { apiStatus: error.status } : {},
|
|
1102
|
-
...typeof error?.message === "string" ? { apiMessage: error.message } : {},
|
|
1103
|
-
reasons: info.map((detail) => detail.reason),
|
|
1104
|
-
violations: details.flatMap((detail) => (detail.violations ?? []).flatMap((violation) => typeof violation.type === "string" ? [violation.type] : [])),
|
|
1105
|
-
...info.find((detail) => detail.metadata?.["consumer"]) ? { consumer: info.find((detail) => detail.metadata?.["consumer"]).metadata["consumer"] } : {}
|
|
1106
|
-
});
|
|
1107
|
-
};
|
|
1108
|
-
/** Whether Google answered that a service is disabled in a project. */
|
|
1109
|
-
const isServiceDisabled = (error) => error instanceof GoogleApiError && (error.reasons.includes("SERVICE_DISABLED") || /has not been used in project .* or it is disabled/i.test(error.apiMessage));
|
|
1110
|
-
/** Requests with the signed-in user's access token, throwing `GoogleApiError`. */
|
|
1111
|
-
const createGoogleRequest = ({ accessToken, fetch }) => async (action, method, url, body) => {
|
|
1112
|
-
const response = await fetch(url, {
|
|
1113
|
-
method,
|
|
1114
|
-
headers: {
|
|
1115
|
-
authorization: `Bearer ${accessToken}`,
|
|
1116
|
-
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
1117
|
-
},
|
|
1118
|
-
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
1119
|
-
});
|
|
1120
|
-
if (!response.ok) throw await readError(action, response);
|
|
1121
|
-
const text = await response.text();
|
|
1122
|
-
return text ? JSON.parse(text) : {};
|
|
1123
|
-
};
|
|
1124
|
-
/**
|
|
1125
|
-
* Polls `operation` at `origin` until it is done, returning its response or
|
|
1126
|
-
* throwing its error as a `GoogleApiError` with the operation's code.
|
|
1127
|
-
*/
|
|
1128
|
-
const waitForOperation = async ({ request, origin, operation, action, sleep, intervalMs = 2e3, attempts = 60 }) => {
|
|
1129
|
-
let current = operation;
|
|
1130
|
-
for (let attempt = 0; !current.done; attempt++) {
|
|
1131
|
-
if (attempt >= attempts || !current.name) throw new Error(`${action} did not finish in time.`);
|
|
1132
|
-
await sleep(intervalMs);
|
|
1133
|
-
current = await request(action, "GET", `${origin}/${current.name}`);
|
|
1134
|
-
}
|
|
1135
|
-
if (current.error) throw new GoogleApiError(action, 400, {
|
|
1136
|
-
apiMessage: current.error.message ?? "",
|
|
1137
|
-
...current.error.code === 7 ? { apiStatus: "PERMISSION_DENIED" } : {},
|
|
1138
|
-
...current.error.code === 8 ? { apiStatus: "RESOURCE_EXHAUSTED" } : {}
|
|
1139
|
-
});
|
|
1140
|
-
return current.response;
|
|
1141
|
-
};
|
|
1142
|
-
//#endregion
|
|
1143
|
-
//#region src/google/types.ts
|
|
1144
|
-
/** A named failure of `issuePlayServiceAccount`, with what to do in its message. */
|
|
1145
|
-
var PlayServiceAccountError = class extends Error {
|
|
1146
|
-
code;
|
|
1147
|
-
constructor(code, message, options) {
|
|
1148
|
-
super(message, options);
|
|
1149
|
-
this.name = "PlayServiceAccountError";
|
|
1150
|
-
this.code = code;
|
|
1151
|
-
}
|
|
1152
|
-
};
|
|
1153
|
-
/** The environment variables that replace Hot Updater's Google OAuth client. */
|
|
1154
|
-
const GOOGLE_OAUTH_CLIENT_ENV_NAMES = {
|
|
1155
|
-
clientId: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID",
|
|
1156
|
-
clientSecret: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_SECRET"
|
|
1157
|
-
};
|
|
1158
|
-
/** The service account Hot Updater creates, `hot-updater-play@<project>.iam.gserviceaccount.com`. */
|
|
1159
|
-
const PLAY_SERVICE_ACCOUNT_ID = "hot-updater-play";
|
|
1160
|
-
/** Where a Play Console admin finds the developer account ID. */
|
|
1161
|
-
const PLAY_CONSOLE_URL = "https://play.google.com/console";
|
|
1162
|
-
//#endregion
|
|
1163
|
-
//#region src/google/googleSignIn.ts
|
|
1164
|
-
const AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth";
|
|
1165
|
-
const TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
1166
|
-
const REVOKE_URL = "https://oauth2.googleapis.com/revoke";
|
|
1167
|
-
/** How long the browser has to come back with the sign-in. */
|
|
1168
|
-
const SIGN_IN_TIMEOUT_MS = 3e5;
|
|
1169
|
-
const base64url = (bytes) => bytes.toString("base64url");
|
|
1170
|
-
const page = (message) => `<!doctype html><meta charset="utf-8"><title>Hot Updater</title><body style="font-family:system-ui;margin:3rem"><p>${message}</p></body>`;
|
|
1171
|
-
/**
|
|
1172
|
-
* Signs in with Google as an installed app does (RFC 8252): the browser
|
|
1173
|
-
* opens Google's own consent screen, so the password and the second factor
|
|
1174
|
-
* stay with Google, and the authorization code comes back to a loopback
|
|
1175
|
-
* server on 127.0.0.1, bound to a random port for this sign-in only. The
|
|
1176
|
-
* code is exchanged with PKCE (S256), and `state` ties the answer to this
|
|
1177
|
-
* request.
|
|
1178
|
-
*
|
|
1179
|
-
* @param onUrl Sees the sign-in URL, to print and open in a browser.
|
|
1180
|
-
*/
|
|
1181
|
-
const signInWithGoogle = async ({ client, scopes, onUrl, fetch = globalThis.fetch, timeoutMs = SIGN_IN_TIMEOUT_MS }) => {
|
|
1182
|
-
const verifier = base64url(crypto$1.randomBytes(32));
|
|
1183
|
-
const challenge = base64url(crypto$1.createHash("sha256").update(verifier).digest());
|
|
1184
|
-
const state = base64url(crypto$1.randomBytes(16));
|
|
1185
|
-
const server = http.createServer();
|
|
1186
|
-
await new Promise((resolve, reject) => {
|
|
1187
|
-
server.once("error", reject);
|
|
1188
|
-
server.listen(0, "127.0.0.1", () => resolve());
|
|
1189
|
-
});
|
|
1190
|
-
try {
|
|
1191
|
-
const { port } = server.address();
|
|
1192
|
-
const redirectUri = `http://127.0.0.1:${port}`;
|
|
1193
|
-
const code = new Promise((resolve, reject) => {
|
|
1194
|
-
const timer = setTimeout(() => reject(new PlayServiceAccountError("sign-in-cancelled", "The Google sign-in did not finish in time.")), timeoutMs);
|
|
1195
|
-
timer.unref();
|
|
1196
|
-
server.on("request", (req, res) => {
|
|
1197
|
-
const query = new URL(req.url ?? "/", redirectUri).searchParams;
|
|
1198
|
-
if (query.get("state") !== state) {
|
|
1199
|
-
res.writeHead(404).end();
|
|
1200
|
-
return;
|
|
1201
|
-
}
|
|
1202
|
-
const error = query.get("error");
|
|
1203
|
-
const answer = query.get("code");
|
|
1204
|
-
res.writeHead(error || !answer ? 400 : 200, { "content-type": "text/html; charset=utf-8" }).end(page(error || !answer ? "The sign-in did not finish. Return to the terminal." : "Signed in. Close this tab and return to the terminal."));
|
|
1205
|
-
clearTimeout(timer);
|
|
1206
|
-
if (error || !answer) reject(new PlayServiceAccountError("sign-in-cancelled", error === "access_denied" ? "The Google sign-in was cancelled." : `The Google sign-in failed: ${error ?? "no authorization code"}.`));
|
|
1207
|
-
else resolve(answer);
|
|
1208
|
-
});
|
|
1209
|
-
});
|
|
1210
|
-
code.catch(() => {});
|
|
1211
|
-
const url = new URL(AUTHORIZATION_URL);
|
|
1212
|
-
url.search = new URLSearchParams({
|
|
1213
|
-
client_id: client.clientId,
|
|
1214
|
-
redirect_uri: redirectUri,
|
|
1215
|
-
response_type: "code",
|
|
1216
|
-
scope: scopes.join(" "),
|
|
1217
|
-
code_challenge: challenge,
|
|
1218
|
-
code_challenge_method: "S256",
|
|
1219
|
-
state,
|
|
1220
|
-
prompt: "select_account"
|
|
1221
|
-
}).toString();
|
|
1222
|
-
await onUrl(url.toString());
|
|
1223
|
-
const authorizationCode = await code;
|
|
1224
|
-
registerSecretValue(authorizationCode);
|
|
1225
|
-
const response = await fetch(TOKEN_URL, {
|
|
1226
|
-
method: "POST",
|
|
1227
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
1228
|
-
body: new URLSearchParams({
|
|
1229
|
-
code: authorizationCode,
|
|
1230
|
-
client_id: client.clientId,
|
|
1231
|
-
...client.clientSecret ? { client_secret: client.clientSecret } : {},
|
|
1232
|
-
redirect_uri: redirectUri,
|
|
1233
|
-
grant_type: "authorization_code",
|
|
1234
|
-
code_verifier: verifier
|
|
1235
|
-
}).toString()
|
|
1236
|
-
});
|
|
1237
|
-
const token = await response.json().catch(() => ({}));
|
|
1238
|
-
if (!response.ok || typeof token.access_token !== "string") throw new PlayServiceAccountError(token.error === "invalid_client" ? "sign-in-not-configured" : "sign-in-cancelled", `Google refused the sign-in (HTTP ${response.status}).${typeof token.error_description === "string" ? `\n${token.error_description}` : typeof token.error === "string" ? `\n${token.error}` : ""}`);
|
|
1239
|
-
registerSecretValue(token.access_token);
|
|
1240
|
-
return {
|
|
1241
|
-
accessToken: token.access_token,
|
|
1242
|
-
scopes: typeof token.scope === "string" ? token.scope.split(" ") : []
|
|
1243
|
-
};
|
|
1244
|
-
} finally {
|
|
1245
|
-
server.closeAllConnections();
|
|
1246
|
-
await new Promise((resolve) => server.close(() => resolve()));
|
|
1247
|
-
}
|
|
1248
|
-
};
|
|
1249
|
-
/** Ends a sign-in: Google revokes its access token. Whether Google did. */
|
|
1250
|
-
const revokeGoogleToken = async (accessToken, fetch = globalThis.fetch) => {
|
|
1251
|
-
try {
|
|
1252
|
-
return (await fetch(REVOKE_URL, {
|
|
1253
|
-
method: "POST",
|
|
1254
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
1255
|
-
body: new URLSearchParams({ token: accessToken }).toString()
|
|
1256
|
-
})).ok;
|
|
1257
|
-
} catch {
|
|
1258
|
-
return false;
|
|
1259
|
-
}
|
|
1260
|
-
};
|
|
1261
|
-
//#endregion
|
|
1262
|
-
//#region src/google/googleKeyIssuer.ts
|
|
1263
|
-
const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
|
|
1264
|
-
const ANDROID_PUBLISHER_SCOPE = "https://www.googleapis.com/auth/androidpublisher";
|
|
1265
|
-
const SCOPES = [CLOUD_PLATFORM_SCOPE, ANDROID_PUBLISHER_SCOPE];
|
|
1266
|
-
const PUBLISHER_API = "https://androidpublisher.googleapis.com/androidpublisher/v3";
|
|
1267
|
-
const RESOURCE_MANAGER_API = "https://cloudresourcemanager.googleapis.com";
|
|
1268
|
-
const SERVICE_USAGE_API = "https://serviceusage.googleapis.com";
|
|
1269
|
-
const IAM_API = "https://iam.googleapis.com/v1";
|
|
1270
|
-
/** IAM creates the service account; the Play Developer API is what it calls. */
|
|
1271
|
-
const SERVICES = ["iam.googleapis.com", "androidpublisher.googleapis.com"];
|
|
1272
|
-
/**
|
|
1273
|
-
* What the service account may do in Play Console, for the app only: read
|
|
1274
|
-
* it, and release to testing tracks, which `--submit play-internal` does.
|
|
1275
|
-
*/
|
|
1276
|
-
const APP_PERMISSIONS = ["CAN_VIEW_NON_FINANCIAL_DATA", "CAN_MANAGE_TRACK_APKS"];
|
|
1277
|
-
const KEY_CREATION_CONSTRAINT = "constraints/iam.disableServiceAccountKeyCreation";
|
|
1278
|
-
/** Retries while Google enables an API or creates a service account. */
|
|
1279
|
-
const PROPAGATION_ATTEMPTS = 12;
|
|
1280
|
-
const PROPAGATION_DELAY_MS = 1e4;
|
|
1281
|
-
const sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1282
|
-
/** The developer account ID in `input`, a number or a Play Console URL. */
|
|
1283
|
-
const parseDeveloperId = (input) => {
|
|
1284
|
-
const trimmed = input.trim();
|
|
1285
|
-
if (/^\d+$/u.test(trimmed)) return trimmed;
|
|
1286
|
-
return trimmed.match(/\/developers\/(\d+)(?:[/?#]|$)/u)?.[1];
|
|
1287
|
-
};
|
|
1288
|
-
/** A project ID nobody has: Google Cloud's are global. */
|
|
1289
|
-
const newProjectId = () => `${PLAY_SERVICE_ACCOUNT_ID}-${crypto$1.randomBytes(3).toString("hex")}`;
|
|
1290
|
-
const isNotFound = (error) => error instanceof GoogleApiError && error.status === 404;
|
|
1291
|
-
const isConflict = (error) => error instanceof GoogleApiError && error.status === 409;
|
|
1292
|
-
/** The API is disabled in the OAuth client's own project: waiting does not help. */
|
|
1293
|
-
const clientApiDisabled = (error) => new PlayServiceAccountError("api-not-enabled", `${error.apiMessage}\nEnable it in the OAuth client's project (${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientId}).`, { cause: error });
|
|
1294
|
-
/** Google's own words, after a message that names the likely cause. */
|
|
1295
|
-
const googleSays = (error) => error instanceof GoogleApiError && error.apiMessage ? `\nGoogle: ${error.apiMessage}` : "";
|
|
1296
|
-
/** A Play Console refusal, as `not-play-admin`. */
|
|
1297
|
-
const notPlayAdmin = (developerId, error) => new PlayServiceAccountError("not-play-admin", `This Google Account isn't an admin of Play Console developer ${developerId}.${googleSays(error)}\nSign in with an account that has the Admin permission there.`, { cause: error });
|
|
1298
|
-
const isDenied = (error) => error instanceof GoogleApiError && (error.status === 403 || error.apiStatus === "PERMISSION_DENIED");
|
|
1299
|
-
/**
|
|
1300
|
-
* `IssuePlayServiceAccount` with Google's own APIs, after a sign-in on
|
|
1301
|
-
* Google's consent screen (OAuth for installed apps, with PKCE and a
|
|
1302
|
-
* loopback redirect):
|
|
1303
|
-
*
|
|
1304
|
-
* 1. the Play Console side is checked first, with no change anywhere: the
|
|
1305
|
-
* developer account answers to the account as its admin, and has the app;
|
|
1306
|
-
* 2. the chosen Google Cloud project, or a new one, gets the IAM and Play
|
|
1307
|
-
* Developer APIs enabled, and the service account `hot-updater-play`;
|
|
1308
|
-
* 3. the service account becomes a Play Console user that may release the
|
|
1309
|
-
* app to testing tracks;
|
|
1310
|
-
* 4. only then is its JSON key created, the last step, so a failure before
|
|
1311
|
-
* it leaves no key behind.
|
|
1312
|
-
*
|
|
1313
|
-
* Each step reuses what an earlier run created: the project, the service
|
|
1314
|
-
* account, and its Play Console access.
|
|
1315
|
-
*/
|
|
1316
|
-
const createGoogleKeyIssuer = ({ fetch = globalThis.fetch, sleep = sleepFor } = {}) => async (request) => {
|
|
1317
|
-
const { packageName, oauthClient, onStep = () => {} } = request;
|
|
1318
|
-
if (!oauthClient?.clientId) throw new PlayServiceAccountError("sign-in-not-configured", [
|
|
1319
|
-
"This build of Hot Updater has no Google OAuth client to sign in with.",
|
|
1320
|
-
"Set these to a \"Desktop app\" OAuth client:",
|
|
1321
|
-
`${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientId}, ${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientSecret}`
|
|
1322
|
-
].join("\n"));
|
|
1323
|
-
const signIn = await signInWithGoogle({
|
|
1324
|
-
client: oauthClient,
|
|
1325
|
-
scopes: SCOPES,
|
|
1326
|
-
onUrl: request.onSignInUrl,
|
|
1327
|
-
fetch
|
|
1328
|
-
});
|
|
1329
|
-
const dispose = async () => {
|
|
1330
|
-
await revokeGoogleToken(signIn.accessToken, fetch);
|
|
1331
|
-
};
|
|
1332
|
-
try {
|
|
1333
|
-
const missing = SCOPES.filter((scope) => !signIn.scopes.includes(scope));
|
|
1334
|
-
if (missing.length > 0) throw new PlayServiceAccountError("scope-not-granted", `The sign-in didn't allow ${missing.map((scope) => scope === ANDROID_PUBLISHER_SCOPE ? "managing Google Play" : "managing Google Cloud").join(" or ")}.\nRun this again and keep every box on Google's consent screen ticked.`);
|
|
1335
|
-
const google = createGoogleRequest({
|
|
1336
|
-
accessToken: signIn.accessToken,
|
|
1337
|
-
fetch
|
|
1338
|
-
});
|
|
1339
|
-
const developerInput = await request.askDeveloperId();
|
|
1340
|
-
const developerId = parseDeveloperId(developerInput);
|
|
1341
|
-
if (developerId === void 0) throw new PlayServiceAccountError("developer-not-found", `"${developerInput.trim()}" is not a developer account ID.\nIt is the number after /developers/ in Play Console's address.`);
|
|
1342
|
-
onStep("Checking the Play Console developer account");
|
|
1343
|
-
await checkPlayConsole({
|
|
1344
|
-
google,
|
|
1345
|
-
developerId,
|
|
1346
|
-
packageName
|
|
1347
|
-
});
|
|
1348
|
-
const project = await chooseProject({
|
|
1349
|
-
google,
|
|
1350
|
-
request,
|
|
1351
|
-
sleep,
|
|
1352
|
-
onStep
|
|
1353
|
-
});
|
|
1354
|
-
const { projectId } = project;
|
|
1355
|
-
onStep(`Enabling the Google Play Developer API in ${projectId}`);
|
|
1356
|
-
await enableServices({
|
|
1357
|
-
google,
|
|
1358
|
-
projectId,
|
|
1359
|
-
sleep
|
|
1360
|
-
});
|
|
1361
|
-
onStep(`Creating the service account in ${projectId}`);
|
|
1362
|
-
const email = await ensureServiceAccount({
|
|
1363
|
-
google,
|
|
1364
|
-
project,
|
|
1365
|
-
sleep
|
|
1366
|
-
});
|
|
1367
|
-
onStep(`Giving ${email} release access to ${packageName}`);
|
|
1368
|
-
await grantPlayAccess({
|
|
1369
|
-
google,
|
|
1370
|
-
developerId,
|
|
1371
|
-
email,
|
|
1372
|
-
packageName
|
|
1373
|
-
});
|
|
1374
|
-
onStep("Creating the service account's JSON key");
|
|
1375
|
-
const key = await createKey({
|
|
1376
|
-
google,
|
|
1377
|
-
project,
|
|
1378
|
-
email,
|
|
1379
|
-
sleep
|
|
1380
|
-
});
|
|
1381
|
-
return {
|
|
1382
|
-
json: key.json,
|
|
1383
|
-
keyId: key.keyId,
|
|
1384
|
-
email,
|
|
1385
|
-
projectId,
|
|
1386
|
-
developerId,
|
|
1387
|
-
revoke: async () => {
|
|
1388
|
-
try {
|
|
1389
|
-
await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`);
|
|
1390
|
-
return true;
|
|
1391
|
-
} catch (error) {
|
|
1392
|
-
return isNotFound(error);
|
|
1393
|
-
}
|
|
1394
|
-
},
|
|
1395
|
-
dispose
|
|
1396
|
-
};
|
|
1397
|
-
} catch (error) {
|
|
1398
|
-
await dispose();
|
|
1399
|
-
throw error;
|
|
1400
|
-
}
|
|
1401
|
-
};
|
|
1402
|
-
/**
|
|
1403
|
-
* Whether the signed-in account administers `developerId`, and Google Play
|
|
1404
|
-
* has `packageName` there, asked without changing anything: listing the
|
|
1405
|
-
* account's users takes the admin permission, and an edit opened on the app
|
|
1406
|
-
* is deleted again.
|
|
1407
|
-
*/
|
|
1408
|
-
const checkPlayConsole = async ({ google, developerId, packageName }) => {
|
|
1409
|
-
try {
|
|
1410
|
-
await google("Listing the Play Console users", "GET", `${PUBLISHER_API}/developers/${developerId}/users?pageSize=1`);
|
|
1411
|
-
} catch (error) {
|
|
1412
|
-
if (isServiceDisabled(error)) throw clientApiDisabled(error);
|
|
1413
|
-
if (isNotFound(error)) throw new PlayServiceAccountError("developer-not-found", `Play Console has no developer account ${developerId}.${googleSays(error)}\nIt is the number after /developers/ in Play Console's address.`, { cause: error });
|
|
1414
|
-
if (isDenied(error)) throw notPlayAdmin(developerId, error);
|
|
1415
|
-
throw error;
|
|
1416
|
-
}
|
|
1417
|
-
let edit;
|
|
1418
|
-
try {
|
|
1419
|
-
edit = await google(`Opening an edit of ${packageName}`, "POST", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits`);
|
|
1420
|
-
} catch (error) {
|
|
1421
|
-
if (isServiceDisabled(error)) throw clientApiDisabled(error);
|
|
1422
|
-
if (isNotFound(error) || isDenied(error)) throw appNotFound(packageName, developerId, error);
|
|
1423
|
-
throw error;
|
|
1424
|
-
}
|
|
1425
|
-
if (edit.id) await google("Deleting the edit", "DELETE", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits/${edit.id}`).catch(() => {});
|
|
1426
|
-
};
|
|
1427
|
-
const appNotFound = (packageName, developerId, cause) => new PlayServiceAccountError("app-not-found", `Google Play has no app ${packageName} in the developer account ${developerId}. Google takes the first .aab of a new app only in Play Console: create the app there, upload one .aab by hand (for example to internal testing), then run this again${googleSays(cause)}.`, { cause });
|
|
1428
|
-
/** The account's active projects, every page of them. */
|
|
1429
|
-
const listProjects = async (google) => {
|
|
1430
|
-
const projects = [];
|
|
1431
|
-
let pageToken;
|
|
1432
|
-
do {
|
|
1433
|
-
const page = await google("Listing the Google Cloud projects", "GET", `${RESOURCE_MANAGER_API}/v3/projects:search?${new URLSearchParams({
|
|
1434
|
-
query: "state:ACTIVE",
|
|
1435
|
-
...pageToken ? { pageToken } : {}
|
|
1436
|
-
})}`);
|
|
1437
|
-
for (const project of page.projects ?? []) if (project.projectId) projects.push({
|
|
1438
|
-
projectId: project.projectId,
|
|
1439
|
-
...project.displayName ? { displayName: project.displayName } : {},
|
|
1440
|
-
...projectNumberOf(project.name)
|
|
1441
|
-
});
|
|
1442
|
-
pageToken = page.nextPageToken || void 0;
|
|
1443
|
-
} while (pageToken);
|
|
1444
|
-
return projects;
|
|
1445
|
-
};
|
|
1446
|
-
/** The project the developer picks, or a new one when there is none or they ask. */
|
|
1447
|
-
const chooseProject = async ({ google, request, sleep, onStep }) => {
|
|
1448
|
-
const projects = await listProjects(google);
|
|
1449
|
-
const chosen = projects.length > 0 ? await request.chooseProject(projects.map(({ projectId, displayName }) => ({
|
|
1450
|
-
projectId,
|
|
1451
|
-
...displayName ? { displayName } : {}
|
|
1452
|
-
}))) : void 0;
|
|
1453
|
-
if (chosen !== void 0) return projects.find((project) => project.projectId === chosen) ?? { projectId: chosen };
|
|
1454
|
-
const projectId = newProjectId();
|
|
1455
|
-
onStep(`Creating the Google Cloud project ${projectId}`);
|
|
1456
|
-
try {
|
|
1457
|
-
const operation = await google("Creating the Google Cloud project", "POST", `${RESOURCE_MANAGER_API}/v3/projects`, {
|
|
1458
|
-
projectId,
|
|
1459
|
-
displayName: "Hot Updater Play"
|
|
1460
|
-
});
|
|
1461
|
-
const created = await waitForOperation({
|
|
1462
|
-
request: google,
|
|
1463
|
-
origin: `${RESOURCE_MANAGER_API}/v3`,
|
|
1464
|
-
operation,
|
|
1465
|
-
action: "Creating the Google Cloud project",
|
|
1466
|
-
sleep
|
|
1467
|
-
});
|
|
1468
|
-
return {
|
|
1469
|
-
projectId,
|
|
1470
|
-
...projectNumberOf(created?.name)
|
|
1471
|
-
};
|
|
1472
|
-
} catch (error) {
|
|
1473
|
-
if (!(error instanceof GoogleApiError)) throw error;
|
|
1474
|
-
if (error.status === 429 || error.apiStatus === "RESOURCE_EXHAUSTED" || /quota/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-quota", [
|
|
1475
|
-
"Google Cloud has no project quota left for this account.",
|
|
1476
|
-
error.apiMessage || "Quota exceeded.",
|
|
1477
|
-
"Run this again and pick an existing project, or delete one at:",
|
|
1478
|
-
"https://console.cloud.google.com/cloud-resource-manager"
|
|
1479
|
-
].join("\n"), { cause: error });
|
|
1480
|
-
if (/terms of service/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-create-denied", "This Google Account hasn't accepted the Google Cloud Terms of Service.\nAccept them at https://console.cloud.google.com, then run this again.", { cause: error });
|
|
1481
|
-
if (isDenied(error) || error.apiStatus === "FAILED_PRECONDITION") throw new PlayServiceAccountError("project-create-denied", [
|
|
1482
|
-
"This Google Account may not create Google Cloud projects.",
|
|
1483
|
-
error.apiMessage || "Permission denied.",
|
|
1484
|
-
"Pick an existing project, or ask an admin for the Project Creator role."
|
|
1485
|
-
].join("\n"), { cause: error });
|
|
1486
|
-
throw error;
|
|
1487
|
-
}
|
|
1488
|
-
};
|
|
1489
|
-
/** `projectNumber` from a resource name `projects/<number>`. */
|
|
1490
|
-
const projectNumberOf = (name) => {
|
|
1491
|
-
const number = name?.match(/^projects\/(\d+)$/u)?.[1];
|
|
1492
|
-
return number === void 0 ? {} : { projectNumber: number };
|
|
1493
|
-
};
|
|
1494
|
-
/**
|
|
1495
|
-
* Runs `run` again while Google is still enabling an API in `project`,
|
|
1496
|
-
* or, with `notFound`, still creating what it reads.
|
|
1497
|
-
*/
|
|
1498
|
-
const whilePropagating = async ({ run, project, sleep, notFound = false }) => {
|
|
1499
|
-
for (let attempt = 1;; attempt++) try {
|
|
1500
|
-
return await run();
|
|
1501
|
-
} catch (error) {
|
|
1502
|
-
const disabled = isServiceDisabled(error);
|
|
1503
|
-
if (disabled && !consumerIs(error, project)) throw clientApiDisabled(error);
|
|
1504
|
-
if (!disabled && !(notFound && isNotFound(error)) || attempt >= PROPAGATION_ATTEMPTS) {
|
|
1505
|
-
if (disabled) throw new PlayServiceAccountError("api-not-enabled", `Google is still enabling the APIs in ${project.projectId}.\n${error.apiMessage}\nWait a few minutes, then run this again.`, { cause: error });
|
|
1506
|
-
throw error;
|
|
1507
|
-
}
|
|
1508
|
-
await sleep(PROPAGATION_DELAY_MS);
|
|
1509
|
-
}
|
|
1510
|
-
};
|
|
1511
|
-
/**
|
|
1512
|
-
* Whether a disabled-service error is about `project` itself, which waiting
|
|
1513
|
-
* fixes: Google names the consumer by number, and an error naming none
|
|
1514
|
-
* counts as the project's own.
|
|
1515
|
-
*/
|
|
1516
|
-
const consumerIs = (error, project) => error.consumer === void 0 || error.consumer === `projects/${project.projectId}` || (project.projectNumber === void 0 ? true : error.consumer === `projects/${project.projectNumber}`);
|
|
1517
|
-
const enableServices = async ({ google, projectId, sleep }) => {
|
|
1518
|
-
try {
|
|
1519
|
-
const operation = await google("Enabling the APIs", "POST", `${SERVICE_USAGE_API}/v1/projects/${projectId}/services:batchEnable`, { serviceIds: SERVICES });
|
|
1520
|
-
await waitForOperation({
|
|
1521
|
-
request: google,
|
|
1522
|
-
origin: `${SERVICE_USAGE_API}/v1`,
|
|
1523
|
-
operation,
|
|
1524
|
-
action: "Enabling the APIs",
|
|
1525
|
-
sleep
|
|
1526
|
-
});
|
|
1527
|
-
} catch (error) {
|
|
1528
|
-
if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", [
|
|
1529
|
-
`This Google Account may not enable APIs in ${projectId}.`,
|
|
1530
|
-
error.apiMessage || "Permission denied.",
|
|
1531
|
-
"Pick a project you own, or ask its owner for the Editor role."
|
|
1532
|
-
].join("\n"), { cause: error });
|
|
1533
|
-
throw error;
|
|
1534
|
-
}
|
|
1535
|
-
};
|
|
1536
|
-
/** The `hot-updater-play` service account's email, created unless it exists. */
|
|
1537
|
-
const ensureServiceAccount = async ({ google, project, sleep }) => {
|
|
1538
|
-
const { projectId } = project;
|
|
1539
|
-
const email = `${PLAY_SERVICE_ACCOUNT_ID}@${projectId}.iam.gserviceaccount.com`;
|
|
1540
|
-
try {
|
|
1541
|
-
return (await whilePropagating({
|
|
1542
|
-
project,
|
|
1543
|
-
sleep,
|
|
1544
|
-
run: () => google("Creating the service account", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts`, {
|
|
1545
|
-
accountId: "hot-updater-play",
|
|
1546
|
-
serviceAccount: {
|
|
1547
|
-
displayName: "Hot Updater Play uploads",
|
|
1548
|
-
description: "Uploads Android App Bundles to Google Play for hot-updater native-build android --submit play-internal."
|
|
1549
|
-
}
|
|
1550
|
-
})
|
|
1551
|
-
})).email ?? email;
|
|
1552
|
-
} catch (error) {
|
|
1553
|
-
if (isConflict(error)) return email;
|
|
1554
|
-
if (isDenied(error) && !isServiceDisabled(error)) throw new PlayServiceAccountError("project-access-denied", [
|
|
1555
|
-
`This Google Account may not create service accounts in ${projectId}.`,
|
|
1556
|
-
error.apiMessage || "Permission denied.",
|
|
1557
|
-
"Pick a project you own, or ask for the Service Account Admin role."
|
|
1558
|
-
].join("\n"), { cause: error });
|
|
1559
|
-
throw error;
|
|
1560
|
-
}
|
|
1561
|
-
};
|
|
1562
|
-
/**
|
|
1563
|
-
* Makes `email` a Play Console user that may release `packageName`, keeping
|
|
1564
|
-
* any permission it has: the user and the app's grant are created, or the
|
|
1565
|
-
* grant gains the release permissions.
|
|
1566
|
-
*/
|
|
1567
|
-
const grantPlayAccess = async ({ google, developerId, email, packageName }) => {
|
|
1568
|
-
const developer = `${PUBLISHER_API}/developers/${developerId}`;
|
|
1569
|
-
const user = `${developer}/users/${encodeURIComponent(email)}`;
|
|
1570
|
-
try {
|
|
1571
|
-
await google("Adding the Play Console user", "POST", `${developer}/users`, {
|
|
1572
|
-
name: `developers/${developerId}/users/${email}`,
|
|
1573
|
-
email
|
|
1574
|
-
});
|
|
1575
|
-
} catch (error) {
|
|
1576
|
-
if (isDenied(error)) throw notPlayAdmin(developerId, error);
|
|
1577
|
-
if (!isConflict(error)) throw error;
|
|
1578
|
-
}
|
|
1579
|
-
try {
|
|
1580
|
-
await google("Granting access to the app", "POST", `${user}/grants`, {
|
|
1581
|
-
name: `developers/${developerId}/users/${email}/grants/${packageName}`,
|
|
1582
|
-
packageName,
|
|
1583
|
-
appLevelPermissions: APP_PERMISSIONS
|
|
1584
|
-
});
|
|
1585
|
-
return;
|
|
1586
|
-
} catch (error) {
|
|
1587
|
-
if (isNotFound(error)) throw appNotFound(packageName, developerId, error);
|
|
1588
|
-
if (isDenied(error)) throw notPlayAdmin(developerId, error);
|
|
1589
|
-
if (!isConflict(error)) throw error;
|
|
1590
|
-
}
|
|
1591
|
-
const granted = await findGrant({
|
|
1592
|
-
google,
|
|
1593
|
-
developer,
|
|
1594
|
-
email,
|
|
1595
|
-
packageName
|
|
1596
|
-
});
|
|
1597
|
-
const missing = APP_PERMISSIONS.filter((permission) => !granted.includes(permission));
|
|
1598
|
-
if (missing.length === 0) return;
|
|
1599
|
-
await google("Granting access to the app", "PATCH", `${user}/grants/${encodeURIComponent(packageName)}?updateMask=appLevelPermissions`, { appLevelPermissions: [...granted, ...missing] });
|
|
1600
|
-
};
|
|
1601
|
-
/** The app permissions `email` holds on `packageName`, from the user list. */
|
|
1602
|
-
const findGrant = async ({ google, developer, email, packageName }) => {
|
|
1603
|
-
let pageToken;
|
|
1604
|
-
do {
|
|
1605
|
-
const page = await google("Listing the Play Console users", "GET", `${developer}/users?${new URLSearchParams({
|
|
1606
|
-
pageSize: "100",
|
|
1607
|
-
...pageToken ? { pageToken } : {}
|
|
1608
|
-
})}`);
|
|
1609
|
-
const found = page.users?.find((candidate) => candidate.email === email);
|
|
1610
|
-
if (found) return found.grants?.find((grant) => grant.packageName === packageName)?.appLevelPermissions ?? [];
|
|
1611
|
-
pageToken = page.nextPageToken || void 0;
|
|
1612
|
-
} while (pageToken);
|
|
1613
|
-
return [];
|
|
1614
|
-
};
|
|
1615
|
-
/** A new JSON key of the service account, checked and masked in the CLI's output. */
|
|
1616
|
-
const createKey = async ({ google, project, email, sleep }) => {
|
|
1617
|
-
const { projectId } = project;
|
|
1618
|
-
let key;
|
|
1619
|
-
try {
|
|
1620
|
-
key = await whilePropagating({
|
|
1621
|
-
project,
|
|
1622
|
-
sleep,
|
|
1623
|
-
notFound: true,
|
|
1624
|
-
run: () => google("Creating the key", "POST", `${IAM_API}/projects/${projectId}/serviceAccounts/${email}/keys`, {
|
|
1625
|
-
privateKeyType: "TYPE_GOOGLE_CREDENTIALS_FILE",
|
|
1626
|
-
keyAlgorithm: "KEY_ALG_RSA_2048"
|
|
1627
|
-
})
|
|
1628
|
-
});
|
|
1629
|
-
} catch (error) {
|
|
1630
|
-
if (error instanceof GoogleApiError && (error.violations.includes(KEY_CREATION_CONSTRAINT) || /disableServiceAccountKeyCreation/u.test(error.apiMessage))) throw new PlayServiceAccountError("key-creation-disabled", [
|
|
1631
|
-
`iam.disableServiceAccountKeyCreation forbids keys in ${projectId}.`,
|
|
1632
|
-
"Ask an organization policy admin to allow keys for this project,",
|
|
1633
|
-
"or run this again with a project outside the organization."
|
|
1634
|
-
].join("\n"), { cause: error });
|
|
1635
|
-
throw error;
|
|
1636
|
-
}
|
|
1637
|
-
if (!key.name || !key.privateKeyData) throw new Error("Google Cloud created the key without its JSON file.");
|
|
1638
|
-
registerSecretValue(key.privateKeyData);
|
|
1639
|
-
const json = Buffer.from(key.privateKeyData, "base64").toString("utf-8");
|
|
1640
|
-
registerSecretValue(json);
|
|
1641
|
-
let parsed;
|
|
1642
|
-
try {
|
|
1643
|
-
parsed = JSON.parse(json);
|
|
1644
|
-
} catch {
|
|
1645
|
-
parsed = {};
|
|
1646
|
-
}
|
|
1647
|
-
if (typeof parsed.private_key !== "string") {
|
|
1648
|
-
await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`).catch(() => {});
|
|
1649
|
-
throw new Error("Google Cloud created a key that is no JSON key file.");
|
|
1650
|
-
}
|
|
1651
|
-
registerSecretValue(parsed.private_key);
|
|
1652
|
-
return {
|
|
1653
|
-
json,
|
|
1654
|
-
name: key.name,
|
|
1655
|
-
keyId: key.name.split("/").pop()
|
|
1656
|
-
};
|
|
1657
|
-
};
|
|
1658
|
-
//#endregion
|
|
1659
|
-
//#region src/playServiceAccount.ts
|
|
1660
|
-
/**
|
|
1661
|
-
* Hot Updater's Google OAuth client, a "Desktop app" client the sign-in
|
|
1662
|
-
* opens Google's consent screen for. Empty in a build that has none, where
|
|
1663
|
-
* `HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID` and `_SECRET` name one.
|
|
1664
|
-
*/
|
|
1665
|
-
const HOT_UPDATER_GOOGLE_OAUTH_CLIENT = {
|
|
1666
|
-
clientId: "",
|
|
1667
|
-
clientSecret: ""
|
|
1668
|
-
};
|
|
1669
|
-
/**
|
|
1670
|
-
* Hot Updater's issuer, the one place that picks how it is done: Google's
|
|
1671
|
-
* OAuth for installed apps, then the Cloud Resource Manager, Service Usage,
|
|
1672
|
-
* IAM, and Play Developer APIs. Another implementation of
|
|
1673
|
-
* `IssuePlayServiceAccount` replaces it here without touching its callers.
|
|
1674
|
-
*/
|
|
1675
|
-
const issuePlayServiceAccount = (request) => createGoogleKeyIssuer()({
|
|
1676
|
-
...request,
|
|
1677
|
-
oauthClient: request.oauthClient ?? HOT_UPDATER_GOOGLE_OAUTH_CLIENT
|
|
1678
|
-
});
|
|
1679
1556
|
//#endregion
|
|
1680
|
-
export {
|
|
1557
|
+
export { PLAY_TRACKS, PlayVersionCodeUsedError, assertPlaySigned, buildAndroid, checkPlayAccess, enrichNativeBuildAndroidScheme, extractBuiltInBundle, findPlayInternalRelease, findSandboxGradleBlocker, installOnAndroidDevice, listAdbDevices, playConsoleInviteUrl, playTestingUrl, readBuiltApp, readBuiltPackageName, readBuiltVersionCode, readPlayHighestVersionCode, readPlayTrackRelease, resolvePlayUploadServiceAccount, selectAdbDevice, uploadToPlay };
|