@hot-updater/android-helper 1.2.0-rc.3 → 1.2.0-rc.5

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 CHANGED
@@ -37,8 +37,6 @@ let stream_promises = require("stream/promises");
37
37
  let zlib = require("zlib");
38
38
  let node_crypto = require("node:crypto");
39
39
  node_crypto = __toESM(node_crypto, 1);
40
- let node_http = require("node:http");
41
- node_http = __toESM(node_http, 1);
42
40
  //#region src/utils/createGradleLogger.ts
43
41
  const createGradleLogger = ({ logPrefix }) => new _hot_updater_cli_tools.BuildLogger({
44
42
  logPrefix,
@@ -676,7 +674,8 @@ const explain = (error, packageName) => {
676
674
  /**
677
675
  * Requests to the Google Play Developer API for `packageName`, as the
678
676
  * service account: each carries an access token, exchanged for a signed
679
- * assertion and replaced well before it expires.
677
+ * assertion and replaced well before it expires. The key issuer checks a
678
+ * new key's access with it too.
680
679
  */
681
680
  const createPlayClient = ({ json, packageName, fetch }) => {
682
681
  const account = readServiceAccount(json);
@@ -752,6 +751,26 @@ const findPlayInternalRelease = async ({ versionCode, packageName, serviceAccoun
752
751
  }
753
752
  };
754
753
  /**
754
+ * Whether Google Play releases any version of `packageName` on any track,
755
+ * which means Play has the app's upload key. It reads the tracks in an edit
756
+ * it then deletes, changing nothing.
757
+ */
758
+ const hasPlayReleases = async ({ packageName, serviceAccount: { json }, fetch = globalThis.fetch }) => {
759
+ const { app, request } = createPlayClient({
760
+ json,
761
+ packageName,
762
+ fetch
763
+ });
764
+ const { id: editId } = await request("Opening a Google Play edit", "POST", `${API_URL}${app}/edits`, {});
765
+ const edit = `${API_URL}${app}/edits/${encodeURIComponent(editId)}`;
766
+ try {
767
+ const { tracks = [] } = await request("Reading the tracks", "GET", `${edit}/tracks`);
768
+ return tracks.some(({ releases = [] }) => releases.some(({ versionCodes = [] }) => versionCodes.length > 0));
769
+ } finally {
770
+ await request("Deleting the Google Play edit", "DELETE", edit).catch(() => void 0);
771
+ }
772
+ };
773
+ /**
755
774
  * The common name of every Android debug certificate: Android Studio's and
756
775
  * the Android Gradle plugin's (`CN=Android Debug, O=Android, C=US`), and React
757
776
  * Native's template `debug.keystore` (`CN=Android Debug, OU=Android,
@@ -1180,281 +1199,197 @@ var PlayServiceAccountError = class extends Error {
1180
1199
  this.code = code;
1181
1200
  }
1182
1201
  };
1183
- /** The environment variables that replace Hot Updater's Google OAuth client. */
1184
- const GOOGLE_OAUTH_CLIENT_ENV_NAMES = {
1185
- clientId: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID",
1186
- clientSecret: "HOT_UPDATER_GOOGLE_OAUTH_CLIENT_SECRET"
1187
- };
1188
1202
  /** The service account Hot Updater creates, `hot-updater-play@<project>.iam.gserviceaccount.com`. */
1189
1203
  const PLAY_SERVICE_ACCOUNT_ID = "hot-updater-play";
1190
- /** Where a Play Console admin finds the developer account ID. */
1191
- const PLAY_CONSOLE_URL = "https://play.google.com/console";
1192
- //#endregion
1193
- //#region src/google/googleSignIn.ts
1194
- const AUTHORIZATION_URL = "https://accounts.google.com/o/oauth2/v2/auth";
1195
- const TOKEN_URL = "https://oauth2.googleapis.com/token";
1196
- const REVOKE_URL = "https://oauth2.googleapis.com/revoke";
1197
- /** How long the browser has to come back with the sign-in. */
1198
- const SIGN_IN_TIMEOUT_MS = 3e5;
1199
- const base64url = (bytes) => bytes.toString("base64url");
1200
- 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>`;
1201
- /**
1202
- * Signs in with Google as an installed app does (RFC 8252): the browser
1203
- * opens Google's own consent screen, so the password and the second factor
1204
- * stay with Google, and the authorization code comes back to a loopback
1205
- * server on 127.0.0.1, bound to a random port for this sign-in only. The
1206
- * code is exchanged with PKCE (S256), and `state` ties the answer to this
1207
- * request.
1208
- *
1209
- * @param onUrl Sees the sign-in URL, to print and open in a browser.
1210
- */
1211
- const signInWithGoogle = async ({ client, scopes, onUrl, fetch = globalThis.fetch, timeoutMs = SIGN_IN_TIMEOUT_MS }) => {
1212
- const verifier = base64url(node_crypto.default.randomBytes(32));
1213
- const challenge = base64url(node_crypto.default.createHash("sha256").update(verifier).digest());
1214
- const state = base64url(node_crypto.default.randomBytes(16));
1215
- const server = node_http.default.createServer();
1216
- await new Promise((resolve, reject) => {
1217
- server.once("error", reject);
1218
- server.listen(0, "127.0.0.1", () => resolve());
1219
- });
1220
- try {
1221
- const { port } = server.address();
1222
- const redirectUri = `http://127.0.0.1:${port}`;
1223
- const code = new Promise((resolve, reject) => {
1224
- const timer = setTimeout(() => reject(new PlayServiceAccountError("sign-in-cancelled", "The Google sign-in did not finish in time.")), timeoutMs);
1225
- timer.unref();
1226
- server.on("request", (req, res) => {
1227
- const query = new URL(req.url ?? "/", redirectUri).searchParams;
1228
- if (query.get("state") !== state) {
1229
- res.writeHead(404).end();
1230
- return;
1231
- }
1232
- const error = query.get("error");
1233
- const answer = query.get("code");
1234
- 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."));
1235
- clearTimeout(timer);
1236
- 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"}.`));
1237
- else resolve(answer);
1238
- });
1239
- });
1240
- code.catch(() => {});
1241
- const url = new URL(AUTHORIZATION_URL);
1242
- url.search = new URLSearchParams({
1243
- client_id: client.clientId,
1244
- redirect_uri: redirectUri,
1245
- response_type: "code",
1246
- scope: scopes.join(" "),
1247
- code_challenge: challenge,
1248
- code_challenge_method: "S256",
1249
- state,
1250
- prompt: "select_account"
1251
- }).toString();
1252
- await onUrl(url.toString());
1253
- const authorizationCode = await code;
1254
- (0, _hot_updater_cli_tools.registerSecretValue)(authorizationCode);
1255
- const response = await fetch(TOKEN_URL, {
1256
- method: "POST",
1257
- headers: { "content-type": "application/x-www-form-urlencoded" },
1258
- body: new URLSearchParams({
1259
- code: authorizationCode,
1260
- client_id: client.clientId,
1261
- ...client.clientSecret ? { client_secret: client.clientSecret } : {},
1262
- redirect_uri: redirectUri,
1263
- grant_type: "authorization_code",
1264
- code_verifier: verifier
1265
- }).toString()
1266
- });
1267
- const token = await response.json().catch(() => ({}));
1268
- 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}` : ""}`);
1269
- (0, _hot_updater_cli_tools.registerSecretValue)(token.access_token);
1270
- return {
1271
- accessToken: token.access_token,
1272
- scopes: typeof token.scope === "string" ? token.scope.split(" ") : []
1273
- };
1274
- } finally {
1275
- server.closeAllConnections();
1276
- await new Promise((resolve) => server.close(() => resolve()));
1277
- }
1278
- };
1279
- /** Ends a sign-in: Google revokes its access token. Whether Google did. */
1280
- const revokeGoogleToken = async (accessToken, fetch = globalThis.fetch) => {
1281
- try {
1282
- return (await fetch(REVOKE_URL, {
1283
- method: "POST",
1284
- headers: { "content-type": "application/x-www-form-urlencoded" },
1285
- body: new URLSearchParams({ token: accessToken }).toString()
1286
- })).ok;
1287
- } catch {
1288
- return false;
1289
- }
1290
- };
1291
1204
  //#endregion
1292
1205
  //#region src/google/googleKeyIssuer.ts
1293
- const CLOUD_PLATFORM_SCOPE = "https://www.googleapis.com/auth/cloud-platform";
1294
- const ANDROID_PUBLISHER_SCOPE = "https://www.googleapis.com/auth/androidpublisher";
1295
- const SCOPES = [CLOUD_PLATFORM_SCOPE, ANDROID_PUBLISHER_SCOPE];
1296
1206
  const PUBLISHER_API = "https://androidpublisher.googleapis.com/androidpublisher/v3";
1297
1207
  const RESOURCE_MANAGER_API = "https://cloudresourcemanager.googleapis.com";
1298
1208
  const SERVICE_USAGE_API = "https://serviceusage.googleapis.com";
1299
1209
  const IAM_API = "https://iam.googleapis.com/v1";
1210
+ const GCLOUD_INSTALL_URL = "https://cloud.google.com/sdk/docs/install";
1300
1211
  /** IAM creates the service account; the Play Developer API is what it calls. */
1301
1212
  const SERVICES = ["iam.googleapis.com", "androidpublisher.googleapis.com"];
1302
- /**
1303
- * What the service account may do in Play Console, for the app only: read
1304
- * it, and release to testing tracks, which `--submit play-internal` does.
1305
- */
1306
- const APP_PERMISSIONS = ["CAN_VIEW_NON_FINANCIAL_DATA", "CAN_MANAGE_TRACK_APKS"];
1307
1213
  const KEY_CREATION_CONSTRAINT = "constraints/iam.disableServiceAccountKeyCreation";
1308
1214
  /** Retries while Google enables an API or creates a service account. */
1309
1215
  const PROPAGATION_ATTEMPTS = 12;
1310
1216
  const PROPAGATION_DELAY_MS = 1e4;
1217
+ /** Checks of the key's access to the app, about ten minutes of them. */
1218
+ const ACCESS_ATTEMPTS = 120;
1219
+ const ACCESS_DELAY_MS = 5e3;
1311
1220
  const sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1312
- /** The developer account ID in `input`, a number or a Play Console URL. */
1313
- const parseDeveloperId = (input) => {
1314
- const trimmed = input.trim();
1315
- if (/^\d+$/u.test(trimmed)) return trimmed;
1316
- return trimmed.match(/\/developers\/(\d+)(?:[/?#]|$)/u)?.[1];
1317
- };
1221
+ const runWithExeca = async (file, args, options) => (await (0, execa.execa)(file, args, options?.interactive ? { stdio: "inherit" } : { stdin: "ignore" })).stdout ?? "";
1222
+ /**
1223
+ * Play Console's page that invites `email` as a user. `_` stands for the
1224
+ * developer account the browser is signed in to, so no ID is needed.
1225
+ */
1226
+ const playConsoleInviteUrl = (email) => `https://play.google.com/console/u/0/developers/_/users-and-permissions?invite=${encodeURIComponent(email)}`;
1318
1227
  /** A project ID nobody has: Google Cloud's are global. */
1319
1228
  const newProjectId = () => `${PLAY_SERVICE_ACCOUNT_ID}-${node_crypto.default.randomBytes(3).toString("hex")}`;
1320
1229
  const isNotFound = (error) => error instanceof GoogleApiError && error.status === 404;
1321
1230
  const isConflict = (error) => error instanceof GoogleApiError && error.status === 409;
1322
- /** The API is disabled in the OAuth client's own project: waiting does not help. */
1323
- 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 });
1324
- /** Google's own words, after a message that names the likely cause. */
1325
- const googleSays = (error) => error instanceof GoogleApiError && error.apiMessage ? `\nGoogle: ${error.apiMessage}` : "";
1326
- /** A Play Console refusal, as `not-play-admin`. */
1327
- 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 });
1231
+ /** The API is disabled in another project than the one set up: waiting does not help. */
1232
+ const consumerApiDisabled = (error) => new PlayServiceAccountError("api-not-enabled", `${error.apiMessage}\nEnable it in ${error.consumer ?? "that project"}, then run this again.`, { cause: error });
1328
1233
  const isDenied = (error) => error instanceof GoogleApiError && (error.status === 403 || error.apiStatus === "PERMISSION_DENIED");
1234
+ /** The Google Account gcloud uses, if one is active. */
1235
+ const activeAccount = async (run) => (await run("gcloud", [
1236
+ "auth",
1237
+ "list",
1238
+ "--filter=status:ACTIVE",
1239
+ "--format=value(account)"
1240
+ ])).trim().split("\n")[0]?.trim() || void 0;
1241
+ /**
1242
+ * gcloud's access token, after `gcloud auth login` when no account is
1243
+ * active. Stops before any change when gcloud is not installed.
1244
+ */
1245
+ const signInWithGcloud = async ({ run, onStep }) => {
1246
+ try {
1247
+ await run("gcloud", ["--version"]);
1248
+ } catch (error) {
1249
+ throw new PlayServiceAccountError("gcloud-not-installed", [
1250
+ "gcloud CLI is not installed.",
1251
+ "Install it, then run this again:",
1252
+ GCLOUD_INSTALL_URL
1253
+ ].join("\n"), { cause: error });
1254
+ }
1255
+ let account = await activeAccount(run);
1256
+ if (account === void 0) {
1257
+ await run("gcloud", ["auth", "login"], { interactive: true }).catch(() => {});
1258
+ account = await activeAccount(run);
1259
+ if (account === void 0) throw new PlayServiceAccountError("gcloud-not-signed-in", "gcloud has no active Google Account.\nRun gcloud auth login, then run this again.");
1260
+ }
1261
+ onStep(`Signed in to gcloud as ${account}`);
1262
+ const accessToken = (await run("gcloud", ["auth", "print-access-token"])).trim();
1263
+ (0, _hot_updater_cli_tools.registerSecretValue)(accessToken);
1264
+ return accessToken;
1265
+ };
1329
1266
  /**
1330
- * `IssuePlayServiceAccount` with Google's own APIs, after a sign-in on
1331
- * Google's consent screen (OAuth for installed apps, with PKCE and a
1332
- * loopback redirect):
1267
+ * `IssuePlayServiceAccount` with the gcloud CLI's sign-in and Google's own
1268
+ * APIs:
1333
1269
  *
1334
- * 1. the Play Console side is checked first, with no change anywhere: the
1335
- * developer account answers to the account as its admin, and has the app;
1336
- * 2. the chosen Google Cloud project, or a new one, gets the IAM and Play
1337
- * Developer APIs enabled, and the service account `hot-updater-play`;
1338
- * 3. the service account becomes a Play Console user that may release the
1339
- * app to testing tracks;
1340
- * 4. only then is its JSON key created, the last step, so a failure before
1341
- * it leaves no key behind.
1270
+ * 1. gcloud's Google Account, signed in with `gcloud auth login` when none
1271
+ * is active, names the access token the Google Cloud steps use;
1272
+ * 2. the Google Cloud project "Hot Updater Play" an earlier run created, or
1273
+ * a new one, gets the IAM and Play Developer APIs enabled, and the
1274
+ * service account `hot-updater-play` its JSON key;
1275
+ * 3. the developer invites the service account in Play Console, which
1276
+ * `onInvite` opens: gcloud's token may not manage Google Play users;
1277
+ * 4. the key itself opens an edit of the app until Google Play lets it,
1278
+ * and is deleted again when it never does.
1342
1279
  *
1343
- * Each step reuses what an earlier run created: the project, the service
1344
- * account, and its Play Console access.
1280
+ * Each step reuses what an earlier run created: the project and the
1281
+ * service account.
1345
1282
  */
1346
- const createGoogleKeyIssuer = ({ fetch = globalThis.fetch, sleep = sleepFor } = {}) => async (request) => {
1347
- const { packageName, oauthClient, onStep = () => {} } = request;
1348
- if (!oauthClient?.clientId) throw new PlayServiceAccountError("sign-in-not-configured", [
1349
- "This build of Hot Updater has no Google OAuth client to sign in with.",
1350
- "Set these to a \"Desktop app\" OAuth client:",
1351
- `${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientId}, ${GOOGLE_OAUTH_CLIENT_ENV_NAMES.clientSecret}`
1352
- ].join("\n"));
1353
- const signIn = await signInWithGoogle({
1354
- client: oauthClient,
1355
- scopes: SCOPES,
1356
- onUrl: request.onSignInUrl,
1283
+ const createGoogleKeyIssuer = ({ fetch = globalThis.fetch, sleep = sleepFor, run = runWithExeca } = {}) => async (request) => {
1284
+ const { packageName, onStep = () => {} } = request;
1285
+ const accessToken = await signInWithGcloud({
1286
+ run,
1287
+ onStep
1288
+ });
1289
+ const google = createGoogleRequest({
1290
+ accessToken,
1357
1291
  fetch
1358
1292
  });
1359
- const dispose = async () => {
1360
- await revokeGoogleToken(signIn.accessToken, fetch);
1293
+ const project = await chooseProject({
1294
+ google,
1295
+ request,
1296
+ sleep,
1297
+ onStep
1298
+ });
1299
+ const { projectId } = project;
1300
+ onStep(`Enabling the Google Play Developer API in ${projectId}`);
1301
+ await enableServices({
1302
+ google,
1303
+ projectId,
1304
+ sleep
1305
+ });
1306
+ onStep(`Creating the service account in ${projectId}`);
1307
+ const email = await ensureServiceAccount({
1308
+ google,
1309
+ project,
1310
+ sleep
1311
+ });
1312
+ onStep("Creating the service account's JSON key");
1313
+ const key = await createKey({
1314
+ google,
1315
+ project,
1316
+ email,
1317
+ sleep
1318
+ });
1319
+ const revoke = async () => {
1320
+ try {
1321
+ await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`);
1322
+ return true;
1323
+ } catch (error) {
1324
+ return isNotFound(error);
1325
+ }
1361
1326
  };
1327
+ const inviteUrl = playConsoleInviteUrl(email);
1362
1328
  try {
1363
- const missing = SCOPES.filter((scope) => !signIn.scopes.includes(scope));
1364
- 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.`);
1365
- const google = createGoogleRequest({
1366
- accessToken: signIn.accessToken,
1367
- fetch
1368
- });
1369
- const developerInput = await request.askDeveloperId();
1370
- const developerId = parseDeveloperId(developerInput);
1371
- 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.`);
1372
- onStep("Checking the Play Console developer account");
1373
- await checkPlayConsole({
1374
- google,
1375
- developerId,
1376
- packageName
1377
- });
1378
- const project = await chooseProject({
1379
- google,
1380
- request,
1381
- sleep,
1382
- onStep
1383
- });
1384
- const { projectId } = project;
1385
- onStep(`Enabling the Google Play Developer API in ${projectId}`);
1386
- await enableServices({
1387
- google,
1388
- projectId,
1389
- sleep
1390
- });
1391
- onStep(`Creating the service account in ${projectId}`);
1392
- const email = await ensureServiceAccount({
1393
- google,
1394
- project,
1395
- sleep
1396
- });
1397
- onStep(`Giving ${email} release access to ${packageName}`);
1398
- await grantPlayAccess({
1399
- google,
1400
- developerId,
1401
- email,
1402
- packageName
1403
- });
1404
- onStep("Creating the service account's JSON key");
1405
- const key = await createKey({
1406
- google,
1407
- project,
1408
- email,
1329
+ await request.onInvite(inviteUrl, email);
1330
+ onStep("Waiting for the Play Console invite");
1331
+ await waitForPlayAccess({
1332
+ json: key.json,
1333
+ packageName,
1334
+ fetch,
1409
1335
  sleep
1410
1336
  });
1411
- return {
1412
- json: key.json,
1413
- keyId: key.keyId,
1414
- email,
1415
- projectId,
1416
- developerId,
1417
- revoke: async () => {
1418
- try {
1419
- await google("Deleting the key", "DELETE", `${IAM_API}/${key.name}`);
1420
- return true;
1421
- } catch (error) {
1422
- return isNotFound(error);
1423
- }
1424
- },
1425
- dispose
1426
- };
1427
1337
  } catch (error) {
1428
- await dispose();
1429
- throw error;
1338
+ const deleted = await revoke();
1339
+ throw new PlayServiceAccountError("play-access-pending", [
1340
+ `The key can't release ${packageName} yet.`,
1341
+ "Invite the service account in Play Console with release access:",
1342
+ email,
1343
+ inviteUrl,
1344
+ "A new app needs its first .aab uploaded in Play Console.",
1345
+ ...deleted ? [] : [`Delete its unused key ${key.keyId} in Google Cloud:`, `https://console.cloud.google.com/iam-admin/serviceaccounts?project=${encodeURIComponent(projectId)}`],
1346
+ "Then run: npx hot-updater google-play login"
1347
+ ].join("\n"), { cause: error });
1430
1348
  }
1349
+ return {
1350
+ json: key.json,
1351
+ keyId: key.keyId,
1352
+ email,
1353
+ projectId,
1354
+ revoke,
1355
+ dispose: async () => {}
1356
+ };
1431
1357
  };
1432
1358
  /**
1433
- * Whether the signed-in account administers `developerId`, and Google Play
1434
- * has `packageName` there, asked without changing anything: listing the
1435
- * account's users takes the admin permission, and an edit opened on the app
1436
- * is deleted again.
1359
+ * Waits until the key opens an edit of `packageName`, which Google Play
1360
+ * allows once the service account is a Play Console user with access to
1361
+ * the app, then deletes the edit, which changed nothing. Google may not
1362
+ * take a key just created for a while either.
1437
1363
  */
1438
- const checkPlayConsole = async ({ google, developerId, packageName }) => {
1439
- try {
1440
- await google("Listing the Play Console users", "GET", `${PUBLISHER_API}/developers/${developerId}/users?pageSize=1`);
1441
- } catch (error) {
1442
- if (isServiceDisabled(error)) throw clientApiDisabled(error);
1443
- 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 });
1444
- if (isDenied(error)) throw notPlayAdmin(developerId, error);
1445
- throw error;
1446
- }
1447
- let edit;
1448
- try {
1449
- edit = await google(`Opening an edit of ${packageName}`, "POST", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits`);
1450
- } catch (error) {
1451
- if (isServiceDisabled(error)) throw clientApiDisabled(error);
1452
- if (isNotFound(error) || isDenied(error)) throw appNotFound(packageName, developerId, error);
1453
- throw error;
1364
+ const waitForPlayAccess = async ({ json, packageName, fetch, sleep }) => {
1365
+ const play = createPlayClient({
1366
+ json,
1367
+ packageName,
1368
+ fetch
1369
+ });
1370
+ const edits = `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits`;
1371
+ for (let attempt = 1;; attempt++) {
1372
+ if (attempt > 1) await sleep(ACCESS_DELAY_MS);
1373
+ let ready = true;
1374
+ try {
1375
+ await play.authorization();
1376
+ } catch {
1377
+ ready = false;
1378
+ }
1379
+ if (ready) try {
1380
+ const edit = await play.request(`Opening an edit of ${packageName}`, "POST", edits);
1381
+ if (edit?.id) await play.request("Deleting the edit", "DELETE", `${edits}/${edit.id}`).catch(() => {});
1382
+ return;
1383
+ } catch (error) {
1384
+ if (!(error instanceof GooglePlayError) || ![
1385
+ 401,
1386
+ 403,
1387
+ 404
1388
+ ].includes(error.status)) throw error;
1389
+ }
1390
+ if (attempt >= ACCESS_ATTEMPTS) throw new Error("Google Play did not let the key reach the app in time.");
1454
1391
  }
1455
- if (edit.id) await google("Deleting the edit", "DELETE", `${PUBLISHER_API}/applications/${encodeURIComponent(packageName)}/edits/${edit.id}`).catch(() => {});
1456
1392
  };
1457
- 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 });
1458
1393
  /** The account's active projects, every page of them. */
1459
1394
  const listProjects = async (google) => {
1460
1395
  const projects = [];
@@ -1473,20 +1408,41 @@ const listProjects = async (google) => {
1473
1408
  } while (pageToken);
1474
1409
  return projects;
1475
1410
  };
1476
- /** The project the developer picks, or a new one when there is none or they ask. */
1411
+ /** The display name of the project Hot Updater creates, which later runs reuse. */
1412
+ const PROJECT_DISPLAY_NAME = "Hot Updater Play";
1413
+ /**
1414
+ * The project the service account goes in, without asking: the one an
1415
+ * earlier run created, else a new one. Only when Google refuses to create
1416
+ * one does the developer pick among the account's projects.
1417
+ */
1477
1418
  const chooseProject = async ({ google, request, sleep, onStep }) => {
1478
1419
  const projects = await listProjects(google);
1479
- const chosen = projects.length > 0 ? await request.chooseProject(projects.map(({ projectId, displayName }) => ({
1480
- projectId,
1481
- ...displayName ? { displayName } : {}
1482
- }))) : void 0;
1483
- if (chosen !== void 0) return projects.find((project) => project.projectId === chosen) ?? { projectId: chosen };
1420
+ const reused = projects.find((project) => project.displayName === PROJECT_DISPLAY_NAME);
1421
+ if (reused) return reused;
1422
+ try {
1423
+ return await createProject({
1424
+ google,
1425
+ sleep,
1426
+ onStep
1427
+ });
1428
+ } catch (error) {
1429
+ if (!(error instanceof PlayServiceAccountError) || error.code !== "project-quota" && error.code !== "project-create-denied" || projects.length === 0) throw error;
1430
+ const chosen = await request.chooseProject(projects.map(({ projectId, displayName }) => ({
1431
+ projectId,
1432
+ ...displayName ? { displayName } : {}
1433
+ })));
1434
+ if (chosen === void 0) throw error;
1435
+ return projects.find((project) => project.projectId === chosen) ?? { projectId: chosen };
1436
+ }
1437
+ };
1438
+ /** A new project, `hot-updater-play-<random>`, once Google has created it. */
1439
+ const createProject = async ({ google, sleep, onStep }) => {
1484
1440
  const projectId = newProjectId();
1485
1441
  onStep(`Creating the Google Cloud project ${projectId}`);
1486
1442
  try {
1487
1443
  const operation = await google("Creating the Google Cloud project", "POST", `${RESOURCE_MANAGER_API}/v3/projects`, {
1488
1444
  projectId,
1489
- displayName: "Hot Updater Play"
1445
+ displayName: PROJECT_DISPLAY_NAME
1490
1446
  });
1491
1447
  const created = await waitForOperation({
1492
1448
  request: google,
@@ -1504,14 +1460,14 @@ const chooseProject = async ({ google, request, sleep, onStep }) => {
1504
1460
  if (error.status === 429 || error.apiStatus === "RESOURCE_EXHAUSTED" || /quota/iu.test(error.apiMessage)) throw new PlayServiceAccountError("project-quota", [
1505
1461
  "Google Cloud has no project quota left for this account.",
1506
1462
  error.apiMessage || "Quota exceeded.",
1507
- "Run this again and pick an existing project, or delete one at:",
1463
+ "Delete a project you no longer use, then run this again:",
1508
1464
  "https://console.cloud.google.com/cloud-resource-manager"
1509
1465
  ].join("\n"), { cause: error });
1510
1466
  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 });
1511
1467
  if (isDenied(error) || error.apiStatus === "FAILED_PRECONDITION") throw new PlayServiceAccountError("project-create-denied", [
1512
1468
  "This Google Account may not create Google Cloud projects.",
1513
1469
  error.apiMessage || "Permission denied.",
1514
- "Pick an existing project, or ask an admin for the Project Creator role."
1470
+ "Ask an admin for the Project Creator role."
1515
1471
  ].join("\n"), { cause: error });
1516
1472
  throw error;
1517
1473
  }
@@ -1530,7 +1486,7 @@ const whilePropagating = async ({ run, project, sleep, notFound = false }) => {
1530
1486
  return await run();
1531
1487
  } catch (error) {
1532
1488
  const disabled = isServiceDisabled(error);
1533
- if (disabled && !consumerIs(error, project)) throw clientApiDisabled(error);
1489
+ if (disabled && !consumerIs(error, project)) throw consumerApiDisabled(error);
1534
1490
  if (!disabled && !(notFound && isNotFound(error)) || attempt >= PROPAGATION_ATTEMPTS) {
1535
1491
  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 });
1536
1492
  throw error;
@@ -1589,59 +1545,6 @@ const ensureServiceAccount = async ({ google, project, sleep }) => {
1589
1545
  throw error;
1590
1546
  }
1591
1547
  };
1592
- /**
1593
- * Makes `email` a Play Console user that may release `packageName`, keeping
1594
- * any permission it has: the user and the app's grant are created, or the
1595
- * grant gains the release permissions.
1596
- */
1597
- const grantPlayAccess = async ({ google, developerId, email, packageName }) => {
1598
- const developer = `${PUBLISHER_API}/developers/${developerId}`;
1599
- const user = `${developer}/users/${encodeURIComponent(email)}`;
1600
- try {
1601
- await google("Adding the Play Console user", "POST", `${developer}/users`, {
1602
- name: `developers/${developerId}/users/${email}`,
1603
- email
1604
- });
1605
- } catch (error) {
1606
- if (isDenied(error)) throw notPlayAdmin(developerId, error);
1607
- if (!isConflict(error)) throw error;
1608
- }
1609
- try {
1610
- await google("Granting access to the app", "POST", `${user}/grants`, {
1611
- name: `developers/${developerId}/users/${email}/grants/${packageName}`,
1612
- packageName,
1613
- appLevelPermissions: APP_PERMISSIONS
1614
- });
1615
- return;
1616
- } catch (error) {
1617
- if (isNotFound(error)) throw appNotFound(packageName, developerId, error);
1618
- if (isDenied(error)) throw notPlayAdmin(developerId, error);
1619
- if (!isConflict(error)) throw error;
1620
- }
1621
- const granted = await findGrant({
1622
- google,
1623
- developer,
1624
- email,
1625
- packageName
1626
- });
1627
- const missing = APP_PERMISSIONS.filter((permission) => !granted.includes(permission));
1628
- if (missing.length === 0) return;
1629
- await google("Granting access to the app", "PATCH", `${user}/grants/${encodeURIComponent(packageName)}?updateMask=appLevelPermissions`, { appLevelPermissions: [...granted, ...missing] });
1630
- };
1631
- /** The app permissions `email` holds on `packageName`, from the user list. */
1632
- const findGrant = async ({ google, developer, email, packageName }) => {
1633
- let pageToken;
1634
- do {
1635
- const page = await google("Listing the Play Console users", "GET", `${developer}/users?${new URLSearchParams({
1636
- pageSize: "100",
1637
- ...pageToken ? { pageToken } : {}
1638
- })}`);
1639
- const found = page.users?.find((candidate) => candidate.email === email);
1640
- if (found) return found.grants?.find((grant) => grant.packageName === packageName)?.appLevelPermissions ?? [];
1641
- pageToken = page.nextPageToken || void 0;
1642
- } while (pageToken);
1643
- return [];
1644
- };
1645
1548
  /** A new JSON key of the service account, checked and masked in the CLI's output. */
1646
1549
  const createKey = async ({ google, project, email, sleep }) => {
1647
1550
  const { projectId } = project;
@@ -1688,28 +1591,13 @@ const createKey = async ({ google, project, email, sleep }) => {
1688
1591
  //#endregion
1689
1592
  //#region src/playServiceAccount.ts
1690
1593
  /**
1691
- * Hot Updater's Google OAuth client, a "Desktop app" client the sign-in
1692
- * opens Google's consent screen for. Empty in a build that has none, where
1693
- * `HOT_UPDATER_GOOGLE_OAUTH_CLIENT_ID` and `_SECRET` name one.
1594
+ * Hot Updater's issuer, the one place that picks how it is done: gcloud's
1595
+ * sign-in, then the Cloud Resource Manager, Service Usage, IAM, and Play
1596
+ * Developer APIs. Another implementation of `IssuePlayServiceAccount`
1597
+ * replaces it here without touching its callers.
1694
1598
  */
1695
- const HOT_UPDATER_GOOGLE_OAUTH_CLIENT = {
1696
- clientId: "",
1697
- clientSecret: ""
1698
- };
1699
- /**
1700
- * Hot Updater's issuer, the one place that picks how it is done: Google's
1701
- * OAuth for installed apps, then the Cloud Resource Manager, Service Usage,
1702
- * IAM, and Play Developer APIs. Another implementation of
1703
- * `IssuePlayServiceAccount` replaces it here without touching its callers.
1704
- */
1705
- const issuePlayServiceAccount = (request) => createGoogleKeyIssuer()({
1706
- ...request,
1707
- oauthClient: request.oauthClient ?? HOT_UPDATER_GOOGLE_OAUTH_CLIENT
1708
- });
1599
+ const issuePlayServiceAccount = (request) => createGoogleKeyIssuer()(request);
1709
1600
  //#endregion
1710
- exports.GOOGLE_OAUTH_CLIENT_ENV_NAMES = GOOGLE_OAUTH_CLIENT_ENV_NAMES;
1711
- exports.HOT_UPDATER_GOOGLE_OAUTH_CLIENT = HOT_UPDATER_GOOGLE_OAUTH_CLIENT;
1712
- exports.PLAY_CONSOLE_URL = PLAY_CONSOLE_URL;
1713
1601
  exports.PLAY_SERVICE_ACCOUNT_ID = PLAY_SERVICE_ACCOUNT_ID;
1714
1602
  exports.PlayServiceAccountError = PlayServiceAccountError;
1715
1603
  exports.PlayVersionCodeUsedError = PlayVersionCodeUsedError;
@@ -1718,6 +1606,7 @@ exports.buildAndroid = buildAndroid;
1718
1606
  exports.enrichNativeBuildAndroidScheme = enrichNativeBuildAndroidScheme;
1719
1607
  exports.extractBuiltInBundle = extractBuiltInBundle;
1720
1608
  exports.findPlayInternalRelease = findPlayInternalRelease;
1609
+ exports.hasPlayReleases = hasPlayReleases;
1721
1610
  exports.issuePlayServiceAccount = issuePlayServiceAccount;
1722
1611
  exports.readBuiltApp = readBuiltApp;
1723
1612
  exports.readBuiltPackageName = readBuiltPackageName;