indraq_cli 2.2.4 → 2.4.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 (172) hide show
  1. package/README.md +158 -21
  2. package/cloud-api/.env.example +10 -0
  3. package/cloud-api/README.md +32 -3
  4. package/cloud-api/dist/index.js +840 -13
  5. package/cloud-api/package.json +5 -3
  6. package/cloud-api/scripts/check-dev-deps.mjs +11 -0
  7. package/cloud-api/sql/011_environment_internal_ipv4.sql +14 -0
  8. package/cloud-api/sql/012_mobile_ota.sql +139 -0
  9. package/cloud-api/src/index.ts +629 -13
  10. package/dist/cli/create-program.d.ts +1 -1
  11. package/dist/cli/create-program.d.ts.map +1 -1
  12. package/dist/cli/create-program.js +126 -46
  13. package/dist/cli/create-program.js.map +1 -1
  14. package/dist/cli/help-content.d.ts +1 -1
  15. package/dist/cli/help-content.d.ts.map +1 -1
  16. package/dist/cli/help-content.js +150 -32
  17. package/dist/cli/help-content.js.map +1 -1
  18. package/dist/index.js +55 -14
  19. package/dist/index.js.map +1 -1
  20. package/dist/modules/access/index.d.ts +1 -1
  21. package/dist/modules/access/index.d.ts.map +1 -1
  22. package/dist/modules/access/index.js +2 -3
  23. package/dist/modules/access/index.js.map +1 -1
  24. package/dist/modules/aws/commands/dns.command.js +4 -4
  25. package/dist/modules/aws/commands/dns.command.js.map +1 -1
  26. package/dist/modules/aws/index.d.ts +1 -1
  27. package/dist/modules/aws/index.d.ts.map +1 -1
  28. package/dist/modules/aws/index.js +18 -42
  29. package/dist/modules/aws/index.js.map +1 -1
  30. package/dist/modules/aws/services/route53-lookup.service.d.ts.map +1 -1
  31. package/dist/modules/aws/services/route53-lookup.service.js +2 -3
  32. package/dist/modules/aws/services/route53-lookup.service.js.map +1 -1
  33. package/dist/modules/aws/services/route53-sdk.d.ts +2 -0
  34. package/dist/modules/aws/services/route53-sdk.d.ts.map +1 -0
  35. package/dist/modules/aws/services/route53-sdk.js +12 -0
  36. package/dist/modules/aws/services/route53-sdk.js.map +1 -0
  37. package/dist/modules/cloud/commands/cloud.command.d.ts +2 -0
  38. package/dist/modules/cloud/commands/cloud.command.d.ts.map +1 -1
  39. package/dist/modules/cloud/commands/cloud.command.js +165 -17
  40. package/dist/modules/cloud/commands/cloud.command.js.map +1 -1
  41. package/dist/modules/cloud/commands/environment.command.d.ts.map +1 -1
  42. package/dist/modules/cloud/commands/environment.command.js +10 -6
  43. package/dist/modules/cloud/commands/environment.command.js.map +1 -1
  44. package/dist/modules/cloud/index.d.ts +1 -1
  45. package/dist/modules/cloud/index.d.ts.map +1 -1
  46. package/dist/modules/cloud/index.js +48 -52
  47. package/dist/modules/cloud/index.js.map +1 -1
  48. package/dist/modules/cloud/services/cloud-api.service.d.ts +1 -0
  49. package/dist/modules/cloud/services/cloud-api.service.d.ts.map +1 -1
  50. package/dist/modules/cloud/services/cloud-api.service.js +41 -1
  51. package/dist/modules/cloud/services/cloud-api.service.js.map +1 -1
  52. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts +1 -0
  53. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts.map +1 -1
  54. package/dist/modules/cloud/services/cloud-jenkins.service.js +5 -1
  55. package/dist/modules/cloud/services/cloud-jenkins.service.js.map +1 -1
  56. package/dist/modules/cloud/services/environment.service.d.ts +7 -1
  57. package/dist/modules/cloud/services/environment.service.d.ts.map +1 -1
  58. package/dist/modules/cloud/services/environment.service.js +5 -1
  59. package/dist/modules/cloud/services/environment.service.js.map +1 -1
  60. package/dist/modules/cloud/services/project-cloud.service.d.ts +2 -1
  61. package/dist/modules/cloud/services/project-cloud.service.d.ts.map +1 -1
  62. package/dist/modules/cloud/services/project-cloud.service.js +9 -1
  63. package/dist/modules/cloud/services/project-cloud.service.js.map +1 -1
  64. package/dist/modules/deploy/commands/build.command.d.ts +2 -1
  65. package/dist/modules/deploy/commands/build.command.d.ts.map +1 -1
  66. package/dist/modules/deploy/commands/build.command.js +120 -75
  67. package/dist/modules/deploy/commands/build.command.js.map +1 -1
  68. package/dist/modules/deploy/index.d.ts +1 -1
  69. package/dist/modules/deploy/index.d.ts.map +1 -1
  70. package/dist/modules/deploy/index.js +67 -36
  71. package/dist/modules/deploy/index.js.map +1 -1
  72. package/dist/modules/dockerfile/index.d.ts +1 -1
  73. package/dist/modules/dockerfile/index.d.ts.map +1 -1
  74. package/dist/modules/dockerfile/index.js +3 -2
  75. package/dist/modules/dockerfile/index.js.map +1 -1
  76. package/dist/modules/jenkins/commands/create-deployment.command.d.ts.map +1 -1
  77. package/dist/modules/jenkins/commands/create-deployment.command.js +7 -11
  78. package/dist/modules/jenkins/commands/create-deployment.command.js.map +1 -1
  79. package/dist/modules/jenkins/index.d.ts +1 -1
  80. package/dist/modules/jenkins/index.d.ts.map +1 -1
  81. package/dist/modules/jenkins/index.js +13 -22
  82. package/dist/modules/jenkins/index.js.map +1 -1
  83. package/dist/modules/mobile/commands/build-mobile.command.d.ts.map +1 -1
  84. package/dist/modules/mobile/commands/build-mobile.command.js +44 -5
  85. package/dist/modules/mobile/commands/build-mobile.command.js.map +1 -1
  86. package/dist/modules/mobile/commands/configure-mobile.command.d.ts.map +1 -1
  87. package/dist/modules/mobile/commands/configure-mobile.command.js +3 -12
  88. package/dist/modules/mobile/commands/configure-mobile.command.js.map +1 -1
  89. package/dist/modules/mobile/commands/mobile-environment.command.d.ts +5 -0
  90. package/dist/modules/mobile/commands/mobile-environment.command.d.ts.map +1 -0
  91. package/dist/modules/mobile/commands/mobile-environment.command.js +67 -0
  92. package/dist/modules/mobile/commands/mobile-environment.command.js.map +1 -0
  93. package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts +6 -0
  94. package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts.map +1 -0
  95. package/dist/modules/mobile/commands/mobile-prebuild.command.js +134 -0
  96. package/dist/modules/mobile/commands/mobile-prebuild.command.js.map +1 -0
  97. package/dist/modules/mobile/commands/ota.command.d.ts +8 -0
  98. package/dist/modules/mobile/commands/ota.command.d.ts.map +1 -0
  99. package/dist/modules/mobile/commands/ota.command.js +190 -0
  100. package/dist/modules/mobile/commands/ota.command.js.map +1 -0
  101. package/dist/modules/mobile/config/mobile-config.d.ts +26 -1
  102. package/dist/modules/mobile/config/mobile-config.d.ts.map +1 -1
  103. package/dist/modules/mobile/config/mobile-config.js +52 -9
  104. package/dist/modules/mobile/config/mobile-config.js.map +1 -1
  105. package/dist/modules/mobile/index.d.ts.map +1 -1
  106. package/dist/modules/mobile/index.js +27 -18
  107. package/dist/modules/mobile/index.js.map +1 -1
  108. package/dist/modules/mobile/services/jenkins-mobile.service.js +1 -1
  109. package/dist/modules/mobile/services/jenkins-mobile.service.js.map +1 -1
  110. package/dist/modules/mobile/services/mobile-cloud.service.d.ts +120 -0
  111. package/dist/modules/mobile/services/mobile-cloud.service.d.ts.map +1 -0
  112. package/dist/modules/mobile/services/mobile-cloud.service.js +53 -0
  113. package/dist/modules/mobile/services/mobile-cloud.service.js.map +1 -0
  114. package/dist/modules/mobile/services/ota-export.service.d.ts +14 -0
  115. package/dist/modules/mobile/services/ota-export.service.d.ts.map +1 -0
  116. package/dist/modules/mobile/services/ota-export.service.js +68 -0
  117. package/dist/modules/mobile/services/ota-export.service.js.map +1 -0
  118. package/dist/modules/mobile/services/ota-setup.service.d.ts +18 -0
  119. package/dist/modules/mobile/services/ota-setup.service.d.ts.map +1 -0
  120. package/dist/modules/mobile/services/ota-setup.service.js +374 -0
  121. package/dist/modules/mobile/services/ota-setup.service.js.map +1 -0
  122. package/dist/modules/prebuild/commands/prebuild.command.d.ts +3 -2
  123. package/dist/modules/prebuild/commands/prebuild.command.d.ts.map +1 -1
  124. package/dist/modules/prebuild/commands/prebuild.command.js +79 -56
  125. package/dist/modules/prebuild/commands/prebuild.command.js.map +1 -1
  126. package/dist/modules/prebuild/index.d.ts +1 -1
  127. package/dist/modules/prebuild/index.d.ts.map +1 -1
  128. package/dist/modules/prebuild/index.js +3 -2
  129. package/dist/modules/prebuild/index.js.map +1 -1
  130. package/dist/modules/proxy/commands/proxy.command.js +3 -3
  131. package/dist/modules/proxy/commands/proxy.command.js.map +1 -1
  132. package/dist/modules/proxy/index.d.ts +1 -1
  133. package/dist/modules/proxy/index.d.ts.map +1 -1
  134. package/dist/modules/proxy/index.js +8 -10
  135. package/dist/modules/proxy/index.js.map +1 -1
  136. package/dist/modules/scaffold/commands/init.command.d.ts.map +1 -1
  137. package/dist/modules/scaffold/commands/init.command.js +52 -18
  138. package/dist/modules/scaffold/commands/init.command.js.map +1 -1
  139. package/dist/modules/scaffold/index.d.ts +1 -1
  140. package/dist/modules/scaffold/index.d.ts.map +1 -1
  141. package/dist/modules/scaffold/index.js +4 -2
  142. package/dist/modules/scaffold/index.js.map +1 -1
  143. package/dist/modules/scaffold/project-topology.d.ts +14 -0
  144. package/dist/modules/scaffold/project-topology.d.ts.map +1 -0
  145. package/dist/modules/scaffold/project-topology.js +59 -0
  146. package/dist/modules/scaffold/project-topology.js.map +1 -0
  147. package/dist/modules/scaffold/types.d.ts +14 -1
  148. package/dist/modules/scaffold/types.d.ts.map +1 -1
  149. package/dist/modules/scopes/commands/scope.command.d.ts.map +1 -1
  150. package/dist/modules/scopes/commands/scope.command.js +18 -11
  151. package/dist/modules/scopes/commands/scope.command.js.map +1 -1
  152. package/dist/modules/scopes/index.d.ts +1 -1
  153. package/dist/modules/scopes/index.d.ts.map +1 -1
  154. package/dist/modules/scopes/index.js +15 -15
  155. package/dist/modules/scopes/index.js.map +1 -1
  156. package/dist/modules/setup/commands/setup.command.d.ts +2 -0
  157. package/dist/modules/setup/commands/setup.command.d.ts.map +1 -0
  158. package/dist/modules/setup/commands/setup.command.js +107 -0
  159. package/dist/modules/setup/commands/setup.command.js.map +1 -0
  160. package/dist/modules/setup/index.d.ts +3 -0
  161. package/dist/modules/setup/index.d.ts.map +1 -0
  162. package/dist/modules/setup/index.js +9 -0
  163. package/dist/modules/setup/index.js.map +1 -0
  164. package/dist/modules/users/index.d.ts +1 -1
  165. package/dist/modules/users/index.d.ts.map +1 -1
  166. package/dist/modules/users/index.js +10 -25
  167. package/dist/modules/users/index.js.map +1 -1
  168. package/dist/modules/users/providers/aws-user.provider.js +1 -1
  169. package/dist/modules/users/providers/aws-user.provider.js.map +1 -1
  170. package/docs/ARCHITECTURE.md +85 -29
  171. package/package.json +21 -5
  172. package/cloud-api/package-lock.json +0 -2250
@@ -5,11 +5,12 @@ import jwt from 'jsonwebtoken';
5
5
  import pg from 'pg';
6
6
  import nodemailer from 'nodemailer';
7
7
  import { IAMClient, CreateAccessKeyCommand, DeleteAccessKeyCommand, ListAccessKeysCommand } from '@aws-sdk/client-iam';
8
- import { createCipheriv, createDecipheriv, createHash, randomBytes, randomInt } from 'node:crypto';
8
+ import { createCipheriv, createDecipheriv, createHash, createSign, randomBytes, randomInt } from 'node:crypto';
9
9
  import { isIP } from 'node:net';
10
10
  import { readdir, readFile } from 'node:fs/promises';
11
11
  import { dirname, resolve } from 'node:path';
12
12
  import { fileURLToPath } from 'node:url';
13
+ import * as Minio from 'minio';
13
14
 
14
15
  const { Pool } = pg;
15
16
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
@@ -22,6 +23,42 @@ const masterHex = process.env.MASTER_KEY || '';
22
23
  if (!/^[a-fA-F0-9]{64}$/.test(masterHex)) throw new Error('MASTER_KEY must be exactly 64 hex characters (32 bytes).');
23
24
  const masterKey = Buffer.from(masterHex, 'hex');
24
25
 
26
+
27
+ const publicApiUrl = (process.env.PUBLIC_API_URL || 'https://cli.indraq.com').replace(/\/+$/, '');
28
+ const minioBucket = process.env.MINIO_BUCKET || 'indraq-ota';
29
+ let minioClient: Minio.Client | null = null;
30
+ const getMinio = (): Minio.Client => {
31
+ if (minioClient) return minioClient;
32
+ const endPoint = process.env.MINIO_ENDPOINT;
33
+ const accessKey = process.env.MINIO_ACCESS_KEY;
34
+ const secretKey = process.env.MINIO_SECRET_KEY;
35
+ if (!endPoint || !accessKey || !secretKey) throw new Error('Mobile OTA MinIO is not configured. Set MINIO_ENDPOINT, MINIO_ACCESS_KEY and MINIO_SECRET_KEY.');
36
+ minioClient = new Minio.Client({
37
+ endPoint,
38
+ port: Number(process.env.MINIO_PORT || 9000),
39
+ useSSL: String(process.env.MINIO_USE_SSL || '').toLowerCase() === 'true',
40
+ accessKey,
41
+ secretKey
42
+ });
43
+ return minioClient;
44
+ };
45
+ const ensureOtaBucket = async (): Promise<void> => {
46
+ const client = getMinio();
47
+ if (!(await client.bucketExists(minioBucket))) await client.makeBucket(minioBucket);
48
+ };
49
+ const base64UrlSha256 = (buffer: Buffer): string => createHash('sha256').update(buffer).digest('base64url');
50
+ const hexSha256 = (buffer: Buffer): string => createHash('sha256').update(buffer).digest('hex');
51
+ const slugValue = (value: unknown, label: string): string => {
52
+ const slug = String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
53
+ if (!slug || slug.length > 80) throw Object.assign(new Error(`${label} must contain letters/numbers and be 1-80 characters.`), { statusCode: 400 });
54
+ return slug;
55
+ };
56
+ const textValue = (value: unknown, label: string, max = 500): string => {
57
+ const text = String(value || '').trim();
58
+ if (!text || text.length > max) throw Object.assign(new Error(`${label} is required and must be ${max} characters or fewer.`), { statusCode: 400 });
59
+ return text;
60
+ };
61
+
25
62
  type Role = 'user' | 'manager' | 'admin';
26
63
  type Auth = { id: string; email: string; name: string; role: Role; mustChangePassword: boolean; sessionId?: string };
27
64
  type AccessClaims = { id?: string; sid?: string };
@@ -1064,6 +1101,49 @@ app.patch('/projects/:id', ...allow('manager', 'admin'), async (req: AuthedReque
1064
1101
  res.json(result.rows[0]);
1065
1102
  });
1066
1103
 
1104
+ app.put('/projects/:id/deployment-topology', auth, async (req: AuthedRequest, res) => {
1105
+ const reason = requireReason(req, res); if (!reason) return;
1106
+ const id = ensureUuid(routeParam(req.params.id), 'Project ID');
1107
+ if (!(await hasProjectWriteAccess(id, req.auth!))) { res.status(403).json({ error: 'WRITE access to the project is required.' }); return; }
1108
+ const deployment = req.body?.deployment;
1109
+ const mode = String(deployment?.mode || '').trim().toLowerCase();
1110
+ const rawTargets = Array.isArray(deployment?.targets) ? deployment.targets : [];
1111
+ if (!['single','multi'].includes(mode)) { res.status(400).json({ error: 'Deployment mode must be single or multi.' }); return; }
1112
+ if (!rawTargets.length) { res.status(400).json({ error: 'Select at least one deployment environment.' }); return; }
1113
+ const roles = new Set(['primary','secondary','replica']);
1114
+ const targets: Array<{ environment: string; role: string; stage: 'dev'|'prod' }> = [];
1115
+ const seen = new Set<string>();
1116
+ for (const raw of rawTargets) {
1117
+ const environment = environmentName(raw?.environment);
1118
+ const role = String(raw?.role || 'replica').trim().toLowerCase();
1119
+ const inferredStage = /(^|[-_.])(prod|production)([-_.]|$)/i.test(environment) ? 'prod' : 'dev';
1120
+ const stage = String(raw?.stage || inferredStage).trim().toLowerCase();
1121
+ if (!['dev','prod'].includes(stage)) { res.status(400).json({ error: `Unsupported Jenkins stage: ${stage}` }); return; }
1122
+ if (!roles.has(role)) { res.status(400).json({ error: `Unsupported deployment target role: ${role}` }); return; }
1123
+ if (seen.has(environment)) continue;
1124
+ seen.add(environment);
1125
+ targets.push({ environment, role, stage: stage as 'dev'|'prod' });
1126
+ }
1127
+ if (mode === 'single' && targets.length !== 1) { res.status(400).json({ error: 'Single deployment mode must contain exactly one environment.' }); return; }
1128
+ if (mode === 'multi' && targets.length < 2) { res.status(400).json({ error: 'Multi deployment mode requires at least two environments.' }); return; }
1129
+ const names = targets.map((target) => target.environment);
1130
+ const existing = await pool.query('SELECT lower(name) AS name FROM environments WHERE lower(name)=ANY($1::text[])', [names]);
1131
+ const existingNames = new Set(existing.rows.map((row) => String(row.name)));
1132
+ const missing = names.filter((name) => !existingNames.has(name));
1133
+ if (missing.length) { res.status(400).json({ error: `Unknown shared environment(s): ${missing.join(', ')}` }); return; }
1134
+ const normalized = { mode, targets };
1135
+ const result = await pool.query(
1136
+ `UPDATE projects
1137
+ SET config=jsonb_set(COALESCE(config,'{}'::jsonb),'{deployment}',$1::jsonb,true),updated_at=now()
1138
+ WHERE id=$2
1139
+ RETURNING *`,
1140
+ [JSON.stringify(normalized), id]
1141
+ );
1142
+ if (!result.rowCount) { res.status(404).json({ error: 'Project not found' }); return; }
1143
+ await audit(req.auth!.id, 'project.deployment.update', 'project', id, reason, { mode, environments: names });
1144
+ res.json({ ...result.rows[0], effective_access: 'write' });
1145
+ });
1146
+
1067
1147
  app.delete('/projects/:id', ...allow('manager', 'admin'), async (req: AuthedRequest, res) => {
1068
1148
  const reason = requireReason(req, res); if (!reason) return;
1069
1149
  const id = ensureUuid(routeParam(req.params.id), 'Project ID');
@@ -1152,9 +1232,16 @@ app.delete('/projects/:id/members/:userId', ...allow('manager', 'admin'), async
1152
1232
  app.get('/environments', auth, async (req, res) => {
1153
1233
  const { search, limit } = listQuery(req);
1154
1234
  const result = await pool.query(`
1155
- SELECT id,name,description,host(ipv4) ipv4,region,health_path AS "healthPath",created_at,updated_at
1235
+ SELECT id,name,description,
1236
+ host(ipv4) ipv4,
1237
+ host(ipv4) AS "externalIpv4",
1238
+ host(coalesce(internal_ipv4, ipv4)) AS "internalIpv4",
1239
+ region,health_path AS "healthPath",created_at,updated_at
1156
1240
  FROM environments
1157
- WHERE ($1='' OR name ILIKE '%'||$1||'%' OR coalesce(description,'') ILIKE '%'||$1||'%' OR host(ipv4) ILIKE '%'||$1||'%')
1241
+ WHERE ($1='' OR name ILIKE '%'||$1||'%'
1242
+ OR coalesce(description,'') ILIKE '%'||$1||'%'
1243
+ OR host(ipv4) ILIKE '%'||$1||'%'
1244
+ OR host(coalesce(internal_ipv4, ipv4)) ILIKE '%'||$1||'%')
1158
1245
  ORDER BY name
1159
1246
  LIMIT $2
1160
1247
  `, [search, limit]);
@@ -1164,18 +1251,23 @@ app.get('/environments', auth, async (req, res) => {
1164
1251
  app.post('/environments', ...allow('admin'), async (req: AuthedRequest, res) => {
1165
1252
  const reason = requireReason(req, res); if (!reason) return;
1166
1253
  const name = String(req.body?.name || '').trim().toLowerCase();
1167
- const ipv4 = String(req.body?.ipv4 || '').trim();
1254
+ const externalIpv4 = String(req.body?.externalIpv4 || req.body?.ipv4 || '').trim();
1255
+ // Compatibility: older clients know only one IP. New CLI always supplies both.
1256
+ const internalIpv4 = String(req.body?.internalIpv4 || req.body?.privateIpv4 || externalIpv4).trim();
1168
1257
  const description = req.body?.description ? String(req.body.description).trim() : null;
1169
1258
  const region = req.body?.region ? String(req.body.region).trim() : null;
1170
1259
  const rawHealthPath = String(req.body?.healthPath || '/health').trim() || '/health';
1171
1260
  const healthPath = rawHealthPath.startsWith('/') ? rawHealthPath : `/${rawHealthPath}`;
1172
1261
  if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(name)) { res.status(400).json({ error: 'Environment name may contain letters, numbers, dots, hyphens and underscores.' }); return; }
1173
- if (isIP(ipv4) !== 4) { res.status(400).json({ error: 'Environment IPv4 must be a valid IPv4 address.' }); return; }
1262
+ if (isIP(externalIpv4) !== 4) { res.status(400).json({ error: 'Environment external/public IPv4 must be a valid IPv4 address.' }); return; }
1263
+ if (isIP(internalIpv4) !== 4) { res.status(400).json({ error: 'Environment internal/private IPv4 must be a valid IPv4 address.' }); return; }
1174
1264
  const result = await pool.query(
1175
- 'INSERT INTO environments(name,description,ipv4,region,health_path,created_by) VALUES($1,$2,$3,$4,$5,$6) RETURNING id,name,description,host(ipv4) ipv4,region,health_path AS "healthPath",created_at,updated_at',
1176
- [name, description, ipv4, region, healthPath, req.auth!.id]
1265
+ `INSERT INTO environments(name,description,ipv4,internal_ipv4,region,health_path,created_by)
1266
+ VALUES($1,$2,$3,$4,$5,$6,$7)
1267
+ RETURNING id,name,description,host(ipv4) ipv4,host(ipv4) AS "externalIpv4",host(internal_ipv4) AS "internalIpv4",region,health_path AS "healthPath",created_at,updated_at`,
1268
+ [name, description, externalIpv4, internalIpv4, region, healthPath, req.auth!.id]
1177
1269
  );
1178
- await audit(req.auth!.id, 'environment.create', 'environment', result.rows[0].id, reason, { name, ipv4, region });
1270
+ await audit(req.auth!.id, 'environment.create', 'environment', result.rows[0].id, reason, { name, externalIpv4, internalIpv4, region });
1179
1271
  res.status(201).json(result.rows[0]);
1180
1272
  });
1181
1273
 
@@ -1183,19 +1275,24 @@ app.put('/environments/:id', ...allow('admin'), async (req: AuthedRequest, res)
1183
1275
  const reason = requireReason(req, res); if (!reason) return;
1184
1276
  const id = routeParam(req.params.id);
1185
1277
  const name = String(req.body?.name || '').trim().toLowerCase();
1186
- const ipv4 = String(req.body?.ipv4 || '').trim();
1278
+ const externalIpv4 = String(req.body?.externalIpv4 || req.body?.ipv4 || '').trim();
1279
+ const internalIpv4 = String(req.body?.internalIpv4 || req.body?.privateIpv4 || externalIpv4).trim();
1187
1280
  const description = req.body?.description ? String(req.body.description).trim() : null;
1188
1281
  const region = req.body?.region ? String(req.body.region).trim() : null;
1189
1282
  const rawHealthPath = String(req.body?.healthPath || '/health').trim() || '/health';
1190
1283
  const healthPath = rawHealthPath.startsWith('/') ? rawHealthPath : `/${rawHealthPath}`;
1191
1284
  if (!/^[a-z0-9][a-z0-9._-]{0,63}$/.test(name)) { res.status(400).json({ error: 'Invalid environment name.' }); return; }
1192
- if (isIP(ipv4) !== 4) { res.status(400).json({ error: 'Environment IPv4 must be a valid IPv4 address.' }); return; }
1285
+ if (isIP(externalIpv4) !== 4) { res.status(400).json({ error: 'Environment external/public IPv4 must be a valid IPv4 address.' }); return; }
1286
+ if (isIP(internalIpv4) !== 4) { res.status(400).json({ error: 'Environment internal/private IPv4 must be a valid IPv4 address.' }); return; }
1193
1287
  const result = await pool.query(
1194
- 'UPDATE environments SET name=$1,description=$2,ipv4=$3,region=$4,health_path=$5,updated_at=now() WHERE id=$6 RETURNING id,name,description,host(ipv4) ipv4,region,health_path AS "healthPath",created_at,updated_at',
1195
- [name, description, ipv4, region, healthPath, id]
1288
+ `UPDATE environments
1289
+ SET name=$1,description=$2,ipv4=$3,internal_ipv4=$4,region=$5,health_path=$6,updated_at=now()
1290
+ WHERE id=$7
1291
+ RETURNING id,name,description,host(ipv4) ipv4,host(ipv4) AS "externalIpv4",host(internal_ipv4) AS "internalIpv4",region,health_path AS "healthPath",created_at,updated_at`,
1292
+ [name, description, externalIpv4, internalIpv4, region, healthPath, id]
1196
1293
  );
1197
1294
  if (!result.rowCount) { res.status(404).json({ error: 'Environment not found' }); return; }
1198
- await audit(req.auth!.id, 'environment.update', 'environment', id, reason, { name, ipv4, region });
1295
+ await audit(req.auth!.id, 'environment.update', 'environment', id, reason, { name, externalIpv4, internalIpv4, region });
1199
1296
  res.json(result.rows[0]);
1200
1297
  });
1201
1298
 
@@ -1940,6 +2037,42 @@ app.post('/projects/:projectId/jenkins-control', auth, async (req: AuthedRequest
1940
2037
  res.json({ exists: true }); return;
1941
2038
  }
1942
2039
 
2040
+ if (operation === 'ensure-mobile-job') {
2041
+ const jobName = String(req.body?.jobName || '').trim();
2042
+ const pipelineScript = String(req.body?.pipelineScript || '');
2043
+ if (jobName !== 'Mobile app Cli build') { res.status(400).json({ error: 'Only the managed IndraQ mobile build job may be reconciled through this operation.' }); return; }
2044
+ if (!pipelineScript || pipelineScript.length > 250_000) { res.status(400).json({ error: 'pipelineScript is required and must be 250 KB or smaller.' }); return; }
2045
+ const xmlEscape = (value: string): string => value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&apos;');
2046
+ const configXml = `<?xml version="1.1" encoding="UTF-8"?>
2047
+ <flow-definition plugin="workflow-job">
2048
+ <actions/>
2049
+ <description>Managed by IndraQ CLI for mobile builds.</description>
2050
+ <keepDependencies>false</keepDependencies>
2051
+ <properties/>
2052
+ <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps">
2053
+ <script>${xmlEscape(pipelineScript)}</script>
2054
+ <sandbox>true</sandbox>
2055
+ </definition>
2056
+ <triggers/>
2057
+ <disabled>false</disabled>
2058
+ </flow-definition>
2059
+ `;
2060
+ const headers = { ...(await jenkinsHeaders(resolved.connection)), 'content-type': 'application/xml' };
2061
+ const lookup = await fetch(`${resolved.connection.url}/${jenkinsJobPath(jobName)}/api/json`, { headers: { authorization: jenkinsBasic(resolved.connection) } });
2062
+ let response: globalThis.Response;
2063
+ if (lookup.status === 404) {
2064
+ response = await fetch(`${resolved.connection.url}/createItem?name=${encodeURIComponent(jobName)}`, { method:'POST', headers, body:configXml });
2065
+ } else if (lookup.ok) {
2066
+ response = await fetch(`${resolved.connection.url}/${jenkinsJobPath(jobName)}/config.xml`, { method:'POST', headers, body:configXml });
2067
+ } else {
2068
+ throw new Error(`Jenkins job lookup failed for ${jobName} (HTTP ${lookup.status}).`);
2069
+ }
2070
+ const responseBody = await response.text();
2071
+ if (!response.ok) throw new Error(`Unable to reconcile Jenkins mobile job ${jobName} (HTTP ${response.status}): ${compactJenkinsError(responseBody)}`);
2072
+ await audit(req.auth!.id, 'jenkins.control.mobile-job.ensure', 'project', projectId, reason, { environment, provider: resolved.provider, scopeId: resolved.scopeId, jobName });
2073
+ res.json({ ok:true, jobName }); return;
2074
+ }
2075
+
1943
2076
  if (operation === 'host-port-check') {
1944
2077
  const port = Number(req.body?.port);
1945
2078
  if (!Number.isInteger(port) || port < 1 || port > 65535) { res.status(400).json({ error: 'port must be between 1 and 65535.' }); return; }
@@ -2242,6 +2375,488 @@ app.post('/projects/:projectId/integrations/:provider/resolve', auth, async (req
2242
2375
  res.json({ config: result.rows[0].config || {}, secret });
2243
2376
  });
2244
2377
 
2378
+ // ---- Mobile environments + self-hosted OTA -------------------------------------------------
2379
+ type OtaIdentity = { type: 'installation'|'userId'|'username'|'email'|'phone'; value: string };
2380
+
2381
+ const mobileAppForUser = async (appIdRaw: string, user: Auth, write = false): Promise<any | null> => {
2382
+ const appId = ensureUuid(appIdRaw, 'Mobile app ID');
2383
+ const found = await pool.query('SELECT ma.*,p.name project_name FROM mobile_apps ma JOIN projects p ON p.id=ma.project_id WHERE ma.id=$1', [appId]);
2384
+ if (!found.rowCount) return null;
2385
+ const allowed = write ? await hasProjectWriteAccess(found.rows[0].project_id, user) : await hasProjectAccess(found.rows[0].project_id, user);
2386
+ return allowed ? found.rows[0] : null;
2387
+ };
2388
+
2389
+ const releaseForUser = async (releaseIdRaw: string, user: Auth, write = false): Promise<any | null> => {
2390
+ const releaseId = ensureUuid(releaseIdRaw, 'OTA release ID');
2391
+ const found = await pool.query(
2392
+ `SELECT r.*,ma.project_id,ma.app_name,ma.update_path FROM ota_releases r JOIN mobile_apps ma ON ma.id=r.app_id WHERE r.id=$1`,
2393
+ [releaseId]
2394
+ );
2395
+ if (!found.rowCount) return null;
2396
+ const allowed = write ? await hasProjectWriteAccess(found.rows[0].project_id, user) : await hasProjectAccess(found.rows[0].project_id, user);
2397
+ return allowed ? found.rows[0] : null;
2398
+ };
2399
+
2400
+ const publicMobileApp = async (updatePath: string): Promise<any | null> => {
2401
+ const result = await pool.query('SELECT * FROM mobile_apps WHERE update_path=$1', [updatePath]);
2402
+ return result.rows[0] || null;
2403
+ };
2404
+
2405
+ const parseExpoExtraParams = (header: unknown): Record<string,string> => {
2406
+ const input=String(header||'').trim(); const out:Record<string,string>={};
2407
+ // Expo-Extra-Params is an SFV dictionary. IndraQ writes only string values, so a
2408
+ // small defensive parser is enough and avoids adding another server dependency.
2409
+ const pair=/([a-z0-9_*.-]+)\s*=\s*("(?:\\.|[^"])*"|[^,]+)(?:,|$)/gi; let match:RegExpExecArray|null;
2410
+ while((match=pair.exec(input))){
2411
+ let value=String(match[2]||'').trim();
2412
+ if(value.startsWith('"')&&value.endsWith('"')) value=value.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,'\\');
2413
+ out[String(match[1]||'').toLowerCase()]=value;
2414
+ }
2415
+ return out;
2416
+ };
2417
+ const requestIdentity = (req: Request): { installationId: string; userId: string; username: string; email: string; phone: string; currentUpdateId:string } => {
2418
+ const extra=parseExpoExtraParams(req.headers['expo-extra-params']);
2419
+ const value=(header:string,extraKey:string,max:number):string=>String(req.headers[header]||extra[extraKey]||'').trim().slice(0,max);
2420
+ return {
2421
+ installationId:value('x-indraq-installation-id','indraq-installation-id',200),
2422
+ userId:value('x-indraq-user-id','indraq-user-id',200),
2423
+ username:value('x-indraq-username','indraq-username',200),
2424
+ email:value('x-indraq-email','indraq-email',320).toLowerCase(),
2425
+ phone:value('x-indraq-phone','indraq-phone',80),
2426
+ currentUpdateId:value('x-indraq-current-update-id','indraq-current-update-id',200)
2427
+ };
2428
+ };
2429
+
2430
+ const audienceMatches = (row: any, identity: ReturnType<typeof requestIdentity>): boolean => {
2431
+ if (row.status === 'released' && row.audience_type === 'all') return true;
2432
+ if (row.status === 'released' && row.audience_type === 'percentage') {
2433
+ if (!identity.installationId || !row.rollout_percent) return false;
2434
+ const bucket = Number.parseInt(createHash('sha256').update(`${identity.installationId}:${row.id}`).digest('hex').slice(0, 8), 16) % 100;
2435
+ return bucket < Number(row.rollout_percent);
2436
+ }
2437
+ const identities = Array.isArray(row.audience?.identities) ? row.audience.identities as OtaIdentity[] : [];
2438
+ return identities.some((item) => {
2439
+ const expected = String(item.value || '').trim().toLowerCase();
2440
+ if (!expected) return false;
2441
+ if (item.type === 'installation') return identity.installationId.toLowerCase() === expected;
2442
+ if (item.type === 'userId') return identity.userId.toLowerCase() === expected;
2443
+ if (item.type === 'username') return identity.username.toLowerCase() === expected;
2444
+ if (item.type === 'email') return identity.email.toLowerCase() === expected;
2445
+ if (item.type === 'phone') return identity.phone.toLowerCase() === expected;
2446
+ return false;
2447
+ });
2448
+ };
2449
+
2450
+ const signExpoManifest = (manifestString: string, encryptedPrivateKey: string): string => {
2451
+ const signer = createSign('RSA-SHA256');
2452
+ signer.update(manifestString);
2453
+ signer.end();
2454
+ const signature = signer.sign(decrypt(encryptedPrivateKey)).toString('base64');
2455
+ return `sig="${signature}", keyid="main", alg="rsa-v1_5-sha256"`;
2456
+ };
2457
+
2458
+ app.get('/mobile/environments', auth, async (_req, res) => {
2459
+ res.json((await pool.query(
2460
+ `SELECT id,name,slug,build_type,jenkins_stage,ota_channel,description,is_active,created_at,updated_at
2461
+ FROM mobile_environments WHERE is_active=true ORDER BY name`
2462
+ )).rows);
2463
+ });
2464
+
2465
+ app.post('/mobile/environments', ...allow('admin'), async (req: AuthedRequest, res) => {
2466
+ const reason = requireReason(req, res); if (!reason) return;
2467
+ const name = textValue(req.body?.name, 'Environment name', 100);
2468
+ const slug = slugValue(req.body?.slug || name, 'Environment slug');
2469
+ const buildType = String(req.body?.buildType || '').trim().toLowerCase();
2470
+ if (!['dev','staging','prod'].includes(buildType)) { res.status(400).json({ error: 'buildType must be dev, staging, or prod.' }); return; }
2471
+ const stage = String(req.body?.jenkinsStage || (buildType === 'dev' ? 'dev' : 'prod')).trim().toLowerCase();
2472
+ if (!['dev','prod'].includes(stage)) { res.status(400).json({ error: 'jenkinsStage must be dev or prod.' }); return; }
2473
+ const otaChannel = slugValue(req.body?.otaChannel || slug, 'OTA channel');
2474
+ const result = await pool.query(
2475
+ `INSERT INTO mobile_environments(name,slug,build_type,jenkins_stage,ota_channel,description,created_by)
2476
+ VALUES($1,$2,$3,$4,$5,$6,$7)
2477
+ RETURNING id,name,slug,build_type,jenkins_stage,ota_channel,description,is_active,created_at,updated_at`,
2478
+ [name,slug,buildType,stage,otaChannel,req.body?.description ? String(req.body.description).trim() : null,req.auth!.id]
2479
+ );
2480
+ await audit(req.auth!.id,'mobile.environment.create','mobile-environment',result.rows[0].id,reason,{name,slug,buildType,stage,otaChannel});
2481
+ res.status(201).json(result.rows[0]);
2482
+ });
2483
+
2484
+ app.put('/mobile/environments/:id', ...allow('admin'), async (req: AuthedRequest, res) => {
2485
+ const reason = requireReason(req, res); if (!reason) return;
2486
+ const id = ensureUuid(routeParam(req.params.id), 'Mobile environment ID');
2487
+ const current = (await pool.query('SELECT * FROM mobile_environments WHERE id=$1',[id])).rows[0];
2488
+ if (!current) { res.status(404).json({ error: 'Mobile environment not found.' }); return; }
2489
+ const name = req.body?.name === undefined ? current.name : textValue(req.body.name,'Environment name',100);
2490
+ const slug = req.body?.slug === undefined ? current.slug : slugValue(req.body.slug,'Environment slug');
2491
+ const buildType = req.body?.buildType === undefined ? current.build_type : String(req.body.buildType).trim().toLowerCase();
2492
+ if (!['dev','staging','prod'].includes(buildType)) { res.status(400).json({ error: 'buildType must be dev, staging, or prod.' }); return; }
2493
+ const stage = req.body?.jenkinsStage === undefined ? current.jenkins_stage : String(req.body.jenkinsStage).trim().toLowerCase();
2494
+ if (!['dev','prod'].includes(stage)) { res.status(400).json({ error: 'jenkinsStage must be dev or prod.' }); return; }
2495
+ const otaChannel = req.body?.otaChannel === undefined ? current.ota_channel : slugValue(req.body.otaChannel,'OTA channel');
2496
+ const active = req.body?.isActive === undefined ? current.is_active : Boolean(req.body.isActive);
2497
+ const result = await pool.query(
2498
+ `UPDATE mobile_environments SET name=$1,slug=$2,build_type=$3,jenkins_stage=$4,ota_channel=$5,description=$6,is_active=$7,updated_at=now()
2499
+ WHERE id=$8 RETURNING id,name,slug,build_type,jenkins_stage,ota_channel,description,is_active,created_at,updated_at`,
2500
+ [name,slug,buildType,stage,otaChannel,req.body?.description === undefined ? current.description : (req.body.description ? String(req.body.description).trim() : null),active,id]
2501
+ );
2502
+ await audit(req.auth!.id,'mobile.environment.update','mobile-environment',id,reason,{name,slug,buildType,stage,otaChannel,active});
2503
+ res.json(result.rows[0]);
2504
+ });
2505
+
2506
+ app.delete('/mobile/environments/:id', ...allow('admin'), async (req: AuthedRequest, res) => {
2507
+ const reason = requireReason(req, res); if (!reason) return;
2508
+ const id = ensureUuid(routeParam(req.params.id), 'Mobile environment ID');
2509
+ const result = await pool.query('UPDATE mobile_environments SET is_active=false,updated_at=now() WHERE id=$1 AND is_active=true RETURNING name',[id]);
2510
+ if (!result.rowCount) { res.status(404).json({ error: 'Mobile environment not found.' }); return; }
2511
+ await audit(req.auth!.id,'mobile.environment.disable','mobile-environment',id,reason,{name:result.rows[0].name});
2512
+ res.status(204).end();
2513
+ });
2514
+
2515
+ app.get('/projects/:projectId/mobile', auth, async (req: AuthedRequest, res) => {
2516
+ const projectId = ensureUuid(routeParam(req.params.projectId),'Project ID');
2517
+ if (!(await hasProjectAccess(projectId,req.auth!))) { res.status(404).json({error:'Project not found or access denied'}); return; }
2518
+ const appRow = (await pool.query(
2519
+ `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,
2520
+ 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,
2521
+ 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
2522
+ FROM mobile_apps ma
2523
+ LEFT JOIN mobile_app_environments mae ON mae.app_id=ma.id
2524
+ LEFT JOIN mobile_environments me ON me.id=mae.mobile_environment_id
2525
+ WHERE ma.project_id=$1 ORDER BY me.name`,[projectId]
2526
+ )).rows;
2527
+ if (!appRow.length) { res.status(404).json({error:'Mobile app is not registered for OTA yet.'}); return; }
2528
+ const first=appRow[0];
2529
+ res.json({
2530
+ id:first.id,projectId:first.project_id,appName:first.app_name,projectType:first.project_type,androidPackage:first.android_package,iosBundleIdentifier:first.ios_bundle_identifier,
2531
+ runtimePolicy:first.runtime_policy,updateUrl:`${publicApiUrl}/ota/v1/manifest/${first.update_path}`,keyId:first.signing_key_id,certificate:first.signing_certificate,
2532
+ environments:appRow.filter((r:any)=>r.environment_id).map((r:any)=>({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}))
2533
+ });
2534
+ });
2535
+
2536
+ app.post('/projects/:projectId/mobile/register', auth, async (req: AuthedRequest, res) => {
2537
+ const reason = requireReason(req,res); if (!reason) return;
2538
+ const projectId = ensureUuid(routeParam(req.params.projectId),'Project ID');
2539
+ if (!(await hasProjectWriteAccess(projectId,req.auth!))) { res.status(403).json({error:'WRITE access to the project is required.'}); return; }
2540
+ const project = (await pool.query('SELECT id,kind FROM projects WHERE id=$1',[projectId])).rows[0];
2541
+ if (!project || project.kind !== 'mobile') { res.status(400).json({error:'OTA registration is available only for mobile projects.'}); return; }
2542
+ const appName=textValue(req.body?.appName,'App name',100);
2543
+ const projectType=String(req.body?.projectType||'').trim();
2544
+ if (!['expo','react-native'].includes(projectType)) { res.status(400).json({error:'projectType must be expo or react-native.'}); return; }
2545
+ const environmentId=ensureUuid(String(req.body?.environmentId||''),'Mobile environment ID');
2546
+ const env=(await pool.query('SELECT * FROM mobile_environments WHERE id=$1 AND is_active=true',[environmentId])).rows[0];
2547
+ if (!env) { res.status(404).json({error:'Mobile environment not found.'}); return; }
2548
+ const runtimeVersion=textValue(req.body?.runtimeVersion,'Runtime version',100);
2549
+ const existing=(await pool.query('SELECT * FROM mobile_apps WHERE project_id=$1',[projectId])).rows[0];
2550
+ const privateKey=typeof req.body?.signingPrivateKey==='string' && req.body.signingPrivateKey.includes('PRIVATE KEY') ? req.body.signingPrivateKey : '';
2551
+ const certificate=typeof req.body?.signingCertificate==='string' && req.body.signingCertificate.includes('CERTIFICATE') ? req.body.signingCertificate : '';
2552
+ if (!existing && (!privateKey || !certificate)) { res.status(400).json({error:'First OTA registration requires signingPrivateKey and signingCertificate.'}); return; }
2553
+ const appResult=await pool.query(
2554
+ `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)
2555
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)
2556
+ 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,
2557
+ 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()
2558
+ RETURNING *`,
2559
+ [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]
2560
+ );
2561
+ const appRow=appResult.rows[0];
2562
+ await pool.query(
2563
+ `INSERT INTO mobile_app_environments(app_id,mobile_environment_id,runtime_version) VALUES($1,$2,$3)
2564
+ ON CONFLICT(app_id,mobile_environment_id) DO UPDATE SET
2565
+ native_fingerprint=CASE WHEN mobile_app_environments.runtime_version IS DISTINCT FROM excluded.runtime_version THEN NULL ELSE mobile_app_environments.native_fingerprint END,
2566
+ 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,
2567
+ 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,
2568
+ 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,
2569
+ 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,
2570
+ 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,
2571
+ 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,
2572
+ runtime_version=excluded.runtime_version,enabled=true,updated_at=now()`,
2573
+ [appRow.id,environmentId,runtimeVersion]
2574
+ );
2575
+ await audit(req.auth!.id,'mobile.app.register','mobile-app',appRow.id,reason,{projectId,environmentId,runtimeVersion,projectType});
2576
+ 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}});
2577
+ });
2578
+
2579
+
2580
+ app.post('/mobile/apps/:appId/environments/:environmentId/native-build', auth, async (req: AuthedRequest,res) => {
2581
+ const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!,true); if(!appRow){res.status(404).json({error:'Mobile app not found or WRITE access denied.'});return;}
2582
+ const environmentId=ensureUuid(routeParam(req.params.environmentId),'Mobile environment ID');
2583
+ const reason=requireReason(req,res); if(!reason)return;
2584
+ const nativeFingerprint=String(req.body?.nativeFingerprint||'').trim().toLowerCase();
2585
+ if(!/^[a-f0-9]{64}$/.test(nativeFingerprint)){res.status(400).json({error:'nativeFingerprint must be a 64-character SHA-256 hex value.'});return;}
2586
+ const runtimeVersion=textValue(req.body?.runtimeVersion,'Runtime version',100);
2587
+ const binding=(await pool.query(`SELECT runtime_version FROM mobile_app_environments WHERE app_id=$1 AND mobile_environment_id=$2 AND enabled=true`,[appRow.id,environmentId])).rows[0];
2588
+ if(!binding){res.status(404).json({error:'This mobile environment is not registered for the app. Run mobile prebuild first.'});return;}
2589
+ if(runtimeVersion!==binding.runtime_version){res.status(409).json({error:`Runtime version ${runtimeVersion} does not match registered runtime ${binding.runtime_version}. Run mobile prebuild first.`});return;}
2590
+ const appVersion=String(req.body?.appVersion||runtimeVersion).trim().slice(0,100);
2591
+ const versionCode=req.body?.versionCode===undefined||req.body?.versionCode===null?null:Number(req.body.versionCode);
2592
+ const buildNumber=req.body?.buildNumber===undefined||req.body?.buildNumber===null?null:Number(req.body.buildNumber);
2593
+ if(versionCode!==null&&(!Number.isInteger(versionCode)||versionCode<1)){res.status(400).json({error:'versionCode must be a positive integer.'});return;}
2594
+ if(buildNumber!==null&&(!Number.isInteger(buildNumber)||buildNumber<1)){res.status(400).json({error:'buildNumber must be a positive integer.'});return;}
2595
+ const buildUrl=req.body?.buildUrl?String(req.body.buildUrl).trim().slice(0,2000):null;
2596
+ const sourceSha=String(req.body?.sourceSha256||'').trim().toLowerCase();
2597
+ if(sourceSha&&!/^[a-f0-9]{64}$/.test(sourceSha)){res.status(400).json({error:'sourceSha256 must be a 64-character SHA-256 hex value.'});return;}
2598
+ const row=(await pool.query(
2599
+ `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()
2600
+ 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`,
2601
+ [nativeFingerprint,appVersion,versionCode,buildNumber,buildUrl,sourceSha||null,appRow.id,environmentId]
2602
+ )).rows[0];
2603
+ await audit(req.auth!.id,'mobile.native-build.record','mobile-app',appRow.id,reason,{environmentId,runtimeVersion,nativeFingerprint,appVersion,versionCode,buildNumber,sourceSha256:sourceSha||null});
2604
+ 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});
2605
+ });
2606
+
2607
+ app.get('/mobile/apps/:appId/releases', auth, async (req: AuthedRequest,res) => {
2608
+ const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!); if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
2609
+ const rows=(await pool.query(
2610
+ `SELECT r.id,r.runtime_version,r.message,r.status,r.audience_type,r.audience,r.rollout_percent,r.promoted_at,r.created_at,me.name environment_name,me.slug environment_slug,
2611
+ json_agg(json_build_object('id',u.id,'platform',u.platform) ORDER BY u.platform) FILTER (WHERE u.id IS NOT NULL) updates
2612
+ FROM ota_releases r JOIN mobile_environments me ON me.id=r.mobile_environment_id LEFT JOIN ota_updates u ON u.release_id=r.id
2613
+ WHERE r.app_id=$1 GROUP BY r.id,me.name,me.slug ORDER BY r.created_at DESC LIMIT 100`,[appRow.id]
2614
+ )).rows;
2615
+ res.json(rows);
2616
+ });
2617
+
2618
+ app.post('/mobile/apps/:appId/releases', auth, async (req: AuthedRequest,res) => {
2619
+ const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!,true); if(!appRow){res.status(404).json({error:'Mobile app not found or WRITE access denied.'});return;}
2620
+ const environmentId=ensureUuid(String(req.body?.environmentId||''),'Mobile environment ID');
2621
+ const binding=(await pool.query(
2622
+ `SELECT mae.runtime_version,me.name,me.slug,me.ota_channel FROM mobile_app_environments mae JOIN mobile_environments me ON me.id=mae.mobile_environment_id
2623
+ WHERE mae.app_id=$1 AND mae.mobile_environment_id=$2 AND mae.enabled=true AND me.is_active=true`,[appRow.id,environmentId]
2624
+ )).rows[0];
2625
+ if(!binding){res.status(400).json({error:'This mobile environment is not registered for the app. Run mobile prebuild first.'});return;}
2626
+ const runtimeVersion=textValue(req.body?.runtimeVersion||binding.runtime_version,'Runtime version',100);
2627
+ if(runtimeVersion!==binding.runtime_version){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.`});return;}
2628
+ 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];
2629
+ if(!nativeBaseline?.native_fingerprint){res.status(409).json({error:'No successful native Jenkins build baseline exists for this mobile environment. Build the native app before publishing OTA updates.'});return;}
2630
+ const requestedFingerprint=String(req.body?.nativeFingerprint||'').trim().toLowerCase();
2631
+ if(!/^[a-f0-9]{64}$/.test(requestedFingerprint)){res.status(400).json({error:'nativeFingerprint is required and must be a SHA-256 hex value.'});return;}
2632
+ if(requestedFingerprint!==String(nativeBaseline.native_fingerprint).toLowerCase()){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.'});return;}
2633
+ const message=textValue(req.body?.message,'Update message',500);
2634
+ const audienceType=String(req.body?.audienceType||'test');
2635
+ if(!['test','all','percentage'].includes(audienceType)){res.status(400).json({error:'audienceType must be test, all, or percentage.'});return;}
2636
+ const platformValues=Array.isArray(req.body?.platforms)?[...new Set<string>(req.body.platforms.map((v:unknown)=>String(v).toLowerCase()))]:[];
2637
+ if(!platformValues.length||platformValues.some((v:string)=>!['android','ios'].includes(v))){res.status(400).json({error:'platforms must contain android and/or ios.'});return;}
2638
+ const platforms=platformValues as Array<'android'|'ios'>;
2639
+ let rollout:number|null=null;
2640
+ if(audienceType==='percentage'){
2641
+ const candidate=Number(req.body?.rolloutPercent);
2642
+ if(!Number.isInteger(candidate)||candidate<1||candidate>100){res.status(400).json({error:'rolloutPercent must be 1-100.'});return;}
2643
+ rollout=candidate;
2644
+ }
2645
+ // Keep partially uploaded releases invisible to clients until finalize succeeds.
2646
+ const status='draft';
2647
+ const client=await pool.connect();
2648
+ try{
2649
+ await client.query('BEGIN');
2650
+ const release=(await client.query(
2651
+ `INSERT INTO ota_releases(app_id,mobile_environment_id,runtime_version,message,status,audience_type,audience,rollout_percent,promoted_at,created_by)
2652
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING *`,
2653
+ [appRow.id,environmentId,runtimeVersion,message,status,audienceType,req.body?.audience||{},rollout,null,req.auth!.id]
2654
+ )).rows[0];
2655
+ const updates:any[]=[];
2656
+ for(const platform of platforms){updates.push((await client.query('INSERT INTO ota_updates(release_id,platform) VALUES($1,$2) RETURNING id,platform,created_at',[release.id,platform])).rows[0]);}
2657
+ await client.query('COMMIT');
2658
+ await audit(req.auth!.id,'ota.release.create','ota-release',release.id,message,{appId:appRow.id,environmentId,runtimeVersion,audienceType,platforms});
2659
+ res.status(201).json({release,updates,environment:binding});
2660
+ }catch(error){await client.query('ROLLBACK');throw error;}finally{client.release();}
2661
+ });
2662
+
2663
+ app.put('/mobile/releases/:releaseId/assets/:sha256', express.raw({type:'*/*',limit:'100mb'}), auth, async (req: AuthedRequest,res) => {
2664
+ const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
2665
+ const sha=String(routeParam(req.params.sha256)).toLowerCase();
2666
+ if(!/^[a-f0-9]{64}$/.test(sha)){res.status(400).json({error:'Asset SHA-256 must be 64 hex characters.'});return;}
2667
+ const body=Buffer.isBuffer(req.body)?req.body:Buffer.from(req.body||'');
2668
+ if(!body.length){res.status(400).json({error:'Asset body is empty.'});return;}
2669
+ if(hexSha256(body)!==sha){res.status(400).json({error:'Asset SHA-256 does not match request path.'});return;}
2670
+ await ensureOtaBucket();
2671
+ const objectKey=`assets/${sha}`;
2672
+ const minio=getMinio();
2673
+ try{await minio.statObject(minioBucket,objectKey);}catch{await minio.putObject(minioBucket,objectKey,body,body.length,{'Content-Type':String(req.headers['x-indraq-content-type']||req.headers['content-type']||'application/octet-stream')});}
2674
+ const extension=String(req.headers['x-indraq-file-extension']||'').trim()||null;
2675
+ const result=await pool.query(
2676
+ `INSERT INTO ota_assets(sha256,object_key,content_type,file_extension,size_bytes) VALUES($1,$2,$3,$4,$5)
2677
+ ON CONFLICT(sha256) DO UPDATE SET content_type=excluded.content_type,file_extension=COALESCE(ota_assets.file_extension,excluded.file_extension)
2678
+ RETURNING id,sha256,size_bytes`,[sha,objectKey,String(req.headers['x-indraq-content-type']||req.headers['content-type']||'application/octet-stream'),extension,body.length]
2679
+ );
2680
+ res.json(result.rows[0]);
2681
+ });
2682
+
2683
+ app.post('/mobile/releases/:releaseId/finalize', auth, async (req: AuthedRequest,res) => {
2684
+ const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
2685
+ const platforms=Array.isArray(req.body?.platforms)?req.body.platforms:[];
2686
+ if(!platforms.length){res.status(400).json({error:'Platform manifests are required.'});return;}
2687
+ const client=await pool.connect();
2688
+ try{
2689
+ await client.query('BEGIN');
2690
+ for(const spec of platforms){
2691
+ const platform=String(spec?.platform||'');
2692
+ const update=(await client.query('SELECT id,created_at FROM ota_updates WHERE release_id=$1 AND platform=$2',[release.id,platform])).rows[0];
2693
+ if(!update) throw Object.assign(new Error(`No ${platform} update exists in this release.`),{statusCode:400});
2694
+ const launch=spec?.launchAsset;
2695
+ const assets=Array.isArray(spec?.assets)?spec.assets:[];
2696
+ if(!launch?.sha256||!launch?.key) throw Object.assign(new Error(`${platform} launch asset is incomplete.`),{statusCode:400});
2697
+ const all=[{...launch,role:'launch',sortOrder:0},...assets.map((a:any,i:number)=>({...a,role:'asset',sortOrder:i+1}))];
2698
+ const manifestAssets:any[]=[]; let launchAsset:any=null;
2699
+ await client.query('DELETE FROM ota_update_assets WHERE update_id=$1',[update.id]);
2700
+ for(const item of all){
2701
+ const asset=(await client.query('SELECT * FROM ota_assets WHERE sha256=$1',[String(item.sha256).toLowerCase()])).rows[0];
2702
+ if(!asset) throw Object.assign(new Error(`Asset ${item.sha256} was not uploaded.`),{statusCode:409});
2703
+ const descriptor={hash:Buffer.from(asset.sha256,'hex').toString('base64url'),key:String(item.key),contentType:String(item.contentType||asset.content_type),...(item.fileExtension?{fileExtension:String(item.fileExtension)}:{}),url:`${publicApiUrl}/ota/v1/assets/${asset.sha256}`};
2704
+ if(item.role==='launch') launchAsset=descriptor; else manifestAssets.push(descriptor);
2705
+ await client.query('INSERT INTO ota_update_assets(update_id,asset_id,asset_key,role,sort_order) VALUES($1,$2,$3,$4,$5)',[update.id,asset.id,String(item.key),item.role,item.sortOrder]);
2706
+ }
2707
+ const manifest={id:update.id,createdAt:new Date(update.created_at).toISOString(),runtimeVersion:release.runtime_version,launchAsset,assets:manifestAssets,metadata:{indraqReleaseId:release.id},extra:{expoClient:spec?.expoConfig||{},indraq:{releaseId:release.id,message:release.message}}};
2708
+ await client.query('UPDATE ota_updates SET manifest=$1,source_hash=$2 WHERE id=$3',[manifest,spec?.sourceHash||null,update.id]);
2709
+ }
2710
+ const finalStatus=release.audience_type==='test'?'test':'released';
2711
+ await client.query(
2712
+ `UPDATE ota_releases SET status=$1,promoted_at=CASE WHEN $1='released' THEN now() ELSE NULL END,updated_at=now() WHERE id=$2`,
2713
+ [finalStatus,release.id]
2714
+ );
2715
+ await client.query('COMMIT');
2716
+ await audit(req.auth!.id,'ota.release.finalize','ota-release',release.id,release.message,{platforms:platforms.map((p:any)=>p.platform),status:finalStatus});
2717
+ res.json({ok:true,releaseId:release.id,status:finalStatus});
2718
+ }catch(error){await client.query('ROLLBACK');throw error;}finally{client.release();}
2719
+ });
2720
+
2721
+ app.post('/mobile/releases/:releaseId/promote', auth, async (req: AuthedRequest,res) => {
2722
+ const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
2723
+ const incomplete=(await pool.query(`SELECT count(*)::int count FROM ota_updates WHERE release_id=$1 AND manifest='{}'::jsonb`,[release.id])).rows[0]?.count||0;
2724
+ if(incomplete){res.status(409).json({error:'OTA release is not finalized yet and cannot be promoted.'});return;}
2725
+ const result=await pool.query(`UPDATE ota_releases SET status='released',audience_type='all',audience='{}'::jsonb,rollout_percent=NULL,promoted_at=now(),updated_at=now() WHERE id=$1 RETURNING *`,[release.id]);
2726
+ await audit(req.auth!.id,'ota.release.promote','ota-release',release.id,req.body?.reason||'Promote tested OTA release',{appId:release.app_id});
2727
+ res.json(result.rows[0]);
2728
+ });
2729
+
2730
+ app.post('/mobile/releases/:releaseId/pause', auth, async (req: AuthedRequest,res) => {
2731
+ const release=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!release){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
2732
+ await pool.query(`UPDATE ota_releases SET status='paused',updated_at=now() WHERE id=$1`,[release.id]);
2733
+ await audit(req.auth!.id,'ota.release.pause','ota-release',release.id,req.body?.reason||'Pause OTA release');
2734
+ res.json({ok:true});
2735
+ });
2736
+
2737
+ app.post('/mobile/releases/:releaseId/rollback', auth, async (req: AuthedRequest,res) => {
2738
+ const current=await releaseForUser(routeParam(req.params.releaseId),req.auth!,true); if(!current){res.status(404).json({error:'OTA release not found or WRITE access denied.'});return;}
2739
+ const targetId=req.body?.targetReleaseId?ensureUuid(String(req.body.targetReleaseId),'Target release ID'):null;
2740
+ const target=(await pool.query(
2741
+ targetId
2742
+ ? `SELECT * FROM ota_releases WHERE id=$1 AND app_id=$2 AND mobile_environment_id=$3 AND runtime_version=$4 AND status='released'`
2743
+ : `SELECT * FROM ota_releases WHERE app_id=$1 AND mobile_environment_id=$2 AND runtime_version=$3 AND id<>$4 AND status='released' ORDER BY created_at DESC LIMIT 1`,
2744
+ targetId?[targetId,current.app_id,current.mobile_environment_id,current.runtime_version]:[current.app_id,current.mobile_environment_id,current.runtime_version,current.id]
2745
+ )).rows[0];
2746
+ if(!target){res.status(404).json({error:'No previous compatible OTA release is available to roll back to.'});return;}
2747
+ const client=await pool.connect();
2748
+ try{
2749
+ await client.query('BEGIN');
2750
+ const rollback=(await client.query(
2751
+ `INSERT INTO ota_releases(app_id,mobile_environment_id,runtime_version,message,status,audience_type,audience,promoted_at,created_by)
2752
+ VALUES($1,$2,$3,$4,'released','all','{}'::jsonb,now(),$5) RETURNING *`,
2753
+ [current.app_id,current.mobile_environment_id,target.runtime_version,`Rollback to ${target.id}: ${target.message}`,req.auth!.id]
2754
+ )).rows[0];
2755
+ const targetUpdates=(await client.query('SELECT * FROM ota_updates WHERE release_id=$1 ORDER BY platform',[target.id])).rows;
2756
+ for(const old of targetUpdates){
2757
+ const next=(await client.query('INSERT INTO ota_updates(release_id,platform,source_hash) VALUES($1,$2,$3) RETURNING id,created_at',[rollback.id,old.platform,old.source_hash])).rows[0];
2758
+ const manifest={...(old.manifest||{}),id:next.id,createdAt:new Date(next.created_at).toISOString(),metadata:{...(old.manifest?.metadata||{}),indraqReleaseId:rollback.id},extra:{...(old.manifest?.extra||{}),indraq:{releaseId:rollback.id,message:rollback.message,rollbackOf:current.id,targetReleaseId:target.id}}};
2759
+ await client.query('UPDATE ota_updates SET manifest=$1 WHERE id=$2',[manifest,next.id]);
2760
+ await client.query(`INSERT INTO ota_update_assets(update_id,asset_id,asset_key,role,sort_order)
2761
+ SELECT $1,asset_id,asset_key,role,sort_order FROM ota_update_assets WHERE update_id=$2`,[next.id,old.id]);
2762
+ }
2763
+ await client.query(`UPDATE ota_releases SET status='rolled_back',updated_at=now() WHERE id=$1`,[current.id]);
2764
+ await client.query('COMMIT');
2765
+ await audit(req.auth!.id,'ota.release.rollback','ota-release',rollback.id,req.body?.reason||'Rollback OTA release',{from:current.id,target:target.id});
2766
+ res.json(rollback);
2767
+ }catch(error){await client.query('ROLLBACK');throw error;}finally{client.release();}
2768
+ });
2769
+
2770
+ app.get('/mobile/apps/:appId/metrics', auth, async (req: AuthedRequest,res) => {
2771
+ const appRow=await mobileAppForUser(routeParam(req.params.appId),req.auth!); if(!appRow){res.status(404).json({error:'Mobile app not found or access denied.'});return;}
2772
+ const releaseId=typeof req.query.releaseId==='string'&&req.query.releaseId?ensureUuid(req.query.releaseId,'Release ID'):null;
2773
+ const counts=(await pool.query(
2774
+ `SELECT event_type,count(*)::int count,count(DISTINCT installation_id)::int installations
2775
+ FROM ota_events WHERE app_id=$1 AND ($2::uuid IS NULL OR release_id=$2) GROUP BY event_type ORDER BY event_type`,[appRow.id,releaseId]
2776
+ )).rows;
2777
+ const installs=(await pool.query('SELECT count(*)::int count FROM ota_installations WHERE app_id=$1',[appRow.id])).rows[0]?.count||0;
2778
+ const releases=(await pool.query(
2779
+ `SELECT r.id,r.message,r.status,r.audience_type,r.runtime_version,r.created_at,me.name environment_name,
2780
+ (SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='manifest_served' AND e.installation_id IS NOT NULL)::int manifest_installations,
2781
+ (SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='download_completed' AND e.installation_id IS NOT NULL)::int downloaded_installations,
2782
+ (SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='launch_success' AND e.installation_id IS NOT NULL)::int successful_launches,
2783
+ (SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='update_failed' AND e.installation_id IS NOT NULL)::int failed_installations,
2784
+ (SELECT count(DISTINCT e.installation_id) FROM ota_events e WHERE e.release_id=r.id AND e.event_type='automatic_rollback' AND e.installation_id IS NOT NULL)::int rollback_installations
2785
+ FROM ota_releases r JOIN mobile_environments me ON me.id=r.mobile_environment_id WHERE r.app_id=$1 ORDER BY r.created_at DESC LIMIT 20`,[appRow.id]
2786
+ )).rows;
2787
+ res.json({appId:appRow.id,appName:appRow.app_name,totalInstallations:installs,releaseId,events:counts,releases});
2788
+ });
2789
+
2790
+ app.get('/ota/v1/manifest/:updatePath', async (req,res) => {
2791
+ const appRow=await publicMobileApp(routeParam(req.params.updatePath)); if(!appRow){res.status(404).end();return;}
2792
+ const platform=String(req.headers['expo-platform']||'').toLowerCase();
2793
+ const runtimeVersion=String(req.headers['expo-runtime-version']||'').trim();
2794
+ const channel=String(req.headers['expo-channel-name']||req.headers['x-indraq-mobile-environment']||'').trim().toLowerCase();
2795
+ if(!['android','ios'].includes(platform)||!runtimeVersion||!channel){res.status(400).json({error:'expo-platform, expo-runtime-version and expo-channel-name are required.'});return;}
2796
+ res.setHeader('expo-protocol-version','1');res.setHeader('expo-sfv-version','0');res.setHeader('cache-control','private, max-age=0');
2797
+ const env=(await pool.query('SELECT * FROM mobile_environments WHERE is_active=true AND (lower(ota_channel)=lower($1) OR lower(slug)=lower($1))',[channel])).rows[0];
2798
+ if(!env){res.status(204).end();return;}
2799
+ 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;
2800
+ if(!binding){res.status(204).end();return;}
2801
+ const identity=requestIdentity(req);
2802
+ if(identity.installationId){
2803
+ await pool.query(
2804
+ `INSERT INTO ota_installations(app_id,installation_id,platform,runtime_version,user_id,username,email,phone,last_seen_at)
2805
+ 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,
2806
+ 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()`,
2807
+ [appRow.id,identity.installationId,platform,runtimeVersion,identity.userId,identity.username,identity.email,identity.phone]
2808
+ );
2809
+ }
2810
+ const candidates=(await pool.query(
2811
+ `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
2812
+ 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
2813
+ ORDER BY r.created_at DESC LIMIT 50`,[appRow.id,env.id,runtimeVersion,platform]
2814
+ )).rows;
2815
+ const selected=candidates.find((row:any)=>audienceMatches(row,identity));
2816
+ if(!selected){res.status(204).end();return;}
2817
+ const currentUpdate=String(req.headers['expo-current-update-id']||identity.currentUpdateId||'');
2818
+ if(currentUpdate===selected.update_id){res.status(204).end();return;}
2819
+ const manifestString=JSON.stringify(selected.manifest);
2820
+ res.setHeader('content-type','application/expo+json');
2821
+ if(req.headers['expo-expect-signature']){
2822
+ if(!appRow.encrypted_signing_private_key){res.status(500).json({error:'OTA signing key is unavailable.'});return;}
2823
+ res.setHeader('expo-signature',signExpoManifest(manifestString,appRow.encrypted_signing_private_key));
2824
+ }
2825
+ await pool.query('INSERT INTO ota_events(app_id,release_id,update_id,installation_id,event_type,platform,runtime_version,metadata) VALUES($1,$2,$3,$4,$5,$6,$7,$8)',[appRow.id,selected.id,selected.update_id,identity.installationId||null,'manifest_served',platform,runtimeVersion,{channel}]);
2826
+ res.status(200).send(manifestString);
2827
+ });
2828
+
2829
+ app.get('/ota/v1/assets/:sha256', async (req,res) => {
2830
+ const sha=String(routeParam(req.params.sha256)).toLowerCase(); if(!/^[a-f0-9]{64}$/.test(sha)){res.status(400).end();return;}
2831
+ const asset=(await pool.query('SELECT * FROM ota_assets WHERE sha256=$1',[sha])).rows[0]; if(!asset){res.status(404).end();return;}
2832
+ await ensureOtaBucket();
2833
+ res.setHeader('content-type',asset.content_type);res.setHeader('cache-control','public, max-age=31536000, immutable');res.setHeader('etag',`"${sha}"`);
2834
+ const stream=await getMinio().getObject(minioBucket,asset.object_key);
2835
+ stream.on('error',(error)=>{console.error(error);if(!res.headersSent)res.status(500).end();else res.destroy(error);});
2836
+ stream.pipe(res);
2837
+ });
2838
+
2839
+ app.post('/ota/v1/events/:updatePath', async (req,res) => {
2840
+ const appRow=await publicMobileApp(routeParam(req.params.updatePath)); if(!appRow){res.status(404).end();return;}
2841
+ const eventType=String(req.body?.eventType||'').trim().slice(0,80); if(!eventType){res.status(400).json({error:'eventType is required.'});return;}
2842
+ const installationId=String(req.body?.installationId||'').trim().slice(0,200); if(!installationId){res.status(400).json({error:'installationId is required.'});return;}
2843
+ const currentUpdateId=req.body?.currentUpdateId&&UUID_RE.test(String(req.body.currentUpdateId))?String(req.body.currentUpdateId):null;
2844
+ const targetUpdateId=req.body?.targetUpdateId&&UUID_RE.test(String(req.body.targetUpdateId))?String(req.body.targetUpdateId):null;
2845
+ const eventUpdateId=targetUpdateId||currentUpdateId;
2846
+ let releaseId:string|null=null;
2847
+ if(eventUpdateId){releaseId=(await pool.query('SELECT release_id FROM ota_updates WHERE id=$1',[eventUpdateId])).rows[0]?.release_id||null;}
2848
+ const platform=String(req.body?.platform||'').toLowerCase(); const runtimeVersion=String(req.body?.runtimeVersion||'').trim();
2849
+ await pool.query(
2850
+ `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)
2851
+ 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,
2852
+ 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()`,
2853
+ [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||{}]
2854
+ );
2855
+ 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||{}]);
2856
+ res.status(202).json({ok:true});
2857
+ });
2858
+
2859
+
2245
2860
  app.post('/audit', auth, async (req: AuthedRequest, res) => {
2246
2861
  const reason = requireReason(req, res); if (!reason) return;
2247
2862
  const { action, resourceType, resourceId, metadata = {} } = req.body || {};
@@ -2286,4 +2901,5 @@ const bootstrap = async (): Promise<void> => {
2286
2901
 
2287
2902
  await runMigrations();
2288
2903
  await bootstrap();
2904
+ if (process.env.MINIO_ENDPOINT && process.env.MINIO_ACCESS_KEY && process.env.MINIO_SECRET_KEY) { await ensureOtaBucket(); console.log(`OTA MinIO bucket ready: ${minioBucket}`); }
2289
2905
  app.listen(Number(process.env.PORT || 4010), () => console.log(`IndraQ Cloud API listening on ${process.env.PORT || 4010}`));