indraq_cli 2.7.3 → 2.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +1526 -0
  2. package/cloud-api/README.md +6 -0
  3. package/cloud-api/dist/index.js +246 -53
  4. package/cloud-api/package.json +1 -1
  5. package/cloud-api/sql/013_ota_tester_enrollment.sql +55 -0
  6. package/cloud-api/src/index.ts +187 -44
  7. package/dist/cli/help-content.d.ts.map +1 -1
  8. package/dist/cli/help-content.js +13 -3
  9. package/dist/cli/help-content.js.map +1 -1
  10. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts +6 -1
  11. package/dist/modules/cloud/services/cloud-jenkins.service.d.ts.map +1 -1
  12. package/dist/modules/cloud/services/cloud-jenkins.service.js +62 -5
  13. package/dist/modules/cloud/services/cloud-jenkins.service.js.map +1 -1
  14. package/dist/modules/mobile/commands/build-mobile.command.js +3 -3
  15. package/dist/modules/mobile/commands/build-mobile.command.js.map +1 -1
  16. package/dist/modules/mobile/commands/configure-mobile.command.js +1 -1
  17. package/dist/modules/mobile/commands/configure-mobile.command.js.map +1 -1
  18. package/dist/modules/mobile/commands/mobile-prebuild.command.d.ts.map +1 -1
  19. package/dist/modules/mobile/commands/mobile-prebuild.command.js +20 -14
  20. package/dist/modules/mobile/commands/mobile-prebuild.command.js.map +1 -1
  21. package/dist/modules/mobile/commands/ota.command.d.ts.map +1 -1
  22. package/dist/modules/mobile/commands/ota.command.js +33 -15
  23. package/dist/modules/mobile/commands/ota.command.js.map +1 -1
  24. package/dist/modules/mobile/commands/testers.command.d.ts +6 -0
  25. package/dist/modules/mobile/commands/testers.command.d.ts.map +1 -0
  26. package/dist/modules/mobile/commands/testers.command.js +143 -0
  27. package/dist/modules/mobile/commands/testers.command.js.map +1 -0
  28. package/dist/modules/mobile/index.d.ts.map +1 -1
  29. package/dist/modules/mobile/index.js +23 -1
  30. package/dist/modules/mobile/index.js.map +1 -1
  31. package/dist/modules/mobile/services/mobile-cloud.service.d.ts +61 -0
  32. package/dist/modules/mobile/services/mobile-cloud.service.d.ts.map +1 -1
  33. package/dist/modules/mobile/services/mobile-cloud.service.js +15 -1
  34. package/dist/modules/mobile/services/mobile-cloud.service.js.map +1 -1
  35. package/dist/modules/mobile/services/ota-identity.service.d.ts +20 -0
  36. package/dist/modules/mobile/services/ota-identity.service.d.ts.map +1 -0
  37. package/dist/modules/mobile/services/ota-identity.service.js +169 -0
  38. package/dist/modules/mobile/services/ota-identity.service.js.map +1 -0
  39. package/dist/modules/mobile/services/ota-setup.service.d.ts +1 -0
  40. package/dist/modules/mobile/services/ota-setup.service.d.ts.map +1 -1
  41. package/dist/modules/mobile/services/ota-setup.service.js +268 -24
  42. package/dist/modules/mobile/services/ota-setup.service.js.map +1 -1
  43. package/package.json +16 -4
  44. package/vendor/QR-CODE-APACHE-2.0-LICENSE.txt +222 -0
  45. package/vendor/QR-CODE-MIT-LICENSE.txt +21 -0
  46. package/vendor/QR-CODE-NOTICE.txt +6 -0
  47. package/vendor/QRCode/QR8bitByte.js +22 -0
  48. package/vendor/QRCode/QRBitBuffer.js +38 -0
  49. package/vendor/QRCode/QRErrorCorrectLevel.js +7 -0
  50. package/vendor/QRCode/QRMaskPattern.js +10 -0
  51. package/vendor/QRCode/QRMath.js +44 -0
  52. package/vendor/QRCode/QRMode.js +6 -0
  53. package/vendor/QRCode/QRPolynomial.js +66 -0
  54. package/vendor/QRCode/QRRSBlock.js +298 -0
  55. package/vendor/QRCode/QRUtil.js +272 -0
  56. package/vendor/QRCode/index.js +462 -0
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ensureOtaIdentityConfig = exports.discoverSavedProfileKeys = exports.saveOtaIdentityConfig = exports.readOtaIdentityConfig = exports.validateOtaIdentityConfig = void 0;
7
+ /**
8
+ * One-time, declarative OTA identity adapter. It deliberately does not scrape
9
+ * arbitrary device storage, intercept fetch/login calls, or store credentials.
10
+ * Developers opt in to the saved *profile* key used by their authentication app.
11
+ */
12
+ const chalk_1 = __importDefault(require("chalk"));
13
+ const inquirer_1 = __importDefault(require("inquirer"));
14
+ const node_fs_1 = require("node:fs");
15
+ const node_path_1 = require("node:path");
16
+ const configPath = (root) => (0, node_path_1.join)(root, 'indraq-ota', 'identity.json');
17
+ const keyPattern = /^[^\r\n\x00-\x1f]{1,200}$/;
18
+ const fieldPattern = /^(?:[A-Za-z_$][\w$]*|\d+)(?:\.(?:[A-Za-z_$][\w$]*|\d+))*$/;
19
+ const fields = ['userId', 'username', 'email', 'phone'];
20
+ const validateOtaIdentityConfig = (value) => {
21
+ if (!value || typeof value !== 'object')
22
+ throw new Error('Invalid IndraQ OTA identity configuration.');
23
+ const config = value;
24
+ if (config.version !== 1 || !['installation', 'async-storage', 'secure-store'].includes(String(config.source))) {
25
+ throw new Error('Unsupported OTA identity configuration.');
26
+ }
27
+ if (config.source !== 'installation' && (!config.storageKey || !keyPattern.test(config.storageKey))) {
28
+ throw new Error('OTA identity storageKey must be a nonempty saved profile key. Do not use an auth token key.');
29
+ }
30
+ if (config.paths !== undefined) {
31
+ if (!config.paths || typeof config.paths !== 'object' || Array.isArray(config.paths))
32
+ throw new Error('OTA identity paths must be an object.');
33
+ for (const [field, path] of Object.entries(config.paths)) {
34
+ if (!fields.includes(field) || typeof path !== 'string' || (path && !fieldPattern.test(path))) {
35
+ throw new Error(`Invalid OTA identity field mapping: ${field}`);
36
+ }
37
+ }
38
+ }
39
+ return { version: 1, source: config.source, ...(config.source === 'installation' ? {} : { storageKey: config.storageKey, paths: config.paths || {} }) };
40
+ };
41
+ exports.validateOtaIdentityConfig = validateOtaIdentityConfig;
42
+ const readOtaIdentityConfig = (root) => {
43
+ const path = configPath(root);
44
+ if (!(0, node_fs_1.existsSync)(path))
45
+ return null;
46
+ try {
47
+ return (0, exports.validateOtaIdentityConfig)(JSON.parse((0, node_fs_1.readFileSync)(path, 'utf8')));
48
+ }
49
+ catch (e) {
50
+ throw new Error(`Invalid ${path}: ${e instanceof Error ? e.message : String(e)}`);
51
+ }
52
+ };
53
+ exports.readOtaIdentityConfig = readOtaIdentityConfig;
54
+ const saveOtaIdentityConfig = (root, config) => {
55
+ const safe = (0, exports.validateOtaIdentityConfig)(config);
56
+ (0, node_fs_1.mkdirSync)((0, node_path_1.join)(root, 'indraq-ota'), { recursive: true });
57
+ (0, node_fs_1.writeFileSync)(configPath(root), `${JSON.stringify(safe, null, 2)}\n`, 'utf8');
58
+ };
59
+ exports.saveOtaIdentityConfig = saveOtaIdentityConfig;
60
+ /** Suggest only literal profile/session keys visible in source; never inspect their values. */
61
+ const discoverSavedProfileKeys = (root) => {
62
+ const results = [];
63
+ const visited = new Set();
64
+ const skip = new Set(['node_modules', '.git', '.expo', 'android', 'ios', '.next', 'build', 'dist', '.indraq', 'indraq-ota']);
65
+ let count = 0;
66
+ const walk = (directory, relative, depth) => {
67
+ if (depth > 6 || count > 400 || !(0, node_fs_1.existsSync)(directory))
68
+ return;
69
+ for (const entry of (0, node_fs_1.readdirSync)(directory, { withFileTypes: true })) {
70
+ if (count > 400)
71
+ break;
72
+ const path = (0, node_path_1.join)(directory, entry.name);
73
+ const file = relative ? `${relative}/${entry.name}` : entry.name;
74
+ if (entry.isDirectory()) {
75
+ if (!skip.has(entry.name))
76
+ walk(path, file, depth + 1);
77
+ continue;
78
+ }
79
+ if (!entry.isFile() || !/\.[cm]?[jt]sx?$/.test(entry.name))
80
+ continue;
81
+ count++;
82
+ const content = (0, node_fs_1.readFileSync)(path, 'utf8');
83
+ const pattern = /\b(AsyncStorage\.setItem|SecureStore\.setItemAsync)\s*\(\s*(['"`])([^'"`\r\n]+)\2/g;
84
+ let match;
85
+ while ((match = pattern.exec(content)) !== null) {
86
+ const storageKey = match[3] || '';
87
+ if (!/user|profile|session|account|auth(?:_?data)?$/i.test(storageKey) || /token|password|secret|jwt|credential|refresh|access.?key/i.test(storageKey))
88
+ continue;
89
+ const source = match[1].startsWith('Secure') ? 'secure-store' : 'async-storage';
90
+ const id = `${source}:${storageKey}`;
91
+ if (!visited.has(id)) {
92
+ visited.add(id);
93
+ results.push({ source, storageKey, file });
94
+ }
95
+ }
96
+ }
97
+ };
98
+ for (const dir of ['app', 'src', 'context', 'contexts', 'hooks', 'services', 'utils'])
99
+ walk((0, node_path_1.join)(root, dir), dir, 0);
100
+ for (const name of ['App.js', 'App.jsx', 'App.ts', 'App.tsx', 'index.js', 'index.ts']) {
101
+ const path = (0, node_path_1.join)(root, name);
102
+ if ((0, node_fs_1.existsSync)(path)) {
103
+ const text = (0, node_fs_1.readFileSync)(path, 'utf8');
104
+ const pattern = /\b(AsyncStorage\.setItem|SecureStore\.setItemAsync)\s*\(\s*(['"`])([^'"`\r\n]+)\2/g;
105
+ let match;
106
+ while ((match = pattern.exec(text)) !== null) {
107
+ const storageKey = match[3] || '';
108
+ if (!/user|profile|session|account|auth(?:_?data)?$/i.test(storageKey) || /token|password|secret|jwt|credential|refresh|access.?key/i.test(storageKey))
109
+ continue;
110
+ const source = match[1].startsWith('Secure') ? 'secure-store' : 'async-storage';
111
+ const id = `${source}:${storageKey}`;
112
+ if (!visited.has(id)) {
113
+ visited.add(id);
114
+ results.push({ source, storageKey, file: (0, node_path_1.basename)(name) });
115
+ }
116
+ }
117
+ }
118
+ }
119
+ return results.slice(0, 20);
120
+ };
121
+ exports.discoverSavedProfileKeys = discoverSavedProfileKeys;
122
+ const ensureOtaIdentityConfig = async (root, unattended = false, force = false) => {
123
+ const prior = (0, exports.readOtaIdentityConfig)(root);
124
+ if (prior && !force) {
125
+ console.log(chalk_1.default.green(`✓ OTA identity adapter: ${prior.source}${prior.storageKey ? ` (${prior.storageKey})` : ''} (existing configuration)`));
126
+ return prior;
127
+ }
128
+ if (unattended || !process.stdin.isTTY) {
129
+ const anonymous = { version: 1, source: 'installation' };
130
+ (0, exports.saveOtaIdentityConfig)(root, anonymous);
131
+ console.log(chalk_1.default.green('✓ OTA identity: automatic per-installation targeting (no app login integration required).'));
132
+ return anonymous;
133
+ }
134
+ const candidates = (0, exports.discoverSavedProfileKeys)(root);
135
+ const choices = [
136
+ ...candidates.map((c) => ({ name: `Detected saved profile: ${c.source} / ${c.storageKey} (${c.file})`, value: `${c.source}:${c.storageKey}` })),
137
+ { name: 'My app stores a user profile in AsyncStorage (enter its key)', value: 'async-storage' },
138
+ { name: 'My app stores a user profile in Expo SecureStore (enter its key)', value: 'secure-store' },
139
+ { name: 'Installation-only OTA (no automatic email/phone/user targeting)', value: 'installation' }
140
+ ];
141
+ console.log(chalk_1.default.blue('\n👤 One-time OTA audience identity setup'));
142
+ console.log(chalk_1.default.gray('Choose where the app saves the signed-in USER PROFILE, not its password or auth token. No login-screen imports are needed.'));
143
+ const { choice } = await inquirer_1.default.prompt([{ type: 'list', name: 'choice', message: 'Where is the signed-in user profile persisted?', choices, default: candidates.length ? 0 : 'installation' }]);
144
+ if (choice === 'installation') {
145
+ const config = { version: 1, source: 'installation' };
146
+ (0, exports.saveOtaIdentityConfig)(root, config);
147
+ console.log(chalk_1.default.yellow('⚠ User-based targeting disabled. Reconfigure indraq-ota/identity.json before enabling email/phone targeting.'));
148
+ return config;
149
+ }
150
+ const source = choice.startsWith('secure-store') ? 'secure-store' : 'async-storage';
151
+ const fromCandidate = candidates.find((c) => `${c.source}:${c.storageKey}` === choice);
152
+ const storageKey = fromCandidate?.storageKey || (await inquirer_1.default.prompt([{ type: 'input', name: 'key', message: 'Saved user profile storage key:', validate: (v) => keyPattern.test(v) && !/token|password|secret|jwt/i.test(v) || 'Use the profile object key, not a token/secret key.' }])).key;
153
+ const { mapping } = await inquirer_1.default.prompt([{ type: 'confirm', name: 'mapping', message: 'Use common user/profile field names automatically? (email, phone, id, username)', default: true }]);
154
+ const paths = {};
155
+ if (!mapping) {
156
+ for (const field of fields) {
157
+ const answer = await inquirer_1.default.prompt([{ type: 'input', name: 'value', message: `JSON property path for ${field} (e.g., user.email; blank = auto-detect):`, validate: (v) => !v || fieldPattern.test(v) || 'Use a dot-separated JSON property path.' }]);
158
+ if (answer.value.trim())
159
+ paths[field] = answer.value.trim();
160
+ }
161
+ }
162
+ const config = { version: 1, source, storageKey, paths };
163
+ (0, exports.saveOtaIdentityConfig)(root, config);
164
+ console.log(chalk_1.default.green(`✓ Saved OTA audience identity configuration: ${source} / ${storageKey}`));
165
+ console.log(chalk_1.default.gray('Email, phone, username and user ID are resolved at app launch and refreshed while the app is active.'));
166
+ return config;
167
+ };
168
+ exports.ensureOtaIdentityConfig = ensureOtaIdentityConfig;
169
+ //# sourceMappingURL=ota-identity.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ota-identity.service.js","sourceRoot":"","sources":["../../../../src/modules/mobile/services/ota-identity.service.ts"],"names":[],"mappings":";;;;;;AAAA;;;;GAIG;AACH,kDAA0B;AAC1B,wDAAgC;AAChC,qCAA0F;AAC1F,yCAA2C;AAW3C,MAAM,UAAU,GAAG,CAAC,IAAY,EAAU,EAAE,CAAC,IAAA,gBAAI,EAAC,IAAI,EAAE,YAAY,EAAE,eAAe,CAAC,CAAC;AACvF,MAAM,UAAU,GAAG,2BAA2B,CAAC;AAC/C,MAAM,YAAY,GAAG,2DAA2D,CAAC;AACjF,MAAM,MAAM,GAAuB,CAAC,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAErE,MAAM,yBAAyB,GAAG,CAAC,KAAc,EAAqB,EAAE;IAC7E,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IACvG,MAAM,MAAM,GAAG,KAAmC,CAAC;IACnD,IAAI,MAAM,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,cAAc,EAAE,eAAe,EAAE,cAAc,CAAC,CAAC,QAAQ,CAAC,MAAM,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terial {
7
7
  export declare const ensureOtaDependencies: (root: string, projectType: MobileProjectType) => void;
8
8
  export declare const generateSigningMaterial: (root: string, appName: string) => SigningMaterial;
9
9
  export declare const ensureCertificateFile: (root: string, certificate: string) => string;
10
+ export declare const ensureOtaEnrollmentScheme: (root: string, projectType: MobileProjectType) => string | null;
10
11
  export declare const configureExpoAppJson: (root: string, updateUrl: string, binding: MobileOtaEnvironmentBinding) => {
11
12
  androidPackage?: string;
12
13
  iosBundleIdentifier?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"ota-setup.service.d.ts","sourceRoot":"","sources":["../../../../src/modules/mobile/services/ota-setup.service.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAyB,2BAA2B,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAGnI,MAAM,WAAW,eAAe;IAAG,UAAU,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,eAAe,EAAE,MAAM,CAAC;CAAE;AAUtG,eAAO,MAAM,qBAAqB,GAAI,MAAK,MAAM,EAAE,aAAY,iBAAiB,KAAG,IAmBlF,CAAC;AAEF,eAAO,MAAM,uBAAuB,GAAI,MAAK,MAAM,EAAE,SAAQ,MAAM,KAAG,eAcrE,CAAC;AAEF,eAAO,MAAM,qBAAqB,GAAI,MAAK,MAAM,EAAC,aAAY,MAAM,KAAG,MAEtE,CAAC;AAgBF,eAAO,MAAM,oBAAoB,GAAI,MAAK,MAAM,EAAE,WAAU,MAAM,EAAE,SAAQ,2BAA2B,KAAG;IAAC,cAAc,CAAC,EAAC,MAAM,CAAC;IAAA,mBAAmB,CAAC,EAAC,MAAM,CAAA;CAQ5J,CAAC;AAeF,eAAO,MAAM,wBAAwB,GAAI,MAAK,MAAM,EAAC,WAAU,MAAM,EAAC,SAAQ,2BAA2B,EAAC,aAAY,MAAM,KAAG,IAmC9H,CAAC;AAEF,eAAO,MAAM,iBAAiB,GAAI,MAAK,MAAM,EAAC,aAAY,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F,eAAO,MAAM,iBAAiB,GAAI,MAAK,MAAM,EAAC,aAAY,iBAAiB,EAAC,WAAU,MAAM,EAAC,SAAQ,2BAA2B,KAAG,IA+QlI,CAAC;AA4DF,eAAO,MAAM,0BAA0B,GAAI,MAAK,MAAM,KAAG,MAQxD,CAAC;AAEF,eAAO,MAAM,4BAA4B,GAAI,MAAK,MAAM,EAAC,QAAO,YAAY,EAAC,SAAQ,2BAA2B,EAAC,WAAU,MAAM,EAAC,aAAY,MAAM,KAAG,IAWtJ,CAAC"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.applyOtaEnvironmentToProject = exports.calculateNativeFingerprint = exports.writeOtaBootstrap = exports.configureBareNativeFiles = exports.configureExpoAppJson = exports.ensureCertificateFile = exports.generateSigningMaterial = exports.ensureOtaDependencies = void 0;
3
+ exports.applyOtaEnvironmentToProject = exports.calculateNativeFingerprint = exports.writeOtaBootstrap = exports.configureBareNativeFiles = exports.configureExpoAppJson = exports.ensureOtaEnrollmentScheme = exports.ensureCertificateFile = exports.generateSigningMaterial = exports.ensureOtaDependencies = void 0;
4
4
  const node_crypto_1 = require("node:crypto");
5
5
  const node_fs_1 = require("node:fs");
6
6
  const node_path_1 = require("node:path");
@@ -8,6 +8,7 @@ const run_npx_1 = require("../../../shared/process/run-npx");
8
8
  const expo_app_json_service_1 = require("./expo-app-json.service");
9
9
  const node_os_1 = require("node:os");
10
10
  const mobile_config_1 = require("../config/mobile-config");
11
+ const ota_identity_service_1 = require("./ota-identity.service");
11
12
  const run = (cwd, command, args) => {
12
13
  if (command !== 'npx')
13
14
  throw new Error(`Unsupported OTA setup command: ${command}`);
@@ -87,6 +88,25 @@ const otaRequestHeaders = (binding) => ({
87
88
  'x-indraq-email': '',
88
89
  'x-indraq-phone': ''
89
90
  });
91
+ const ensureOtaEnrollmentScheme = (root, projectType) => {
92
+ if (projectType !== 'expo')
93
+ return null;
94
+ const file = appJsonPath(root);
95
+ const doc = (0, node_fs_1.existsSync)(file) ? (0, expo_app_json_service_1.readExpoAppJson)(file).doc : { expo: {} };
96
+ const expo = doc.expo || doc;
97
+ if (!expo.scheme) {
98
+ const slug = String(expo.slug || expo.name || 'indraq-mobile').toLowerCase().replace(/[^a-z0-9+.-]/g, '-').replace(/^[^a-z]+/, '').slice(0, 35);
99
+ expo.scheme = slug.length >= 2 ? slug : 'indraq-mobile';
100
+ doc.expo = expo;
101
+ (0, expo_app_json_service_1.writeExpoAppJson)(file, doc);
102
+ console.log('Configured Expo deep-link scheme for one-time QR tester enrollment. A new native build is required.');
103
+ }
104
+ const scheme = String(expo.scheme).trim().toLowerCase();
105
+ if (!/^[a-z][a-z0-9+.-]{1,39}$/.test(scheme))
106
+ throw new Error('Expo app scheme must contain a valid URI scheme for tester QR enrollment.');
107
+ return scheme;
108
+ };
109
+ exports.ensureOtaEnrollmentScheme = ensureOtaEnrollmentScheme;
90
110
  const configureExpoAppJson = (root, updateUrl, binding) => {
91
111
  const path = appJsonPath(root);
92
112
  let doc = { expo: { name: readPackage(root).name || 'IndraQ Mobile' } };
@@ -97,6 +117,12 @@ const configureExpoAppJson = (root, updateUrl, binding) => {
97
117
  }
98
118
  const expo = doc.expo || {};
99
119
  expo.runtimeVersion = binding.runtimeVersion;
120
+ // Enrolled tester QR codes require a native deep-link scheme. Configure it
121
+ // automatically on first prebuild; no developer changes to login screens.
122
+ if (!expo.scheme) {
123
+ const slug = String(expo.slug || expo.name || 'indraq-mobile').toLowerCase().replace(/[^a-z0-9+.-]/g, '-').replace(/^[^a-z]+/, '').slice(0, 35);
124
+ expo.scheme = slug.length >= 2 ? slug : 'indraq-mobile';
125
+ }
100
126
  expo.updates = { ...(expo.updates || {}), enabled: true, url: updateUrl, checkAutomatically: 'NEVER', fallbackToCacheTimeout: 0, codeSigningCertificate: './indraq-ota/certificate.pem', codeSigningMetadata: { keyid: 'main', alg: 'rsa-v1_5-sha256' }, requestHeaders: { ...(expo.updates?.requestHeaders || {}), ...otaRequestHeaders(binding) } };
101
127
  doc.expo = expo;
102
128
  (0, expo_app_json_service_1.writeExpoAppJson)(path, doc);
@@ -160,67 +186,285 @@ const configureBareNativeFiles = (root, updateUrl, binding, certificate) => {
160
186
  }
161
187
  };
162
188
  exports.configureBareNativeFiles = configureBareNativeFiles;
189
+ /** One-time generated auth-profile adapter; never imports into app login screens. */
190
+ const writeOtaIdentityRuntime = (root, config) => {
191
+ const dir = (0, node_path_1.join)(root, 'indraq-ota');
192
+ (0, node_fs_1.mkdirSync)(dir, { recursive: true });
193
+ const secureImport = config.source === 'secure-store' ? "import * as SecureStore from 'expo-secure-store';\n" : '';
194
+ const getStored = config.source === 'secure-store' ? 'SecureStore.getItemAsync(CONFIG.storageKey)' : 'AsyncStorage.getItem(CONFIG.storageKey)';
195
+ const source = `// Generated by IndraQ CLI. Only reads the explicitly configured saved profile key.
196
+ import AsyncStorage from '@react-native-async-storage/async-storage';
197
+ ${secureImport}const CONFIG=${JSON.stringify(config)};
198
+ export const indraqIdentitySource=CONFIG.source;
199
+ const common={
200
+ userId:['userId','user_id','uid','id','user.id','user.userId','profile.id','profile.userId','data.user.id','auth.user.id','state.user.id'],
201
+ username:['username','userName','handle','name','user.username','user.name','profile.username','data.user.username','auth.user.username'],
202
+ email:['email','emailAddress','user.email','profile.email','data.user.email','auth.user.email','state.user.email'],
203
+ phone:['phone','phoneNumber','mobile','mobileNumber','contactNumber','user.phone','user.phoneNumber','user.mobile','profile.phone','data.user.phone','auth.user.phone']
204
+ };
205
+ const getPath=(record,path)=>{let current=record;for(const key of path.split('.')){if(!current||typeof current!=='object'||!Object.prototype.hasOwnProperty.call(current,key))return undefined;current=current[key];}return current;};
206
+ const text=(value)=>typeof value==='string'||typeof value==='number'?String(value).trim().slice(0,320):'';
207
+ export async function readIndraqOtaProfile(){
208
+ if(CONFIG.source==='installation')return {};
209
+ try{
210
+ const raw=await ${getStored};
211
+ if(!raw)return {};
212
+ const record=JSON.parse(raw);
213
+ if(!record||typeof record!=='object'||Array.isArray(record))return {};
214
+ const identity={};
215
+ for(const field of Object.keys(common)){
216
+ const configured=CONFIG.paths&&CONFIG.paths[field];
217
+ const candidates=configured?[configured]:common[field];
218
+ for(const path of candidates){const value=text(getPath(record,path));if(value){identity[field]=field==='email'?value.toLowerCase():value;break;}}
219
+ }
220
+ return identity;
221
+ }catch{return {};}
222
+ }
223
+ `;
224
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'identity-runtime.js'), source, 'utf8');
225
+ };
163
226
  const writeOtaBootstrap = (root, projectType, updateUrl, binding) => {
164
227
  const eventUrl = updateUrl.replace('/ota/v1/manifest/', '/ota/v1/events/');
165
228
  const dir = (0, node_path_1.join)(root, 'indraq-ota');
166
229
  (0, node_fs_1.mkdirSync)(dir, { recursive: true });
230
+ const identityConfig = (0, ota_identity_service_1.readOtaIdentityConfig)(root) || { version: 1, source: 'installation' };
231
+ writeOtaIdentityRuntime(root, identityConfig);
167
232
  const source = `// Generated by IndraQ CLI. Safe to commit.
168
233
  import * as Updates from 'expo-updates';
169
234
  import * as SplashScreen from 'expo-splash-screen';
170
235
  import AsyncStorage from '@react-native-async-storage/async-storage';
171
- import { Platform } from 'react-native';
236
+ import { Platform, AppState, Linking } from 'react-native';
237
+ import { readIndraqOtaProfile, indraqIdentitySource } from './identity-runtime.js';
172
238
 
173
239
  const ID_KEY='@indraq/ota/installation';
174
240
  const USER_KEY='@indraq/ota/identity';
241
+ // Scoped to both the native runtime and update channel; never reuse an update from another binary.
242
+ const PENDING_KEY='@indraq/ota/pending/'+String(Updates.runtimeVersion||'unknown')+'/'+${JSON.stringify(binding.otaChannel)};
175
243
  const EVENT_URL=${JSON.stringify(eventUrl)};
244
+ const ENROLLMENT_URL=${JSON.stringify(new URL('/ota/v1/enroll/redeem', updateUrl).toString())};
176
245
  const STATIC_HEADERS=${JSON.stringify({ 'expo-channel-name': binding.otaChannel, 'x-indraq-mobile-environment': binding.slug })};
177
246
  const CHECK_TIMEOUT_MS=10000;
178
247
  const DOWNLOAD_TIMEOUT_MS=60000;
179
248
 
180
- // Keep the native splash visible while the startup-only update decision is made.
181
- // The user therefore never reaches checkout/navigation and gets reloaded mid-flow.
249
+ // Only the generated entrypoint owns OTA startup. React screens don't need imports.
182
250
  void SplashScreen.preventAutoHideAsync().catch(()=>{});
183
251
  const randomId=()=> 'ins_'+Date.now().toString(36)+'_'+Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2);
184
252
  const withTimeout=(promise,ms,label)=>new Promise((resolve,reject)=>{const timer=setTimeout(()=>reject(new Error('IndraQ OTA '+label+' timed out')),ms);Promise.resolve(promise).then((value)=>{clearTimeout(timer);resolve(value);},(error)=>{clearTimeout(timer);reject(error);});});
185
253
  async function installationId(){let id=await AsyncStorage.getItem(ID_KEY);if(!id){id=randomId();await AsyncStorage.setItem(ID_KEY,id);}return id;}
186
254
  export async function identifyIndraqOTA(identity={}){await AsyncStorage.setItem(USER_KEY,JSON.stringify(identity||{}));}
255
+ async function readIdentity(){
256
+ if(indraqIdentitySource!=='installation')return readIndraqOtaProfile();
257
+ try{return JSON.parse((await AsyncStorage.getItem(USER_KEY))||'{}');}catch{return {};}
258
+ }
259
+ let currentIdentitySignature='';
260
+ let refreshInProgress=false;
261
+ async function refreshIdentity(id){
262
+ if(refreshInProgress)return;
263
+ refreshInProgress=true;
264
+ try{
265
+ const identity=await readIdentity();
266
+ const signature=JSON.stringify(identity);
267
+ if(currentIdentitySignature!==signature){
268
+ currentIdentitySignature=signature;
269
+ await report('identity_synced',id,identity,{source:indraqIdentitySource});
270
+ if(typeof Updates.setExtraParamAsync==='function'){
271
+ for(const [key,value] of Object.entries({'indraq-user-id':identity.userId||'', 'indraq-username':identity.username||'', 'indraq-email':identity.email||'', 'indraq-phone':identity.phone||''})){
272
+ try{await Updates.setExtraParamAsync(key,String(value)||null);}catch{}
273
+ }
274
+ }
275
+ }
276
+ }finally{refreshInProgress=false;}
277
+ }
278
+ function installIdentityRefresh(id){
279
+ if(indraqIdentitySource==='installation')return;
280
+ const refresh=()=>{if(AppState.currentState==='active')void refreshIdentity(id).catch(()=>{});};
281
+ AppState.addEventListener('change',(state)=>{if(state==='active')refresh();});
282
+ setInterval(refresh,20000);
283
+ }
187
284
  async function report(eventType,id,identity,extra={}){try{await fetch(EVENT_URL,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({eventType,installationId:id,platform:Platform.OS,runtimeVersion:Updates.runtimeVersion,currentUpdateId:Updates.updateId||null,targetUpdateId:extra.availableUpdateId||null,userId:identity.userId||'',username:identity.username||'',email:identity.email||'',phone:identity.phone||'',metadata:extra})});}catch{}}
285
+ // Secure tester enrollment: opening the generated QR link is enough.
286
+ // No login-screen imports or app-specific account identifiers are required.
287
+ let lastEnrollmentToken='';
288
+ let enrollmentPromise=null;
289
+ const tokenFromUrl=(url)=>{
290
+ try{
291
+ const parsed=new URL(String(url));
292
+ if(parsed.hostname!=='indraq-enroll' && !parsed.pathname.replace(/^\\/+/, '').startsWith('indraq-enroll'))return null;
293
+ const token=parsed.searchParams.get('token')||'';
294
+ return /^[A-Za-z0-9_-]{43}$/.test(token)?token:null;
295
+ }catch{return null;}
296
+ };
297
+ export async function redeemIndraqEnrollment(token){
298
+ if(!/^[A-Za-z0-9_-]{43}$/.test(String(token||'')))throw new Error('Invalid device enrollment code.');
299
+ if(token===lastEnrollmentToken&&enrollmentPromise)return enrollmentPromise;
300
+ lastEnrollmentToken=token;
301
+ enrollmentPromise=(async()=>{
302
+ const id=await installationId();
303
+ const identity=await readIdentity();
304
+ await report('enrollment_opened',id,identity);
305
+ const response=await withTimeout(fetch(ENROLLMENT_URL,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({token,installationId:id})}),10000,'enrollment');
306
+ const body=await response.json().catch(()=>({}));
307
+ if(!response.ok||!body.ok)throw new Error(String(body.error||'Enrollment failed; request a new QR code.'));
308
+ await report('enrollment_confirmed',id,identity,{groupId:body.groupId||null});
309
+ return {label:body.label||'',appName:body.appName||''};
310
+ })();
311
+ try{return await enrollmentPromise;}catch(error){lastEnrollmentToken='';enrollmentPromise=null;throw error;}
312
+ }
313
+ async function installEnrollmentLinkListener(){
314
+ if(!Linking || typeof Linking.addEventListener!=='function' || typeof Linking.getInitialURL!=='function')return false;
315
+ const handle=(url)=>{const token=tokenFromUrl(url);if(token)void redeemIndraqEnrollment(token).catch((error)=>{console.warn('IndraQ OTA device enrollment failed:',String(error?.message||error).slice(0,160));});};
316
+ Linking.addEventListener('url',({url})=>handle(url));
317
+ const initialUrl=await Linking.getInitialURL().catch(()=>null);
318
+ const token=initialUrl?tokenFromUrl(initialUrl):null;
319
+ if(token){
320
+ try{await redeemIndraqEnrollment(token);}catch(error){console.warn('IndraQ OTA device enrollment failed:',String(error?.message||error).slice(0,160));}
321
+ return true; // QR cold-start should not be interrupted by OTA reload.
322
+ }
323
+ return false;
324
+ }
188
325
  async function revealApp(){try{await SplashScreen.hideAsync();}catch{}}
326
+ async function getPending(){
327
+ try{const value=JSON.parse((await AsyncStorage.getItem(PENDING_KEY))||'null');return value&&typeof value.updateId==='string'&&/^[a-f0-9-]{36}$/i.test(value.updateId)?value:null;}catch{return null;}
328
+ }
329
+ async function putPending(state){await AsyncStorage.setItem(PENDING_KEY,JSON.stringify(state));}
330
+ const safeErrorText=(value)=>String(value||'').slice(0,500).replace(/Bearer\\s+[^\\s]+/gi,'Bearer [redacted]').replace(/https?:\\/\\/[^\\s]+/gi,'[url]').replace(/[A-Za-z0-9_\\-]{40,}/g,'[long-token]');
331
+ const errorDetail=(error)=>({message:safeErrorText(error?.message||error),code:error?.code||null});
332
+ async function nativeLogs(){
333
+ try{if(typeof Updates.readLogEntriesAsync!=='function')return [];
334
+ const logs=await Updates.readLogEntriesAsync(90000);
335
+ return logs.slice(-12).map(({code,level,message,updateId})=>({code,level,message:safeErrorText(message),updateId:updateId||null}));
336
+ }catch{return [];}
337
+ }
338
+ // A downloaded OTA must be activated only after the native React runtime is ready.
339
+ // Native rejection is NOT recoverable by repeatedly downloading the same bundle.
340
+ async function activatePending(id,identity,pending){
341
+ if(pending.activationAttempts>=1){
342
+ await report('activation_pending',id,identity,{availableUpdateId:pending.updateId,reason:'Reload already attempted; waiting for native cold-start selection',lastError:pending.lastError||null});
343
+ await revealApp();
344
+ return;
345
+ }
346
+ pending.activationAttempts=1;
347
+ await putPending(pending); // Persist attempt BEFORE reload (reload may terminate JS).
348
+ await report('activation_started',id,identity,{availableUpdateId:pending.updateId});
349
+ // Let the app's entrypoint finish registration before asking native to reload.
350
+ await revealApp();
351
+ await new Promise((resolve)=>setTimeout(resolve,750));
352
+ try{
353
+ await Updates.reloadAsync();
354
+ // No success event here. Only a subsequent JS launch matching updateId is proof.
355
+ }catch(error){
356
+ const detail=errorDetail(error);
357
+ pending.lastError=detail.message;
358
+ await putPending(pending);
359
+ await report('activation_failed',id,identity,{availableUpdateId:pending.updateId,...detail,nativeLogs:await nativeLogs()});
360
+ }
361
+ }
362
+ let started=false;
189
363
  export async function runIndraqOTAStartup(){
364
+ if(started)return;
365
+ started=true;
190
366
  if(__DEV__){await revealApp();return;}
191
- const id=await installationId();let identity={};
192
- try{identity=JSON.parse((await AsyncStorage.getItem(USER_KEY))||'{}');}catch{}
193
- const headers={...STATIC_HEADERS,'x-indraq-installation-id':id,'x-indraq-current-update-id':Updates.updateId?String(Updates.updateId):'','x-indraq-user-id':identity.userId?String(identity.userId):'','x-indraq-username':identity.username?String(identity.username):'','x-indraq-email':identity.email?String(identity.email):'','x-indraq-phone':identity.phone?String(identity.phone):''};
367
+ let id='';let identity={};let targetId=null;
194
368
  try{
369
+ id=await installationId();
370
+ const openedByEnrollment=await installEnrollmentLinkListener();
371
+ identity=await readIdentity();
372
+ if(openedByEnrollment){await revealApp();return;}
373
+ currentIdentitySignature=JSON.stringify(identity);
374
+ installIdentityRefresh(id);
375
+ const headers={...STATIC_HEADERS,'x-indraq-installation-id':id,'x-indraq-current-update-id':Updates.updateId?String(Updates.updateId):'','x-indraq-user-id':identity.userId?String(identity.userId):'','x-indraq-username':identity.username?String(identity.username):'','x-indraq-email':identity.email?String(identity.email):'','x-indraq-phone':identity.phone?String(identity.phone):''};
195
376
  const extraParams={'indraq-installation-id':id,'indraq-current-update-id':Updates.updateId?String(Updates.updateId):'','indraq-user-id':identity.userId?String(identity.userId):'','indraq-username':identity.username?String(identity.username):'','indraq-email':identity.email?String(identity.email):'','indraq-phone':identity.phone?String(identity.phone):''};
196
- if(typeof Updates.setExtraParamAsync==='function'){for(const [key,value] of Object.entries(extraParams)) await Updates.setExtraParamAsync(key,value||null);}
197
- // SDKs that expose the request-header override can additionally carry the same
198
- // values as plain headers; the server accepts either representation.
199
- if(typeof Updates.setUpdateRequestHeadersOverride==='function') Updates.setUpdateRequestHeadersOverride(headers);
200
- await report(Updates.isEmergencyLaunch?'automatic_rollback':'launch_started',id,identity,Updates.isEmergencyLaunch?{emergencyLaunchReason:Updates.emergencyLaunchReason||''}:{});
377
+ if(typeof Updates.setExtraParamAsync==='function'){for(const [key,value] of Object.entries(extraParams))await Updates.setExtraParamAsync(key,value||null);}
378
+ if(typeof Updates.setUpdateRequestHeadersOverride==='function')Updates.setUpdateRequestHeadersOverride(headers);
379
+
380
+ let pending=await getPending();
381
+ if(pending && Updates.updateId===pending.updateId && !Updates.isEmergencyLaunch){
382
+ await AsyncStorage.removeItem(PENDING_KEY);
383
+ await report('update_applied',id,identity,{availableUpdateId:pending.updateId,isEmbeddedLaunch:!!Updates.isEmbeddedLaunch});
384
+ pending=null;
385
+ }
386
+ // Emergency launch != a rollback of a downloaded release. Record and do not
387
+ // immediately fetch/reload the same update into an already failing native runtime.
388
+ if(Updates.isEmergencyLaunch){
389
+ await report('emergency_launch',id,identity,{emergencyLaunchReason:Updates.emergencyLaunchReason||'',isEmbeddedLaunch:!!Updates.isEmbeddedLaunch,nativeLogs:await nativeLogs()});
390
+ await revealApp();
391
+ return;
392
+ }
393
+ await report('launch_started',id,identity,{isEmbeddedLaunch:!!Updates.isEmbeddedLaunch});
394
+ // If download finished but reload was never attempted (process was killed),
395
+ // activate the already cached OTA, even without network access.
396
+ if(pending && Updates.updateId!==pending.updateId && pending.activationAttempts===0){
397
+ await activatePending(id,identity,pending);
398
+ return;
399
+ }
400
+ // Otherwise check the server for a NEWER repair release on each launch.
401
+ // Metadata checks are cheap; the SAME downloaded update will not be fetched again.
201
402
  const check=await withTimeout(Updates.checkForUpdateAsync(),CHECK_TIMEOUT_MS,'check');
202
403
  if(check.isAvailable){
203
- await report('download_started',id,identity,{availableUpdateId:check.manifest?.id||null});
204
- await withTimeout(Updates.fetchUpdateAsync(),DOWNLOAD_TIMEOUT_MS,'download');
205
- await report('download_completed',id,identity,{availableUpdateId:check.manifest?.id||null});
206
- // This is the only forced reload path and it happens while the splash screen
207
- // still owns startup, before the user can enter a workflow.
208
- await Updates.reloadAsync();
209
- return;
404
+ const availableId=String(check.manifest?.id||'');
405
+ if(!/^[a-f0-9-]{36}$/i.test(availableId))throw new Error('OTA manifest is missing a valid update ID.');
406
+ targetId=availableId;
407
+ if(Updates.updateId===availableId){
408
+ await report('update_already_running',id,identity,{availableUpdateId:availableId});
409
+ }else if(pending?.updateId===availableId){
410
+ await report('download_already_cached',id,identity,{availableUpdateId:availableId});
411
+ await activatePending(id,identity,pending);
412
+ return;
413
+ }else{
414
+ await report('download_started',id,identity,{availableUpdateId:availableId});
415
+ const fetched=await withTimeout(Updates.fetchUpdateAsync(),DOWNLOAD_TIMEOUT_MS,'download');
416
+ if(!fetched?.isNew || fetched?.isRollBackToEmbedded){
417
+ await report('download_no_new',id,identity,{availableUpdateId:availableId});
418
+ }else{
419
+ const downloadedId=String(fetched.manifest?.id||availableId);
420
+ if(downloadedId!==availableId)throw new Error('Downloaded update ID does not match the manifest selected for this installation.');
421
+ pending={updateId:downloadedId,downloadedAt:Date.now(),activationAttempts:0};
422
+ await putPending(pending);
423
+ await report('download_completed',id,identity,{availableUpdateId:downloadedId});
424
+ await activatePending(id,identity,pending);
425
+ return;
426
+ }
427
+ }
210
428
  }
211
429
  await revealApp();
212
- setTimeout(()=>{void report('launch_success',id,identity);},1500);
430
+ // This means JS booted, not that a target OTA was applied. See update_applied.
431
+ setTimeout(()=>{void report('launch_success',id,identity,{isEmbeddedLaunch:!!Updates.isEmbeddedLaunch});},1500);
213
432
  }catch(error){
214
- await report('update_failed',id,identity,{message:String(error?.message||error)});
215
- // Do not reload later in this session after a timeout/failure. Keep the current
216
- // known-good bundle running; any completed download can be used next cold start.
433
+ await report('update_failed',id||'unknown',identity,{availableUpdateId:targetId,...errorDetail(error),nativeLogs:await nativeLogs()});
217
434
  await revealApp();
218
435
  }
219
436
  }
220
437
  void runIndraqOTAStartup();
221
438
  `;
222
439
  (0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'bootstrap.js'), source, 'utf8');
223
- (0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'README.md'), '# IndraQ OTA\n\nGenerated by `indraq prebuild`. Call `identifyIndraqOTA({ userId, username, email, phone })` after login if you want user-targeted OTA releases. The app checks OTA only at cold startup; if an update is downloaded it reloads immediately before normal app usage.\n', 'utf8');
440
+ // For Expo Router, provide a real route so the scanner's deep link does not
441
+ // land on the framework's unmatched-route screen. Existing routes are sacred.
442
+ if (projectType === 'expo') {
443
+ const packageJson = readPackage(root);
444
+ if (packageJson.dependencies?.['expo-router'] || packageJson.devDependencies?.['expo-router']) {
445
+ const route = (0, node_path_1.join)(root, 'app', 'indraq-enroll.jsx');
446
+ if ((0, node_fs_1.existsSync)((0, node_path_1.join)(root, 'app')) && !(0, node_fs_1.existsSync)(route)) {
447
+ (0, node_fs_1.writeFileSync)(route, `// Generated by IndraQ CLI. QR enrollment needs no app auth integration.
448
+ import React,{useEffect,useState} from 'react';
449
+ import {View,Text,ActivityIndicator,StyleSheet} from 'react-native';
450
+ import {useLocalSearchParams} from 'expo-router';
451
+ import {redeemIndraqEnrollment} from '../indraq-ota/bootstrap.js';
452
+ export default function IndraQEnrollmentScreen(){
453
+ const {token}=useLocalSearchParams();
454
+ const [status,setStatus]=useState('Enrolling this device...');
455
+ useEffect(()=>{let active=true;redeemIndraqEnrollment(String(token||''))
456
+ .then(()=>{if(active)setStatus('Device successfully enrolled for OTA testing. You may return to the app.');})
457
+ .catch(e=>{if(active)setStatus(String(e?.message||'Enrollment failed. Please request a new QR code.'));});
458
+ return()=>{active=false;};
459
+ },[token]);
460
+ return <View style={styles.container}><ActivityIndicator/><Text style={styles.title}>IndraQ Device Enrollment</Text><Text style={styles.message}>{status}</Text></View>;
461
+ }
462
+ const styles=StyleSheet.create({container:{flex:1,justifyContent:'center',alignItems:'center',padding:24,gap:16},title:{fontSize:20,fontWeight:'700'},message:{fontSize:15,textAlign:'center'}});
463
+ `, 'utf8');
464
+ }
465
+ }
466
+ }
467
+ (0, node_fs_1.writeFileSync)((0, node_path_1.join)(dir, 'README.md'), '# IndraQ OTA\n\nGenerated by `indraq mobile prebuild`. See `identity.json` for the one-time profile storage adapter. If configured, the app automatically reads the signed-in user profile and refreshes identity after login/logout without screen imports. Updates download once, attempt immediate native reload, and record success only when the downloaded update actually runs. Native reload failures are surfaced without redownloading the same release. For custom memory-only authentication, an explicit adapter is still required. Never put access tokens/passwords in identity.json.\n', 'utf8');
224
468
  const pkg = readPackage(root);
225
469
  if (projectType === 'expo') {
226
470
  const target = (0, node_path_1.join)(root, 'indraq-ota-entry.js');