indraq_cli 2.7.3 → 2.7.9

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 (56) hide show
  1. package/README.md +1526 -0
  2. package/cloud-api/README.md +6 -0
  3. package/cloud-api/dist/index.js +246 -53
  4. package/cloud-api/package.json +1 -1
  5. package/cloud-api/sql/013_ota_tester_enrollment.sql +55 -0
  6. package/cloud-api/src/index.ts +187 -44
  7. package/dist/cli/help-content.d.ts.map +1 -1
  8. package/dist/cli/help-content.js +13 -3
  9. package/dist/cli/help-content.js.map +1 -1
  10. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts +6 -1
  11. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts.map +1 -1
  12. package/dist/modules/cloud/services/cloud-jenkins.service.js +62 -5
  13. package/dist/modules/cloud/services/cloud-jenkins.service.js.map +1 -1
  14. package/dist/modules/mobile/commands/build-mobile.command.js +3 -3
  15. package/dist/modules/mobile/commands/build-mobile.command.js.map +1 -1
  16. package/dist/modules/mobile/commands/configure-mobile.command.js +1 -1
  17. package/dist/modules/mobile/commands/configure-mobile.command.js.map +1 -1
  18. package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts.map +1 -1
  19. package/dist/modules/mobile/commands/mobile-prebuild.command.js +20 -14
  20. package/dist/modules/mobile/commands/mobile-prebuild.command.js.map +1 -1
  21. package/dist/modules/mobile/commands/ota.command.d.ts.map +1 -1
  22. package/dist/modules/mobile/commands/ota.command.js +33 -15
  23. package/dist/modules/mobile/commands/ota.command.js.map +1 -1
  24. package/dist/modules/mobile/commands/testers.command.d.ts +6 -0
  25. package/dist/modules/mobile/commands/testers.command.d.ts.map +1 -0
  26. package/dist/modules/mobile/commands/testers.command.js +143 -0
  27. package/dist/modules/mobile/commands/testers.command.js.map +1 -0
  28. package/dist/modules/mobile/index.d.ts.map +1 -1
  29. package/dist/modules/mobile/index.js +23 -1
  30. package/dist/modules/mobile/index.js.map +1 -1
  31. package/dist/modules/mobile/services/mobile-cloud.service.d.ts +61 -0
  32. package/dist/modules/mobile/services/mobile-cloud.service.d.ts.map +1 -1
  33. package/dist/modules/mobile/services/mobile-cloud.service.js +15 -1
  34. package/dist/modules/mobile/services/mobile-cloud.service.js.map +1 -1
  35. package/dist/modules/mobile/services/ota-identity.service.d.ts +20 -0
  36. package/dist/modules/mobile/services/ota-identity.service.d.ts.map +1 -0
  37. package/dist/modules/mobile/services/ota-identity.service.js +169 -0
  38. package/dist/modules/mobile/services/ota-identity.service.js.map +1 -0
  39. package/dist/modules/mobile/services/ota-setup.service.d.ts +1 -0
  40. package/dist/modules/mobile/services/ota-setup.service.d.ts.map +1 -1
  41. package/dist/modules/mobile/services/ota-setup.service.js +268 -24
  42. package/dist/modules/mobile/services/ota-setup.service.js.map +1 -1
  43. package/package.json +16 -4
  44. package/vendor/QR-CODE-APACHE-2.0-LICENSE.txt +222 -0
  45. package/vendor/QR-CODE-MIT-LICENSE.txt +21 -0
  46. package/vendor/QR-CODE-NOTICE.txt +6 -0
  47. package/vendor/QRCode/QR8bitByte.js +22 -0
  48. package/vendor/QRCode/QRBitBuffer.js +38 -0
  49. package/vendor/QRCode/QRErrorCorrectLevel.js +7 -0
  50. package/vendor/QRCode/QRMaskPattern.js +10 -0
  51. package/vendor/QRCode/QRMath.js +44 -0
  52. package/vendor/QRCode/QRMode.js +6 -0
  53. package/vendor/QRCode/QRPolynomial.js +66 -0
  54. package/vendor/QRCode/QRRSBlock.js +298 -0
  55. package/vendor/QRCode/QRUtil.js +272 -0
  56. 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,193 @@ 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.delete('/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 installationId = routeParam(req.params.installationId);
3178
+ 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]);
3179
+ if (!result.rowCount) {
3180
+ res.status(404).json({ error: 'Active tester installation not found.' });
3181
+ return;
3182
+ }
3183
+ await audit(req.auth.id, 'ota.testers.revoke', 'mobile-app', appRow.id, 'Revoke OTA tester enrollment', { installationId });
3184
+ res.status(204).end();
3185
+ });
3186
+ app.get('/ota/enroll/:token', async (req, res) => {
3187
+ const token = routeParam(req.params.token);
3188
+ res.setHeader('Cache-Control', 'no-store');
3189
+ res.setHeader('Referrer-Policy', 'no-referrer');
3190
+ res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'");
3191
+ if (!enrollmentTokenPattern.test(token)) {
3192
+ res.status(404).type('text/plain').send('Invalid enrollment invitation.');
3193
+ return;
3194
+ }
3195
+ const item = (await pool.query(`SELECT e.app_scheme,ma.app_name,e.label FROM ota_enrollment_invitations e
3196
+ JOIN mobile_apps ma ON ma.id=e.app_id WHERE e.token_hash=$1 AND e.expires_at>now()
3197
+ AND e.revoked_at IS NULL AND e.redeemed_at IS NULL`, [hashEnrollmentToken(token)])).rows[0];
3198
+ if (!item) {
3199
+ res.status(410).type('text/plain').send('This invitation is expired or already used. Request a fresh QR code.');
3200
+ return;
3201
+ }
3202
+ // app_scheme is strictly validated on invitation creation and cannot contain HTML.
3203
+ const deepLink = `${item.app_scheme}://indraq-enroll?token=${token}`;
3204
+ const escapeHtml = (v) => String(v).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c] || c));
3205
+ 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>`);
3206
+ });
3207
+ app.post('/ota/v1/enroll/redeem', async (req, res) => {
3208
+ const token = String(req.body?.token || '');
3209
+ const installationId = String(req.body?.installationId || '').trim();
3210
+ if (!enrollmentTokenPattern.test(token) || !/^[A-Za-z0-9_-]{12,200}$/.test(installationId)) {
3211
+ res.status(400).json({ error: 'Invalid invitation or installation ID.' });
3212
+ return;
3213
+ }
3214
+ const digest = hashEnrollmentToken(token);
3215
+ const client = await pool.connect();
3216
+ try {
3217
+ await client.query('BEGIN');
3218
+ const invite = (await client.query(`SELECT e.*,ma.app_name FROM ota_enrollment_invitations e
3219
+ 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];
3220
+ if (!invite) {
3221
+ await client.query('ROLLBACK');
3222
+ res.status(410).json({ error: 'Invitation expired or already redeemed.' });
3223
+ return;
3224
+ }
3225
+ const installed = await client.query('SELECT 1 FROM ota_installations WHERE app_id=$1 AND installation_id=$2', [invite.app_id, installationId]);
3226
+ if (!installed.rowCount) {
3227
+ await client.query('ROLLBACK');
3228
+ res.status(409).json({ error: 'This installation has not registered with the app OTA service. Open the release app online before enrolling.' });
3229
+ return;
3230
+ }
3231
+ await client.query(`INSERT INTO ota_tester_installations(app_id,installation_id,label,enrolled_by,revoked_at)
3232
+ 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]);
3233
+ if (invite.group_id) {
3234
+ await client.query(`INSERT INTO ota_tester_group_members(app_id,group_id,installation_id,added_by)
3235
+ VALUES($1,$2,$3,$4) ON CONFLICT(group_id,installation_id) DO NOTHING`, [invite.app_id, invite.group_id, installationId, invite.created_by]);
3236
+ }
3237
+ await client.query('UPDATE ota_enrollment_invitations SET redeemed_at=now(),redeemed_installation_id=$2 WHERE id=$1', [invite.id, installationId]);
3238
+ await client.query(`INSERT INTO ota_events(app_id,installation_id,event_type,metadata)
3239
+ VALUES($1,$2,'device_enrolled',$3)`, [invite.app_id, installationId, { inviteId: invite.id, groupId: invite.group_id }]);
3240
+ await client.query('COMMIT');
3241
+ res.status(200).json({ ok: true, appName: invite.app_name, label: invite.label, groupId: invite.group_id || null });
3242
+ }
3243
+ catch (error) {
3244
+ await client.query('ROLLBACK').catch(() => { });
3245
+ throw error;
3246
+ }
3247
+ finally {
3248
+ client.release();
3249
+ }
3250
+ });
3093
3251
  const signExpoManifest = (manifestString, encryptedPrivateKey) => {
3094
3252
  const signer = createSign('RSA-SHA256');
3095
3253
  signer.update(manifestString);
@@ -3172,7 +3330,7 @@ app.get('/projects/:projectId/mobile', auth, async (req, res) => {
3172
3330
  res.status(404).json({ error: 'Project not found or access denied' });
3173
3331
  return;
3174
3332
  }
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,
3333
+ 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
3334
  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
3335
  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
3178
3336
  FROM mobile_apps ma
@@ -3185,7 +3343,7 @@ app.get('/projects/:projectId/mobile', auth, async (req, res) => {
3185
3343
  }
3186
3344
  const first = appRow[0];
3187
3345
  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,
3346
+ 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
3347
  runtimePolicy: first.runtime_policy, updateUrl: `${publicApiUrl}/ota/v1/manifest/${first.update_path}`, keyId: first.signing_key_id, certificate: first.signing_certificate,
3190
3348
  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
3349
  });
@@ -3204,6 +3362,11 @@ app.post('/projects/:projectId/mobile/register', auth, async (req, res) => {
3204
3362
  res.status(400).json({ error: 'OTA registration requires a mobile or backend-mobile project.' });
3205
3363
  return;
3206
3364
  }
3365
+ const schemeInput = req.body?.enrollmentScheme === undefined || req.body?.enrollmentScheme === null ? '' : String(req.body.enrollmentScheme).trim().toLowerCase();
3366
+ if (schemeInput && !enrollmentSchemePattern.test(schemeInput)) {
3367
+ res.status(400).json({ error: 'enrollmentScheme must be a valid native application deep-link scheme.' });
3368
+ return;
3369
+ }
3207
3370
  const appName = textValue(req.body?.appName, 'App name', 100);
3208
3371
  const projectType = String(req.body?.projectType || '').trim();
3209
3372
  if (!['expo', 'react-native'].includes(projectType)) {
@@ -3224,11 +3387,11 @@ app.post('/projects/:projectId/mobile/register', auth, async (req, res) => {
3224
3387
  res.status(400).json({ error: 'First OTA registration requires signingPrivateKey and signingCertificate.' });
3225
3388
  return;
3226
3389
  }
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)
3390
+ 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)
3391
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
3229
3392
  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]);
3393
+ 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()
3394
+ 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
3395
  const appRow = appResult.rows[0];
3233
3396
  await pool.query(`INSERT INTO mobile_app_environments(app_id,mobile_environment_id,runtime_version) VALUES($1,$2,$3)
3234
3397
  ON CONFLICT(app_id,mobile_environment_id) DO UPDATE SET
@@ -3340,6 +3503,21 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
3340
3503
  res.status(400).json({ error: 'audienceType must be test, all, or percentage.' });
3341
3504
  return;
3342
3505
  }
3506
+ if (audienceType === 'test') {
3507
+ const groupIds = Array.isArray(req.body?.audience?.groupIds) ? req.body.audience.groupIds : [];
3508
+ if (groupIds.length > 40) {
3509
+ res.status(400).json({ error: 'Maximum 40 tester groups per release.' });
3510
+ return;
3511
+ }
3512
+ for (const raw of groupIds) {
3513
+ const groupId = ensureUuid(String(raw), 'OTA tester group ID');
3514
+ const found = await pool.query('SELECT 1 FROM ota_tester_groups WHERE id=$1 AND app_id=$2', [groupId, appRow.id]);
3515
+ if (!found.rowCount) {
3516
+ res.status(400).json({ error: 'Target tester group does not belong to this mobile app.' });
3517
+ return;
3518
+ }
3519
+ }
3520
+ }
3343
3521
  const platformValues = Array.isArray(req.body?.platforms) ? [...new Set(req.body.platforms.map((v) => String(v).toLowerCase()))] : [];
3344
3522
  if (!platformValues.length || platformValues.some((v) => !['android', 'ios'].includes(v))) {
3345
3523
  res.status(400).json({ error: 'platforms must contain android and/or ios.' });
@@ -3582,12 +3760,27 @@ app.get('/ota/v1/manifest/:updatePath', async (req, res) => {
3582
3760
  if (identity.installationId) {
3583
3761
  await pool.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,user_id,username,email,phone,last_seen_at)
3584
3762
  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]);
3763
+ 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
3764
  }
3587
3765
  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
3766
  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
3767
  ORDER BY r.created_at DESC LIMIT 50`, [appRow.id, env.id, runtimeVersion, platform])).rows;
3590
- const selected = candidates.find((row) => audienceMatches(row, identity));
3768
+ // Group membership is evaluated at request time: adding/revoking an enrolled
3769
+ // tester takes effect without rebuilding or editing an existing release.
3770
+ const currentGroups = new Set();
3771
+ let activeTester = false;
3772
+ if (identity.installationId) {
3773
+ const enrollment = await pool.query(`SELECT 1 FROM ota_tester_installations
3774
+ WHERE app_id=$1 AND installation_id=$2 AND revoked_at IS NULL`, [appRow.id, identity.installationId]);
3775
+ activeTester = !!enrollment.rowCount;
3776
+ if (activeTester) {
3777
+ const rows = (await pool.query(`SELECT group_id FROM ota_tester_group_members
3778
+ WHERE app_id=$1 AND installation_id=$2`, [appRow.id, identity.installationId])).rows;
3779
+ for (const row of rows)
3780
+ currentGroups.add(String(row.group_id));
3781
+ }
3782
+ }
3783
+ const selected = candidates.find((row) => audienceMatches(row, identity, currentGroups, activeTester));
3591
3784
  if (!selected) {
3592
3785
  res.status(204).end();
3593
3786
  return;
@@ -3658,7 +3851,7 @@ app.post('/ota/v1/events/:updatePath', async (req, res) => {
3658
3851
  const runtimeVersion = String(req.body?.runtimeVersion || '').trim();
3659
3852
  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
3853
  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 || {}]);
3854
+ 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
3855
  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
3856
  res.status(202).json({ ok: true });
3664
3857
  });
@@ -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.6",
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;