pakstr 0.28.0 → 0.29.1

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.
Files changed (27) hide show
  1. package/README.md +10 -0
  2. package/android-template/app/src/androidTest/java/com/pakstr/app/signer/SignerManagerTest.kt +65 -0
  3. package/android-template/app/src/androidTest/java/com/pakstr/app/signer/local/LocalAccountStoreTest.kt +78 -0
  4. package/android-template/app/src/androidTest/java/com/pakstr/app/utils/SignerPickerBottomSheetTest.kt +40 -6
  5. package/android-template/app/src/main/java/com/pakstr/app/MainActivity.kt +124 -0
  6. package/android-template/app/src/main/java/com/pakstr/app/crypto/Nip19Codec.kt +181 -0
  7. package/android-template/app/src/main/java/com/pakstr/app/signer/SignerManager.kt +25 -0
  8. package/android-template/app/src/main/java/com/pakstr/app/signer/local/LocalAccountImportCandidate.kt +42 -0
  9. package/android-template/app/src/main/java/com/pakstr/app/signer/local/LocalAccountStore.kt +17 -2
  10. package/android-template/app/src/main/java/com/pakstr/app/utils/SignerPickerBottomSheet.kt +80 -4
  11. package/android-template/app/src/main/res/layout/activity_developer_tools.xml +15 -0
  12. package/android-template/app/src/main/res/layout/dialog_picker.xml +62 -0
  13. package/android-template/app/src/main/res/values/strings.xml +15 -2
  14. package/android-template/app/src/test/java/com/pakstr/app/crypto/Nip19CodecTest.kt +178 -0
  15. package/dist/cli.js +13 -6
  16. package/dist/commands/artifactPublisher.js +125 -0
  17. package/dist/commands/build.js +16 -30
  18. package/dist/commands/publish.js +37 -3
  19. package/dist/commands/run.js +60 -29
  20. package/dist/core/apkSignature.js +197 -0
  21. package/dist/core/nsite.js +49 -0
  22. package/dist/runners/DockerGradleRunner.js +45 -24
  23. package/dist/runners/DockerSignRunner.js +58 -19
  24. package/dist/runners/LocalGradleRunner.js +7 -0
  25. package/dist/runners/process.js +51 -0
  26. package/dist/runners/timeouts.js +66 -0
  27. package/package.json +4 -3
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.stageArtifact = stageArtifact;
7
+ exports.publishArtifact = publishArtifact;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const path_1 = __importDefault(require("path"));
10
+ /**
11
+ * Copy `artifactPath` into a fresh staging directory next to `finalPath`, so
12
+ * publishArtifact can move it into place with a same-filesystem rename.
13
+ * Returns the staged path; the staging directory is removed on failure.
14
+ * `description` names the artifact in errors (e.g. "built APK").
15
+ */
16
+ function stageArtifact(artifactPath, finalPath, description = "built APK") {
17
+ const parent = path_1.default.dirname(finalPath);
18
+ const stageDir = fs_1.default.mkdtempSync(path_1.default.join(parent, ".pakstr-stage-"));
19
+ const stagedPath = path_1.default.join(stageDir, "app.apk");
20
+ try {
21
+ fs_1.default.copyFileSync(artifactPath, stagedPath, fs_1.default.constants.COPYFILE_EXCL);
22
+ if (fs_1.default.statSync(stagedPath).size !== fs_1.default.statSync(artifactPath).size) {
23
+ throw new Error(`Staged copy of the ${description} is incomplete (size mismatch); ` +
24
+ "the existing output was left unchanged");
25
+ }
26
+ }
27
+ catch (error) {
28
+ fs_1.default.rmSync(stageDir, { recursive: true, force: true });
29
+ throw error;
30
+ }
31
+ return stagedPath;
32
+ }
33
+ /**
34
+ * Publish a staged APK at `finalPath` without ever leaving the user without
35
+ * their previous APK.
36
+ *
37
+ * The previous APK is copied into the staging directory, then the staged APK
38
+ * atomically replaces `finalPath` (it is never deleted first). If publication
39
+ * fails, the previous APK is restored from the backup. The staging directory
40
+ * (which holds the backup) is only removed once `finalPath` is known to hold a
41
+ * good APK; if restoring fails it is kept so the backup is never lost.
42
+ */
43
+ function publishArtifact(stagedPath, finalPath) {
44
+ const stageDir = path_1.default.dirname(stagedPath);
45
+ const backupPath = path_1.default.join(stageDir, "previous.apk");
46
+ if (isInside(path_1.default.resolve(finalPath), path_1.default.resolve(stageDir))) {
47
+ throw new Error(`Staging directory must not contain the output APK: ${stageDir}`);
48
+ }
49
+ let hadPreviousOutput;
50
+ try {
51
+ hadPreviousOutput = existingOutputIsFile(finalPath);
52
+ if (hadPreviousOutput) {
53
+ fs_1.default.copyFileSync(finalPath, backupPath, fs_1.default.constants.COPYFILE_EXCL);
54
+ if (fs_1.default.statSync(backupPath).size !== fs_1.default.statSync(finalPath).size) {
55
+ throw new Error("Backup of the previous APK is incomplete");
56
+ }
57
+ }
58
+ }
59
+ catch (error) {
60
+ // `finalPath` has not been touched yet, so the staging directory holds
61
+ // nothing worth keeping.
62
+ removeStageDir(stageDir);
63
+ throw error;
64
+ }
65
+ let replacedOutput = false;
66
+ try {
67
+ fs_1.default.renameSync(stagedPath, finalPath);
68
+ replacedOutput = true;
69
+ const stat = fs_1.default.lstatSync(finalPath);
70
+ if (!stat.isFile() || stat.isSymbolicLink()) {
71
+ throw new Error("Final APK publication failed");
72
+ }
73
+ }
74
+ catch (error) {
75
+ try {
76
+ restorePreviousOutput(finalPath, backupPath, hadPreviousOutput, replacedOutput);
77
+ }
78
+ catch (restoreError) {
79
+ throw new Error(`Failed to publish the new APK and restore the previous APK. ` +
80
+ `Previous APK kept at: ${backupPath}`, { cause: new AggregateError([error, restoreError]) });
81
+ }
82
+ removeStageDir(stageDir);
83
+ throw error;
84
+ }
85
+ removeStageDir(stageDir);
86
+ }
87
+ function restorePreviousOutput(finalPath, backupPath, hadPreviousOutput, replacedOutput) {
88
+ if (!hadPreviousOutput) {
89
+ // Don't leave a rejected artifact behind at the output path.
90
+ if (replacedOutput && fs_1.default.lstatSync(finalPath, { throwIfNoEntry: false })?.isFile()) {
91
+ fs_1.default.unlinkSync(finalPath);
92
+ }
93
+ return;
94
+ }
95
+ // A failed rename leaves the destination untouched, so the previous APK is
96
+ // usually still in place; only restore when it was replaced or is missing.
97
+ if (!replacedOutput && existingOutputIsFile(finalPath))
98
+ return;
99
+ fs_1.default.renameSync(backupPath, finalPath);
100
+ if (!existingOutputIsFile(finalPath)) {
101
+ throw new Error("Restored APK is not a regular file");
102
+ }
103
+ }
104
+ function existingOutputIsFile(finalPath) {
105
+ const stat = fs_1.default.lstatSync(finalPath, { throwIfNoEntry: false });
106
+ if (!stat)
107
+ return false;
108
+ if (!stat.isFile() || stat.isSymbolicLink()) {
109
+ throw new Error(`Output path must be a regular file: ${finalPath}`);
110
+ }
111
+ return true;
112
+ }
113
+ function removeStageDir(stageDir) {
114
+ try {
115
+ fs_1.default.rmSync(stageDir, { recursive: true, force: true });
116
+ }
117
+ catch (error) {
118
+ console.warn("Warning: failed to remove APK staging directory:", error instanceof Error ? error.message : "unknown cleanup error");
119
+ }
120
+ }
121
+ function isInside(child, parent) {
122
+ const relative = path_1.default.relative(parent, child);
123
+ return (relative === "" ||
124
+ (relative.split(path_1.default.sep)[0] !== ".." && !path_1.default.isAbsolute(relative)));
125
+ }
@@ -11,6 +11,7 @@ const releaseWorkspace_1 = require("../android/releaseWorkspace");
11
11
  const pakstrConfig_1 = require("../core/pakstrConfig");
12
12
  const androidProject_1 = require("../core/androidProject");
13
13
  const createRunner_1 = require("../runners/createRunner");
14
+ const artifactPublisher_1 = require("./artifactPublisher");
14
15
  /**
15
16
  * `pakstr build` — produce an UNSIGNED release APK at `build.out`.
16
17
  * Spec §5.2. No nsec required.
@@ -24,7 +25,11 @@ async function buildCommand(configPath) {
24
25
  console.log("📱 Out:", finalPath);
25
26
  console.log("🏗️ Builder:", config.build.builder);
26
27
  validateOutputParent(finalPath);
27
- removeExistingOutput(finalPath);
28
+ // Whatever happens next, the APK at finalPath is no longer the signed output
29
+ // of this config: on success it is replaced by a new unsigned APK, and on
30
+ // failure it is kept but may be an older build (e.g. a previous versionCode).
31
+ // Removing its sidecars makes publish refuse it until `pakstr sign` runs.
32
+ removeStaleSigningSidecars(finalPath);
28
33
  const templateRoot = await (0, template_1.ensureTemplate)();
29
34
  const workspace = (0, releaseWorkspace_1.createReleaseWorkspace)(templateRoot);
30
35
  let stagedPath;
@@ -53,7 +58,7 @@ async function buildCommand(configPath) {
53
58
  if (!result.unsigned) {
54
59
  throw new Error("Build runner did not produce an unsigned release APK");
55
60
  }
56
- stagedPath = stageArtifact(result.artifactPath, finalPath);
61
+ stagedPath = (0, artifactPublisher_1.stageArtifact)(result.artifactPath, finalPath);
57
62
  }
58
63
  catch (error) {
59
64
  primaryError = error;
@@ -67,7 +72,6 @@ async function buildCommand(configPath) {
67
72
  }
68
73
  if (primaryError || cleanupError) {
69
74
  removeStagedArtifact(stagedPath);
70
- removeExistingOutput(finalPath);
71
75
  if (primaryError) {
72
76
  if (cleanupError) {
73
77
  console.error("Workspace cleanup also failed:", safeErrorMessage(cleanupError));
@@ -79,7 +83,7 @@ async function buildCommand(configPath) {
79
83
  if (!stagedPath) {
80
84
  throw new Error("Build completed without a staged APK");
81
85
  }
82
- publishArtifact(stagedPath, finalPath);
86
+ (0, artifactPublisher_1.publishArtifact)(stagedPath, finalPath);
83
87
  console.log("\n✅ BUILD COMPLETE (unsigned)");
84
88
  console.log("📦 Output:", finalPath);
85
89
  console.log("➡️ Next: pakstr sign");
@@ -102,33 +106,15 @@ function validateOutputParent(finalPath) {
102
106
  }
103
107
  }
104
108
  }
105
- function stageArtifact(artifactPath, finalPath) {
106
- const parent = path_1.default.dirname(finalPath);
107
- const stageDir = fs_1.default.mkdtempSync(path_1.default.join(parent, ".pakstr-stage-"));
108
- const stagedPath = path_1.default.join(stageDir, "app.apk");
109
- fs_1.default.copyFileSync(artifactPath, stagedPath, fs_1.default.constants.COPYFILE_EXCL);
110
- if (fs_1.default.statSync(stagedPath).size !== fs_1.default.statSync(artifactPath).size) {
111
- fs_1.default.rmSync(stageDir, { recursive: true, force: true });
112
- throw new Error("Staged APK size does not match built artifact");
113
- }
114
- return stagedPath;
115
- }
116
- function publishArtifact(stagedPath, finalPath) {
117
- removeExistingOutput(finalPath);
118
- fs_1.default.renameSync(stagedPath, finalPath);
119
- fs_1.default.rmSync(path_1.default.dirname(stagedPath), { recursive: true, force: true });
120
- if (!fs_1.default.existsSync(finalPath) || !fs_1.default.lstatSync(finalPath).isFile()) {
121
- throw new Error("Final APK publication failed");
122
- }
123
- }
124
- function removeExistingOutput(finalPath) {
125
- if (!fs_1.default.existsSync(finalPath))
126
- return;
127
- const stat = fs_1.default.lstatSync(finalPath);
128
- if (!stat.isFile() || stat.isSymbolicLink()) {
129
- throw new Error(`Refusing to remove non-regular output path: ${finalPath}`);
109
+ function removeStaleSigningSidecars(apkPath) {
110
+ for (const sidecar of [`${apkPath}.signer-sha256`, `${apkPath}.identity-proof`]) {
111
+ try {
112
+ fs_1.default.rmSync(sidecar, { force: true });
113
+ }
114
+ catch (error) {
115
+ console.warn(`Warning: could not remove stale signing sidecar ${sidecar}:`, safeErrorMessage(error));
116
+ }
130
117
  }
131
- fs_1.default.unlinkSync(finalPath);
132
118
  }
133
119
  function removeStagedArtifact(stagedPath) {
134
120
  if (!stagedPath)
@@ -10,6 +10,7 @@ const artifactUpload_1 = require("../core/artifactUpload");
10
10
  const blossom_1 = require("../core/blossom");
11
11
  const giteaRelease_1 = require("../core/giteaRelease");
12
12
  const identityProof_1 = require("../core/identityProof");
13
+ const apkSignature_1 = require("../core/apkSignature");
13
14
  const nostr_1 = require("../core/nostr");
14
15
  const pakstrConfig_1 = require("../core/pakstrConfig");
15
16
  const nsite_1 = require("../core/nsite");
@@ -56,6 +57,9 @@ async function publishCommand(configPath, options = {}) {
56
57
  dryRun: options.dryRun,
57
58
  fetchImpl,
58
59
  });
60
+ reportNsitePartialFailures(nsite);
61
+ if (options.verify && !options.dryRun)
62
+ await (0, nsite_1.verifyNsite)(nsite, transport, fetchImpl);
59
63
  const result = { artifactUrl: "", uploadProvider: null, nsite };
60
64
  if (options.outJson) {
61
65
  fs_1.default.writeFileSync(options.outJson, JSON.stringify({
@@ -95,6 +99,10 @@ async function publishCommand(configPath, options = {}) {
95
99
  throw new Error(`Signer certificate sidecar not found: ${certShaPath}. Run \`pakstr sign\` first.`);
96
100
  }
97
101
  signerCertificateSha256 = fs_1.default.readFileSync(certShaPath, "utf8").trim();
102
+ // The sidecar must describe the APK actually being published: a rebuilt or
103
+ // failed-sign APK left next to sidecars from an earlier sign is refused.
104
+ // The identity proof is bound to this certificate by parseIdentityProofSidecar.
105
+ assertApkSignedWith(apkPath, signerCertificateSha256, certShaPath);
98
106
  const proofPath = `${apkPath}.identity-proof`;
99
107
  if (zapstoreEnabled && fs_1.default.existsSync(proofPath)) {
100
108
  identityProof = (0, identityProof_1.parseIdentityProofSidecar)(fs_1.default.readFileSync(proofPath, "utf8").trim(), proofPath, signerCertificateSha256);
@@ -300,9 +308,9 @@ async function publishCommand(configPath, options = {}) {
300
308
  dryRun: options.dryRun,
301
309
  fetchImpl,
302
310
  });
303
- if (nsiteResult.partialFailures > 0) {
304
- console.log(`⚠️ Nsite published with ${nsiteResult.partialFailures} target failure(s)`);
305
- }
311
+ reportNsitePartialFailures(nsiteResult);
312
+ if (options.verify && !options.dryRun)
313
+ await (0, nsite_1.verifyNsite)(nsiteResult, transport, fetchImpl);
306
314
  }
307
315
  const result = {
308
316
  artifactUrl,
@@ -343,3 +351,29 @@ async function publishCommand(configPath, options = {}) {
343
351
  }
344
352
  return result;
345
353
  }
354
+ function reportNsitePartialFailures(result) {
355
+ if (result.partialFailures > 0) {
356
+ console.log(`⚠️ Nsite published with ${result.partialFailures} target failure(s)`);
357
+ }
358
+ }
359
+ function assertApkSignedWith(apkPath, expectedSha256, certShaPath) {
360
+ if (!/^[0-9a-f]{64}$/.test(expectedSha256)) {
361
+ throw new Error(`Signer certificate sidecar ${certShaPath} is not a lowercase SHA-256. Run \`pakstr sign\` again.`);
362
+ }
363
+ let actual;
364
+ try {
365
+ actual = (0, apkSignature_1.readApkSignerCertificateSha256)(apkPath);
366
+ }
367
+ catch (error) {
368
+ if (!(error instanceof apkSignature_1.ApkSignatureError))
369
+ throw error;
370
+ if (error.reason === "unsigned") {
371
+ throw new Error(`APK at ${apkPath} is not signed (${error.message}). Run \`pakstr sign\` first.`);
372
+ }
373
+ throw new Error(`Cannot use the APK at ${apkPath}: ${error.message}. Rebuild and sign it with \`pakstr run\`.`);
374
+ }
375
+ if (actual !== expectedSha256) {
376
+ throw new Error(`APK at ${apkPath} is signed with certificate ${actual}, but ${certShaPath} expects ${expectedSha256}. ` +
377
+ "The sidecar is stale or the APK was replaced; run `pakstr sign` to sign the current APK.");
378
+ }
379
+ }
@@ -25,19 +25,31 @@ const publish_1 = require("./publish");
25
25
  async function runCommand(configPath, options = {}) {
26
26
  // Step 1: load & validate config, pre-validate nsecs.
27
27
  const config = (0, pakstrConfig_1.loadPakstrConfig)(configPath);
28
- // Verify PAKSTR_NSEC present (fail fast before any work).
29
- (0, nostr_1.requireSigningNsec)(process.env);
28
+ // Verify PAKSTR_NSEC (fail fast before any work). A dry run skips build and
29
+ // sign, so it only needs the publish key checked below — which is
30
+ // PAKSTR_NSEC itself unless publish.publishKey names a separate one.
31
+ if (!options.dryRun)
32
+ (0, nostr_1.requireSigningNsec)(process.env);
30
33
  // Pre-validate the Nostr publish nsec when Zapstore, Blossom, or nsite needs it.
31
34
  if (config.publish.zapstoreEnabled || config.publish.nsite.enabled || (config.publish.upload.enabled && config.publish.upload.provider === "blossom")) {
35
+ const envVar = config.publish.publishKey === undefined
36
+ ? "PAKSTR_NSEC"
37
+ : config.publish.publishKey === null
38
+ ? "PAKSTR_PUBLISH_NSEC"
39
+ : config.publish.publishKey;
32
40
  if (!(0, nostr_1.isPublishNsecPresent)(config.publish.publishKey, process.env)) {
33
- const envVar = config.publish.publishKey === undefined
34
- ? "PAKSTR_NSEC"
35
- : config.publish.publishKey === null
36
- ? "PAKSTR_PUBLISH_NSEC"
37
- : config.publish.publishKey;
38
41
  throw new Error(`${envVar} is required for publishing and must not be empty. ` +
39
42
  `Pre-validation failed before any build work.`);
40
43
  }
44
+ // Decode it too, so a malformed key fails here rather than after build
45
+ // and sign (where sign would also silently skip the identity proof).
46
+ try {
47
+ (0, nostr_1.resolvePublishNsec)(config.publish.publishKey, process.env);
48
+ }
49
+ catch (error) {
50
+ throw new Error(`${envVar} is not a valid nsec: ${error instanceof Error ? error.message : String(error)}. ` +
51
+ `Pre-validation failed before any build work.`);
52
+ }
41
53
  }
42
54
  console.log("\n🚀 pakstr run");
43
55
  console.log("App:", config.app.appName, `(${config.app.appId})`);
@@ -62,6 +74,9 @@ async function runCommand(configPath, options = {}) {
62
74
  console.log("\n✅ pakstr run complete (dry-run)");
63
75
  return;
64
76
  }
77
+ // Keystores already on disk belong to the user (pakstr never writes one), so
78
+ // only files that appear or change during this run are treated as leaks.
79
+ const keystoresBefore = findKeystores(config);
65
80
  // Step 3: build the unsigned APK.
66
81
  console.log("\n— Step 1/3: build —");
67
82
  await (0, build_1.buildCommand)(config.configPath || undefined);
@@ -81,36 +96,52 @@ async function runCommand(configPath, options = {}) {
81
96
  }
82
97
  // Step 6: cleanup. The signed APK at build.out is the artifact and is kept.
83
98
  // Derived signing material is cleaned up inside the sign runner (tmpfs).
84
- verifyNoLeakedKeystores(config);
99
+ verifyNoLeakedKeystores(config, keystoresBefore);
85
100
  console.log("\n✅ pakstr run complete");
86
101
  console.log("Signed APK:", path_1.default.resolve(config.build.out));
87
102
  }
88
- /** Best-effort: ensure no derived .p12 keystore leaked onto disk (§7). */
89
- function verifyNoLeakedKeystores(config) {
90
- const buildDir = path_1.default.join(config.configDir, "build");
91
- if (!fs_1.default.existsSync(buildDir))
92
- return;
103
+ /**
104
+ * Keystore files under `<configDir>/build`, mapped to a fingerprint that
105
+ * changes when a file is replaced (inode) or written in place (size, mtime,
106
+ * and ctime, which also changes if mtime is reset afterwards).
107
+ */
108
+ function findKeystores(config) {
109
+ const found = new Map();
93
110
  const walk = (dir) => {
94
- const found = [];
95
- for (const entry of fs_1.default.readdirSync(dir, { withFileTypes: true })) {
111
+ let entries;
112
+ try {
113
+ entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
114
+ }
115
+ catch {
116
+ return;
117
+ }
118
+ for (const entry of entries) {
96
119
  const p = path_1.default.join(dir, entry.name);
97
120
  if (entry.isDirectory())
98
- found.push(...walk(p));
99
- else if (entry.name.endsWith(".p12") || entry.name.endsWith(".keystore"))
100
- found.push(p);
121
+ walk(p);
122
+ else if (entry.name.endsWith(".p12") || entry.name.endsWith(".keystore")) {
123
+ const stat = fs_1.default.lstatSync(p, { throwIfNoEntry: false });
124
+ if (stat) {
125
+ found.set(p, [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(":"));
126
+ }
127
+ }
101
128
  }
102
- return found;
103
129
  };
104
- const leaked = walk(buildDir);
130
+ walk(path_1.default.join(config.configDir, "build"));
131
+ return found;
132
+ }
133
+ /**
134
+ * Ensure no derived keystore leaked onto disk during this run (§7). Never
135
+ * deletes anything: a keystore may be the user's own (customer-keystore flow,
136
+ * exported derived keys), and pakstr cannot tell the two apart reliably.
137
+ */
138
+ function verifyNoLeakedKeystores(config, before) {
139
+ const leaked = [...findKeystores(config)]
140
+ .filter(([file, fingerprint]) => before.get(file) !== fingerprint)
141
+ .map(([file]) => file);
105
142
  if (leaked.length > 0) {
106
- for (const f of leaked) {
107
- try {
108
- fs_1.default.rmSync(f, { force: true });
109
- }
110
- catch {
111
- /* ignore */
112
- }
113
- }
114
- throw new Error(`Derived keystore material leaked onto disk: ${leaked.join(", ")}`);
143
+ throw new Error(`Keystore files appeared or changed during this run: ${leaked.join(", ")}. ` +
144
+ "pakstr never writes signing keys to disk, so these may be leaked key material; " +
145
+ "they were left in place. Inspect them and delete any you did not create.");
115
146
  }
116
147
  }
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ApkSignatureError = void 0;
7
+ exports.readApkSignerCertificateSha256 = readApkSignerCertificateSha256;
8
+ const crypto_1 = require("crypto");
9
+ const fs_1 = __importDefault(require("fs"));
10
+ /**
11
+ * Reads the signing certificate of an APK from its APK Signing Block (APK
12
+ * Signature Scheme v2/v3, which `pakstr sign` always produces: min SDK 28).
13
+ *
14
+ * This identifies the certificate the APK claims to be signed with; it does not
15
+ * cryptographically verify the signature (Android and apksigner do that on
16
+ * install). It lets `pakstr publish` refuse an APK whose signer does not match
17
+ * the `.signer-sha256` sidecar, e.g. an unsigned rebuild next to stale sidecars.
18
+ *
19
+ * Format: https://source.android.com/docs/security/features/apksigning/v2
20
+ */
21
+ const EOCD_SIGNATURE = 0x06054b50;
22
+ const EOCD_MIN_SIZE = 22;
23
+ const MAX_ZIP_COMMENT = 0xffff;
24
+ const SIGNING_BLOCK_MAGIC = "APK Sig Block 42";
25
+ // Signing blocks are a few KB; refuse absurd sizes from a corrupt file.
26
+ const MAX_SIGNING_BLOCK_SIZE = 64 * 1024 * 1024;
27
+ const SCHEMES = [
28
+ ["v3.1", 0x1b93ad61],
29
+ ["v3", 0xf05368c0],
30
+ ["v2", 0x7109871a],
31
+ ];
32
+ class ApkSignatureError extends Error {
33
+ reason;
34
+ constructor(reason, message) {
35
+ super(message);
36
+ this.reason = reason;
37
+ this.name = "ApkSignatureError";
38
+ }
39
+ }
40
+ exports.ApkSignatureError = ApkSignatureError;
41
+ /** Lowercase hex SHA-256 of the APK's signing certificate (DER), as apksigner prints it. */
42
+ function readApkSignerCertificateSha256(apkPath) {
43
+ const fd = fs_1.default.openSync(apkPath, "r");
44
+ try {
45
+ const block = readSigningBlock(fd, fs_1.default.fstatSync(fd).size);
46
+ if (!block) {
47
+ throw new ApkSignatureError("unsigned", "it has no APK Signature Scheme v2/v3 signing block");
48
+ }
49
+ const certificates = new Set();
50
+ for (const [scheme, id] of SCHEMES) {
51
+ const value = block.get(id);
52
+ if (value) {
53
+ for (const der of signerCertificates(value, scheme))
54
+ certificates.add(certificateSha256(der, scheme));
55
+ }
56
+ }
57
+ if (certificates.size === 0) {
58
+ throw new ApkSignatureError("unsigned", "its signing block has no v2/v3 signature");
59
+ }
60
+ if (certificates.size > 1) {
61
+ throw new ApkSignatureError("multiple-certificates", `it is signed with ${certificates.size} different certificates (multiple signers or key rotation are not supported)`);
62
+ }
63
+ return [...certificates][0];
64
+ }
65
+ finally {
66
+ fs_1.default.closeSync(fd);
67
+ }
68
+ }
69
+ /** The signing block's ID → value pairs, or undefined if the APK has none. */
70
+ function readSigningBlock(fd, fileSize) {
71
+ const eocd = findEndOfCentralDirectory(fd, fileSize);
72
+ const centralDirectorySize = eocd.record.readUInt32LE(12);
73
+ const centralDirectoryOffset = eocd.record.readUInt32LE(16);
74
+ if (centralDirectoryOffset === 0xffffffff || centralDirectorySize === 0xffffffff) {
75
+ throw malformed("ZIP64 archives are not supported");
76
+ }
77
+ // APK signing requires the central directory to sit directly before the EOCD.
78
+ if (centralDirectoryOffset + centralDirectorySize !== eocd.offset) {
79
+ throw malformed("the ZIP central directory is not where the end record says");
80
+ }
81
+ const footerSize = 8 + SIGNING_BLOCK_MAGIC.length;
82
+ if (centralDirectoryOffset < footerSize + 8)
83
+ return undefined;
84
+ const footer = read(fd, centralDirectoryOffset - footerSize, footerSize);
85
+ if (footer.toString("latin1", 8) !== SIGNING_BLOCK_MAGIC)
86
+ return undefined;
87
+ const blockSize = toSafeLength(footer.readBigUInt64LE(0));
88
+ if (blockSize < footerSize || blockSize > MAX_SIGNING_BLOCK_SIZE || blockSize + 8 > centralDirectoryOffset) {
89
+ throw malformed("the signing block size is invalid");
90
+ }
91
+ const blockStart = centralDirectoryOffset - blockSize - 8;
92
+ const block = read(fd, blockStart, blockSize + 8);
93
+ if (toSafeLength(block.readBigUInt64LE(0)) !== blockSize) {
94
+ throw malformed("the signing block header and footer sizes differ");
95
+ }
96
+ const pairs = new Map();
97
+ const end = block.length - footerSize;
98
+ for (let offset = 8; offset < end;) {
99
+ if (end - offset < 12)
100
+ throw malformed("a signing block entry is truncated");
101
+ const length = toSafeLength(block.readBigUInt64LE(offset));
102
+ if (length < 4 || length > end - offset - 8)
103
+ throw malformed("a signing block entry has an invalid length");
104
+ const id = block.readUInt32LE(offset + 8);
105
+ if (pairs.has(id))
106
+ throw malformed(`the signing block repeats entry 0x${id.toString(16)}`);
107
+ pairs.set(id, block.subarray(offset + 12, offset + 8 + length));
108
+ offset += 8 + length;
109
+ }
110
+ return pairs;
111
+ }
112
+ function findEndOfCentralDirectory(fd, fileSize) {
113
+ if (fileSize < EOCD_MIN_SIZE)
114
+ throw malformed("it is too small to be a ZIP archive");
115
+ const tailSize = Math.min(fileSize, EOCD_MIN_SIZE + MAX_ZIP_COMMENT);
116
+ const tail = read(fd, fileSize - tailSize, tailSize);
117
+ // Search backwards; the record's comment must run exactly to the end of file.
118
+ for (let i = tail.length - EOCD_MIN_SIZE; i >= 0; i--) {
119
+ if (tail.readUInt32LE(i) !== EOCD_SIGNATURE)
120
+ continue;
121
+ if (i + EOCD_MIN_SIZE + tail.readUInt16LE(i + 20) !== tail.length)
122
+ continue;
123
+ return { record: tail.subarray(i, i + EOCD_MIN_SIZE), offset: fileSize - tailSize + i };
124
+ }
125
+ throw malformed("it is not a ZIP archive (no end of central directory record)");
126
+ }
127
+ /** First certificate (DER) of every signer in a v2/v3 signature scheme block. */
128
+ function signerCertificates(value, scheme) {
129
+ const signers = new Reader(value, `${scheme} block`).lengthPrefixed();
130
+ const certificates = [];
131
+ while (!signers.done()) {
132
+ const signer = signers.lengthPrefixed();
133
+ const signedData = signer.lengthPrefixed();
134
+ signedData.lengthPrefixed(); // digests
135
+ const certs = signedData.lengthPrefixed();
136
+ if (certs.done())
137
+ throw malformed(`a ${scheme} signer has no certificate`);
138
+ certificates.push(certs.lengthPrefixed().rest());
139
+ }
140
+ if (certificates.length === 0)
141
+ throw malformed(`the ${scheme} block has no signers`);
142
+ return certificates;
143
+ }
144
+ function certificateSha256(der, scheme) {
145
+ try {
146
+ new crypto_1.X509Certificate(der);
147
+ }
148
+ catch {
149
+ throw malformed(`a ${scheme} signer certificate is not valid X.509`);
150
+ }
151
+ return (0, crypto_1.createHash)("sha256").update(der).digest("hex");
152
+ }
153
+ /** Bounds-checked reader of uint32 length-prefixed values. */
154
+ class Reader {
155
+ buffer;
156
+ what;
157
+ offset = 0;
158
+ constructor(buffer, what) {
159
+ this.buffer = buffer;
160
+ this.what = what;
161
+ }
162
+ done() {
163
+ return this.offset >= this.buffer.length;
164
+ }
165
+ lengthPrefixed() {
166
+ if (this.buffer.length - this.offset < 4)
167
+ throw malformed(`the ${this.what} is truncated`);
168
+ const length = this.buffer.readUInt32LE(this.offset);
169
+ const start = this.offset + 4;
170
+ if (length > this.buffer.length - start)
171
+ throw malformed(`the ${this.what} has an invalid length`);
172
+ this.offset = start + length;
173
+ return new Reader(this.buffer.subarray(start, start + length), this.what);
174
+ }
175
+ rest() {
176
+ return this.buffer.subarray(this.offset);
177
+ }
178
+ }
179
+ function read(fd, position, length) {
180
+ const buffer = Buffer.alloc(length);
181
+ let total = 0;
182
+ while (total < length) {
183
+ const bytes = fs_1.default.readSync(fd, buffer, total, length - total, position + total);
184
+ if (bytes === 0)
185
+ throw malformed("it ends unexpectedly");
186
+ total += bytes;
187
+ }
188
+ return buffer;
189
+ }
190
+ function toSafeLength(value) {
191
+ if (value > BigInt(Number.MAX_SAFE_INTEGER))
192
+ throw malformed("a length field is out of range");
193
+ return Number(value);
194
+ }
195
+ function malformed(detail) {
196
+ return new ApkSignatureError("malformed", detail);
197
+ }
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.NSITE_MANIFEST_KIND = void 0;
7
7
  exports.publishNsite = publishNsite;
8
+ exports.verifyNsite = verifyNsite;
8
9
  exports.inspectNsiteDirectory = inspectNsiteDirectory;
9
10
  exports.buildNsiteEventTemplates = buildNsiteEventTemplates;
10
11
  const crypto_1 = require("crypto");
@@ -90,6 +91,54 @@ async function publishNsite(options) {
90
91
  partialFailures,
91
92
  };
92
93
  }
94
+ /**
95
+ * `--verify` for nsite: the manifest must be readable back from a relay that
96
+ * accepted it, and every file downloadable from a server that accepted its
97
+ * upload. Throws listing what could not be verified.
98
+ */
99
+ async function verifyNsite(result, transport, fetchImpl = fetch) {
100
+ if (!transport.query) {
101
+ throw new Error("Nsite verification is not supported by this relay transport (it cannot query events)");
102
+ }
103
+ const query = transport.query.bind(transport);
104
+ const accepted = (targets) => targets.filter(t => t.success && !t.skipped);
105
+ const problems = [];
106
+ for (const { event, relays } of result.events.filter(e => e.event.kind === exports.NSITE_MANIFEST_KIND)) {
107
+ let found = false;
108
+ for (const relay of accepted(relays)) {
109
+ try {
110
+ found = (await query({ ids: [event.id], limit: 1 }, relay.target))?.id === event.id;
111
+ }
112
+ catch {
113
+ // Try the next relay.
114
+ }
115
+ if (found)
116
+ break;
117
+ }
118
+ if (!found)
119
+ problems.push(`manifest ${event.id} was not found on any relay that accepted it`);
120
+ }
121
+ for (const file of result.files) {
122
+ let found = false;
123
+ for (const server of accepted(file.servers)) {
124
+ try {
125
+ found = (await fetchImpl(`${server.target}/${file.sha256}`, { method: "HEAD" })).ok;
126
+ }
127
+ catch {
128
+ // Try the next server.
129
+ }
130
+ if (found)
131
+ break;
132
+ }
133
+ if (!found)
134
+ problems.push(`${file.path} is not downloadable from any server that accepted it`);
135
+ }
136
+ if (problems.length > 0) {
137
+ const shown = problems.slice(0, 5).join("; ");
138
+ const more = problems.length > 5 ? `; and ${problems.length - 5} more` : "";
139
+ throw new Error(`Nsite verification failed: ${shown}${more}`);
140
+ }
141
+ }
93
142
  function inspectNsiteDirectory(directory) {
94
143
  const root = path_1.default.resolve(directory);
95
144
  if (!fs_1.default.existsSync(root) || !fs_1.default.lstatSync(root).isDirectory()) {