indraq_cli 2.7.1 → 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 (100) hide show
  1. package/README.md +1167 -419
  2. package/cloud-api/README.md +6 -0
  3. package/cloud-api/dist/index.js +315 -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 +229 -44
  7. package/dist/cli/help-content.d.ts.map +1 -1
  8. package/dist/cli/help-content.js +20 -7
  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.d.ts +1 -0
  15. package/dist/modules/mobile/commands/build-mobile.command.d.ts.map +1 -1
  16. package/dist/modules/mobile/commands/build-mobile.command.js +41 -23
  17. package/dist/modules/mobile/commands/build-mobile.command.js.map +1 -1
  18. package/dist/modules/mobile/commands/configure-mobile.command.js +1 -1
  19. package/dist/modules/mobile/commands/configure-mobile.command.js.map +1 -1
  20. package/dist/modules/mobile/commands/mobile-build-wizard.command.d.ts +15 -0
  21. package/dist/modules/mobile/commands/mobile-build-wizard.command.d.ts.map +1 -0
  22. package/dist/modules/mobile/commands/mobile-build-wizard.command.js +134 -0
  23. package/dist/modules/mobile/commands/mobile-build-wizard.command.js.map +1 -0
  24. package/dist/modules/mobile/commands/mobile-environment.command.d.ts.map +1 -1
  25. package/dist/modules/mobile/commands/mobile-environment.command.js +4 -6
  26. package/dist/modules/mobile/commands/mobile-environment.command.js.map +1 -1
  27. package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts +2 -0
  28. package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts.map +1 -1
  29. package/dist/modules/mobile/commands/mobile-prebuild.command.js +24 -18
  30. package/dist/modules/mobile/commands/mobile-prebuild.command.js.map +1 -1
  31. package/dist/modules/mobile/commands/ota.command.d.ts +1 -0
  32. package/dist/modules/mobile/commands/ota.command.d.ts.map +1 -1
  33. package/dist/modules/mobile/commands/ota.command.js +67 -13
  34. package/dist/modules/mobile/commands/ota.command.js.map +1 -1
  35. package/dist/modules/mobile/commands/testers.command.d.ts +6 -0
  36. package/dist/modules/mobile/commands/testers.command.d.ts.map +1 -0
  37. package/dist/modules/mobile/commands/testers.command.js +143 -0
  38. package/dist/modules/mobile/commands/testers.command.js.map +1 -0
  39. package/dist/modules/mobile/config/mobile-config.d.ts +1 -0
  40. package/dist/modules/mobile/config/mobile-config.d.ts.map +1 -1
  41. package/dist/modules/mobile/config/mobile-config.js +6 -1
  42. package/dist/modules/mobile/config/mobile-config.js.map +1 -1
  43. package/dist/modules/mobile/index.d.ts.map +1 -1
  44. package/dist/modules/mobile/index.js +40 -1
  45. package/dist/modules/mobile/index.js.map +1 -1
  46. package/dist/modules/mobile/services/mobile-cloud.service.d.ts +61 -0
  47. package/dist/modules/mobile/services/mobile-cloud.service.d.ts.map +1 -1
  48. package/dist/modules/mobile/services/mobile-cloud.service.js +15 -1
  49. package/dist/modules/mobile/services/mobile-cloud.service.js.map +1 -1
  50. package/dist/modules/mobile/services/ota-identity.service.d.ts +20 -0
  51. package/dist/modules/mobile/services/ota-identity.service.d.ts.map +1 -0
  52. package/dist/modules/mobile/services/ota-identity.service.js +169 -0
  53. package/dist/modules/mobile/services/ota-identity.service.js.map +1 -0
  54. package/dist/modules/mobile/services/ota-setup.service.d.ts +1 -0
  55. package/dist/modules/mobile/services/ota-setup.service.d.ts.map +1 -1
  56. package/dist/modules/mobile/services/ota-setup.service.js +268 -24
  57. package/dist/modules/mobile/services/ota-setup.service.js.map +1 -1
  58. package/dist/modules/scopes/commands/scope.command.d.ts +2 -0
  59. package/dist/modules/scopes/commands/scope.command.d.ts.map +1 -1
  60. package/dist/modules/scopes/commands/scope.command.js +125 -3
  61. package/dist/modules/scopes/commands/scope.command.js.map +1 -1
  62. package/dist/modules/scopes/index.d.ts.map +1 -1
  63. package/dist/modules/scopes/index.js +1 -0
  64. package/dist/modules/scopes/index.js.map +1 -1
  65. package/dist/modules/scopes/services/native-scope-inspection.service.d.ts +10 -0
  66. package/dist/modules/scopes/services/native-scope-inspection.service.d.ts.map +1 -0
  67. package/dist/modules/scopes/services/native-scope-inspection.service.js +75 -0
  68. package/dist/modules/scopes/services/native-scope-inspection.service.js.map +1 -0
  69. package/dist/modules/scopes/services/scope-native.service.d.ts +2 -0
  70. package/dist/modules/scopes/services/scope-native.service.d.ts.map +1 -1
  71. package/dist/modules/scopes/services/scope-native.service.js +43 -5
  72. package/dist/modules/scopes/services/scope-native.service.js.map +1 -1
  73. package/dist/modules/users/providers/npm-user.provider.d.ts +11 -0
  74. package/dist/modules/users/providers/npm-user.provider.d.ts.map +1 -1
  75. package/dist/modules/users/providers/npm-user.provider.js +16 -1
  76. package/dist/modules/users/providers/npm-user.provider.js.map +1 -1
  77. package/docs/assets/architecture.png +0 -0
  78. package/docs/assets/architecture.svg +123 -0
  79. package/docs/assets/backend-mobile.png +0 -0
  80. package/docs/assets/backend-mobile.svg +97 -0
  81. package/docs/assets/cleanup.png +0 -0
  82. package/docs/assets/cleanup.svg +104 -0
  83. package/docs/assets/setup-flow.png +0 -0
  84. package/docs/assets/setup-flow.svg +95 -0
  85. package/docs/assets/web-deployment.png +0 -0
  86. package/docs/assets/web-deployment.svg +72 -0
  87. package/package.json +21 -4
  88. package/vendor/QR-CODE-APACHE-2.0-LICENSE.txt +222 -0
  89. package/vendor/QR-CODE-MIT-LICENSE.txt +21 -0
  90. package/vendor/QR-CODE-NOTICE.txt +6 -0
  91. package/vendor/QRCode/QR8bitByte.js +22 -0
  92. package/vendor/QRCode/QRBitBuffer.js +38 -0
  93. package/vendor/QRCode/QRErrorCorrectLevel.js +7 -0
  94. package/vendor/QRCode/QRMaskPattern.js +10 -0
  95. package/vendor/QRCode/QRMath.js +44 -0
  96. package/vendor/QRCode/QRMode.js +6 -0
  97. package/vendor/QRCode/QRPolynomial.js +66 -0
  98. package/vendor/QRCode/QRRSBlock.js +298 -0
  99. package/vendor/QRCode/QRUtil.js +272 -0
  100. 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) } });
@@ -1724,6 +1727,75 @@ app.delete('/scopes/:id/members/:userId', ...allow('manager', 'admin'), async (r
1724
1727
  await audit(req.auth.id, 'scope.member.remove', 'provider-scope', id, reason, { userId, email: target.rows[0].email });
1725
1728
  res.status(204).end();
1726
1729
  });
1730
+ // Verify stored native logins on the exact provider scope; passwords never leave the Cloud API.
1731
+ // This is intentionally read-only. External account deletion/permission drift is
1732
+ // handled by explicit CLI repair, never by silently deleting Cloud membership.
1733
+ app.post('/scopes/:id/native-logins/verify', ...allow('manager', 'admin'), async (req, res) => {
1734
+ const id = ensureUuid(routeParam(req.params.id), 'Scope ID');
1735
+ if (!(await canManageScope(id, req.auth))) {
1736
+ res.status(403).json({ error: 'MANAGE access to this scope is required.' });
1737
+ return;
1738
+ }
1739
+ const scope = (await pool.query('SELECT provider,config FROM provider_scopes WHERE id=$1 AND is_active=true', [id])).rows[0];
1740
+ if (!scope) {
1741
+ res.status(404).json({ error: 'Scope not found.' });
1742
+ return;
1743
+ }
1744
+ if (!['jenkins-dev', 'jenkins-prod', 'npm'].includes(scope.provider)) {
1745
+ res.json([]);
1746
+ return;
1747
+ }
1748
+ const rows = (await pool.query(`SELECT psm.user_id AS cloud_user_id,COALESCE(sea.external_username,u.name) AS external_username,
1749
+ COALESCE(sea.external_email,u.email) AS external_email,sea.encrypted_secret,u.role
1750
+ FROM provider_scope_members psm JOIN users u ON u.id=psm.user_id
1751
+ LEFT JOIN scope_external_accounts sea ON sea.scope_id=psm.scope_id AND sea.cloud_user_id=u.id
1752
+ WHERE psm.scope_id=$1 AND u.is_active=true ORDER BY u.email LIMIT 200`, [id])).rows;
1753
+ const url = String(scope.config?.url || '').replace(/\/+$/, '');
1754
+ const entries = [];
1755
+ // Bounded sequential network calls avoid overloading Jenkins/NPM while auditing.
1756
+ for (const row of rows) {
1757
+ if (req.auth.role === 'manager' && row.role !== 'user')
1758
+ continue;
1759
+ if (!row.encrypted_secret || !url) {
1760
+ entries.push({ userId: row.cloud_user_id, status: 'unconfigured' });
1761
+ continue;
1762
+ }
1763
+ try {
1764
+ const secret = decrypt(row.encrypted_secret);
1765
+ const ctrl = new AbortController();
1766
+ const timeout = setTimeout(() => ctrl.abort(), 8000);
1767
+ try {
1768
+ const response = scope.provider === 'npm'
1769
+ ? await fetch(`${url}/api/tokens`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ identity: row.external_email || row.external_username, secret }), redirect: 'manual', signal: ctrl.signal })
1770
+ : await fetch(`${url}/whoAmI/api/json`, { headers: { authorization: `Basic ${Buffer.from(`${row.external_username}:${secret}`).toString('base64')}` }, redirect: 'manual', signal: ctrl.signal });
1771
+ if (response.status === 401 || response.status === 302 || response.status === 303) {
1772
+ entries.push({ userId: row.cloud_user_id, status: 'invalid' });
1773
+ continue;
1774
+ }
1775
+ if (response.status === 403) {
1776
+ entries.push({ userId: row.cloud_user_id, status: 'permissions' });
1777
+ continue;
1778
+ }
1779
+ if (!response.ok) {
1780
+ entries.push({ userId: row.cloud_user_id, status: 'provider-error' });
1781
+ continue;
1782
+ }
1783
+ const body = await response.json();
1784
+ const authenticated = scope.provider === 'npm' ? Boolean(body.token) : body.authenticated === true;
1785
+ entries.push({ userId: row.cloud_user_id, status: authenticated ? 'valid' : 'invalid' });
1786
+ }
1787
+ finally {
1788
+ clearTimeout(timeout);
1789
+ }
1790
+ }
1791
+ catch {
1792
+ entries.push({ userId: row.cloud_user_id, status: 'unreachable' });
1793
+ }
1794
+ }
1795
+ await audit(req.auth.id, 'scope.native-logins.verify', 'provider-scope', id, 'Check stored native logins without exposing passwords', { checked: entries.length, provider: scope.provider });
1796
+ res.setHeader('Cache-Control', 'no-store');
1797
+ res.json(entries);
1798
+ });
1727
1799
  app.get('/scopes/:id/audit', auth, async (req, res) => {
1728
1800
  const id = ensureUuid(routeParam(req.params.id), 'Scope ID');
1729
1801
  if (!(await canManageScope(id, req.auth))) {
@@ -2508,49 +2580,12 @@ app.post('/projects/:projectId/jenkins-control', auth, async (req, res) => {
2508
2580
  res.json({ exists: true });
2509
2581
  return;
2510
2582
  }
2511
- if (operation === 'ensure-mobile-job') {
2512
- const jobName = String(req.body?.jobName || '').trim();
2513
- const pipelineScript = String(req.body?.pipelineScript || '');
2514
- if (jobName !== 'Mobile app Cli build') {
2515
- res.status(400).json({ error: 'Only the managed IndraQ mobile build job may be reconciled through this operation.' });
2516
- return;
2517
- }
2518
- if (!pipelineScript || pipelineScript.length > 250_000) {
2519
- res.status(400).json({ error: 'pipelineScript is required and must be 250 KB or smaller.' });
2520
- return;
2521
- }
2522
- const xmlEscape = (value) => value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
2523
- const configXml = `<?xml version="1.1" encoding="UTF-8"?>
2524
- <flow-definition plugin="workflow-job">
2525
- <actions/>
2526
- <description>Managed by IndraQ CLI for mobile builds.</description>
2527
- <keepDependencies>false</keepDependencies>
2528
- <properties/>
2529
- <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps">
2530
- <script>${xmlEscape(pipelineScript)}</script>
2531
- <sandbox>true</sandbox>
2532
- </definition>
2533
- <triggers/>
2534
- <disabled>false</disabled>
2535
- </flow-definition>
2536
- `;
2537
- const headers = { ...(await jenkinsHeaders(resolved.connection)), 'content-type': 'application/xml' };
2538
- const lookup = await fetch(`${resolved.connection.url}/${jenkinsJobPath(jobName)}/api/json`, { headers: { authorization: jenkinsBasic(resolved.connection) } });
2539
- let response;
2540
- if (lookup.status === 404) {
2541
- response = await fetch(`${resolved.connection.url}/createItem?name=${encodeURIComponent(jobName)}`, { method: 'POST', headers, body: configXml });
2542
- }
2543
- else if (lookup.ok) {
2544
- response = await fetch(`${resolved.connection.url}/${jenkinsJobPath(jobName)}/config.xml`, { method: 'POST', headers, body: configXml });
2545
- }
2546
- else {
2547
- throw new Error(`Jenkins job lookup failed for ${jobName} (HTTP ${lookup.status}).`);
2548
- }
2549
- const responseBody = await response.text();
2550
- if (!response.ok)
2551
- throw new Error(`Unable to reconcile Jenkins mobile job ${jobName} (HTTP ${response.status}): ${compactJenkinsError(responseBody)}`);
2552
- await audit(req.auth.id, 'jenkins.control.mobile-job.ensure', 'project', projectId, reason, { environment, provider: resolved.provider, scopeId: resolved.scopeId, jobName });
2553
- 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
+ });
2554
2589
  return;
2555
2590
  }
2556
2591
  if (operation === 'host-port-check') {
@@ -2994,7 +3029,7 @@ const requestIdentity = (req) => {
2994
3029
  currentUpdateId: value('x-indraq-current-update-id', 'indraq-current-update-id', 200)
2995
3030
  };
2996
3031
  };
2997
- const audienceMatches = (row, identity) => {
3032
+ const audienceMatches = (row, identity, groups = new Set(), activeTester = false) => {
2998
3033
  if (row.status === 'released' && row.audience_type === 'all')
2999
3034
  return true;
3000
3035
  if (row.status === 'released' && row.audience_type === 'percentage') {
@@ -3003,6 +3038,11 @@ const audienceMatches = (row, identity) => {
3003
3038
  const bucket = Number.parseInt(createHash('sha256').update(`${identity.installationId}:${row.id}`).digest('hex').slice(0, 8), 16) % 100;
3004
3039
  return bucket < Number(row.rollout_percent);
3005
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;
3006
3046
  const identities = Array.isArray(row.audience?.identities) ? row.audience.identities : [];
3007
3047
  return identities.some((item) => {
3008
3048
  const expected = String(item.value || '').trim().toLowerCase();
@@ -3021,6 +3061,193 @@ const audienceMatches = (row, identity) => {
3021
3061
  return false;
3022
3062
  });
3023
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
+ });
3024
3251
  const signExpoManifest = (manifestString, encryptedPrivateKey) => {
3025
3252
  const signer = createSign('RSA-SHA256');
3026
3253
  signer.update(manifestString);
@@ -3103,7 +3330,7 @@ app.get('/projects/:projectId/mobile', auth, async (req, res) => {
3103
3330
  res.status(404).json({ error: 'Project not found or access denied' });
3104
3331
  return;
3105
3332
  }
3106
- 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,
3107
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,
3108
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
3109
3336
  FROM mobile_apps ma
@@ -3116,7 +3343,7 @@ app.get('/projects/:projectId/mobile', auth, async (req, res) => {
3116
3343
  }
3117
3344
  const first = appRow[0];
3118
3345
  res.json({
3119
- 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,
3120
3347
  runtimePolicy: first.runtime_policy, updateUrl: `${publicApiUrl}/ota/v1/manifest/${first.update_path}`, keyId: first.signing_key_id, certificate: first.signing_certificate,
3121
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 }))
3122
3349
  });
@@ -3135,6 +3362,11 @@ app.post('/projects/:projectId/mobile/register', auth, async (req, res) => {
3135
3362
  res.status(400).json({ error: 'OTA registration requires a mobile or backend-mobile project.' });
3136
3363
  return;
3137
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
+ }
3138
3370
  const appName = textValue(req.body?.appName, 'App name', 100);
3139
3371
  const projectType = String(req.body?.projectType || '').trim();
3140
3372
  if (!['expo', 'react-native'].includes(projectType)) {
@@ -3155,11 +3387,11 @@ app.post('/projects/:projectId/mobile/register', auth, async (req, res) => {
3155
3387
  res.status(400).json({ error: 'First OTA registration requires signingPrivateKey and signingCertificate.' });
3156
3388
  return;
3157
3389
  }
3158
- 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)
3159
- 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)
3160
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,
3161
- 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()
3162
- 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]);
3163
3395
  const appRow = appResult.rows[0];
3164
3396
  await pool.query(`INSERT INTO mobile_app_environments(app_id,mobile_environment_id,runtime_version) VALUES($1,$2,$3)
3165
3397
  ON CONFLICT(app_id,mobile_environment_id) DO UPDATE SET
@@ -3271,6 +3503,21 @@ app.post('/mobile/apps/:appId/releases', auth, async (req, res) => {
3271
3503
  res.status(400).json({ error: 'audienceType must be test, all, or percentage.' });
3272
3504
  return;
3273
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
+ }
3274
3521
  const platformValues = Array.isArray(req.body?.platforms) ? [...new Set(req.body.platforms.map((v) => String(v).toLowerCase()))] : [];
3275
3522
  if (!platformValues.length || platformValues.some((v) => !['android', 'ios'].includes(v))) {
3276
3523
  res.status(400).json({ error: 'platforms must contain android and/or ios.' });
@@ -3513,12 +3760,27 @@ app.get('/ota/v1/manifest/:updatePath', async (req, res) => {
3513
3760
  if (identity.installationId) {
3514
3761
  await pool.query(`INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,user_id,username,email,phone,last_seen_at)
3515
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,
3516
- 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]);
3517
3764
  }
3518
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
3519
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
3520
3767
  ORDER BY r.created_at DESC LIMIT 50`, [appRow.id, env.id, runtimeVersion, platform])).rows;
3521
- 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));
3522
3784
  if (!selected) {
3523
3785
  res.status(204).end();
3524
3786
  return;
@@ -3589,7 +3851,7 @@ app.post('/ota/v1/events/:updatePath', async (req, res) => {
3589
3851
  const runtimeVersion = String(req.body?.runtimeVersion || '').trim();
3590
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)
3591
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,
3592
- 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 || {}]);
3593
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 || {}]);
3594
3856
  res.status(202).json({ ok: true });
3595
3857
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@indraq/cloud-api",
3
3
  "private": true,
4
- "version": "1.3.0",
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;