indraq_cli 2.8.1 → 2.13.2
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/README.md +185 -2
- package/cloud-api/.env.example +9 -0
- package/cloud-api/README.md +34 -1
- package/cloud-api/dist/index.js +1396 -68
- package/cloud-api/dist/index.js.map +1 -1
- package/cloud-api/dist/ota-device-enrollment.js +41 -0
- package/cloud-api/dist/ota-device-enrollment.js.map +1 -0
- package/cloud-api/dist/ota-enrollment-pages.js +67 -0
- package/cloud-api/dist/ota-enrollment-pages.js.map +1 -0
- package/cloud-api/dist/ota-recovery-content.js +36 -0
- package/cloud-api/dist/ota-recovery-content.js.map +1 -0
- package/cloud-api/dist/ota-recovery-protocol.js +16 -0
- package/cloud-api/dist/ota-release-policy.js +25 -0
- package/cloud-api/dist/ota-release-policy.js.map +1 -0
- package/cloud-api/package.json +1 -1
- package/cloud-api/public/indraq-logo.png +0 -0
- package/cloud-api/sql/015_ota_device_registry_and_withdrawal.sql +23 -0
- package/cloud-api/sql/016_ota_verified_tester_devices.sql +19 -0
- package/cloud-api/sql/017_ota_device_app_access_grants.sql +18 -0
- package/cloud-api/sql/018_ota_android_tester_agent.sql +24 -0
- package/cloud-api/sql/019_ota_android_scoped_testers.sql +9 -0
- package/cloud-api/sql/020_ota_recovery_and_retention.sql +21 -0
- package/cloud-api/sql/021_ota_device_profile_consolidation.sql +14 -0
- package/cloud-api/src/index.ts +1078 -82
- package/cloud-api/src/index.ts.backup-before-extra-params-2026-11-20T19-41-35-684Z +3189 -0
- package/cloud-api/src/ota-device-enrollment.ts +30 -0
- package/cloud-api/src/ota-enrollment-pages.ts +71 -0
- package/cloud-api/src/ota-recovery-content.ts +45 -0
- package/cloud-api/src/ota-recovery-protocol.ts +16 -0
- package/cloud-api/src/ota-release-policy.ts +28 -0
- package/dist/cli/help-content.d.ts.map +1 -1
- package/dist/cli/help-content.js +34 -10
- package/dist/cli/help-content.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modules/mobile/commands/build-mobile.command.d.ts +3 -1
- package/dist/modules/mobile/commands/build-mobile.command.d.ts.map +1 -1
- package/dist/modules/mobile/commands/build-mobile.command.js +214 -57
- package/dist/modules/mobile/commands/build-mobile.command.js.map +1 -1
- package/dist/modules/mobile/commands/mobile-build-wizard.command.d.ts +3 -1
- package/dist/modules/mobile/commands/mobile-build-wizard.command.d.ts.map +1 -1
- package/dist/modules/mobile/commands/mobile-build-wizard.command.js +23 -16
- package/dist/modules/mobile/commands/mobile-build-wizard.command.js.map +1 -1
- package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts +2 -0
- package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts.map +1 -1
- package/dist/modules/mobile/commands/mobile-prebuild.command.js +58 -2
- package/dist/modules/mobile/commands/mobile-prebuild.command.js.map +1 -1
- package/dist/modules/mobile/commands/ota.command.d.ts +9 -0
- package/dist/modules/mobile/commands/ota.command.d.ts.map +1 -1
- package/dist/modules/mobile/commands/ota.command.js +271 -103
- package/dist/modules/mobile/commands/ota.command.js.map +1 -1
- package/dist/modules/mobile/commands/testers.command.d.ts +11 -0
- package/dist/modules/mobile/commands/testers.command.d.ts.map +1 -1
- package/dist/modules/mobile/commands/testers.command.js +236 -5
- package/dist/modules/mobile/commands/testers.command.js.map +1 -1
- package/dist/modules/mobile/config/mobile-config.d.ts +3 -0
- package/dist/modules/mobile/config/mobile-config.d.ts.map +1 -1
- package/dist/modules/mobile/config/mobile-config.js.map +1 -1
- package/dist/modules/mobile/index.d.ts.map +1 -1
- package/dist/modules/mobile/index.js +41 -6
- package/dist/modules/mobile/index.js.map +1 -1
- package/dist/modules/mobile/services/mobile-cloud.service.d.ts +85 -1
- package/dist/modules/mobile/services/mobile-cloud.service.d.ts.map +1 -1
- package/dist/modules/mobile/services/mobile-cloud.service.js +27 -1
- package/dist/modules/mobile/services/mobile-cloud.service.js.map +1 -1
- package/dist/modules/mobile/services/mobile-native-integration.service.d.ts +12 -0
- package/dist/modules/mobile/services/mobile-native-integration.service.d.ts.map +1 -0
- package/dist/modules/mobile/services/mobile-native-integration.service.js +394 -0
- package/dist/modules/mobile/services/mobile-native-integration.service.js.map +1 -0
- package/dist/modules/mobile/services/ota-apk-validator.service.d.ts +4 -0
- package/dist/modules/mobile/services/ota-apk-validator.service.d.ts.map +1 -1
- package/dist/modules/mobile/services/ota-apk-validator.service.js +25 -3
- package/dist/modules/mobile/services/ota-apk-validator.service.js.map +1 -1
- package/dist/modules/mobile/services/ota-native-compatibility.service.d.ts +18 -0
- package/dist/modules/mobile/services/ota-native-compatibility.service.d.ts.map +1 -0
- package/dist/modules/mobile/services/ota-native-compatibility.service.js +21 -0
- package/dist/modules/mobile/services/ota-native-compatibility.service.js.map +1 -0
- package/dist/modules/mobile/services/ota-setup.service.d.ts +4 -0
- package/dist/modules/mobile/services/ota-setup.service.d.ts.map +1 -1
- package/dist/modules/mobile/services/ota-setup.service.js +231 -42
- package/dist/modules/mobile/services/ota-setup.service.js.map +1 -1
- package/dist/modules/mobile/services/tester-reconnect-policy.d.ts +9 -0
- package/dist/modules/mobile/services/tester-reconnect-policy.d.ts.map +1 -0
- package/dist/modules/mobile/services/tester-reconnect-policy.js +12 -0
- package/dist/modules/mobile/services/tester-reconnect-policy.js.map +1 -0
- package/dist/modules/mobile/services/tester-reconnect-probe.service.d.ts +5 -0
- package/dist/modules/mobile/services/tester-reconnect-probe.service.d.ts.map +1 -0
- package/dist/modules/mobile/services/tester-reconnect-probe.service.js +41 -0
- package/dist/modules/mobile/services/tester-reconnect-probe.service.js.map +1 -0
- package/dist/modules/scaffold/commands/init.command.d.ts.map +1 -1
- package/dist/modules/scaffold/commands/init.command.js +8 -2
- package/dist/modules/scaffold/commands/init.command.js.map +1 -1
- package/package.json +58 -4
- package/src/modules/mobile/services/android-agent-bridge/IIndraQTesterAgent.aidl +2 -0
- package/src/modules/mobile/services/android-agent-bridge/IndraQTesterModule.java +67 -0
- package/src/modules/mobile/services/android-agent-bridge/IndraQTesterPackage.java +15 -0
- package/src/modules/mobile/services/android-identity-bridge/IndraQDeviceIdentityModule.java +31 -0
- package/src/modules/mobile/services/android-identity-bridge/IndraQDeviceIdentityPackage.java +16 -0
- package/src/modules/mobile/services/expo-android-identity-plugin.cjs +44 -0
package/cloud-api/src/index.ts
CHANGED
|
@@ -5,12 +5,17 @@ import jwt from 'jsonwebtoken';
|
|
|
5
5
|
import pg from 'pg';
|
|
6
6
|
import nodemailer from 'nodemailer';
|
|
7
7
|
import { IAMClient, CreateAccessKeyCommand, DeleteAccessKeyCommand, ListAccessKeysCommand } from '@aws-sdk/client-iam';
|
|
8
|
-
import { createCipheriv, createDecipheriv, createHash, createSign, randomBytes, randomInt } from 'node:crypto';
|
|
8
|
+
import { createCipheriv, createDecipheriv, createHash, createHmac, createSign, createVerify, createPublicKey, randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
|
|
9
9
|
import { isIP } from 'node:net';
|
|
10
10
|
import { readdir, readFile } from 'node:fs/promises';
|
|
11
11
|
import { dirname, resolve } from 'node:path';
|
|
12
12
|
import { fileURLToPath } from 'node:url';
|
|
13
13
|
import * as Minio from 'minio';
|
|
14
|
+
import { deviceToken, deviceTokenHash, deviceCookieHeader, readDeviceCookie, verifiedBrowserMatches, registeredInviteCanRedeem } from './ota-device-enrollment.js';
|
|
15
|
+
import { mayFinalize, mayPromote, mayPause, mayRollback, mayWithdraw, otaAudiencesMayOverlap } from './ota-release-policy.js';
|
|
16
|
+
import { embeddedDirective, multipartDirective } from './ota-recovery-protocol.js';
|
|
17
|
+
import { recoveryPayloadsMatch } from './ota-recovery-content.js';
|
|
18
|
+
import { enrollmentPage, devicePortalPage, reconnectPage } from './ota-enrollment-pages.js';
|
|
14
19
|
|
|
15
20
|
const { Pool } = pg;
|
|
16
21
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
@@ -24,6 +29,11 @@ if (!/^[a-fA-F0-9]{64}$/.test(masterHex)) throw new Error('MASTER_KEY must be ex
|
|
|
24
29
|
const masterKey = Buffer.from(masterHex, 'hex');
|
|
25
30
|
|
|
26
31
|
|
|
32
|
+
// An Android ID is an identification hint, NOT possession proof. This opt-in
|
|
33
|
+
// weak-trust mode is restricted to private tester builds. Disabled by default.
|
|
34
|
+
const androidScopedTesterRestoreEnabled = process.env.OTA_ANDROID_SCOPED_TESTER_RESTORE === 'true';
|
|
35
|
+
const androidScopedIdPattern = /^(?!9774d56d682e549c$)[0-9a-f]{16}$/i;
|
|
36
|
+
const scopedIdDigest=(value:string):string=>createHmac('sha256',masterKey).update('indraq-ota-ssaid-v1\0'+value.toLowerCase()).digest('hex');
|
|
27
37
|
const publicApiUrl = (process.env.PUBLIC_API_URL || 'https://cli.indraq.com').replace(/\/+$/, '');
|
|
28
38
|
const minioBucket = process.env.MINIO_BUCKET || 'indraq-ota';
|
|
29
39
|
let minioClient: Minio.Client | null = null;
|
|
@@ -2477,37 +2487,80 @@ const publicMobileApp = async (updatePath: string): Promise<any | null> => {
|
|
|
2477
2487
|
};
|
|
2478
2488
|
|
|
2479
2489
|
const parseExpoExtraParams = (header: unknown): Record<string,string> => {
|
|
2480
|
-
|
|
2481
|
-
//
|
|
2482
|
-
//
|
|
2483
|
-
const
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2490
|
+
// Expo-Extra-Params is an RFC 8941-style structured-field dictionary.
|
|
2491
|
+
// Our CLI sends string values. Parse those strictly and reject malformed
|
|
2492
|
+
// dictionaries instead of accidentally reading a substring of a bad header.
|
|
2493
|
+
const input = (typeof header === 'string' ? header : Array.isArray(header) ? header[0] : '')?.trim() || '';
|
|
2494
|
+
const out: Record<string,string> = {};
|
|
2495
|
+
if (!input || input.length > 8192) return out;
|
|
2496
|
+
let i = 0;
|
|
2497
|
+
const whitespace = () => { while (input[i] === ' ' || input[i] === '\t') i += 1; };
|
|
2498
|
+
while (i < input.length) {
|
|
2499
|
+
whitespace();
|
|
2500
|
+
const start = i;
|
|
2501
|
+
while (i < input.length && /[a-z0-9_.*-]/i.test(input[i])) i += 1;
|
|
2502
|
+
const key = input.slice(start, i).toLowerCase();
|
|
2503
|
+
if (!/^[a-z*][a-z0-9_.*-]*$/.test(key) || Object.prototype.hasOwnProperty.call(out, key)) return {};
|
|
2504
|
+
whitespace();
|
|
2505
|
+
if (input[i] !== '=') return {};
|
|
2506
|
+
i += 1;
|
|
2507
|
+
whitespace();
|
|
2508
|
+
if (input[i] !== '"') return {}; // IndraQ extra parameters are always strings.
|
|
2509
|
+
i += 1;
|
|
2510
|
+
let value = '';
|
|
2511
|
+
let closed = false;
|
|
2512
|
+
while (i < input.length) {
|
|
2513
|
+
const ch = input[i++];
|
|
2514
|
+
if (ch === '"') { closed = true; break; }
|
|
2515
|
+
if (ch === '\\') {
|
|
2516
|
+
const next = input[i++];
|
|
2517
|
+
if (next !== '"' && next !== '\\') return {};
|
|
2518
|
+
value += next;
|
|
2519
|
+
} else {
|
|
2520
|
+
if (ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127) return {};
|
|
2521
|
+
value += ch;
|
|
2522
|
+
}
|
|
2523
|
+
}
|
|
2524
|
+
if (!closed) return {};
|
|
2525
|
+
out[key] = value;
|
|
2526
|
+
whitespace();
|
|
2527
|
+
if (i === input.length) break;
|
|
2528
|
+
if (input[i] !== ',') return {};
|
|
2529
|
+
i += 1;
|
|
2530
|
+
whitespace();
|
|
2531
|
+
if (i === input.length) return {};
|
|
2488
2532
|
}
|
|
2489
2533
|
return out;
|
|
2490
2534
|
};
|
|
2491
2535
|
const requestIdentity = (req: Request): { installationId: string; userId: string; username: string; email: string; phone: string; currentUpdateId:string } => {
|
|
2492
|
-
const extra=parseExpoExtraParams(req.headers['expo-extra-params']);
|
|
2493
|
-
const value=(header:string,extraKey:string,max:number):string=>
|
|
2536
|
+
const extra = parseExpoExtraParams(req.headers['expo-extra-params']);
|
|
2537
|
+
const value = (header: string, extraKey: string, max: number): string => {
|
|
2538
|
+
// New clients use Expo-Extra-Params to avoid changing the native launch
|
|
2539
|
+
// identity. Old clients still send x-indraq-* headers. Prefer extra params
|
|
2540
|
+
// whenever available, but keep the legacy fallback for deployed APKs.
|
|
2541
|
+
const extraValue = extra[extraKey];
|
|
2542
|
+
const legacyValue = req.headers[header];
|
|
2543
|
+
const raw = extraValue || (typeof legacyValue === 'string' ? legacyValue : Array.isArray(legacyValue) ? legacyValue[0] : '') || '';
|
|
2544
|
+
return String(raw).trim().slice(0, max);
|
|
2545
|
+
};
|
|
2494
2546
|
return {
|
|
2495
|
-
installationId:value('x-indraq-installation-id','indraq-installation-id',200),
|
|
2496
|
-
userId:value('x-indraq-user-id','indraq-user-id',200),
|
|
2497
|
-
username:value('x-indraq-username','indraq-username',200),
|
|
2498
|
-
email:value('x-indraq-email','indraq-email',320).toLowerCase(),
|
|
2499
|
-
phone:value('x-indraq-phone','indraq-phone',80),
|
|
2500
|
-
currentUpdateId:value('x-indraq-current-update-id','indraq-current-update-id',200)
|
|
2547
|
+
installationId: value('x-indraq-installation-id','indraq-installation-id',200),
|
|
2548
|
+
userId: value('x-indraq-user-id','indraq-user-id',200),
|
|
2549
|
+
username: value('x-indraq-username','indraq-username',200),
|
|
2550
|
+
email: value('x-indraq-email','indraq-email',320).toLowerCase(),
|
|
2551
|
+
phone: value('x-indraq-phone','indraq-phone',80),
|
|
2552
|
+
currentUpdateId: value('x-indraq-current-update-id','indraq-current-update-id',200)
|
|
2501
2553
|
};
|
|
2502
2554
|
};
|
|
2503
|
-
|
|
2504
|
-
const audienceMatches = (row: any, identity: ReturnType<typeof requestIdentity>, groups: ReadonlySet<string> = new Set(), activeTester = false): boolean => {
|
|
2555
|
+
const audienceMatches = (row: any, identity: ReturnType<typeof requestIdentity>, groups: ReadonlySet<string> = new Set(), activeTester = false, approvedDeviceId: string|null = null, legacyDeviceIds:ReadonlySet<string> = new Set()): boolean => {
|
|
2505
2556
|
if (row.status === 'released' && row.audience_type === 'all') return true;
|
|
2506
2557
|
if (row.status === 'released' && row.audience_type === 'percentage') {
|
|
2507
2558
|
if (!identity.installationId || !row.rollout_percent) return false;
|
|
2508
2559
|
const bucket = Number.parseInt(createHash('sha256').update(`${identity.installationId}:${row.id}`).digest('hex').slice(0, 8), 16) % 100;
|
|
2509
2560
|
return bucket < Number(row.rollout_percent);
|
|
2510
2561
|
}
|
|
2562
|
+
const deviceIds=Array.isArray(row.audience?.deviceIds) ? row.audience.deviceIds as string[] : [];
|
|
2563
|
+
if(deviceIds.length && activeTester && approvedDeviceId && deviceIds.some(id=>id===approvedDeviceId||legacyDeviceIds.has(id)))return true;
|
|
2511
2564
|
const groupIds = Array.isArray(row.audience?.groupIds) ? row.audience.groupIds as string[] : [];
|
|
2512
2565
|
if (groupIds.some((id) => groups.has(String(id)))) return true;
|
|
2513
2566
|
if (row.audience?.enrolledOnly === true && !activeTester) return false;
|
|
@@ -2530,6 +2583,458 @@ const audienceMatches = (row: any, identity: ReturnType<typeof requestIdentity>,
|
|
|
2530
2583
|
const enrollmentTokenPattern = /^[A-Za-z0-9_-]{43}$/;
|
|
2531
2584
|
const enrollmentSchemePattern = /^[a-z][a-z0-9+.-]{1,39}$/;
|
|
2532
2585
|
const hashEnrollmentToken = (token: string): string => createHash('sha256').update(token).digest('hex');
|
|
2586
|
+
// Grants authorize an account-owned, QR-verified phone profile for a mobile project.
|
|
2587
|
+
// They never substitute for cryptographic installation pairing across app sandboxes.
|
|
2588
|
+
const requestedAppIds=(input:unknown):string[]=>{
|
|
2589
|
+
if(input===undefined)return [];
|
|
2590
|
+
if(!Array.isArray(input)||input.length>50)throw Object.assign(new Error('appIds must be an array of at most 50 app IDs.'),{statusCode:400});
|
|
2591
|
+
return [...new Set(input.map(v=>ensureUuid(String(v),'Mobile app ID')))];
|
|
2592
|
+
};
|
|
2593
|
+
const requestedDeviceIds=(input:unknown):string[]=>{
|
|
2594
|
+
if(!Array.isArray(input)||input.length<1||input.length>50)throw Object.assign(new Error('deviceIds must contain 1 to 50 registered devices.'),{statusCode:400});
|
|
2595
|
+
return [...new Set(input.map(v=>ensureUuid(String(v),'Registered device ID')))];
|
|
2596
|
+
};
|
|
2597
|
+
const authorizeDeviceApps=async(user:Auth,appIds:string[]):Promise<void>=>{
|
|
2598
|
+
for(const appId of appIds){
|
|
2599
|
+
if(!await mobileAppForUser(appId,user,true))
|
|
2600
|
+
throw Object.assign(new Error(`WRITE access required to authorize tester devices for app ${appId}.`),{statusCode:403});
|
|
2601
|
+
}
|
|
2602
|
+
};
|
|
2603
|
+
|
|
2604
|
+
|
|
2605
|
+
// Tester profiles are PENDING until a real phone browser approves a one-use QR.
|
|
2606
|
+
// Proof is a secure browser credential; it is not an OS hardware ID or biometric attestation.
|
|
2607
|
+
const createDeviceChallenge = async (deviceId:string,ownerId:string):Promise<{challengeId:string;enrollmentUrl:string;expiresAt:string}> => {
|
|
2608
|
+
const token=deviceToken();
|
|
2609
|
+
const row=(await pool.query(`INSERT INTO ota_device_registration_challenges(device_id,token_hash,expires_at)
|
|
2610
|
+
SELECT d.id,$2,now()+interval '15 minutes' FROM ota_registered_tester_devices d
|
|
2611
|
+
WHERE d.id=$1 AND d.owner_user_id=$3 AND d.revoked_at IS NULL AND d.verified_at IS NULL
|
|
2612
|
+
RETURNING id,expires_at`,[deviceId,deviceTokenHash(token),ownerId])).rows[0];
|
|
2613
|
+
if(!row)throw Object.assign(new Error('Profile is already verified or revoked.'),{statusCode:409});
|
|
2614
|
+
return {challengeId:row.id,enrollmentUrl:`${publicApiUrl}/ota/device/register/${token}`,expiresAt:row.expires_at};
|
|
2615
|
+
};
|
|
2616
|
+
app.get('/mobile/tester-devices', auth, async (req: AuthedRequest,res) => {
|
|
2617
|
+
const rows=(await pool.query(`SELECT d.id,d.label,d.created_at,d.verified_at,d.revoked_at,d.agent_activated_at,
|
|
2618
|
+
(SELECT count(*)::int FROM ota_registered_device_installations l WHERE l.device_id=d.id) linked_installations
|
|
2619
|
+
FROM ota_registered_tester_devices d WHERE d.owner_user_id=$1 AND ($2::boolean OR d.revoked_at IS NULL) ORDER BY d.created_at DESC`,[req.auth!.id,req.query.all==='true'])).rows;
|
|
2620
|
+
res.json(rows);
|
|
2621
|
+
});
|
|
2622
|
+
app.post('/mobile/tester-devices', auth, async (req: AuthedRequest,res) => {
|
|
2623
|
+
const label=textValue(req.body?.label,'Device label',80);
|
|
2624
|
+
const appIds=requestedAppIds(req.body?.appIds);
|
|
2625
|
+
await authorizeDeviceApps(req.auth!,appIds); // Validate ALL grants before creating a profile.
|
|
2626
|
+
const client=await pool.connect();
|
|
2627
|
+
let row:any;
|
|
2628
|
+
try{
|
|
2629
|
+
await client.query('BEGIN');
|
|
2630
|
+
row=(await client.query(`INSERT INTO ota_registered_tester_devices(owner_user_id,label)
|
|
2631
|
+
VALUES($1,$2) RETURNING id,label,created_at,verified_at`,[req.auth!.id,label])).rows[0];
|
|
2632
|
+
for(const appId of appIds)await client.query(`INSERT INTO ota_device_app_grants(device_id,app_id,granted_by)
|
|
2633
|
+
VALUES($1,$2,$3)`,[row.id,appId,req.auth!.id]);
|
|
2634
|
+
await client.query('COMMIT');
|
|
2635
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}finally{client.release();}
|
|
2636
|
+
const challenge=await createDeviceChallenge(row.id,req.auth!.id);
|
|
2637
|
+
await audit(req.auth!.id,'ota.device.pending','tester-device',row.id,'Create pending tester device with app grants; QR confirmation required',{appIds});
|
|
2638
|
+
res.setHeader('Cache-Control','no-store');
|
|
2639
|
+
res.status(201).json({...row,...challenge,authorizedAppIds:appIds});
|
|
2640
|
+
});
|
|
2641
|
+
// Existing v2.9 profile-only records can be verified without creating duplicate devices.
|
|
2642
|
+
app.post('/mobile/tester-devices/:id/verify', auth, async (req: AuthedRequest,res) => {
|
|
2643
|
+
const id=ensureUuid(routeParam(req.params.id),'Device ID');
|
|
2644
|
+
// Explicit reset allows recovering a verified profile after browser data was cleared.
|
|
2645
|
+
// The old browser credential becomes invalid immediately; the profile is pending again.
|
|
2646
|
+
if(req.body?.reset===true){
|
|
2647
|
+
const reset=await pool.query(`UPDATE ota_registered_tester_devices
|
|
2648
|
+
SET verified_at=NULL,browser_credential_hash=NULL,agent_public_key=NULL,agent_activated_at=NULL
|
|
2649
|
+
WHERE id=$1 AND owner_user_id=$2 AND revoked_at IS NULL RETURNING id`,[id,req.auth!.id]);
|
|
2650
|
+
if(!reset.rowCount){res.status(404).json({error:'Active device profile not found.'});return;}
|
|
2651
|
+
await audit(req.auth!.id,'ota.device.reset','tester-device',id,'Reset browser approval; previous credential revoked');
|
|
2652
|
+
}
|
|
2653
|
+
const challenge=await createDeviceChallenge(id,req.auth!.id);
|
|
2654
|
+
res.setHeader('Cache-Control','no-store');res.json(challenge);
|
|
2655
|
+
});
|
|
2656
|
+
// Authenticated CLI polling. Never expose the one-time registration secret here.
|
|
2657
|
+
app.get('/mobile/tester-devices/:id/challenges/:challengeId/status',auth,async(req:AuthedRequest,res)=>{
|
|
2658
|
+
const id=ensureUuid(routeParam(req.params.id),'Device ID');
|
|
2659
|
+
const challengeId=ensureUuid(routeParam(req.params.challengeId),'Challenge ID');
|
|
2660
|
+
const row=(await pool.query(`SELECT d.id,d.label,d.verified_at,d.revoked_at,c.expires_at,c.completed_at
|
|
2661
|
+
FROM ota_registered_tester_devices d JOIN ota_device_registration_challenges c ON c.device_id=d.id
|
|
2662
|
+
WHERE d.id=$1 AND d.owner_user_id=$2 AND c.id=$3`,[id,req.auth!.id,challengeId])).rows[0];
|
|
2663
|
+
if(!row){res.status(404).json({error:'Registration challenge not found.'});return;}
|
|
2664
|
+
const status=row.revoked_at?'revoked':row.completed_at&&row.verified_at?'verified':
|
|
2665
|
+
row.completed_at?'duplicate':row.verified_at?'superseded':new Date(row.expires_at).getTime()<=Date.now()?'expired':'pending';
|
|
2666
|
+
res.setHeader('Cache-Control','no-store');res.json({id:row.id,label:row.label,status,verifiedAt:row.verified_at||null,expiresAt:row.expires_at});
|
|
2667
|
+
});
|
|
2668
|
+
app.get('/ota/device/register/:token', async (req,res) => {
|
|
2669
|
+
const token=routeParam(req.params.token);
|
|
2670
|
+
res.setHeader('Cache-Control','no-store');res.setHeader('Referrer-Policy','no-referrer');
|
|
2671
|
+
res.setHeader('Content-Security-Policy',"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; base-uri 'none'");
|
|
2672
|
+
if(!enrollmentTokenPattern.test(token)){res.status(404).type('text/plain').send('Invalid device QR.');return;}
|
|
2673
|
+
const row=(await pool.query(`SELECT d.id,d.label,d.owner_user_id FROM ota_device_registration_challenges c
|
|
2674
|
+
JOIN ota_registered_tester_devices d ON d.id=c.device_id
|
|
2675
|
+
WHERE c.token_hash=$1 AND c.expires_at>now() AND c.completed_at IS NULL
|
|
2676
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NULL`,[deviceTokenHash(token)])).rows[0];
|
|
2677
|
+
if(!row){res.status(410).type('html').send(enrollmentPage({state:'expired'}));return;}
|
|
2678
|
+
const browser=await verifiedOtaBrowser(req.headers.cookie);
|
|
2679
|
+
if(browser && browser.owner_user_id===row.owner_user_id && browser.id!==row.id){
|
|
2680
|
+
// Inform the waiting CLI immediately instead of leaving its QR pending
|
|
2681
|
+
// until expiry. The unused profile stays unverified for audit/retry.
|
|
2682
|
+
await pool.query(`UPDATE ota_device_registration_challenges SET completed_at=now()
|
|
2683
|
+
WHERE token_hash=$1 AND completed_at IS NULL`,[deviceTokenHash(token)]);
|
|
2684
|
+
res.status(409).type('html').send(enrollmentPage({state:'duplicate',name:browser.label,link:'/ota/device/apps'}));return;
|
|
2685
|
+
}
|
|
2686
|
+
const grants=(await pool.query(`SELECT ma.app_name FROM ota_device_app_grants g
|
|
2687
|
+
JOIN mobile_apps ma ON ma.id=g.app_id
|
|
2688
|
+
WHERE g.device_id=$1 AND g.revoked_at IS NULL ORDER BY ma.app_name`,[row.id])).rows;
|
|
2689
|
+
res.type('html').send(enrollmentPage({state:'register',name:row.label,apps:grants.map(g=>g.app_name),action:`/ota/device/register/${token}/confirm`}));
|
|
2690
|
+
});
|
|
2691
|
+
app.post('/ota/device/register/:token/confirm', async (req,res) => {
|
|
2692
|
+
const token=routeParam(req.params.token);
|
|
2693
|
+
res.setHeader('Cache-Control','no-store');res.setHeader('Referrer-Policy','no-referrer');
|
|
2694
|
+
if(!enrollmentTokenPattern.test(token)){res.status(404).type('text/plain').send('Invalid device QR.');return;}
|
|
2695
|
+
const client=await pool.connect();
|
|
2696
|
+
try{
|
|
2697
|
+
await client.query('BEGIN');
|
|
2698
|
+
const row=(await client.query(`SELECT c.id challenge_id,d.id device_id,d.owner_user_id FROM ota_device_registration_challenges c
|
|
2699
|
+
JOIN ota_registered_tester_devices d ON d.id=c.device_id
|
|
2700
|
+
WHERE c.token_hash=$1 AND c.expires_at>now() AND c.completed_at IS NULL
|
|
2701
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NULL FOR UPDATE OF c,d`,[deviceTokenHash(token)])).rows[0];
|
|
2702
|
+
if(!row){await client.query('ROLLBACK');res.status(410).type('html').send(enrollmentPage({state:'expired'}));return;}
|
|
2703
|
+
const browser=await verifiedOtaBrowser(req.headers.cookie);
|
|
2704
|
+
if(browser && browser.owner_user_id===row.owner_user_id && browser.id!==row.device_id){
|
|
2705
|
+
// Mark only the one-time challenge as duplicate, not the verified profile.
|
|
2706
|
+
await client.query(`UPDATE ota_device_registration_challenges SET completed_at=now() WHERE id=$1`,[row.challenge_id]);
|
|
2707
|
+
await client.query('COMMIT');
|
|
2708
|
+
res.status(409).type('html').send(enrollmentPage({state:'duplicate',name:browser.label,link:'/ota/device/apps'}));return;
|
|
2709
|
+
}
|
|
2710
|
+
const secret=deviceToken();
|
|
2711
|
+
await client.query('UPDATE ota_registered_tester_devices SET verified_at=now(),browser_credential_hash=$2 WHERE id=$1',
|
|
2712
|
+
[row.device_id,deviceTokenHash(secret)]);
|
|
2713
|
+
await client.query('UPDATE ota_device_registration_challenges SET completed_at=now() WHERE id=$1',[row.challenge_id]);
|
|
2714
|
+
await client.query('COMMIT');
|
|
2715
|
+
res.setHeader('Set-Cookie',deviceCookieHeader(row.device_id,secret));
|
|
2716
|
+
res.type('html').send(enrollmentPage({state:'approved',link:'/ota/device/apps'}));
|
|
2717
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}finally{client.release();}
|
|
2718
|
+
});
|
|
2719
|
+
// Consolidate two profiles ONLY after the authenticated owner explicitly confirms
|
|
2720
|
+
// that both registrations represent the SAME phone. Labels are never evidence.
|
|
2721
|
+
// Preserve audit history and old OTA audiences via the permanent alias row.
|
|
2722
|
+
app.post('/mobile/tester-devices/consolidate',auth,async(req:AuthedRequest,res)=>{
|
|
2723
|
+
const canonicalId=ensureUuid(String(req.body?.canonicalDeviceId||''),'Surviving device ID');
|
|
2724
|
+
const duplicateId=ensureUuid(String(req.body?.duplicateDeviceId||''),'Duplicate device ID');
|
|
2725
|
+
const reason=String(req.body?.reason||'').trim();
|
|
2726
|
+
if(canonicalId===duplicateId||req.body?.confirmSamePhysicalDevice!==true||reason.length<12||reason.length>500){
|
|
2727
|
+
res.status(400).json({error:'Choose distinct profiles, confirm same physical phone and provide a reason (12–500 characters).'});return;
|
|
2728
|
+
}
|
|
2729
|
+
const client=await pool.connect();
|
|
2730
|
+
try{
|
|
2731
|
+
await client.query('BEGIN');
|
|
2732
|
+
const rows=(await client.query(`SELECT id,label,verified_at,revoked_at,agent_public_key
|
|
2733
|
+
FROM ota_registered_tester_devices WHERE id=ANY($1::uuid[]) AND owner_user_id=$2
|
|
2734
|
+
ORDER BY id FOR UPDATE`,[[canonicalId,duplicateId],req.auth!.id])).rows;
|
|
2735
|
+
const primary=rows.find((d:any)=>d.id===canonicalId),duplicate=rows.find((d:any)=>d.id===duplicateId);
|
|
2736
|
+
if(!primary||!duplicate||!primary.verified_at||!duplicate.verified_at||primary.revoked_at||duplicate.revoked_at){
|
|
2737
|
+
await client.query('ROLLBACK');res.status(409).json({error:'Both profiles must be active, verified, and owned by your account.'});return;
|
|
2738
|
+
}
|
|
2739
|
+
// Do not silently override app-level revocations: caller must explicitly
|
|
2740
|
+
// reconcile access conflicts before consolidating device identities.
|
|
2741
|
+
const conflicts=(await client.query(`SELECT p.app_id FROM ota_device_app_grants p
|
|
2742
|
+
JOIN ota_device_app_grants d ON d.app_id=p.app_id
|
|
2743
|
+
WHERE p.device_id=$1 AND d.device_id=$2
|
|
2744
|
+
AND (p.revoked_at IS NULL) <> (d.revoked_at IS NULL)`,[canonicalId,duplicateId])).rows;
|
|
2745
|
+
if(conflicts.length){await client.query('ROLLBACK');res.status(409).json({error:'App permission conflict between profiles. Reconcile revoked access before consolidating.',appIds:conflicts.map((g:any)=>g.app_id)});return;}
|
|
2746
|
+
if(primary.agent_public_key&&duplicate.agent_public_key&&primary.agent_public_key!==duplicate.agent_public_key){
|
|
2747
|
+
await client.query('ROLLBACK');res.status(409).json({error:'Profiles have different cryptographic agent keys. Cannot prove that they are the same device.'});return;
|
|
2748
|
+
}
|
|
2749
|
+
const aliased=(await client.query(`SELECT 1 FROM ota_tester_device_profile_aliases
|
|
2750
|
+
WHERE duplicate_device_id=ANY($1::uuid[]) OR canonical_device_id=ANY($1::uuid[])
|
|
2751
|
+
LIMIT 1`,[[canonicalId,duplicateId]])).rowCount;
|
|
2752
|
+
if(aliased){await client.query('ROLLBACK');res.status(409).json({error:'One of these profiles was already consolidated. Choose two original active profiles.'});return;}
|
|
2753
|
+
// Preserve the union of active app grants, but never reactivate a revoked grant.
|
|
2754
|
+
await client.query(`INSERT INTO ota_device_app_grants(device_id,app_id,granted_by,granted_at,revoked_at)
|
|
2755
|
+
SELECT $1,app_id,granted_by,granted_at,NULL FROM ota_device_app_grants
|
|
2756
|
+
WHERE device_id=$2 AND revoked_at IS NULL
|
|
2757
|
+
ON CONFLICT(device_id,app_id) DO NOTHING`,[canonicalId,duplicateId]);
|
|
2758
|
+
const moved=(await client.query(`UPDATE ota_registered_device_installations
|
|
2759
|
+
SET device_id=$1 WHERE device_id=$2 RETURNING app_id,installation_id`,[canonicalId,duplicateId])).rows;
|
|
2760
|
+
await client.query(`UPDATE ota_android_scoped_tester_identities SET device_id=$1 WHERE device_id=$2`,[canonicalId,duplicateId]);
|
|
2761
|
+
if(!primary.agent_public_key && duplicate.agent_public_key){
|
|
2762
|
+
await client.query(`UPDATE ota_registered_tester_devices
|
|
2763
|
+
SET agent_public_key=$2,agent_activated_at=now() WHERE id=$1`,[canonicalId,duplicate.agent_public_key]);
|
|
2764
|
+
}
|
|
2765
|
+
// Outstanding one-use links for the retired profile must not be redeemed.
|
|
2766
|
+
await client.query(`UPDATE ota_enrollment_invitations SET revoked_at=now()
|
|
2767
|
+
WHERE registered_device_id=$1 AND redeemed_at IS NULL AND revoked_at IS NULL`,[duplicateId]);
|
|
2768
|
+
await client.query(`INSERT INTO ota_tester_device_profile_aliases
|
|
2769
|
+
(duplicate_device_id,canonical_device_id,merged_by,reason) VALUES($1,$2,$3,$4)`,
|
|
2770
|
+
[duplicateId,canonicalId,req.auth!.id,reason]);
|
|
2771
|
+
await client.query(`UPDATE ota_registered_tester_devices
|
|
2772
|
+
SET revoked_at=now(),browser_credential_hash=NULL,agent_public_key=NULL,agent_activated_at=NULL
|
|
2773
|
+
WHERE id=$1`,[duplicateId]);
|
|
2774
|
+
// Record who approved the merge IN THE SAME TRANSACTION. The action
|
|
2775
|
+
// must never succeed without its audit trail or return 500 after commit.
|
|
2776
|
+
await client.query(`INSERT INTO audit_logs(actor_id,action,resource_type,resource_id,reason,metadata)
|
|
2777
|
+
VALUES($1,'ota.device.consolidate','tester-device',$2,$3,$4)`,
|
|
2778
|
+
[req.auth!.id,canonicalId,reason,{duplicateDeviceId:duplicateId,linkedInstallationsMoved:moved.length}]);
|
|
2779
|
+
await client.query('COMMIT');
|
|
2780
|
+
res.json({ok:true,canonicalDeviceId:canonicalId,retiredDeviceId:duplicateId,
|
|
2781
|
+
linkedInstallationsMoved:moved.length,note:'Existing release audiences preserved. Retired browser credential invalidated; use surviving registration for future browser pairing.'});
|
|
2782
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}finally{client.release();}
|
|
2783
|
+
});
|
|
2784
|
+
|
|
2785
|
+
app.delete('/mobile/tester-devices/:id', auth, async (req: AuthedRequest,res) => {
|
|
2786
|
+
const id=ensureUuid(routeParam(req.params.id),'Registered device ID');
|
|
2787
|
+
const client=await pool.connect();
|
|
2788
|
+
try {
|
|
2789
|
+
await client.query('BEGIN');
|
|
2790
|
+
const owned=(await client.query(`UPDATE ota_registered_tester_devices SET revoked_at=now(),browser_credential_hash=NULL
|
|
2791
|
+
WHERE id=$1 AND owner_user_id=$2 AND revoked_at IS NULL RETURNING id`,[id,req.auth!.id])).rows[0];
|
|
2792
|
+
if(!owned){await client.query('ROLLBACK');res.status(404).json({error:'Registered device not found.'});return;}
|
|
2793
|
+
await client.query(`UPDATE ota_tester_installations ti SET revoked_at=now() FROM ota_registered_device_installations li
|
|
2794
|
+
WHERE li.device_id=$1 AND li.app_id=ti.app_id AND li.installation_id=ti.installation_id AND ti.revoked_at IS NULL`,[id]);
|
|
2795
|
+
await client.query('COMMIT');
|
|
2796
|
+
await audit(req.auth!.id,'ota.device.revoke','tester-device',id,'Revoke reusable tester profile and linked testing installs');
|
|
2797
|
+
res.status(204).end();
|
|
2798
|
+
}catch(error){await client.query('ROLLBACK');throw error;}finally{client.release();}
|
|
2799
|
+
});
|
|
2800
|
+
|
|
2801
|
+
|
|
2802
|
+
// Browser-based one-time app pairing: verified phone => app association without scanning a second QR.
|
|
2803
|
+
// This is NOT silent cross-app hardware recognition. The phone owner approves each app.
|
|
2804
|
+
const verifiedOtaBrowser=async(cookieHeader:string|undefined):Promise<any|null>=>{
|
|
2805
|
+
const cookie=readDeviceCookie(cookieHeader);
|
|
2806
|
+
if(!cookie)return null;
|
|
2807
|
+
const row=(await pool.query(`SELECT id,label,owner_user_id,verified_at,revoked_at,browser_credential_hash
|
|
2808
|
+
FROM ota_registered_tester_devices WHERE id=$1`,[cookie.id])).rows[0];
|
|
2809
|
+
return row&&verifiedBrowserMatches(cookieHeader,row)?row:null;
|
|
2810
|
+
};
|
|
2811
|
+
const devicePortalCsrf=(cookieHeader:string|undefined,appId:string):string=>{
|
|
2812
|
+
const cookie=readDeviceCookie(cookieHeader);
|
|
2813
|
+
return cookie?deviceTokenHash(cookie.secret+'|indraq-device-app|'+appId):'';
|
|
2814
|
+
};
|
|
2815
|
+
// First-party brand asset. Served from the same origin; no remote trackers.
|
|
2816
|
+
app.get('/ota/brand/indraq-logo.png',async(_req,res)=>{
|
|
2817
|
+
res.setHeader('Cache-Control','public, max-age=86400');
|
|
2818
|
+
const file=resolve(process.cwd(),'public','indraq-logo.png');
|
|
2819
|
+
res.type('png').send(await readFile(file));
|
|
2820
|
+
});
|
|
2821
|
+
const devicePortalHeaders=(res:Response):void=>{
|
|
2822
|
+
res.setHeader('Cache-Control','no-store');res.setHeader('Referrer-Policy','no-referrer');
|
|
2823
|
+
res.setHeader('X-Content-Type-Options','nosniff');
|
|
2824
|
+
res.setHeader('Content-Security-Policy',"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; base-uri 'none'");
|
|
2825
|
+
};
|
|
2826
|
+
// Reconnect a freshly installed (or reinstalled) app through the *previously verified*
|
|
2827
|
+
// phone browser. Unlike ANDROID_ID/IDFV, a browser credential is possession proof.
|
|
2828
|
+
// The app opens this HTTPS address once; no new QR is issued. Browsers may require
|
|
2829
|
+
// the user to tap Open App to complete their OS-level deep-link handoff.
|
|
2830
|
+
app.get('/ota/device/reconnect/:appId',async(req,res)=>{
|
|
2831
|
+
devicePortalHeaders(res);
|
|
2832
|
+
const appId=ensureUuid(routeParam(req.params.appId),'Mobile app ID');
|
|
2833
|
+
const state=typeof req.query.state==='string'?req.query.state:'';
|
|
2834
|
+
if(!/^[A-Za-z0-9_-]{12,128}$/.test(state)){
|
|
2835
|
+
res.status(400).type('html').send(reconnectPage({state:'denied'}));return;
|
|
2836
|
+
}
|
|
2837
|
+
const device=await verifiedOtaBrowser(req.headers.cookie);
|
|
2838
|
+
if(!device){res.status(403).type('html').send(reconnectPage({state:'denied'}));return;}
|
|
2839
|
+
const row=(await pool.query(`SELECT ma.id,ma.app_name,ma.enrollment_scheme FROM mobile_apps ma
|
|
2840
|
+
JOIN projects p ON p.id=ma.project_id
|
|
2841
|
+
LEFT JOIN project_members pm ON pm.project_id=p.id AND pm.user_id=$3
|
|
2842
|
+
JOIN ota_device_app_grants g ON g.app_id=ma.id AND g.device_id=$2 AND g.revoked_at IS NULL
|
|
2843
|
+
WHERE ma.id=$1 AND p.archived_at IS NULL AND (p.created_by=$3 OR pm.user_id=$3)`,
|
|
2844
|
+
[appId,device.id,device.owner_user_id])).rows[0];
|
|
2845
|
+
if(!row||!enrollmentSchemePattern.test(String(row.enrollment_scheme||''))){
|
|
2846
|
+
res.status(403).type('html').send(reconnectPage({state:'unavailable'}));return;
|
|
2847
|
+
}
|
|
2848
|
+
// Bound the number of outstanding invitations per device/app; a malicious
|
|
2849
|
+
// third-party web page must not be able to create unlimited pending records.
|
|
2850
|
+
const recent=await pool.query(`SELECT count(*)::int count FROM ota_enrollment_invitations
|
|
2851
|
+
WHERE registered_device_id=$1 AND app_id=$2 AND created_at>now()-interval '10 minutes'`,[device.id,appId]);
|
|
2852
|
+
if(Number(recent.rows[0]?.count||0)>=10){
|
|
2853
|
+
res.status(429).type('html').send(reconnectPage({state:'unavailable'}));return;
|
|
2854
|
+
}
|
|
2855
|
+
const token=deviceToken();
|
|
2856
|
+
await pool.query(`INSERT INTO ota_enrollment_invitations(app_id,token_hash,label,app_scheme,created_by,expires_at,registered_device_id,browser_approved_at)
|
|
2857
|
+
VALUES($1,$2,$3,$4,$5,now()+interval '5 minutes',$6,now())`,
|
|
2858
|
+
[appId,hashEnrollmentToken(token),device.label,row.enrollment_scheme,device.owner_user_id,device.id]);
|
|
2859
|
+
await audit(device.owner_user_id,'ota.device.app.reconnect','mobile-app',appId,'Verified browser issued installation reconnect token',{deviceId:device.id});
|
|
2860
|
+
const link=`${row.enrollment_scheme}://indraq-enroll?token=${token}&state=${encodeURIComponent(state)}`;
|
|
2861
|
+
res.type('html').send(reconnectPage({state:'open',app:row.app_name,link}));
|
|
2862
|
+
});
|
|
2863
|
+
|
|
2864
|
+
app.get('/ota/device/apps',async(req,res)=>{
|
|
2865
|
+
devicePortalHeaders(res);
|
|
2866
|
+
const device=await verifiedOtaBrowser(req.headers.cookie);
|
|
2867
|
+
if(!device){res.status(403).type('html').send(enrollmentPage({state:'denied'}));return;}
|
|
2868
|
+
const rows=(await pool.query(`SELECT DISTINCT ma.id,ma.app_name,ma.enrollment_scheme
|
|
2869
|
+
FROM mobile_apps ma JOIN projects p ON p.id=ma.project_id
|
|
2870
|
+
JOIN ota_device_app_grants g ON g.app_id=ma.id AND g.device_id=$2 AND g.revoked_at IS NULL
|
|
2871
|
+
LEFT JOIN project_members pm ON pm.project_id=p.id AND pm.user_id=$1
|
|
2872
|
+
WHERE p.archived_at IS NULL AND (p.created_by=$1 OR pm.user_id=$1)
|
|
2873
|
+
ORDER BY ma.app_name LIMIT 150`,[device.owner_user_id,device.id])).rows;
|
|
2874
|
+
res.type('html').send(devicePortalPage({deviceLabel:device.label,apps:rows.map(a=>({
|
|
2875
|
+
id:a.id,name:a.app_name,scheme:a.enrollment_scheme||null,csrf:devicePortalCsrf(req.headers.cookie,a.id)
|
|
2876
|
+
}))}));
|
|
2877
|
+
});
|
|
2878
|
+
app.post('/ota/device/apps/:appId/link',express.urlencoded({extended:false,limit:'10kb'}),async(req,res)=>{
|
|
2879
|
+
devicePortalHeaders(res);
|
|
2880
|
+
const device=await verifiedOtaBrowser(req.headers.cookie);
|
|
2881
|
+
if(!device){res.status(403).type('html').send(enrollmentPage({state:'denied'}));return;}
|
|
2882
|
+
const appId=ensureUuid(routeParam(req.params.appId),'Mobile app ID');
|
|
2883
|
+
const expected=devicePortalCsrf(req.headers.cookie,appId);
|
|
2884
|
+
const received=String(req.body?.csrf||'');
|
|
2885
|
+
const a=Buffer.from(expected,'hex'),b=Buffer.from(received,'hex');
|
|
2886
|
+
if(a.length!==32||b.length!==32||!timingSafeEqual(a,b)){
|
|
2887
|
+
res.status(403).type('html').send(enrollmentPage({state:'denied'}));return;
|
|
2888
|
+
}
|
|
2889
|
+
const appRow=(await pool.query(`SELECT ma.id,ma.app_name,ma.enrollment_scheme FROM mobile_apps ma
|
|
2890
|
+
JOIN projects p ON p.id=ma.project_id LEFT JOIN project_members pm ON pm.project_id=p.id AND pm.user_id=$2
|
|
2891
|
+
WHERE ma.id=$1 AND p.archived_at IS NULL AND (p.created_by=$2 OR pm.user_id=$2)`,
|
|
2892
|
+
[appId,device.owner_user_id])).rows[0];
|
|
2893
|
+
if(!appRow||!enrollmentSchemePattern.test(String(appRow.enrollment_scheme||''))){
|
|
2894
|
+
res.status(404).type('html').send(enrollmentPage({state:'expired'}));return;
|
|
2895
|
+
}
|
|
2896
|
+
const granted=await pool.query(`SELECT 1 FROM ota_device_app_grants
|
|
2897
|
+
WHERE app_id=$1 AND device_id=$2 AND revoked_at IS NULL`,[appId,device.id]);
|
|
2898
|
+
if(!granted.rowCount){res.status(403).type('html').send(enrollmentPage({state:'denied'}));return;}
|
|
2899
|
+
const token=deviceToken();
|
|
2900
|
+
await pool.query(`INSERT INTO ota_enrollment_invitations(app_id,token_hash,label,app_scheme,created_by,expires_at,registered_device_id,browser_approved_at)
|
|
2901
|
+
VALUES($1,$2,$3,$4,$5,now()+interval '15 minutes',$6,now())`,
|
|
2902
|
+
[appId,hashEnrollmentToken(token),device.label,appRow.enrollment_scheme,device.owner_user_id,device.id]);
|
|
2903
|
+
await audit(device.owner_user_id,'ota.device.app.link','mobile-app',appId,'Verified browser approved app pairing',{deviceId:device.id});
|
|
2904
|
+
res.type('html').send(enrollmentPage({state:'open',app:appRow.app_name,
|
|
2905
|
+
link:`${appRow.enrollment_scheme}://indraq-enroll?token=${token}`}));
|
|
2906
|
+
});
|
|
2907
|
+
|
|
2908
|
+
// One-time verified-browser activation of a persistent Android Tester Agent.
|
|
2909
|
+
// The agent holds an Android Keystore private key; the browser only grants initial consent.
|
|
2910
|
+
app.get('/ota/device/agent/setup',async(req,res)=>{
|
|
2911
|
+
devicePortalHeaders(res);
|
|
2912
|
+
const device=await verifiedOtaBrowser(req.headers.cookie);
|
|
2913
|
+
if(!device){res.status(403).type('text/plain').send('Verify this device in IndraQ Cloud first.');return;}
|
|
2914
|
+
const csrf=devicePortalCsrf(req.headers.cookie,'indraq-agent-setup');
|
|
2915
|
+
res.type('html').send(`<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="font:16px system-ui;max-width:560px;margin:50px auto;padding:16px"><h2>Enable silent testing for this phone</h2><p>The IndraQ Tester Agent will keep a device key on this phone. It lets approved, compatible IndraQ test apps reconnect without a browser after reinstall.</p><p>Only apps signed with the same authorized signing key can contact the agent. You can revoke this device in IndraQ Cloud.</p><form method="POST" action="/ota/device/agent/setup"><input type="hidden" name="csrf" value="${csrf}"><button type="submit" style="padding:12px">Approve Tester Agent</button></form></body></html>`);
|
|
2916
|
+
});
|
|
2917
|
+
app.post('/ota/device/agent/setup',express.urlencoded({extended:false,limit:'10kb'}),async(req,res)=>{
|
|
2918
|
+
devicePortalHeaders(res);
|
|
2919
|
+
const device=await verifiedOtaBrowser(req.headers.cookie);
|
|
2920
|
+
if(!device){res.status(403).type('text/plain').send('Device not verified.');return;}
|
|
2921
|
+
const expected=devicePortalCsrf(req.headers.cookie,'indraq-agent-setup');
|
|
2922
|
+
const a=Buffer.from(expected,'hex'), b=Buffer.from(String(req.body?.csrf||''),'hex');
|
|
2923
|
+
if(a.length!==32||b.length!==32||!timingSafeEqual(a,b)){res.status(403).type('text/plain').send('Invalid request.');return;}
|
|
2924
|
+
const token=deviceToken();
|
|
2925
|
+
await pool.query(`INSERT INTO ota_device_agent_activations(device_id,token_hash,expires_at)
|
|
2926
|
+
VALUES($1,$2,now()+interval '5 minutes')`,[device.id,hashEnrollmentToken(token)]);
|
|
2927
|
+
const link=`indraqtester://activate?token=${token}`;
|
|
2928
|
+
res.type('html').send(`<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="font:16px system-ui;max-width:560px;margin:50px auto;padding:16px"><h2>Open IndraQ Tester Agent</h2><p>Install the matching signed Tester Agent first, then activate it once.</p><a style="display:inline-block;padding:12px" href="${link}">Activate Tester Agent</a><p>Link expires in five minutes.</p></body></html>`);
|
|
2929
|
+
});
|
|
2930
|
+
const agentPayload=(id:string,appId:string,installationId:string,androidPackage:string,nonce:string):string=>
|
|
2931
|
+
['indraq-agent-v1',id,appId,installationId,androidPackage,nonce].join('\n');
|
|
2932
|
+
const agentSignatureValid=(publicKey:string,payload:string,signature:string):boolean=>{
|
|
2933
|
+
try{
|
|
2934
|
+
if(!/^[A-Za-z0-9+/]{100,1024}={0,2}$/.test(signature))return false;
|
|
2935
|
+
const verifier=createVerify('RSA-SHA256');verifier.update(payload,'utf8');verifier.end();
|
|
2936
|
+
return verifier.verify(publicKey,Buffer.from(signature,'base64'));
|
|
2937
|
+
}catch{return false;}
|
|
2938
|
+
};
|
|
2939
|
+
// Activation is authorized by the pre-existing registered device's verified browser.
|
|
2940
|
+
// No device identifier, IP address, user-agent string, or APK-embedded secret grants access.
|
|
2941
|
+
app.post('/ota/v1/agent/activate',async(req,res)=>{
|
|
2942
|
+
res.setHeader('Cache-Control','no-store');
|
|
2943
|
+
const token=String(req.body?.token||'');
|
|
2944
|
+
const key=String(req.body?.publicKey||''); // base64 DER SubjectPublicKeyInfo
|
|
2945
|
+
if(!enrollmentTokenPattern.test(token)||key.length<300||key.length>4096||!/^[A-Za-z0-9+/=]+$/.test(key)){
|
|
2946
|
+
res.status(400).json({error:'Invalid agent activation data.'});return;
|
|
2947
|
+
}
|
|
2948
|
+
let pem='';
|
|
2949
|
+
try{
|
|
2950
|
+
const pub=createPublicKey({key:Buffer.from(key,'base64'),format:'der',type:'spki'});
|
|
2951
|
+
if(pub.asymmetricKeyType!=='rsa'||Number(pub.asymmetricKeyDetails?.modulusLength||0)<2048)throw new Error('RSA key required');
|
|
2952
|
+
pem=pub.export({type:'spki',format:'pem'}).toString();
|
|
2953
|
+
}catch{res.status(400).json({error:'Invalid Android agent public key.'});return;}
|
|
2954
|
+
const client=await pool.connect();
|
|
2955
|
+
try{
|
|
2956
|
+
await client.query('BEGIN');
|
|
2957
|
+
const challenge=(await client.query(`SELECT a.id,a.device_id FROM ota_device_agent_activations a
|
|
2958
|
+
JOIN ota_registered_tester_devices d ON d.id=a.device_id
|
|
2959
|
+
WHERE a.token_hash=$1 AND a.expires_at>now() AND a.redeemed_at IS NULL
|
|
2960
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NOT NULL FOR UPDATE OF a`,[hashEnrollmentToken(token)])).rows[0];
|
|
2961
|
+
if(!challenge){await client.query('ROLLBACK');res.status(410).json({error:'Activation expired or already used.'});return;}
|
|
2962
|
+
await client.query(`UPDATE ota_registered_tester_devices SET agent_public_key=$2,agent_activated_at=now()
|
|
2963
|
+
WHERE id=$1`,[challenge.device_id,pem]);
|
|
2964
|
+
await client.query('UPDATE ota_device_agent_activations SET redeemed_at=now() WHERE id=$1',[challenge.id]);
|
|
2965
|
+
await client.query('COMMIT');
|
|
2966
|
+
res.json({ok:true,deviceId:challenge.device_id});
|
|
2967
|
+
}catch(e){await client.query('ROLLBACK').catch(()=>{});throw e;}finally{client.release();}
|
|
2968
|
+
});
|
|
2969
|
+
app.get('/ota/v1/agent/capabilities/:updatePath',async(req,res)=>{
|
|
2970
|
+
res.setHeader('Cache-Control','no-store');
|
|
2971
|
+
const appRow=await publicMobileApp(routeParam(req.params.updatePath));
|
|
2972
|
+
if(!appRow){res.status(404).json({error:'Unknown app.'});return;}
|
|
2973
|
+
const active=await pool.query(`SELECT count(*)::int count FROM ota_registered_tester_devices d
|
|
2974
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=$1 AND g.revoked_at IS NULL
|
|
2975
|
+
WHERE d.revoked_at IS NULL AND d.verified_at IS NOT NULL AND d.agent_public_key IS NOT NULL`,[appRow.id]);
|
|
2976
|
+
res.json({supported:!!appRow.android_package,appId:appRow.id,activatedDevices:Number(active.rows[0]?.count||0)});
|
|
2977
|
+
});
|
|
2978
|
+
// Challenge is only signed by the separately-installed agent's private key.
|
|
2979
|
+
app.post('/ota/v1/agent/challenge/:updatePath',async(req,res)=>{
|
|
2980
|
+
res.setHeader('Cache-Control','no-store');
|
|
2981
|
+
const appRow=await publicMobileApp(routeParam(req.params.updatePath));
|
|
2982
|
+
if(!appRow){res.status(404).json({error:'Unknown application.'});return;}
|
|
2983
|
+
const installationId=String(req.body?.installationId||'');
|
|
2984
|
+
if(!/^[A-Za-z0-9_-]{12,200}$/.test(installationId)||!appRow.android_package){res.status(400).json({error:'Installation or Android package not configured.'});return;}
|
|
2985
|
+
const installed=await pool.query(`SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2 AND platform='android'`,[appRow.id,installationId]);
|
|
2986
|
+
if(!installed.rowCount){res.status(409).json({error:'Launch the release app online to register installation first.'});return;}
|
|
2987
|
+
const recent=await pool.query(`SELECT count(*)::int count FROM ota_device_agent_challenges WHERE app_id=$1 AND installation_id=$2 AND created_at>now()-interval '1 minute'`,[appRow.id,installationId]);
|
|
2988
|
+
if(Number(recent.rows[0]?.count||0)>=6){res.status(429).json({error:'Too many agent challenges; retry later.'});return;}
|
|
2989
|
+
const nonce=randomBytes(32).toString('base64url');
|
|
2990
|
+
const row=(await pool.query(`INSERT INTO ota_device_agent_challenges(app_id,installation_id,nonce,expires_at)
|
|
2991
|
+
VALUES($1,$2,$3,now()+interval '90 seconds') RETURNING id`,[appRow.id,installationId,nonce])).rows[0];
|
|
2992
|
+
res.json({challengeId:row.id,payload:agentPayload(row.id,appRow.id,installationId,appRow.android_package,nonce)});
|
|
2993
|
+
});
|
|
2994
|
+
app.post('/ota/v1/agent/redeem/:updatePath',async(req,res)=>{
|
|
2995
|
+
res.setHeader('Cache-Control','no-store');
|
|
2996
|
+
const appRow=await publicMobileApp(routeParam(req.params.updatePath));
|
|
2997
|
+
if(!appRow){res.status(404).json({error:'Unknown application.'});return;}
|
|
2998
|
+
const challengeId=String(req.body?.challengeId||'');
|
|
2999
|
+
const deviceId=String(req.body?.deviceId||'');
|
|
3000
|
+
const signature=String(req.body?.signature||'');
|
|
3001
|
+
const installationId=String(req.body?.installationId||'');
|
|
3002
|
+
if(!/^[0-9a-f-]{36}$/i.test(challengeId)||!/^[0-9a-f-]{36}$/i.test(deviceId)||
|
|
3003
|
+
!/^[A-Za-z0-9_-]{12,200}$/.test(installationId)||signature.length>2048){
|
|
3004
|
+
res.status(400).json({error:'Invalid agent enrollment request.'});return;
|
|
3005
|
+
}
|
|
3006
|
+
const client=await pool.connect();
|
|
3007
|
+
try{
|
|
3008
|
+
await client.query('BEGIN');
|
|
3009
|
+
const challenge=(await client.query(`SELECT * FROM ota_device_agent_challenges
|
|
3010
|
+
WHERE id=$1 AND app_id=$2 AND installation_id=$3 AND expires_at>now() AND redeemed_at IS NULL FOR UPDATE`,
|
|
3011
|
+
[challengeId,appRow.id,installationId])).rows[0];
|
|
3012
|
+
if(!challenge){await client.query('ROLLBACK');res.status(410).json({error:'Challenge expired or already used.'});return;}
|
|
3013
|
+
const device=(await client.query(`SELECT d.id,d.label,d.owner_user_id,d.agent_public_key
|
|
3014
|
+
FROM ota_registered_tester_devices d
|
|
3015
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=$2 AND g.revoked_at IS NULL
|
|
3016
|
+
WHERE d.id=$1 AND d.verified_at IS NOT NULL AND d.revoked_at IS NULL FOR UPDATE OF d`,
|
|
3017
|
+
[deviceId,appRow.id])).rows[0];
|
|
3018
|
+
if(!device?.agent_public_key||!agentSignatureValid(device.agent_public_key,
|
|
3019
|
+
agentPayload(challenge.id,appRow.id,installationId,appRow.android_package,challenge.nonce),signature)){
|
|
3020
|
+
await client.query('ROLLBACK');res.status(403).json({error:'Device agent signature invalid, unavailable, or app access revoked.'});return;
|
|
3021
|
+
}
|
|
3022
|
+
const installed=await client.query(`SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2 AND platform='android'`,[appRow.id,installationId]);
|
|
3023
|
+
if(!installed.rowCount){await client.query('ROLLBACK');res.status(409).json({error:'Installation not yet registered.'});return;}
|
|
3024
|
+
await client.query(`INSERT INTO ota_tester_installations(app_id,installation_id,label,enrolled_by,revoked_at)
|
|
3025
|
+
VALUES($1,$2,$3,$4,NULL) ON CONFLICT(app_id,installation_id) DO UPDATE
|
|
3026
|
+
SET label=excluded.label,enrolled_by=excluded.enrolled_by,enrolled_at=now(),revoked_at=NULL`,
|
|
3027
|
+
[appRow.id,installationId,device.label,device.owner_user_id]);
|
|
3028
|
+
await client.query(`INSERT INTO ota_registered_device_installations(device_id,app_id,installation_id)
|
|
3029
|
+
VALUES($1,$2,$3) ON CONFLICT(app_id,installation_id) DO UPDATE SET device_id=excluded.device_id,linked_at=now()`,
|
|
3030
|
+
[device.id,appRow.id,installationId]);
|
|
3031
|
+
await client.query('UPDATE ota_device_agent_challenges SET redeemed_at=now() WHERE id=$1',[challengeId]);
|
|
3032
|
+
await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,metadata)
|
|
3033
|
+
VALUES($1,$2,'device_enrolled',$3)`,[appRow.id,installationId,{source:'android_tester_agent'}]);
|
|
3034
|
+
await client.query('COMMIT');
|
|
3035
|
+
res.json({ok:true,enrolled:true,deviceLabel:device.label});
|
|
3036
|
+
}catch(e){await client.query('ROLLBACK').catch(()=>{});throw e;}finally{client.release();}
|
|
3037
|
+
});
|
|
2533
3038
|
|
|
2534
3039
|
app.get('/mobile/apps', auth, async (req: AuthedRequest,res) => {
|
|
2535
3040
|
// All project members, including normal users with VIEW, may select their own app.
|
|
@@ -2541,6 +3046,70 @@ app.get('/mobile/apps', auth, async (req: AuthedRequest,res) => {
|
|
|
2541
3046
|
res.json(rows.map(row=>({id:row.id,projectId:row.project_id,appName:row.app_name,projectName:row.project_name,projectType:row.project_type,enrollmentScheme:row.enrollment_scheme||null})));
|
|
2542
3047
|
});
|
|
2543
3048
|
|
|
3049
|
+
// Assign already-registered phones during a build, or later without re-enrolling a phone.
|
|
3050
|
+
// This grants app ACCESS only. A new sandbox must still prove possession to bind its installation.
|
|
3051
|
+
app.get('/mobile/apps/:appId/device-grants',auth,async(req:AuthedRequest,res)=>{
|
|
3052
|
+
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!);
|
|
3053
|
+
if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
|
|
3054
|
+
const rows=(await pool.query(`SELECT d.id device_id,d.label,d.verified_at,g.granted_at,
|
|
3055
|
+
(SELECT count(*)::int FROM ota_registered_device_installations li
|
|
3056
|
+
WHERE li.device_id=d.id AND li.app_id=$1) linked_installations,
|
|
3057
|
+
ARRAY(SELECT DISTINCT i.runtime_version FROM ota_registered_device_installations li
|
|
3058
|
+
JOIN ota_installations i ON i.app_id=li.app_id AND i.installation_id=li.installation_id
|
|
3059
|
+
WHERE li.device_id=d.id AND li.app_id=$1 AND i.runtime_version IS NOT NULL
|
|
3060
|
+
ORDER BY i.runtime_version) linked_runtimes
|
|
3061
|
+
FROM ota_device_app_grants g JOIN ota_registered_tester_devices d ON d.id=g.device_id
|
|
3062
|
+
WHERE g.app_id=$1 AND g.revoked_at IS NULL AND d.revoked_at IS NULL AND d.verified_at IS NOT NULL ORDER BY d.label`,[appRow.id])).rows;
|
|
3063
|
+
res.json(rows);
|
|
3064
|
+
});
|
|
3065
|
+
app.post('/mobile/apps/:appId/device-grants',auth,async(req:AuthedRequest,res)=>{
|
|
3066
|
+
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!,true);
|
|
3067
|
+
if(!appRow){res.status(404).json({error:'Mobile app not found or WRITE access denied.'});return;}
|
|
3068
|
+
const deviceIds=requestedDeviceIds(req.body?.deviceIds);
|
|
3069
|
+
const client=await pool.connect();
|
|
3070
|
+
try{
|
|
3071
|
+
await client.query('BEGIN');
|
|
3072
|
+
// Lock verified device rows until grants are committed, so revocation
|
|
3073
|
+
// cannot race a grant and re-enable a revoked phone's existing installs.
|
|
3074
|
+
const verified=await client.query(`SELECT id FROM ota_registered_tester_devices
|
|
3075
|
+
WHERE owner_user_id=$1 AND verified_at IS NOT NULL AND revoked_at IS NULL AND id=ANY($2::uuid[]) FOR UPDATE`,[req.auth!.id,deviceIds]);
|
|
3076
|
+
if(verified.rowCount!==deviceIds.length){
|
|
3077
|
+
await client.query('ROLLBACK');
|
|
3078
|
+
res.status(403).json({error:'All selected phones must be QR-verified, active and owned by your account.'});return;
|
|
3079
|
+
}
|
|
3080
|
+
for(const deviceId of deviceIds){
|
|
3081
|
+
await client.query(`INSERT INTO ota_device_app_grants(device_id,app_id,granted_by)
|
|
3082
|
+
VALUES($1,$2,$3) ON CONFLICT(device_id,app_id) DO UPDATE
|
|
3083
|
+
SET revoked_at=NULL,granted_at=now(),granted_by=EXCLUDED.granted_by`,[deviceId,appRow.id,req.auth!.id]);
|
|
3084
|
+
// Restore pre-existing, securely linked installations; never attach unknown installations.
|
|
3085
|
+
await client.query(`UPDATE ota_tester_installations t SET revoked_at=NULL,enrolled_at=now()
|
|
3086
|
+
FROM ota_registered_device_installations l
|
|
3087
|
+
WHERE l.device_id=$1 AND l.app_id=$2 AND t.app_id=l.app_id AND t.installation_id=l.installation_id`,[deviceId,appRow.id]);
|
|
3088
|
+
}
|
|
3089
|
+
await client.query('COMMIT');
|
|
3090
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}finally{client.release();}
|
|
3091
|
+
await audit(req.auth!.id,'ota.device.app.grant','mobile-app',appRow.id,'Grant selected verified phones access to app',{deviceIds});
|
|
3092
|
+
res.json({ok:true,appId:appRow.id,grantedDeviceIds:deviceIds,note:'Existing linked installs are enabled. New app installs still need secure one-time pairing.'});
|
|
3093
|
+
});
|
|
3094
|
+
app.delete('/mobile/apps/:appId/device-grants/:deviceId',auth,async(req:AuthedRequest,res)=>{
|
|
3095
|
+
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!,true);
|
|
3096
|
+
if(!appRow){res.status(404).json({error:'Mobile app not found or WRITE access denied.'});return;}
|
|
3097
|
+
const deviceId=ensureUuid(routeParam(req.params.deviceId),'Registered device ID');
|
|
3098
|
+
const client=await pool.connect();
|
|
3099
|
+
try{
|
|
3100
|
+
await client.query('BEGIN');
|
|
3101
|
+
const existing=await client.query(`UPDATE ota_device_app_grants g SET revoked_at=now()
|
|
3102
|
+
FROM ota_registered_tester_devices d WHERE g.device_id=$1 AND g.app_id=$2
|
|
3103
|
+
AND g.device_id=d.id AND d.owner_user_id=$3 AND g.revoked_at IS NULL RETURNING g.device_id`,[deviceId,appRow.id,req.auth!.id]);
|
|
3104
|
+
if(!existing.rowCount){await client.query('ROLLBACK');res.status(404).json({error:'Active device access grant not found.'});return;}
|
|
3105
|
+
await client.query(`UPDATE ota_tester_installations t SET revoked_at=now()
|
|
3106
|
+
FROM ota_registered_device_installations l WHERE l.device_id=$1 AND l.app_id=$2
|
|
3107
|
+
AND t.app_id=l.app_id AND t.installation_id=l.installation_id AND t.revoked_at IS NULL`,[deviceId,appRow.id]);
|
|
3108
|
+
await client.query('COMMIT');
|
|
3109
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}finally{client.release();}
|
|
3110
|
+
await audit(req.auth!.id,'ota.device.app.revoke','mobile-app',appRow.id,'Revoke tester-device app authorization',{deviceId});
|
|
3111
|
+
res.status(204).end();
|
|
3112
|
+
});
|
|
2544
3113
|
app.get('/mobile/apps/:appId/installations', auth, async (req: AuthedRequest,res) => {
|
|
2545
3114
|
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!);
|
|
2546
3115
|
if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
|
|
@@ -2590,12 +3159,19 @@ app.post('/mobile/apps/:appId/enrollments', auth, async (req: AuthedRequest,res)
|
|
|
2590
3159
|
const ttlMinutes=Number(req.body?.ttlMinutes||15);
|
|
2591
3160
|
if(!Number.isInteger(ttlMinutes)||ttlMinutes<5||ttlMinutes>60){res.status(400).json({error:'Invitation TTL must be between 5 and 60 minutes.'});return;}
|
|
2592
3161
|
const groupId=req.body?.groupId?ensureUuid(String(req.body.groupId),'Tester group ID'):null;
|
|
3162
|
+
const registeredDeviceId=req.body?.registeredDeviceId?ensureUuid(String(req.body.registeredDeviceId),'Registered device ID'):null;
|
|
3163
|
+
if(registeredDeviceId){
|
|
3164
|
+
const owned=await pool.query('SELECT 1 FROM ota_registered_tester_devices WHERE id=$1 AND owner_user_id=$2 AND revoked_at IS NULL AND verified_at IS NOT NULL',[registeredDeviceId,req.auth!.id]);
|
|
3165
|
+
if(!owned.rowCount){res.status(403).json({error:'Registered device must be owned, QR-verified and not revoked.'});return;}
|
|
3166
|
+
const permitted=await pool.query(`SELECT 1 FROM ota_device_app_grants WHERE device_id=$1 AND app_id=$2 AND revoked_at IS NULL`,[registeredDeviceId,appRow.id]);
|
|
3167
|
+
if(!permitted.rowCount){res.status(403).json({error:'Grant this device access to the app before creating a pairing invitation.'});return;}
|
|
3168
|
+
}
|
|
2593
3169
|
if(groupId){const exists=await pool.query('SELECT 1 FROM ota_tester_groups WHERE id=$1 AND app_id=$2',[groupId,appRow.id]);if(!exists.rowCount){res.status(404).json({error:'Tester group not found in this app.'});return;}}
|
|
2594
3170
|
const token=randomBytes(32).toString('base64url');
|
|
2595
|
-
const row=(await pool.query(`INSERT INTO ota_enrollment_invitations(app_id,token_hash,label,group_id,app_scheme,created_by,expires_at)
|
|
2596
|
-
VALUES($1,$2,$3,$4,$5,$6,now()+($7::integer * interval '1 minute')) RETURNING id,expires_at`,
|
|
2597
|
-
[appRow.id,hashEnrollmentToken(token),label,groupId,scheme,req.auth!.id,ttlMinutes])).rows[0];
|
|
2598
|
-
await audit(req.auth!.id,'ota.testers.invite.create','mobile-app',appRow.id,'Create one-time device enrollment QR',{inviteId:row.id,label,groupId,ttlMinutes});
|
|
3171
|
+
const row=(await pool.query(`INSERT INTO ota_enrollment_invitations(app_id,token_hash,label,group_id,app_scheme,created_by,expires_at,registered_device_id)
|
|
3172
|
+
VALUES($1,$2,$3,$4,$5,$6,now()+($7::integer * interval '1 minute'),$8) RETURNING id,expires_at`,
|
|
3173
|
+
[appRow.id,hashEnrollmentToken(token),label,groupId,scheme,req.auth!.id,ttlMinutes,registeredDeviceId])).rows[0];
|
|
3174
|
+
await audit(req.auth!.id,'ota.testers.invite.create','mobile-app',appRow.id,'Create one-time device enrollment QR',{inviteId:row.id,label,groupId,ttlMinutes,registeredDeviceId});
|
|
2599
3175
|
res.setHeader('Cache-Control','no-store');
|
|
2600
3176
|
res.status(201).json({id:row.id,appName:appRow.app_name,label,groupId,expiresAt:row.expires_at,
|
|
2601
3177
|
enrollmentUrl:`${publicApiUrl}/ota/enroll/${token}`});
|
|
@@ -2604,7 +3180,7 @@ app.post('/mobile/apps/:appId/enrollments', auth, async (req: AuthedRequest,res)
|
|
|
2604
3180
|
app.get('/mobile/apps/:appId/enrollments', auth, async (req: AuthedRequest,res) => {
|
|
2605
3181
|
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!);
|
|
2606
3182
|
if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
|
|
2607
|
-
const rows=(await pool.query(`SELECT id,label,group_id,created_at,expires_at,redeemed_at,redeemed_installation_id,revoked_at
|
|
3183
|
+
const rows=(await pool.query(`SELECT id,label,group_id,registered_device_id,created_at,expires_at,redeemed_at,redeemed_installation_id,revoked_at
|
|
2608
3184
|
FROM ota_enrollment_invitations WHERE app_id=$1 ORDER BY created_at DESC LIMIT 100`,[appRow.id])).rows;
|
|
2609
3185
|
res.json(rows);
|
|
2610
3186
|
});
|
|
@@ -2632,19 +3208,48 @@ app.delete('/mobile/apps/:appId/testers/:installationId', auth, async (req: Auth
|
|
|
2632
3208
|
res.status(204).end();
|
|
2633
3209
|
});
|
|
2634
3210
|
|
|
2635
|
-
|
|
2636
|
-
|
|
3211
|
+
const escapeOtaHtml=(v:unknown):string=>String(v).replace(/[&<>"']/g,(c)=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]||c));
|
|
3212
|
+
const enrollmentLanding=async(token:string,cookieHeader:string|undefined):Promise<{item:any;authorized:boolean}|null>=>{
|
|
3213
|
+
const item=(await pool.query(`SELECT e.app_scheme,ma.app_name,e.label,e.registered_device_id,e.browser_approved_at,
|
|
3214
|
+
d.id device_id,d.verified_at,d.revoked_at,d.browser_credential_hash
|
|
3215
|
+
FROM ota_enrollment_invitations e JOIN mobile_apps ma ON ma.id=e.app_id
|
|
3216
|
+
LEFT JOIN ota_registered_tester_devices d ON d.id=e.registered_device_id
|
|
3217
|
+
WHERE e.token_hash=$1 AND e.expires_at>now() AND e.revoked_at IS NULL AND e.redeemed_at IS NULL`,
|
|
3218
|
+
[hashEnrollmentToken(token)])).rows[0];
|
|
3219
|
+
if(!item)return null;
|
|
3220
|
+
const authorized=!item.registered_device_id||
|
|
3221
|
+
(item.device_id&&verifiedBrowserMatches(cookieHeader,{id:item.device_id,verified_at:item.verified_at,
|
|
3222
|
+
revoked_at:item.revoked_at,browser_credential_hash:item.browser_credential_hash}));
|
|
3223
|
+
return {item,authorized:Boolean(authorized)};
|
|
3224
|
+
};
|
|
3225
|
+
const publicEnrollmentHeaders=(res:Response):void=>{
|
|
2637
3226
|
res.setHeader('Cache-Control','no-store');res.setHeader('Referrer-Policy','no-referrer');
|
|
2638
|
-
res.setHeader('Content-Security-Policy',"default-src 'none'; style-src 'unsafe-inline';
|
|
3227
|
+
res.setHeader('Content-Security-Policy',"default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; base-uri 'none'");
|
|
3228
|
+
};
|
|
3229
|
+
app.get('/ota/enroll/:token', async (req,res) => {
|
|
3230
|
+
const token=routeParam(req.params.token);publicEnrollmentHeaders(res);
|
|
2639
3231
|
if(!enrollmentTokenPattern.test(token)){res.status(404).type('text/plain').send('Invalid enrollment invitation.');return;}
|
|
2640
|
-
const
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
if(!
|
|
2644
|
-
|
|
3232
|
+
const found=await enrollmentLanding(token,req.headers.cookie);
|
|
3233
|
+
if(!found){res.status(410).type('text/plain').send('This invitation is expired or already used. Request a fresh QR code.');return;}
|
|
3234
|
+
const item=found.item;
|
|
3235
|
+
if(!found.authorized){res.status(403).type('html').send(enrollmentPage({state:'denied',app:item.app_name}));return;}
|
|
3236
|
+
if(item.registered_device_id&&!item.browser_approved_at){
|
|
3237
|
+
res.type('html').send(enrollmentPage({state:'pair',app:item.app_name,action:`/ota/enroll/${token}/approve`}));return;
|
|
3238
|
+
}
|
|
2645
3239
|
const deepLink=`${item.app_scheme}://indraq-enroll?token=${token}`;
|
|
2646
|
-
|
|
2647
|
-
|
|
3240
|
+
res.type('html').send(enrollmentPage({state:'open',app:item.app_name,link:deepLink}));
|
|
3241
|
+
});
|
|
3242
|
+
app.post('/ota/enroll/:token/approve', async (req,res) => {
|
|
3243
|
+
const token=routeParam(req.params.token);publicEnrollmentHeaders(res);
|
|
3244
|
+
if(!enrollmentTokenPattern.test(token)){res.status(404).type('text/plain').send('Invalid invitation.');return;}
|
|
3245
|
+
const found=await enrollmentLanding(token,req.headers.cookie);
|
|
3246
|
+
if(!found){res.status(410).type('text/plain').send('Invitation expired or already used.');return;}
|
|
3247
|
+
if(!found.item.registered_device_id||!found.authorized){res.status(403).type('text/plain').send('Open this invitation in the verified device browser.');return;}
|
|
3248
|
+
const updated=await pool.query(`UPDATE ota_enrollment_invitations SET browser_approved_at=now()
|
|
3249
|
+
WHERE token_hash=$1 AND expires_at>now() AND revoked_at IS NULL AND redeemed_at IS NULL
|
|
3250
|
+
AND registered_device_id=$2 RETURNING id`,[hashEnrollmentToken(token),found.item.registered_device_id]);
|
|
3251
|
+
if(!updated.rowCount){res.status(410).type('text/plain').send('Invitation expired or unavailable.');return;}
|
|
3252
|
+
res.redirect(303,`/ota/enroll/${token}`);
|
|
2648
3253
|
});
|
|
2649
3254
|
|
|
2650
3255
|
app.post('/ota/v1/enroll/redeem', async (req,res) => {
|
|
@@ -2653,6 +3258,10 @@ app.post('/ota/v1/enroll/redeem', async (req,res) => {
|
|
|
2653
3258
|
if(!enrollmentTokenPattern.test(token)||!/^[A-Za-z0-9_-]{12,200}$/.test(installationId)){
|
|
2654
3259
|
res.status(400).json({error:'Invalid invitation or installation ID.'});return;
|
|
2655
3260
|
}
|
|
3261
|
+
// Bind the scoped identifier ONLY after a real verified-browser invitation
|
|
3262
|
+
// has been redeemed. A standalone, unapproved API claim cannot bind it.
|
|
3263
|
+
const scopedId=String(req.body?.androidScopedId||'').toLowerCase();
|
|
3264
|
+
const scopedProvided=!!scopedId && androidScopedIdPattern.test(scopedId) && req.body?.platform==='android';
|
|
2656
3265
|
const digest=hashEnrollmentToken(token);
|
|
2657
3266
|
const client=await pool.connect();
|
|
2658
3267
|
try {
|
|
@@ -2660,6 +3269,7 @@ app.post('/ota/v1/enroll/redeem', async (req,res) => {
|
|
|
2660
3269
|
const invite=(await client.query(`SELECT e.*,ma.app_name FROM ota_enrollment_invitations e
|
|
2661
3270
|
JOIN mobile_apps ma ON ma.id=e.app_id WHERE e.token_hash=$1 AND e.expires_at>now() AND e.revoked_at IS NULL AND e.redeemed_at IS NULL FOR UPDATE OF e`,[digest])).rows[0];
|
|
2662
3271
|
if(!invite){await client.query('ROLLBACK');res.status(410).json({error:'Invitation expired or already redeemed.'});return;}
|
|
3272
|
+
if(!registeredInviteCanRedeem(invite)){await client.query('ROLLBACK');res.status(403).json({error:'The verified phone browser must approve this app pairing before redeeming the QR.'});return;}
|
|
2663
3273
|
const installed=await client.query('SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2',[invite.app_id,installationId]);
|
|
2664
3274
|
if(!installed.rowCount){await client.query('ROLLBACK');res.status(409).json({error:'This installation has not registered with the app OTA service. Open the release app online before enrolling.'});return;}
|
|
2665
3275
|
await client.query(`INSERT INTO ota_tester_installations(app_id,installation_id,label,enrolled_by,revoked_at)
|
|
@@ -2667,6 +3277,26 @@ app.post('/ota/v1/enroll/redeem', async (req,res) => {
|
|
|
2667
3277
|
[invite.app_id,installationId,invite.label,invite.created_by]);
|
|
2668
3278
|
if(invite.group_id){await client.query(`INSERT INTO ota_tester_group_members(app_id,group_id,installation_id,added_by)
|
|
2669
3279
|
VALUES($1,$2,$3,$4) ON CONFLICT(group_id,installation_id) DO NOTHING`,[invite.app_id,invite.group_id,installationId,invite.created_by]);}
|
|
3280
|
+
if(invite.registered_device_id){
|
|
3281
|
+
const active=(await client.query(`SELECT 1 FROM ota_registered_tester_devices
|
|
3282
|
+
WHERE id=$1 AND owner_user_id=$2 AND revoked_at IS NULL AND verified_at IS NOT NULL FOR UPDATE`,[invite.registered_device_id,invite.created_by])).rowCount;
|
|
3283
|
+
if(!active){await client.query('ROLLBACK');res.status(409).json({error:'The selected registered tester device was revoked.'});return;}
|
|
3284
|
+
const grant=await client.query(`SELECT 1 FROM ota_device_app_grants WHERE device_id=$1 AND app_id=$2 AND revoked_at IS NULL`,[invite.registered_device_id,invite.app_id]);
|
|
3285
|
+
if(!grant.rowCount){await client.query('ROLLBACK');res.status(403).json({error:'Tester device no longer has access to this app.'});return;}
|
|
3286
|
+
if(scopedProvided && androidScopedTesterRestoreEnabled){
|
|
3287
|
+
const digestId=scopedIdDigest(scopedId);
|
|
3288
|
+
const collision=await client.query(`SELECT device_id FROM ota_android_scoped_tester_identities
|
|
3289
|
+
WHERE identity_digest=$1`,[digestId]);
|
|
3290
|
+
if(collision.rowCount && collision.rows[0].device_id!==invite.registered_device_id){
|
|
3291
|
+
await client.query('ROLLBACK');res.status(409).json({error:'Android device identity already bound to a different tester.'});return;
|
|
3292
|
+
}
|
|
3293
|
+
await client.query(`INSERT INTO ota_android_scoped_tester_identities(device_id,identity_digest)
|
|
3294
|
+
VALUES($1,$2) ON CONFLICT(device_id,identity_digest) DO NOTHING`,[invite.registered_device_id,digestId]);
|
|
3295
|
+
}
|
|
3296
|
+
await client.query(`INSERT INTO ota_registered_device_installations(device_id,app_id,installation_id)
|
|
3297
|
+
VALUES($1,$2,$3) ON CONFLICT(app_id,installation_id) DO UPDATE SET device_id=excluded.device_id,linked_at=now()`,
|
|
3298
|
+
[invite.registered_device_id,invite.app_id,installationId]);
|
|
3299
|
+
}
|
|
2670
3300
|
await client.query('UPDATE ota_enrollment_invitations SET redeemed_at=now(),redeemed_installation_id=$2 WHERE id=$1',[invite.id,installationId]);
|
|
2671
3301
|
await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,metadata)
|
|
2672
3302
|
VALUES($1,$2,'device_enrolled',$3)`,[invite.app_id,installationId,{inviteId:invite.id,groupId:invite.group_id}]);
|
|
@@ -2843,7 +3473,7 @@ app.get('/mobile/apps/:appId/native-builds', auth, async (req: AuthedRequest,res
|
|
|
2843
3473
|
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!);
|
|
2844
3474
|
if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
|
|
2845
3475
|
const rows=(await pool.query(`SELECT b.id,b.mobile_environment_id environment_id,me.name environment_name,
|
|
2846
|
-
me.slug environment_slug,me.ota_channel,b.runtime_version,b.native_fingerprint,b.app_version,
|
|
3476
|
+
me.slug environment_slug,me.ota_channel,b.runtime_version,b.native_fingerprint,b.app_version,b.platform,
|
|
2847
3477
|
b.version_code,b.build_number,b.build_url,b.source_sha256,b.built_at
|
|
2848
3478
|
FROM mobile_native_builds b JOIN mobile_environments me ON me.id=b.mobile_environment_id
|
|
2849
3479
|
WHERE b.app_id=$1 ORDER BY b.built_at DESC LIMIT 200`,[appRow.id])).rows;
|
|
@@ -2853,10 +3483,13 @@ app.get('/mobile/apps/:appId/native-builds', auth, async (req: AuthedRequest,res
|
|
|
2853
3483
|
app.get('/mobile/apps/:appId/releases', auth, async (req: AuthedRequest,res) => {
|
|
2854
3484
|
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!); if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
|
|
2855
3485
|
const rows=(await pool.query(
|
|
2856
|
-
`SELECT r.id,r.runtime_version,r.message,r.status,r.audience_type,r.audience,r.rollout_percent,r.promoted_at,r.created_at,me.name environment_name,me.slug environment_slug,
|
|
3486
|
+
`SELECT r.id,r.runtime_version,r.message,r.status,r.audience_type,r.audience,r.rollout_percent,r.promoted_at,r.created_at,r.recovery_kind,r.recovery_of,r.recovery_target_id,r.deployment_group_id,r.is_pinned,r.verified_at,me.name environment_name,me.slug environment_slug,
|
|
3487
|
+
original.message recovery_source_message,
|
|
2857
3488
|
json_agg(json_build_object('id',u.id,'platform',u.platform) ORDER BY u.platform) FILTER (WHERE u.id IS NOT NULL) updates
|
|
2858
|
-
FROM ota_releases r JOIN mobile_environments me ON me.id=r.mobile_environment_id
|
|
2859
|
-
|
|
3489
|
+
FROM ota_releases r JOIN mobile_environments me ON me.id=r.mobile_environment_id
|
|
3490
|
+
LEFT JOIN ota_releases original ON original.id=r.recovery_target_id
|
|
3491
|
+
LEFT JOIN ota_updates u ON u.release_id=r.id
|
|
3492
|
+
WHERE r.app_id=$1 GROUP BY r.id,me.name,me.slug,original.message ORDER BY r.created_at DESC LIMIT 100`,[appRow.id]
|
|
2860
3493
|
)).rows;
|
|
2861
3494
|
res.json(rows);
|
|
2862
3495
|
});
|
|
@@ -2894,10 +3527,29 @@ app.post('/mobile/apps/:appId/releases', auth, async (req: AuthedRequest,res) =>
|
|
|
2894
3527
|
const found=await pool.query('SELECT 1 FROM ota_tester_groups WHERE id=$1 AND app_id=$2',[groupId,appRow.id]);
|
|
2895
3528
|
if(!found.rowCount){res.status(400).json({error:'Target tester group does not belong to this mobile app.'});return;}
|
|
2896
3529
|
}
|
|
3530
|
+
const deviceIds=Array.isArray(req.body?.audience?.deviceIds)?req.body.audience.deviceIds:[];
|
|
3531
|
+
if(deviceIds.length>100 || (req.body?.audience?.deviceIds!==undefined && !deviceIds.length)){
|
|
3532
|
+
res.status(400).json({error:'Select 1–100 approved tester devices.'});return;
|
|
3533
|
+
}
|
|
3534
|
+
if(deviceIds.length){
|
|
3535
|
+
const validIds=deviceIds.map((v:unknown)=>ensureUuid(String(v),'Tester device ID'));
|
|
3536
|
+
if(new Set(validIds).size!==validIds.length){res.status(400).json({error:'Duplicate tester device ID.'});return;}
|
|
3537
|
+
const approved=await pool.query(`SELECT count(*)::int count FROM ota_device_app_grants g
|
|
3538
|
+
JOIN ota_registered_tester_devices d ON d.id=g.device_id
|
|
3539
|
+
WHERE g.app_id=$1 AND g.device_id=ANY($2::uuid[]) AND g.revoked_at IS NULL
|
|
3540
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NOT NULL`,[appRow.id,validIds]);
|
|
3541
|
+
if(Number(approved.rows[0]?.count)!==validIds.length){
|
|
3542
|
+
res.status(403).json({error:'One or more tester devices are not verified or no longer granted access to this app.'});return;
|
|
3543
|
+
}
|
|
3544
|
+
}
|
|
2897
3545
|
}
|
|
2898
3546
|
const platformValues=Array.isArray(req.body?.platforms)?[...new Set<string>(req.body.platforms.map((v:unknown)=>String(v).toLowerCase()))]:[];
|
|
2899
3547
|
if(!platformValues.length||platformValues.some((v:string)=>!['android','ios'].includes(v))){res.status(400).json({error:'platforms must contain android and/or ios.'});return;}
|
|
2900
3548
|
const platforms=platformValues as Array<'android'|'ios'>;
|
|
3549
|
+
if(platforms.some(p=>p!==String(baseline.platform||'android'))){
|
|
3550
|
+
res.status(409).json({error:`No independently verified ${platforms.filter(p=>p!==String(baseline.platform||'android')).join('/')} native binary exists for this selected build. Never publish a JS-only update to a platform without its own native build.`});return;
|
|
3551
|
+
}
|
|
3552
|
+
|
|
2901
3553
|
let rollout:number|null=null;
|
|
2902
3554
|
if(audienceType==='percentage'){
|
|
2903
3555
|
const candidate=Number(req.body?.rolloutPercent);
|
|
@@ -2905,6 +3557,7 @@ app.post('/mobile/apps/:appId/releases', auth, async (req: AuthedRequest,res) =>
|
|
|
2905
3557
|
rollout=candidate;
|
|
2906
3558
|
}
|
|
2907
3559
|
const clientRequestId=ensureUuid(String(req.body?.clientRequestId||''),'OTA publish request ID');
|
|
3560
|
+
const deploymentGroupId=req.body?.deploymentGroupId?ensureUuid(String(req.body.deploymentGroupId),'OTA deployment group ID'):null;
|
|
2908
3561
|
const existingRelease=(await pool.query(`SELECT r.*,json_agg(json_build_object('id',u.id,'platform',u.platform)) updates
|
|
2909
3562
|
FROM ota_releases r LEFT JOIN ota_updates u ON u.release_id=r.id
|
|
2910
3563
|
WHERE r.app_id=$1 AND r.client_request_id=$2 GROUP BY r.id`,[appRow.id,clientRequestId])).rows[0];
|
|
@@ -2918,9 +3571,9 @@ app.post('/mobile/apps/:appId/releases', auth, async (req: AuthedRequest,res) =>
|
|
|
2918
3571
|
try{
|
|
2919
3572
|
await client.query('BEGIN');
|
|
2920
3573
|
const release=(await client.query(
|
|
2921
|
-
`INSERT INTO ota_releases(app_id,mobile_environment_id,runtime_version,message,status,audience_type,audience,rollout_percent,promoted_at,created_by,client_request_id)
|
|
2922
|
-
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING *`,
|
|
2923
|
-
[appRow.id,environmentId,runtimeVersion,message,status,audienceType,req.body?.audience||{},rollout,null,req.auth!.id,clientRequestId]
|
|
3574
|
+
`INSERT INTO ota_releases(app_id,mobile_environment_id,runtime_version,message,status,audience_type,audience,rollout_percent,promoted_at,created_by,client_request_id,deployment_group_id)
|
|
3575
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) RETURNING *`,
|
|
3576
|
+
[appRow.id,environmentId,runtimeVersion,message,status,audienceType,req.body?.audience||{},rollout,null,req.auth!.id,clientRequestId,deploymentGroupId]
|
|
2924
3577
|
)).rows[0];
|
|
2925
3578
|
const updates:any[]=[];
|
|
2926
3579
|
for(const platform of platforms){updates.push((await client.query('INSERT INTO ota_updates(release_id,platform) VALUES($1,$2) RETURNING id,platform,created_at',[release.id,platform])).rows[0]);}
|
|
@@ -2932,26 +3585,35 @@ app.post('/mobile/apps/:appId/releases', auth, async (req: AuthedRequest,res) =>
|
|
|
2932
3585
|
|
|
2933
3586
|
app.put('/mobile/releases/:releaseId/assets/:sha256', express.raw({type:'*/*',limit:'100mb'}), auth, async (req: AuthedRequest,res) => {
|
|
2934
3587
|
const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
|
|
3588
|
+
if(!mayFinalize(release.status)){res.status(409).json({error:'Assets can only be uploaded to a draft release.'});return;}
|
|
2935
3589
|
const sha=String(routeParam(req.params.sha256)).toLowerCase();
|
|
2936
3590
|
if(!/^[a-f0-9]{64}$/.test(sha)){res.status(400).json({error:'Asset SHA-256 must be 64 hex characters.'});return;}
|
|
2937
3591
|
const body=Buffer.isBuffer(req.body)?req.body:Buffer.from(req.body||'');
|
|
2938
3592
|
if(!body.length){res.status(400).json({error:'Asset body is empty.'});return;}
|
|
2939
3593
|
if(hexSha256(body)!==sha){res.status(400).json({error:'Asset SHA-256 does not match request path.'});return;}
|
|
2940
|
-
await
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
3594
|
+
const client=await pool.connect();
|
|
3595
|
+
try{
|
|
3596
|
+
await client.query('BEGIN');
|
|
3597
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))',[sha]);
|
|
3598
|
+
await ensureOtaBucket();
|
|
3599
|
+
const objectKey=`assets/${sha}`;
|
|
3600
|
+
const minio=getMinio();
|
|
3601
|
+
try{await minio.statObject(minioBucket,objectKey);}
|
|
3602
|
+
catch{await minio.putObject(minioBucket,objectKey,body,body.length,{'Content-Type':String(req.headers['x-indraq-content-type']||req.headers['content-type']||'application/octet-stream')});}
|
|
3603
|
+
const extension=String(req.headers['x-indraq-file-extension']||'').trim()||null;
|
|
3604
|
+
const result=await client.query(
|
|
3605
|
+
`INSERT INTO ota_assets(sha256,object_key,content_type,file_extension,size_bytes) VALUES($1,$2,$3,$4,$5)
|
|
3606
|
+
ON CONFLICT(sha256) DO UPDATE SET content_type=excluded.content_type,file_extension=COALESCE(ota_assets.file_extension,excluded.file_extension),created_at=now()
|
|
3607
|
+
RETURNING id,sha256,size_bytes`,[sha,objectKey,String(req.headers['x-indraq-content-type']||req.headers['content-type']||'application/octet-stream'),extension,body.length]
|
|
3608
|
+
);
|
|
3609
|
+
await client.query('COMMIT');res.json(result.rows[0]);
|
|
3610
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}
|
|
3611
|
+
finally{client.release();}
|
|
2951
3612
|
});
|
|
2952
3613
|
|
|
2953
3614
|
app.post('/mobile/releases/:releaseId/finalize', auth, async (req: AuthedRequest,res) => {
|
|
2954
3615
|
const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
|
|
3616
|
+
if(!mayFinalize(release.status)){res.status(409).json({error:'Only draft OTA releases may be finalized. Published updates are immutable.'});return;}
|
|
2955
3617
|
const platforms=Array.isArray(req.body?.platforms)?req.body.platforms:[];
|
|
2956
3618
|
if(!platforms.length){res.status(400).json({error:'Platform manifests are required.'});return;}
|
|
2957
3619
|
const client=await pool.connect();
|
|
@@ -2966,6 +3628,11 @@ app.post('/mobile/releases/:releaseId/finalize', auth, async (req: AuthedRequest
|
|
|
2966
3628
|
if(!launch?.sha256||!launch?.key) throw Object.assign(new Error(`${platform} launch asset is incomplete.`),{statusCode:400});
|
|
2967
3629
|
const all=[{...launch,role:'launch',sortOrder:0},...assets.map((a:any,i:number)=>({...a,role:'asset',sortOrder:i+1}))];
|
|
2968
3630
|
const manifestAssets:any[]=[]; let launchAsset:any=null;
|
|
3631
|
+
// Acquire asset locks in a deterministic SHA order before referencing
|
|
3632
|
+
// uploaded objects. This excludes a concurrent orphan cleanup job from
|
|
3633
|
+
// removing a stale upload while a delayed draft is being finalized.
|
|
3634
|
+
const publishShas=[...new Set(all.map((item:any)=>String(item.sha256).toLowerCase()))].sort();
|
|
3635
|
+
for(const sha of publishShas)await client.query('SELECT pg_advisory_xact_lock(hashtext($1))',[sha]);
|
|
2969
3636
|
await client.query('DELETE FROM ota_update_assets WHERE update_id=$1',[update.id]);
|
|
2970
3637
|
for(const item of all){
|
|
2971
3638
|
const asset=(await client.query('SELECT * FROM ota_assets WHERE sha256=$1',[String(item.sha256).toLowerCase()])).rows[0];
|
|
@@ -2990,53 +3657,239 @@ app.post('/mobile/releases/:releaseId/finalize', auth, async (req: AuthedRequest
|
|
|
2990
3657
|
|
|
2991
3658
|
app.post('/mobile/releases/:releaseId/promote', auth, async (req: AuthedRequest,res) => {
|
|
2992
3659
|
const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
|
|
3660
|
+
if(!mayPromote(release.status,release.promoted_at)){res.status(409).json({error:'Only testing or never-promoted paused releases can be promoted.'});return;}
|
|
2993
3661
|
const incomplete=(await pool.query(`SELECT count(*)::int count FROM ota_updates WHERE release_id=$1 AND manifest='{}'::jsonb`,[release.id])).rows[0]?.count||0;
|
|
2994
3662
|
if(incomplete){res.status(409).json({error:'OTA release is not finalized yet and cannot be promoted.'});return;}
|
|
2995
|
-
const result=await pool.query(`UPDATE ota_releases SET status='released',audience_type='all',audience='{}'::jsonb,rollout_percent=NULL,promoted_at=now(),updated_at=now()
|
|
3663
|
+
const result=await pool.query(`UPDATE ota_releases SET status='released',audience_type='all',audience='{}'::jsonb,rollout_percent=NULL,promoted_at=now(),verified_at=COALESCE(verified_at,now()),updated_at=now()
|
|
3664
|
+
WHERE id=$1 AND (status='test' OR (status='paused' AND promoted_at IS NULL)) RETURNING *`,[release.id]);
|
|
3665
|
+
if(!result.rowCount){res.status(409).json({error:'Release status changed. Refresh and try again.'});return;}
|
|
2996
3666
|
await audit(req.auth!.id,'ota.release.promote','ota-release',release.id,req.body?.reason||'Promote tested OTA release',{appId:release.app_id});
|
|
2997
3667
|
res.json(result.rows[0]);
|
|
2998
3668
|
});
|
|
2999
3669
|
|
|
3000
3670
|
app.post('/mobile/releases/:releaseId/pause', auth, async (req: AuthedRequest,res) => {
|
|
3001
3671
|
const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
|
|
3002
|
-
|
|
3672
|
+
if(!mayPause(release.status)){res.status(409).json({error:'Only active testing or released updates can be paused.'});return;}
|
|
3673
|
+
const updated=await pool.query(`UPDATE ota_releases SET status='paused',updated_at=now() WHERE id=$1 AND status IN ('released','test') RETURNING id`,[release.id]);
|
|
3674
|
+
if(!updated.rowCount){res.status(409).json({error:'Release status changed. Refresh and try again.'});return;}
|
|
3003
3675
|
await audit(req.auth!.id,'ota.release.pause','ota-release',release.id,req.body?.reason||'Pause OTA release');
|
|
3004
3676
|
res.json({ok:true});
|
|
3005
3677
|
});
|
|
3006
3678
|
|
|
3007
|
-
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3679
|
+
/** Create a brand-new signed recovery deployment. Source manifests are never edited.
|
|
3680
|
+
* Embedded recovery uses one placeholder OTA-update row PER PLATFORM so all
|
|
3681
|
+
* existing audience selection, runtime and platform filters still apply. */
|
|
3682
|
+
const makeOtaRecovery=async(client:any,source:any,target:any|null,actorId:string,status:'test'|'released')=>{
|
|
3683
|
+
const recovery=(await client.query(
|
|
3684
|
+
`INSERT INTO ota_releases(app_id,mobile_environment_id,runtime_version,message,status,audience_type,audience,rollout_percent,promoted_at,verified_at,created_by,recovery_kind,recovery_of,recovery_target_id,deployment_group_id)
|
|
3685
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) RETURNING *`,
|
|
3686
|
+
[source.app_id,source.mobile_environment_id,source.runtime_version,
|
|
3687
|
+
target?`Recovery → ${target.message.startsWith('Recovery → ')?target.message.slice('Recovery → '.length):target.message}`:`Recovery → embedded (${source.runtime_version})`,
|
|
3688
|
+
status, status==='released'?'all':source.audience_type,status==='released'?{}:source.audience,
|
|
3689
|
+
status==='released'?null:source.rollout_percent,status==='released'?new Date():null,
|
|
3690
|
+
target?.verified_at||null,actorId,target?'assets':'embedded',source.id,target?.id||null,source.deployment_group_id||null]
|
|
3015
3691
|
)).rows[0];
|
|
3016
|
-
|
|
3692
|
+
const sourceUpdates=(await client.query('SELECT * FROM ota_updates WHERE release_id=$1 ORDER BY platform',[source.id])).rows;
|
|
3693
|
+
const targetUpdates=target?(await client.query('SELECT * FROM ota_updates WHERE release_id=$1',[target.id])).rows:[];
|
|
3694
|
+
if(!sourceUpdates.length)throw Object.assign(new Error('Original update has no published platforms.'),{statusCode:409});
|
|
3695
|
+
for(const old of sourceUpdates){
|
|
3696
|
+
const good=target?targetUpdates.find((u:any)=>u.platform===old.platform):null;
|
|
3697
|
+
if(target&&(!good||!good.manifest||!good.manifest.launchAsset))
|
|
3698
|
+
throw Object.assign(new Error(`Recovery target has no complete ${old.platform} assets.`),{statusCode:409});
|
|
3699
|
+
const next=(await client.query('INSERT INTO ota_updates(release_id,platform,source_hash) VALUES($1,$2,$3) RETURNING id,created_at',
|
|
3700
|
+
[recovery.id,old.platform,good?.source_hash||null])).rows[0];
|
|
3701
|
+
const manifest=good?{
|
|
3702
|
+
...good.manifest,id:next.id,createdAt:new Date(next.created_at).toISOString(),
|
|
3703
|
+
metadata:{...(good.manifest.metadata||{}),indraqReleaseId:recovery.id},
|
|
3704
|
+
extra:{...(good.manifest.extra||{}),indraq:{releaseId:recovery.id,recoveryOf:source.id,recoveryTargetId:target.id}}
|
|
3705
|
+
}:{type:'rollBackToEmbedded'};
|
|
3706
|
+
await client.query('UPDATE ota_updates SET manifest=$1 WHERE id=$2',[manifest,next.id]);
|
|
3707
|
+
if(good)await client.query(`INSERT INTO ota_update_assets(update_id,asset_id,asset_key,role,sort_order)
|
|
3708
|
+
SELECT $1,asset_id,asset_key,role,sort_order FROM ota_update_assets WHERE update_id=$2`,[next.id,good.id]);
|
|
3709
|
+
}
|
|
3710
|
+
return recovery;
|
|
3711
|
+
};
|
|
3712
|
+
|
|
3713
|
+
app.post('/mobile/releases/:releaseId/rollback', auth, async (req: AuthedRequest,res) => {
|
|
3714
|
+
const current=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true);
|
|
3715
|
+
if(!current){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
|
|
3716
|
+
if(!mayRollback(current.status)){res.status(409).json({error:'Production rollback requires an active released OTA. Use withdraw for testing updates.'});return;}
|
|
3717
|
+
const active=(await pool.query(`SELECT id FROM ota_releases WHERE app_id=$1 AND mobile_environment_id=$2 AND runtime_version=$3
|
|
3718
|
+
AND status='released' ORDER BY created_at DESC,id DESC LIMIT 1`,[current.app_id,current.mobile_environment_id,current.runtime_version])).rows[0];
|
|
3719
|
+
if(active?.id!==current.id){res.status(409).json({error:'Only the newest active production release can be rolled back.'});return;}
|
|
3720
|
+
const targetInput=String(req.body?.targetReleaseId||'embedded');
|
|
3721
|
+
const target=targetInput==='embedded'?null:(await pool.query(`SELECT * FROM ota_releases WHERE id=$1
|
|
3722
|
+
AND app_id=$2 AND mobile_environment_id=$3 AND runtime_version=$4 AND status='released'
|
|
3723
|
+
AND recovery_kind='assets' AND created_at<$5`,
|
|
3724
|
+
[ensureUuid(targetInput,'Recovery target'),current.app_id,current.mobile_environment_id,current.runtime_version,current.created_at])).rows[0];
|
|
3725
|
+
if(targetInput!=='embedded'&&!target){res.status(409).json({error:'Selected production recovery target is not an earlier compatible released OTA.'});return;}
|
|
3017
3726
|
const client=await pool.connect();
|
|
3018
3727
|
try{
|
|
3019
3728
|
await client.query('BEGIN');
|
|
3020
|
-
const
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
))
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
SELECT $1,asset_id,asset_key,role,sort_order FROM ota_update_assets WHERE update_id=$2`,[next.id,old.id]);
|
|
3032
|
-
}
|
|
3033
|
-
await client.query(`UPDATE ota_releases SET status='rolled_back',updated_at=now() WHERE id=$1`,[current.id]);
|
|
3729
|
+
const locked=(await client.query(`SELECT * FROM ota_releases WHERE id=$1 FOR UPDATE`,[current.id])).rows[0];
|
|
3730
|
+
if(locked?.status!=='released')throw Object.assign(new Error('Release changed status; retry.'),{statusCode:409});
|
|
3731
|
+
// A production recovery to identical published content cannot change
|
|
3732
|
+
// running JS. Do not create another release or roll back the source.
|
|
3733
|
+
if(target ? await recoveryPayloadsMatch(client,locked.id,target.id) : locked.recovery_kind==='embedded')
|
|
3734
|
+
throw Object.assign(new Error('Selected production recovery already contains identical content. Choose different assets or an embedded/native target.'),
|
|
3735
|
+
{statusCode:409,code:'OTA_RECOVERY_SAME_CONTENT'});
|
|
3736
|
+
const recovery=await makeOtaRecovery(client,current,target,req.auth!.id,'released');
|
|
3737
|
+
const updated=await client.query(`UPDATE ota_releases SET status='rolled_back',updated_at=now()
|
|
3738
|
+
WHERE id=$1 AND status='released' RETURNING id`,[current.id]);
|
|
3739
|
+
if(!updated.rowCount)throw Object.assign(new Error('Release changed status.'),{statusCode:409});
|
|
3034
3740
|
await client.query('COMMIT');
|
|
3035
|
-
await audit(req.auth!.id,'ota.release.rollback','ota-release',
|
|
3036
|
-
|
|
3741
|
+
await audit(req.auth!.id,'ota.release.rollback','ota-release',recovery.id,req.body?.reason||'Production OTA rollback',
|
|
3742
|
+
{from:current.id,target:target?.id||'embedded'});
|
|
3743
|
+
res.json(recovery);
|
|
3037
3744
|
}catch(error){await client.query('ROLLBACK');throw error;}finally{client.release();}
|
|
3038
3745
|
});
|
|
3039
3746
|
|
|
3747
|
+
app.post('/mobile/releases/:releaseId/withdraw', auth, async (req: AuthedRequest,res) => {
|
|
3748
|
+
const accessible=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true);
|
|
3749
|
+
if(!accessible){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
|
|
3750
|
+
const requested=String(req.body?.targetReleaseId||'auto');
|
|
3751
|
+
const pinWithdrawn=req.body?.pinWithdrawn===true;
|
|
3752
|
+
if(!['none','embedded','auto'].includes(requested))ensureUuid(requested,'Recovery target ID');
|
|
3753
|
+
const client=await pool.connect();
|
|
3754
|
+
try{
|
|
3755
|
+
await client.query('BEGIN');
|
|
3756
|
+
// Serialize recovery for this app/environment/runtime. This also ensures
|
|
3757
|
+
// pinning and withdrawal are atomic: an HTTP 409 changes nothing.
|
|
3758
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))',
|
|
3759
|
+
[`ota-withdraw:${accessible.app_id}:${accessible.mobile_environment_id}:${accessible.runtime_version}`]);
|
|
3760
|
+
const current=(await client.query('SELECT * FROM ota_releases WHERE id=$1 FOR UPDATE',[accessible.id])).rows[0];
|
|
3761
|
+
if(!current||!mayWithdraw(current.status,current.promoted_at))
|
|
3762
|
+
throw Object.assign(new Error('Only never-promoted testing updates can be withdrawn. Released updates require rollback.'),{statusCode:409});
|
|
3763
|
+
if(requested!=='none'){
|
|
3764
|
+
const sourcePlatforms=(await client.query('SELECT platform FROM ota_updates WHERE release_id=$1',[current.id])).rows.map((r:any)=>String(r.platform));
|
|
3765
|
+
// PostgreSQL timestamptz has microsecond precision; JS Date loses sub-ms
|
|
3766
|
+
// precision. Compare using the exact selected release row in PostgreSQL.
|
|
3767
|
+
// Without this, the release being withdrawn can appear newer than itself.
|
|
3768
|
+
const later=(await client.query(`SELECT DISTINCT r.id,r.message,r.created_at,r.status,r.audience_type,r.audience
|
|
3769
|
+
FROM ota_releases r JOIN ota_updates u ON u.release_id=r.id
|
|
3770
|
+
JOIN ota_releases anchor ON anchor.id=$5
|
|
3771
|
+
WHERE r.app_id=$1 AND r.mobile_environment_id=$2 AND r.runtime_version=$3
|
|
3772
|
+
AND r.status IN ('released','test') AND u.platform=ANY($4::text[])
|
|
3773
|
+
AND r.id <> anchor.id
|
|
3774
|
+
AND (r.created_at,r.id)>(anchor.created_at,anchor.id)
|
|
3775
|
+
ORDER BY r.created_at DESC,r.id DESC LIMIT 50`,
|
|
3776
|
+
[current.app_id,current.mobile_environment_id,current.runtime_version,sourcePlatforms,current.id])).rows;
|
|
3777
|
+
// Device profiles may have been consolidated since an older OTA was published.
|
|
3778
|
+
// Normalize retired IDs for overlap protection without modifying releases.
|
|
3779
|
+
const relevantIds=[...new Set([current,...later].flatMap((r:any)=>
|
|
3780
|
+
Array.isArray(r.audience?.deviceIds)?r.audience.deviceIds:[]))];
|
|
3781
|
+
const aliasRows=relevantIds.length?(await client.query(`SELECT duplicate_device_id,canonical_device_id
|
|
3782
|
+
FROM ota_tester_device_profile_aliases WHERE duplicate_device_id=ANY($1::uuid[])`,[relevantIds])).rows:[];
|
|
3783
|
+
const aliasMap=new Map(aliasRows.map((r:any)=>[String(r.duplicate_device_id),String(r.canonical_device_id)]));
|
|
3784
|
+
const canonicalAudience=(r:any)=>({...r,audience:{...r.audience,deviceIds:
|
|
3785
|
+
Array.isArray(r.audience?.deviceIds)?r.audience.deviceIds.map((id:string)=>aliasMap.get(id)||id):undefined}});
|
|
3786
|
+
const blockers=later.filter((other:any)=>other.id!==current.id && otaAudiencesMayOverlap(canonicalAudience(current),canonicalAudience(other)));
|
|
3787
|
+
if(blockers.length){
|
|
3788
|
+
const item=blockers[0];
|
|
3789
|
+
throw Object.assign(new Error(`Newer overlapping OTA ${item.id} (${item.message}; ${item.status}; ${new Date(item.created_at).toISOString()}) is active for this runtime/audience. Withdraw it first or choose Stop delivery only.`),
|
|
3790
|
+
{statusCode:409,blockingReleaseId:item.id});
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
let target:any=null;
|
|
3794
|
+
if(requested!=='embedded'&&requested!=='none'){
|
|
3795
|
+
const params=requested==='auto'
|
|
3796
|
+
?[current.app_id,current.mobile_environment_id,current.runtime_version,current.id]
|
|
3797
|
+
:[requested,current.app_id,current.mobile_environment_id,current.runtime_version,current.id];
|
|
3798
|
+
const sql=requested==='auto'
|
|
3799
|
+
?`SELECT * FROM ota_releases WHERE app_id=$1 AND mobile_environment_id=$2 AND runtime_version=$3
|
|
3800
|
+
AND status='released' AND recovery_kind='assets'
|
|
3801
|
+
AND (created_at,id)<(SELECT created_at,id FROM ota_releases WHERE id=$4)
|
|
3802
|
+
ORDER BY created_at DESC,id DESC LIMIT 1`
|
|
3803
|
+
:`SELECT * FROM ota_releases WHERE id=$1 AND app_id=$2 AND mobile_environment_id=$3 AND runtime_version=$4
|
|
3804
|
+
AND status IN ('released','test','paused') AND recovery_kind='assets'
|
|
3805
|
+
AND (created_at,id)<(SELECT created_at,id FROM ota_releases WHERE id=$5)`;
|
|
3806
|
+
target=(await client.query(sql,params)).rows[0]||null;
|
|
3807
|
+
if(requested!=='auto'&&!target)throw Object.assign(new Error('Recovery target must be an earlier compatible OTA with retained assets.'),{statusCode:409});
|
|
3808
|
+
}
|
|
3809
|
+
// An older recovery may point to the exact same already-running JS.
|
|
3810
|
+
// Reject that no-op BEFORE changing status/pinning or creating another
|
|
3811
|
+
// immutable release. 'none' always remains available to stop delivery.
|
|
3812
|
+
if(requested!=='none' && (target
|
|
3813
|
+
?await recoveryPayloadsMatch(client,current.id,target.id)
|
|
3814
|
+
:current.recovery_kind==='embedded')){
|
|
3815
|
+
throw Object.assign(new Error('This recovery target already contains the same JavaScript/assets as the selected update. No new recovery was created. Choose an older DIFFERENT update, restore embedded JS, or Stop delivery only.'),
|
|
3816
|
+
{statusCode:409,code:'OTA_RECOVERY_SAME_CONTENT'});
|
|
3817
|
+
}
|
|
3818
|
+
const withdrawn=await client.query(`UPDATE ota_releases SET status='withdrawn',is_pinned=(is_pinned OR $2),updated_at=now()
|
|
3819
|
+
WHERE id=$1 AND (status='test' OR (status='paused' AND promoted_at IS NULL)) RETURNING id`,
|
|
3820
|
+
[current.id,pinWithdrawn]);
|
|
3821
|
+
if(!withdrawn.rowCount)throw Object.assign(new Error('Update changed status; cannot withdraw.'),{statusCode:409});
|
|
3822
|
+
const recovery=requested==='none'?null:await makeOtaRecovery(client,current,target,req.auth!.id,'test');
|
|
3823
|
+
await client.query('COMMIT');
|
|
3824
|
+
await audit(req.auth!.id,'ota.release.withdraw','ota-release',current.id,req.body?.reason||'Withdraw testing OTA',
|
|
3825
|
+
{recoveryId:recovery?.id||null,target:target?.id||(requested==='none'?'none':'embedded'),pinWithdrawn,cleanup:'orphan-assets-only'});
|
|
3826
|
+
res.json({ok:true,withdrawnReleaseId:current.id,recoveryReleaseId:recovery?.id||null,
|
|
3827
|
+
recoveryKind:recovery?.recovery_kind||null,requiresClientRemediation:requested==='none',
|
|
3828
|
+
note:recovery?`Recovery ${recovery.recovery_kind} published to the same affected audience. Clients apply it on the next online OTA check. Published MinIO assets remain available for cached manifests; unreferenced uploads are GC-eligible after 7 days.`:'Delivery stopped; cached JS may continue to run until a later recovery is published.'});
|
|
3829
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}finally{client.release();}
|
|
3830
|
+
});
|
|
3831
|
+
|
|
3832
|
+
/** Asset URLs are immutable. Only objects that were uploaded but have no
|
|
3833
|
+
* update reference can be reclaimed. This NEVER prunes published manifests. */
|
|
3834
|
+
const orphanAssetsQuery=`SELECT a.id,a.sha256,a.object_key,a.size_bytes FROM ota_assets a
|
|
3835
|
+
WHERE a.created_at < now()-interval '7 days'
|
|
3836
|
+
AND NOT EXISTS(SELECT 1 FROM ota_update_assets ua WHERE ua.asset_id=a.id)
|
|
3837
|
+
ORDER BY a.created_at ASC LIMIT $1`;
|
|
3838
|
+
const collectUnreferencedAssets=async(limit=50)=>{
|
|
3839
|
+
const candidates=(await pool.query(orphanAssetsQuery,[Math.max(1,Math.min(50,limit))])).rows;
|
|
3840
|
+
let deleted=0,bytesDeleted=0;
|
|
3841
|
+
for(const item of candidates){
|
|
3842
|
+
const client=await pool.connect();
|
|
3843
|
+
try{
|
|
3844
|
+
await client.query('BEGIN');
|
|
3845
|
+
// Lock by SHA both here and during upload; avoids an upload racing GC.
|
|
3846
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))',[item.sha256]);
|
|
3847
|
+
const fresh=(await client.query(`SELECT a.id,a.object_key,a.size_bytes FROM ota_assets a
|
|
3848
|
+
WHERE a.id=$1 AND a.created_at<now()-interval '7 days'
|
|
3849
|
+
AND NOT EXISTS(SELECT 1 FROM ota_update_assets ua WHERE ua.asset_id=a.id)
|
|
3850
|
+
FOR UPDATE`,[item.id])).rows[0];
|
|
3851
|
+
if(!fresh){await client.query('COMMIT');continue;}
|
|
3852
|
+
// CAS using the SHA/object identity. In case MinIO fails, DB rollback
|
|
3853
|
+
// preserves the record so the job can retry.
|
|
3854
|
+
await ensureOtaBucket();
|
|
3855
|
+
await getMinio().removeObject(minioBucket,String(fresh.object_key));
|
|
3856
|
+
await client.query('DELETE FROM ota_assets WHERE id=$1',[fresh.id]);
|
|
3857
|
+
await client.query('COMMIT');deleted++;bytesDeleted+=Number(fresh.size_bytes||0);
|
|
3858
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});console.error('OTA orphan cleanup failed',error);}
|
|
3859
|
+
finally{client.release();}
|
|
3860
|
+
}
|
|
3861
|
+
return {deleted,bytesDeleted,scanned:candidates.length};
|
|
3862
|
+
};
|
|
3863
|
+
|
|
3864
|
+
app.get('/mobile/apps/:appId/storage', auth, async (req: AuthedRequest,res) => {
|
|
3865
|
+
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!);
|
|
3866
|
+
if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
|
|
3867
|
+
const owned=(await pool.query(`SELECT COUNT(*)::int count,COALESCE(sum(size_bytes),0)::text bytes FROM ota_assets
|
|
3868
|
+
WHERE id IN (SELECT DISTINCT ua.asset_id FROM ota_update_assets ua JOIN ota_updates u ON u.id=ua.update_id
|
|
3869
|
+
JOIN ota_releases r ON r.id=u.release_id WHERE r.app_id=$1)`,[appRow.id])).rows[0];
|
|
3870
|
+
const orphans=(await pool.query(`SELECT COUNT(*)::int count,COALESCE(sum(a.size_bytes),0)::text bytes FROM ota_assets a
|
|
3871
|
+
WHERE a.created_at<now()-interval '7 days'
|
|
3872
|
+
AND NOT EXISTS(SELECT 1 FROM ota_update_assets ua WHERE ua.asset_id=a.id)`)).rows[0];
|
|
3873
|
+
res.json({appAssets:Number(owned.count),appAssetBytes:Number(owned.bytes),orphanCount:Number(orphans.count),orphanBytes:Number(orphans.bytes),
|
|
3874
|
+
policy:'No published OTA asset is garbage-collected. Only unreferenced uploads older than 7 days are eligible.'});
|
|
3875
|
+
});
|
|
3876
|
+
|
|
3877
|
+
app.post('/mobile/apps/:appId/storage/cleanup', auth, ...allow('admin'), async (req: AuthedRequest,res) => {
|
|
3878
|
+
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!,true);
|
|
3879
|
+
if(!appRow){res.status(404).json({error:'Mobile app not found or WRITE access denied.'});return;}
|
|
3880
|
+
const result=await collectUnreferencedAssets(50);
|
|
3881
|
+
await audit(req.auth!.id,'ota.storage.orphan_cleanup','mobile-app',appRow.id,'Delete unreferenced stale uploads',{...result});
|
|
3882
|
+
res.json(result);
|
|
3883
|
+
});
|
|
3884
|
+
|
|
3885
|
+
app.post('/mobile/releases/:releaseId/pin',auth,async(req:AuthedRequest,res)=>{
|
|
3886
|
+
const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true);
|
|
3887
|
+
if(!release){res.status(404).json({error:'Release not found or WRITE access denied.'});return;}
|
|
3888
|
+
if(typeof req.body?.pinned!=='boolean'){res.status(400).json({error:'pinned must be a boolean.'});return;}
|
|
3889
|
+
const row=(await pool.query('UPDATE ota_releases SET is_pinned=$1,updated_at=now() WHERE id=$2 RETURNING id,is_pinned',[req.body.pinned,release.id])).rows[0];
|
|
3890
|
+
await audit(req.auth!.id,'ota.release.pin','ota-release',release.id,req.body.pinned?'Pin':'Unpin');res.json(row);
|
|
3891
|
+
});
|
|
3892
|
+
|
|
3040
3893
|
app.get('/mobile/apps/:appId/metrics', auth, async (req: AuthedRequest,res) => {
|
|
3041
3894
|
const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!); if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
|
|
3042
3895
|
const releaseId=typeof req.query.releaseId==='string'&&req.query.releaseId?ensureUuid(req.query.releaseId,'Release ID'):null;
|
|
@@ -3047,7 +3900,7 @@ app.get('/mobile/apps/:appId/metrics', auth, async (req: AuthedRequest,res) => {
|
|
|
3047
3900
|
const installs=(await pool.query('SELECT count(*)::int count FROM ota_installations WHERE app_id=$1',[appRow.id])).rows[0]?.count||0;
|
|
3048
3901
|
const releases=(await pool.query(
|
|
3049
3902
|
`SELECT r.id,r.message,r.status,r.audience_type,r.runtime_version,r.created_at,me.name environment_name,
|
|
3050
|
-
(SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type
|
|
3903
|
+
(SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type IN ('manifest_served','embedded_recovery_served') AND e.installation_id IS NOT NULL)::int manifest_installations,
|
|
3051
3904
|
(SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='download_completed' AND e.installation_id IS NOT NULL)::int downloaded_installations,
|
|
3052
3905
|
(SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='launch_success' AND e.installation_id IS NOT NULL)::int successful_launches,
|
|
3053
3906
|
(SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='update_failed' AND e.installation_id IS NOT NULL)::int failed_installations,
|
|
@@ -3057,6 +3910,95 @@ app.get('/mobile/apps/:appId/metrics', auth, async (req: AuthedRequest,res) => {
|
|
|
3057
3910
|
res.json({appId:appRow.id,appName:appRow.app_name,totalInstallations:installs,releaseId,events:counts,releases});
|
|
3058
3911
|
});
|
|
3059
3912
|
|
|
3913
|
+
// Acknowledged registration, independent of telemetry. Required before browser
|
|
3914
|
+
// token redemption and safe to call repeatedly. Does not enroll a tester.
|
|
3915
|
+
app.post('/ota/v1/enroll/announce/:updatePath',async(req,res)=>{
|
|
3916
|
+
res.setHeader('Cache-Control','no-store');
|
|
3917
|
+
const appRow=await publicMobileApp(routeParam(req.params.updatePath));
|
|
3918
|
+
if(!appRow){res.status(404).json({error:'Unknown app.'});return;}
|
|
3919
|
+
const installationId=String(req.body?.installationId||'');
|
|
3920
|
+
const runtimeVersion=String(req.body?.runtimeVersion||'');
|
|
3921
|
+
const platform=String(req.body?.platform||'');
|
|
3922
|
+
if(!/^[A-Za-z0-9_-]{12,200}$/.test(installationId)||runtimeVersion.length>140||!runtimeVersion||!['android','ios'].includes(platform)){
|
|
3923
|
+
res.status(400).json({error:'Invalid installation registration.'});return;
|
|
3924
|
+
}
|
|
3925
|
+
await pool.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,last_seen_at)
|
|
3926
|
+
VALUES($1,$2,$3,$4,now()) ON CONFLICT(app_id,installation_id) DO UPDATE SET
|
|
3927
|
+
platform=excluded.platform,runtime_version=excluded.runtime_version,last_seen_at=now()`,
|
|
3928
|
+
[appRow.id,installationId,platform,runtimeVersion]);
|
|
3929
|
+
res.status(200).json({ok:true});
|
|
3930
|
+
});
|
|
3931
|
+
|
|
3932
|
+
// Android-only private tester mode: weaker trust based on a signing-key-scoped
|
|
3933
|
+
// identifier. This is not cryptographic device attestation. Do NOT use for
|
|
3934
|
+
// public apps, signing keys shared with untrusted developers, or sensitive OTA.
|
|
3935
|
+
app.get('/ota/v1/android-scoped/capabilities/:updatePath',async(req,res)=>{
|
|
3936
|
+
res.setHeader('Cache-Control','no-store');
|
|
3937
|
+
const appRow=await publicMobileApp(routeParam(req.params.updatePath));
|
|
3938
|
+
if(!appRow){res.status(404).json({error:'Unknown app.'});return;}
|
|
3939
|
+
res.json({supported:true,enabled:androidScopedTesterRestoreEnabled,appId:appRow.id,
|
|
3940
|
+
assurance:'identifier-only',fallback:'verified-browser',platform:'android'});
|
|
3941
|
+
});
|
|
3942
|
+
|
|
3943
|
+
app.post('/ota/v1/enroll/android-scoped/:updatePath',async(req,res)=>{
|
|
3944
|
+
res.setHeader('Cache-Control','no-store');
|
|
3945
|
+
const appRow=await publicMobileApp(routeParam(req.params.updatePath));
|
|
3946
|
+
if(!appRow){res.status(404).json({error:'Unknown app.'});return;}
|
|
3947
|
+
if(!androidScopedTesterRestoreEnabled){res.status(403).json({enrolled:false,recovery:'browser',reason:'feature_disabled'});return;}
|
|
3948
|
+
const installationId=String(req.body?.installationId||'');
|
|
3949
|
+
const runtimeVersion=String(req.body?.runtimeVersion||'');
|
|
3950
|
+
const androidScopedId=String(req.body?.androidScopedId||'').toLowerCase();
|
|
3951
|
+
if(!/^[A-Za-z0-9_-]{12,200}$/.test(installationId)||!/^.{1,100}-indraq-(staging|prod)$/.test(runtimeVersion)||!androidScopedIdPattern.test(androidScopedId)){
|
|
3952
|
+
res.status(400).json({enrolled:false,recovery:'browser',reason:'invalid_request'});return;
|
|
3953
|
+
}
|
|
3954
|
+
// A successful native build record must exist for the exact runtime. Merely
|
|
3955
|
+
// copying an app ID from the CLI is insufficient to claim a runtime.
|
|
3956
|
+
const built=await pool.query(`SELECT 1 FROM mobile_native_builds WHERE app_id=$1 AND runtime_version=$2 LIMIT 1`,[appRow.id,runtimeVersion]);
|
|
3957
|
+
if(!built.rowCount){res.status(409).json({enrolled:false,recovery:'browser',reason:'runtime_not_recorded'});return;}
|
|
3958
|
+
const client=await pool.connect();
|
|
3959
|
+
try{
|
|
3960
|
+
await client.query('BEGIN');
|
|
3961
|
+
const identity=(await client.query(`SELECT d.id,d.label,d.owner_user_id FROM ota_android_scoped_tester_identities i
|
|
3962
|
+
JOIN ota_registered_tester_devices d ON d.id=i.device_id
|
|
3963
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=$2 AND g.revoked_at IS NULL
|
|
3964
|
+
WHERE i.identity_digest=$1 AND d.verified_at IS NOT NULL AND d.revoked_at IS NULL FOR UPDATE OF d`,
|
|
3965
|
+
[scopedIdDigest(androidScopedId),appRow.id])).rows[0];
|
|
3966
|
+
if(!identity){await client.query('ROLLBACK');res.status(403).json({enrolled:false,recovery:'browser',reason:'not_bound_or_not_authorized'});return;}
|
|
3967
|
+
await client.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,last_seen_at)
|
|
3968
|
+
VALUES($1,$2,'android',$3,now()) ON CONFLICT(app_id,installation_id)
|
|
3969
|
+
DO UPDATE SET platform='android',runtime_version=excluded.runtime_version,last_seen_at=now()`,[appRow.id,installationId,runtimeVersion]);
|
|
3970
|
+
await client.query(`INSERT INTO ota_tester_installations(app_id,installation_id,label,enrolled_by,revoked_at)
|
|
3971
|
+
VALUES($1,$2,$3,$4,NULL) ON CONFLICT(app_id,installation_id) DO UPDATE SET
|
|
3972
|
+
label=excluded.label,enrolled_by=excluded.enrolled_by,enrolled_at=now(),revoked_at=NULL`,
|
|
3973
|
+
[appRow.id,installationId,identity.label,identity.owner_user_id]);
|
|
3974
|
+
await client.query(`INSERT INTO ota_registered_device_installations(device_id,app_id,installation_id)
|
|
3975
|
+
VALUES($1,$2,$3) ON CONFLICT(app_id,installation_id) DO UPDATE SET
|
|
3976
|
+
device_id=excluded.device_id,linked_at=now()`,[identity.id,appRow.id,installationId]);
|
|
3977
|
+
await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,platform,runtime_version,metadata)
|
|
3978
|
+
VALUES($1,$2,'device_enrolled','android',$3,$4)`,[appRow.id,installationId,runtimeVersion,{source:'android_scoped_internal',assurance:'identifier_only'}]);
|
|
3979
|
+
await client.query('COMMIT');
|
|
3980
|
+
res.json({enrolled:true,assurance:'identifier_only'});
|
|
3981
|
+
}catch(error){await client.query('ROLLBACK').catch(()=>{});throw error;}finally{client.release();}
|
|
3982
|
+
});
|
|
3983
|
+
|
|
3984
|
+
// Only tester-enabled builds call this: never expose a phone's browser credential
|
|
3985
|
+
// or registered device identity to an unauthenticated app installation.
|
|
3986
|
+
app.get('/ota/v1/enrollment/status/:updatePath',async(req,res)=>{
|
|
3987
|
+
res.setHeader('Cache-Control','no-store');
|
|
3988
|
+
const appRow=await publicMobileApp(routeParam(req.params.updatePath));
|
|
3989
|
+
if(!appRow){res.status(404).json({error:'Unknown app.'});return;}
|
|
3990
|
+
const installationId=String(req.query.installationId||'');
|
|
3991
|
+
if(!/^[A-Za-z0-9_-]{12,200}$/.test(installationId)){
|
|
3992
|
+
res.status(400).json({error:'Invalid installation ID.'});return;
|
|
3993
|
+
}
|
|
3994
|
+
const enrollment=await pool.query(`SELECT 1 FROM ota_tester_installations
|
|
3995
|
+
WHERE app_id=$1 AND installation_id=$2 AND revoked_at IS NULL`,[appRow.id,installationId]);
|
|
3996
|
+
const grants=await pool.query(`SELECT 1 FROM ota_device_app_grants g
|
|
3997
|
+
JOIN ota_registered_tester_devices d ON d.id=g.device_id
|
|
3998
|
+
WHERE g.app_id=$1 AND g.revoked_at IS NULL AND d.verified_at IS NOT NULL AND d.revoked_at IS NULL LIMIT 1`,[appRow.id]);
|
|
3999
|
+
res.json({enrolled:!!enrollment.rowCount,reconnectAvailable:!!grants.rowCount,appId:appRow.id});
|
|
4000
|
+
});
|
|
4001
|
+
|
|
3060
4002
|
app.get('/ota/v1/manifest/:updatePath', async (req,res) => {
|
|
3061
4003
|
const appRow=await publicMobileApp(routeParam(req.params.updatePath)); if(!appRow){res.status(404).end();return;}
|
|
3062
4004
|
const platform=String(req.headers['expo-platform']||'').toLowerCase();
|
|
@@ -3080,7 +4022,7 @@ app.get('/ota/v1/manifest/:updatePath', async (req,res) => {
|
|
|
3080
4022
|
const candidates=(await pool.query(
|
|
3081
4023
|
`SELECT r.*,u.id update_id,u.manifest,u.created_at update_created_at FROM ota_releases r JOIN ota_updates u ON u.release_id=r.id
|
|
3082
4024
|
WHERE r.app_id=$1 AND r.mobile_environment_id=$2 AND r.runtime_version=$3 AND u.platform=$4 AND r.status IN ('test','released') AND u.manifest <> '{}'::jsonb
|
|
3083
|
-
ORDER BY r.created_at DESC LIMIT 50`,[appRow.id,env.id,runtimeVersion,platform]
|
|
4025
|
+
ORDER BY r.created_at DESC,r.id DESC LIMIT 50`,[appRow.id,env.id,runtimeVersion,platform]
|
|
3084
4026
|
)).rows;
|
|
3085
4027
|
// Group membership is evaluated at request time: adding/revoking an enrolled
|
|
3086
4028
|
// tester takes effect without rebuilding or editing an existing release.
|
|
@@ -3096,9 +4038,50 @@ app.get('/ota/v1/manifest/:updatePath', async (req,res) => {
|
|
|
3096
4038
|
for(const row of rows)currentGroups.add(String(row.group_id));
|
|
3097
4039
|
}
|
|
3098
4040
|
}
|
|
3099
|
-
|
|
4041
|
+
// A device ID is trusted ONLY when derived server-side from a previously
|
|
4042
|
+
// linked installation, current app grant and current tester enrollment.
|
|
4043
|
+
// The client cannot request this audience by sending an arbitrary device ID.
|
|
4044
|
+
let approvedDeviceId:string|null=null;
|
|
4045
|
+
if(activeTester && identity.installationId){
|
|
4046
|
+
const verified=(await pool.query(`SELECT li.device_id FROM ota_registered_device_installations li
|
|
4047
|
+
JOIN ota_registered_tester_devices d ON d.id=li.device_id
|
|
4048
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=li.app_id
|
|
4049
|
+
JOIN ota_installations i ON i.app_id=li.app_id AND i.installation_id=li.installation_id
|
|
4050
|
+
WHERE li.app_id=$1 AND li.installation_id=$2 AND i.platform=$3 AND i.runtime_version=$4
|
|
4051
|
+
AND g.revoked_at IS NULL AND d.revoked_at IS NULL AND d.verified_at IS NOT NULL
|
|
4052
|
+
LIMIT 1`,[appRow.id,identity.installationId,platform,runtimeVersion])).rows[0];
|
|
4053
|
+
approvedDeviceId=verified?.device_id?String(verified.device_id):null;
|
|
4054
|
+
}
|
|
4055
|
+
// Retired aliases preserve immutable historical test-targeted release audiences.
|
|
4056
|
+
// Aliases cannot grant access: we only use them after verifying the active
|
|
4057
|
+
// surviving device, its current app grant, and the enrolled installation.
|
|
4058
|
+
const legacyDeviceIds=new Set<string>();
|
|
4059
|
+
if(approvedDeviceId){
|
|
4060
|
+
const aliases=(await pool.query(`SELECT duplicate_device_id FROM ota_tester_device_profile_aliases
|
|
4061
|
+
WHERE canonical_device_id=$1`,[approvedDeviceId])).rows;
|
|
4062
|
+
for(const item of aliases)legacyDeviceIds.add(String(item.duplicate_device_id));
|
|
4063
|
+
}
|
|
4064
|
+
const selected=candidates.find((row:any)=>audienceMatches(row,identity,currentGroups,activeTester,approvedDeviceId,legacyDeviceIds));
|
|
3100
4065
|
if(!selected){res.status(204).end();return;}
|
|
3101
4066
|
const currentUpdate=String(req.headers['expo-current-update-id']||identity.currentUpdateId||'');
|
|
4067
|
+
if(selected.recovery_kind==='embedded'){
|
|
4068
|
+
// Roll back only the native runtime/platform/audience for which this
|
|
4069
|
+
// directive was created. Never broadcast an embedded rollback to every APK.
|
|
4070
|
+
const embeddedUpdate=String(req.headers['expo-embedded-update-id']||'');
|
|
4071
|
+
if(!embeddedUpdate){res.status(409).json({error:'Expo-Embedded-Update-ID is required for embedded recovery.'});return;}
|
|
4072
|
+
if(currentUpdate===embeddedUpdate){res.status(204).end();return;}
|
|
4073
|
+
const directive=embeddedDirective(new Date(selected.update_created_at).toISOString());
|
|
4074
|
+
const json=JSON.stringify(directive);
|
|
4075
|
+
const signature=req.headers['expo-expect-signature']
|
|
4076
|
+
?(appRow.encrypted_signing_private_key?signExpoManifest(json,appRow.encrypted_signing_private_key):null)
|
|
4077
|
+
:undefined;
|
|
4078
|
+
if(signature===null){res.status(500).json({error:'OTA signing key unavailable for recovery directive.'});return;}
|
|
4079
|
+
const part=multipartDirective(directive,signature||undefined,`indraq${selected.update_id.replace(/-/g,'')}`);
|
|
4080
|
+
res.setHeader('content-type',part.contentType);
|
|
4081
|
+
await pool.query('INSERT INTO ota_events(app_id,release_id,update_id,installation_id,event_type,platform,runtime_version,metadata) VALUES($1,$2,$3,$4,$5,$6,$7,$8)',
|
|
4082
|
+
[appRow.id,selected.id,selected.update_id,identity.installationId||null,'embedded_recovery_served',platform,runtimeVersion,{channel}]);
|
|
4083
|
+
res.status(200).send(part.body);return;
|
|
4084
|
+
}
|
|
3102
4085
|
if(currentUpdate===selected.update_id){res.status(204).end();return;}
|
|
3103
4086
|
const manifestString=JSON.stringify(selected.manifest);
|
|
3104
4087
|
res.setHeader('content-type','application/expo+json');
|
|
@@ -3186,4 +4169,17 @@ const bootstrap = async (): Promise<void> => {
|
|
|
3186
4169
|
await runMigrations();
|
|
3187
4170
|
await bootstrap();
|
|
3188
4171
|
if (process.env.MINIO_ENDPOINT && process.env.MINIO_ACCESS_KEY && process.env.MINIO_SECRET_KEY) { await ensureOtaBucket(); console.log(`OTA MinIO bucket ready: ${minioBucket}`); }
|
|
4172
|
+
// Opt-in scheduled orphan-upload GC. Safe defaults: dry-run only until explicitly
|
|
4173
|
+
// enabled after production verification. Leader elected by Postgres advisory lock.
|
|
4174
|
+
if(process.env.OTA_ORPHAN_GC_ENABLED==='true'){
|
|
4175
|
+
const runGc=async()=>{
|
|
4176
|
+
const client=await pool.connect();
|
|
4177
|
+
try{
|
|
4178
|
+
const lock=(await client.query('SELECT pg_try_advisory_lock(2120160) locked')).rows[0]?.locked;
|
|
4179
|
+
if(!lock)return;
|
|
4180
|
+
try{await collectUnreferencedAssets(50);}finally{await client.query('SELECT pg_advisory_unlock(2120160)');}
|
|
4181
|
+
}catch(error){console.error('OTA orphan GC error',error);}finally{client.release();}
|
|
4182
|
+
};
|
|
4183
|
+
const timer=setInterval(()=>{void runGc();},6*60*60*1000);timer.unref();
|
|
4184
|
+
}
|
|
3189
4185
|
app.listen(Number(process.env.PORT || 4010), () => console.log(`IndraQ Cloud API listening on ${process.env.PORT || 4010}`));
|