2026-06-13 20:13:12 -05:00
|
|
|
'use strict';
|
|
|
|
|
|
2026-06-14 18:27:03 -05:00
|
|
|
const fs = require('fs');
|
2026-06-13 20:13:12 -05:00
|
|
|
const path = require('path');
|
|
|
|
|
|
2026-06-14 18:27:03 -05:00
|
|
|
// better-sqlite3's better_sqlite3.node is architecture-specific (it links
|
|
|
|
|
// against libnode.so, which is the real Android binary already loaded into
|
|
|
|
|
// this process by nodejs-mobile-cordova). The copy under node_modules/ is
|
|
|
|
|
// whichever architecture it happened to be built for last; replace it with
|
|
|
|
|
// the prebuild matching this device's actual arch before anything requires
|
2026-07-11 09:42:53 -05:00
|
|
|
// better-sqlite3. See scripts/build-better-sqlite3-node18.sh.
|
2026-06-14 18:27:03 -05:00
|
|
|
(function installBetterSqlite3Prebuild() {
|
|
|
|
|
const archDirs = {
|
|
|
|
|
arm64: 'arm64-v8a',
|
|
|
|
|
arm: 'armeabi-v7a',
|
|
|
|
|
x64: 'x86_64',
|
|
|
|
|
ia32: 'x86',
|
|
|
|
|
};
|
|
|
|
|
const archDir = archDirs[process.arch];
|
|
|
|
|
if (!archDir) return; // Unknown arch — fall back to whatever's bundled.
|
|
|
|
|
|
|
|
|
|
const prebuilt = path.join(__dirname, 'prebuilds', archDir, 'better_sqlite3.node');
|
|
|
|
|
const target = path.join(__dirname, 'node_modules', 'better-sqlite3', 'build', 'Release', 'better_sqlite3.node');
|
|
|
|
|
if (!fs.existsSync(prebuilt)) return;
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
|
|
|
fs.copyFileSync(prebuilt, target);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error('[main.js] Failed to install better-sqlite3 prebuild for', process.arch, err);
|
|
|
|
|
}
|
|
|
|
|
})();
|
|
|
|
|
|
2026-07-11 09:42:53 -05:00
|
|
|
// nodejs-mobile's Node 18.20.4 build ships WITHOUT ICU (verified:
|
|
|
|
|
// process.versions.icu === undefined, typeof Intl === 'undefined'), so `Intl`
|
|
|
|
|
// is entirely absent. Polyfill just the bits the server uses — en-US number
|
2026-06-14 13:10:14 -05:00
|
|
|
// formatting with thousands separators, and a no-op DateTimeFormat whose
|
|
|
|
|
// resolvedOptions().timeZone the callers already treat as optional.
|
2026-07-11 09:42:53 -05:00
|
|
|
//
|
|
|
|
|
// (crypto.randomUUID and crypto.hkdfSync are NATIVE on Node 18 — the Node-12
|
|
|
|
|
// shims for them are gone. See PLAN/FUTURE Batch 6.)
|
2026-06-14 13:10:14 -05:00
|
|
|
if (typeof global.Intl === 'undefined') {
|
|
|
|
|
global.Intl = {
|
|
|
|
|
NumberFormat: function (_locale, options) {
|
|
|
|
|
const opts = options || {};
|
|
|
|
|
const minFrac = opts.minimumFractionDigits || 0;
|
|
|
|
|
const maxFrac = Math.max(opts.maximumFractionDigits || 0, minFrac);
|
|
|
|
|
this.format = function (value) {
|
|
|
|
|
const fixed = Number(value).toFixed(maxFrac);
|
|
|
|
|
let [intPart, fracPart] = fixed.split('.');
|
|
|
|
|
const negative = intPart.startsWith('-');
|
|
|
|
|
if (negative) intPart = intPart.slice(1);
|
|
|
|
|
intPart = intPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
|
|
|
|
let out = (negative ? '-' : '') + intPart;
|
|
|
|
|
if (fracPart) out += '.' + fracPart;
|
|
|
|
|
return out;
|
|
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
DateTimeFormat: function () {
|
|
|
|
|
this.resolvedOptions = function () {
|
|
|
|
|
return { timeZone: undefined };
|
|
|
|
|
};
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
feat(mobile): shared api/config layer, server-mode CSRF fix, robustness + update-safe DB (batch 10)
Unify the native shell and harden it:
- src/config.ts: single source for local host/port, preference keys, secure-storage
key, timeouts, and CSRF constants (dedupes LOCAL_URL etc. across App/LoadingScreen).
- src/api.ts: one HTTP client — credentials mode, AbortController timeouts, and error
normalization into user-facing messages (network/timeout/401/403/429/5xx), with typed
auth responses.
- Batch 10 CSRF fix: /api/auth/totp/challenge is not CSRF-exempt, so the native TOTP
step now fetches GET /api/auth/csrf-token and echoes it as x-csrf-token (mirrors the
web client); TOTP login no longer breaks for 2FA users.
- Error-handling / boot robustness: LoadingScreen gets a health-poll timeout and
surfaces main.js's {type:'serverError'} channel messages instead of spinning forever;
App.tsx bootstrap and the encryption-key fetch now .catch to a visible state; crypto.ts
reports secure-storage failures.
- Data safety: move the SQLite DB, backups, and tmp OUT of nodejs-project into the app's
filesDir (bt-data). nodejs-mobile re-copies nodejs-project on every app update, which was
silently wiping local-mode data. Verified on the emulator: create data -> bump versionCode
-> reinstall -> migrations skipped, no re-seed, data persists.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-11 10:48:23 -05:00
|
|
|
// Server-side paths. CRITICAL: keep the database, backups, and temp OUTSIDE the
|
|
|
|
|
// nodejs-project directory. nodejs-mobile-cordova re-copies nodejs-project from
|
|
|
|
|
// the APK assets on every app update, which would wipe anything stored inside it
|
|
|
|
|
// (a silent data-loss bug). __dirname is <filesDir>/www/nodejs-project, so two
|
|
|
|
|
// levels up is the app-private filesDir, which persists across updates.
|
|
|
|
|
const DATA_ROOT = path.join(__dirname, '..', '..', 'bt-data');
|
|
|
|
|
process.env.DB_PATH = path.join(DATA_ROOT, 'db', 'bills.db');
|
|
|
|
|
process.env.BACKUP_PATH = path.join(DATA_ROOT, 'backups');
|
2026-07-11 09:42:53 -05:00
|
|
|
// Android has no /tmp; point os.tmpdir() at app-writable storage so the daily
|
|
|
|
|
// worker's temp-export cleanup doesn't error (ENOENT scandir '/tmp').
|
feat(mobile): shared api/config layer, server-mode CSRF fix, robustness + update-safe DB (batch 10)
Unify the native shell and harden it:
- src/config.ts: single source for local host/port, preference keys, secure-storage
key, timeouts, and CSRF constants (dedupes LOCAL_URL etc. across App/LoadingScreen).
- src/api.ts: one HTTP client — credentials mode, AbortController timeouts, and error
normalization into user-facing messages (network/timeout/401/403/429/5xx), with typed
auth responses.
- Batch 10 CSRF fix: /api/auth/totp/challenge is not CSRF-exempt, so the native TOTP
step now fetches GET /api/auth/csrf-token and echoes it as x-csrf-token (mirrors the
web client); TOTP login no longer breaks for 2FA users.
- Error-handling / boot robustness: LoadingScreen gets a health-poll timeout and
surfaces main.js's {type:'serverError'} channel messages instead of spinning forever;
App.tsx bootstrap and the encryption-key fetch now .catch to a visible state; crypto.ts
reports secure-storage failures.
- Data safety: move the SQLite DB, backups, and tmp OUT of nodejs-project into the app's
filesDir (bt-data). nodejs-mobile re-copies nodejs-project on every app update, which was
silently wiping local-mode data. Verified on the emulator: create data -> bump versionCode
-> reinstall -> migrations skipped, no re-seed, data persists.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-11 10:48:23 -05:00
|
|
|
process.env.TMPDIR = path.join(DATA_ROOT, 'tmp');
|
|
|
|
|
try {
|
|
|
|
|
fs.mkdirSync(path.dirname(process.env.DB_PATH), { recursive: true });
|
|
|
|
|
fs.mkdirSync(process.env.BACKUP_PATH, { recursive: true });
|
|
|
|
|
fs.mkdirSync(process.env.TMPDIR, { recursive: true });
|
|
|
|
|
} catch (_) { /* best effort — database.cts also ensures the DB dir */ }
|
2026-06-13 20:13:12 -05:00
|
|
|
process.env.PORT = process.env.PORT || '3000';
|
|
|
|
|
process.env.BIND_HOST = '127.0.0.1';
|
2026-06-14 13:10:14 -05:00
|
|
|
// The Capacitor WebView's origin (androidScheme: 'https') is cross-origin
|
|
|
|
|
// from this server's http://localhost:3000, so the LoadingScreen's
|
|
|
|
|
// /api/health poll and the app's API calls need CORS allowed for it.
|
|
|
|
|
process.env.CORS_ORIGIN = 'https://localhost';
|
2026-06-13 20:13:12 -05:00
|
|
|
|
|
|
|
|
const cordova = require('cordova-bridge');
|
|
|
|
|
|
2026-07-11 09:42:53 -05:00
|
|
|
// Surface fatal errors to logcat and to the WebView (LoadingScreen) instead of
|
|
|
|
|
// dying silently behind an endless "Starting…" spinner.
|
|
|
|
|
function reportError(where, err) {
|
|
|
|
|
const msg = err && err.stack ? err.stack : String(err);
|
|
|
|
|
console.error('[main.js] ' + where + ':', msg);
|
|
|
|
|
try {
|
|
|
|
|
cordova.channel.post('message', { type: 'serverError', message: String((err && err.message) || err) });
|
|
|
|
|
} catch (_) { /* channel may not be ready */ }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
process.on('uncaughtException', (err) => reportError('uncaughtException', err));
|
|
|
|
|
process.on('unhandledRejection', (err) => reportError('unhandledRejection', err));
|
|
|
|
|
|
|
|
|
|
// Wait for the WebView to hand over the device-bound encryption key (stored in
|
|
|
|
|
// Android Keystore / iOS Keychain — see src/crypto.ts) before starting the
|
|
|
|
|
// server, so encryptionService picks up TOKEN_ENCRYPTION_KEY on first use.
|
2026-06-13 20:13:12 -05:00
|
|
|
cordova.channel.on('message', function (msg) {
|
|
|
|
|
if (msg && msg.type === 'encryptionKey' && typeof msg.key === 'string') {
|
|
|
|
|
process.env.TOKEN_ENCRYPTION_KEY = msg.key;
|
2026-07-11 09:42:53 -05:00
|
|
|
try {
|
|
|
|
|
require('./server/server.cts');
|
|
|
|
|
} catch (err) {
|
|
|
|
|
reportError('server failed to start', err);
|
|
|
|
|
}
|
2026-06-13 20:13:12 -05:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
cordova.channel.post('message', { type: 'ready' });
|