indraq_cli 2.7.3 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +1547 -0
  2. package/cloud-api/README.md +6 -0
  3. package/cloud-api/dist/index.js +322 -74
  4. package/cloud-api/package.json +1 -1
  5. package/cloud-api/sql/013_ota_tester_enrollment.sql +55 -0
  6. package/cloud-api/sql/014_mobile_native_build_history.sql +50 -0
  7. package/cloud-api/src/index.ts +250 -63
  8. package/dist/cli/help-content.d.ts.map +1 -1
  9. package/dist/cli/help-content.js +13 -3
  10. package/dist/cli/help-content.js.map +1 -1
  11. package/dist/modules/cloud/services/cloud-api.service.d.ts.map +1 -1
  12. package/dist/modules/cloud/services/cloud-api.service.js +53 -15
  13. package/dist/modules/cloud/services/cloud-api.service.js.map +1 -1
  14. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts +6 -1
  15. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts.map +1 -1
  16. package/dist/modules/cloud/services/cloud-jenkins.service.js +62 -5
  17. package/dist/modules/cloud/services/cloud-jenkins.service.js.map +1 -1
  18. package/dist/modules/mobile/commands/build-mobile.command.js +3 -3
  19. package/dist/modules/mobile/commands/build-mobile.command.js.map +1 -1
  20. package/dist/modules/mobile/commands/configure-mobile.command.js +1 -1
  21. package/dist/modules/mobile/commands/configure-mobile.command.js.map +1 -1
  22. package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts.map +1 -1
  23. package/dist/modules/mobile/commands/mobile-prebuild.command.js +20 -14
  24. package/dist/modules/mobile/commands/mobile-prebuild.command.js.map +1 -1
  25. package/dist/modules/mobile/commands/ota.command.d.ts.map +1 -1
  26. package/dist/modules/mobile/commands/ota.command.js +199 -64
  27. package/dist/modules/mobile/commands/ota.command.js.map +1 -1
  28. package/dist/modules/mobile/commands/testers.command.d.ts +7 -0
  29. package/dist/modules/mobile/commands/testers.command.d.ts.map +1 -0
  30. package/dist/modules/mobile/commands/testers.command.js +166 -0
  31. package/dist/modules/mobile/commands/testers.command.js.map +1 -0
  32. package/dist/modules/mobile/index.d.ts.map +1 -1
  33. package/dist/modules/mobile/index.js +24 -1
  34. package/dist/modules/mobile/index.js.map +1 -1
  35. package/dist/modules/mobile/services/mobile-cloud.service.d.ts +83 -0
  36. package/dist/modules/mobile/services/mobile-cloud.service.d.ts.map +1 -1
  37. package/dist/modules/mobile/services/mobile-cloud.service.js +19 -1
  38. package/dist/modules/mobile/services/mobile-cloud.service.js.map +1 -1
  39. package/dist/modules/mobile/services/ota-identity.service.d.ts +20 -0
  40. package/dist/modules/mobile/services/ota-identity.service.d.ts.map +1 -0
  41. package/dist/modules/mobile/services/ota-identity.service.js +169 -0
  42. package/dist/modules/mobile/services/ota-identity.service.js.map +1 -0
  43. package/dist/modules/mobile/services/ota-setup.service.d.ts +1 -0
  44. package/dist/modules/mobile/services/ota-setup.service.d.ts.map +1 -1
  45. package/dist/modules/mobile/services/ota-setup.service.js +268 -24
  46. package/dist/modules/mobile/services/ota-setup.service.js.map +1 -1
  47. package/dist/shared/process/run-npx.d.ts +7 -0
  48. package/dist/shared/process/run-npx.d.ts.map +1 -1
  49. package/dist/shared/process/run-npx.js +42 -1
  50. package/dist/shared/process/run-npx.js.map +1 -1
  51. package/package.json +17 -4
  52. package/vendor/QR-CODE-APACHE-2.0-LICENSE.txt +222 -0
  53. package/vendor/QR-CODE-MIT-LICENSE.txt +21 -0
  54. package/vendor/QR-CODE-NOTICE.txt +6 -0
  55. package/vendor/QRCode/QR8bitByte.js +22 -0
  56. package/vendor/QRCode/QRBitBuffer.js +38 -0
  57. package/vendor/QRCode/QRErrorCorrectLevel.js +7 -0
  58. package/vendor/QRCode/QRMaskPattern.js +10 -0
  59. package/vendor/QRCode/QRMath.js +44 -0
  60. package/vendor/QRCode/QRMode.js +6 -0
  61. package/vendor/QRCode/QRPolynomial.js +66 -0
  62. package/vendor/QRCode/QRRSBlock.js +298 -0
  63. package/vendor/QRCode/QRUtil.js +272 -0
  64. package/vendor/QRCode/index.js +462 -0
@@ -128,3 +128,9 @@ A successful `/auth/login` creates a server-side `auth_sessions` row and returns
128
128
  - Secret-resolution responses are `Cache-Control: no-store` and audited.
129
129
  - Role/account state is re-read from PostgreSQL on protected requests so demotion/disable takes effect without waiting for JWT expiry.
130
130
  - Keep bootstrap credentials and `MASTER_KEY` out of source control.
131
+
132
+ ## OTA tester enrollment (API v1.3.6)
133
+
134
+ The database migrates automatically with `sql/013_ota_tester_enrollment.sql`. After project owner mobile prebuild has registered the app deep-link scheme, authenticated project members with VIEW access can create short-lived, single-use invitation QR URLs using `POST /mobile/apps/:appId/enrollments` and list apps via `GET /mobile/apps`. Group creation/revocation requires WRITE; OTA publication always requires WRITE.
135
+
136
+ The public `GET /ota/enroll/:token` landing page opens the installed app with its native deep link. The generated Expo OTA bootstrap calls `POST /ota/v1/enroll/redeem` to bind the existing anonymous installation to a named tester and optional group. Only a SHA-256 hash of the token is stored. Enrollment has no Cloud login/auth privileges. Group membership is checked during manifest selection. Existing Jenkins pipeline jobs are not modified.
@@ -285,6 +285,9 @@ const runJenkinsManagementGroovy = async (connection, script) => {
285
285
  throw new Error(`Jenkins control-plane operation failed (HTTP ${response.status}): ${compactJenkinsError(body)}`);
286
286
  return body.trim();
287
287
  };
288
+ // Security contract: IndraQ Cloud never creates, repairs, rewrites or changes a
289
+ // mobile Jenkins job. The job is managed entirely in Jenkins. Legacy control
290
+ // operations are rejected below, including requests from older CLI versions.
288
291
  const jenkinsConsoleTail = async (connection, buildUrl) => {
289
292
  try {
290
293
  const response = await fetch(`${buildUrl.replace(/\/$/, '')}/consoleText`, { headers: { authorization: jenkinsBasic(connection) } });
@@ -2577,49 +2580,12 @@ app.post('/projects/:projectId/jenkins-control', auth, async (req, res) => {
2577
2580
  res.json({ exists: true });
2578
2581
  return;
2579
2582
  }
2580
- if (operation === 'ensure-mobile-job') {
2581
- const jobName = String(req.body?.jobName || '').trim();
2582
- const pipelineScript = String(req.body?.pipelineScript || '');
2583
- if (jobName !== 'Mobile app Cli build') {
2584
- res.status(400).json({ error: 'Only the managed IndraQ mobile build job may be reconciled through this operation.' });
2585
- return;
2586
- }
2587
- if (!pipelineScript || pipelineScript.length > 250_000) {
2588
- res.status(400).json({ error: 'pipelineScript is required and must be 250 KB or smaller.' });
2589
- return;
2590
- }
2591
- const xmlEscape = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
2592
- const configXml = `<?xml version="1.1" encoding="UTF-8"?>
2593
- <flow-definition plugin="workflow-job">
2594
- <actions/>
2595
- <description>Managed by IndraQ CLI for mobile builds.</description>
2596
- <keepDependencies>false</keepDependencies>
2597
- <properties/>
2598
- <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps">
2599
- <script>${xmlEscape(pipelineScript)}</script>
2600
- <sandbox>true</sandbox>
2601
- </definition>
2602
- <triggers/>
2603
- <disabled>false</disabled>
2604
- </flow-definition>
2605
- `;
2606
- const headers = { ...(await jenkinsHeaders(resolved.connection)), 'content-type': 'application/xml' };
2607
- const lookup = await fetch(`${resolved.connection.url}/${jenkinsJobPath(jobName)}/api/json`, { headers: { authorization: jenkinsBasic(resolved.connection) } });
2608
- let response;
2609
- if (lookup.status === 404) {
2610
- response = await fetch(`${resolved.connection.url}/createItem?name=${encodeURIComponent(jobName)}`, { method: 'POST', headers, body: configXml });
2611
- }
2612
- else if (lookup.ok) {
2613
- response = await fetch(`${resolved.connection.url}/${jenkinsJobPath(jobName)}/config.xml`, { method: 'POST', headers, body: configXml });
2614
- }
2615
- else {
2616
- throw new Error(`Jenkins job lookup failed for ${jobName} (HTTP ${lookup.status}).`);
2617
- }
2618
- const responseBody = await response.text();
2619
- if (!response.ok)
2620
- throw new Error(`Unable to reconcile Jenkins mobile job ${jobName} (HTTP ${response.status}): ${compactJenkinsError(responseBody)}`);
2621
- await audit(req.auth.id, 'jenkins.control.mobile-job.ensure', 'project', projectId, reason, { environment, provider: resolved.provider, scopeId: resolved.scopeId, jobName });
2622
- res.json({ ok: true, jobName });
2583
+ // Deny legacy mobile mutations from ALL CLI versions. Do not call Jenkins,
2584
+ // load a Jenkinsfile, update parameters or create a job here.
2585
+ if (operation === 'ensure-mobile-job' || operation === 'repair-mobile-job-parameters') {
2586
+ res.status(409).json({
2587
+ error: 'IndraQ never creates or changes mobile Jenkins pipelines. Configure Mobile app Cli build and its parameters manually in Jenkins, then retry mobile prebuild/build.'
2588
+ });
2623
2589
  return;
2624
2590
  }
2625
2591
  if (operation === 'host-port-check') {
@@ -3063,7 +3029,7 @@ const requestIdentity = (req) => {
3063
3029
  currentUpdateId: value('x-indraq-current-update-id', 'indraq-current-update-id', 200)
3064
3030
  };
3065
3031
  };
3066
- const audienceMatches = (row, identity) => {
3032
+ const audienceMatches = (row, identity, groups = new Set(), activeTester = false) => {
3067
3033
  if (row.status === 'released' && row.audience_type === 'all')
3068
3034
  return true;
3069
3035
  if (row.status === 'released' && row.audience_type === 'percentage') {
@@ -3072,6 +3038,11 @@ const audienceMatches = (row, identity) => {
3072
3038
  const bucket = Number.parseInt(createHash('sha256').update(`${identity.installationId}:${row.id}`).digest('hex').slice(0, 8), 16) % 100;
3073
3039
  return bucket < Number(row.rollout_percent);
3074
3040
  }
3041
+ const groupIds = Array.isArray(row.audience?.groupIds) ? row.audience.groupIds : [];
3042
+ if (groupIds.some((id) => groups.has(String(id))))
3043
+ return true;
3044
+ if (row.audience?.enrolledOnly === true && !activeTester)
3045
+ return false;
3075
3046
  const identities = Array.isArray(row.audience?.identities) ? row.audience.identities : [];
3076
3047
  return identities.some((item) => {
3077
3048
  const expected = String(item.value || '').trim().toLowerCase();
@@ -3090,6 +3061,210 @@ const audienceMatches = (row, identity) => {
3090
3061
  return false;
3091
3062
  });
3092
3063
  };
3064
+ // QR enrollment is available to every ACTIVE IndraQ user who can access this
3065
+ // mobile project. It is not a publishing permission. QR possession grants only
3066
+ // tester device enrollment, never Cloud login or project write privileges.
3067
+ const enrollmentTokenPattern = /^[A-Za-z0-9_-]{43}$/;
3068
+ const enrollmentSchemePattern = /^[a-z][a-z0-9+.-]{1,39}$/;
3069
+ const hashEnrollmentToken = (token) => createHash('sha256').update(token).digest('hex');
3070
+ app.get('/mobile/apps', auth, async (req, res) => {
3071
+ // All project members, including normal users with VIEW, may select their own app.
3072
+ const rows = (await pool.query(`SELECT ma.id,ma.project_id,ma.app_name,ma.project_type,ma.enrollment_scheme,p.name project_name
3073
+ FROM mobile_apps ma JOIN projects p ON p.id=ma.project_id
3074
+ LEFT JOIN project_members pm ON pm.project_id=p.id AND pm.user_id=$1
3075
+ WHERE p.archived_at IS NULL AND ($2='admin' OR p.created_by=$1 OR pm.user_id=$1)
3076
+ ORDER BY p.name,ma.app_name LIMIT 500`, [req.auth.id, req.auth.role])).rows;
3077
+ 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
+ });
3079
+ app.get('/mobile/apps/:appId/installations', auth, async (req, res) => {
3080
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
3081
+ if (!appRow) {
3082
+ res.status(404).json({ error: 'Mobile app not found or access denied.' });
3083
+ return;
3084
+ }
3085
+ const rows = (await pool.query(`SELECT i.installation_id,i.platform,i.runtime_version,i.app_version,i.first_seen_at,i.last_seen_at,
3086
+ t.label tester_label,(t.revoked_at IS NULL AND t.installation_id IS NOT NULL) is_tester
3087
+ FROM ota_installations i LEFT JOIN ota_tester_installations t ON t.app_id=i.app_id AND t.installation_id=i.installation_id
3088
+ WHERE i.app_id=$1 ORDER BY i.last_seen_at DESC LIMIT 500`, [appRow.id])).rows;
3089
+ res.json(rows);
3090
+ });
3091
+ app.get('/mobile/apps/:appId/testers', auth, async (req, res) => {
3092
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
3093
+ if (!appRow) {
3094
+ res.status(404).json({ error: 'Mobile app not found or access denied.' });
3095
+ return;
3096
+ }
3097
+ const groups = (await pool.query(`SELECT g.id,g.name,g.created_at,count(m.installation_id) FILTER(WHERE t.revoked_at IS NULL)::int member_count
3098
+ FROM ota_tester_groups g LEFT JOIN ota_tester_group_members m ON m.group_id=g.id
3099
+ LEFT JOIN ota_tester_installations t ON t.app_id=m.app_id AND t.installation_id=m.installation_id
3100
+ WHERE g.app_id=$1 GROUP BY g.id ORDER BY g.name`, [appRow.id])).rows;
3101
+ const testers = (await pool.query(`SELECT t.installation_id,t.label,t.enrolled_at,t.revoked_at,i.platform,i.runtime_version,i.last_seen_at,
3102
+ COALESCE(array_agg(m.group_id) FILTER (WHERE m.group_id IS NOT NULL),'{}'::uuid[]) group_ids
3103
+ FROM ota_tester_installations t JOIN ota_installations i ON i.app_id=t.app_id AND i.installation_id=t.installation_id
3104
+ LEFT JOIN ota_tester_group_members m ON m.app_id=t.app_id AND m.installation_id=t.installation_id
3105
+ WHERE t.app_id=$1 GROUP BY t.installation_id,t.label,t.enrolled_at,t.revoked_at,i.platform,i.runtime_version,i.last_seen_at
3106
+ ORDER BY t.enrolled_at DESC`, [appRow.id])).rows;
3107
+ res.json({ groups, testers });
3108
+ });
3109
+ app.post('/mobile/apps/:appId/tester-groups', auth, async (req, res) => {
3110
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth, true);
3111
+ if (!appRow) {
3112
+ res.status(404).json({ error: 'Mobile app not found or WRITE access denied.' });
3113
+ return;
3114
+ }
3115
+ const name = textValue(req.body?.name, 'Group name', 80);
3116
+ const result = await pool.query(`INSERT INTO ota_tester_groups(app_id,name,created_by) VALUES($1,$2,$3)
3117
+ ON CONFLICT (app_id,name) DO NOTHING RETURNING id,name,created_at`, [appRow.id, name, req.auth.id]);
3118
+ if (!result.rowCount) {
3119
+ res.status(409).json({ error: 'A tester group with this name already exists.' });
3120
+ return;
3121
+ }
3122
+ await audit(req.auth.id, 'ota.testers.group.create', 'mobile-app', appRow.id, 'Create OTA tester group', { groupId: result.rows[0].id, name });
3123
+ res.status(201).json(result.rows[0]);
3124
+ });
3125
+ app.post('/mobile/apps/:appId/enrollments', auth, async (req, res) => {
3126
+ // Project READ permission is intentional: every active, authorized member
3127
+ // can generate an enrollment QR without a manager/admin or write grant.
3128
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
3129
+ if (!appRow) {
3130
+ res.status(404).json({ error: 'Mobile app not found or access denied.' });
3131
+ return;
3132
+ }
3133
+ const label = textValue(req.body?.label, 'Device/tester label', 80);
3134
+ // Readers cannot redirect enrollment to a different app by supplying a scheme.
3135
+ const scheme = String(appRow.enrollment_scheme || '').trim().toLowerCase();
3136
+ if (!enrollmentSchemePattern.test(scheme)) {
3137
+ res.status(409).json({ error: 'This app has no registered deep-link scheme. Ask a project owner to run `indraq mobile prebuild` and rebuild the app.' });
3138
+ return;
3139
+ }
3140
+ const ttlMinutes = Number(req.body?.ttlMinutes || 15);
3141
+ if (!Number.isInteger(ttlMinutes) || ttlMinutes < 5 || ttlMinutes > 60) {
3142
+ res.status(400).json({ error: 'Invitation TTL must be between 5 and 60 minutes.' });
3143
+ return;
3144
+ }
3145
+ const groupId = req.body?.groupId ? ensureUuid(String(req.body.groupId), 'Tester group ID') : null;
3146
+ if (groupId) {
3147
+ const exists = await pool.query('SELECT 1 FROM ota_tester_groups WHERE id=$1 AND app_id=$2', [groupId, appRow.id]);
3148
+ if (!exists.rowCount) {
3149
+ res.status(404).json({ error: 'Tester group not found in this app.' });
3150
+ return;
3151
+ }
3152
+ }
3153
+ 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 });
3157
+ res.setHeader('Cache-Control', 'no-store');
3158
+ res.status(201).json({ id: row.id, appName: appRow.app_name, label, groupId, expiresAt: row.expires_at,
3159
+ enrollmentUrl: `${publicApiUrl}/ota/enroll/${token}` });
3160
+ });
3161
+ app.get('/mobile/apps/:appId/enrollments', auth, async (req, res) => {
3162
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
3163
+ if (!appRow) {
3164
+ res.status(404).json({ error: 'Mobile app not found or access denied.' });
3165
+ return;
3166
+ }
3167
+ const rows = (await pool.query(`SELECT id,label,group_id,created_at,expires_at,redeemed_at,redeemed_installation_id,revoked_at
3168
+ FROM ota_enrollment_invitations WHERE app_id=$1 ORDER BY created_at DESC LIMIT 100`, [appRow.id])).rows;
3169
+ res.json(rows);
3170
+ });
3171
+ app.patch('/mobile/apps/:appId/testers/:installationId', auth, async (req, res) => {
3172
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth, true);
3173
+ if (!appRow) {
3174
+ res.status(404).json({ error: 'Mobile app not found or WRITE access denied.' });
3175
+ return;
3176
+ }
3177
+ const label = textValue(req.body?.label, 'Device name', 80);
3178
+ const installationId = routeParam(req.params.installationId);
3179
+ const row = (await pool.query(`UPDATE ota_tester_installations SET label=$1
3180
+ WHERE app_id=$2 AND installation_id=$3 AND revoked_at IS NULL RETURNING installation_id,label`, [label, appRow.id, installationId])).rows[0];
3181
+ if (!row) {
3182
+ res.status(404).json({ error: 'Active tester device not found.' });
3183
+ return;
3184
+ }
3185
+ await audit(req.auth.id, 'ota.testers.rename', 'mobile-app', appRow.id, 'Rename enrolled tester device', { installationId, label });
3186
+ res.json(row);
3187
+ });
3188
+ app.delete('/mobile/apps/:appId/testers/:installationId', auth, async (req, res) => {
3189
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth, true);
3190
+ if (!appRow) {
3191
+ res.status(404).json({ error: 'Mobile app not found or WRITE access denied.' });
3192
+ return;
3193
+ }
3194
+ const installationId = routeParam(req.params.installationId);
3195
+ const result = await pool.query(`UPDATE ota_tester_installations SET revoked_at=now() WHERE app_id=$1 AND installation_id=$2 AND revoked_at IS NULL RETURNING installation_id`, [appRow.id, installationId]);
3196
+ if (!result.rowCount) {
3197
+ res.status(404).json({ error: 'Active tester installation not found.' });
3198
+ return;
3199
+ }
3200
+ await audit(req.auth.id, 'ota.testers.revoke', 'mobile-app', appRow.id, 'Revoke OTA tester enrollment', { installationId });
3201
+ res.status(204).end();
3202
+ });
3203
+ app.get('/ota/enroll/:token', async (req, res) => {
3204
+ const token = routeParam(req.params.token);
3205
+ res.setHeader('Cache-Control', 'no-store');
3206
+ res.setHeader('Referrer-Policy', 'no-referrer');
3207
+ res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'");
3208
+ if (!enrollmentTokenPattern.test(token)) {
3209
+ res.status(404).type('text/plain').send('Invalid enrollment invitation.');
3210
+ return;
3211
+ }
3212
+ const item = (await pool.query(`SELECT e.app_scheme,ma.app_name,e.label FROM ota_enrollment_invitations e
3213
+ JOIN mobile_apps ma ON ma.id=e.app_id WHERE e.token_hash=$1 AND e.expires_at>now()
3214
+ AND e.revoked_at IS NULL AND e.redeemed_at IS NULL`, [hashEnrollmentToken(token)])).rows[0];
3215
+ if (!item) {
3216
+ res.status(410).type('text/plain').send('This invitation is expired or already used. Request a fresh QR code.');
3217
+ return;
3218
+ }
3219
+ // app_scheme is strictly validated on invitation creation and cannot contain HTML.
3220
+ const deepLink = `${item.app_scheme}://indraq-enroll?token=${token}`;
3221
+ const escapeHtml = (v) => String(v).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c] || c));
3222
+ res.type('html').send(`<!doctype html><html lang="en"><head><meta name="viewport" content="width=device-width, initial-scale=1"><title>IndraQ OTA Enrollment</title><style>body{font-family:system-ui,sans-serif;max-width:480px;margin:14vh auto;padding:24px;color:#17202a}a{display:block;text-align:center;background:#174ed6;color:#fff;padding:16px;border-radius:9px;text-decoration:none;font-weight:700}p{line-height:1.55}</style></head><body><h2>Enroll ${escapeHtml(item.app_name)} device</h2><p>Device: ${escapeHtml(item.label)}</p><p>On the phone where ${escapeHtml(item.app_name)} is installed, tap below. The invitation can be used once.</p><a href="${escapeHtml(deepLink)}">Open ${escapeHtml(item.app_name)} to enroll</a><p>If the app does not open, install the IndraQ-enabled release and try again. This invitation does not grant a user account or login access.</p></body></html>`);
3223
+ });
3224
+ app.post('/ota/v1/enroll/redeem', async (req, res) => {
3225
+ const token = String(req.body?.token || '');
3226
+ const installationId = String(req.body?.installationId || '').trim();
3227
+ if (!enrollmentTokenPattern.test(token) || !/^[A-Za-z0-9_-]{12,200}$/.test(installationId)) {
3228
+ res.status(400).json({ error: 'Invalid invitation or installation ID.' });
3229
+ return;
3230
+ }
3231
+ const digest = hashEnrollmentToken(token);
3232
+ const client = await pool.connect();
3233
+ try {
3234
+ await client.query('BEGIN');
3235
+ const invite = (await client.query(`SELECT e.*,ma.app_name FROM ota_enrollment_invitations e
3236
+ JOIN mobile_apps ma ON ma.id=e.app_id WHERE e.token_hash=$1 AND e.expires_at>now() AND e.revoked_at IS NULL AND e.redeemed_at IS NULL FOR UPDATE OF e`, [digest])).rows[0];
3237
+ if (!invite) {
3238
+ await client.query('ROLLBACK');
3239
+ res.status(410).json({ error: 'Invitation expired or already redeemed.' });
3240
+ return;
3241
+ }
3242
+ const installed = await client.query('SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2', [invite.app_id, installationId]);
3243
+ if (!installed.rowCount) {
3244
+ await client.query('ROLLBACK');
3245
+ res.status(409).json({ error: 'This installation has not registered with the app OTA service. Open the release app online before enrolling.' });
3246
+ return;
3247
+ }
3248
+ await client.query(`INSERT INTO ota_tester_installations(app_id,installation_id,label,enrolled_by,revoked_at)
3249
+ VALUES($1,$2,$3,$4,NULL) ON CONFLICT(app_id,installation_id) DO UPDATE SET label=excluded.label,enrolled_by=excluded.enrolled_by,enrolled_at=now(),revoked_at=NULL`, [invite.app_id, installationId, invite.label, invite.created_by]);
3250
+ if (invite.group_id) {
3251
+ await client.query(`INSERT INTO ota_tester_group_members(app_id,group_id,installation_id,added_by)
3252
+ VALUES($1,$2,$3,$4) ON CONFLICT(group_id,installation_id) DO NOTHING`, [invite.app_id, invite.group_id, installationId, invite.created_by]);
3253
+ }
3254
+ await client.query('UPDATE ota_enrollment_invitations SET redeemed_at=now(),redeemed_installation_id=$2 WHERE id=$1', [invite.id, installationId]);
3255
+ await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,metadata)
3256
+ VALUES($1,$2,'device_enrolled',$3)`, [invite.app_id, installationId, { inviteId: invite.id, groupId: invite.group_id }]);
3257
+ await client.query('COMMIT');
3258
+ res.status(200).json({ ok: true, appName: invite.app_name, label: invite.label, groupId: invite.group_id || null });
3259
+ }
3260
+ catch (error) {
3261
+ await client.query('ROLLBACK').catch(() => { });
3262
+ throw error;
3263
+ }
3264
+ finally {
3265
+ client.release();
3266
+ }
3267
+ });
3093
3268
  const signExpoManifest = (manifestString, encryptedPrivateKey) => {
3094
3269
  const signer = createSign('RSA-SHA256');
3095
3270
  signer.update(manifestString);
@@ -3172,11 +3347,14 @@ app.get('/projects/:projectId/mobile', auth, async (req, res) => {
3172
3347
  res.status(404).json({ error: 'Project not found or access denied' });
3173
3348
  return;
3174
3349
  }
3175
- const appRow = (await pool.query(`SELECT ma.id,ma.project_id,ma.app_name,ma.project_type,ma.android_package,ma.ios_bundle_identifier,ma.runtime_policy,ma.update_path,ma.signing_key_id,ma.signing_certificate,
3350
+ const appRow = (await pool.query(`SELECT ma.id,ma.project_id,ma.app_name,ma.project_type,ma.android_package,ma.ios_bundle_identifier,ma.enrollment_scheme,ma.runtime_policy,ma.update_path,ma.signing_key_id,ma.signing_certificate,
3176
3351
  me.id environment_id,me.name environment_name,me.slug environment_slug,me.build_type,me.jenkins_stage,me.ota_channel,mae.runtime_version,mae.enabled,
3177
- mae.native_fingerprint,mae.native_build_version,mae.native_build_version_code,mae.native_build_number,mae.native_build_url,mae.native_build_source_sha256,mae.native_built_at
3352
+ nb.native_fingerprint,nb.app_version AS native_build_version,nb.version_code AS native_build_version_code,nb.build_number AS native_build_number,nb.build_url AS native_build_url,nb.source_sha256 AS native_build_source_sha256,nb.built_at AS native_built_at
3178
3353
  FROM mobile_apps ma
3179
3354
  LEFT JOIN mobile_app_environments mae ON mae.app_id=ma.id
3355
+ LEFT JOIN LATERAL (SELECT b.* FROM mobile_native_builds b
3356
+ WHERE b.app_id=mae.app_id AND b.mobile_environment_id=mae.mobile_environment_id AND b.runtime_version=mae.runtime_version
3357
+ ORDER BY b.built_at DESC LIMIT 1) nb ON true
3180
3358
  LEFT JOIN mobile_environments me ON me.id=mae.mobile_environment_id
3181
3359
  WHERE ma.project_id=$1 ORDER BY me.name`, [projectId])).rows;
3182
3360
  if (!appRow.length) {
@@ -3185,7 +3363,7 @@ app.get('/projects/:projectId/mobile', auth, async (req, res) => {
3185
3363
  }
3186
3364
  const first = appRow[0];
3187
3365
  res.json({
3188
- id: first.id, projectId: first.project_id, appName: first.app_name, projectType: first.project_type, androidPackage: first.android_package, iosBundleIdentifier: first.ios_bundle_identifier,
3366
+ id: first.id, projectId: first.project_id, appName: first.app_name, projectType: first.project_type, androidPackage: first.android_package, iosBundleIdentifier: first.ios_bundle_identifier, enrollmentScheme: first.enrollment_scheme || null,
3189
3367
  runtimePolicy: first.runtime_policy, updateUrl: `${publicApiUrl}/ota/v1/manifest/${first.update_path}`, keyId: first.signing_key_id, certificate: first.signing_certificate,
3190
3368
  environments: appRow.filter((r) => r.environment_id).map((r) => ({ id: r.environment_id, name: r.environment_name, slug: r.environment_slug, buildType: r.build_type, jenkinsStage: r.jenkins_stage, otaChannel: r.ota_channel, runtimeVersion: r.runtime_version, enabled: r.enabled, nativeFingerprint: r.native_fingerprint, nativeBuildVersion: r.native_build_version, nativeBuildVersionCode: r.native_build_version_code === null ? null : Number(r.native_build_version_code), nativeBuildNumber: r.native_build_number, nativeBuildUrl: r.native_build_url, nativeBuildSourceSha256: r.native_build_source_sha256, nativeBuiltAt: r.native_built_at }))
3191
3369
  });
@@ -3204,6 +3382,11 @@ app.post('/projects/:projectId/mobile/register', auth, async (req, res) => {
3204
3382
  res.status(400).json({ error: 'OTA registration requires a mobile or backend-mobile project.' });
3205
3383
  return;
3206
3384
  }
3385
+ const schemeInput = req.body?.enrollmentScheme === undefined || req.body?.enrollmentScheme === null ? '' : String(req.body.enrollmentScheme).trim().toLowerCase();
3386
+ if (schemeInput && !enrollmentSchemePattern.test(schemeInput)) {
3387
+ res.status(400).json({ error: 'enrollmentScheme must be a valid native application deep-link scheme.' });
3388
+ return;
3389
+ }
3207
3390
  const appName = textValue(req.body?.appName, 'App name', 100);
3208
3391
  const projectType = String(req.body?.projectType || '').trim();
3209
3392
  if (!['expo', 'react-native'].includes(projectType)) {
@@ -3224,21 +3407,16 @@ app.post('/projects/:projectId/mobile/register', auth, async (req, res) => {
3224
3407
  res.status(400).json({ error: 'First OTA registration requires signingPrivateKey and signingCertificate.' });
3225
3408
  return;
3226
3409
  }
3227
- const appResult = await pool.query(`INSERT INTO mobile_apps(project_id,app_name,project_type,android_package,ios_bundle_identifier,update_path,encrypted_signing_private_key,signing_certificate,created_by)
3228
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)
3410
+ const appResult = await pool.query(`INSERT INTO mobile_apps(project_id,app_name,project_type,android_package,ios_bundle_identifier,update_path,encrypted_signing_private_key,signing_certificate,created_by,enrollment_scheme)
3411
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
3229
3412
  ON CONFLICT(project_id) DO UPDATE SET app_name=excluded.app_name,project_type=excluded.project_type,android_package=excluded.android_package,ios_bundle_identifier=excluded.ios_bundle_identifier,
3230
- encrypted_signing_private_key=COALESCE(excluded.encrypted_signing_private_key,mobile_apps.encrypted_signing_private_key),signing_certificate=COALESCE(excluded.signing_certificate,mobile_apps.signing_certificate),updated_at=now()
3231
- RETURNING *`, [projectId, appName, projectType, req.body?.androidPackage || null, req.body?.iosBundleIdentifier || null, existing?.update_path || randomBytes(24).toString('base64url'), privateKey ? encrypt(privateKey) : null, certificate || null, req.auth.id]);
3413
+ enrollment_scheme=COALESCE(excluded.enrollment_scheme,mobile_apps.enrollment_scheme),encrypted_signing_private_key=COALESCE(excluded.encrypted_signing_private_key,mobile_apps.encrypted_signing_private_key),signing_certificate=COALESCE(excluded.signing_certificate,mobile_apps.signing_certificate),updated_at=now()
3414
+ RETURNING *`, [projectId, appName, projectType, req.body?.androidPackage || null, req.body?.iosBundleIdentifier || null, existing?.update_path || randomBytes(24).toString('base64url'), privateKey ? encrypt(privateKey) : null, certificate || null, req.auth.id, schemeInput || null]);
3232
3415
  const appRow = appResult.rows[0];
3233
3416
  await pool.query(`INSERT INTO mobile_app_environments(app_id,mobile_environment_id,runtime_version) VALUES($1,$2,$3)
3234
3417
  ON CONFLICT(app_id,mobile_environment_id) DO UPDATE SET
3235
- native_fingerprint=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_fingerprint END,
3236
- native_build_version=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_build_version END,
3237
- native_build_version_code=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_build_version_code END,
3238
- native_build_number=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_build_number END,
3239
- native_build_url=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_build_url END,
3240
- native_build_source_sha256=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_build_source_sha256 END,
3241
- native_built_at=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_built_at END,
3418
+ -- Keep the last successful native baseline as a historical pointer.
3419
+ -- Prebuild NEVER clears a successful binary's fingerprint.
3242
3420
  runtime_version=excluded.runtime_version,enabled=true,updated_at=now()`, [appRow.id, environmentId, runtimeVersion]);
3243
3421
  await audit(req.auth.id, 'mobile.app.register', 'mobile-app', appRow.id, reason, { projectId, environmentId, runtimeVersion, projectType });
3244
3422
  res.json({ id: appRow.id, projectId, appName: appRow.app_name, projectType: appRow.project_type, updateUrl: `${publicApiUrl}/ota/v1/manifest/${appRow.update_path}`, keyId: appRow.signing_key_id, certificate: appRow.signing_certificate, environment: { id: env.id, name: env.name, slug: env.slug, buildType: env.build_type, jenkinsStage: env.jenkins_stage, otaChannel: env.ota_channel, runtimeVersion } });
@@ -3285,10 +3463,30 @@ app.post('/mobile/apps/:appId/environments/:environmentId/native-build', auth, a
3285
3463
  res.status(400).json({ error: 'sourceSha256 must be a 64-character SHA-256 hex value.' });
3286
3464
  return;
3287
3465
  }
3466
+ // Persist every successful build. A future prebuild cannot invalidate it.
3467
+ const savedBuild = (await pool.query(`INSERT INTO mobile_native_builds
3468
+ (app_id,mobile_environment_id,runtime_version,native_fingerprint,app_version,version_code,build_number,build_url,source_sha256,built_at,recorded_by)
3469
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,now(),$10)
3470
+ ON CONFLICT (app_id,mobile_environment_id,build_number) WHERE build_number IS NOT NULL
3471
+ DO UPDATE SET build_url=EXCLUDED.build_url
3472
+ RETURNING id`, [appRow.id, environmentId, runtimeVersion, nativeFingerprint, appVersion, versionCode, buildNumber, buildUrl, sourceSha || null, req.auth.id])).rows[0];
3288
3473
  const row = (await pool.query(`UPDATE mobile_app_environments SET native_fingerprint=$1,native_build_version=$2,native_build_version_code=$3,native_build_number=$4,native_build_url=$5,native_build_source_sha256=$6,native_built_at=now(),updated_at=now()
3289
3474
  WHERE app_id=$7 AND mobile_environment_id=$8 RETURNING runtime_version,native_fingerprint,native_build_version,native_build_version_code,native_build_number,native_build_url,native_build_source_sha256,native_built_at`, [nativeFingerprint, appVersion, versionCode, buildNumber, buildUrl, sourceSha || null, appRow.id, environmentId])).rows[0];
3290
3475
  await audit(req.auth.id, 'mobile.native-build.record', 'mobile-app', appRow.id, reason, { environmentId, runtimeVersion, nativeFingerprint, appVersion, versionCode, buildNumber, sourceSha256: sourceSha || null });
3291
- res.json({ runtimeVersion: row.runtime_version, nativeFingerprint: row.native_fingerprint, nativeBuildVersion: row.native_build_version, nativeBuildVersionCode: row.native_build_version_code === null ? null : Number(row.native_build_version_code), nativeBuildNumber: row.native_build_number, nativeBuildUrl: row.native_build_url, nativeBuildSourceSha256: row.native_build_source_sha256, nativeBuiltAt: row.native_built_at });
3476
+ res.json({ nativeBuildId: savedBuild.id, runtimeVersion: row.runtime_version, nativeFingerprint: row.native_fingerprint, nativeBuildVersion: row.native_build_version, nativeBuildVersionCode: row.native_build_version_code === null ? null : Number(row.native_build_version_code), nativeBuildNumber: row.native_build_number, nativeBuildUrl: row.native_build_url, nativeBuildSourceSha256: row.native_build_source_sha256, nativeBuiltAt: row.native_built_at });
3477
+ });
3478
+ app.get('/mobile/apps/:appId/native-builds', auth, async (req, res) => {
3479
+ const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
3480
+ if (!appRow) {
3481
+ res.status(404).json({ error: 'Mobile app not found or access denied.' });
3482
+ return;
3483
+ }
3484
+ 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,
3486
+ b.version_code,b.build_number,b.build_url,b.source_sha256,b.built_at
3487
+ FROM mobile_native_builds b JOIN mobile_environments me ON me.id=b.mobile_environment_id
3488
+ WHERE b.app_id=$1 ORDER BY b.built_at DESC LIMIT 200`, [appRow.id])).rows;
3489
+ res.json(rows);
3292
3490
  });
3293
3491
  app.get('/mobile/apps/:appId/releases', auth, async (req, res) => {
3294
3492
  const appRow = await mobileAppForUser(routeParam(req.params.appId), req.auth);
@@ -3315,23 +3513,31 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
3315
3513
  res.status(400).json({ error: 'This mobile environment is not registered for the app. Run mobile prebuild first.' });
3316
3514
  return;
3317
3515
  }
3318
- const runtimeVersion = textValue(req.body?.runtimeVersion || binding.runtime_version, 'Runtime version', 100);
3319
- if (runtimeVersion !== binding.runtime_version) {
3320
- res.status(409).json({ error: `Runtime version ${runtimeVersion} does not match the registered ${binding.runtime_version} binary for this environment. Run mobile prebuild/native build when native runtime changes.` });
3516
+ const buildId = ensureUuid(String(req.body?.nativeBuildId || ''), 'Verified native build ID');
3517
+ const baseline = (await pool.query(`SELECT * FROM mobile_native_builds
3518
+ WHERE id=$1 AND app_id=$2 AND mobile_environment_id=$3`, [buildId, appRow.id, environmentId])).rows[0];
3519
+ if (!baseline) {
3520
+ res.status(409).json({ error: 'Selected successful native build does not exist for this app/environment.' });
3321
3521
  return;
3322
3522
  }
3323
- const nativeBaseline = (await pool.query('SELECT native_fingerprint,native_built_at FROM mobile_app_environments WHERE app_id=$1 AND mobile_environment_id=$2', [appRow.id, environmentId])).rows[0];
3324
- if (!nativeBaseline?.native_fingerprint) {
3325
- res.status(409).json({ error: 'No successful native Jenkins build baseline exists for this mobile environment. Build the native app before publishing OTA updates.' });
3523
+ const runtimeVersion = textValue(req.body?.runtimeVersion || baseline.runtime_version, 'Runtime version', 100);
3524
+ if (runtimeVersion !== baseline.runtime_version) {
3525
+ res.status(409).json({ error: 'Selected build/runtime mismatch. Re-select the native build.' });
3326
3526
  return;
3327
3527
  }
3328
3528
  const requestedFingerprint = String(req.body?.nativeFingerprint || '').trim().toLowerCase();
3329
3529
  if (!/^[a-f0-9]{64}$/.test(requestedFingerprint)) {
3330
- res.status(400).json({ error: 'nativeFingerprint is required and must be a SHA-256 hex value.' });
3530
+ res.status(400).json({ error: 'nativeFingerprint must be SHA-256 hex.' });
3331
3531
  return;
3332
3532
  }
3333
- if (requestedFingerprint !== String(nativeBaseline.native_fingerprint).toLowerCase()) {
3334
- res.status(409).json({ error: 'Native project fingerprint no longer matches the last successful Jenkins binary. OTA publication is blocked until a new native build succeeds.' });
3533
+ if (requestedFingerprint !== String(baseline.native_fingerprint).toLowerCase()) {
3534
+ res.status(409).json({ error: 'Native dependency fingerprint differs from selected successful build. Build a new APK before publishing this OTA.' });
3535
+ return;
3536
+ }
3537
+ // Different native capabilities must never share a runtime (runtime is the Expo safety boundary).
3538
+ const conflicts = (await pool.query(`SELECT 1 FROM mobile_native_builds WHERE app_id=$1 AND mobile_environment_id=$2 AND runtime_version=$3 AND native_fingerprint<>$4 LIMIT 1`, [appRow.id, environmentId, runtimeVersion, requestedFingerprint])).rowCount;
3539
+ if (conflicts) {
3540
+ res.status(409).json({ error: 'Different native fingerprints share this runtime. Publishing is blocked; create a distinct runtime.' });
3335
3541
  return;
3336
3542
  }
3337
3543
  const message = textValue(req.body?.message, 'Update message', 500);
@@ -3340,6 +3546,21 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
3340
3546
  res.status(400).json({ error: 'audienceType must be test, all, or percentage.' });
3341
3547
  return;
3342
3548
  }
3549
+ if (audienceType === 'test') {
3550
+ const groupIds = Array.isArray(req.body?.audience?.groupIds) ? req.body.audience.groupIds : [];
3551
+ if (groupIds.length > 40) {
3552
+ res.status(400).json({ error: 'Maximum 40 tester groups per release.' });
3553
+ return;
3554
+ }
3555
+ for (const raw of groupIds) {
3556
+ const groupId = ensureUuid(String(raw), 'OTA tester group ID');
3557
+ const found = await pool.query('SELECT 1 FROM ota_tester_groups WHERE id=$1 AND app_id=$2', [groupId, appRow.id]);
3558
+ if (!found.rowCount) {
3559
+ res.status(400).json({ error: 'Target tester group does not belong to this mobile app.' });
3560
+ return;
3561
+ }
3562
+ }
3563
+ }
3343
3564
  const platformValues = Array.isArray(req.body?.platforms) ? [...new Set(req.body.platforms.map((v) => String(v).toLowerCase()))] : [];
3344
3565
  if (!platformValues.length || platformValues.some((v) => !['android', 'ios'].includes(v))) {
3345
3566
  res.status(400).json({ error: 'platforms must contain android and/or ios.' });
@@ -3355,13 +3576,25 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
3355
3576
  }
3356
3577
  rollout = candidate;
3357
3578
  }
3579
+ const clientRequestId = ensureUuid(String(req.body?.clientRequestId || ''), 'OTA publish request ID');
3580
+ const existingRelease = (await pool.query(`SELECT r.*,json_agg(json_build_object('id',u.id,'platform',u.platform)) updates
3581
+ FROM ota_releases r LEFT JOIN ota_updates u ON u.release_id=r.id
3582
+ WHERE r.app_id=$1 AND r.client_request_id=$2 GROUP BY r.id`, [appRow.id, clientRequestId])).rows[0];
3583
+ if (existingRelease) {
3584
+ if (existingRelease.runtime_version !== runtimeVersion || existingRelease.message !== message) {
3585
+ res.status(409).json({ error: 'OTA request ID was previously used for a different update.' });
3586
+ return;
3587
+ }
3588
+ res.json({ release: existingRelease, updates: existingRelease.updates, environment: binding, reused: true });
3589
+ return;
3590
+ }
3358
3591
  // Keep partially uploaded releases invisible to clients until finalize succeeds.
3359
3592
  const status = 'draft';
3360
3593
  const client = await pool.connect();
3361
3594
  try {
3362
3595
  await client.query('BEGIN');
3363
- 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)
3364
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING *`, [appRow.id, environmentId, runtimeVersion, message, status, audienceType, req.body?.audience || {}, rollout, null, req.auth.id])).rows[0];
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];
3365
3598
  const updates = [];
3366
3599
  for (const platform of platforms) {
3367
3600
  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]);
@@ -3573,7 +3806,7 @@ app.get('/ota/v1/manifest/:updatePath', async (req, res) => {
3573
3806
  res.status(204).end();
3574
3807
  return;
3575
3808
  }
3576
- const binding = (await pool.query('SELECT 1 FROM mobile_app_environments WHERE app_id=$1 AND mobile_environment_id=$2 AND runtime_version=$3 AND enabled=true', [appRow.id, env.id, runtimeVersion])).rowCount;
3809
+ const binding = (await pool.query(`SELECT 1 FROM mobile_native_builds b JOIN mobile_app_environments mae ON mae.app_id=b.app_id AND mae.mobile_environment_id=b.mobile_environment_id AND mae.enabled=true WHERE b.app_id=$1 AND b.mobile_environment_id=$2 AND b.runtime_version=$3 LIMIT 1`, [appRow.id, env.id, runtimeVersion])).rowCount;
3577
3810
  if (!binding) {
3578
3811
  res.status(204).end();
3579
3812
  return;
@@ -3582,12 +3815,27 @@ app.get('/ota/v1/manifest/:updatePath', async (req, res) => {
3582
3815
  if (identity.installationId) {
3583
3816
  await pool.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,user_id,username,email,phone,last_seen_at)
3584
3817
  VALUES($1,$2,$3,$4,$5,$6,$7,$8,now()) ON CONFLICT(app_id,installation_id) DO UPDATE SET platform=excluded.platform,runtime_version=excluded.runtime_version,
3585
- user_id=COALESCE(NULLIF(excluded.user_id,''),ota_installations.user_id),username=COALESCE(NULLIF(excluded.username,''),ota_installations.username),email=COALESCE(NULLIF(excluded.email,''),ota_installations.email),phone=COALESCE(NULLIF(excluded.phone,''),ota_installations.phone),last_seen_at=now()`, [appRow.id, identity.installationId, platform, runtimeVersion, identity.userId, identity.username, identity.email, identity.phone]);
3818
+ user_id=excluded.user_id,username=excluded.username,email=excluded.email,phone=excluded.phone,last_seen_at=now()`, [appRow.id, identity.installationId, platform, runtimeVersion, identity.userId, identity.username, identity.email, identity.phone]);
3586
3819
  }
3587
3820
  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
3588
3821
  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
3589
3822
  ORDER BY r.created_at DESC LIMIT 50`, [appRow.id, env.id, runtimeVersion, platform])).rows;
3590
- const selected = candidates.find((row) => audienceMatches(row, identity));
3823
+ // Group membership is evaluated at request time: adding/revoking an enrolled
3824
+ // tester takes effect without rebuilding or editing an existing release.
3825
+ const currentGroups = new Set();
3826
+ let activeTester = false;
3827
+ if (identity.installationId) {
3828
+ const enrollment = await pool.query(`SELECT 1 FROM ota_tester_installations
3829
+ WHERE app_id=$1 AND installation_id=$2 AND revoked_at IS NULL`, [appRow.id, identity.installationId]);
3830
+ activeTester = !!enrollment.rowCount;
3831
+ if (activeTester) {
3832
+ const rows = (await pool.query(`SELECT group_id FROM ota_tester_group_members
3833
+ WHERE app_id=$1 AND installation_id=$2`, [appRow.id, identity.installationId])).rows;
3834
+ for (const row of rows)
3835
+ currentGroups.add(String(row.group_id));
3836
+ }
3837
+ }
3838
+ const selected = candidates.find((row) => audienceMatches(row, identity, currentGroups, activeTester));
3591
3839
  if (!selected) {
3592
3840
  res.status(204).end();
3593
3841
  return;
@@ -3658,7 +3906,7 @@ app.post('/ota/v1/events/:updatePath', async (req, res) => {
3658
3906
  const runtimeVersion = String(req.body?.runtimeVersion || '').trim();
3659
3907
  await pool.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,user_id,username,email,phone,current_update_id,app_version,metadata,last_seen_at)
3660
3908
  VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,now()) ON CONFLICT(app_id,installation_id) DO UPDATE SET platform=excluded.platform,runtime_version=excluded.runtime_version,
3661
- user_id=COALESCE(NULLIF(excluded.user_id,''),ota_installations.user_id),username=COALESCE(NULLIF(excluded.username,''),ota_installations.username),email=COALESCE(NULLIF(excluded.email,''),ota_installations.email),phone=COALESCE(NULLIF(excluded.phone,''),ota_installations.phone),current_update_id=COALESCE(excluded.current_update_id,ota_installations.current_update_id),app_version=COALESCE(NULLIF(excluded.app_version,''),ota_installations.app_version),metadata=ota_installations.metadata||excluded.metadata,last_seen_at=now()`, [appRow.id, installationId, ['android', 'ios'].includes(platform) ? platform : null, runtimeVersion || null, String(req.body?.userId || ''), String(req.body?.username || ''), String(req.body?.email || '').toLowerCase(), String(req.body?.phone || ''), currentUpdateId, String(req.body?.appVersion || ''), req.body?.metadata || {}]);
3909
+ user_id=excluded.user_id,username=excluded.username,email=excluded.email,phone=excluded.phone,current_update_id=COALESCE(excluded.current_update_id,ota_installations.current_update_id),app_version=COALESCE(NULLIF(excluded.app_version,''),ota_installations.app_version),metadata=ota_installations.metadata||excluded.metadata,last_seen_at=now()`, [appRow.id, installationId, ['android', 'ios'].includes(platform) ? platform : null, runtimeVersion || null, String(req.body?.userId || ''), String(req.body?.username || ''), String(req.body?.email || '').toLowerCase(), String(req.body?.phone || ''), currentUpdateId, String(req.body?.appVersion || ''), req.body?.metadata || {}]);
3662
3910
  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, releaseId, eventUpdateId, installationId, eventType, platform || null, runtimeVersion || null, req.body?.metadata || {}]);
3663
3911
  res.status(202).json({ ok: true });
3664
3912
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@indraq/cloud-api",
3
3
  "private": true,
4
- "version": "1.3.1",
4
+ "version": "1.3.7",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "tsx watch src/index.ts",
@@ -0,0 +1,55 @@
1
+ -- IndraQ OTA: privacy-preserving, installation-based tester enrollment.
2
+ -- Tokens are stored only as SHA-256 digests; QR invitations are single-use and expire.
3
+ CREATE TABLE IF NOT EXISTS ota_tester_groups (
4
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
5
+ app_id uuid NOT NULL REFERENCES mobile_apps(id) ON DELETE CASCADE,
6
+ name text NOT NULL,
7
+ created_by uuid NOT NULL REFERENCES users(id),
8
+ created_at timestamptz NOT NULL DEFAULT now(),
9
+ UNIQUE (app_id, name),
10
+ UNIQUE (app_id, id)
11
+ );
12
+
13
+ CREATE TABLE IF NOT EXISTS ota_tester_installations (
14
+ app_id uuid NOT NULL REFERENCES mobile_apps(id) ON DELETE CASCADE,
15
+ installation_id text NOT NULL,
16
+ label text NOT NULL,
17
+ enrolled_by uuid NOT NULL REFERENCES users(id),
18
+ enrolled_at timestamptz NOT NULL DEFAULT now(),
19
+ revoked_at timestamptz,
20
+ PRIMARY KEY (app_id, installation_id),
21
+ FOREIGN KEY (app_id, installation_id) REFERENCES ota_installations(app_id, installation_id) ON DELETE CASCADE
22
+ );
23
+
24
+ CREATE TABLE IF NOT EXISTS ota_tester_group_members (
25
+ app_id uuid NOT NULL,
26
+ group_id uuid NOT NULL,
27
+ installation_id text NOT NULL,
28
+ added_by uuid NOT NULL REFERENCES users(id),
29
+ created_at timestamptz NOT NULL DEFAULT now(),
30
+ PRIMARY KEY (group_id, installation_id),
31
+ FOREIGN KEY (app_id, group_id) REFERENCES ota_tester_groups(app_id, id) ON DELETE CASCADE,
32
+ FOREIGN KEY (app_id, installation_id) REFERENCES ota_tester_installations(app_id, installation_id) ON DELETE CASCADE
33
+ );
34
+ CREATE INDEX IF NOT EXISTS ota_tester_group_installation_idx ON ota_tester_group_members(app_id, installation_id);
35
+
36
+ CREATE TABLE IF NOT EXISTS ota_enrollment_invitations (
37
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
38
+ app_id uuid NOT NULL REFERENCES mobile_apps(id) ON DELETE CASCADE,
39
+ token_hash char(64) NOT NULL UNIQUE,
40
+ label text NOT NULL,
41
+ group_id uuid,
42
+ app_scheme text NOT NULL,
43
+ created_by uuid NOT NULL REFERENCES users(id),
44
+ created_at timestamptz NOT NULL DEFAULT now(),
45
+ expires_at timestamptz NOT NULL,
46
+ redeemed_at timestamptz,
47
+ redeemed_installation_id text,
48
+ revoked_at timestamptz,
49
+ FOREIGN KEY (app_id, group_id) REFERENCES ota_tester_groups(app_id, id) ON DELETE RESTRICT
50
+ );
51
+ CREATE INDEX IF NOT EXISTS ota_enrollment_invites_app_idx ON ota_enrollment_invitations(app_id, created_at DESC);
52
+
53
+ -- The first project owner prebuild registers the app's immutable native link scheme.
54
+ -- Readers can create QR invitations from any directory without checking out source.
55
+ ALTER TABLE mobile_apps ADD COLUMN IF NOT EXISTS enrollment_scheme text;