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/dist/index.js
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
|
const { Pool } = pg;
|
|
15
20
|
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
16
21
|
const app = express();
|
|
@@ -22,6 +27,11 @@ const masterHex = process.env.MASTER_KEY || '';
|
|
|
22
27
|
if (!/^[a-fA-F0-9]{64}$/.test(masterHex))
|
|
23
28
|
throw new Error('MASTER_KEY must be exactly 64 hex characters (32 bytes).');
|
|
24
29
|
const masterKey = Buffer.from(masterHex, 'hex');
|
|
30
|
+
// An Android ID is an identification hint, NOT possession proof. This opt-in
|
|
31
|
+
// weak-trust mode is restricted to private tester builds. Disabled by default.
|
|
32
|
+
const androidScopedTesterRestoreEnabled = process.env.OTA_ANDROID_SCOPED_TESTER_RESTORE === 'true';
|
|
33
|
+
const androidScopedIdPattern = /^(?!9774d56d682e549c$)[0-9a-f]{16}$/i;
|
|
34
|
+
const scopedIdDigest = (value) => createHmac('sha256', masterKey).update('indraq-ota-ssaid-v1\0' + value.toLowerCase()).digest('hex');
|
|
25
35
|
const publicApiUrl = (process.env.PUBLIC_API_URL || 'https://cli.indraq.com').replace(/\/+$/, '');
|
|
26
36
|
const minioBucket = process.env.MINIO_BUCKET || 'indraq-ota';
|
|
27
37
|
let minioClient = null;
|
|
@@ -3003,23 +3013,78 @@ const publicMobileApp = async (updatePath) => {
|
|
|
3003
3013
|
return result.rows[0] || null;
|
|
3004
3014
|
};
|
|
3005
3015
|
const parseExpoExtraParams = (header) => {
|
|
3006
|
-
|
|
3016
|
+
// Expo-Extra-Params is an RFC 8941-style structured-field dictionary.
|
|
3017
|
+
// Our CLI sends string values. Parse those strictly and reject malformed
|
|
3018
|
+
// dictionaries instead of accidentally reading a substring of a bad header.
|
|
3019
|
+
const input = (typeof header === 'string' ? header : Array.isArray(header) ? header[0] : '')?.trim() || '';
|
|
3007
3020
|
const out = {};
|
|
3008
|
-
|
|
3009
|
-
|
|
3010
|
-
|
|
3011
|
-
|
|
3012
|
-
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3021
|
+
if (!input || input.length > 8192)
|
|
3022
|
+
return out;
|
|
3023
|
+
let i = 0;
|
|
3024
|
+
const whitespace = () => { while (input[i] === ' ' || input[i] === '\t')
|
|
3025
|
+
i += 1; };
|
|
3026
|
+
while (i < input.length) {
|
|
3027
|
+
whitespace();
|
|
3028
|
+
const start = i;
|
|
3029
|
+
while (i < input.length && /[a-z0-9_.*-]/i.test(input[i]))
|
|
3030
|
+
i += 1;
|
|
3031
|
+
const key = input.slice(start, i).toLowerCase();
|
|
3032
|
+
if (!/^[a-z*][a-z0-9_.*-]*$/.test(key) || Object.prototype.hasOwnProperty.call(out, key))
|
|
3033
|
+
return {};
|
|
3034
|
+
whitespace();
|
|
3035
|
+
if (input[i] !== '=')
|
|
3036
|
+
return {};
|
|
3037
|
+
i += 1;
|
|
3038
|
+
whitespace();
|
|
3039
|
+
if (input[i] !== '"')
|
|
3040
|
+
return {}; // IndraQ extra parameters are always strings.
|
|
3041
|
+
i += 1;
|
|
3042
|
+
let value = '';
|
|
3043
|
+
let closed = false;
|
|
3044
|
+
while (i < input.length) {
|
|
3045
|
+
const ch = input[i++];
|
|
3046
|
+
if (ch === '"') {
|
|
3047
|
+
closed = true;
|
|
3048
|
+
break;
|
|
3049
|
+
}
|
|
3050
|
+
if (ch === '\\') {
|
|
3051
|
+
const next = input[i++];
|
|
3052
|
+
if (next !== '"' && next !== '\\')
|
|
3053
|
+
return {};
|
|
3054
|
+
value += next;
|
|
3055
|
+
}
|
|
3056
|
+
else {
|
|
3057
|
+
if (ch.charCodeAt(0) < 32 || ch.charCodeAt(0) === 127)
|
|
3058
|
+
return {};
|
|
3059
|
+
value += ch;
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
if (!closed)
|
|
3063
|
+
return {};
|
|
3064
|
+
out[key] = value;
|
|
3065
|
+
whitespace();
|
|
3066
|
+
if (i === input.length)
|
|
3067
|
+
break;
|
|
3068
|
+
if (input[i] !== ',')
|
|
3069
|
+
return {};
|
|
3070
|
+
i += 1;
|
|
3071
|
+
whitespace();
|
|
3072
|
+
if (i === input.length)
|
|
3073
|
+
return {};
|
|
3017
3074
|
}
|
|
3018
3075
|
return out;
|
|
3019
3076
|
};
|
|
3020
3077
|
const requestIdentity = (req) => {
|
|
3021
3078
|
const extra = parseExpoExtraParams(req.headers['expo-extra-params']);
|
|
3022
|
-
const value = (header, extraKey, max) =>
|
|
3079
|
+
const value = (header, extraKey, max) => {
|
|
3080
|
+
// New clients use Expo-Extra-Params to avoid changing the native launch
|
|
3081
|
+
// identity. Old clients still send x-indraq-* headers. Prefer extra params
|
|
3082
|
+
// whenever available, but keep the legacy fallback for deployed APKs.
|
|
3083
|
+
const extraValue = extra[extraKey];
|
|
3084
|
+
const legacyValue = req.headers[header];
|
|
3085
|
+
const raw = extraValue || (typeof legacyValue === 'string' ? legacyValue : Array.isArray(legacyValue) ? legacyValue[0] : '') || '';
|
|
3086
|
+
return String(raw).trim().slice(0, max);
|
|
3087
|
+
};
|
|
3023
3088
|
return {
|
|
3024
3089
|
installationId: value('x-indraq-installation-id', 'indraq-installation-id', 200),
|
|
3025
3090
|
userId: value('x-indraq-user-id', 'indraq-user-id', 200),
|
|
@@ -3029,7 +3094,7 @@ const requestIdentity = (req) => {
|
|
|
3029
3094
|
currentUpdateId: value('x-indraq-current-update-id', 'indraq-current-update-id', 200)
|
|
3030
3095
|
};
|
|
3031
3096
|
};
|
|
3032
|
-
const audienceMatches = (row, identity, groups = new Set(), activeTester = false) => {
|
|
3097
|
+
const audienceMatches = (row, identity, groups = new Set(), activeTester = false, approvedDeviceId = null, legacyDeviceIds = new Set()) => {
|
|
3033
3098
|
if (row.status === 'released' && row.audience_type === 'all')
|
|
3034
3099
|
return true;
|
|
3035
3100
|
if (row.status === 'released' && row.audience_type === 'percentage') {
|
|
@@ -3038,6 +3103,9 @@ const audienceMatches = (row, identity, groups = new Set(), activeTester = false
|
|
|
3038
3103
|
const bucket = Number.parseInt(createHash('sha256').update(`${identity.installationId}:${row.id}`).digest('hex').slice(0, 8), 16) % 100;
|
|
3039
3104
|
return bucket < Number(row.rollout_percent);
|
|
3040
3105
|
}
|
|
3106
|
+
const deviceIds = Array.isArray(row.audience?.deviceIds) ? row.audience.deviceIds : [];
|
|
3107
|
+
if (deviceIds.length && activeTester && approvedDeviceId && deviceIds.some(id => id === approvedDeviceId || legacyDeviceIds.has(id)))
|
|
3108
|
+
return true;
|
|
3041
3109
|
const groupIds = Array.isArray(row.audience?.groupIds) ? row.audience.groupIds : [];
|
|
3042
3110
|
if (groupIds.some((id) => groups.has(String(id))))
|
|
3043
3111
|
return true;
|
|
@@ -3067,6 +3135,600 @@ const audienceMatches = (row, identity, groups = new Set(), activeTester = false
|
|
|
3067
3135
|
const enrollmentTokenPattern = /^[A-Za-z0-9_-]{43}$/;
|
|
3068
3136
|
const enrollmentSchemePattern = /^[a-z][a-z0-9+.-]{1,39}$/;
|
|
3069
3137
|
const hashEnrollmentToken = (token) => createHash('sha256').update(token).digest('hex');
|
|
3138
|
+
// Grants authorize an account-owned, QR-verified phone profile for a mobile project.
|
|
3139
|
+
// They never substitute for cryptographic installation pairing across app sandboxes.
|
|
3140
|
+
const requestedAppIds = (input) => {
|
|
3141
|
+
if (input === undefined)
|
|
3142
|
+
return [];
|
|
3143
|
+
if (!Array.isArray(input) || input.length > 50)
|
|
3144
|
+
throw Object.assign(new Error('appIds must be an array of at most 50 app IDs.'), { statusCode: 400 });
|
|
3145
|
+
return [...new Set(input.map(v => ensureUuid(String(v), 'Mobile app ID')))];
|
|
3146
|
+
};
|
|
3147
|
+
const requestedDeviceIds = (input) => {
|
|
3148
|
+
if (!Array.isArray(input) || input.length < 1 || input.length > 50)
|
|
3149
|
+
throw Object.assign(new Error('deviceIds must contain 1 to 50 registered devices.'), { statusCode: 400 });
|
|
3150
|
+
return [...new Set(input.map(v => ensureUuid(String(v), 'Registered device ID')))];
|
|
3151
|
+
};
|
|
3152
|
+
const authorizeDeviceApps = async (user, appIds) => {
|
|
3153
|
+
for (const appId of appIds) {
|
|
3154
|
+
if (!await mobileAppForUser(appId, user, true))
|
|
3155
|
+
throw Object.assign(new Error(`WRITE access required to authorize tester devices for app ${appId}.`), { statusCode: 403 });
|
|
3156
|
+
}
|
|
3157
|
+
};
|
|
3158
|
+
// Tester profiles are PENDING until a real phone browser approves a one-use QR.
|
|
3159
|
+
// Proof is a secure browser credential; it is not an OS hardware ID or biometric attestation.
|
|
3160
|
+
const createDeviceChallenge = async (deviceId, ownerId) => {
|
|
3161
|
+
const token = deviceToken();
|
|
3162
|
+
const row = (await pool.query(`INSERT INTO ota_device_registration_challenges(device_id,token_hash,expires_at)
|
|
3163
|
+
SELECT d.id,$2,now()+interval '15 minutes' FROM ota_registered_tester_devices d
|
|
3164
|
+
WHERE d.id=$1 AND d.owner_user_id=$3 AND d.revoked_at IS NULL AND d.verified_at IS NULL
|
|
3165
|
+
RETURNING id,expires_at`, [deviceId, deviceTokenHash(token), ownerId])).rows[0];
|
|
3166
|
+
if (!row)
|
|
3167
|
+
throw Object.assign(new Error('Profile is already verified or revoked.'), { statusCode: 409 });
|
|
3168
|
+
return { challengeId: row.id, enrollmentUrl: `${publicApiUrl}/ota/device/register/${token}`, expiresAt: row.expires_at };
|
|
3169
|
+
};
|
|
3170
|
+
app.get('/mobile/tester-devices', auth, async (req, res) => {
|
|
3171
|
+
const rows = (await pool.query(`SELECT d.id,d.label,d.created_at,d.verified_at,d.revoked_at,d.agent_activated_at,
|
|
3172
|
+
(SELECT count(*)::int FROM ota_registered_device_installations l WHERE l.device_id=d.id) linked_installations
|
|
3173
|
+
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;
|
|
3174
|
+
res.json(rows);
|
|
3175
|
+
});
|
|
3176
|
+
app.post('/mobile/tester-devices', auth, async (req, res) => {
|
|
3177
|
+
const label = textValue(req.body?.label, 'Device label', 80);
|
|
3178
|
+
const appIds = requestedAppIds(req.body?.appIds);
|
|
3179
|
+
await authorizeDeviceApps(req.auth, appIds); // Validate ALL grants before creating a profile.
|
|
3180
|
+
const client = await pool.connect();
|
|
3181
|
+
let row;
|
|
3182
|
+
try {
|
|
3183
|
+
await client.query('BEGIN');
|
|
3184
|
+
row = (await client.query(`INSERT INTO ota_registered_tester_devices(owner_user_id,label)
|
|
3185
|
+
VALUES($1,$2) RETURNING id,label,created_at,verified_at`, [req.auth.id, label])).rows[0];
|
|
3186
|
+
for (const appId of appIds)
|
|
3187
|
+
await client.query(`INSERT INTO ota_device_app_grants(device_id,app_id,granted_by)
|
|
3188
|
+
VALUES($1,$2,$3)`, [row.id, appId, req.auth.id]);
|
|
3189
|
+
await client.query('COMMIT');
|
|
3190
|
+
}
|
|
3191
|
+
catch (error) {
|
|
3192
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
3193
|
+
throw error;
|
|
3194
|
+
}
|
|
3195
|
+
finally {
|
|
3196
|
+
client.release();
|
|
3197
|
+
}
|
|
3198
|
+
const challenge = await createDeviceChallenge(row.id, req.auth.id);
|
|
3199
|
+
await audit(req.auth.id, 'ota.device.pending', 'tester-device', row.id, 'Create pending tester device with app grants; QR confirmation required', { appIds });
|
|
3200
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3201
|
+
res.status(201).json({ ...row, ...challenge, authorizedAppIds: appIds });
|
|
3202
|
+
});
|
|
3203
|
+
// Existing v2.9 profile-only records can be verified without creating duplicate devices.
|
|
3204
|
+
app.post('/mobile/tester-devices/:id/verify', auth, async (req, res) => {
|
|
3205
|
+
const id = ensureUuid(routeParam(req.params.id), 'Device ID');
|
|
3206
|
+
// Explicit reset allows recovering a verified profile after browser data was cleared.
|
|
3207
|
+
// The old browser credential becomes invalid immediately; the profile is pending again.
|
|
3208
|
+
if (req.body?.reset === true) {
|
|
3209
|
+
const reset = await pool.query(`UPDATE ota_registered_tester_devices
|
|
3210
|
+
SET verified_at=NULL,browser_credential_hash=NULL,agent_public_key=NULL,agent_activated_at=NULL
|
|
3211
|
+
WHERE id=$1 AND owner_user_id=$2 AND revoked_at IS NULL RETURNING id`, [id, req.auth.id]);
|
|
3212
|
+
if (!reset.rowCount) {
|
|
3213
|
+
res.status(404).json({ error: 'Active device profile not found.' });
|
|
3214
|
+
return;
|
|
3215
|
+
}
|
|
3216
|
+
await audit(req.auth.id, 'ota.device.reset', 'tester-device', id, 'Reset browser approval; previous credential revoked');
|
|
3217
|
+
}
|
|
3218
|
+
const challenge = await createDeviceChallenge(id, req.auth.id);
|
|
3219
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3220
|
+
res.json(challenge);
|
|
3221
|
+
});
|
|
3222
|
+
// Authenticated CLI polling. Never expose the one-time registration secret here.
|
|
3223
|
+
app.get('/mobile/tester-devices/:id/challenges/:challengeId/status', auth, async (req, res) => {
|
|
3224
|
+
const id = ensureUuid(routeParam(req.params.id), 'Device ID');
|
|
3225
|
+
const challengeId = ensureUuid(routeParam(req.params.challengeId), 'Challenge ID');
|
|
3226
|
+
const row = (await pool.query(`SELECT d.id,d.label,d.verified_at,d.revoked_at,c.expires_at,c.completed_at
|
|
3227
|
+
FROM ota_registered_tester_devices d JOIN ota_device_registration_challenges c ON c.device_id=d.id
|
|
3228
|
+
WHERE d.id=$1 AND d.owner_user_id=$2 AND c.id=$3`, [id, req.auth.id, challengeId])).rows[0];
|
|
3229
|
+
if (!row) {
|
|
3230
|
+
res.status(404).json({ error: 'Registration challenge not found.' });
|
|
3231
|
+
return;
|
|
3232
|
+
}
|
|
3233
|
+
const status = row.revoked_at ? 'revoked' : row.completed_at && row.verified_at ? 'verified' :
|
|
3234
|
+
row.completed_at ? 'duplicate' : row.verified_at ? 'superseded' : new Date(row.expires_at).getTime() <= Date.now() ? 'expired' : 'pending';
|
|
3235
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3236
|
+
res.json({ id: row.id, label: row.label, status, verifiedAt: row.verified_at || null, expiresAt: row.expires_at });
|
|
3237
|
+
});
|
|
3238
|
+
app.get('/ota/device/register/:token', async (req, res) => {
|
|
3239
|
+
const token = routeParam(req.params.token);
|
|
3240
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3241
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
3242
|
+
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; base-uri 'none'");
|
|
3243
|
+
if (!enrollmentTokenPattern.test(token)) {
|
|
3244
|
+
res.status(404).type('text/plain').send('Invalid device QR.');
|
|
3245
|
+
return;
|
|
3246
|
+
}
|
|
3247
|
+
const row = (await pool.query(`SELECT d.id,d.label,d.owner_user_id FROM ota_device_registration_challenges c
|
|
3248
|
+
JOIN ota_registered_tester_devices d ON d.id=c.device_id
|
|
3249
|
+
WHERE c.token_hash=$1 AND c.expires_at>now() AND c.completed_at IS NULL
|
|
3250
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NULL`, [deviceTokenHash(token)])).rows[0];
|
|
3251
|
+
if (!row) {
|
|
3252
|
+
res.status(410).type('html').send(enrollmentPage({ state: 'expired' }));
|
|
3253
|
+
return;
|
|
3254
|
+
}
|
|
3255
|
+
const browser = await verifiedOtaBrowser(req.headers.cookie);
|
|
3256
|
+
if (browser && browser.owner_user_id === row.owner_user_id && browser.id !== row.id) {
|
|
3257
|
+
// Inform the waiting CLI immediately instead of leaving its QR pending
|
|
3258
|
+
// until expiry. The unused profile stays unverified for audit/retry.
|
|
3259
|
+
await pool.query(`UPDATE ota_device_registration_challenges SET completed_at=now()
|
|
3260
|
+
WHERE token_hash=$1 AND completed_at IS NULL`, [deviceTokenHash(token)]);
|
|
3261
|
+
res.status(409).type('html').send(enrollmentPage({ state: 'duplicate', name: browser.label, link: '/ota/device/apps' }));
|
|
3262
|
+
return;
|
|
3263
|
+
}
|
|
3264
|
+
const grants = (await pool.query(`SELECT ma.app_name FROM ota_device_app_grants g
|
|
3265
|
+
JOIN mobile_apps ma ON ma.id=g.app_id
|
|
3266
|
+
WHERE g.device_id=$1 AND g.revoked_at IS NULL ORDER BY ma.app_name`, [row.id])).rows;
|
|
3267
|
+
res.type('html').send(enrollmentPage({ state: 'register', name: row.label, apps: grants.map(g => g.app_name), action: `/ota/device/register/${token}/confirm` }));
|
|
3268
|
+
});
|
|
3269
|
+
app.post('/ota/device/register/:token/confirm', async (req, res) => {
|
|
3270
|
+
const token = routeParam(req.params.token);
|
|
3271
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3272
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
3273
|
+
if (!enrollmentTokenPattern.test(token)) {
|
|
3274
|
+
res.status(404).type('text/plain').send('Invalid device QR.');
|
|
3275
|
+
return;
|
|
3276
|
+
}
|
|
3277
|
+
const client = await pool.connect();
|
|
3278
|
+
try {
|
|
3279
|
+
await client.query('BEGIN');
|
|
3280
|
+
const row = (await client.query(`SELECT c.id challenge_id,d.id device_id,d.owner_user_id FROM ota_device_registration_challenges c
|
|
3281
|
+
JOIN ota_registered_tester_devices d ON d.id=c.device_id
|
|
3282
|
+
WHERE c.token_hash=$1 AND c.expires_at>now() AND c.completed_at IS NULL
|
|
3283
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NULL FOR UPDATE OF c,d`, [deviceTokenHash(token)])).rows[0];
|
|
3284
|
+
if (!row) {
|
|
3285
|
+
await client.query('ROLLBACK');
|
|
3286
|
+
res.status(410).type('html').send(enrollmentPage({ state: 'expired' }));
|
|
3287
|
+
return;
|
|
3288
|
+
}
|
|
3289
|
+
const browser = await verifiedOtaBrowser(req.headers.cookie);
|
|
3290
|
+
if (browser && browser.owner_user_id === row.owner_user_id && browser.id !== row.device_id) {
|
|
3291
|
+
// Mark only the one-time challenge as duplicate, not the verified profile.
|
|
3292
|
+
await client.query(`UPDATE ota_device_registration_challenges SET completed_at=now() WHERE id=$1`, [row.challenge_id]);
|
|
3293
|
+
await client.query('COMMIT');
|
|
3294
|
+
res.status(409).type('html').send(enrollmentPage({ state: 'duplicate', name: browser.label, link: '/ota/device/apps' }));
|
|
3295
|
+
return;
|
|
3296
|
+
}
|
|
3297
|
+
const secret = deviceToken();
|
|
3298
|
+
await client.query('UPDATE ota_registered_tester_devices SET verified_at=now(),browser_credential_hash=$2 WHERE id=$1', [row.device_id, deviceTokenHash(secret)]);
|
|
3299
|
+
await client.query('UPDATE ota_device_registration_challenges SET completed_at=now() WHERE id=$1', [row.challenge_id]);
|
|
3300
|
+
await client.query('COMMIT');
|
|
3301
|
+
res.setHeader('Set-Cookie', deviceCookieHeader(row.device_id, secret));
|
|
3302
|
+
res.type('html').send(enrollmentPage({ state: 'approved', link: '/ota/device/apps' }));
|
|
3303
|
+
}
|
|
3304
|
+
catch (error) {
|
|
3305
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
3306
|
+
throw error;
|
|
3307
|
+
}
|
|
3308
|
+
finally {
|
|
3309
|
+
client.release();
|
|
3310
|
+
}
|
|
3311
|
+
});
|
|
3312
|
+
// Consolidate two profiles ONLY after the authenticated owner explicitly confirms
|
|
3313
|
+
// that both registrations represent the SAME phone. Labels are never evidence.
|
|
3314
|
+
// Preserve audit history and old OTA audiences via the permanent alias row.
|
|
3315
|
+
app.post('/mobile/tester-devices/consolidate', auth, async (req, res) => {
|
|
3316
|
+
const canonicalId = ensureUuid(String(req.body?.canonicalDeviceId || ''), 'Surviving device ID');
|
|
3317
|
+
const duplicateId = ensureUuid(String(req.body?.duplicateDeviceId || ''), 'Duplicate device ID');
|
|
3318
|
+
const reason = String(req.body?.reason || '').trim();
|
|
3319
|
+
if (canonicalId === duplicateId || req.body?.confirmSamePhysicalDevice !== true || reason.length < 12 || reason.length > 500) {
|
|
3320
|
+
res.status(400).json({ error: 'Choose distinct profiles, confirm same physical phone and provide a reason (12–500 characters).' });
|
|
3321
|
+
return;
|
|
3322
|
+
}
|
|
3323
|
+
const client = await pool.connect();
|
|
3324
|
+
try {
|
|
3325
|
+
await client.query('BEGIN');
|
|
3326
|
+
const rows = (await client.query(`SELECT id,label,verified_at,revoked_at,agent_public_key
|
|
3327
|
+
FROM ota_registered_tester_devices WHERE id=ANY($1::uuid[]) AND owner_user_id=$2
|
|
3328
|
+
ORDER BY id FOR UPDATE`, [[canonicalId, duplicateId], req.auth.id])).rows;
|
|
3329
|
+
const primary = rows.find((d) => d.id === canonicalId), duplicate = rows.find((d) => d.id === duplicateId);
|
|
3330
|
+
if (!primary || !duplicate || !primary.verified_at || !duplicate.verified_at || primary.revoked_at || duplicate.revoked_at) {
|
|
3331
|
+
await client.query('ROLLBACK');
|
|
3332
|
+
res.status(409).json({ error: 'Both profiles must be active, verified, and owned by your account.' });
|
|
3333
|
+
return;
|
|
3334
|
+
}
|
|
3335
|
+
// Do not silently override app-level revocations: caller must explicitly
|
|
3336
|
+
// reconcile access conflicts before consolidating device identities.
|
|
3337
|
+
const conflicts = (await client.query(`SELECT p.app_id FROM ota_device_app_grants p
|
|
3338
|
+
JOIN ota_device_app_grants d ON d.app_id=p.app_id
|
|
3339
|
+
WHERE p.device_id=$1 AND d.device_id=$2
|
|
3340
|
+
AND (p.revoked_at IS NULL) <> (d.revoked_at IS NULL)`, [canonicalId, duplicateId])).rows;
|
|
3341
|
+
if (conflicts.length) {
|
|
3342
|
+
await client.query('ROLLBACK');
|
|
3343
|
+
res.status(409).json({ error: 'App permission conflict between profiles. Reconcile revoked access before consolidating.', appIds: conflicts.map((g) => g.app_id) });
|
|
3344
|
+
return;
|
|
3345
|
+
}
|
|
3346
|
+
if (primary.agent_public_key && duplicate.agent_public_key && primary.agent_public_key !== duplicate.agent_public_key) {
|
|
3347
|
+
await client.query('ROLLBACK');
|
|
3348
|
+
res.status(409).json({ error: 'Profiles have different cryptographic agent keys. Cannot prove that they are the same device.' });
|
|
3349
|
+
return;
|
|
3350
|
+
}
|
|
3351
|
+
const aliased = (await client.query(`SELECT 1 FROM ota_tester_device_profile_aliases
|
|
3352
|
+
WHERE duplicate_device_id=ANY($1::uuid[]) OR canonical_device_id=ANY($1::uuid[])
|
|
3353
|
+
LIMIT 1`, [[canonicalId, duplicateId]])).rowCount;
|
|
3354
|
+
if (aliased) {
|
|
3355
|
+
await client.query('ROLLBACK');
|
|
3356
|
+
res.status(409).json({ error: 'One of these profiles was already consolidated. Choose two original active profiles.' });
|
|
3357
|
+
return;
|
|
3358
|
+
}
|
|
3359
|
+
// Preserve the union of active app grants, but never reactivate a revoked grant.
|
|
3360
|
+
await client.query(`INSERT INTO ota_device_app_grants(device_id,app_id,granted_by,granted_at,revoked_at)
|
|
3361
|
+
SELECT $1,app_id,granted_by,granted_at,NULL FROM ota_device_app_grants
|
|
3362
|
+
WHERE device_id=$2 AND revoked_at IS NULL
|
|
3363
|
+
ON CONFLICT(device_id,app_id) DO NOTHING`, [canonicalId, duplicateId]);
|
|
3364
|
+
const moved = (await client.query(`UPDATE ota_registered_device_installations
|
|
3365
|
+
SET device_id=$1 WHERE device_id=$2 RETURNING app_id,installation_id`, [canonicalId, duplicateId])).rows;
|
|
3366
|
+
await client.query(`UPDATE ota_android_scoped_tester_identities SET device_id=$1 WHERE device_id=$2`, [canonicalId, duplicateId]);
|
|
3367
|
+
if (!primary.agent_public_key && duplicate.agent_public_key) {
|
|
3368
|
+
await client.query(`UPDATE ota_registered_tester_devices
|
|
3369
|
+
SET agent_public_key=$2,agent_activated_at=now() WHERE id=$1`, [canonicalId, duplicate.agent_public_key]);
|
|
3370
|
+
}
|
|
3371
|
+
// Outstanding one-use links for the retired profile must not be redeemed.
|
|
3372
|
+
await client.query(`UPDATE ota_enrollment_invitations SET revoked_at=now()
|
|
3373
|
+
WHERE registered_device_id=$1 AND redeemed_at IS NULL AND revoked_at IS NULL`, [duplicateId]);
|
|
3374
|
+
await client.query(`INSERT INTO ota_tester_device_profile_aliases
|
|
3375
|
+
(duplicate_device_id,canonical_device_id,merged_by,reason) VALUES($1,$2,$3,$4)`, [duplicateId, canonicalId, req.auth.id, reason]);
|
|
3376
|
+
await client.query(`UPDATE ota_registered_tester_devices
|
|
3377
|
+
SET revoked_at=now(),browser_credential_hash=NULL,agent_public_key=NULL,agent_activated_at=NULL
|
|
3378
|
+
WHERE id=$1`, [duplicateId]);
|
|
3379
|
+
// Record who approved the merge IN THE SAME TRANSACTION. The action
|
|
3380
|
+
// must never succeed without its audit trail or return 500 after commit.
|
|
3381
|
+
await client.query(`INSERT INTO audit_logs(actor_id,action,resource_type,resource_id,reason,metadata)
|
|
3382
|
+
VALUES($1,'ota.device.consolidate','tester-device',$2,$3,$4)`, [req.auth.id, canonicalId, reason, { duplicateDeviceId: duplicateId, linkedInstallationsMoved: moved.length }]);
|
|
3383
|
+
await client.query('COMMIT');
|
|
3384
|
+
res.json({ ok: true, canonicalDeviceId: canonicalId, retiredDeviceId: duplicateId,
|
|
3385
|
+
linkedInstallationsMoved: moved.length, note: 'Existing release audiences preserved. Retired browser credential invalidated; use surviving registration for future browser pairing.' });
|
|
3386
|
+
}
|
|
3387
|
+
catch (error) {
|
|
3388
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
3389
|
+
throw error;
|
|
3390
|
+
}
|
|
3391
|
+
finally {
|
|
3392
|
+
client.release();
|
|
3393
|
+
}
|
|
3394
|
+
});
|
|
3395
|
+
app.delete('/mobile/tester-devices/:id', auth, async (req, res) => {
|
|
3396
|
+
const id = ensureUuid(routeParam(req.params.id), 'Registered device ID');
|
|
3397
|
+
const client = await pool.connect();
|
|
3398
|
+
try {
|
|
3399
|
+
await client.query('BEGIN');
|
|
3400
|
+
const owned = (await client.query(`UPDATE ota_registered_tester_devices SET revoked_at=now(),browser_credential_hash=NULL
|
|
3401
|
+
WHERE id=$1 AND owner_user_id=$2 AND revoked_at IS NULL RETURNING id`, [id, req.auth.id])).rows[0];
|
|
3402
|
+
if (!owned) {
|
|
3403
|
+
await client.query('ROLLBACK');
|
|
3404
|
+
res.status(404).json({ error: 'Registered device not found.' });
|
|
3405
|
+
return;
|
|
3406
|
+
}
|
|
3407
|
+
await client.query(`UPDATE ota_tester_installations ti SET revoked_at=now() FROM ota_registered_device_installations li
|
|
3408
|
+
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]);
|
|
3409
|
+
await client.query('COMMIT');
|
|
3410
|
+
await audit(req.auth.id, 'ota.device.revoke', 'tester-device', id, 'Revoke reusable tester profile and linked testing installs');
|
|
3411
|
+
res.status(204).end();
|
|
3412
|
+
}
|
|
3413
|
+
catch (error) {
|
|
3414
|
+
await client.query('ROLLBACK');
|
|
3415
|
+
throw error;
|
|
3416
|
+
}
|
|
3417
|
+
finally {
|
|
3418
|
+
client.release();
|
|
3419
|
+
}
|
|
3420
|
+
});
|
|
3421
|
+
// Browser-based one-time app pairing: verified phone => app association without scanning a second QR.
|
|
3422
|
+
// This is NOT silent cross-app hardware recognition. The phone owner approves each app.
|
|
3423
|
+
const verifiedOtaBrowser = async (cookieHeader) => {
|
|
3424
|
+
const cookie = readDeviceCookie(cookieHeader);
|
|
3425
|
+
if (!cookie)
|
|
3426
|
+
return null;
|
|
3427
|
+
const row = (await pool.query(`SELECT id,label,owner_user_id,verified_at,revoked_at,browser_credential_hash
|
|
3428
|
+
FROM ota_registered_tester_devices WHERE id=$1`, [cookie.id])).rows[0];
|
|
3429
|
+
return row && verifiedBrowserMatches(cookieHeader, row) ? row : null;
|
|
3430
|
+
};
|
|
3431
|
+
const devicePortalCsrf = (cookieHeader, appId) => {
|
|
3432
|
+
const cookie = readDeviceCookie(cookieHeader);
|
|
3433
|
+
return cookie ? deviceTokenHash(cookie.secret + '|indraq-device-app|' + appId) : '';
|
|
3434
|
+
};
|
|
3435
|
+
// First-party brand asset. Served from the same origin; no remote trackers.
|
|
3436
|
+
app.get('/ota/brand/indraq-logo.png', async (_req, res) => {
|
|
3437
|
+
res.setHeader('Cache-Control', 'public, max-age=86400');
|
|
3438
|
+
const file = resolve(process.cwd(), 'public', 'indraq-logo.png');
|
|
3439
|
+
res.type('png').send(await readFile(file));
|
|
3440
|
+
});
|
|
3441
|
+
const devicePortalHeaders = (res) => {
|
|
3442
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3443
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
3444
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
3445
|
+
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; base-uri 'none'");
|
|
3446
|
+
};
|
|
3447
|
+
// Reconnect a freshly installed (or reinstalled) app through the *previously verified*
|
|
3448
|
+
// phone browser. Unlike ANDROID_ID/IDFV, a browser credential is possession proof.
|
|
3449
|
+
// The app opens this HTTPS address once; no new QR is issued. Browsers may require
|
|
3450
|
+
// the user to tap Open App to complete their OS-level deep-link handoff.
|
|
3451
|
+
app.get('/ota/device/reconnect/:appId', async (req, res) => {
|
|
3452
|
+
devicePortalHeaders(res);
|
|
3453
|
+
const appId = ensureUuid(routeParam(req.params.appId), 'Mobile app ID');
|
|
3454
|
+
const state = typeof req.query.state === 'string' ? req.query.state : '';
|
|
3455
|
+
if (!/^[A-Za-z0-9_-]{12,128}$/.test(state)) {
|
|
3456
|
+
res.status(400).type('html').send(reconnectPage({ state: 'denied' }));
|
|
3457
|
+
return;
|
|
3458
|
+
}
|
|
3459
|
+
const device = await verifiedOtaBrowser(req.headers.cookie);
|
|
3460
|
+
if (!device) {
|
|
3461
|
+
res.status(403).type('html').send(reconnectPage({ state: 'denied' }));
|
|
3462
|
+
return;
|
|
3463
|
+
}
|
|
3464
|
+
const row = (await pool.query(`SELECT ma.id,ma.app_name,ma.enrollment_scheme FROM mobile_apps ma
|
|
3465
|
+
JOIN projects p ON p.id=ma.project_id
|
|
3466
|
+
LEFT JOIN project_members pm ON pm.project_id=p.id AND pm.user_id=$3
|
|
3467
|
+
JOIN ota_device_app_grants g ON g.app_id=ma.id AND g.device_id=$2 AND g.revoked_at IS NULL
|
|
3468
|
+
WHERE ma.id=$1 AND p.archived_at IS NULL AND (p.created_by=$3 OR pm.user_id=$3)`, [appId, device.id, device.owner_user_id])).rows[0];
|
|
3469
|
+
if (!row || !enrollmentSchemePattern.test(String(row.enrollment_scheme || ''))) {
|
|
3470
|
+
res.status(403).type('html').send(reconnectPage({ state: 'unavailable' }));
|
|
3471
|
+
return;
|
|
3472
|
+
}
|
|
3473
|
+
// Bound the number of outstanding invitations per device/app; a malicious
|
|
3474
|
+
// third-party web page must not be able to create unlimited pending records.
|
|
3475
|
+
const recent = await pool.query(`SELECT count(*)::int count FROM ota_enrollment_invitations
|
|
3476
|
+
WHERE registered_device_id=$1 AND app_id=$2 AND created_at>now()-interval '10 minutes'`, [device.id, appId]);
|
|
3477
|
+
if (Number(recent.rows[0]?.count || 0) >= 10) {
|
|
3478
|
+
res.status(429).type('html').send(reconnectPage({ state: 'unavailable' }));
|
|
3479
|
+
return;
|
|
3480
|
+
}
|
|
3481
|
+
const token = deviceToken();
|
|
3482
|
+
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)
|
|
3483
|
+
VALUES($1,$2,$3,$4,$5,now()+interval '5 minutes',$6,now())`, [appId, hashEnrollmentToken(token), device.label, row.enrollment_scheme, device.owner_user_id, device.id]);
|
|
3484
|
+
await audit(device.owner_user_id, 'ota.device.app.reconnect', 'mobile-app', appId, 'Verified browser issued installation reconnect token', { deviceId: device.id });
|
|
3485
|
+
const link = `${row.enrollment_scheme}://indraq-enroll?token=${token}&state=${encodeURIComponent(state)}`;
|
|
3486
|
+
res.type('html').send(reconnectPage({ state: 'open', app: row.app_name, link }));
|
|
3487
|
+
});
|
|
3488
|
+
app.get('/ota/device/apps', async (req, res) => {
|
|
3489
|
+
devicePortalHeaders(res);
|
|
3490
|
+
const device = await verifiedOtaBrowser(req.headers.cookie);
|
|
3491
|
+
if (!device) {
|
|
3492
|
+
res.status(403).type('html').send(enrollmentPage({ state: 'denied' }));
|
|
3493
|
+
return;
|
|
3494
|
+
}
|
|
3495
|
+
const rows = (await pool.query(`SELECT DISTINCT ma.id,ma.app_name,ma.enrollment_scheme
|
|
3496
|
+
FROM mobile_apps ma JOIN projects p ON p.id=ma.project_id
|
|
3497
|
+
JOIN ota_device_app_grants g ON g.app_id=ma.id AND g.device_id=$2 AND g.revoked_at IS NULL
|
|
3498
|
+
LEFT JOIN project_members pm ON pm.project_id=p.id AND pm.user_id=$1
|
|
3499
|
+
WHERE p.archived_at IS NULL AND (p.created_by=$1 OR pm.user_id=$1)
|
|
3500
|
+
ORDER BY ma.app_name LIMIT 150`, [device.owner_user_id, device.id])).rows;
|
|
3501
|
+
res.type('html').send(devicePortalPage({ deviceLabel: device.label, apps: rows.map(a => ({
|
|
3502
|
+
id: a.id, name: a.app_name, scheme: a.enrollment_scheme || null, csrf: devicePortalCsrf(req.headers.cookie, a.id)
|
|
3503
|
+
})) }));
|
|
3504
|
+
});
|
|
3505
|
+
app.post('/ota/device/apps/:appId/link', express.urlencoded({ extended: false, limit: '10kb' }), async (req, res) => {
|
|
3506
|
+
devicePortalHeaders(res);
|
|
3507
|
+
const device = await verifiedOtaBrowser(req.headers.cookie);
|
|
3508
|
+
if (!device) {
|
|
3509
|
+
res.status(403).type('html').send(enrollmentPage({ state: 'denied' }));
|
|
3510
|
+
return;
|
|
3511
|
+
}
|
|
3512
|
+
const appId = ensureUuid(routeParam(req.params.appId), 'Mobile app ID');
|
|
3513
|
+
const expected = devicePortalCsrf(req.headers.cookie, appId);
|
|
3514
|
+
const received = String(req.body?.csrf || '');
|
|
3515
|
+
const a = Buffer.from(expected, 'hex'), b = Buffer.from(received, 'hex');
|
|
3516
|
+
if (a.length !== 32 || b.length !== 32 || !timingSafeEqual(a, b)) {
|
|
3517
|
+
res.status(403).type('html').send(enrollmentPage({ state: 'denied' }));
|
|
3518
|
+
return;
|
|
3519
|
+
}
|
|
3520
|
+
const appRow = (await pool.query(`SELECT ma.id,ma.app_name,ma.enrollment_scheme FROM mobile_apps ma
|
|
3521
|
+
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
|
|
3522
|
+
WHERE ma.id=$1 AND p.archived_at IS NULL AND (p.created_by=$2 OR pm.user_id=$2)`, [appId, device.owner_user_id])).rows[0];
|
|
3523
|
+
if (!appRow || !enrollmentSchemePattern.test(String(appRow.enrollment_scheme || ''))) {
|
|
3524
|
+
res.status(404).type('html').send(enrollmentPage({ state: 'expired' }));
|
|
3525
|
+
return;
|
|
3526
|
+
}
|
|
3527
|
+
const granted = await pool.query(`SELECT 1 FROM ota_device_app_grants
|
|
3528
|
+
WHERE app_id=$1 AND device_id=$2 AND revoked_at IS NULL`, [appId, device.id]);
|
|
3529
|
+
if (!granted.rowCount) {
|
|
3530
|
+
res.status(403).type('html').send(enrollmentPage({ state: 'denied' }));
|
|
3531
|
+
return;
|
|
3532
|
+
}
|
|
3533
|
+
const token = deviceToken();
|
|
3534
|
+
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)
|
|
3535
|
+
VALUES($1,$2,$3,$4,$5,now()+interval '15 minutes',$6,now())`, [appId, hashEnrollmentToken(token), device.label, appRow.enrollment_scheme, device.owner_user_id, device.id]);
|
|
3536
|
+
await audit(device.owner_user_id, 'ota.device.app.link', 'mobile-app', appId, 'Verified browser approved app pairing', { deviceId: device.id });
|
|
3537
|
+
res.type('html').send(enrollmentPage({ state: 'open', app: appRow.app_name,
|
|
3538
|
+
link: `${appRow.enrollment_scheme}://indraq-enroll?token=${token}` }));
|
|
3539
|
+
});
|
|
3540
|
+
// One-time verified-browser activation of a persistent Android Tester Agent.
|
|
3541
|
+
// The agent holds an Android Keystore private key; the browser only grants initial consent.
|
|
3542
|
+
app.get('/ota/device/agent/setup', async (req, res) => {
|
|
3543
|
+
devicePortalHeaders(res);
|
|
3544
|
+
const device = await verifiedOtaBrowser(req.headers.cookie);
|
|
3545
|
+
if (!device) {
|
|
3546
|
+
res.status(403).type('text/plain').send('Verify this device in IndraQ Cloud first.');
|
|
3547
|
+
return;
|
|
3548
|
+
}
|
|
3549
|
+
const csrf = devicePortalCsrf(req.headers.cookie, 'indraq-agent-setup');
|
|
3550
|
+
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>`);
|
|
3551
|
+
});
|
|
3552
|
+
app.post('/ota/device/agent/setup', express.urlencoded({ extended: false, limit: '10kb' }), async (req, res) => {
|
|
3553
|
+
devicePortalHeaders(res);
|
|
3554
|
+
const device = await verifiedOtaBrowser(req.headers.cookie);
|
|
3555
|
+
if (!device) {
|
|
3556
|
+
res.status(403).type('text/plain').send('Device not verified.');
|
|
3557
|
+
return;
|
|
3558
|
+
}
|
|
3559
|
+
const expected = devicePortalCsrf(req.headers.cookie, 'indraq-agent-setup');
|
|
3560
|
+
const a = Buffer.from(expected, 'hex'), b = Buffer.from(String(req.body?.csrf || ''), 'hex');
|
|
3561
|
+
if (a.length !== 32 || b.length !== 32 || !timingSafeEqual(a, b)) {
|
|
3562
|
+
res.status(403).type('text/plain').send('Invalid request.');
|
|
3563
|
+
return;
|
|
3564
|
+
}
|
|
3565
|
+
const token = deviceToken();
|
|
3566
|
+
await pool.query(`INSERT INTO ota_device_agent_activations(device_id,token_hash,expires_at)
|
|
3567
|
+
VALUES($1,$2,now()+interval '5 minutes')`, [device.id, hashEnrollmentToken(token)]);
|
|
3568
|
+
const link = `indraqtester://activate?token=${token}`;
|
|
3569
|
+
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>`);
|
|
3570
|
+
});
|
|
3571
|
+
const agentPayload = (id, appId, installationId, androidPackage, nonce) => ['indraq-agent-v1', id, appId, installationId, androidPackage, nonce].join('\n');
|
|
3572
|
+
const agentSignatureValid = (publicKey, payload, signature) => {
|
|
3573
|
+
try {
|
|
3574
|
+
if (!/^[A-Za-z0-9+/]{100,1024}={0,2}$/.test(signature))
|
|
3575
|
+
return false;
|
|
3576
|
+
const verifier = createVerify('RSA-SHA256');
|
|
3577
|
+
verifier.update(payload, 'utf8');
|
|
3578
|
+
verifier.end();
|
|
3579
|
+
return verifier.verify(publicKey, Buffer.from(signature, 'base64'));
|
|
3580
|
+
}
|
|
3581
|
+
catch {
|
|
3582
|
+
return false;
|
|
3583
|
+
}
|
|
3584
|
+
};
|
|
3585
|
+
// Activation is authorized by the pre-existing registered device's verified browser.
|
|
3586
|
+
// No device identifier, IP address, user-agent string, or APK-embedded secret grants access.
|
|
3587
|
+
app.post('/ota/v1/agent/activate', async (req, res) => {
|
|
3588
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3589
|
+
const token = String(req.body?.token || '');
|
|
3590
|
+
const key = String(req.body?.publicKey || ''); // base64 DER SubjectPublicKeyInfo
|
|
3591
|
+
if (!enrollmentTokenPattern.test(token) || key.length < 300 || key.length > 4096 || !/^[A-Za-z0-9+/=]+$/.test(key)) {
|
|
3592
|
+
res.status(400).json({ error: 'Invalid agent activation data.' });
|
|
3593
|
+
return;
|
|
3594
|
+
}
|
|
3595
|
+
let pem = '';
|
|
3596
|
+
try {
|
|
3597
|
+
const pub = createPublicKey({ key: Buffer.from(key, 'base64'), format: 'der', type: 'spki' });
|
|
3598
|
+
if (pub.asymmetricKeyType !== 'rsa' || Number(pub.asymmetricKeyDetails?.modulusLength || 0) < 2048)
|
|
3599
|
+
throw new Error('RSA key required');
|
|
3600
|
+
pem = pub.export({ type: 'spki', format: 'pem' }).toString();
|
|
3601
|
+
}
|
|
3602
|
+
catch {
|
|
3603
|
+
res.status(400).json({ error: 'Invalid Android agent public key.' });
|
|
3604
|
+
return;
|
|
3605
|
+
}
|
|
3606
|
+
const client = await pool.connect();
|
|
3607
|
+
try {
|
|
3608
|
+
await client.query('BEGIN');
|
|
3609
|
+
const challenge = (await client.query(`SELECT a.id,a.device_id FROM ota_device_agent_activations a
|
|
3610
|
+
JOIN ota_registered_tester_devices d ON d.id=a.device_id
|
|
3611
|
+
WHERE a.token_hash=$1 AND a.expires_at>now() AND a.redeemed_at IS NULL
|
|
3612
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NOT NULL FOR UPDATE OF a`, [hashEnrollmentToken(token)])).rows[0];
|
|
3613
|
+
if (!challenge) {
|
|
3614
|
+
await client.query('ROLLBACK');
|
|
3615
|
+
res.status(410).json({ error: 'Activation expired or already used.' });
|
|
3616
|
+
return;
|
|
3617
|
+
}
|
|
3618
|
+
await client.query(`UPDATE ota_registered_tester_devices SET agent_public_key=$2,agent_activated_at=now()
|
|
3619
|
+
WHERE id=$1`, [challenge.device_id, pem]);
|
|
3620
|
+
await client.query('UPDATE ota_device_agent_activations SET redeemed_at=now() WHERE id=$1', [challenge.id]);
|
|
3621
|
+
await client.query('COMMIT');
|
|
3622
|
+
res.json({ ok: true, deviceId: challenge.device_id });
|
|
3623
|
+
}
|
|
3624
|
+
catch (e) {
|
|
3625
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
3626
|
+
throw e;
|
|
3627
|
+
}
|
|
3628
|
+
finally {
|
|
3629
|
+
client.release();
|
|
3630
|
+
}
|
|
3631
|
+
});
|
|
3632
|
+
app.get('/ota/v1/agent/capabilities/:updatePath', async (req, res) => {
|
|
3633
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3634
|
+
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
3635
|
+
if (!appRow) {
|
|
3636
|
+
res.status(404).json({ error: 'Unknown app.' });
|
|
3637
|
+
return;
|
|
3638
|
+
}
|
|
3639
|
+
const active = await pool.query(`SELECT count(*)::int count FROM ota_registered_tester_devices d
|
|
3640
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=$1 AND g.revoked_at IS NULL
|
|
3641
|
+
WHERE d.revoked_at IS NULL AND d.verified_at IS NOT NULL AND d.agent_public_key IS NOT NULL`, [appRow.id]);
|
|
3642
|
+
res.json({ supported: !!appRow.android_package, appId: appRow.id, activatedDevices: Number(active.rows[0]?.count || 0) });
|
|
3643
|
+
});
|
|
3644
|
+
// Challenge is only signed by the separately-installed agent's private key.
|
|
3645
|
+
app.post('/ota/v1/agent/challenge/:updatePath', async (req, res) => {
|
|
3646
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3647
|
+
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
3648
|
+
if (!appRow) {
|
|
3649
|
+
res.status(404).json({ error: 'Unknown application.' });
|
|
3650
|
+
return;
|
|
3651
|
+
}
|
|
3652
|
+
const installationId = String(req.body?.installationId || '');
|
|
3653
|
+
if (!/^[A-Za-z0-9_-]{12,200}$/.test(installationId) || !appRow.android_package) {
|
|
3654
|
+
res.status(400).json({ error: 'Installation or Android package not configured.' });
|
|
3655
|
+
return;
|
|
3656
|
+
}
|
|
3657
|
+
const installed = await pool.query(`SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2 AND platform='android'`, [appRow.id, installationId]);
|
|
3658
|
+
if (!installed.rowCount) {
|
|
3659
|
+
res.status(409).json({ error: 'Launch the release app online to register installation first.' });
|
|
3660
|
+
return;
|
|
3661
|
+
}
|
|
3662
|
+
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]);
|
|
3663
|
+
if (Number(recent.rows[0]?.count || 0) >= 6) {
|
|
3664
|
+
res.status(429).json({ error: 'Too many agent challenges; retry later.' });
|
|
3665
|
+
return;
|
|
3666
|
+
}
|
|
3667
|
+
const nonce = randomBytes(32).toString('base64url');
|
|
3668
|
+
const row = (await pool.query(`INSERT INTO ota_device_agent_challenges(app_id,installation_id,nonce,expires_at)
|
|
3669
|
+
VALUES($1,$2,$3,now()+interval '90 seconds') RETURNING id`, [appRow.id, installationId, nonce])).rows[0];
|
|
3670
|
+
res.json({ challengeId: row.id, payload: agentPayload(row.id, appRow.id, installationId, appRow.android_package, nonce) });
|
|
3671
|
+
});
|
|
3672
|
+
app.post('/ota/v1/agent/redeem/:updatePath', async (req, res) => {
|
|
3673
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
3674
|
+
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
3675
|
+
if (!appRow) {
|
|
3676
|
+
res.status(404).json({ error: 'Unknown application.' });
|
|
3677
|
+
return;
|
|
3678
|
+
}
|
|
3679
|
+
const challengeId = String(req.body?.challengeId || '');
|
|
3680
|
+
const deviceId = String(req.body?.deviceId || '');
|
|
3681
|
+
const signature = String(req.body?.signature || '');
|
|
3682
|
+
const installationId = String(req.body?.installationId || '');
|
|
3683
|
+
if (!/^[0-9a-f-]{36}$/i.test(challengeId) || !/^[0-9a-f-]{36}$/i.test(deviceId) ||
|
|
3684
|
+
!/^[A-Za-z0-9_-]{12,200}$/.test(installationId) || signature.length > 2048) {
|
|
3685
|
+
res.status(400).json({ error: 'Invalid agent enrollment request.' });
|
|
3686
|
+
return;
|
|
3687
|
+
}
|
|
3688
|
+
const client = await pool.connect();
|
|
3689
|
+
try {
|
|
3690
|
+
await client.query('BEGIN');
|
|
3691
|
+
const challenge = (await client.query(`SELECT * FROM ota_device_agent_challenges
|
|
3692
|
+
WHERE id=$1 AND app_id=$2 AND installation_id=$3 AND expires_at>now() AND redeemed_at IS NULL FOR UPDATE`, [challengeId, appRow.id, installationId])).rows[0];
|
|
3693
|
+
if (!challenge) {
|
|
3694
|
+
await client.query('ROLLBACK');
|
|
3695
|
+
res.status(410).json({ error: 'Challenge expired or already used.' });
|
|
3696
|
+
return;
|
|
3697
|
+
}
|
|
3698
|
+
const device = (await client.query(`SELECT d.id,d.label,d.owner_user_id,d.agent_public_key
|
|
3699
|
+
FROM ota_registered_tester_devices d
|
|
3700
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=$2 AND g.revoked_at IS NULL
|
|
3701
|
+
WHERE d.id=$1 AND d.verified_at IS NOT NULL AND d.revoked_at IS NULL FOR UPDATE OF d`, [deviceId, appRow.id])).rows[0];
|
|
3702
|
+
if (!device?.agent_public_key || !agentSignatureValid(device.agent_public_key, agentPayload(challenge.id, appRow.id, installationId, appRow.android_package, challenge.nonce), signature)) {
|
|
3703
|
+
await client.query('ROLLBACK');
|
|
3704
|
+
res.status(403).json({ error: 'Device agent signature invalid, unavailable, or app access revoked.' });
|
|
3705
|
+
return;
|
|
3706
|
+
}
|
|
3707
|
+
const installed = await client.query(`SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2 AND platform='android'`, [appRow.id, installationId]);
|
|
3708
|
+
if (!installed.rowCount) {
|
|
3709
|
+
await client.query('ROLLBACK');
|
|
3710
|
+
res.status(409).json({ error: 'Installation not yet registered.' });
|
|
3711
|
+
return;
|
|
3712
|
+
}
|
|
3713
|
+
await client.query(`INSERT INTO ota_tester_installations(app_id,installation_id,label,enrolled_by,revoked_at)
|
|
3714
|
+
VALUES($1,$2,$3,$4,NULL) ON CONFLICT(app_id,installation_id) DO UPDATE
|
|
3715
|
+
SET label=excluded.label,enrolled_by=excluded.enrolled_by,enrolled_at=now(),revoked_at=NULL`, [appRow.id, installationId, device.label, device.owner_user_id]);
|
|
3716
|
+
await client.query(`INSERT INTO ota_registered_device_installations(device_id,app_id,installation_id)
|
|
3717
|
+
VALUES($1,$2,$3) ON CONFLICT(app_id,installation_id) DO UPDATE SET device_id=excluded.device_id,linked_at=now()`, [device.id, appRow.id, installationId]);
|
|
3718
|
+
await client.query('UPDATE ota_device_agent_challenges SET redeemed_at=now() WHERE id=$1', [challengeId]);
|
|
3719
|
+
await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,metadata)
|
|
3720
|
+
VALUES($1,$2,'device_enrolled',$3)`, [appRow.id, installationId, { source: 'android_tester_agent' }]);
|
|
3721
|
+
await client.query('COMMIT');
|
|
3722
|
+
res.json({ ok: true, enrolled: true, deviceLabel: device.label });
|
|
3723
|
+
}
|
|
3724
|
+
catch (e) {
|
|
3725
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
3726
|
+
throw e;
|
|
3727
|
+
}
|
|
3728
|
+
finally {
|
|
3729
|
+
client.release();
|
|
3730
|
+
}
|
|
3731
|
+
});
|
|
3070
3732
|
app.get('/mobile/apps', auth, async (req, res) => {
|
|
3071
3733
|
// All project members, including normal users with VIEW, may select their own app.
|
|
3072
3734
|
const rows = (await pool.query(`SELECT ma.id,ma.project_id,ma.app_name,ma.project_type,ma.enrollment_scheme,p.name project_name
|
|
@@ -3076,6 +3738,98 @@ app.get('/mobile/apps', auth, async (req, res) => {
|
|
|
3076
3738
|
ORDER BY p.name,ma.app_name LIMIT 500`, [req.auth.id, req.auth.role])).rows;
|
|
3077
3739
|
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 })));
|
|
3078
3740
|
});
|
|
3741
|
+
// Assign already-registered phones during a build, or later without re-enrolling a phone.
|
|
3742
|
+
// This grants app ACCESS only. A new sandbox must still prove possession to bind its installation.
|
|
3743
|
+
app.get('/mobile/apps/:appId/device-grants', auth, async (req, res) => {
|
|
3744
|
+
const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
|
|
3745
|
+
if (!appRow) {
|
|
3746
|
+
res.status(404).json({ error: 'Mobile app not found or access denied.' });
|
|
3747
|
+
return;
|
|
3748
|
+
}
|
|
3749
|
+
const rows = (await pool.query(`SELECT d.id device_id,d.label,d.verified_at,g.granted_at,
|
|
3750
|
+
(SELECT count(*)::int FROM ota_registered_device_installations li
|
|
3751
|
+
WHERE li.device_id=d.id AND li.app_id=$1) linked_installations,
|
|
3752
|
+
ARRAY(SELECT DISTINCT i.runtime_version FROM ota_registered_device_installations li
|
|
3753
|
+
JOIN ota_installations i ON i.app_id=li.app_id AND i.installation_id=li.installation_id
|
|
3754
|
+
WHERE li.device_id=d.id AND li.app_id=$1 AND i.runtime_version IS NOT NULL
|
|
3755
|
+
ORDER BY i.runtime_version) linked_runtimes
|
|
3756
|
+
FROM ota_device_app_grants g JOIN ota_registered_tester_devices d ON d.id=g.device_id
|
|
3757
|
+
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;
|
|
3758
|
+
res.json(rows);
|
|
3759
|
+
});
|
|
3760
|
+
app.post('/mobile/apps/:appId/device-grants', auth, async (req, res) => {
|
|
3761
|
+
const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth, true);
|
|
3762
|
+
if (!appRow) {
|
|
3763
|
+
res.status(404).json({ error: 'Mobile app not found or WRITE access denied.' });
|
|
3764
|
+
return;
|
|
3765
|
+
}
|
|
3766
|
+
const deviceIds = requestedDeviceIds(req.body?.deviceIds);
|
|
3767
|
+
const client = await pool.connect();
|
|
3768
|
+
try {
|
|
3769
|
+
await client.query('BEGIN');
|
|
3770
|
+
// Lock verified device rows until grants are committed, so revocation
|
|
3771
|
+
// cannot race a grant and re-enable a revoked phone's existing installs.
|
|
3772
|
+
const verified = await client.query(`SELECT id FROM ota_registered_tester_devices
|
|
3773
|
+
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]);
|
|
3774
|
+
if (verified.rowCount !== deviceIds.length) {
|
|
3775
|
+
await client.query('ROLLBACK');
|
|
3776
|
+
res.status(403).json({ error: 'All selected phones must be QR-verified, active and owned by your account.' });
|
|
3777
|
+
return;
|
|
3778
|
+
}
|
|
3779
|
+
for (const deviceId of deviceIds) {
|
|
3780
|
+
await client.query(`INSERT INTO ota_device_app_grants(device_id,app_id,granted_by)
|
|
3781
|
+
VALUES($1,$2,$3) ON CONFLICT(device_id,app_id) DO UPDATE
|
|
3782
|
+
SET revoked_at=NULL,granted_at=now(),granted_by=EXCLUDED.granted_by`, [deviceId, appRow.id, req.auth.id]);
|
|
3783
|
+
// Restore pre-existing, securely linked installations; never attach unknown installations.
|
|
3784
|
+
await client.query(`UPDATE ota_tester_installations t SET revoked_at=NULL,enrolled_at=now()
|
|
3785
|
+
FROM ota_registered_device_installations l
|
|
3786
|
+
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]);
|
|
3787
|
+
}
|
|
3788
|
+
await client.query('COMMIT');
|
|
3789
|
+
}
|
|
3790
|
+
catch (error) {
|
|
3791
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
3792
|
+
throw error;
|
|
3793
|
+
}
|
|
3794
|
+
finally {
|
|
3795
|
+
client.release();
|
|
3796
|
+
}
|
|
3797
|
+
await audit(req.auth.id, 'ota.device.app.grant', 'mobile-app', appRow.id, 'Grant selected verified phones access to app', { deviceIds });
|
|
3798
|
+
res.json({ ok: true, appId: appRow.id, grantedDeviceIds: deviceIds, note: 'Existing linked installs are enabled. New app installs still need secure one-time pairing.' });
|
|
3799
|
+
});
|
|
3800
|
+
app.delete('/mobile/apps/:appId/device-grants/:deviceId', auth, async (req, res) => {
|
|
3801
|
+
const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth, true);
|
|
3802
|
+
if (!appRow) {
|
|
3803
|
+
res.status(404).json({ error: 'Mobile app not found or WRITE access denied.' });
|
|
3804
|
+
return;
|
|
3805
|
+
}
|
|
3806
|
+
const deviceId = ensureUuid(routeParam(req.params.deviceId), 'Registered device ID');
|
|
3807
|
+
const client = await pool.connect();
|
|
3808
|
+
try {
|
|
3809
|
+
await client.query('BEGIN');
|
|
3810
|
+
const existing = await client.query(`UPDATE ota_device_app_grants g SET revoked_at=now()
|
|
3811
|
+
FROM ota_registered_tester_devices d WHERE g.device_id=$1 AND g.app_id=$2
|
|
3812
|
+
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]);
|
|
3813
|
+
if (!existing.rowCount) {
|
|
3814
|
+
await client.query('ROLLBACK');
|
|
3815
|
+
res.status(404).json({ error: 'Active device access grant not found.' });
|
|
3816
|
+
return;
|
|
3817
|
+
}
|
|
3818
|
+
await client.query(`UPDATE ota_tester_installations t SET revoked_at=now()
|
|
3819
|
+
FROM ota_registered_device_installations l WHERE l.device_id=$1 AND l.app_id=$2
|
|
3820
|
+
AND t.app_id=l.app_id AND t.installation_id=l.installation_id AND t.revoked_at IS NULL`, [deviceId, appRow.id]);
|
|
3821
|
+
await client.query('COMMIT');
|
|
3822
|
+
}
|
|
3823
|
+
catch (error) {
|
|
3824
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
3825
|
+
throw error;
|
|
3826
|
+
}
|
|
3827
|
+
finally {
|
|
3828
|
+
client.release();
|
|
3829
|
+
}
|
|
3830
|
+
await audit(req.auth.id, 'ota.device.app.revoke', 'mobile-app', appRow.id, 'Revoke tester-device app authorization', { deviceId });
|
|
3831
|
+
res.status(204).end();
|
|
3832
|
+
});
|
|
3079
3833
|
app.get('/mobile/apps/:appId/installations', auth, async (req, res) => {
|
|
3080
3834
|
const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
|
|
3081
3835
|
if (!appRow) {
|
|
@@ -3143,6 +3897,19 @@ app.post('/mobile/apps/:appId/enrollments', auth, async (req, res) => {
|
|
|
3143
3897
|
return;
|
|
3144
3898
|
}
|
|
3145
3899
|
const groupId = req.body?.groupId ? ensureUuid(String(req.body.groupId), 'Tester group ID') : null;
|
|
3900
|
+
const registeredDeviceId = req.body?.registeredDeviceId ? ensureUuid(String(req.body.registeredDeviceId), 'Registered device ID') : null;
|
|
3901
|
+
if (registeredDeviceId) {
|
|
3902
|
+
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]);
|
|
3903
|
+
if (!owned.rowCount) {
|
|
3904
|
+
res.status(403).json({ error: 'Registered device must be owned, QR-verified and not revoked.' });
|
|
3905
|
+
return;
|
|
3906
|
+
}
|
|
3907
|
+
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]);
|
|
3908
|
+
if (!permitted.rowCount) {
|
|
3909
|
+
res.status(403).json({ error: 'Grant this device access to the app before creating a pairing invitation.' });
|
|
3910
|
+
return;
|
|
3911
|
+
}
|
|
3912
|
+
}
|
|
3146
3913
|
if (groupId) {
|
|
3147
3914
|
const exists = await pool.query('SELECT 1 FROM ota_tester_groups WHERE id=$1 AND app_id=$2', [groupId, appRow.id]);
|
|
3148
3915
|
if (!exists.rowCount) {
|
|
@@ -3151,9 +3918,9 @@ app.post('/mobile/apps/:appId/enrollments', auth, async (req, res) => {
|
|
|
3151
3918
|
}
|
|
3152
3919
|
}
|
|
3153
3920
|
const token = randomBytes(32).toString('base64url');
|
|
3154
|
-
const row = (await pool.query(`INSERT INTO ota_enrollment_invitations(app_id,token_hash,label,group_id,app_scheme,created_by,expires_at)
|
|
3155
|
-
VALUES($1,$2,$3,$4,$5,$6,now()+($7::integer * interval '1 minute')) RETURNING id,expires_at`, [appRow.id, hashEnrollmentToken(token), label, groupId, scheme, req.auth.id, ttlMinutes])).rows[0];
|
|
3156
|
-
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 });
|
|
3921
|
+
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)
|
|
3922
|
+
VALUES($1,$2,$3,$4,$5,$6,now()+($7::integer * interval '1 minute'),$8) RETURNING id,expires_at`, [appRow.id, hashEnrollmentToken(token), label, groupId, scheme, req.auth.id, ttlMinutes, registeredDeviceId])).rows[0];
|
|
3923
|
+
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 });
|
|
3157
3924
|
res.setHeader('Cache-Control', 'no-store');
|
|
3158
3925
|
res.status(201).json({ id: row.id, appName: appRow.app_name, label, groupId, expiresAt: row.expires_at,
|
|
3159
3926
|
enrollmentUrl: `${publicApiUrl}/ota/enroll/${token}` });
|
|
@@ -3164,7 +3931,7 @@ app.get('/mobile/apps/:appId/enrollments', auth, async (req, res) => {
|
|
|
3164
3931
|
res.status(404).json({ error: 'Mobile app not found or access denied.' });
|
|
3165
3932
|
return;
|
|
3166
3933
|
}
|
|
3167
|
-
const rows = (await pool.query(`SELECT id,label,group_id,created_at,expires_at,redeemed_at,redeemed_installation_id,revoked_at
|
|
3934
|
+
const rows = (await pool.query(`SELECT id,label,group_id,registered_device_id,created_at,expires_at,redeemed_at,redeemed_installation_id,revoked_at
|
|
3168
3935
|
FROM ota_enrollment_invitations WHERE app_id=$1 ORDER BY created_at DESC LIMIT 100`, [appRow.id])).rows;
|
|
3169
3936
|
res.json(rows);
|
|
3170
3937
|
});
|
|
@@ -3200,26 +3967,73 @@ app.delete('/mobile/apps/:appId/testers/:installationId', auth, async (req, res)
|
|
|
3200
3967
|
await audit(req.auth.id, 'ota.testers.revoke', 'mobile-app', appRow.id, 'Revoke OTA tester enrollment', { installationId });
|
|
3201
3968
|
res.status(204).end();
|
|
3202
3969
|
});
|
|
3203
|
-
|
|
3204
|
-
|
|
3970
|
+
const escapeOtaHtml = (v) => String(v).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] || c));
|
|
3971
|
+
const enrollmentLanding = async (token, cookieHeader) => {
|
|
3972
|
+
const item = (await pool.query(`SELECT e.app_scheme,ma.app_name,e.label,e.registered_device_id,e.browser_approved_at,
|
|
3973
|
+
d.id device_id,d.verified_at,d.revoked_at,d.browser_credential_hash
|
|
3974
|
+
FROM ota_enrollment_invitations e JOIN mobile_apps ma ON ma.id=e.app_id
|
|
3975
|
+
LEFT JOIN ota_registered_tester_devices d ON d.id=e.registered_device_id
|
|
3976
|
+
WHERE e.token_hash=$1 AND e.expires_at>now() AND e.revoked_at IS NULL AND e.redeemed_at IS NULL`, [hashEnrollmentToken(token)])).rows[0];
|
|
3977
|
+
if (!item)
|
|
3978
|
+
return null;
|
|
3979
|
+
const authorized = !item.registered_device_id ||
|
|
3980
|
+
(item.device_id && verifiedBrowserMatches(cookieHeader, { id: item.device_id, verified_at: item.verified_at,
|
|
3981
|
+
revoked_at: item.revoked_at, browser_credential_hash: item.browser_credential_hash }));
|
|
3982
|
+
return { item, authorized: Boolean(authorized) };
|
|
3983
|
+
};
|
|
3984
|
+
const publicEnrollmentHeaders = (res) => {
|
|
3205
3985
|
res.setHeader('Cache-Control', 'no-store');
|
|
3206
3986
|
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
3207
|
-
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline';
|
|
3987
|
+
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; base-uri 'none'");
|
|
3988
|
+
};
|
|
3989
|
+
app.get('/ota/enroll/:token', async (req, res) => {
|
|
3990
|
+
const token = routeParam(req.params.token);
|
|
3991
|
+
publicEnrollmentHeaders(res);
|
|
3208
3992
|
if (!enrollmentTokenPattern.test(token)) {
|
|
3209
3993
|
res.status(404).type('text/plain').send('Invalid enrollment invitation.');
|
|
3210
3994
|
return;
|
|
3211
3995
|
}
|
|
3212
|
-
const
|
|
3213
|
-
|
|
3214
|
-
AND e.revoked_at IS NULL AND e.redeemed_at IS NULL`, [hashEnrollmentToken(token)])).rows[0];
|
|
3215
|
-
if (!item) {
|
|
3996
|
+
const found = await enrollmentLanding(token, req.headers.cookie);
|
|
3997
|
+
if (!found) {
|
|
3216
3998
|
res.status(410).type('text/plain').send('This invitation is expired or already used. Request a fresh QR code.');
|
|
3217
3999
|
return;
|
|
3218
4000
|
}
|
|
3219
|
-
|
|
4001
|
+
const item = found.item;
|
|
4002
|
+
if (!found.authorized) {
|
|
4003
|
+
res.status(403).type('html').send(enrollmentPage({ state: 'denied', app: item.app_name }));
|
|
4004
|
+
return;
|
|
4005
|
+
}
|
|
4006
|
+
if (item.registered_device_id && !item.browser_approved_at) {
|
|
4007
|
+
res.type('html').send(enrollmentPage({ state: 'pair', app: item.app_name, action: `/ota/enroll/${token}/approve` }));
|
|
4008
|
+
return;
|
|
4009
|
+
}
|
|
3220
4010
|
const deepLink = `${item.app_scheme}://indraq-enroll?token=${token}`;
|
|
3221
|
-
|
|
3222
|
-
|
|
4011
|
+
res.type('html').send(enrollmentPage({ state: 'open', app: item.app_name, link: deepLink }));
|
|
4012
|
+
});
|
|
4013
|
+
app.post('/ota/enroll/:token/approve', async (req, res) => {
|
|
4014
|
+
const token = routeParam(req.params.token);
|
|
4015
|
+
publicEnrollmentHeaders(res);
|
|
4016
|
+
if (!enrollmentTokenPattern.test(token)) {
|
|
4017
|
+
res.status(404).type('text/plain').send('Invalid invitation.');
|
|
4018
|
+
return;
|
|
4019
|
+
}
|
|
4020
|
+
const found = await enrollmentLanding(token, req.headers.cookie);
|
|
4021
|
+
if (!found) {
|
|
4022
|
+
res.status(410).type('text/plain').send('Invitation expired or already used.');
|
|
4023
|
+
return;
|
|
4024
|
+
}
|
|
4025
|
+
if (!found.item.registered_device_id || !found.authorized) {
|
|
4026
|
+
res.status(403).type('text/plain').send('Open this invitation in the verified device browser.');
|
|
4027
|
+
return;
|
|
4028
|
+
}
|
|
4029
|
+
const updated = await pool.query(`UPDATE ota_enrollment_invitations SET browser_approved_at=now()
|
|
4030
|
+
WHERE token_hash=$1 AND expires_at>now() AND revoked_at IS NULL AND redeemed_at IS NULL
|
|
4031
|
+
AND registered_device_id=$2 RETURNING id`, [hashEnrollmentToken(token), found.item.registered_device_id]);
|
|
4032
|
+
if (!updated.rowCount) {
|
|
4033
|
+
res.status(410).type('text/plain').send('Invitation expired or unavailable.');
|
|
4034
|
+
return;
|
|
4035
|
+
}
|
|
4036
|
+
res.redirect(303, `/ota/enroll/${token}`);
|
|
3223
4037
|
});
|
|
3224
4038
|
app.post('/ota/v1/enroll/redeem', async (req, res) => {
|
|
3225
4039
|
const token = String(req.body?.token || '');
|
|
@@ -3228,6 +4042,10 @@ app.post('/ota/v1/enroll/redeem', async (req, res) => {
|
|
|
3228
4042
|
res.status(400).json({ error: 'Invalid invitation or installation ID.' });
|
|
3229
4043
|
return;
|
|
3230
4044
|
}
|
|
4045
|
+
// Bind the scoped identifier ONLY after a real verified-browser invitation
|
|
4046
|
+
// has been redeemed. A standalone, unapproved API claim cannot bind it.
|
|
4047
|
+
const scopedId = String(req.body?.androidScopedId || '').toLowerCase();
|
|
4048
|
+
const scopedProvided = !!scopedId && androidScopedIdPattern.test(scopedId) && req.body?.platform === 'android';
|
|
3231
4049
|
const digest = hashEnrollmentToken(token);
|
|
3232
4050
|
const client = await pool.connect();
|
|
3233
4051
|
try {
|
|
@@ -3239,6 +4057,11 @@ app.post('/ota/v1/enroll/redeem', async (req, res) => {
|
|
|
3239
4057
|
res.status(410).json({ error: 'Invitation expired or already redeemed.' });
|
|
3240
4058
|
return;
|
|
3241
4059
|
}
|
|
4060
|
+
if (!registeredInviteCanRedeem(invite)) {
|
|
4061
|
+
await client.query('ROLLBACK');
|
|
4062
|
+
res.status(403).json({ error: 'The verified phone browser must approve this app pairing before redeeming the QR.' });
|
|
4063
|
+
return;
|
|
4064
|
+
}
|
|
3242
4065
|
const installed = await client.query('SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2', [invite.app_id, installationId]);
|
|
3243
4066
|
if (!installed.rowCount) {
|
|
3244
4067
|
await client.query('ROLLBACK');
|
|
@@ -3250,6 +4073,35 @@ app.post('/ota/v1/enroll/redeem', async (req, res) => {
|
|
|
3250
4073
|
if (invite.group_id) {
|
|
3251
4074
|
await client.query(`INSERT INTO ota_tester_group_members(app_id,group_id,installation_id,added_by)
|
|
3252
4075
|
VALUES($1,$2,$3,$4) ON CONFLICT(group_id,installation_id) DO NOTHING`, [invite.app_id, invite.group_id, installationId, invite.created_by]);
|
|
4076
|
+
}
|
|
4077
|
+
if (invite.registered_device_id) {
|
|
4078
|
+
const active = (await client.query(`SELECT 1 FROM ota_registered_tester_devices
|
|
4079
|
+
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;
|
|
4080
|
+
if (!active) {
|
|
4081
|
+
await client.query('ROLLBACK');
|
|
4082
|
+
res.status(409).json({ error: 'The selected registered tester device was revoked.' });
|
|
4083
|
+
return;
|
|
4084
|
+
}
|
|
4085
|
+
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]);
|
|
4086
|
+
if (!grant.rowCount) {
|
|
4087
|
+
await client.query('ROLLBACK');
|
|
4088
|
+
res.status(403).json({ error: 'Tester device no longer has access to this app.' });
|
|
4089
|
+
return;
|
|
4090
|
+
}
|
|
4091
|
+
if (scopedProvided && androidScopedTesterRestoreEnabled) {
|
|
4092
|
+
const digestId = scopedIdDigest(scopedId);
|
|
4093
|
+
const collision = await client.query(`SELECT device_id FROM ota_android_scoped_tester_identities
|
|
4094
|
+
WHERE identity_digest=$1`, [digestId]);
|
|
4095
|
+
if (collision.rowCount && collision.rows[0].device_id !== invite.registered_device_id) {
|
|
4096
|
+
await client.query('ROLLBACK');
|
|
4097
|
+
res.status(409).json({ error: 'Android device identity already bound to a different tester.' });
|
|
4098
|
+
return;
|
|
4099
|
+
}
|
|
4100
|
+
await client.query(`INSERT INTO ota_android_scoped_tester_identities(device_id,identity_digest)
|
|
4101
|
+
VALUES($1,$2) ON CONFLICT(device_id,identity_digest) DO NOTHING`, [invite.registered_device_id, digestId]);
|
|
4102
|
+
}
|
|
4103
|
+
await client.query(`INSERT INTO ota_registered_device_installations(device_id,app_id,installation_id)
|
|
4104
|
+
VALUES($1,$2,$3) ON CONFLICT(app_id,installation_id) DO UPDATE SET device_id=excluded.device_id,linked_at=now()`, [invite.registered_device_id, invite.app_id, installationId]);
|
|
3253
4105
|
}
|
|
3254
4106
|
await client.query('UPDATE ota_enrollment_invitations SET redeemed_at=now(),redeemed_installation_id=$2 WHERE id=$1', [invite.id, installationId]);
|
|
3255
4107
|
await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,metadata)
|
|
@@ -3482,7 +4334,7 @@ app.get('/mobile/apps/:appId/native-builds', auth, async (req, res) => {
|
|
|
3482
4334
|
return;
|
|
3483
4335
|
}
|
|
3484
4336
|
const rows = (await pool.query(`SELECT b.id,b.mobile_environment_id environment_id,me.name environment_name,
|
|
3485
|
-
me.slug environment_slug,me.ota_channel,b.runtime_version,b.native_fingerprint,b.app_version,
|
|
4337
|
+
me.slug environment_slug,me.ota_channel,b.runtime_version,b.native_fingerprint,b.app_version,b.platform,
|
|
3486
4338
|
b.version_code,b.build_number,b.build_url,b.source_sha256,b.built_at
|
|
3487
4339
|
FROM mobile_native_builds b JOIN mobile_environments me ON me.id=b.mobile_environment_id
|
|
3488
4340
|
WHERE b.app_id=$1 ORDER BY b.built_at DESC LIMIT 200`, [appRow.id])).rows;
|
|
@@ -3494,10 +4346,13 @@ app.get('/mobile/apps/:appId/releases', auth, async (req, res) => {
|
|
|
3494
4346
|
res.status(404).json({ error: 'Mobile app not found or access denied.' });
|
|
3495
4347
|
return;
|
|
3496
4348
|
}
|
|
3497
|
-
const rows = (await pool.query(`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,
|
|
4349
|
+
const rows = (await pool.query(`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,
|
|
4350
|
+
original.message recovery_source_message,
|
|
3498
4351
|
json_agg(json_build_object('id',u.id,'platform',u.platform) ORDER BY u.platform) FILTER (WHERE u.id IS NOT NULL) updates
|
|
3499
|
-
FROM ota_releases r JOIN mobile_environments me ON me.id=r.mobile_environment_id
|
|
3500
|
-
|
|
4352
|
+
FROM ota_releases r JOIN mobile_environments me ON me.id=r.mobile_environment_id
|
|
4353
|
+
LEFT JOIN ota_releases original ON original.id=r.recovery_target_id
|
|
4354
|
+
LEFT JOIN ota_updates u ON u.release_id=r.id
|
|
4355
|
+
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])).rows;
|
|
3501
4356
|
res.json(rows);
|
|
3502
4357
|
});
|
|
3503
4358
|
app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
|
|
@@ -3560,6 +4415,26 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
|
|
|
3560
4415
|
return;
|
|
3561
4416
|
}
|
|
3562
4417
|
}
|
|
4418
|
+
const deviceIds = Array.isArray(req.body?.audience?.deviceIds) ? req.body.audience.deviceIds : [];
|
|
4419
|
+
if (deviceIds.length > 100 || (req.body?.audience?.deviceIds !== undefined && !deviceIds.length)) {
|
|
4420
|
+
res.status(400).json({ error: 'Select 1–100 approved tester devices.' });
|
|
4421
|
+
return;
|
|
4422
|
+
}
|
|
4423
|
+
if (deviceIds.length) {
|
|
4424
|
+
const validIds = deviceIds.map((v) => ensureUuid(String(v), 'Tester device ID'));
|
|
4425
|
+
if (new Set(validIds).size !== validIds.length) {
|
|
4426
|
+
res.status(400).json({ error: 'Duplicate tester device ID.' });
|
|
4427
|
+
return;
|
|
4428
|
+
}
|
|
4429
|
+
const approved = await pool.query(`SELECT count(*)::int count FROM ota_device_app_grants g
|
|
4430
|
+
JOIN ota_registered_tester_devices d ON d.id=g.device_id
|
|
4431
|
+
WHERE g.app_id=$1 AND g.device_id=ANY($2::uuid[]) AND g.revoked_at IS NULL
|
|
4432
|
+
AND d.revoked_at IS NULL AND d.verified_at IS NOT NULL`, [appRow.id, validIds]);
|
|
4433
|
+
if (Number(approved.rows[0]?.count) !== validIds.length) {
|
|
4434
|
+
res.status(403).json({ error: 'One or more tester devices are not verified or no longer granted access to this app.' });
|
|
4435
|
+
return;
|
|
4436
|
+
}
|
|
4437
|
+
}
|
|
3563
4438
|
}
|
|
3564
4439
|
const platformValues = Array.isArray(req.body?.platforms) ? [...new Set(req.body.platforms.map((v) => String(v).toLowerCase()))] : [];
|
|
3565
4440
|
if (!platformValues.length || platformValues.some((v) => !['android', 'ios'].includes(v))) {
|
|
@@ -3567,6 +4442,10 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
|
|
|
3567
4442
|
return;
|
|
3568
4443
|
}
|
|
3569
4444
|
const platforms = platformValues;
|
|
4445
|
+
if (platforms.some(p => p !== String(baseline.platform || 'android'))) {
|
|
4446
|
+
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.` });
|
|
4447
|
+
return;
|
|
4448
|
+
}
|
|
3570
4449
|
let rollout = null;
|
|
3571
4450
|
if (audienceType === 'percentage') {
|
|
3572
4451
|
const candidate = Number(req.body?.rolloutPercent);
|
|
@@ -3577,6 +4456,7 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
|
|
|
3577
4456
|
rollout = candidate;
|
|
3578
4457
|
}
|
|
3579
4458
|
const clientRequestId = ensureUuid(String(req.body?.clientRequestId || ''), 'OTA publish request ID');
|
|
4459
|
+
const deploymentGroupId = req.body?.deploymentGroupId ? ensureUuid(String(req.body.deploymentGroupId), 'OTA deployment group ID') : null;
|
|
3580
4460
|
const existingRelease = (await pool.query(`SELECT r.*,json_agg(json_build_object('id',u.id,'platform',u.platform)) updates
|
|
3581
4461
|
FROM ota_releases r LEFT JOIN ota_updates u ON u.release_id=r.id
|
|
3582
4462
|
WHERE r.app_id=$1 AND r.client_request_id=$2 GROUP BY r.id`, [appRow.id, clientRequestId])).rows[0];
|
|
@@ -3593,8 +4473,8 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
|
|
|
3593
4473
|
const client = await pool.connect();
|
|
3594
4474
|
try {
|
|
3595
4475
|
await client.query('BEGIN');
|
|
3596
|
-
const release = (await client.query(`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)
|
|
3597
|
-
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING *`, [appRow.id, environmentId, runtimeVersion, message, status, audienceType, req.body?.audience || {}, rollout, null, req.auth.id, clientRequestId])).rows[0];
|
|
4476
|
+
const release = (await client.query(`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)
|
|
4477
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) RETURNING *`, [appRow.id, environmentId, runtimeVersion, message, status, audienceType, req.body?.audience || {}, rollout, null, req.auth.id, clientRequestId, deploymentGroupId])).rows[0];
|
|
3598
4478
|
const updates = [];
|
|
3599
4479
|
for (const platform of platforms) {
|
|
3600
4480
|
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]);
|
|
@@ -3617,6 +4497,10 @@ app.put('/mobile/releases/:releaseId/assets/:sha256', express.raw({ type: '*/*',
|
|
|
3617
4497
|
res.status(404).json({ error: 'OTA release not found or WRITE access denied.' });
|
|
3618
4498
|
return;
|
|
3619
4499
|
}
|
|
4500
|
+
if (!mayFinalize(release.status)) {
|
|
4501
|
+
res.status(409).json({ error: 'Assets can only be uploaded to a draft release.' });
|
|
4502
|
+
return;
|
|
4503
|
+
}
|
|
3620
4504
|
const sha = String(routeParam(req.params.sha256)).toLowerCase();
|
|
3621
4505
|
if (!/^[a-f0-9]{64}$/.test(sha)) {
|
|
3622
4506
|
res.status(400).json({ error: 'Asset SHA-256 must be 64 hex characters.' });
|
|
@@ -3631,20 +4515,33 @@ app.put('/mobile/releases/:releaseId/assets/:sha256', express.raw({ type: '*/*',
|
|
|
3631
4515
|
res.status(400).json({ error: 'Asset SHA-256 does not match request path.' });
|
|
3632
4516
|
return;
|
|
3633
4517
|
}
|
|
3634
|
-
await
|
|
3635
|
-
const objectKey = `assets/${sha}`;
|
|
3636
|
-
const minio = getMinio();
|
|
4518
|
+
const client = await pool.connect();
|
|
3637
4519
|
try {
|
|
3638
|
-
await
|
|
4520
|
+
await client.query('BEGIN');
|
|
4521
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sha]);
|
|
4522
|
+
await ensureOtaBucket();
|
|
4523
|
+
const objectKey = `assets/${sha}`;
|
|
4524
|
+
const minio = getMinio();
|
|
4525
|
+
try {
|
|
4526
|
+
await minio.statObject(minioBucket, objectKey);
|
|
4527
|
+
}
|
|
4528
|
+
catch {
|
|
4529
|
+
await minio.putObject(minioBucket, objectKey, body, body.length, { 'Content-Type': String(req.headers['x-indraq-content-type'] || req.headers['content-type'] || 'application/octet-stream') });
|
|
4530
|
+
}
|
|
4531
|
+
const extension = String(req.headers['x-indraq-file-extension'] || '').trim() || null;
|
|
4532
|
+
const result = await client.query(`INSERT INTO ota_assets(sha256,object_key,content_type,file_extension,size_bytes) VALUES($1,$2,$3,$4,$5)
|
|
4533
|
+
ON CONFLICT(sha256) DO UPDATE SET content_type=excluded.content_type,file_extension=COALESCE(ota_assets.file_extension,excluded.file_extension),created_at=now()
|
|
4534
|
+
RETURNING id,sha256,size_bytes`, [sha, objectKey, String(req.headers['x-indraq-content-type'] || req.headers['content-type'] || 'application/octet-stream'), extension, body.length]);
|
|
4535
|
+
await client.query('COMMIT');
|
|
4536
|
+
res.json(result.rows[0]);
|
|
3639
4537
|
}
|
|
3640
|
-
catch {
|
|
3641
|
-
await
|
|
4538
|
+
catch (error) {
|
|
4539
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
4540
|
+
throw error;
|
|
4541
|
+
}
|
|
4542
|
+
finally {
|
|
4543
|
+
client.release();
|
|
3642
4544
|
}
|
|
3643
|
-
const extension = String(req.headers['x-indraq-file-extension'] || '').trim() || null;
|
|
3644
|
-
const result = await pool.query(`INSERT INTO ota_assets(sha256,object_key,content_type,file_extension,size_bytes) VALUES($1,$2,$3,$4,$5)
|
|
3645
|
-
ON CONFLICT(sha256) DO UPDATE SET content_type=excluded.content_type,file_extension=COALESCE(ota_assets.file_extension,excluded.file_extension)
|
|
3646
|
-
RETURNING id,sha256,size_bytes`, [sha, objectKey, String(req.headers['x-indraq-content-type'] || req.headers['content-type'] || 'application/octet-stream'), extension, body.length]);
|
|
3647
|
-
res.json(result.rows[0]);
|
|
3648
4545
|
});
|
|
3649
4546
|
app.post('/mobile/releases/:releaseId/finalize', auth, async (req, res) => {
|
|
3650
4547
|
const release = await releaseForUser(routeParam(req.params.releaseId), req.auth, true);
|
|
@@ -3652,6 +4549,10 @@ app.post('/mobile/releases/:releaseId/finalize', auth, async (req, res) => {
|
|
|
3652
4549
|
res.status(404).json({ error: 'OTA release not found or WRITE access denied.' });
|
|
3653
4550
|
return;
|
|
3654
4551
|
}
|
|
4552
|
+
if (!mayFinalize(release.status)) {
|
|
4553
|
+
res.status(409).json({ error: 'Only draft OTA releases may be finalized. Published updates are immutable.' });
|
|
4554
|
+
return;
|
|
4555
|
+
}
|
|
3655
4556
|
const platforms = Array.isArray(req.body?.platforms) ? req.body.platforms : [];
|
|
3656
4557
|
if (!platforms.length) {
|
|
3657
4558
|
res.status(400).json({ error: 'Platform manifests are required.' });
|
|
@@ -3672,6 +4573,12 @@ app.post('/mobile/releases/:releaseId/finalize', auth, async (req, res) => {
|
|
|
3672
4573
|
const all = [{ ...launch, role: 'launch', sortOrder: 0 }, ...assets.map((a, i) => ({ ...a, role: 'asset', sortOrder: i + 1 }))];
|
|
3673
4574
|
const manifestAssets = [];
|
|
3674
4575
|
let launchAsset = null;
|
|
4576
|
+
// Acquire asset locks in a deterministic SHA order before referencing
|
|
4577
|
+
// uploaded objects. This excludes a concurrent orphan cleanup job from
|
|
4578
|
+
// removing a stale upload while a delayed draft is being finalized.
|
|
4579
|
+
const publishShas = [...new Set(all.map((item) => String(item.sha256).toLowerCase()))].sort();
|
|
4580
|
+
for (const sha of publishShas)
|
|
4581
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sha]);
|
|
3675
4582
|
await client.query('DELETE FROM ota_update_assets WHERE update_id=$1', [update.id]);
|
|
3676
4583
|
for (const item of all) {
|
|
3677
4584
|
const asset = (await client.query('SELECT * FROM ota_assets WHERE sha256=$1', [String(item.sha256).toLowerCase()])).rows[0];
|
|
@@ -3707,12 +4614,21 @@ app.post('/mobile/releases/:releaseId/promote', auth, async (req, res) => {
|
|
|
3707
4614
|
res.status(404).json({ error: 'OTA release not found or WRITE access denied.' });
|
|
3708
4615
|
return;
|
|
3709
4616
|
}
|
|
4617
|
+
if (!mayPromote(release.status, release.promoted_at)) {
|
|
4618
|
+
res.status(409).json({ error: 'Only testing or never-promoted paused releases can be promoted.' });
|
|
4619
|
+
return;
|
|
4620
|
+
}
|
|
3710
4621
|
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;
|
|
3711
4622
|
if (incomplete) {
|
|
3712
4623
|
res.status(409).json({ error: 'OTA release is not finalized yet and cannot be promoted.' });
|
|
3713
4624
|
return;
|
|
3714
4625
|
}
|
|
3715
|
-
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()
|
|
4626
|
+
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()
|
|
4627
|
+
WHERE id=$1 AND (status='test' OR (status='paused' AND promoted_at IS NULL)) RETURNING *`, [release.id]);
|
|
4628
|
+
if (!result.rowCount) {
|
|
4629
|
+
res.status(409).json({ error: 'Release status changed. Refresh and try again.' });
|
|
4630
|
+
return;
|
|
4631
|
+
}
|
|
3716
4632
|
await audit(req.auth.id, 'ota.release.promote', 'ota-release', release.id, req.body?.reason || 'Promote tested OTA release', { appId: release.app_id });
|
|
3717
4633
|
res.json(result.rows[0]);
|
|
3718
4634
|
});
|
|
@@ -3722,41 +4638,91 @@ app.post('/mobile/releases/:releaseId/pause', auth, async (req, res) => {
|
|
|
3722
4638
|
res.status(404).json({ error: 'OTA release not found or WRITE access denied.' });
|
|
3723
4639
|
return;
|
|
3724
4640
|
}
|
|
3725
|
-
|
|
4641
|
+
if (!mayPause(release.status)) {
|
|
4642
|
+
res.status(409).json({ error: 'Only active testing or released updates can be paused.' });
|
|
4643
|
+
return;
|
|
4644
|
+
}
|
|
4645
|
+
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]);
|
|
4646
|
+
if (!updated.rowCount) {
|
|
4647
|
+
res.status(409).json({ error: 'Release status changed. Refresh and try again.' });
|
|
4648
|
+
return;
|
|
4649
|
+
}
|
|
3726
4650
|
await audit(req.auth.id, 'ota.release.pause', 'ota-release', release.id, req.body?.reason || 'Pause OTA release');
|
|
3727
4651
|
res.json({ ok: true });
|
|
3728
4652
|
});
|
|
4653
|
+
/** Create a brand-new signed recovery deployment. Source manifests are never edited.
|
|
4654
|
+
* Embedded recovery uses one placeholder OTA-update row PER PLATFORM so all
|
|
4655
|
+
* existing audience selection, runtime and platform filters still apply. */
|
|
4656
|
+
const makeOtaRecovery = async (client, source, target, actorId, status) => {
|
|
4657
|
+
const recovery = (await client.query(`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)
|
|
4658
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15) RETURNING *`, [source.app_id, source.mobile_environment_id, source.runtime_version,
|
|
4659
|
+
target ? `Recovery → ${target.message.startsWith('Recovery → ') ? target.message.slice('Recovery → '.length) : target.message}` : `Recovery → embedded (${source.runtime_version})`,
|
|
4660
|
+
status, status === 'released' ? 'all' : source.audience_type, status === 'released' ? {} : source.audience,
|
|
4661
|
+
status === 'released' ? null : source.rollout_percent, status === 'released' ? new Date() : null,
|
|
4662
|
+
target?.verified_at || null, actorId, target ? 'assets' : 'embedded', source.id, target?.id || null, source.deployment_group_id || null])).rows[0];
|
|
4663
|
+
const sourceUpdates = (await client.query('SELECT * FROM ota_updates WHERE release_id=$1 ORDER BY platform', [source.id])).rows;
|
|
4664
|
+
const targetUpdates = target ? (await client.query('SELECT * FROM ota_updates WHERE release_id=$1', [target.id])).rows : [];
|
|
4665
|
+
if (!sourceUpdates.length)
|
|
4666
|
+
throw Object.assign(new Error('Original update has no published platforms.'), { statusCode: 409 });
|
|
4667
|
+
for (const old of sourceUpdates) {
|
|
4668
|
+
const good = target ? targetUpdates.find((u) => u.platform === old.platform) : null;
|
|
4669
|
+
if (target && (!good || !good.manifest || !good.manifest.launchAsset))
|
|
4670
|
+
throw Object.assign(new Error(`Recovery target has no complete ${old.platform} assets.`), { statusCode: 409 });
|
|
4671
|
+
const next = (await client.query('INSERT INTO ota_updates(release_id,platform,source_hash) VALUES($1,$2,$3) RETURNING id,created_at', [recovery.id, old.platform, good?.source_hash || null])).rows[0];
|
|
4672
|
+
const manifest = good ? {
|
|
4673
|
+
...good.manifest, id: next.id, createdAt: new Date(next.created_at).toISOString(),
|
|
4674
|
+
metadata: { ...(good.manifest.metadata || {}), indraqReleaseId: recovery.id },
|
|
4675
|
+
extra: { ...(good.manifest.extra || {}), indraq: { releaseId: recovery.id, recoveryOf: source.id, recoveryTargetId: target.id } }
|
|
4676
|
+
} : { type: 'rollBackToEmbedded' };
|
|
4677
|
+
await client.query('UPDATE ota_updates SET manifest=$1 WHERE id=$2', [manifest, next.id]);
|
|
4678
|
+
if (good)
|
|
4679
|
+
await client.query(`INSERT INTO ota_update_assets(update_id,asset_id,asset_key,role,sort_order)
|
|
4680
|
+
SELECT $1,asset_id,asset_key,role,sort_order FROM ota_update_assets WHERE update_id=$2`, [next.id, good.id]);
|
|
4681
|
+
}
|
|
4682
|
+
return recovery;
|
|
4683
|
+
};
|
|
3729
4684
|
app.post('/mobile/releases/:releaseId/rollback', auth, async (req, res) => {
|
|
3730
4685
|
const current = await releaseForUser(routeParam(req.params.releaseId), req.auth, true);
|
|
3731
4686
|
if (!current) {
|
|
3732
4687
|
res.status(404).json({ error: 'OTA release not found or WRITE access denied.' });
|
|
3733
4688
|
return;
|
|
3734
4689
|
}
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
4690
|
+
if (!mayRollback(current.status)) {
|
|
4691
|
+
res.status(409).json({ error: 'Production rollback requires an active released OTA. Use withdraw for testing updates.' });
|
|
4692
|
+
return;
|
|
4693
|
+
}
|
|
4694
|
+
const active = (await pool.query(`SELECT id FROM ota_releases WHERE app_id=$1 AND mobile_environment_id=$2 AND runtime_version=$3
|
|
4695
|
+
AND status='released' ORDER BY created_at DESC,id DESC LIMIT 1`, [current.app_id, current.mobile_environment_id, current.runtime_version])).rows[0];
|
|
4696
|
+
if (active?.id !== current.id) {
|
|
4697
|
+
res.status(409).json({ error: 'Only the newest active production release can be rolled back.' });
|
|
4698
|
+
return;
|
|
4699
|
+
}
|
|
4700
|
+
const targetInput = String(req.body?.targetReleaseId || 'embedded');
|
|
4701
|
+
const target = targetInput === 'embedded' ? null : (await pool.query(`SELECT * FROM ota_releases WHERE id=$1
|
|
4702
|
+
AND app_id=$2 AND mobile_environment_id=$3 AND runtime_version=$4 AND status='released'
|
|
4703
|
+
AND recovery_kind='assets' AND created_at<$5`, [ensureUuid(targetInput, 'Recovery target'), current.app_id, current.mobile_environment_id, current.runtime_version, current.created_at])).rows[0];
|
|
4704
|
+
if (targetInput !== 'embedded' && !target) {
|
|
4705
|
+
res.status(409).json({ error: 'Selected production recovery target is not an earlier compatible released OTA.' });
|
|
3741
4706
|
return;
|
|
3742
4707
|
}
|
|
3743
4708
|
const client = await pool.connect();
|
|
3744
4709
|
try {
|
|
3745
4710
|
await client.query('BEGIN');
|
|
3746
|
-
const
|
|
3747
|
-
|
|
3748
|
-
|
|
3749
|
-
|
|
3750
|
-
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
4711
|
+
const locked = (await client.query(`SELECT * FROM ota_releases WHERE id=$1 FOR UPDATE`, [current.id])).rows[0];
|
|
4712
|
+
if (locked?.status !== 'released')
|
|
4713
|
+
throw Object.assign(new Error('Release changed status; retry.'), { statusCode: 409 });
|
|
4714
|
+
// A production recovery to identical published content cannot change
|
|
4715
|
+
// running JS. Do not create another release or roll back the source.
|
|
4716
|
+
if (target ? await recoveryPayloadsMatch(client, locked.id, target.id) : locked.recovery_kind === 'embedded')
|
|
4717
|
+
throw Object.assign(new Error('Selected production recovery already contains identical content. Choose different assets or an embedded/native target.'), { statusCode: 409, code: 'OTA_RECOVERY_SAME_CONTENT' });
|
|
4718
|
+
const recovery = await makeOtaRecovery(client, current, target, req.auth.id, 'released');
|
|
4719
|
+
const updated = await client.query(`UPDATE ota_releases SET status='rolled_back',updated_at=now()
|
|
4720
|
+
WHERE id=$1 AND status='released' RETURNING id`, [current.id]);
|
|
4721
|
+
if (!updated.rowCount)
|
|
4722
|
+
throw Object.assign(new Error('Release changed status.'), { statusCode: 409 });
|
|
3757
4723
|
await client.query('COMMIT');
|
|
3758
|
-
await audit(req.auth.id, 'ota.release.rollback', 'ota-release',
|
|
3759
|
-
res.json(
|
|
4724
|
+
await audit(req.auth.id, 'ota.release.rollback', 'ota-release', recovery.id, req.body?.reason || 'Production OTA rollback', { from: current.id, target: target?.id || 'embedded' });
|
|
4725
|
+
res.json(recovery);
|
|
3760
4726
|
}
|
|
3761
4727
|
catch (error) {
|
|
3762
4728
|
await client.query('ROLLBACK');
|
|
@@ -3766,6 +4732,176 @@ app.post('/mobile/releases/:releaseId/rollback', auth, async (req, res) => {
|
|
|
3766
4732
|
client.release();
|
|
3767
4733
|
}
|
|
3768
4734
|
});
|
|
4735
|
+
app.post('/mobile/releases/:releaseId/withdraw', auth, async (req, res) => {
|
|
4736
|
+
const accessible = await releaseForUser(routeParam(req.params.releaseId), req.auth, true);
|
|
4737
|
+
if (!accessible) {
|
|
4738
|
+
res.status(404).json({ error: 'OTA release not found or WRITE access denied.' });
|
|
4739
|
+
return;
|
|
4740
|
+
}
|
|
4741
|
+
const requested = String(req.body?.targetReleaseId || 'auto');
|
|
4742
|
+
const pinWithdrawn = req.body?.pinWithdrawn === true;
|
|
4743
|
+
if (!['none', 'embedded', 'auto'].includes(requested))
|
|
4744
|
+
ensureUuid(requested, 'Recovery target ID');
|
|
4745
|
+
const client = await pool.connect();
|
|
4746
|
+
try {
|
|
4747
|
+
await client.query('BEGIN');
|
|
4748
|
+
// Serialize recovery for this app/environment/runtime. This also ensures
|
|
4749
|
+
// pinning and withdrawal are atomic: an HTTP 409 changes nothing.
|
|
4750
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`ota-withdraw:${accessible.app_id}:${accessible.mobile_environment_id}:${accessible.runtime_version}`]);
|
|
4751
|
+
const current = (await client.query('SELECT * FROM ota_releases WHERE id=$1 FOR UPDATE', [accessible.id])).rows[0];
|
|
4752
|
+
if (!current || !mayWithdraw(current.status, current.promoted_at))
|
|
4753
|
+
throw Object.assign(new Error('Only never-promoted testing updates can be withdrawn. Released updates require rollback.'), { statusCode: 409 });
|
|
4754
|
+
if (requested !== 'none') {
|
|
4755
|
+
const sourcePlatforms = (await client.query('SELECT platform FROM ota_updates WHERE release_id=$1', [current.id])).rows.map((r) => String(r.platform));
|
|
4756
|
+
// PostgreSQL timestamptz has microsecond precision; JS Date loses sub-ms
|
|
4757
|
+
// precision. Compare using the exact selected release row in PostgreSQL.
|
|
4758
|
+
// Without this, the release being withdrawn can appear newer than itself.
|
|
4759
|
+
const later = (await client.query(`SELECT DISTINCT r.id,r.message,r.created_at,r.status,r.audience_type,r.audience
|
|
4760
|
+
FROM ota_releases r JOIN ota_updates u ON u.release_id=r.id
|
|
4761
|
+
JOIN ota_releases anchor ON anchor.id=$5
|
|
4762
|
+
WHERE r.app_id=$1 AND r.mobile_environment_id=$2 AND r.runtime_version=$3
|
|
4763
|
+
AND r.status IN ('released','test') AND u.platform=ANY($4::text[])
|
|
4764
|
+
AND r.id <> anchor.id
|
|
4765
|
+
AND (r.created_at,r.id)>(anchor.created_at,anchor.id)
|
|
4766
|
+
ORDER BY r.created_at DESC,r.id DESC LIMIT 50`, [current.app_id, current.mobile_environment_id, current.runtime_version, sourcePlatforms, current.id])).rows;
|
|
4767
|
+
// Device profiles may have been consolidated since an older OTA was published.
|
|
4768
|
+
// Normalize retired IDs for overlap protection without modifying releases.
|
|
4769
|
+
const relevantIds = [...new Set([current, ...later].flatMap((r) => Array.isArray(r.audience?.deviceIds) ? r.audience.deviceIds : []))];
|
|
4770
|
+
const aliasRows = relevantIds.length ? (await client.query(`SELECT duplicate_device_id,canonical_device_id
|
|
4771
|
+
FROM ota_tester_device_profile_aliases WHERE duplicate_device_id=ANY($1::uuid[])`, [relevantIds])).rows : [];
|
|
4772
|
+
const aliasMap = new Map(aliasRows.map((r) => [String(r.duplicate_device_id), String(r.canonical_device_id)]));
|
|
4773
|
+
const canonicalAudience = (r) => ({ ...r, audience: { ...r.audience, deviceIds: Array.isArray(r.audience?.deviceIds) ? r.audience.deviceIds.map((id) => aliasMap.get(id) || id) : undefined } });
|
|
4774
|
+
const blockers = later.filter((other) => other.id !== current.id && otaAudiencesMayOverlap(canonicalAudience(current), canonicalAudience(other)));
|
|
4775
|
+
if (blockers.length) {
|
|
4776
|
+
const item = blockers[0];
|
|
4777
|
+
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.`), { statusCode: 409, blockingReleaseId: item.id });
|
|
4778
|
+
}
|
|
4779
|
+
}
|
|
4780
|
+
let target = null;
|
|
4781
|
+
if (requested !== 'embedded' && requested !== 'none') {
|
|
4782
|
+
const params = requested === 'auto'
|
|
4783
|
+
? [current.app_id, current.mobile_environment_id, current.runtime_version, current.id]
|
|
4784
|
+
: [requested, current.app_id, current.mobile_environment_id, current.runtime_version, current.id];
|
|
4785
|
+
const sql = requested === 'auto'
|
|
4786
|
+
? `SELECT * FROM ota_releases WHERE app_id=$1 AND mobile_environment_id=$2 AND runtime_version=$3
|
|
4787
|
+
AND status='released' AND recovery_kind='assets'
|
|
4788
|
+
AND (created_at,id)<(SELECT created_at,id FROM ota_releases WHERE id=$4)
|
|
4789
|
+
ORDER BY created_at DESC,id DESC LIMIT 1`
|
|
4790
|
+
: `SELECT * FROM ota_releases WHERE id=$1 AND app_id=$2 AND mobile_environment_id=$3 AND runtime_version=$4
|
|
4791
|
+
AND status IN ('released','test','paused') AND recovery_kind='assets'
|
|
4792
|
+
AND (created_at,id)<(SELECT created_at,id FROM ota_releases WHERE id=$5)`;
|
|
4793
|
+
target = (await client.query(sql, params)).rows[0] || null;
|
|
4794
|
+
if (requested !== 'auto' && !target)
|
|
4795
|
+
throw Object.assign(new Error('Recovery target must be an earlier compatible OTA with retained assets.'), { statusCode: 409 });
|
|
4796
|
+
}
|
|
4797
|
+
// An older recovery may point to the exact same already-running JS.
|
|
4798
|
+
// Reject that no-op BEFORE changing status/pinning or creating another
|
|
4799
|
+
// immutable release. 'none' always remains available to stop delivery.
|
|
4800
|
+
if (requested !== 'none' && (target
|
|
4801
|
+
? await recoveryPayloadsMatch(client, current.id, target.id)
|
|
4802
|
+
: current.recovery_kind === 'embedded')) {
|
|
4803
|
+
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.'), { statusCode: 409, code: 'OTA_RECOVERY_SAME_CONTENT' });
|
|
4804
|
+
}
|
|
4805
|
+
const withdrawn = await client.query(`UPDATE ota_releases SET status='withdrawn',is_pinned=(is_pinned OR $2),updated_at=now()
|
|
4806
|
+
WHERE id=$1 AND (status='test' OR (status='paused' AND promoted_at IS NULL)) RETURNING id`, [current.id, pinWithdrawn]);
|
|
4807
|
+
if (!withdrawn.rowCount)
|
|
4808
|
+
throw Object.assign(new Error('Update changed status; cannot withdraw.'), { statusCode: 409 });
|
|
4809
|
+
const recovery = requested === 'none' ? null : await makeOtaRecovery(client, current, target, req.auth.id, 'test');
|
|
4810
|
+
await client.query('COMMIT');
|
|
4811
|
+
await audit(req.auth.id, 'ota.release.withdraw', 'ota-release', current.id, req.body?.reason || 'Withdraw testing OTA', { recoveryId: recovery?.id || null, target: target?.id || (requested === 'none' ? 'none' : 'embedded'), pinWithdrawn, cleanup: 'orphan-assets-only' });
|
|
4812
|
+
res.json({ ok: true, withdrawnReleaseId: current.id, recoveryReleaseId: recovery?.id || null,
|
|
4813
|
+
recoveryKind: recovery?.recovery_kind || null, requiresClientRemediation: requested === 'none',
|
|
4814
|
+
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.' });
|
|
4815
|
+
}
|
|
4816
|
+
catch (error) {
|
|
4817
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
4818
|
+
throw error;
|
|
4819
|
+
}
|
|
4820
|
+
finally {
|
|
4821
|
+
client.release();
|
|
4822
|
+
}
|
|
4823
|
+
});
|
|
4824
|
+
/** Asset URLs are immutable. Only objects that were uploaded but have no
|
|
4825
|
+
* update reference can be reclaimed. This NEVER prunes published manifests. */
|
|
4826
|
+
const orphanAssetsQuery = `SELECT a.id,a.sha256,a.object_key,a.size_bytes FROM ota_assets a
|
|
4827
|
+
WHERE a.created_at < now()-interval '7 days'
|
|
4828
|
+
AND NOT EXISTS(SELECT 1 FROM ota_update_assets ua WHERE ua.asset_id=a.id)
|
|
4829
|
+
ORDER BY a.created_at ASC LIMIT $1`;
|
|
4830
|
+
const collectUnreferencedAssets = async (limit = 50) => {
|
|
4831
|
+
const candidates = (await pool.query(orphanAssetsQuery, [Math.max(1, Math.min(50, limit))])).rows;
|
|
4832
|
+
let deleted = 0, bytesDeleted = 0;
|
|
4833
|
+
for (const item of candidates) {
|
|
4834
|
+
const client = await pool.connect();
|
|
4835
|
+
try {
|
|
4836
|
+
await client.query('BEGIN');
|
|
4837
|
+
// Lock by SHA both here and during upload; avoids an upload racing GC.
|
|
4838
|
+
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [item.sha256]);
|
|
4839
|
+
const fresh = (await client.query(`SELECT a.id,a.object_key,a.size_bytes FROM ota_assets a
|
|
4840
|
+
WHERE a.id=$1 AND a.created_at<now()-interval '7 days'
|
|
4841
|
+
AND NOT EXISTS(SELECT 1 FROM ota_update_assets ua WHERE ua.asset_id=a.id)
|
|
4842
|
+
FOR UPDATE`, [item.id])).rows[0];
|
|
4843
|
+
if (!fresh) {
|
|
4844
|
+
await client.query('COMMIT');
|
|
4845
|
+
continue;
|
|
4846
|
+
}
|
|
4847
|
+
// CAS using the SHA/object identity. In case MinIO fails, DB rollback
|
|
4848
|
+
// preserves the record so the job can retry.
|
|
4849
|
+
await ensureOtaBucket();
|
|
4850
|
+
await getMinio().removeObject(minioBucket, String(fresh.object_key));
|
|
4851
|
+
await client.query('DELETE FROM ota_assets WHERE id=$1', [fresh.id]);
|
|
4852
|
+
await client.query('COMMIT');
|
|
4853
|
+
deleted++;
|
|
4854
|
+
bytesDeleted += Number(fresh.size_bytes || 0);
|
|
4855
|
+
}
|
|
4856
|
+
catch (error) {
|
|
4857
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
4858
|
+
console.error('OTA orphan cleanup failed', error);
|
|
4859
|
+
}
|
|
4860
|
+
finally {
|
|
4861
|
+
client.release();
|
|
4862
|
+
}
|
|
4863
|
+
}
|
|
4864
|
+
return { deleted, bytesDeleted, scanned: candidates.length };
|
|
4865
|
+
};
|
|
4866
|
+
app.get('/mobile/apps/:appId/storage', auth, async (req, res) => {
|
|
4867
|
+
const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
|
|
4868
|
+
if (!appRow) {
|
|
4869
|
+
res.status(404).json({ error: 'Mobile app not found or access denied.' });
|
|
4870
|
+
return;
|
|
4871
|
+
}
|
|
4872
|
+
const owned = (await pool.query(`SELECT COUNT(*)::int count,COALESCE(sum(size_bytes),0)::text bytes FROM ota_assets
|
|
4873
|
+
WHERE id IN (SELECT DISTINCT ua.asset_id FROM ota_update_assets ua JOIN ota_updates u ON u.id=ua.update_id
|
|
4874
|
+
JOIN ota_releases r ON r.id=u.release_id WHERE r.app_id=$1)`, [appRow.id])).rows[0];
|
|
4875
|
+
const orphans = (await pool.query(`SELECT COUNT(*)::int count,COALESCE(sum(a.size_bytes),0)::text bytes FROM ota_assets a
|
|
4876
|
+
WHERE a.created_at<now()-interval '7 days'
|
|
4877
|
+
AND NOT EXISTS(SELECT 1 FROM ota_update_assets ua WHERE ua.asset_id=a.id)`)).rows[0];
|
|
4878
|
+
res.json({ appAssets: Number(owned.count), appAssetBytes: Number(owned.bytes), orphanCount: Number(orphans.count), orphanBytes: Number(orphans.bytes),
|
|
4879
|
+
policy: 'No published OTA asset is garbage-collected. Only unreferenced uploads older than 7 days are eligible.' });
|
|
4880
|
+
});
|
|
4881
|
+
app.post('/mobile/apps/:appId/storage/cleanup', auth, ...allow('admin'), async (req, res) => {
|
|
4882
|
+
const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth, true);
|
|
4883
|
+
if (!appRow) {
|
|
4884
|
+
res.status(404).json({ error: 'Mobile app not found or WRITE access denied.' });
|
|
4885
|
+
return;
|
|
4886
|
+
}
|
|
4887
|
+
const result = await collectUnreferencedAssets(50);
|
|
4888
|
+
await audit(req.auth.id, 'ota.storage.orphan_cleanup', 'mobile-app', appRow.id, 'Delete unreferenced stale uploads', { ...result });
|
|
4889
|
+
res.json(result);
|
|
4890
|
+
});
|
|
4891
|
+
app.post('/mobile/releases/:releaseId/pin', auth, async (req, res) => {
|
|
4892
|
+
const release = await releaseForUser(routeParam(req.params.releaseId), req.auth, true);
|
|
4893
|
+
if (!release) {
|
|
4894
|
+
res.status(404).json({ error: 'Release not found or WRITE access denied.' });
|
|
4895
|
+
return;
|
|
4896
|
+
}
|
|
4897
|
+
if (typeof req.body?.pinned !== 'boolean') {
|
|
4898
|
+
res.status(400).json({ error: 'pinned must be a boolean.' });
|
|
4899
|
+
return;
|
|
4900
|
+
}
|
|
4901
|
+
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];
|
|
4902
|
+
await audit(req.auth.id, 'ota.release.pin', 'ota-release', release.id, req.body.pinned ? 'Pin' : 'Unpin');
|
|
4903
|
+
res.json(row);
|
|
4904
|
+
});
|
|
3769
4905
|
app.get('/mobile/apps/:appId/metrics', auth, async (req, res) => {
|
|
3770
4906
|
const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
|
|
3771
4907
|
if (!appRow) {
|
|
@@ -3777,7 +4913,7 @@ app.get('/mobile/apps/:appId/metrics', auth, async (req, res) => {
|
|
|
3777
4913
|
FROM ota_events WHERE app_id=$1 AND ($2::uuid IS NULL OR release_id=$2) GROUP BY event_type ORDER BY event_type`, [appRow.id, releaseId])).rows;
|
|
3778
4914
|
const installs = (await pool.query('SELECT count(*)::int count FROM ota_installations WHERE app_id=$1', [appRow.id])).rows[0]?.count || 0;
|
|
3779
4915
|
const releases = (await pool.query(`SELECT r.id,r.message,r.status,r.audience_type,r.runtime_version,r.created_at,me.name environment_name,
|
|
3780
|
-
(SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type
|
|
4916
|
+
(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,
|
|
3781
4917
|
(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,
|
|
3782
4918
|
(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,
|
|
3783
4919
|
(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,
|
|
@@ -3785,6 +4921,120 @@ app.get('/mobile/apps/:appId/metrics', auth, async (req, res) => {
|
|
|
3785
4921
|
FROM ota_releases r JOIN mobile_environments me ON me.id=r.mobile_environment_id WHERE r.app_id=$1 ORDER BY r.created_at DESC LIMIT 20`, [appRow.id])).rows;
|
|
3786
4922
|
res.json({ appId: appRow.id, appName: appRow.app_name, totalInstallations: installs, releaseId, events: counts, releases });
|
|
3787
4923
|
});
|
|
4924
|
+
// Acknowledged registration, independent of telemetry. Required before browser
|
|
4925
|
+
// token redemption and safe to call repeatedly. Does not enroll a tester.
|
|
4926
|
+
app.post('/ota/v1/enroll/announce/:updatePath', async (req, res) => {
|
|
4927
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
4928
|
+
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
4929
|
+
if (!appRow) {
|
|
4930
|
+
res.status(404).json({ error: 'Unknown app.' });
|
|
4931
|
+
return;
|
|
4932
|
+
}
|
|
4933
|
+
const installationId = String(req.body?.installationId || '');
|
|
4934
|
+
const runtimeVersion = String(req.body?.runtimeVersion || '');
|
|
4935
|
+
const platform = String(req.body?.platform || '');
|
|
4936
|
+
if (!/^[A-Za-z0-9_-]{12,200}$/.test(installationId) || runtimeVersion.length > 140 || !runtimeVersion || !['android', 'ios'].includes(platform)) {
|
|
4937
|
+
res.status(400).json({ error: 'Invalid installation registration.' });
|
|
4938
|
+
return;
|
|
4939
|
+
}
|
|
4940
|
+
await pool.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,last_seen_at)
|
|
4941
|
+
VALUES($1,$2,$3,$4,now()) ON CONFLICT(app_id,installation_id) DO UPDATE SET
|
|
4942
|
+
platform=excluded.platform,runtime_version=excluded.runtime_version,last_seen_at=now()`, [appRow.id, installationId, platform, runtimeVersion]);
|
|
4943
|
+
res.status(200).json({ ok: true });
|
|
4944
|
+
});
|
|
4945
|
+
// Android-only private tester mode: weaker trust based on a signing-key-scoped
|
|
4946
|
+
// identifier. This is not cryptographic device attestation. Do NOT use for
|
|
4947
|
+
// public apps, signing keys shared with untrusted developers, or sensitive OTA.
|
|
4948
|
+
app.get('/ota/v1/android-scoped/capabilities/:updatePath', async (req, res) => {
|
|
4949
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
4950
|
+
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
4951
|
+
if (!appRow) {
|
|
4952
|
+
res.status(404).json({ error: 'Unknown app.' });
|
|
4953
|
+
return;
|
|
4954
|
+
}
|
|
4955
|
+
res.json({ supported: true, enabled: androidScopedTesterRestoreEnabled, appId: appRow.id,
|
|
4956
|
+
assurance: 'identifier-only', fallback: 'verified-browser', platform: 'android' });
|
|
4957
|
+
});
|
|
4958
|
+
app.post('/ota/v1/enroll/android-scoped/:updatePath', async (req, res) => {
|
|
4959
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
4960
|
+
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
4961
|
+
if (!appRow) {
|
|
4962
|
+
res.status(404).json({ error: 'Unknown app.' });
|
|
4963
|
+
return;
|
|
4964
|
+
}
|
|
4965
|
+
if (!androidScopedTesterRestoreEnabled) {
|
|
4966
|
+
res.status(403).json({ enrolled: false, recovery: 'browser', reason: 'feature_disabled' });
|
|
4967
|
+
return;
|
|
4968
|
+
}
|
|
4969
|
+
const installationId = String(req.body?.installationId || '');
|
|
4970
|
+
const runtimeVersion = String(req.body?.runtimeVersion || '');
|
|
4971
|
+
const androidScopedId = String(req.body?.androidScopedId || '').toLowerCase();
|
|
4972
|
+
if (!/^[A-Za-z0-9_-]{12,200}$/.test(installationId) || !/^.{1,100}-indraq-(staging|prod)$/.test(runtimeVersion) || !androidScopedIdPattern.test(androidScopedId)) {
|
|
4973
|
+
res.status(400).json({ enrolled: false, recovery: 'browser', reason: 'invalid_request' });
|
|
4974
|
+
return;
|
|
4975
|
+
}
|
|
4976
|
+
// A successful native build record must exist for the exact runtime. Merely
|
|
4977
|
+
// copying an app ID from the CLI is insufficient to claim a runtime.
|
|
4978
|
+
const built = await pool.query(`SELECT 1 FROM mobile_native_builds WHERE app_id=$1 AND runtime_version=$2 LIMIT 1`, [appRow.id, runtimeVersion]);
|
|
4979
|
+
if (!built.rowCount) {
|
|
4980
|
+
res.status(409).json({ enrolled: false, recovery: 'browser', reason: 'runtime_not_recorded' });
|
|
4981
|
+
return;
|
|
4982
|
+
}
|
|
4983
|
+
const client = await pool.connect();
|
|
4984
|
+
try {
|
|
4985
|
+
await client.query('BEGIN');
|
|
4986
|
+
const identity = (await client.query(`SELECT d.id,d.label,d.owner_user_id FROM ota_android_scoped_tester_identities i
|
|
4987
|
+
JOIN ota_registered_tester_devices d ON d.id=i.device_id
|
|
4988
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=$2 AND g.revoked_at IS NULL
|
|
4989
|
+
WHERE i.identity_digest=$1 AND d.verified_at IS NOT NULL AND d.revoked_at IS NULL FOR UPDATE OF d`, [scopedIdDigest(androidScopedId), appRow.id])).rows[0];
|
|
4990
|
+
if (!identity) {
|
|
4991
|
+
await client.query('ROLLBACK');
|
|
4992
|
+
res.status(403).json({ enrolled: false, recovery: 'browser', reason: 'not_bound_or_not_authorized' });
|
|
4993
|
+
return;
|
|
4994
|
+
}
|
|
4995
|
+
await client.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,last_seen_at)
|
|
4996
|
+
VALUES($1,$2,'android',$3,now()) ON CONFLICT(app_id,installation_id)
|
|
4997
|
+
DO UPDATE SET platform='android',runtime_version=excluded.runtime_version,last_seen_at=now()`, [appRow.id, installationId, runtimeVersion]);
|
|
4998
|
+
await client.query(`INSERT INTO ota_tester_installations(app_id,installation_id,label,enrolled_by,revoked_at)
|
|
4999
|
+
VALUES($1,$2,$3,$4,NULL) ON CONFLICT(app_id,installation_id) DO UPDATE SET
|
|
5000
|
+
label=excluded.label,enrolled_by=excluded.enrolled_by,enrolled_at=now(),revoked_at=NULL`, [appRow.id, installationId, identity.label, identity.owner_user_id]);
|
|
5001
|
+
await client.query(`INSERT INTO ota_registered_device_installations(device_id,app_id,installation_id)
|
|
5002
|
+
VALUES($1,$2,$3) ON CONFLICT(app_id,installation_id) DO UPDATE SET
|
|
5003
|
+
device_id=excluded.device_id,linked_at=now()`, [identity.id, appRow.id, installationId]);
|
|
5004
|
+
await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,platform,runtime_version,metadata)
|
|
5005
|
+
VALUES($1,$2,'device_enrolled','android',$3,$4)`, [appRow.id, installationId, runtimeVersion, { source: 'android_scoped_internal', assurance: 'identifier_only' }]);
|
|
5006
|
+
await client.query('COMMIT');
|
|
5007
|
+
res.json({ enrolled: true, assurance: 'identifier_only' });
|
|
5008
|
+
}
|
|
5009
|
+
catch (error) {
|
|
5010
|
+
await client.query('ROLLBACK').catch(() => { });
|
|
5011
|
+
throw error;
|
|
5012
|
+
}
|
|
5013
|
+
finally {
|
|
5014
|
+
client.release();
|
|
5015
|
+
}
|
|
5016
|
+
});
|
|
5017
|
+
// Only tester-enabled builds call this: never expose a phone's browser credential
|
|
5018
|
+
// or registered device identity to an unauthenticated app installation.
|
|
5019
|
+
app.get('/ota/v1/enrollment/status/:updatePath', async (req, res) => {
|
|
5020
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
5021
|
+
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
5022
|
+
if (!appRow) {
|
|
5023
|
+
res.status(404).json({ error: 'Unknown app.' });
|
|
5024
|
+
return;
|
|
5025
|
+
}
|
|
5026
|
+
const installationId = String(req.query.installationId || '');
|
|
5027
|
+
if (!/^[A-Za-z0-9_-]{12,200}$/.test(installationId)) {
|
|
5028
|
+
res.status(400).json({ error: 'Invalid installation ID.' });
|
|
5029
|
+
return;
|
|
5030
|
+
}
|
|
5031
|
+
const enrollment = await pool.query(`SELECT 1 FROM ota_tester_installations
|
|
5032
|
+
WHERE app_id=$1 AND installation_id=$2 AND revoked_at IS NULL`, [appRow.id, installationId]);
|
|
5033
|
+
const grants = await pool.query(`SELECT 1 FROM ota_device_app_grants g
|
|
5034
|
+
JOIN ota_registered_tester_devices d ON d.id=g.device_id
|
|
5035
|
+
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]);
|
|
5036
|
+
res.json({ enrolled: !!enrollment.rowCount, reconnectAvailable: !!grants.rowCount, appId: appRow.id });
|
|
5037
|
+
});
|
|
3788
5038
|
app.get('/ota/v1/manifest/:updatePath', async (req, res) => {
|
|
3789
5039
|
const appRow = await publicMobileApp(routeParam(req.params.updatePath));
|
|
3790
5040
|
if (!appRow) {
|
|
@@ -3819,7 +5069,7 @@ app.get('/ota/v1/manifest/:updatePath', async (req, res) => {
|
|
|
3819
5069
|
}
|
|
3820
5070
|
const candidates = (await pool.query(`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
|
|
3821
5071
|
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
|
|
3822
|
-
ORDER BY r.created_at DESC LIMIT 50`, [appRow.id, env.id, runtimeVersion, platform])).rows;
|
|
5072
|
+
ORDER BY r.created_at DESC,r.id DESC LIMIT 50`, [appRow.id, env.id, runtimeVersion, platform])).rows;
|
|
3823
5073
|
// Group membership is evaluated at request time: adding/revoking an enrolled
|
|
3824
5074
|
// tester takes effect without rebuilding or editing an existing release.
|
|
3825
5075
|
const currentGroups = new Set();
|
|
@@ -3835,12 +5085,63 @@ app.get('/ota/v1/manifest/:updatePath', async (req, res) => {
|
|
|
3835
5085
|
currentGroups.add(String(row.group_id));
|
|
3836
5086
|
}
|
|
3837
5087
|
}
|
|
3838
|
-
|
|
5088
|
+
// A device ID is trusted ONLY when derived server-side from a previously
|
|
5089
|
+
// linked installation, current app grant and current tester enrollment.
|
|
5090
|
+
// The client cannot request this audience by sending an arbitrary device ID.
|
|
5091
|
+
let approvedDeviceId = null;
|
|
5092
|
+
if (activeTester && identity.installationId) {
|
|
5093
|
+
const verified = (await pool.query(`SELECT li.device_id FROM ota_registered_device_installations li
|
|
5094
|
+
JOIN ota_registered_tester_devices d ON d.id=li.device_id
|
|
5095
|
+
JOIN ota_device_app_grants g ON g.device_id=d.id AND g.app_id=li.app_id
|
|
5096
|
+
JOIN ota_installations i ON i.app_id=li.app_id AND i.installation_id=li.installation_id
|
|
5097
|
+
WHERE li.app_id=$1 AND li.installation_id=$2 AND i.platform=$3 AND i.runtime_version=$4
|
|
5098
|
+
AND g.revoked_at IS NULL AND d.revoked_at IS NULL AND d.verified_at IS NOT NULL
|
|
5099
|
+
LIMIT 1`, [appRow.id, identity.installationId, platform, runtimeVersion])).rows[0];
|
|
5100
|
+
approvedDeviceId = verified?.device_id ? String(verified.device_id) : null;
|
|
5101
|
+
}
|
|
5102
|
+
// Retired aliases preserve immutable historical test-targeted release audiences.
|
|
5103
|
+
// Aliases cannot grant access: we only use them after verifying the active
|
|
5104
|
+
// surviving device, its current app grant, and the enrolled installation.
|
|
5105
|
+
const legacyDeviceIds = new Set();
|
|
5106
|
+
if (approvedDeviceId) {
|
|
5107
|
+
const aliases = (await pool.query(`SELECT duplicate_device_id FROM ota_tester_device_profile_aliases
|
|
5108
|
+
WHERE canonical_device_id=$1`, [approvedDeviceId])).rows;
|
|
5109
|
+
for (const item of aliases)
|
|
5110
|
+
legacyDeviceIds.add(String(item.duplicate_device_id));
|
|
5111
|
+
}
|
|
5112
|
+
const selected = candidates.find((row) => audienceMatches(row, identity, currentGroups, activeTester, approvedDeviceId, legacyDeviceIds));
|
|
3839
5113
|
if (!selected) {
|
|
3840
5114
|
res.status(204).end();
|
|
3841
5115
|
return;
|
|
3842
5116
|
}
|
|
3843
5117
|
const currentUpdate = String(req.headers['expo-current-update-id'] || identity.currentUpdateId || '');
|
|
5118
|
+
if (selected.recovery_kind === 'embedded') {
|
|
5119
|
+
// Roll back only the native runtime/platform/audience for which this
|
|
5120
|
+
// directive was created. Never broadcast an embedded rollback to every APK.
|
|
5121
|
+
const embeddedUpdate = String(req.headers['expo-embedded-update-id'] || '');
|
|
5122
|
+
if (!embeddedUpdate) {
|
|
5123
|
+
res.status(409).json({ error: 'Expo-Embedded-Update-ID is required for embedded recovery.' });
|
|
5124
|
+
return;
|
|
5125
|
+
}
|
|
5126
|
+
if (currentUpdate === embeddedUpdate) {
|
|
5127
|
+
res.status(204).end();
|
|
5128
|
+
return;
|
|
5129
|
+
}
|
|
5130
|
+
const directive = embeddedDirective(new Date(selected.update_created_at).toISOString());
|
|
5131
|
+
const json = JSON.stringify(directive);
|
|
5132
|
+
const signature = req.headers['expo-expect-signature']
|
|
5133
|
+
? (appRow.encrypted_signing_private_key ? signExpoManifest(json, appRow.encrypted_signing_private_key) : null)
|
|
5134
|
+
: undefined;
|
|
5135
|
+
if (signature === null) {
|
|
5136
|
+
res.status(500).json({ error: 'OTA signing key unavailable for recovery directive.' });
|
|
5137
|
+
return;
|
|
5138
|
+
}
|
|
5139
|
+
const part = multipartDirective(directive, signature || undefined, `indraq${selected.update_id.replace(/-/g, '')}`);
|
|
5140
|
+
res.setHeader('content-type', part.contentType);
|
|
5141
|
+
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)', [appRow.id, selected.id, selected.update_id, identity.installationId || null, 'embedded_recovery_served', platform, runtimeVersion, { channel }]);
|
|
5142
|
+
res.status(200).send(part.body);
|
|
5143
|
+
return;
|
|
5144
|
+
}
|
|
3844
5145
|
if (currentUpdate === selected.update_id) {
|
|
3845
5146
|
res.status(204).end();
|
|
3846
5147
|
return;
|
|
@@ -3965,4 +5266,31 @@ if (process.env.MINIO_ENDPOINT && process.env.MINIO_ACCESS_KEY && process.env.MI
|
|
|
3965
5266
|
await ensureOtaBucket();
|
|
3966
5267
|
console.log(`OTA MinIO bucket ready: ${minioBucket}`);
|
|
3967
5268
|
}
|
|
5269
|
+
// Opt-in scheduled orphan-upload GC. Safe defaults: dry-run only until explicitly
|
|
5270
|
+
// enabled after production verification. Leader elected by Postgres advisory lock.
|
|
5271
|
+
if (process.env.OTA_ORPHAN_GC_ENABLED === 'true') {
|
|
5272
|
+
const runGc = async () => {
|
|
5273
|
+
const client = await pool.connect();
|
|
5274
|
+
try {
|
|
5275
|
+
const lock = (await client.query('SELECT pg_try_advisory_lock(2120160) locked')).rows[0]?.locked;
|
|
5276
|
+
if (!lock)
|
|
5277
|
+
return;
|
|
5278
|
+
try {
|
|
5279
|
+
await collectUnreferencedAssets(50);
|
|
5280
|
+
}
|
|
5281
|
+
finally {
|
|
5282
|
+
await client.query('SELECT pg_advisory_unlock(2120160)');
|
|
5283
|
+
}
|
|
5284
|
+
}
|
|
5285
|
+
catch (error) {
|
|
5286
|
+
console.error('OTA orphan GC error', error);
|
|
5287
|
+
}
|
|
5288
|
+
finally {
|
|
5289
|
+
client.release();
|
|
5290
|
+
}
|
|
5291
|
+
};
|
|
5292
|
+
const timer = setInterval(() => { void runGc(); }, 6 * 60 * 60 * 1000);
|
|
5293
|
+
timer.unref();
|
|
5294
|
+
}
|
|
3968
5295
|
app.listen(Number(process.env.PORT || 4010), () => console.log(`IndraQ Cloud API listening on ${process.env.PORT || 4010}`));
|
|
5296
|
+
//# sourceMappingURL=index.js.map
|