native-update 3.1.5 → 3.3.0
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/AI-INTEGRATION-GUIDE.md +199 -3
- package/android/src/main/java/com/aoneahsan/nativeupdate/LiveUpdatePlugin.kt +67 -1
- package/android/src/main/java/com/aoneahsan/nativeupdate/NativeUpdatePlugin.kt +5 -0
- package/cli/commands/remote-shared.js +243 -0
- package/cli/commands/remote.js +211 -0
- package/cli/index.js +144 -0
- package/dist/esm/core/update-check.d.ts +23 -5
- package/dist/esm/core/update-check.js +32 -5
- package/dist/esm/definitions.d.ts +14 -0
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/plugin.js +23 -0
- package/dist/esm/types/app-identity.d.ts +36 -0
- package/dist/esm/types/app-identity.js +1 -0
- package/dist/esm/web.d.ts +2 -1
- package/dist/esm/web.js +5 -0
- package/dist/plugin.cjs.js +1 -1
- package/dist/plugin.esm.js +1 -1
- package/dist/plugin.js +2 -2
- package/docs/CHANGELOG.md +80 -0
- package/docs/KNOWN_LIMITATIONS.md +23 -0
- package/docs/server-requirements.md +15 -0
- package/ios/Plugin/LiveUpdate/LiveUpdatePlugin.swift +18 -1
- package/ios/Plugin/NativeUpdatePlugin.m +1 -0
- package/ios/Plugin/NativeUpdatePlugin.swift +5 -1
- package/package.json +1 -1
package/AI-INTEGRATION-GUIDE.md
CHANGED
|
@@ -214,7 +214,10 @@ Self-hosting instead? Your server must implement this contract
|
|
|
214
214
|
### GET {serverUrl}/v1/updates/check?channel={channel}
|
|
215
215
|
|
|
216
216
|
Request headers sent by the plugin: `X-API-Key`, `X-Device-ID`,
|
|
217
|
-
`X-Current-Version`, `X-Platform` (and `X-App-Version` when known).
|
|
217
|
+
`X-Current-Version`, `X-Platform` (and `X-App-Version` when known). Native
|
|
218
|
+
builds also send client-identity headers (`X-Android-Package`,
|
|
219
|
+
`X-Android-Cert-Sha256`/`-Sha1`, `X-Ios-Bundle-Id`) — see "Lock your API key to
|
|
220
|
+
your clients" below.
|
|
218
221
|
|
|
219
222
|
Response — `200` with `available: false` when there is no update, `200` with:
|
|
220
223
|
|
|
@@ -234,6 +237,51 @@ Response — `200` with `available: false` when there is no update, `200` with:
|
|
|
234
237
|
|
|
235
238
|
`downloadUrl` must be an HTTPS URL that returns the bundle zip.
|
|
236
239
|
|
|
240
|
+
## Lock your API key to your clients (restrictions)
|
|
241
|
+
|
|
242
|
+
The `nu_app_…` API key is meant to ship **inside** your app — you do not need
|
|
243
|
+
your own backend just to hide it. In the dashboard (**Apps → API Keys →
|
|
244
|
+
Restrictions**) you can lock each key to the clients that may use it:
|
|
245
|
+
|
|
246
|
+
- **Web** — allowed origins (exact `https://app.example.com` or a
|
|
247
|
+
`https://*.example.com` wildcard). Enforced against the browser's `Origin`
|
|
248
|
+
header, so the update API is safe to call directly from your web app. (The
|
|
249
|
+
`/v1/*` API sends permissive CORS precisely so browsers can call it; the real
|
|
250
|
+
gate is this per-key check, not CORS.)
|
|
251
|
+
- **Android** — allowed apps by package name + signing-cert SHA-256/SHA-1
|
|
252
|
+
(`keytool -list -printcert`; add both your upload key and the Play App
|
|
253
|
+
Signing cert).
|
|
254
|
+
- **iOS** — allowed apps by bundle identifier.
|
|
255
|
+
|
|
256
|
+
A key with **no** restrictions works from anywhere (default). A restricted key
|
|
257
|
+
that a client doesn't satisfy gets `403 { error: { code:
|
|
258
|
+
"API_KEY_RESTRICTED", … } }`.
|
|
259
|
+
|
|
260
|
+
The plugin sends the needed headers automatically on native update checks. If
|
|
261
|
+
you run your **own** fetch, read the identity first and attach the headers:
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
import { NativeUpdate } from 'native-update';
|
|
265
|
+
|
|
266
|
+
const id = await NativeUpdate.getAppIdentity();
|
|
267
|
+
const headers: Record<string, string> = { 'X-API-Key': apiKey, /* … */ };
|
|
268
|
+
if (id.platform === 'android') {
|
|
269
|
+
if (id.packageName) headers['X-Android-Package'] = id.packageName;
|
|
270
|
+
if (id.certSha256) headers['X-Android-Cert-Sha256'] = id.certSha256;
|
|
271
|
+
if (id.certSha1) headers['X-Android-Cert-Sha1'] = id.certSha1;
|
|
272
|
+
} else if (id.platform === 'ios') {
|
|
273
|
+
if (id.bundleId) headers['X-Ios-Bundle-Id'] = id.bundleId;
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
**Requirements & honesty:** Android/iOS restrictions only take effect for apps
|
|
278
|
+
built with **native-update ≥ 3.2.0** (older builds send no identity and are
|
|
279
|
+
blocked by an Android/iOS restriction — web restrictions work with any version).
|
|
280
|
+
The native identity headers are **client-attested** (parity with Google Maps
|
|
281
|
+
API-key app restrictions): they stop cross-site/casual key reuse and quota
|
|
282
|
+
abuse, not a determined attacker replaying headers by hand. Only the web
|
|
283
|
+
`Origin` check is browser-enforced.
|
|
284
|
+
|
|
237
285
|
## CLI Tools
|
|
238
286
|
|
|
239
287
|
```bash
|
|
@@ -250,8 +298,156 @@ npx native-update bundle verify ./bundles/1.2.0.zip --key ./public.key
|
|
|
250
298
|
npx native-update keys generate --type rsa --size 4096
|
|
251
299
|
```
|
|
252
300
|
|
|
253
|
-
Upload the resulting bundle through
|
|
254
|
-
|
|
301
|
+
Upload the resulting bundle through the dashboard, the public management API, or
|
|
302
|
+
the `deploy` command below.
|
|
303
|
+
|
|
304
|
+
## Public Management API (access tokens)
|
|
305
|
+
|
|
306
|
+
Everything the dashboard does — list apps, upload a bundle, publish, promote,
|
|
307
|
+
adjust rollout — is also an HTTP API. Use it from CI, a script, or an agent.
|
|
308
|
+
|
|
309
|
+
**Two token families. They are not interchangeable.**
|
|
310
|
+
|
|
311
|
+
| Token | Prefix | Used by | Where it may live |
|
|
312
|
+
|---|---|---|---|
|
|
313
|
+
| App API key | `nu_app_…` | The plugin in your app (`/api/v1/updates/check`) | Ships in the app. Lock it down with client restrictions. |
|
|
314
|
+
| **Access token** | `nu_pat_…` | **You / CI / an agent** (`/api/public/v1/*`) | **Server or CI secret only — NEVER a browser or a repo.** |
|
|
315
|
+
|
|
316
|
+
An access token is a user-level secret with no origin restrictions. Anyone
|
|
317
|
+
holding it can manage the apps it is scoped to. Treat it like a password.
|
|
318
|
+
|
|
319
|
+
**Create one:** dashboard → **Access Tokens** → *New token*. Tick the apps it may
|
|
320
|
+
manage, and grant *Allow deleting builds* only if you need it. Copy the token
|
|
321
|
+
anytime from that page.
|
|
322
|
+
|
|
323
|
+
### Authenticate
|
|
324
|
+
|
|
325
|
+
```
|
|
326
|
+
Authorization: Bearer nu_pat_…
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Base URL: `https://nativeupdatebe.aoneahsan.com/api/public/v1`
|
|
330
|
+
(`X-Access-Token: nu_pat_…` also works if your transport owns `Authorization`.)
|
|
331
|
+
|
|
332
|
+
**Start here.** `GET /token` tells an agent who it is and what it may touch, so
|
|
333
|
+
it never has to guess an app id:
|
|
334
|
+
|
|
335
|
+
```bash
|
|
336
|
+
curl -H "Authorization: Bearer $NATIVE_UPDATE_TOKEN" \
|
|
337
|
+
https://nativeupdatebe.aoneahsan.com/api/public/v1/token
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
```json
|
|
341
|
+
{ "data": {
|
|
342
|
+
"name": "GitHub Actions",
|
|
343
|
+
"permissions": ["manage"],
|
|
344
|
+
"apps": [{ "id": 12, "app_id": "com.example.app", "name": "Example" }]
|
|
345
|
+
} }
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
### Endpoints
|
|
349
|
+
|
|
350
|
+
`{app}` accepts the numeric id **or** the string `app_id` (`com.example.app`).
|
|
351
|
+
|
|
352
|
+
| Method | Path | Does |
|
|
353
|
+
|---|---|---|
|
|
354
|
+
| GET | `/token` | What this token is and which apps it manages |
|
|
355
|
+
| GET | `/apps` | Apps this token manages (paginated) |
|
|
356
|
+
| GET | `/apps/{app}` | App details |
|
|
357
|
+
| GET | `/apps/{app}/builds` | Builds; filter `?channel=` `?status=` |
|
|
358
|
+
| GET | `/apps/{app}/builds/{build}` | Build details |
|
|
359
|
+
| POST | `/apps/{app}/builds` | **Upload a bundle — queued, returns 202** |
|
|
360
|
+
| PATCH | `/apps/{app}/builds/{build}` | Set `status` (`active`/`paused`/`archived`), release notes |
|
|
361
|
+
| POST | `/apps/{app}/builds/{build}/promote` | Copy into another channel (`target_channel`) |
|
|
362
|
+
| PATCH | `/apps/{app}/builds/{build}/rollout` | Set `rollout_percentage` (0–100) |
|
|
363
|
+
| DELETE | `/apps/{app}/builds/{build}` | Delete — needs the `builds.delete` permission |
|
|
364
|
+
| GET | `/jobs/{jobId}` | Status of queued work |
|
|
365
|
+
|
|
366
|
+
Machine-readable spec (OpenAPI 3.1):
|
|
367
|
+
<https://nativeupdate-docs.aoneahsan.com/openapi/public-api.json>
|
|
368
|
+
|
|
369
|
+
### Upload: 202 now, live in a moment
|
|
370
|
+
|
|
371
|
+
Signing and storing a bundle takes too long to hold a request open, so an upload
|
|
372
|
+
is **always queued**. You get a job id; poll it until the build goes live.
|
|
373
|
+
|
|
374
|
+
```bash
|
|
375
|
+
# 1. Upload → 202
|
|
376
|
+
curl -X POST \
|
|
377
|
+
-H "Authorization: Bearer $NATIVE_UPDATE_TOKEN" \
|
|
378
|
+
-F "file=@./bundle.zip" \
|
|
379
|
+
-F "version=1.2.0" \
|
|
380
|
+
-F "channel=production" \
|
|
381
|
+
-F "release_notes=Bug fixes" \
|
|
382
|
+
https://nativeupdatebe.aoneahsan.com/api/public/v1/apps/com.example.app/builds
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
```json
|
|
386
|
+
{ "data": {
|
|
387
|
+
"job_id": "01hq2xk8...",
|
|
388
|
+
"status_url": "https://nativeupdatebe.aoneahsan.com/api/public/v1/jobs/01hq2xk8...",
|
|
389
|
+
"build": { "id": 42, "version": "1.2.0", "status": "processing" }
|
|
390
|
+
} }
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
```bash
|
|
394
|
+
# 2. Poll until status is "completed" or "failed"
|
|
395
|
+
curl -H "Authorization: Bearer $NATIVE_UPDATE_TOKEN" \
|
|
396
|
+
https://nativeupdatebe.aoneahsan.com/api/public/v1/jobs/01hq2xk8...
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
```json
|
|
400
|
+
{ "data": {
|
|
401
|
+
"status": "completed",
|
|
402
|
+
"result": { "build_id": 42, "version": "1.2.0", "channel": "production" }
|
|
403
|
+
} }
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
**Agents: poll, don't assume.** A 202 means *accepted*, not *live*. The build
|
|
407
|
+
stays `processing` and devices never see it until the job reports `completed`.
|
|
408
|
+
On `failed`, read `error` — the build never goes live and the owner is emailed.
|
|
409
|
+
Poll every ~5s; processing normally finishes in well under a minute.
|
|
410
|
+
|
|
411
|
+
### CLI equivalents
|
|
412
|
+
|
|
413
|
+
```bash
|
|
414
|
+
export NATIVE_UPDATE_TOKEN=nu_pat_… # never pass --token in CI; it leaks into logs
|
|
415
|
+
|
|
416
|
+
npx native-update token info # who am I, which apps?
|
|
417
|
+
npx native-update apps list
|
|
418
|
+
npx native-update builds list com.example.app
|
|
419
|
+
|
|
420
|
+
# Deploy: zips the directory, uploads, and (with --wait) blocks until live.
|
|
421
|
+
# Exits non-zero if the release fails, so CI fails too.
|
|
422
|
+
npx native-update deploy ./dist --app com.example.app --version 1.2.0 --wait
|
|
423
|
+
|
|
424
|
+
npx native-update builds promote com.example.app 42 --to production
|
|
425
|
+
npx native-update builds rollout com.example.app 42 --percent 10
|
|
426
|
+
npx native-update builds status com.example.app 42 --set paused
|
|
427
|
+
npx native-update jobs status 01hq2xk8... --wait
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
### Errors
|
|
431
|
+
|
|
432
|
+
Every error uses one envelope:
|
|
433
|
+
|
|
434
|
+
```json
|
|
435
|
+
{ "error": { "code": "APP_NOT_FOUND", "message": "…", "details": { } } }
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
| Status | Code | Meaning |
|
|
439
|
+
|---|---|---|
|
|
440
|
+
| 401 | `MISSING_ACCESS_TOKEN`, `INVALID_ACCESS_TOKEN_FORMAT`, `ACCESS_TOKEN_NOT_FOUND`, `ACCESS_TOKEN_INVALID` | No, malformed, unknown, revoked, or expired token |
|
|
441
|
+
| 403 | `TOKEN_PERMISSION_DENIED` | The token lacks an opt-in permission (`details.required_permission`) |
|
|
442
|
+
| 404 | `APP_NOT_FOUND`, `BUILD_NOT_FOUND`, `JOB_NOT_FOUND` | Absent **or** outside this token's apps — the two are deliberately indistinguishable |
|
|
443
|
+
| 409 | `VERSION_ALREADY_EXISTS` | That version already exists in the channel |
|
|
444
|
+
| 422 | `VERSION_NOT_NEWER` | Not newer than the channel's current head — bump the version |
|
|
445
|
+
| 429 | — | Rate limited: 120 requests/min; uploads 30/hour |
|
|
446
|
+
|
|
447
|
+
**A 404 does not always mean "gone".** Scoping errors answer 404 on purpose, so
|
|
448
|
+
the API cannot be used to discover which apps exist. If an app id you believe in
|
|
449
|
+
returns 404, check the token's app list with `GET /token` before concluding the
|
|
450
|
+
app is missing.
|
|
255
451
|
|
|
256
452
|
## Platform-Specific Setup
|
|
257
453
|
|
|
@@ -37,6 +37,16 @@ class LiveUpdatePlugin(
|
|
|
37
37
|
/** Hard cap on uncompressed bundle size (zip-bomb defense). */
|
|
38
38
|
private val maxUncompressedBundleBytes: Long = 500L * 1024 * 1024
|
|
39
39
|
|
|
40
|
+
/**
|
|
41
|
+
* The app's signing-certificate fingerprints (SHA-256, SHA-1) as lowercase
|
|
42
|
+
* hex with no separators, computed once. Used for API-key client
|
|
43
|
+
* restrictions (the X-Android-Cert-* headers + getAppIdentity()). Null on
|
|
44
|
+
* any failure — identity is best-effort and must NEVER break an update check.
|
|
45
|
+
*/
|
|
46
|
+
private val signingCertFingerprints: Pair<String?, String?> by lazy { computeSigningCertFingerprints() }
|
|
47
|
+
private val appSigningSha256: String? get() = signingCertFingerprints.first
|
|
48
|
+
private val appSigningSha1: String? get() = signingCertFingerprints.second
|
|
49
|
+
|
|
40
50
|
companion object {
|
|
41
51
|
// SharedPreferences keys. Kept as constants so A2 (boot-time
|
|
42
52
|
// re-verification) and A3 (crash-loop auto-rollback) stay in sync
|
|
@@ -424,8 +434,59 @@ class LiveUpdatePlugin(
|
|
|
424
434
|
}
|
|
425
435
|
}
|
|
426
436
|
|
|
437
|
+
/**
|
|
438
|
+
* The app's client identity for API-key client restrictions: applicationId
|
|
439
|
+
* + signing-cert SHA-256/SHA-1. Consumed by the dashboard "Restrictions"
|
|
440
|
+
* UI and attached as X-Android-* headers on native update checks.
|
|
441
|
+
*/
|
|
442
|
+
fun getAppIdentity(call: PluginCall) {
|
|
443
|
+
val result = JSObject()
|
|
444
|
+
result.put("platform", "android")
|
|
445
|
+
result.put("packageName", context.packageName)
|
|
446
|
+
appSigningSha256?.let { result.put("certSha256", it) }
|
|
447
|
+
appSigningSha1?.let { result.put("certSha1", it) }
|
|
448
|
+
call.resolve(result)
|
|
449
|
+
}
|
|
450
|
+
|
|
427
451
|
// Private helper methods
|
|
428
|
-
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Read the app's first signing certificate and return (SHA-256, SHA-1) as
|
|
455
|
+
* lowercase hex, no separators. Uses GET_SIGNING_CERTIFICATES on API 28+
|
|
456
|
+
* (v2/v3 signing) and falls back to the deprecated GET_SIGNATURES on API
|
|
457
|
+
* 22–27. Any failure yields (null, null) — never throws.
|
|
458
|
+
*/
|
|
459
|
+
private fun computeSigningCertFingerprints(): Pair<String?, String?> {
|
|
460
|
+
return try {
|
|
461
|
+
val pm = context.packageManager
|
|
462
|
+
val pkg = context.packageName
|
|
463
|
+
val certBytes: ByteArray? = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
|
|
464
|
+
val info = pm.getPackageInfo(pkg, android.content.pm.PackageManager.GET_SIGNING_CERTIFICATES)
|
|
465
|
+
info.signingInfo?.apkContentsSigners?.firstOrNull()?.toByteArray()
|
|
466
|
+
} else {
|
|
467
|
+
@Suppress("DEPRECATION")
|
|
468
|
+
val info = pm.getPackageInfo(pkg, android.content.pm.PackageManager.GET_SIGNATURES)
|
|
469
|
+
@Suppress("DEPRECATION")
|
|
470
|
+
info.signatures?.firstOrNull()?.toByteArray()
|
|
471
|
+
}
|
|
472
|
+
if (certBytes == null) {
|
|
473
|
+
Pair(null, null)
|
|
474
|
+
} else {
|
|
475
|
+
Pair(hashHex(certBytes, "SHA-256"), hashHex(certBytes, "SHA-1"))
|
|
476
|
+
}
|
|
477
|
+
} catch (e: Exception) {
|
|
478
|
+
Pair(null, null)
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
private fun hashHex(bytes: ByteArray, algorithm: String): String {
|
|
483
|
+
// `it.toInt() and 0xFF` is REQUIRED: a bare Byte sign-extends in
|
|
484
|
+
// "%02x".format (e.g. 0xFF → "ffffffff"), which would corrupt the
|
|
485
|
+
// fingerprint and break cert matching.
|
|
486
|
+
return MessageDigest.getInstance(algorithm).digest(bytes)
|
|
487
|
+
.joinToString("") { "%02x".format(it.toInt() and 0xFF) }
|
|
488
|
+
}
|
|
489
|
+
|
|
429
490
|
/**
|
|
430
491
|
* v3 wire contract (mirrors src/core/update-check.ts):
|
|
431
492
|
* GET {serverUrl}/v1/updates/check?channel={channel}
|
|
@@ -456,7 +517,12 @@ class LiveUpdatePlugin(
|
|
|
456
517
|
.header("X-Device-ID", getOrCreateDeviceId())
|
|
457
518
|
.header("X-Current-Version", getCurrentVersion())
|
|
458
519
|
.header("X-Platform", "android")
|
|
520
|
+
.header("X-Android-Package", context.packageName)
|
|
459
521
|
getBinaryVersion()?.let { requestBuilder.header("X-App-Version", it) }
|
|
522
|
+
// App-identity headers for API-key client restrictions. Best-effort:
|
|
523
|
+
// null fingerprints (e.g. odd signing setup) simply omit the header.
|
|
524
|
+
appSigningSha256?.let { requestBuilder.header("X-Android-Cert-Sha256", it) }
|
|
525
|
+
appSigningSha1?.let { requestBuilder.header("X-Android-Cert-Sha1", it) }
|
|
460
526
|
|
|
461
527
|
val response = okHttpClient.newCall(requestBuilder.build()).execute()
|
|
462
528
|
if (response.isSuccessful) {
|
|
@@ -240,6 +240,11 @@ class NativeUpdatePlugin : Plugin() {
|
|
|
240
240
|
fun getLatest(call: PluginCall) {
|
|
241
241
|
liveUpdatePlugin.getLatest(call)
|
|
242
242
|
}
|
|
243
|
+
|
|
244
|
+
@PluginMethod
|
|
245
|
+
fun getAppIdentity(call: PluginCall) {
|
|
246
|
+
liveUpdatePlugin.getAppIdentity(call)
|
|
247
|
+
}
|
|
243
248
|
|
|
244
249
|
@PluginMethod
|
|
245
250
|
fun setChannel(call: PluginCall) {
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import os from 'os';
|
|
5
|
+
import { ZipArchive } from 'archiver';
|
|
6
|
+
import { createWriteStream, createReadStream } from 'fs';
|
|
7
|
+
|
|
8
|
+
/** Where the hosted backend lives unless told otherwise. */
|
|
9
|
+
export const DEFAULT_SERVER = 'https://nativeupdatebe.aoneahsan.com';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Resolve the access token. A flag wins over the environment, but the
|
|
13
|
+
* environment is the intended path for CI — passing a secret as an argv flag
|
|
14
|
+
* leaks it into shell history and process listings.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveToken(options) {
|
|
17
|
+
const token = options.token || process.env.NATIVE_UPDATE_TOKEN;
|
|
18
|
+
|
|
19
|
+
if (!token) {
|
|
20
|
+
console.error(chalk.red('Error: no access token.'));
|
|
21
|
+
console.error(
|
|
22
|
+
chalk.gray(' Set NATIVE_UPDATE_TOKEN, or pass --token. Create a token at\n') +
|
|
23
|
+
chalk.blue(' https://nativeupdate.aoneahsan.com/dashboard/access-tokens')
|
|
24
|
+
);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (!/^nu_pat_[a-f0-9]{64}_[a-f0-9]{4}$/.test(token)) {
|
|
29
|
+
console.error(chalk.red('Error: that does not look like an access token.'));
|
|
30
|
+
console.error(
|
|
31
|
+
chalk.gray(
|
|
32
|
+
' Access tokens start with nu_pat_. An app API key (nu_app_…) authenticates\n' +
|
|
33
|
+
' the device update plane and is not accepted here.'
|
|
34
|
+
)
|
|
35
|
+
);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return token;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function resolveServer(options) {
|
|
43
|
+
const base = options.server || process.env.NATIVE_UPDATE_SERVER || DEFAULT_SERVER;
|
|
44
|
+
return base.replace(/\/+$/, '');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A thin client over the public management API. Every call returns the parsed
|
|
49
|
+
* `data` envelope, or exits non-zero after printing the API's own error message
|
|
50
|
+
* — the backend already explains what went wrong and how to fix it, so the CLI
|
|
51
|
+
* relays that rather than inventing its own wording.
|
|
52
|
+
*/
|
|
53
|
+
export function apiClient(options) {
|
|
54
|
+
const token = resolveToken(options);
|
|
55
|
+
const server = resolveServer(options);
|
|
56
|
+
const base = `${server}/api/public/v1`;
|
|
57
|
+
|
|
58
|
+
async function handle(res, path) {
|
|
59
|
+
if (res.status === 204) return null;
|
|
60
|
+
|
|
61
|
+
let body;
|
|
62
|
+
try {
|
|
63
|
+
body = await res.json();
|
|
64
|
+
} catch {
|
|
65
|
+
fail(`${res.status} ${res.statusText}`, `Unreadable response from ${base}${path}`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (!res.ok) {
|
|
69
|
+
const err = body?.error ?? {};
|
|
70
|
+
// Laravel's validator answers 422 with {message, errors:{field:[…]}},
|
|
71
|
+
// which is a different shape from our {error:{code,message}} envelope.
|
|
72
|
+
const message = err.message ?? body?.message ?? `${res.status} ${res.statusText}`;
|
|
73
|
+
const details = body?.errors
|
|
74
|
+
? Object.entries(body.errors)
|
|
75
|
+
.map(([field, msgs]) => ` ${field}: ${[].concat(msgs).join(' ')}`)
|
|
76
|
+
.join('\n')
|
|
77
|
+
: null;
|
|
78
|
+
fail(err.code ?? `HTTP ${res.status}`, message, details);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return body;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function fail(code, message, details) {
|
|
85
|
+
console.error(chalk.red(`Error (${code}): ${message}`));
|
|
86
|
+
if (details) console.error(chalk.gray(details));
|
|
87
|
+
process.exit(1);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
server,
|
|
92
|
+
base,
|
|
93
|
+
|
|
94
|
+
async get(path) {
|
|
95
|
+
const res = await fetch(`${base}${path}`, {
|
|
96
|
+
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
|
97
|
+
});
|
|
98
|
+
return handle(res, path);
|
|
99
|
+
},
|
|
100
|
+
|
|
101
|
+
async send(method, path, payload) {
|
|
102
|
+
const res = await fetch(`${base}${path}`, {
|
|
103
|
+
method,
|
|
104
|
+
headers: {
|
|
105
|
+
Authorization: `Bearer ${token}`,
|
|
106
|
+
Accept: 'application/json',
|
|
107
|
+
'Content-Type': 'application/json',
|
|
108
|
+
},
|
|
109
|
+
body: payload === undefined ? undefined : JSON.stringify(payload),
|
|
110
|
+
});
|
|
111
|
+
return handle(res, path);
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
/** Multipart upload. Node >= 20 gives us fetch + FormData + Blob natively. */
|
|
115
|
+
async upload(path, filePath, fields) {
|
|
116
|
+
const form = new FormData();
|
|
117
|
+
const buffer = await fs.readFile(filePath);
|
|
118
|
+
form.append('file', new Blob([buffer], { type: 'application/zip' }), path_basename(filePath));
|
|
119
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
120
|
+
if (value !== undefined && value !== null && value !== '') {
|
|
121
|
+
form.append(key, String(value));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const res = await fetch(`${base}${path}`, {
|
|
126
|
+
method: 'POST',
|
|
127
|
+
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
|
128
|
+
body: form,
|
|
129
|
+
});
|
|
130
|
+
return handle(res, path);
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function path_basename(p) {
|
|
136
|
+
return path.basename(p);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Poll a job until it finishes. Uploads are queued server-side, so this is what
|
|
141
|
+
* turns "accepted" into "actually live" for a CI step that must fail the build
|
|
142
|
+
* when a release fails.
|
|
143
|
+
*/
|
|
144
|
+
export async function waitForJob(client, jobId, { intervalMs = 5000, timeoutMs = 600000 } = {}) {
|
|
145
|
+
const startedAt = Date.now();
|
|
146
|
+
|
|
147
|
+
for (;;) {
|
|
148
|
+
const { data: job } = await client.get(`/jobs/${jobId}`);
|
|
149
|
+
|
|
150
|
+
if (job.status === 'completed') return job;
|
|
151
|
+
|
|
152
|
+
if (job.status === 'failed') {
|
|
153
|
+
console.error(chalk.red(`Job failed: ${job.error ?? 'no reason reported'}`));
|
|
154
|
+
process.exit(1);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (Date.now() - startedAt > timeoutMs) {
|
|
158
|
+
console.error(
|
|
159
|
+
chalk.red(`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for job ${jobId}.`)
|
|
160
|
+
);
|
|
161
|
+
console.error(chalk.gray(` The job may still finish — check ${job.status_url}`));
|
|
162
|
+
process.exit(1);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
process.stdout.write(chalk.gray(` status: ${job.status}…\r`));
|
|
166
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Accept either a prebuilt .zip or a web directory. Passing a directory is the
|
|
172
|
+
* common CI case ("deploy ./dist"), so zip it into a temp file rather than
|
|
173
|
+
* making every pipeline shell out to `zip` first.
|
|
174
|
+
*
|
|
175
|
+
* @returns {Promise<{path: string, cleanup: () => Promise<void>}>}
|
|
176
|
+
*/
|
|
177
|
+
export async function resolveBundle(target) {
|
|
178
|
+
const stat = await fs.stat(target).catch(() => null);
|
|
179
|
+
|
|
180
|
+
if (!stat) {
|
|
181
|
+
console.error(chalk.red(`Error: ${target} does not exist.`));
|
|
182
|
+
process.exit(1);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (stat.isFile()) {
|
|
186
|
+
if (!target.endsWith('.zip')) {
|
|
187
|
+
console.error(chalk.red('Error: a bundle file must be a .zip.'));
|
|
188
|
+
process.exit(1);
|
|
189
|
+
}
|
|
190
|
+
return { path: target, cleanup: async () => {} };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'native-update-'));
|
|
194
|
+
const zipPath = path.join(tempDir, 'bundle.zip');
|
|
195
|
+
|
|
196
|
+
console.log(chalk.gray(` Zipping ${target}…`));
|
|
197
|
+
|
|
198
|
+
const output = createWriteStream(zipPath);
|
|
199
|
+
const archive = new ZipArchive({ zlib: { level: 9 } });
|
|
200
|
+
const done = new Promise((resolve, reject) => {
|
|
201
|
+
output.on('close', resolve);
|
|
202
|
+
archive.on('error', reject);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
archive.pipe(output);
|
|
206
|
+
archive.directory(target, false);
|
|
207
|
+
await archive.finalize();
|
|
208
|
+
await done;
|
|
209
|
+
|
|
210
|
+
return {
|
|
211
|
+
path: zipPath,
|
|
212
|
+
cleanup: () => fs.rm(tempDir, { recursive: true, force: true }),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Render rows as a simple aligned table — no dependency, readable in CI logs. */
|
|
217
|
+
export function printTable(rows, columns) {
|
|
218
|
+
if (rows.length === 0) {
|
|
219
|
+
console.log(chalk.gray(' (none)'));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const widths = columns.map((col) =>
|
|
224
|
+
Math.max(col.header.length, ...rows.map((row) => String(col.value(row) ?? '').length))
|
|
225
|
+
);
|
|
226
|
+
|
|
227
|
+
console.log(
|
|
228
|
+
' ' + columns.map((col, i) => chalk.bold(col.header.padEnd(widths[i]))).join(' ')
|
|
229
|
+
);
|
|
230
|
+
|
|
231
|
+
for (const row of rows) {
|
|
232
|
+
console.log(
|
|
233
|
+
' ' + columns.map((col, i) => String(col.value(row) ?? '').padEnd(widths[i])).join(' ')
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Attach the auth/server flags every remote command shares. */
|
|
239
|
+
export function withRemoteOptions(command) {
|
|
240
|
+
return command
|
|
241
|
+
.option('-t, --token <token>', 'Access token (or set NATIVE_UPDATE_TOKEN)')
|
|
242
|
+
.option('-s, --server <url>', `Backend base URL (default: ${DEFAULT_SERVER})`);
|
|
243
|
+
}
|