Skip to content

Over-the-Air Updates

Your app’s PHP code, templates, styles, and assets run from a bundle inside the installed app. Over-the-air (OTA) updates let you replace that bundle without a new store release, so a PHP bug fix can reach users in hours instead of days.

PAM Native OTA is built to fail closed. Every update is signed with your Ed25519 key, pinned to the exact bundle bytes, checked against the native host that is installed on the device, rolled out to a percentage of installations, and activated atomically. A broken bundle never replaces a working app: the host falls back to the bundle that shipped in the store.

  1. You build a bundle from your project with pam native update:bundle.
  2. A release script describes it in a small manifest (bundle hash, runtime compatibility, channel, rollout percentage) and signs the manifest with your private key.
  3. You publish the bundle, the manifest, and the signature on any HTTPS host: a CDN, object storage, Laravel, or PAM HTTP.
  4. The app downloads the manifest and signature, verifies them with the public key compiled into the app, downloads the bundle, checks its hash, and stages it.
  5. On the next cold launch, the native host re-hashes the active bundle and starts it. If anything is wrong, it quarantines the bundle and starts the store bundle instead.

The download and the server are your choice. The app needs no server package and the server needs no PAM package; the only shared contract is the manifest JSON and the bundle bytes.

Create one Ed25519 key pair per app, once:

Terminal window
pam -r '$k = sodium_crypto_sign_keypair(); echo "secret: ", base64_encode(sodium_crypto_sign_secretkey($k)), "\npublic: ", base64_encode(sodium_crypto_sign_publickey($k)), "\n";'
  • Store the secret key only in your release secret store (for example a CI secret named OTA_SECRET_KEY). Anyone who has it can sign updates for your app.
  • Put the public key in the app’s source code. It is not a secret.

From the project root:

Terminal window
pam native update:bundle

The command stages exactly the files that run on the device (your PHP, Composer dependencies, and assets, minus .pamignore entries), encodes them in the platform-neutral PNA1 format, and writes artifacts/pam-update.pna. It prints the path, the SHA-256, and the size:

PAM Native update bundle
Path /home/alice/acme/artifacts/pam-update.pna
SHA256 0a37c7d7545ad4d586e12ef977da561b9726b5fe9f13cc232b3a36832a320691
Bytes 4183552

To write the bundle somewhere else, pass the project directory and then the output path. The command refuses symbolic links, unsafe paths, more than 10,000 files, files over 8 MiB, and bundles over 256 MiB. Android and iOS use the same bounded decoder.

The manifest is a canonical JSON object. Build it with SignedUpdateManifest, which also validates every field, and sign its exact bytes:

bin/ota-sign.php
<?php
declare(strict_types=1);
require __DIR__.'/../vendor/autoload.php';
use Pam\Native\Protocol;
use Pam\Native\Update\SignedUpdateManifest;
use Pam\Native\Update\UpdateChannel;
$bundle = $argv[1] ?? 'artifacts/pam-update.pna';
$rolloutPercent = (float) ($argv[2] ?? 100);
$secretKey = base64_decode((string) getenv('OTA_SECRET_KEY'), true);
if ($secretKey === false || strlen($secretKey) !== SODIUM_CRYPTO_SIGN_SECRETKEYBYTES) {
fwrite(STDERR, "OTA_SECRET_KEY must be a base64 Ed25519 secret key.\n");
exit(1);
}
$sha256 = hash_file('sha256', $bundle);
$manifest = new SignedUpdateManifest(
buildIdentifier: $sha256,
bundleSha256: $sha256,
abiVersion: Protocol::ABI_VERSION,
protocolVersion: Protocol::VERSION,
channel: UpdateChannel::Stable,
rolloutBasisPoints: (int) round($rolloutPercent * 100),
capabilities: Protocol::CAPABILITIES,
);
$json = $manifest->canonicalJson();
$directory = dirname($bundle);
file_put_contents("{$directory}/manifest.json", $json);
file_put_contents("{$directory}/manifest.sig", base64_encode(sodium_crypto_sign_detached($json, $secretKey)));
copy($bundle, "{$directory}/{$sha256}.pna");
echo "Signed {$sha256} for {$rolloutPercent}% of installations.\n";
Terminal window
OTA_SECRET_KEY='…' pam bin/ota-sign.php artifacts/pam-update.pna 10

The manifest fields:

Field Meaning
buildId A lowercase SHA-256 that identifies this build. Using the bundle hash is the simplest choice.
bundleSha256 The exact lowercase SHA-256 of the bundle.
abiVersion, protocolVersion Must be compatible with the native host installed on the device.
capabilities Runtime capabilities the bundle needs; each must exist in the installed host.
channel 1 stable, 2 beta, 3 nightly (UpdateChannel).
rolloutBasisPoints 0 to 10000: the share of installations, in hundredths of a percent, that may take the update.
version Always 1.

Running the script with the project’s own vendor keeps abiVersion, protocolVersion, and capabilities identical to the runtime the store build shipped.

Upload the three files to your host, for example:

https://updates.example.com/acme/stable/manifest.json
https://updates.example.com/acme/stable/manifest.sig
https://updates.example.com/acme/stable/0a37c7d7…0691.pna

Serve manifest.json byte for byte. The verifier compares the downloaded manifest with its canonical form, so a reformatted or re-encoded manifest (an added newline, pretty printing, escaped slashes) is rejected. Naming the bundle after its hash lets you cache it forever on a CDN.

To widen a rollout, sign a new manifest for the same bundle with a larger percentage. To stop one, publish a manifest at 0.

UpdateVerifier::evaluate() checks the manifest size and schema, the signature, runtime compatibility, whether the build is already active, and the rollout. It returns an UpdateDecision:

UpdateDecisionStatus Meaning
Approved Verified, compatible, and this installation is in the rollout.
InvalidSignature The signature does not match the public key, or the device cannot verify it.
Incompatible The ABI, protocol, or a capability does not match the installed host.
OutsideRollout This installation’s bucket is outside rolloutBasisPoints.
AlreadyCurrent The buildId is already active.
InvalidManifest The manifest is too large, not canonical JSON, or has an invalid schema.

A complete checker, run once at startup or when the app returns to the foreground:

src/Updates/UpdateChecker.php
<?php
declare(strict_types=1);
namespace App\Updates;
use Closure;
use Pam\Native\Http\Http;
use Pam\Native\Http\HttpResponse;
use Pam\Native\Storage\Storage;
use Pam\Native\Update\SignedUpdateManifest;
use Pam\Native\Update\UpdateSlotManager;
use Pam\Native\Update\UpdateVerifier;
use RuntimeException;
final class UpdateChecker
{
private const string BASE_URL = 'https://updates.example.com/acme/stable';
private const string PUBLIC_KEY = 'REPLACE_WITH_YOUR_BASE64_PUBLIC_KEY';
/**
* @param Closure(string $url, Closure(?string $localPath): void $done): void $download
* Downloads the bundle to a local file PHP can read, or reports null.
*/
public function __construct(private readonly Closure $download)
{
}
public function check(): void
{
$this->rolloutBucket(function (int $bucket): void {
Http::get(self::BASE_URL.'/manifest.json', function (HttpResponse $manifest) use ($bucket): void {
if (!$manifest->successful()) {
return;
}
Http::get(self::BASE_URL.'/manifest.sig', function (HttpResponse $signature) use ($manifest, $bucket): void {
if (!$signature->successful()) {
return;
}
$decision = UpdateVerifier::evaluate(
manifestJson: $manifest->body,
signatureBase64: trim($signature->body),
publicKeyBase64: self::PUBLIC_KEY,
currentBuildIdentifier: $this->activeBuildIdentifier(),
rolloutBucket: $bucket,
);
if ($decision->approved()) {
$this->downloadAndStage($decision->manifest);
}
});
});
});
}
private function downloadAndStage(SignedUpdateManifest $manifest): void
{
$url = self::BASE_URL."/{$manifest->bundleSha256}.pna";
($this->download)($url, function (?string $path) use ($manifest): void {
if ($path === null || !UpdateVerifier::verifyBundle($path, $manifest)) {
return;
}
try {
$slots = UpdateSlotManager::forRuntime();
$slots->stage($path, $manifest);
$slots->activate();
} catch (RuntimeException $error) {
error_log('OTA update was not activated: '.$error->getMessage());
}
});
}
/** A stable number from 0 to 9,999 for this installation. */
private function rolloutBucket(Closure $done): void
{
Storage::get('ota.bucket', function (?string $stored) use ($done): void {
if ($stored !== null) {
$done((int) $stored);
return;
}
$bucket = random_int(0, 9_999);
Storage::set('ota.bucket', (string) $bucket);
$done($bucket);
});
}
/** The buildId of the active OTA slot, or "store" for the bundle that shipped with the app. */
private function activeBuildIdentifier(): string
{
$state = getenv('PAM_NATIVE_STATE_DIR');
$metadata = is_string($state) && $state !== '' ? dirname($state).'/updates/active.json' : '';
$active = $metadata !== '' && is_file($metadata)
? json_decode((string) file_get_contents($metadata), true)
: null;
return is_array($active) && is_string($active['buildId'] ?? null) ? $active['buildId'] : 'store';
}
}

activeBuildIdentifier() reads the metadata that UpdateSlotManager writes next to the active slot. When the host quarantines a broken bundle, that file moves away and the app reports the store bundle again.

The bundle download is left to your app because the right tool depends on the bundle size and your network policy. Whatever you use must hand UpdateVerifier::verifyBundle() a local file path that PHP can read.

The mobile PHP runtimes do not include ext-sodium, so UpdateVerifier asks the Android or iOS host to verify the Ed25519 signature with libsodium’s exact rules. When ext-sodium is loaded (for example in tests on your machine), it is used instead, with identical results. A host older than PAM Native 1.19.0 cannot verify signatures, so every update is refused with InvalidSignature.

UpdateSlotManager::forRuntime() manages the update slots in the app’s private directory:

  • stage() checks the size (up to 256 MiB) and hash, copies the bundle into the slot directory, hashes the copy again, and renames it into place as the candidate.
  • activate() moves the current active bundle to the previous slot and the candidate to active, under an exclusive lock. One previous slot is kept.
  • rollback() quarantines the active bundle as failed and restores the previous one.

The new bundle starts on the next cold launch; the running app keeps its current code. On launch, Android and iOS each re-hash active.bundle against its metadata and extract it into a content-addressed private release. A malformed, truncated, or mismatched slot is quarantined and the app starts the bundle that shipped in the store. Extraction is crash-safe: files are written to a staging directory, synced, renamed into place, and only then marked complete, so a process killed mid-extraction is extracted again on the next launch.

To give users an explicit way back, for example from a hidden diagnostics screen:

src/Screens/DiagnosticsScreen.php
use Pam\Native\Update\UpdateSlotManager;
public function rollbackUpdate(): void
{
UpdateSlotManager::forRuntime()->rollback();
$this->message = 'The previous version starts the next time you open the app.';
}
Limit Value
Manifest size 64 KiB
Bundle size 256 MiB
Files per bundle 10,000
Size of one file 8 MiB
Rollout buckets 0–9,999
Capabilities per manifest 256

Unknown manifest fields, non-canonical JSON, invalid keys, mismatched bytes, and incompatible capabilities all fail before anything is staged.