create-expo-updates-server 0.1.6 → 0.2.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.
- package/dist/template/.dockerignore +16 -0
- package/dist/template/Dockerfile +5 -0
- package/dist/template/README.md +51 -660
- package/dist/template/app/api/admin/device-targets/route.test.ts +43 -0
- package/dist/template/app/api/admin/device-targets/route.ts +91 -0
- package/dist/template/app/api/admin/devices/route.test.ts +41 -0
- package/dist/template/app/api/admin/devices/route.ts +15 -0
- package/dist/template/app/api/admin/updates/[encodedKey]/audience/route.ts +75 -0
- package/dist/template/app/api/device-heartbeat/route.ts +2 -0
- package/dist/template/app/globals.css +114 -15
- package/dist/template/app/layout.tsx +12 -4
- package/dist/template/app/login/page.tsx +22 -18
- package/dist/template/app/updates/[encodedKey]/page.tsx +112 -88
- package/dist/template/app/updates/devices/page.tsx +264 -0
- package/dist/template/app/updates/embedded/page.tsx +102 -68
- package/dist/template/app/updates/emergency-redirects/page.tsx +144 -111
- package/dist/template/app/updates/layout.tsx +6 -1
- package/dist/template/app/updates/page.tsx +262 -212
- package/dist/template/components/admin/admin-shell.tsx +196 -0
- package/dist/template/components/admin/language-switcher.tsx +25 -0
- package/dist/template/components/admin/theme-provider.tsx +15 -0
- package/dist/template/components/ui/alert.tsx +65 -0
- package/dist/template/components/ui/badge.tsx +47 -0
- package/dist/template/components/ui/button.tsx +63 -0
- package/dist/template/components/ui/card.tsx +91 -0
- package/dist/template/components/ui/chart.tsx +373 -0
- package/dist/template/components/ui/checkbox.tsx +31 -0
- package/dist/template/components/ui/dialog.tsx +158 -0
- package/dist/template/components/ui/dropdown-menu.tsx +256 -0
- package/dist/template/components/ui/input.tsx +20 -0
- package/dist/template/components/ui/label.tsx +23 -0
- package/dist/template/components/ui/native-select.tsx +61 -0
- package/dist/template/components/ui/popover.tsx +88 -0
- package/dist/template/components/ui/scroll-area.tsx +57 -0
- package/dist/template/components/ui/select.tsx +189 -0
- package/dist/template/components/ui/separator.tsx +27 -0
- package/dist/template/components/ui/sheet.tsx +142 -0
- package/dist/template/components/ui/sidebar.tsx +736 -0
- package/dist/template/components/ui/skeleton.tsx +13 -0
- package/dist/template/components/ui/switch.tsx +34 -0
- package/dist/template/components/ui/table.tsx +115 -0
- package/dist/template/components/ui/tabs.tsx +90 -0
- package/dist/template/components/ui/textarea.tsx +17 -0
- package/dist/template/components/ui/tooltip.tsx +56 -0
- package/dist/template/components.json +22 -0
- package/dist/template/docker/minio.Dockerfile +11 -0
- package/dist/template/docker-compose.yml +7 -9
- package/dist/template/docs/admin-ui.md +35 -0
- package/dist/template/docs/device-targeting.md +129 -0
- package/dist/template/docs/doctor.md +137 -0
- package/dist/template/docs/expo-app-setup.md +174 -47
- package/dist/template/docs/getting-started.md +109 -146
- package/dist/template/docs/getting-started.ru.md +110 -193
- package/dist/template/docs/index.md +14 -33
- package/dist/template/docs/installation-telemetry.md +233 -0
- package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +89 -0
- package/dist/template/docs/migrations/2026-10-19-device-heartbeat.sql +131 -0
- package/dist/template/docs/migrations/2026-10-22-device-analytics.sql +264 -0
- package/dist/template/docs/migrations/2026-10-22-device-targeting-activation.sql +108 -0
- package/dist/template/docs/migrations/2026-10-22-device-targeting.sql +130 -0
- package/dist/template/docs/migrations/2026-10-22-device-version-metadata.sql +154 -0
- package/dist/template/docs/migrations/schema.sql +868 -6
- package/dist/template/docs/npm-installer.md +15 -30
- package/dist/template/docs/operations-guide.md +87 -0
- package/dist/template/docs/ota-client-lifecycle.md +263 -0
- package/dist/template/docs/ota-update-policy.md +36 -2
- package/dist/template/docs/supabase-setup.md +4 -0
- package/dist/template/hooks/use-mobile.ts +21 -0
- package/dist/template/lib/utils.ts +6 -0
- package/dist/template/package-lock.json +2325 -101
- package/dist/template/package.json +13 -3
- package/dist/template/scripts/configure-expo-app.mjs +11 -15
- package/dist/template/scripts/doctor.mjs +51 -0
- package/dist/template/scripts/ensure-storage-bucket.mjs +25 -0
- package/dist/template/scripts/ensure-test-bucket.mjs +21 -0
- package/dist/template/scripts/lib/device-identity.test.ts +29 -0
- package/dist/template/scripts/lib/doctor-probes.mjs +139 -0
- package/dist/template/scripts/lib/doctor.mjs +208 -0
- package/dist/template/scripts/lib/doctor.test.mjs +262 -0
- package/dist/template/scripts/lib/expo-app-configurator.mjs +14 -9
- package/dist/template/scripts/lib/expo-app-configurator.test.ts +3 -2
- package/dist/template/scripts/lib/ota-client-configurator.mjs +69 -0
- package/dist/template/scripts/lib/ota-client-configurator.test.ts +88 -0
- package/dist/template/scripts/lib/ota-client.test.ts +55 -0
- package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +173 -0
- package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +123 -0
- package/dist/template/scripts/lib/ota-update-controller.test.ts +231 -0
- package/dist/template/scripts/tests/device-analytics-migrations.mjs +80 -0
- package/dist/template/scripts/tests/device-analytics.mjs +126 -0
- package/dist/template/scripts/tests/device-heartbeat.mjs +86 -0
- package/dist/template/scripts/tests/device-targeting-activation.mjs +111 -0
- package/dist/template/scripts/tests/device-targeting.mjs +39 -0
- package/dist/template/scripts/tests/device-version-metadata.mjs +31 -0
- package/dist/template/scripts/tests/manifest-identity-concurrency.mjs +106 -0
- package/dist/template/scripts/tests/manifest-identity.sql +204 -0
- package/dist/template/src/client/admin-types.ts +1 -0
- package/dist/template/src/client/devices/analytics.tsx +429 -0
- package/dist/template/src/client/devices/device-name.tsx +82 -0
- package/dist/template/src/client/devices/registry.tsx +399 -0
- package/dist/template/src/client/devices/use-devices-report.ts +108 -0
- package/dist/template/src/client/devices/version-adoption-chart.tsx +269 -0
- package/dist/template/src/client/devices/version-groups.test.ts +57 -0
- package/dist/template/src/client/devices/version-groups.ts +101 -0
- package/dist/template/src/client/distribution-control.tsx +135 -81
- package/dist/template/src/client/guard-action-combobox.tsx +13 -24
- package/dist/template/src/client/i18n/en.json +286 -0
- package/dist/template/src/client/i18n/messages.test.ts +42 -0
- package/dist/template/src/client/i18n/messages.ts +31 -0
- package/dist/template/src/client/i18n/provider.tsx +55 -0
- package/dist/template/src/client/i18n/use-formatters.ts +38 -0
- package/dist/template/src/client/logout-button.tsx +3 -1
- package/dist/template/src/client/update-audience-editor.tsx +285 -0
- package/dist/template/src/client/update-policy-editor.tsx +53 -41
- package/dist/template/src/server/controllers/manifest.test.ts +250 -7
- package/dist/template/src/server/controllers/manifest.ts +39 -31
- package/dist/template/src/server/devices/audience.test.ts +48 -0
- package/dist/template/src/server/devices/audience.ts +86 -0
- package/dist/template/src/server/devices/heartbeat.test.ts +39 -0
- package/dist/template/src/server/devices/heartbeat.ts +75 -0
- package/dist/template/src/server/devices/report-types.ts +114 -0
- package/dist/template/src/server/devices/report.test.ts +29 -0
- package/dist/template/src/server/devices/report.ts +27 -0
- package/dist/template/src/server/lib/admin-audience-activation.test.ts +94 -0
- package/dist/template/src/server/lib/admin-updates.ts +32 -168
- package/dist/template/src/server/lib/supabase.js +10 -10
- package/dist/template/src/server/lib/supabase.test.ts +11 -0
- package/dist/template/src/server/manifest/manifest-identity.test.ts +30 -0
- package/dist/template/src/server/manifest/manifest-identity.ts +24 -0
- package/dist/template/src/server/manifest/manifest-repository.ts +31 -102
- package/dist/template/src/server/manifest/manifest-response.ts +1 -1
- package/dist/template/templates/expo-app/ota-client/README.md +59 -0
- package/dist/template/templates/expo-app/ota-client/controller.js +60 -0
- package/dist/template/templates/expo-app/ota-client/device-identity.js +26 -0
- package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +52 -0
- package/dist/template/templates/expo-app/ota-client/index.d.ts +47 -0
- package/dist/template/templates/expo-app/ota-client/index.js +3 -0
- package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +48 -0
- package/dist/template/templates/expo-app/ota-client/model/update-controller.js +182 -0
- package/dist/template/templates/expo-app/ota-client/runtime.js +112 -0
- package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +56 -0
- package/dist/template-manifest.json +592 -77
- package/lib/cli.mjs +4 -6
- package/package.json +1 -1
|
@@ -21,7 +21,8 @@
|
|
|
21
21
|
"test:watch": "vitest",
|
|
22
22
|
"create-admin": "node scripts/create-admin.mjs",
|
|
23
23
|
"create-access-token": "node scripts/create-access-token.mjs",
|
|
24
|
-
"restart-docker": "docker compose up -d --force-recreate app"
|
|
24
|
+
"restart-docker": "docker compose up -d --force-recreate app",
|
|
25
|
+
"doctor": "node scripts/doctor.mjs"
|
|
25
26
|
},
|
|
26
27
|
"dependencies": {
|
|
27
28
|
"@aws-sdk/client-s3": "^3.888.0",
|
|
@@ -29,11 +30,21 @@
|
|
|
29
30
|
"@supabase/supabase-js": "^2.57.4",
|
|
30
31
|
"@types/form-data": "^2.2.1",
|
|
31
32
|
"bcryptjs": "^3.0.3",
|
|
33
|
+
"class-variance-authority": "^0.7.1",
|
|
34
|
+
"clsx": "^2.1.1",
|
|
32
35
|
"form-data": "^4.0.5",
|
|
36
|
+
"lucide-react": "^1.61.0",
|
|
33
37
|
"next": "16.1.6",
|
|
38
|
+
"next-themes": "^0.4.6",
|
|
34
39
|
"pg": "^8.16.3",
|
|
40
|
+
"radix-ui": "^1.8.1",
|
|
35
41
|
"react": "19.2.3",
|
|
36
|
-
"react-dom": "19.2.3"
|
|
42
|
+
"react-dom": "19.2.3",
|
|
43
|
+
"recharts": "^3.8.0",
|
|
44
|
+
"structured-headers": "^2.1.1",
|
|
45
|
+
"tailwind-merge": "^3.7.0",
|
|
46
|
+
"tw-animate-css": "^1.4.0",
|
|
47
|
+
"typescript": "^5"
|
|
37
48
|
},
|
|
38
49
|
"devDependencies": {
|
|
39
50
|
"@tailwindcss/postcss": "^4",
|
|
@@ -43,7 +54,6 @@
|
|
|
43
54
|
"eslint": "^9",
|
|
44
55
|
"eslint-config-next": "16.1.6",
|
|
45
56
|
"tailwindcss": "^4",
|
|
46
|
-
"typescript": "^5",
|
|
47
57
|
"vitepress": "^1.6.4",
|
|
48
58
|
"vitest": "^4.1.11"
|
|
49
59
|
}
|
|
@@ -28,7 +28,8 @@ Required:
|
|
|
28
28
|
|
|
29
29
|
Optional:
|
|
30
30
|
--platform all, ios or android (default: all)
|
|
31
|
-
--
|
|
31
|
+
--server-env Local Docker env file (default: server .env)
|
|
32
|
+
--force Replace generated client, publisher and certificate files
|
|
32
33
|
--help Show this message
|
|
33
34
|
`);
|
|
34
35
|
}
|
|
@@ -60,7 +61,8 @@ function parseArgs(argv) {
|
|
|
60
61
|
}
|
|
61
62
|
index += 1;
|
|
62
63
|
|
|
63
|
-
if (key === "
|
|
64
|
+
if (key === "server-env") options.serverEnv = value;
|
|
65
|
+
else if (key === "app") options.app = value;
|
|
64
66
|
else if (key === "certificate") options.certificate = value;
|
|
65
67
|
else if (key === "server-url") options.serverUrl = value;
|
|
66
68
|
else if (key === "channel") options.channel = value;
|
|
@@ -121,7 +123,7 @@ try {
|
|
|
121
123
|
`Publisher environment: ${
|
|
122
124
|
result.publisherEnvConfigured
|
|
123
125
|
? "configured from local Docker .env"
|
|
124
|
-
: "
|
|
126
|
+
: "verify .env.ota credentials; create from .env.ota.example only if missing"
|
|
125
127
|
}`,
|
|
126
128
|
);
|
|
127
129
|
if (result.migrationWarnings.length > 0) {
|
|
@@ -131,20 +133,14 @@ try {
|
|
|
131
133
|
}
|
|
132
134
|
}
|
|
133
135
|
console.log("\nNext:");
|
|
136
|
+
let step = 1;
|
|
134
137
|
if (!result.publisherEnvConfigured) {
|
|
135
|
-
console.log(
|
|
136
|
-
"1. Copy .env.ota.example to .env.ota and add publisher secrets.",
|
|
137
|
-
);
|
|
138
|
+
console.log(`${step++}. Keep any existing .env.ota; create it from .env.ota.example only if missing, then verify publisher/registration credentials.`);
|
|
138
139
|
}
|
|
139
|
-
console.log(
|
|
140
|
-
|
|
141
|
-
);
|
|
142
|
-
console.log(
|
|
143
|
-
`${result.publisherEnvConfigured ? "2" : "3"}. Activate the update in the OTA admin panel.`,
|
|
144
|
-
);
|
|
145
|
-
console.log(
|
|
146
|
-
`${result.publisherEnvConfigured ? "3" : "4"}. Build Android with npm run ota:build:android:apk or build iOS in Xcode.`,
|
|
147
|
-
);
|
|
140
|
+
console.log(`${step++}. In the app, add manual check/download/reload controls or enable hook automation before building. The generated root only auto-checks by default.`);
|
|
141
|
+
console.log(`${step++}. Build and install a native binary with telemetry dependencies: npm run ota:build:android:apk or Xcode for iOS. Do this before delivering ota-client via OTA.`);
|
|
142
|
+
console.log(`${step++}. Publish with: npm run ota:publish -- --message "Update description"`);
|
|
143
|
+
console.log(`${step++}. Activate the update in the OTA admin panel.`);
|
|
148
144
|
} catch (error) {
|
|
149
145
|
console.error(`Expo OTA configuration failed: ${error.message}`);
|
|
150
146
|
process.exit(1);
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseDoctorArgs, runDoctor } from './lib/doctor.mjs';
|
|
3
|
+
|
|
4
|
+
const help = `Read-only OTA setup diagnostics. No files, database rows or releases are changed.
|
|
5
|
+
|
|
6
|
+
Usage: npm run doctor -- [options]
|
|
7
|
+
--mode docker|remote Docker app container or explicit remote env (default: docker)
|
|
8
|
+
--server-env PATH Exact env file (default: .env for Docker, .env.local for remote)
|
|
9
|
+
--app PATH Check a static app.json Expo application and .env.ota
|
|
10
|
+
--certificate PATH Public certificate (defaults to app.json certificate)
|
|
11
|
+
--offline Check files only; no Docker execution or network probes
|
|
12
|
+
--compose-file PATH Compose file, repeatable (default: docker-compose.yml)
|
|
13
|
+
--project NAME Docker Compose project name
|
|
14
|
+
--timeout MS Per-operation timeout, 500–30000 (default: 5000)
|
|
15
|
+
--json Structured JSON without credentials (use npm run --silent)
|
|
16
|
+
--help Show help
|
|
17
|
+
|
|
18
|
+
Run from the server directory with Node.js 20.12+ (project recommendation: 24).
|
|
19
|
+
Exit 0: no detected blockers (warnings/skips may remain). Exit 1: failed checks.
|
|
20
|
+
Exit 2: invalid arguments or unexpected diagnostic failure.
|
|
21
|
+
No dynamic app config is executed. Phone reachability/native binary state and
|
|
22
|
+
publisher write permissions still require a real device/release test.`;
|
|
23
|
+
let options;
|
|
24
|
+
try { options = parseDoctorArgs(process.argv.slice(2)); }
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (process.argv.includes('--json')) console.log(JSON.stringify({ version: 1, status: 'fail', checks: [{ id: 'cli.arguments', status: 'fail', message: error.message }] }));
|
|
27
|
+
else console.error(error.message);
|
|
28
|
+
process.exitCode = 2;
|
|
29
|
+
}
|
|
30
|
+
if (options) {
|
|
31
|
+
if (options.help) console.log(help);
|
|
32
|
+
else {
|
|
33
|
+
try {
|
|
34
|
+
const result = await runDoctor(options);
|
|
35
|
+
if (options.json) console.log(JSON.stringify(result, null, 2));
|
|
36
|
+
else {
|
|
37
|
+
console.log(`OTA doctor — ${result.mode}${result.offline ? ' (offline)' : ''}`);
|
|
38
|
+
for (const check of result.checks) {
|
|
39
|
+
console.log(`[${check.status.toUpperCase()}] ${check.id}: ${check.message}`);
|
|
40
|
+
if (check.remedy && check.status !== 'pass') console.log(` → ${check.remedy}`);
|
|
41
|
+
}
|
|
42
|
+
console.log(`\nResult: ${result.status}. Passes cover only the checks above; warnings/skips are not proof of readiness.`);
|
|
43
|
+
}
|
|
44
|
+
process.exitCode = result.status === 'fail' ? 1 : 0;
|
|
45
|
+
} catch {
|
|
46
|
+
const failure = { version: 1, status: 'fail', checks: [{ id: 'doctor.internal', status: 'fail', message: 'Diagnostic execution failed. Check runtime, dependencies and file permissions; no raw exception is printed to avoid disclosing secrets.' }] };
|
|
47
|
+
console.log(options.json ? JSON.stringify(failure) : failure.checks[0].message);
|
|
48
|
+
process.exitCode = 2;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CreateBucketCommand, HeadBucketCommand, S3Client } from "@aws-sdk/client-s3";
|
|
2
|
+
|
|
3
|
+
const client = new S3Client({
|
|
4
|
+
endpoint: "http://minio:9000",
|
|
5
|
+
region: "us-east-1",
|
|
6
|
+
forcePathStyle: true,
|
|
7
|
+
credentials: {
|
|
8
|
+
accessKeyId: process.env.MINIO_ROOT_USER,
|
|
9
|
+
secretAccessKey: process.env.MINIO_ROOT_PASSWORD,
|
|
10
|
+
},
|
|
11
|
+
});
|
|
12
|
+
const Bucket = process.env.OTA_STORAGE_BUCKET;
|
|
13
|
+
if (!Bucket) throw new Error("OTA_STORAGE_BUCKET is required.");
|
|
14
|
+
|
|
15
|
+
try {
|
|
16
|
+
try {
|
|
17
|
+
await client.send(new CreateBucketCommand({ Bucket }));
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error.name !== "BucketAlreadyOwnedByYou") throw error;
|
|
20
|
+
}
|
|
21
|
+
await client.send(new HeadBucketCommand({ Bucket }));
|
|
22
|
+
console.log("Storage bucket ready.");
|
|
23
|
+
} finally {
|
|
24
|
+
client.destroy();
|
|
25
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { CreateBucketCommand, S3Client } from "@aws-sdk/client-s3";
|
|
2
|
+
|
|
3
|
+
const client = new S3Client({
|
|
4
|
+
endpoint: "http://minio:9000",
|
|
5
|
+
region: "us-east-1",
|
|
6
|
+
forcePathStyle: true,
|
|
7
|
+
credentials: {
|
|
8
|
+
accessKeyId: process.env.MINIO_ROOT_USER,
|
|
9
|
+
secretAccessKey: process.env.MINIO_ROOT_PASSWORD,
|
|
10
|
+
},
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
try {
|
|
14
|
+
await client.send(new CreateBucketCommand({ Bucket: process.env.OTA_STORAGE_BUCKET }));
|
|
15
|
+
console.log("Test storage bucket ready.");
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (!["BucketAlreadyOwnedByYou", "BucketAlreadyExists"].includes(error.name)) throw error;
|
|
18
|
+
console.log("Test storage bucket already exists.");
|
|
19
|
+
} finally {
|
|
20
|
+
client.destroy();
|
|
21
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { createDeviceIdentity } from '../../templates/expo-app/ota-client/device-identity.js';
|
|
4
|
+
const digest = async (v: string) => createHash('sha256').update(v).digest('hex');
|
|
5
|
+
function options(platform = 'android', store = new Map<string, string>()) {
|
|
6
|
+
return { platform, scope: 'com.example:https://updates.example.com', androidId: () => 'abc123', digest,
|
|
7
|
+
uuid: randomUUID, readSecure: async (k: string) => store.get(k), writeSecure: async (k: string, v: string) => { store.set(k, v); } };
|
|
8
|
+
}
|
|
9
|
+
describe('device identity independent of installation state', () => {
|
|
10
|
+
it('recognizes Android reinstalls, isolates app/server and signing identity changes', async () => {
|
|
11
|
+
const o = options(); const first = await createDeviceIdentity(o)();
|
|
12
|
+
expect(await createDeviceIdentity(options())()).toBe(first);
|
|
13
|
+
expect(await createDeviceIdentity({ ...o, scope: 'another-app' })()).not.toBe(first);
|
|
14
|
+
expect(await createDeviceIdentity({ ...o, androidId: () => 'changed-key' })()).not.toBe(first);
|
|
15
|
+
expect(first).toMatch(/^[a-f0-9]{64}$/); expect(first).not.toContain('abc123');
|
|
16
|
+
});
|
|
17
|
+
it('reuses iOS Keychain across reinstall, regenerates only when actually absent', async () => {
|
|
18
|
+
const store = new Map<string, string>(); const o = options('ios', store);
|
|
19
|
+
const first = await createDeviceIdentity(o)();
|
|
20
|
+
expect(await createDeviceIdentity(o)()).toBe(first);
|
|
21
|
+
expect(await createDeviceIdentity(options('ios'))()).not.toBe(first);
|
|
22
|
+
});
|
|
23
|
+
it('single-flights concurrent callers and retries Keychain errors without replacing the existing seed', async () => {
|
|
24
|
+
const store = new Map<string, string>(); const o = options('ios', store); let calls = 0;
|
|
25
|
+
const id = createDeviceIdentity({ ...o, readSecure: async (k: string) => { calls++; if (calls === 1) throw new Error('locked'); return o.readSecure(k); } });
|
|
26
|
+
await expect(id()).rejects.toThrow('locked');
|
|
27
|
+
const [a, b] = await Promise.all([id(), id()]); expect(a).toBe(b); expect(calls).toBe(2); expect(store.size).toBe(1);
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Self-contained so the same read-only probes can run inside the existing app container.
|
|
2
|
+
// Never return raw exceptions, connection strings, tokens or PEM material.
|
|
3
|
+
export async function probeServer({ env, timeout = 5000, network = true }) {
|
|
4
|
+
const checks = [];
|
|
5
|
+
const add = (id, status, message, remedy) => checks.push({ id, status, message, ...(remedy ? { remedy } : {}) });
|
|
6
|
+
const present = (value) => typeof value === 'string' && value.trim() && !/(?:<[^>]+>|replace-with|YOUR_|choose-a-|:\/\/USER:PASSWORD@HOST|:\/\/user:password@host|updates\.example\.com|storage\.example\.com)/.test(value);
|
|
7
|
+
const endpoint = (value) => {
|
|
8
|
+
try {
|
|
9
|
+
const url = new URL(value);
|
|
10
|
+
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash && present(value);
|
|
11
|
+
} catch { return false; }
|
|
12
|
+
};
|
|
13
|
+
const bucket = env.OTA_STORAGE_BUCKET || env.R2_BUCKET || env.SUPABASE_UPDATES_BUCKET || 'expo-updates';
|
|
14
|
+
let keyFingerprint;
|
|
15
|
+
try {
|
|
16
|
+
const crypto = await import('node:crypto');
|
|
17
|
+
const fs = await import('node:fs/promises');
|
|
18
|
+
const pem = env.CODE_SIGNING_PRIVATE_KEY?.trim()
|
|
19
|
+
? env.CODE_SIGNING_PRIVATE_KEY.replaceAll('\\n', '\n')
|
|
20
|
+
: await fs.readFile(env.CODE_SIGNING_PRIVATE_KEY_PATH, 'utf8');
|
|
21
|
+
const key = crypto.createPrivateKey(pem);
|
|
22
|
+
if (key.asymmetricKeyType !== 'rsa' || key.asymmetricKeyDetails.modulusLength < 2048) throw new Error('unsupported');
|
|
23
|
+
keyFingerprint = crypto.createHash('sha256').update(crypto.createPublicKey(key).export({ type: 'spki', format: 'der' })).digest('hex');
|
|
24
|
+
add('signing.key', 'pass', 'RSA signing key is readable and valid (at least 2048 bits).');
|
|
25
|
+
} catch {
|
|
26
|
+
add('signing.key', 'fail', 'Signing key is missing, unreadable or invalid.', 'Set CODE_SIGNING_PRIVATE_KEY or CODE_SIGNING_PRIVATE_KEY_PATH. For Docker check the mount and read permission for container UID/GID 1001.');
|
|
27
|
+
}
|
|
28
|
+
const publicUrl = endpoint(env.OTA_PUBLIC_BASE_URL) ? env.OTA_PUBLIC_BASE_URL : undefined;
|
|
29
|
+
add('server.url', publicUrl ? 'pass' : 'fail', publicUrl ? 'Public server URL is configured.' : 'Public server URL is missing, a placeholder or invalid.', publicUrl ? undefined : 'Set OTA_PUBLIC_BASE_URL to your server URL without credentials, query or fragment.');
|
|
30
|
+
if (publicUrl) {
|
|
31
|
+
const url = new URL(publicUrl);
|
|
32
|
+
if (url.protocol !== 'https:' || ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) {
|
|
33
|
+
add('server.phone-url', 'warn', 'HTTP or loopback URL needs special device network/native configuration.', 'Use a phone-reachable HTTPS URL. localhost on a phone points to the phone; host connectivity cannot prove device connectivity.');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const provider = (env.DATABASE_PROVIDER || env.DB_PROVIDER || 'pg').toLowerCase();
|
|
37
|
+
if (!['pg', 'supabase'].includes(provider)) {
|
|
38
|
+
add('database.config', 'fail', 'Unsupported database provider.', 'Set DATABASE_PROVIDER to pg or supabase.');
|
|
39
|
+
return { checks, keyFingerprint, publicUrl };
|
|
40
|
+
}
|
|
41
|
+
const supabaseUrl = env.SUPABASE_PROJECT_URL || env.SUPABASE_URL;
|
|
42
|
+
const supabaseKey = env.SUPABASE_SERVICE_ROLE_KEY;
|
|
43
|
+
let databaseConfigured = false;
|
|
44
|
+
if (provider === 'pg') {
|
|
45
|
+
try {
|
|
46
|
+
const url = new URL(env.DATABASE_URL);
|
|
47
|
+
databaseConfigured = ['postgres:', 'postgresql:'].includes(url.protocol) && present(env.DATABASE_URL) && Boolean(url.hostname && url.username && url.password && url.pathname.length > 1) && [...url.searchParams.keys()].every((key) => key === 'sslmode');
|
|
48
|
+
} catch { /* Report only a fixed message below. */ }
|
|
49
|
+
} else databaseConfigured = endpoint(supabaseUrl) && Boolean(present(supabaseKey));
|
|
50
|
+
add('database.config', databaseConfigured ? 'pass' : 'fail', databaseConfigured ? 'Database credentials are configured.' : 'Database configuration is missing or invalid.', databaseConfigured ? undefined : 'For pg set DATABASE_URL including an explicit user/password (percent-encoded); only sslmode is supported in URL query parameters and ambient PG credentials are not used. For Supabase set SUPABASE_PROJECT_URL and SUPABASE_SERVICE_ROLE_KEY.');
|
|
51
|
+
const storageConfigured = provider === 'supabase'
|
|
52
|
+
? databaseConfigured
|
|
53
|
+
: endpoint(env.R2_ENDPOINT) && Boolean(present(env.R2_ACCESS_KEY_ID) && present(env.R2_SECRET_ACCESS_KEY));
|
|
54
|
+
add('storage.config', storageConfigured ? 'pass' : 'fail', storageConfigured ? 'Storage credentials are configured.' : 'Storage configuration is missing or invalid.', storageConfigured ? undefined : 'Set R2_ENDPOINT, R2_ACCESS_KEY_ID and R2_SECRET_ACCESS_KEY (or Supabase service credentials).');
|
|
55
|
+
if (!network) {
|
|
56
|
+
add('database.connection', 'skip', 'Database/schema connectivity not checked in offline mode.');
|
|
57
|
+
add('storage.bucket', 'skip', 'Bucket reachability not checked in offline mode.');
|
|
58
|
+
return { checks, keyFingerprint, publicUrl };
|
|
59
|
+
}
|
|
60
|
+
if (databaseConfigured && provider === 'pg') {
|
|
61
|
+
let client;
|
|
62
|
+
try {
|
|
63
|
+
const { default: pg } = await import('pg');
|
|
64
|
+
const databaseUrl = new URL(env.DATABASE_URL);
|
|
65
|
+
databaseUrl.port ||= '5432';
|
|
66
|
+
client = new pg.Client({ connectionString: databaseUrl.toString(), application_name: 'ota-doctor', replication: 'false', client_encoding: 'utf8',
|
|
67
|
+
ssl: ['true', '1', 'require'].includes((env.DATABASE_SSL || '').toLowerCase()) ? { rejectUnauthorized: false } : false,
|
|
68
|
+
connectionTimeoutMillis: timeout, query_timeout: timeout, statement_timeout: timeout,
|
|
69
|
+
options: '-c default_transaction_read_only=on' });
|
|
70
|
+
// A connection-level error after a query timeout must not become an unhandled event.
|
|
71
|
+
client.on('error', () => {});
|
|
72
|
+
await client.connect();
|
|
73
|
+
await client.query('SELECT 1');
|
|
74
|
+
add('database.connection', 'pass', 'Database is reachable with the configured credentials.');
|
|
75
|
+
try {
|
|
76
|
+
await client.query('SELECT id, audience_mode, audience_device_ids FROM public.ota_updates LIMIT 0');
|
|
77
|
+
await client.query('SELECT installation_id, device_id, reported_update_id FROM public.ota_device_state LIMIT 0');
|
|
78
|
+
await client.query('SELECT * FROM public.ota_named_devices LIMIT 0');
|
|
79
|
+
const result = await client.query(`SELECT
|
|
80
|
+
to_regclass('public.ota_embedded_updates') IS NOT NULL
|
|
81
|
+
AND to_regclass('public.ota_admin_users') IS NOT NULL
|
|
82
|
+
AND to_regclass('public.ota_device_activity_daily') IS NOT NULL
|
|
83
|
+
AND to_regclass('public.ota_device_activity_cohorts') IS NOT NULL
|
|
84
|
+
AND to_regclass('public.ota_device_analytics_metadata') IS NOT NULL
|
|
85
|
+
AND to_regclass('public.ota_distribution_control') IS NOT NULL
|
|
86
|
+
AND to_regclass('public.ota_distribution_control_events') IS NOT NULL
|
|
87
|
+
AND to_regprocedure('public.ota_record_heartbeat(jsonb)') IS NOT NULL
|
|
88
|
+
AND to_regprocedure('public.ota_latest_eligible_update(text,text,text,text,text)') IS NOT NULL
|
|
89
|
+
AND to_regprocedure('public.ota_replace_audience(uuid,text,jsonb,jsonb,integer)') IS NOT NULL
|
|
90
|
+
AND to_regprocedure('public.ota_devices_report_v2(integer,text,text,text,integer,text,text)') IS NOT NULL
|
|
91
|
+
AND to_regprocedure('public.assert_ota_distribution_mutation_allowed(text)') IS NOT NULL
|
|
92
|
+
AND EXISTS (SELECT 1 FROM pg_trigger WHERE tgrelid = 'public.ota_updates'::regclass
|
|
93
|
+
AND tgname = 'trg_ota_updates_activate_audience' AND tgenabled IN ('O','A')
|
|
94
|
+
AND tgfoid = to_regprocedure('public.ota_activate_audience()')) AS ready`);
|
|
95
|
+
if (!result.rows[0]?.ready) throw new Error('schema');
|
|
96
|
+
add('database.schema', 'pass', 'Core OTA, telemetry and targeting schema is accessible.');
|
|
97
|
+
} catch {
|
|
98
|
+
add('database.schema', 'fail', 'Core OTA schema is missing, outdated or inaccessible.', 'Review database permissions and apply the project schema/migrations after backing up existing data.');
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
add('database.connection', 'fail', 'Database connection failed or timed out.', 'Check DATABASE_URL, SSL, network, credentials and installed pg dependency.');
|
|
102
|
+
} finally { if (client) await client.end().catch(() => {}); }
|
|
103
|
+
} else if (databaseConfigured) {
|
|
104
|
+
try {
|
|
105
|
+
const selections = ['ota_updates?select=id,audience_mode,audience_device_ids&limit=0', 'ota_device_state?select=installation_id,device_id,reported_update_id&limit=0', 'ota_named_devices?select=*&limit=0', 'ota_embedded_updates?select=*&limit=0', 'ota_admin_users?select=*&limit=0', 'ota_device_activity_daily?select=*&limit=0'];
|
|
106
|
+
const responses = await Promise.all(selections.map((selection) => fetch(`${supabaseUrl.replace(/\/+$/, '')}/rest/v1/${selection}`, {
|
|
107
|
+
headers: { apikey: supabaseKey, Authorization: `Bearer ${supabaseKey}` }, redirect: 'error', signal: AbortSignal.timeout(timeout),
|
|
108
|
+
})));
|
|
109
|
+
await Promise.all(responses.map((response) => response.body?.cancel()));
|
|
110
|
+
if (responses.some((response) => !response.ok)) throw new Error('schema');
|
|
111
|
+
add('database.schema', 'pass', 'Core OTA tables are accessible through Supabase REST.');
|
|
112
|
+
add('database.schema-functions', 'warn', 'Supabase REST cannot verify required SQL functions and activation triggers.', 'For full schema diagnostics, run remote mode with DATABASE_PROVIDER=pg and an explicit database connection URL.');
|
|
113
|
+
} catch {
|
|
114
|
+
add('database.schema', 'fail', 'Supabase tables are missing, inaccessible or timed out.', 'Check URL/service-role key, REST permissions and current schema/migrations.');
|
|
115
|
+
}
|
|
116
|
+
} else add('database.connection', 'skip', 'Database probe skipped until configuration is fixed.');
|
|
117
|
+
if (storageConfigured) {
|
|
118
|
+
try {
|
|
119
|
+
if (provider === 'supabase') {
|
|
120
|
+
const response = await fetch(`${supabaseUrl.replace(/\/+$/, '')}/storage/v1/bucket/${encodeURIComponent(bucket)}`, {
|
|
121
|
+
headers: { apikey: supabaseKey, Authorization: `Bearer ${supabaseKey}` }, redirect: 'error', signal: AbortSignal.timeout(timeout),
|
|
122
|
+
});
|
|
123
|
+
await response.body?.cancel();
|
|
124
|
+
if (!response.ok) throw new Error('bucket');
|
|
125
|
+
} else {
|
|
126
|
+
const { S3Client, HeadBucketCommand } = await import('@aws-sdk/client-s3');
|
|
127
|
+
const s3 = new S3Client({ endpoint: env.R2_ENDPOINT, region: env.R2_REGION || 'auto', maxAttempts: 1,
|
|
128
|
+
forcePathStyle: ['true', '1'].includes((env.S3_FORCE_PATH_STYLE || '').toLowerCase()),
|
|
129
|
+
credentials: { accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY } });
|
|
130
|
+
try { await s3.send(new HeadBucketCommand({ Bucket: bucket }), { abortSignal: AbortSignal.timeout(timeout) }); }
|
|
131
|
+
finally { s3.destroy(); }
|
|
132
|
+
}
|
|
133
|
+
add('storage.bucket', 'pass', 'Configured bucket is reachable. Write permissions were not tested.');
|
|
134
|
+
} catch {
|
|
135
|
+
add('storage.bucket', 'fail', 'Bucket is missing, inaccessible or timed out.', 'Check endpoint, region, path-style mode, credentials and bucket existence. No bucket was created.');
|
|
136
|
+
}
|
|
137
|
+
} else add('storage.bucket', 'skip', 'Bucket probe skipped until configuration is fixed.');
|
|
138
|
+
return { checks, keyFingerprint, publicUrl };
|
|
139
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import * as util from 'node:util';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { createHash, X509Certificate } from 'node:crypto';
|
|
7
|
+
import { probeServer } from './doctor-probes.mjs';
|
|
8
|
+
|
|
9
|
+
const exec = util.promisify(execFile);
|
|
10
|
+
const present = (value) => typeof value === 'string' && Boolean(value.trim()) && !/(?:<[^>]+>|replace-with|YOUR_|choose-a-|:\/\/USER:PASSWORD@HOST|:\/\/user:password@host|updates\.example\.com|storage\.example\.com)/.test(value);
|
|
11
|
+
const readJson = async (file) => JSON.parse(await fs.readFile(file, 'utf8'));
|
|
12
|
+
const exists = async (file) => fs.access(file).then(() => true, () => false);
|
|
13
|
+
export function baseUrl(value) {
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(value);
|
|
16
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) return null;
|
|
17
|
+
return `${url.origin}${url.pathname.replace(/\/api\/(manifest|device-heartbeat)\/?$/, '').replace(/\/+$/, '')}`;
|
|
18
|
+
} catch { return null; }
|
|
19
|
+
}
|
|
20
|
+
export async function readDoctorEnv(file) {
|
|
21
|
+
if (!util.parseEnv) throw new Error('Node 20.12+ is required for doctor env parsing.');
|
|
22
|
+
// Explicit file only: never load .env.local, execute app config, expand shell variables,
|
|
23
|
+
// or mutate process.env. Docker evaluates its own env file when starting the service.
|
|
24
|
+
return util.parseEnv(await fs.readFile(file, 'utf8'));
|
|
25
|
+
}
|
|
26
|
+
export function parseDoctorArgs(argv) {
|
|
27
|
+
const options = { mode: 'docker', timeout: 5000, composeFiles: [] };
|
|
28
|
+
const values = new Map([['--mode', 'mode'], ['--server-env', 'serverEnv'], ['--app', 'app'], ['--certificate', 'certificate'], ['--timeout', 'timeout'], ['--compose-file', 'composeFile'], ['--project', 'project']]);
|
|
29
|
+
for (let index = 0; index < argv.length; index++) {
|
|
30
|
+
const arg = argv[index];
|
|
31
|
+
if (['--offline', '--json', '--help'].includes(arg)) { options[arg.slice(2)] = true; continue; }
|
|
32
|
+
const key = values.get(arg);
|
|
33
|
+
const value = argv[++index];
|
|
34
|
+
if (!key || !value || value.startsWith('--')) throw new Error('Invalid doctor arguments. Use --help.');
|
|
35
|
+
if (key === 'composeFile') options.composeFiles.push(value); else options[key] = value;
|
|
36
|
+
}
|
|
37
|
+
options.timeout = Number(options.timeout);
|
|
38
|
+
if (!['docker', 'remote'].includes(options.mode) || !Number.isInteger(options.timeout) || options.timeout < 500 || options.timeout > 30000) throw new Error('Use --mode docker|remote and --timeout between 500 and 30000 milliseconds.');
|
|
39
|
+
if (options.mode === 'remote' && (options.project || options.composeFiles.length)) throw new Error('Compose options require --mode docker.');
|
|
40
|
+
return options;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function inspectApplication(appRoot, serverUrl, add) {
|
|
44
|
+
let certificate;
|
|
45
|
+
const dynamic = await Promise.all(['ts', 'js', 'mjs', 'cjs'].map((extension) => exists(path.join(appRoot, `app.config.${extension}`))));
|
|
46
|
+
if (dynamic.some(Boolean)) {
|
|
47
|
+
add('app.config', 'fail', 'Dynamic app.config.* cannot be verified by the static configurator/publisher.', 'Doctor does not execute app code. Use manual client integration and a publishing flow that supports your dynamic configuration.');
|
|
48
|
+
return {};
|
|
49
|
+
}
|
|
50
|
+
let expo, pkg;
|
|
51
|
+
try {
|
|
52
|
+
expo = (await readJson(path.join(appRoot, 'app.json'))).expo;
|
|
53
|
+
pkg = await readJson(path.join(appRoot, 'package.json'));
|
|
54
|
+
if (!expo || !pkg) throw new Error('config');
|
|
55
|
+
add('app.config', 'pass', 'Static Expo configuration and package.json are readable.');
|
|
56
|
+
} catch {
|
|
57
|
+
add('app.config', 'fail', 'App directory needs valid app.json and package.json.', 'Pass --app with the Expo application directory.');
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
const require = createRequire(path.join(appRoot, 'package.json'));
|
|
61
|
+
const dependencies = ['expo', 'expo-updates', 'expo-application', 'expo-crypto', 'expo-secure-store', '@react-native-async-storage/async-storage'];
|
|
62
|
+
const missing = dependencies.filter((name) => {
|
|
63
|
+
if (!pkg.dependencies?.[name]) return true;
|
|
64
|
+
try { require.resolve(name); return false; } catch { return true; }
|
|
65
|
+
});
|
|
66
|
+
add('app.dependencies', missing.length ? 'fail' : 'pass', missing.length ? `Missing client dependencies: ${missing.join(', ')}.` : 'Client dependencies are declared and resolvable.', missing.length ? 'Run configure-app or install the documented Expo-compatible client dependencies in the app.' : undefined);
|
|
67
|
+
const clientFiles = ['index.js', 'runtime.js', 'controller.js', 'device-identity.js', 'model/update-controller.js', 'model/hooks/useOtaUpdates.js', 'ui/ota-update-gate.js'];
|
|
68
|
+
const clientFilesPresent = (await Promise.all(clientFiles.map((file) => exists(path.join(appRoot, 'ota-client', file))))).every(Boolean);
|
|
69
|
+
add('app.client', clientFilesPresent ? 'pass' : 'fail', clientFilesPresent ? 'Generated client implementation files are present.' : 'Generated client implementation files are incomplete.', clientFilesPresent ? undefined : 'Run configure-app or copy the complete ota-client directory using the manual integration guide.');
|
|
70
|
+
const updates = expo.updates || {};
|
|
71
|
+
const channel = updates.requestHeaders?.['expo-channel-name'];
|
|
72
|
+
const runtime = expo.runtimeVersion?.policy === 'appVersion' ? expo.version : expo.runtimeVersion;
|
|
73
|
+
const configured = updates.enabled !== false && typeof channel === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(channel) && typeof runtime === 'string' && runtime.length > 0 && runtime.length <= 100 && runtime === runtime.trim();
|
|
74
|
+
add('app.scope', configured ? 'pass' : 'fail', configured ? 'OTA is enabled with a channel and supported runtime.' : 'OTA is disabled or channel/runtime configuration is missing.', configured ? undefined : 'Use a lowercase channel (letters/numbers/dot/underscore/hyphen, up to 64 characters) and a nonempty runtime up to 100 characters without surrounding whitespace.');
|
|
75
|
+
for (const platform of ['ios', 'android']) {
|
|
76
|
+
if (expo[platform]?.updates || expo[platform]?.runtimeVersion) add(`app.${platform}-overrides`, 'warn', 'Platform-specific update/runtime overrides need manual verification.', 'The bundled publisher reads the top-level app.json scope. Verify the installed native scope and export match.');
|
|
77
|
+
}
|
|
78
|
+
const appBase = baseUrl(updates.url);
|
|
79
|
+
const expectedManifest = appBase && `${appBase}/api/manifest`;
|
|
80
|
+
const urlMatches = expectedManifest && updates.url?.replace(/\/+$/, '') === expectedManifest && (!serverUrl || appBase === baseUrl(serverUrl));
|
|
81
|
+
add('app.url', urlMatches ? 'pass' : 'fail', urlMatches ? 'Manifest URL matches the configured server (when available).' : 'Manifest URL is invalid or differs from the server public URL.', urlMatches ? undefined : 'Use the server OTA_PUBLIC_BASE_URL plus /api/manifest. Rebuild native binaries after changing the URL.');
|
|
82
|
+
add('app.native-checks', updates.checkAutomatically === 'NEVER' ? 'pass' : 'fail', updates.checkAutomatically === 'NEVER' ? 'Native automatic checks are disabled for hook orchestration.' : 'Native automatic checks can bypass the hook lifecycle.', updates.checkAutomatically === 'NEVER' ? undefined : 'Set expo.updates.checkAutomatically to NEVER and rebuild.');
|
|
83
|
+
if (typeof updates.codeSigningCertificate === 'string') certificate = path.resolve(appRoot, updates.codeSigningCertificate);
|
|
84
|
+
add('app.signing-config', certificate && updates.codeSigningMetadata?.alg === 'rsa-v1_5-sha256' && updates.codeSigningMetadata?.keyid === 'main' ? 'pass' : 'fail', 'App signing requires a certificate, rsa-v1_5-sha256 and keyid main.', 'Use configure-app to set the certificate and signing metadata.');
|
|
85
|
+
try {
|
|
86
|
+
const config = await readJson(path.join(appRoot, 'ota-client/config.json'));
|
|
87
|
+
if (typeof config.identityNamespace !== 'string' || !config.identityNamespace.trim() || config.channel !== channel || config.heartbeatUrl !== `${appBase}/api/device-heartbeat`) throw new Error('client');
|
|
88
|
+
add('app.identity', 'pass', 'Identity namespace, telemetry endpoint and channel are configured.');
|
|
89
|
+
} catch {
|
|
90
|
+
add('app.identity', 'fail', 'Client config is missing or differs from the app scope/endpoint.', 'Review ota-client/config.json. Preserve identityNamespace when changing a tunnel URL; do not regenerate it for every runtime.');
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
let originalEntry = pkg.main || '__platform_default__';
|
|
94
|
+
if (['ota-entry.js', './ota-entry.js'].includes(originalEntry)) {
|
|
95
|
+
originalEntry = (await readJson(path.join(appRoot, 'ota-client-entry.json'))).originalEntry;
|
|
96
|
+
if (!(await fs.readFile(path.join(appRoot, 'ota-entry.js'), 'utf8')).includes('.start()')) throw new Error('entry');
|
|
97
|
+
}
|
|
98
|
+
const { planOtaRootHook } = await import('./ota-root-hook-patcher.mjs');
|
|
99
|
+
const plan = planOtaRootHook({ appRoot, originalEntry });
|
|
100
|
+
if (!plan.files.length) {
|
|
101
|
+
add('app.root', 'warn', 'Custom entry/root cannot be verified automatically.', 'Verify one unconditional useOtaUpdates call and a mounted OtaUpdateGate in the actual root.');
|
|
102
|
+
} else {
|
|
103
|
+
const changes = await Promise.all(plan.files.map(async ([file, content]) => content !== await fs.readFile(path.join(appRoot, file), 'utf8')));
|
|
104
|
+
if (changes.some(Boolean)) throw new Error('root');
|
|
105
|
+
add('app.root', 'pass', 'Recognized root hook/gate wiring is present (source inspection only).');
|
|
106
|
+
}
|
|
107
|
+
} catch {
|
|
108
|
+
add('app.root', 'fail', 'Root hook/gate or bootstrap metadata is missing or unsupported.', 'Run configure-app or review manual hook integration. Doctor never applies the patch.');
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
const publisher = await readDoctorEnv(path.join(appRoot, '.env.ota'));
|
|
112
|
+
let databaseUrlValid = false;
|
|
113
|
+
try { const url = new URL(publisher.OTA_DATABASE_URL); databaseUrlValid = ['postgres:', 'postgresql:'].includes(url.protocol) && Boolean(url.hostname && url.pathname.length > 1) && present(publisher.OTA_DATABASE_URL); } catch { /* Fixed diagnostic below. */ }
|
|
114
|
+
const configured = databaseUrlValid && Boolean(baseUrl(publisher.R2_ENDPOINT)) && ['R2_ENDPOINT', 'R2_ACCESS_KEY_ID', 'R2_SECRET_ACCESS_KEY', 'R2_BUCKET'].every((key) => present(publisher[key]));
|
|
115
|
+
add('app.publisher', configured && Boolean(pkg.scripts?.['ota:publish']) ? 'pass' : 'fail', configured ? 'Publisher credentials are present; permissions were not exercised.' : 'Publisher database/storage credentials are incomplete.', 'Keep existing .env.ota; fill missing values. An access token does not replace publisher DB/S3 credentials.');
|
|
116
|
+
const publisherChannel = publisher.EXPO_UPDATE_CHANNEL?.trim().toLowerCase();
|
|
117
|
+
if (publisherChannel && publisherChannel !== channel) add('app.publisher-channel', 'fail', 'Publisher channel differs from the native app channel.', 'Align EXPO_UPDATE_CHANNEL with expo-channel-name.');
|
|
118
|
+
if (publisher.OTA_SERVER_URL && baseUrl(publisher.OTA_SERVER_URL) !== appBase) add('app.registration-url', 'fail', 'Registrar URL differs from the app/server URL.', 'Align OTA_SERVER_URL in .env.ota with the public server base.');
|
|
119
|
+
const registration = databaseUrlValid || (present(publisher.OTA_ACCESS_TOKEN) && Boolean(baseUrl(publisher.OTA_SERVER_URL)));
|
|
120
|
+
add('app.registration', registration ? 'pass' : 'fail', registration ? 'Embedded registration credentials are present (scope/permissions not exercised).' : 'No usable embedded registration credentials found.', registration ? undefined : 'Set OTA_DATABASE_URL or OTA_SERVER_URL + OTA_ACCESS_TOKEN with updates:write.');
|
|
121
|
+
} catch {
|
|
122
|
+
add('app.publisher', 'fail', 'App .env.ota is missing or unreadable.', 'Create it from .env.ota.example only if absent, then fill publisher and registrar credentials.');
|
|
123
|
+
}
|
|
124
|
+
add('app.native-build', 'warn', 'Source configuration does not prove what is installed on the phone.', 'Build/install a native release after native configuration changes. Include manual download/reload controls or enable hook automation before the first build.');
|
|
125
|
+
return { certificate };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export async function runDoctor(rawOptions = {}, dependencies = {}) {
|
|
129
|
+
const options = { mode: 'docker', timeout: 5000, composeFiles: [], ...rawOptions };
|
|
130
|
+
const cwd = path.resolve(options.cwd || process.cwd());
|
|
131
|
+
const checks = [];
|
|
132
|
+
const add = (id, status, message, remedy) => checks.push({ id, status, message, ...(remedy ? { remedy } : {}) });
|
|
133
|
+
const finish = () => ({ version: 1, mode: options.mode, offline: Boolean(options.offline), status: checks.some((c) => c.status === 'fail') ? 'fail' : checks.some((c) => c.status === 'warn') ? 'warn' : 'pass', checks });
|
|
134
|
+
if (!util.parseEnv) { add('runtime.node', 'fail', 'Doctor requires Node.js 20.12+ (recommended project runtime: Node.js 24).', 'Update Node.js before running doctor.'); return finish(); }
|
|
135
|
+
add('runtime.node', 'pass', 'Node.js supports the required env parser.');
|
|
136
|
+
const require = createRequire(path.join(cwd, 'package.json'));
|
|
137
|
+
for (const name of ['typescript', 'pg', '@aws-sdk/client-s3']) {
|
|
138
|
+
try { require.resolve(name); add(`dependencies.${name}`, 'pass', `Server dependency ${name} is available.`); }
|
|
139
|
+
catch { add(`dependencies.${name}`, 'fail', `Server dependency ${name} is missing.`, 'Run npm ci in the server directory.'); }
|
|
140
|
+
}
|
|
141
|
+
let env;
|
|
142
|
+
const envPath = path.resolve(cwd, options.serverEnv || (options.mode === 'docker' ? '.env' : '.env.local'));
|
|
143
|
+
try { env = await readDoctorEnv(envPath); add('server.env', 'pass', 'Selected env file is readable. Ambient server credentials are not merged.'); }
|
|
144
|
+
catch { add('server.env', 'fail', 'Selected server env file is missing or unreadable.', 'Pass --server-env with a valid file; create it from the appropriate example if absent.'); return finish(); }
|
|
145
|
+
if (Object.values(env).some((value) => /\$\{[^}]+\}/.test(value))) add('server.env-expansion', 'warn', 'Env interpolation is present and is not evaluated by static diagnostics.', 'Use explicit values for remote mode. Docker online probes inspect the actual running process environment.');
|
|
146
|
+
let result;
|
|
147
|
+
if (options.mode === 'docker' && !options.offline) {
|
|
148
|
+
const args = ['compose', '--env-file', envPath];
|
|
149
|
+
if (options.project) args.push('--project-name', options.project);
|
|
150
|
+
for (const file of options.composeFiles.length ? options.composeFiles : ['docker-compose.yml']) args.push('--file', path.resolve(cwd, file));
|
|
151
|
+
const script = `const probe = ${probeServer.toString()}; process.stdout.write(JSON.stringify(await probe({env: process.env, timeout: ${options.timeout}})));`;
|
|
152
|
+
// Forward only execution/Docker context settings, never arbitrary application env overrides.
|
|
153
|
+
const childEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => /^(PATH|HOME|USER|TMPDIR|SystemRoot|DOCKER_HOST|DOCKER_CONTEXT|DOCKER_CONFIG|DOCKER_TLS_VERIFY|DOCKER_CERT_PATH|SSH_AUTH_SOCK|XDG_RUNTIME_DIR)$/.test(key)));
|
|
154
|
+
try {
|
|
155
|
+
const output = await (dependencies.exec || exec)('docker', [...args, 'exec', '-T', 'app', 'node', '--input-type=module', '-e', script], { cwd, env: childEnv, timeout: options.timeout * 12 + 10000, maxBuffer: 1024 * 1024 });
|
|
156
|
+
result = JSON.parse(output.stdout);
|
|
157
|
+
if (!Array.isArray(result.checks)) throw new Error('probe');
|
|
158
|
+
add('docker.app', 'pass', 'Read-only probes executed as the running app container user.');
|
|
159
|
+
if (env.OTA_PUBLIC_BASE_URL && baseUrl(env.OTA_PUBLIC_BASE_URL) !== baseUrl(result.publicUrl)) add('docker.env-drift', 'fail', 'Running container public URL differs from the selected env file.', 'Check Compose overrides and recreate the app after reviewing the environment change.');
|
|
160
|
+
} catch {
|
|
161
|
+
add('docker.app', 'fail', 'Cannot run probes in the selected app container.', 'Check Docker availability, project/files, and that service app is running. Use --offline to inspect files before startup.');
|
|
162
|
+
}
|
|
163
|
+
} else {
|
|
164
|
+
let configured = { ...env };
|
|
165
|
+
if (options.mode === 'docker') {
|
|
166
|
+
configured = { ...env, DATABASE_PROVIDER: 'pg',
|
|
167
|
+
R2_ENDPOINT: `http://127.0.0.1:${env.MINIO_API_PORT || '9000'}`, R2_ACCESS_KEY_ID: env.MINIO_ROOT_USER || 'expo_updates', R2_SECRET_ACCESS_KEY: env.MINIO_ROOT_PASSWORD,
|
|
168
|
+
OTA_PUBLIC_BASE_URL: env.OTA_PUBLIC_BASE_URL || 'http://localhost:3000', CODE_SIGNING_PRIVATE_KEY_PATH: path.join(cwd, 'secrets/code-signing-private-key.pem') };
|
|
169
|
+
configured.DATABASE_URL = `postgresql://${encodeURIComponent(env.POSTGRES_USER || 'expo_updates')}:${encodeURIComponent(env.POSTGRES_PASSWORD || '')}@127.0.0.1:${env.POSTGRES_PORT || '5432'}/${encodeURIComponent(env.POSTGRES_DB || 'expo_updates')}`;
|
|
170
|
+
add('docker.offline', 'skip', 'Container permissions, actual Compose overrides and connectivity are not checked offline.');
|
|
171
|
+
if (!present(env.POSTGRES_PASSWORD) || !present(env.MINIO_ROOT_PASSWORD)) add('docker.credentials', 'fail', 'Docker database/storage passwords are missing or placeholders.', 'Set separate strong POSTGRES_PASSWORD and MINIO_ROOT_PASSWORD values.');
|
|
172
|
+
} else if (configured.CODE_SIGNING_PRIVATE_KEY_PATH) configured.CODE_SIGNING_PRIVATE_KEY_PATH = path.resolve(cwd, configured.CODE_SIGNING_PRIVATE_KEY_PATH);
|
|
173
|
+
result = await (dependencies.probe || probeServer)({ env: configured, timeout: options.timeout, network: !options.offline });
|
|
174
|
+
}
|
|
175
|
+
if (options.mode === 'docker' && ['POSTGRES_PASSWORD', 'MINIO_ROOT_PASSWORD'].some((key) => env[key] && /[^a-zA-Z0-9_-]/.test(env[key]))) add('docker.env-characters', 'warn', 'Docker passwords contain characters requiring env/URI escaping.', 'Current Compose/configurator handling is limited. Verify credentials round-trip correctly; random hex passwords avoid the known interpolation issue.');
|
|
176
|
+
if (result) checks.push(...result.checks);
|
|
177
|
+
const serverUrl = result?.publicUrl || env.OTA_PUBLIC_BASE_URL;
|
|
178
|
+
if (!options.offline && baseUrl(serverUrl)) {
|
|
179
|
+
try {
|
|
180
|
+
const response = await (dependencies.fetch || fetch)(`${baseUrl(serverUrl)}/api/health`, { redirect: 'error', signal: AbortSignal.timeout(options.timeout) });
|
|
181
|
+
const body = await response.json();
|
|
182
|
+
if (!response.ok || body.status !== 'ok' || body.checks?.database !== 'ok') throw new Error('health');
|
|
183
|
+
add('server.health', 'pass', 'Public health endpoint is reachable from this host and reports database readiness.');
|
|
184
|
+
} catch {
|
|
185
|
+
add('server.health', 'fail', 'Public health endpoint is unreachable, redirected, invalid or unhealthy.', 'Check server startup, HTTPS/proxy/tunnel access and OTA_PUBLIC_BASE_URL. Device endpoints must not require browser sign-in.');
|
|
186
|
+
}
|
|
187
|
+
} else add('server.health', 'skip', 'Public health probe skipped (offline mode or invalid URL).');
|
|
188
|
+
let app = {};
|
|
189
|
+
if (options.app) app = await inspectApplication(path.resolve(cwd, options.app), serverUrl, add);
|
|
190
|
+
else add('app.config', 'skip', 'No application selected. Use --app to verify client integration.');
|
|
191
|
+
const certificatePath = options.certificate ? path.resolve(cwd, options.certificate) : app.certificate;
|
|
192
|
+
if (certificatePath) {
|
|
193
|
+
try {
|
|
194
|
+
const cert = new X509Certificate(await fs.readFile(certificatePath));
|
|
195
|
+
const now = Date.now();
|
|
196
|
+
if (now < Date.parse(cert.validFrom) || now > Date.parse(cert.validTo) || cert.publicKey.asymmetricKeyType !== 'rsa' || cert.publicKey.asymmetricKeyDetails.modulusLength < 2048 || cert.ca) throw new Error('certificate');
|
|
197
|
+
const details = await exec('openssl', ['x509', '-in', certificatePath, '-noout', '-text'], { timeout: options.timeout, maxBuffer: 1024 * 1024 });
|
|
198
|
+
if (!/X509v3 Key Usage:[^\n]*\n\s*Digital Signature\b/.test(details.stdout)
|
|
199
|
+
|| !/X509v3 Extended Key Usage:[^\n]*\n\s*(?:[^\n]*,\s*)?Code Signing\b/.test(details.stdout)) throw new Error('certificate usage');
|
|
200
|
+
add('signing.certificate', 'pass', 'Public RSA certificate is valid, current, non-CA and allows Digital Signature / Code Signing.');
|
|
201
|
+
const fingerprint = createHash('sha256').update(cert.publicKey.export({ type: 'spki', format: 'der' })).digest('hex');
|
|
202
|
+
if (result?.keyFingerprint) add('signing.match', fingerprint === result.keyFingerprint ? 'pass' : 'fail', fingerprint === result.keyFingerprint ? 'App certificate matches the server signing key.' : 'Certificate and server signing key do not match.', fingerprint === result.keyFingerprint ? undefined : 'Use the matching certificate/key pair. Changing the app certificate requires a native rebuild.');
|
|
203
|
+
else add('signing.match', 'skip', 'Cannot compare certificate without a readable server key.');
|
|
204
|
+
if (options.certificate && app.certificate && path.resolve(cwd, options.certificate) !== app.certificate) add('signing.override', 'warn', 'Explicit certificate overrides the app certificate for comparison.', 'Omit --certificate to verify the certificate referenced by app.json.');
|
|
205
|
+
} catch { add('signing.certificate', 'fail', 'Public certificate is missing, invalid, expired, not yet valid or unsuitable.', 'Install OpenSSL and use a current non-CA RSA certificate (at least 2048 bits) with Digital Signature and Code Signing usage, matching the server key.'); }
|
|
206
|
+
} else add('signing.certificate', 'skip', 'No certificate selected. Use --certificate or --app to compare signing keys.');
|
|
207
|
+
return finish();
|
|
208
|
+
}
|