After adding the fonctionality for apk publish
This commit is contained in:
parent
3f7eb5358d
commit
607652144e
@ -147,5 +147,12 @@ WS_PATH=/ws/v1/games/candle-predict
|
||||
# CLAMAV_HOST=clamav
|
||||
# CLAMAV_PORT=3310
|
||||
|
||||
# Mobile APK release distribution (see docs/MOBILE_APP_RELEASES.md)
|
||||
# SHA-256 of the Android signing certificate (hex, optional colons). Empty = skip cert check (dev only).
|
||||
# ANDROID_APK_EXPECTED_CERT_SHA256=
|
||||
# ANDROID_APK_EXPECTED_PACKAGE=com.prediqo.mobile
|
||||
# APK_MAX_UPLOAD_BYTES=125829120
|
||||
# APK_DOWNLOAD_TOKEN_TTL_SECONDS=3600
|
||||
|
||||
# Optional: containerized PostgreSQL instead of host
|
||||
# docker compose --profile docker-db up -d
|
||||
|
||||
@ -108,6 +108,12 @@ WORKER_ID=worker-1
|
||||
# CLAMAV_PORT=3310
|
||||
# CLAMAV_TIMEOUT_MS=30000
|
||||
|
||||
# Mobile APK releases (see docs/MOBILE_APP_RELEASES.md)
|
||||
# ANDROID_APK_EXPECTED_CERT_SHA256=
|
||||
# ANDROID_APK_EXPECTED_PACKAGE=com.prediqo.mobile
|
||||
# APK_MAX_UPLOAD_BYTES=125829120
|
||||
# APK_DOWNLOAD_TOKEN_TTL_SECONDS=3600
|
||||
|
||||
# Slack alerts (optional — create one Incoming Webhook per channel in Slack)
|
||||
# SLACK_SECURITY_WEBHOOK_URL=https://hooks.slack.com/services/... # #security
|
||||
# SLACK_REFERRAL_WEBHOOK_URL=https://hooks.slack.com/services/... # #referral-fraud
|
||||
|
||||
9
backend/dist/config/index.d.ts
vendored
9
backend/dist/config/index.d.ts
vendored
@ -203,5 +203,14 @@ export declare const config: {
|
||||
port: number;
|
||||
timeoutMs: number;
|
||||
};
|
||||
mobileReleases: {
|
||||
/** Expected Android signing certificate SHA-256 (hex, no colons). Empty = skip cert check (dev only). */
|
||||
expectedCertSha256: string;
|
||||
expectedPackage: string;
|
||||
maxUploadBytes: number;
|
||||
/** HMAC secret for short-lived download tokens (falls back to JWT secret). */
|
||||
downloadTokenSecret: string;
|
||||
downloadTokenTtlSeconds: number;
|
||||
};
|
||||
};
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
2
backend/dist/config/index.d.ts.map
vendored
2
backend/dist/config/index.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmEH,kFAAkF;AAClF,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;YAoBb,kIAAkI;;;;;;;YAOlI,iFAAiF;;;;;YAKjF;;;;eAIG;;YAKH,mFAAmF;;;;YAInF;;;eAGG;;YAKH,8EAA8E;;YAK9E;;;;eAIG;;YAEH,uEAAuE;;YAEvE;;;eAGG;;YAEH,4DAA4D;;;;;;;;;;;;QAgB9D,kFAAkF;;QAElF,4FAA4F;;;;;QAQ5F,6FAA6F;;QAE7F,8EAA8E;;;;QAI9E,kEAAkE;;QAElE;;;WAGG;;QAEH;;;WAGG;;QAEH;;;WAGG;;;QAMH,gDAAgD;;QAEhD,0DAA0D;;QAE1D;;;WAGG;;QAEH,2DAA2D;;;;QAI3D,iFAAiF;;;;QAIjF,yDAAyD;;;;QAOzD,6FAA6F;;;;QAI7F,gEAAgE;;;;;;;;;;QAUhE,+DAA+D;;;;;;;;;;;;;;QAc/D,iEAAiE;;QAEjE,8DAA8D;;QAE9D,4DAA4D;;;;;QAK5D,oEAAoE;;QAIpE,6DAA6D;;QAE7D,2EAA2E;;;;;;;;;;IAU7E,mFAAmF;;;QAGjF;;;WAGG;;;;;;;;;;;;;;;;;CAsBN,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmEH,kFAAkF;AAClF,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;YAoBb,kIAAkI;;;;;;;YAOlI,iFAAiF;;;;;YAKjF;;;;eAIG;;YAKH,mFAAmF;;;;YAInF;;;eAGG;;YAKH,8EAA8E;;YAK9E;;;;eAIG;;YAEH,uEAAuE;;YAEvE;;;eAGG;;YAEH,4DAA4D;;;;;;;;;;;;QAgB9D,kFAAkF;;QAElF,4FAA4F;;;;;QAQ5F,6FAA6F;;QAE7F,8EAA8E;;;;QAI9E,kEAAkE;;QAElE;;;WAGG;;QAEH;;;WAGG;;QAEH;;;WAGG;;;QAMH,gDAAgD;;QAEhD,0DAA0D;;QAE1D;;;WAGG;;QAEH,2DAA2D;;;;QAI3D,iFAAiF;;;;QAIjF,yDAAyD;;;;QAOzD,6FAA6F;;;;QAI7F,gEAAgE;;;;;;;;;;QAUhE,+DAA+D;;;;;;;;;;;;;;QAc/D,iEAAiE;;QAEjE,8DAA8D;;QAE9D,4DAA4D;;;;;QAK5D,oEAAoE;;QAIpE,6DAA6D;;QAE7D,2EAA2E;;;;;;;;;;IAU7E,mFAAmF;;;QAGjF;;;WAGG;;;;;;;;;;;;;;;;;;QAuBH,yGAAyG;;;;QAIzG,8EAA8E;;;;CAOjF,CAAC"}
|
||||
11
backend/dist/config/index.js
vendored
11
backend/dist/config/index.js
vendored
@ -279,5 +279,16 @@ exports.config = {
|
||||
port: parseInt(process.env.CLAMAV_PORT || '3310', 10),
|
||||
timeoutMs: readEnvInt('CLAMAV_TIMEOUT_MS', 30000, 5000, 120000),
|
||||
},
|
||||
mobileReleases: {
|
||||
/** Expected Android signing certificate SHA-256 (hex, no colons). Empty = skip cert check (dev only). */
|
||||
expectedCertSha256: (process.env.ANDROID_APK_EXPECTED_CERT_SHA256 || '').trim().toLowerCase().replace(/:/g, ''),
|
||||
expectedPackage: (process.env.ANDROID_APK_EXPECTED_PACKAGE || 'com.prediqo.mobile').trim(),
|
||||
maxUploadBytes: readEnvInt('APK_MAX_UPLOAD_BYTES', 120 * 1024 * 1024, 1000000, 300 * 1024 * 1024),
|
||||
/** HMAC secret for short-lived download tokens (falls back to JWT secret). */
|
||||
downloadTokenSecret: process.env.APK_DOWNLOAD_TOKEN_SECRET ||
|
||||
process.env.JWT_SECRET ||
|
||||
'change-me-in-production',
|
||||
downloadTokenTtlSeconds: readEnvInt('APK_DOWNLOAD_TOKEN_TTL_SECONDS', 3600, 60, 86400),
|
||||
},
|
||||
};
|
||||
//# sourceMappingURL=index.js.map
|
||||
2
backend/dist/config/index.js.map
vendored
2
backend/dist/config/index.js.map
vendored
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"version":3,"file":"referralController.d.ts","sourceRoot":"","sources":["../../src/controllers/referralController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAYjD,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOtF;AAED,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAO3F;AAED,wBAAsB,wBAAwB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAY7F;AAED,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAQrF;AAED,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBxF;AAED,wBAAsB,sBAAsB,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAO5F;AAED,wBAAsB,2BAA2B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,I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,IAAI,CAAC,CAYxF;AAED,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOtF;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAmClF;AAED,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAS3F;AAED,wBAAsB,yBAAyB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAa9F;AAED,wBAAsB,wBAAwB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAiB7F;AAED,wBAAsB,yBAAyB,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAO/F;AAED,wBAAsB,0BAA0B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAiB/F;AAED,wBAAsB,yBAAyB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ9F;AAED,wBAAsB,2BAA2B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CA+BhG;AAED,wBAAsB,0BAA0B,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwB/F"}
|
||||
21
backend/dist/controllers/referralController.js
vendored
21
backend/dist/controllers/referralController.js
vendored
@ -55,6 +55,7 @@ exports.exportReferralClawbacksCsv = exportReferralClawbacksCsv;
|
||||
const referralService = __importStar(require("../services/referralService"));
|
||||
const bonusService = __importStar(require("../services/bonusService"));
|
||||
const referralRepository = __importStar(require("../repositories/referralRepository"));
|
||||
const bonusPoolRepository = __importStar(require("../repositories/bonusPoolRepository"));
|
||||
const referralExportService_1 = require("../services/referralExportService");
|
||||
const referralRegularizationService_1 = require("../services/referralRegularizationService");
|
||||
async function getMyReferralInfo(req, res) {
|
||||
@ -129,6 +130,7 @@ async function getAdminReferralConfig(_req, res) {
|
||||
async function updateAdminReferralSettings(req, res) {
|
||||
try {
|
||||
const body = req.body;
|
||||
const { walletTypeId: commissionWalletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
|
||||
await referralRepository.updateSettings({
|
||||
enabled: body.enabled,
|
||||
defaultReferrerUserId: body.defaultReferrerUserId,
|
||||
@ -150,7 +152,7 @@ async function updateAdminReferralSettings(req, res) {
|
||||
withdrawalCommissionsEnabled: body.withdrawalCommissionsEnabled,
|
||||
predictionCommissionsEnabled: body.predictionCommissionsEnabled,
|
||||
minFirstDepositRaw: body.minFirstDepositRaw,
|
||||
commissionWalletTypeId: body.commissionWalletTypeId,
|
||||
commissionWalletTypeId,
|
||||
});
|
||||
const config = await referralService.getProgramSettingsForAdmin();
|
||||
res.json(config);
|
||||
@ -198,9 +200,9 @@ async function getReferralStats(_req, res) {
|
||||
}
|
||||
async function fundBonusPool(req, res) {
|
||||
try {
|
||||
const { walletTypeId, amountRaw } = req.body;
|
||||
if (!walletTypeId || !amountRaw) {
|
||||
res.status(400).json({ error: 'walletTypeId and amountRaw are required' });
|
||||
const { amountRaw } = req.body;
|
||||
if (!amountRaw) {
|
||||
res.status(400).json({ error: 'amountRaw is required' });
|
||||
return;
|
||||
}
|
||||
const amount = BigInt(amountRaw);
|
||||
@ -208,16 +210,23 @@ async function fundBonusPool(req, res) {
|
||||
res.status(400).json({ error: 'Amount must be positive' });
|
||||
return;
|
||||
}
|
||||
// Always fund the single USDT_TRC20 ledger pool (ignore any client walletTypeId).
|
||||
const { walletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
|
||||
await referralRepository.updateSettings({ commissionWalletTypeId: walletTypeId });
|
||||
const { createFundRequest } = await Promise.resolve().then(() => __importStar(require('../services/fundApprovalService')));
|
||||
const result = await createFundRequest({
|
||||
operationType: 'bonus_pool_fund',
|
||||
payload: { walletTypeId, amountRaw },
|
||||
requestedBy: req.user.userId,
|
||||
});
|
||||
res.status(202).json({
|
||||
const auto = Boolean(result.autoExecuted);
|
||||
res.status(auto ? 200 : 202).json({
|
||||
requestId: result.id,
|
||||
status: result.status,
|
||||
message: 'Bonus pool funding submitted — pending super-admin approval',
|
||||
autoExecuted: auto,
|
||||
message: auto
|
||||
? 'Bonus pool funded (auto-executed by approval policy)'
|
||||
: 'Bonus pool funding submitted — pending approval',
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -3,6 +3,21 @@ export declare function listPools(): Promise<Array<{
|
||||
wallet_type_id: number;
|
||||
available_balance: string;
|
||||
}>>;
|
||||
/** Single fundable pool = unified USDT ledger (USDT_TRC20). */
|
||||
export declare function listCommissionPools(): Promise<Array<{
|
||||
wallet_type_id: number;
|
||||
available_balance: string;
|
||||
}>>;
|
||||
export declare function hasPool(walletTypeId: number): Promise<boolean>;
|
||||
/** Ensure a pool row exists (e.g. after changing commission wallet type). */
|
||||
export declare function ensurePool(walletTypeId: number): Promise<void>;
|
||||
/**
|
||||
* Resolve the fixed commission ledger wallet (USDT_TRC20), ensure its pool exists,
|
||||
* and drop stray pools for custody rails (e.g. USDT_BEP20) so only one pool remains.
|
||||
*/
|
||||
export declare function lockCommissionLedgerPool(): Promise<{
|
||||
walletTypeId: number;
|
||||
}>;
|
||||
/** Admin funds the platform bonus pool (off-chain treasury allocation). */
|
||||
export declare function fundPool(walletTypeId: number, amount: bigint): Promise<void>;
|
||||
export declare function debitPool(walletTypeId: number, amount: bigint): Promise<boolean>;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"bonusPoolRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/bonusPoolRepository.ts"],"names":[],"mappings":"AAEA,wBAAsB,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAM1E;AAED,wBAAsB,SAAS,IAAI,OAAO,CAAC,KAAK,CAAC;IAAE,cAAc,EAAE,MAAM,CAAC;IAAC,iBAAiB,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAIvG;AAED,2EAA2E;AAC3E,wBAAsB,QAAQ,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAqBlF;AAED,wBAAsB,SAAS,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CA6BtF;AAED,iFAAiF;AACjF,wBAAsB,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAGpF"}
|
||||
{"version":3,"file":"bonusPoolRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/bonusPoolRepository.ts"],"names":[],"mappings":"AAKA,wBAAsB,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAM1E;AAED,wBAAsB,SAAS,IAAI,OAAO,CAAC,KAAK,CAAC;IAAE,cAAc,EAAE,MAAM,CAAC;IAAC,iBAAiB,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAIvG;AAED,+DAA+D;AAC/D,wBAAsB,mBAAmB,IAAI,OAAO,CAClD,KAAK,CAAC;IAAE,cAAc,EAAE,MAAM,CAAC;IAAC,iBAAiB,EAAE,MAAM,CAAA;CAAE,CAAC,CAC7D,CASA;AAED,wBAAsB,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAMpE;AAED,6EAA6E;AAC7E,wBAAsB,UAAU,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAOpE;AAED;;;GAGG;AACH,wBAAsB,wBAAwB,IAAI,OAAO,CAAC;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CAiBlF;AAED,2EAA2E;AAC3E,wBAAsB,QAAQ,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAyBlF;AAED,wBAAsB,SAAS,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CA6BtF;AAED,iFAAiF;AACjF,wBAAsB,UAAU,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAGpF"}
|
||||
45
backend/dist/repositories/bonusPoolRepository.js
vendored
45
backend/dist/repositories/bonusPoolRepository.js
vendored
@ -2,10 +2,16 @@
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getPoolBalance = getPoolBalance;
|
||||
exports.listPools = listPools;
|
||||
exports.listCommissionPools = listCommissionPools;
|
||||
exports.hasPool = hasPool;
|
||||
exports.ensurePool = ensurePool;
|
||||
exports.lockCommissionLedgerPool = lockCommissionLedgerPool;
|
||||
exports.fundPool = fundPool;
|
||||
exports.debitPool = debitPool;
|
||||
exports.creditPool = creditPool;
|
||||
const connection_1 = require("../db/connection");
|
||||
/** Unified spendable USDT ledger code — sole referral commission / bonus pool wallet. */
|
||||
const COMMISSION_LEDGER_CODE = 'USDT_TRC20';
|
||||
async function getPoolBalance(walletTypeId) {
|
||||
const rows = await (0, connection_1.query)('SELECT available_balance::text FROM platform_bonus_pools WHERE wallet_type_id = $1', [walletTypeId]);
|
||||
return rows[0]?.available_balance ?? '0';
|
||||
@ -13,14 +19,49 @@ async function getPoolBalance(walletTypeId) {
|
||||
async function listPools() {
|
||||
return (0, connection_1.query)('SELECT wallet_type_id, available_balance::text FROM platform_bonus_pools ORDER BY wallet_type_id');
|
||||
}
|
||||
/** Single fundable pool = unified USDT ledger (USDT_TRC20). */
|
||||
async function listCommissionPools() {
|
||||
return (0, connection_1.query)(`SELECT p.wallet_type_id, p.available_balance::text
|
||||
FROM platform_bonus_pools p
|
||||
INNER JOIN wallet_types wt ON wt.id = p.wallet_type_id
|
||||
WHERE wt.code = $1
|
||||
ORDER BY p.wallet_type_id`, [COMMISSION_LEDGER_CODE]);
|
||||
}
|
||||
async function hasPool(walletTypeId) {
|
||||
const rows = await (0, connection_1.query)('SELECT wallet_type_id FROM platform_bonus_pools WHERE wallet_type_id = $1', [walletTypeId]);
|
||||
return Boolean(rows[0]);
|
||||
}
|
||||
/** Ensure a pool row exists (e.g. after changing commission wallet type). */
|
||||
async function ensurePool(walletTypeId) {
|
||||
await (0, connection_1.query)(`INSERT INTO platform_bonus_pools (wallet_type_id, available_balance)
|
||||
VALUES ($1, 0)
|
||||
ON CONFLICT (wallet_type_id) DO NOTHING`, [walletTypeId]);
|
||||
}
|
||||
/**
|
||||
* Resolve the fixed commission ledger wallet (USDT_TRC20), ensure its pool exists,
|
||||
* and drop stray pools for custody rails (e.g. USDT_BEP20) so only one pool remains.
|
||||
*/
|
||||
async function lockCommissionLedgerPool() {
|
||||
const rows = await (0, connection_1.query)('SELECT id FROM wallet_types WHERE code = $1 LIMIT 1', [COMMISSION_LEDGER_CODE]);
|
||||
const walletTypeId = rows[0]?.id;
|
||||
if (!walletTypeId) {
|
||||
throw new Error('USDT_TRC20 wallet type not configured — cannot lock referral commission pool');
|
||||
}
|
||||
await ensurePool(walletTypeId);
|
||||
await (0, connection_1.query)(`DELETE FROM platform_bonus_pools p
|
||||
USING wallet_types wt
|
||||
WHERE p.wallet_type_id = wt.id AND wt.code <> $1`, [COMMISSION_LEDGER_CODE]);
|
||||
return { walletTypeId };
|
||||
}
|
||||
/** Admin funds the platform bonus pool (off-chain treasury allocation). */
|
||||
async function fundPool(walletTypeId, amount) {
|
||||
const client = await (0, connection_1.getClient)();
|
||||
try {
|
||||
await (0, connection_1.beginAuthorizedTransaction)(client);
|
||||
const row = await client.query('SELECT available_balance FROM platform_bonus_pools WHERE wallet_type_id = $1 FOR UPDATE', [walletTypeId]);
|
||||
if (!row.rows[0])
|
||||
throw new Error('Bonus pool not found for wallet type');
|
||||
if (!row.rows[0]) {
|
||||
throw new Error('Bonus pool not found for wallet type. Fund only the commission wallet type (USDT_TRC20 ledger), not a custody rail like USDT_BEP20.');
|
||||
}
|
||||
const newBalance = BigInt(row.rows[0].available_balance) + amount;
|
||||
await client.query('UPDATE platform_bonus_pools SET available_balance = $1, updated_at = NOW() WHERE wallet_type_id = $2', [newBalance.toString(), walletTypeId]);
|
||||
await client.query('COMMIT');
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"bonusPoolRepository.js","sourceRoot":"","sources":["../../src/repositories/bonusPoolRepository.ts"],"names":[],"mappings":";;AAEA,wCAMC;AAED,8BAIC;AAGD,4BAqBC;AAED,8BA6BC;AAGD,gCAGC;AA3ED,iDAAgF;AAEzE,KAAK,UAAU,cAAc,CAAC,YAAoB;IACvD,MAAM,IAAI,GAAG,MAAM,IAAA,kBAAK,EACtB,oFAAoF,EACpF,CAAC,YAAY,CAAC,CACf,CAAC;IACF,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,iBAAiB,IAAI,GAAG,CAAC;AAC3C,CAAC;AAEM,KAAK,UAAU,SAAS;IAC7B,OAAO,IAAA,kBAAK,EACV,kGAAkG,CACnG,CAAC;AACJ,CAAC;AAED,2EAA2E;AACpE,KAAK,UAAU,QAAQ,CAAC,YAAoB,EAAE,MAAc;IACjE,MAAM,MAAM,GAAG,MAAM,IAAA,sBAAS,GAAE,CAAC;IACjC,IAAI,CAAC;QACH,MAAM,IAAA,uCAA0B,EAAC,MAAM,CAAC,CAAC;QACzC,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,KAAK,CAC5B,yFAAyF,EACzF,CAAC,YAA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AO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,MAAM,CAAC,KAAK,CAChB,sGAAsG,EACtG,CAAC,CAAC,SAAS,GAAG,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,YAAY,CAAC,CAChD,CAAC;QACF,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC/B,MAAM,CAAC,CAAC;IACV,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,OAAO,EAAE,CAAC;IACnB,CAAC;AACH,CAAC;AAED,iFAAiF;AAC1E,KAAK,UAAU,UAAU,CAAC,YAAoB,EAAE,MAAc;IACnE,IAAI,MAAM,IAAI,EAAE;QAAE,OAAO;IACzB,MAAM,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;AACvC,CAAC"}
|
||||
{"version":3,"file":"bonusPoolRepository.js","sourceRoot":"","sources":["../../src/repositories/bonusPoolRepository.ts"],"names":[],"mappings":";;AAKA,wCAMC;AAED,8BAIC;AAGD,kDAWC;AAED,0BAMC;AAGD,gCAOC;AAMD,4DAiBC;AAGD,4BAyBC;AAED,8BA6BC;AAGD,gCAGC;AAzID,iDAAgF;AAEhF,yFAAyF;AACzF,MAAM,sBAAsB,GAAG,YAAY,CAAC;AAErC,KAAK,UAAU,cAAc,CAAC,YAAoB;IACvD,MAAM,IAAI,GAAG,MAAM,IAAA,kBAAK,EACtB,oFAAoF,EACpF,CAAC,YAAY,CAAC,CACf,CAAC;IACF,OAAO,IAAI,CAAC,CAAC,CAAC,EAAE,iBAAiB,IAAI,GAAG,CAAC;AAC3C,CAAC;AAEM,KAAK,UAAU,SAAS;IAC7B,OAAO,IAAA,kBAAK,EACV,kGAAkG,CACnG,CAAC;AACJ,CAAC;AAED,+DAA+D;AACxD,KAAK,UAAU,mBAAmB;I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CAAC,KAAK,CAChB,sGAAsG,EACtG,CAAC,CAAC,SAAS,GAAG,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,YAAY,CAAC,CAChD,CAAC;QACF,MAAM,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,MAAM,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QAC/B,MAAM,CAAC,CAAC;IACV,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,OAAO,EAAE,CAAC;IACnB,CAAC;AACH,CAAC;AAED,iFAAiF;AAC1E,KAAK,UAAU,UAAU,CAAC,YAAoB,EAAE,MAAc;IACnE,IAAI,MAAM,IAAI,EAAE;QAAE,OAAO;IACzB,MAAM,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;AACvC,CAAC"}
|
||||
@ -17,6 +17,12 @@ export declare function listAlerts(opts: {
|
||||
total: number;
|
||||
}>;
|
||||
export declare function findById(id: string): Promise<SecurityAlert | null>;
|
||||
/** True if an open FIM alert already exists for the same root/path/issue (stops alert storms). */
|
||||
export declare function hasOpenFileIntegrityAlert(input: {
|
||||
rootKey: string;
|
||||
relativePath: string;
|
||||
issue: string;
|
||||
}): Promise<boolean>;
|
||||
export declare function updateAlertStatus(id: string, status: SecurityAlertStatus, resolvedBy: string | null, resolutionNote?: string): Promise<SecurityAlert | null>;
|
||||
export declare function setAlertEmails(emails: string[]): Promise<void>;
|
||||
export declare function getAlertEmailsDecrypted(): Promise<string[]>;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"securityAlertRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/securityAlertRepository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAI1G,wBAAsB,WAAW,CAAC,KAAK,EAAE;IACvC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,QAAQ,EAAE,qBAAqB,CAAC;IAChC,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,GAAG,OAAO,CAAC,aAAa,CAAC,CAezB;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE;IACrC,MAAM,CAAC,EAAE,mBAAmB,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC;IAAE,KAAK,EAAE,aAAa,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CA0BrD;AAED,wBAAsB,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAGxE;AAED,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,MAAM,EACV,MAAM,EAAE,mBAAmB,EAC3B,UAAU,EAAE,MAAM,GAAG,IAAI,EACzB,cAAc,CAAC,EAAE,MAAM,GACtB,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAgB/B;AAED,wBAAsB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAQpE;AAED,wBAAsB,uBAAuB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAkBjE"}
|
||||
{"version":3,"file":"securityAlertRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/securityAlertRepository.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAI1G,wBAAsB,WAAW,CAAC,KAAK,EAAE;IACv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Property(exports, "__esModule", { value: true });
|
||||
exports.createAlert = createAlert;
|
||||
exports.listAlerts = listAlerts;
|
||||
exports.findById = findById;
|
||||
exports.hasOpenFileIntegrityAlert = hasOpenFileIntegrityAlert;
|
||||
exports.updateAlertStatus = updateAlertStatus;
|
||||
exports.setAlertEmails = setAlertEmails;
|
||||
exports.getAlertEmailsDecrypted = getAlertEmailsDecrypted;
|
||||
@ -78,6 +79,17 @@ async function findById(id) {
|
||||
const rows = await (0, connection_1.query)('SELECT * FROM security_alerts WHERE id = $1', [id]);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
/** True if an open FIM alert already exists for the same root/path/issue (stops alert storms). */
|
||||
async function hasOpenFileIntegrityAlert(input) {
|
||||
const rows = await (0, connection_1.query)(`SELECT id FROM security_alerts
|
||||
WHERE status = 'open'
|
||||
AND alert_type = 'file_integrity_violation'
|
||||
AND metadata->>'rootKey' = $1
|
||||
AND metadata->>'relativePath' = $2
|
||||
AND metadata->>'issue' = $3
|
||||
LIMIT 1`, [input.rootKey, input.relativePath, input.issue]);
|
||||
return Boolean(rows[0]);
|
||||
}
|
||||
async function updateAlertStatus(id, status, resolvedBy, resolutionNote) {
|
||||
const rows = await (0, connection_1.query)(`UPDATE security_alerts
|
||||
SET status = $2::varchar,
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"securityAlertRepository.js","sourceRoot":"","sources":["../../src/repositories/securityAlertRepository.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,kCAsBC;AAED,gCA+BC;AAED,4BAGC;AAED,8CAqBC;AAED,wCAQC;AAED,0DAkBC;AAvHD,iDAAyC;AACzC,4CAAgE;AAGhE,MAAM,yBAAyB,GAAG,iCAAiC,CAAC;AAE7D,KAAK,UAAU,WAAW,CAAC,KAOjC;IACC,MAAM,IAAI,GAAG,MAAM,IAAA,kBAAK,EACtB;;iBAEa,EACb;QACE,KAAK,CAAC,MAAM,IAAI,IAAI;QACpB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EACgE,EAChE,CAAC,yBAAyB,EAAE,SAAS,CAAC,CACvC,CAAC;AACJ,CAAC;AAEM,KAAK,UAAU,uBAAuB;IAC3C,MAAM,IAAI,GAAG,MAAM,IAAA,kBAAK,EACtB,kDAAkD,EAClD,CAAC,yBAAyB,CAAC,CAC5B,CAAC;IACF,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK;QAAE,OAAO,EAAE,CAAC;IAC/B,MAAM,EAAE,gBAAgB,EAAE,GAAG,wDAAa,iBAAiB,GAAC,CAAC;IAC7D,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC1B,IAAI,IAAI,GAAG,GAAG,CAAC;IACf,IAAI,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE,CAAC;QAC9B,IAAI,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IACD,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAClF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
|
||||
{"version":3,"file":"securityAlertRepository.js","sourceRoot":"","sources":["../../src/repositories/securityAlertRepository.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,kCAsBC;AAED,gCA+BC;AAED,4BAGC;AAGD,8DAgBC;AAED,8CAqBC;AAED,wCAQC;AAED,0DAkBC;AA1ID,iDAAyC;AACzC,4CAAgE;AAGhE,MAAM,yBAAyB,GAAG,iCAAiC,CAAC;AAE7D,KAAK,UAAU,WAAW,CAAC,K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AAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC"}
|
||||
2
backend/dist/routes/index.d.ts.map
vendored
2
backend/dist/routes/index.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmIH,QAAA,MAAM,MAAM,4CAAW,CAAC;AA8fxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA+IH,QAAA,MAAM,MAAM,4CAAW,CAAC;AA4nBxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
29
backend/dist/routes/index.js
vendored
29
backend/dist/routes/index.js
vendored
@ -70,6 +70,10 @@ const adminCreditController = __importStar(require("../controllers/adminCreditCo
|
||||
const testWalletController = __importStar(require("../controllers/testWalletController"));
|
||||
const soloEncouragementController = __importStar(require("../controllers/soloEncouragementController"));
|
||||
const shareCardController = __importStar(require("../controllers/shareCardController"));
|
||||
const mobileAppReleaseController = __importStar(require("../controllers/mobileAppReleaseController"));
|
||||
const apkUpload_1 = require("../middleware/apkUpload");
|
||||
const requireSupportedAppVersion_1 = require("../middleware/requireSupportedAppVersion");
|
||||
const mobileReleaseSchemas_1 = require("../validation/mobileReleaseSchemas");
|
||||
const countryController = __importStar(require("../controllers/countryController"));
|
||||
const presenceController = __importStar(require("../controllers/presenceController"));
|
||||
const supportController = __importStar(require("../controllers/supportController"));
|
||||
@ -117,6 +121,10 @@ router.get('/marketing/activity-feed', marketingController.getActivityFeed);
|
||||
router.get('/marketing/withdrawal-feed', marketingController.getWithdrawalFeed);
|
||||
/** Public Share Card verification (HMAC token). */
|
||||
router.get('/share-cards/verify/:token', shareCardController.verifyShareCard);
|
||||
/** Public Android in-app update check / APK download / telemetry (no auth). */
|
||||
router.get('/app-updates/android', (0, validate_1.validateQuery)(mobileReleaseSchemas_1.mobileUpdateCheckQuerySchema), mobileAppReleaseController.checkAndroid);
|
||||
router.get('/app-updates/android/download/:id', (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), mobileAppReleaseController.downloadAndroid);
|
||||
router.post('/app-updates/android/events', optionalAuth_1.optionalAuthMiddleware, (0, validate_1.validateBody)(mobileReleaseSchemas_1.mobileUpdateEventBodySchema), mobileAppReleaseController.postEvent);
|
||||
/** Support messaging — guests (visitor token) and optional authenticated users. */
|
||||
router.get('/support/files/:filename', supportController.getAttachment);
|
||||
router.post('/support/conversations/current', optionalAuth_1.optionalAuthMiddleware, supportController.getOrCreateConversation);
|
||||
@ -159,13 +167,13 @@ router.post('/2fa/setup', authController.setup2FA);
|
||||
router.post('/2fa/enable', (0, validate_1.validateBody)(schemas_1.totpEnableBodySchema), authController.enable2FA);
|
||||
router.post('/2fa/disable', (0, validate_1.validateBody)(schemas_1.totpDisableBodySchema), authController.disable2FA);
|
||||
router.post('/2fa/recovery/regenerate', authController.regenerateRecoveryCodes);
|
||||
router.post('/withdraw', (0, validate_1.validateBody)(schemas_1.withdrawBodySchema), (0, audit_1.auditAction)('withdrawal_requested', 'wallet'), (0, errorHandler_1.asyncHandler)(withdrawalController.withdraw));
|
||||
router.post('/transfer', (0, validate_1.validateBody)(schemas_1.transferBodySchema), (0, audit_1.auditAction)('transfer_requested', 'wallet'), (0, errorHandler_1.asyncHandler)(transferController.transfer));
|
||||
router.post('/withdraw', requireSupportedAppVersion_1.requireSupportedAppVersion, (0, validate_1.validateBody)(schemas_1.withdrawBodySchema), (0, audit_1.auditAction)('withdrawal_requested', 'wallet'), (0, errorHandler_1.asyncHandler)(withdrawalController.withdraw));
|
||||
router.post('/transfer', requireSupportedAppVersion_1.requireSupportedAppVersion, (0, validate_1.validateBody)(schemas_1.transferBodySchema), (0, audit_1.auditAction)('transfer_requested', 'wallet'), (0, errorHandler_1.asyncHandler)(transferController.transfer));
|
||||
router.get('/games/candle-predict/state', candlePredictController.getState);
|
||||
router.get('/games/candle-predict/candles', candlePredictController.getCandles);
|
||||
router.post('/games/candle-predict/bets', (0, validate_1.validateBody)(adminSchemas_1.candlePredictBetBodySchema), candlePredictController.placeBet);
|
||||
router.post('/games/candle-predict/bets', requireSupportedAppVersion_1.requireSupportedAppVersion, (0, validate_1.validateBody)(adminSchemas_1.candlePredictBetBodySchema), candlePredictController.placeBet);
|
||||
router.get('/games/candle-predict/bets/outcome/:idempotencyKey', candlePredictController.getBetOutcome);
|
||||
router.post('/games/candle-predict/bets/multi', (0, validate_1.validateBody)(adminSchemas_1.candlePredictMultiBetBodySchema), candlePredictController.placeMultiBet);
|
||||
router.post('/games/candle-predict/bets/multi', requireSupportedAppVersion_1.requireSupportedAppVersion, (0, validate_1.validateBody)(adminSchemas_1.candlePredictMultiBetBodySchema), candlePredictController.placeMultiBet);
|
||||
router.get('/games/candle-predict/bets/me', candlePredictController.getMyBets);
|
||||
router.get('/games/candle-predict/auto', candlePredictController.getAutoSettings);
|
||||
router.put('/games/candle-predict/auto', (0, validate_1.validateBody)(adminSchemas_1.candlePredictAutoBodySchema), candlePredictController.updateAutoSettings);
|
||||
@ -272,6 +280,19 @@ router.patch('/admin/test-wallet/config', (0, auth_1.requireRoles)('admin'), (0,
|
||||
router.get('/admin/test-wallet/credits', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), testWalletController.listAdminCredits);
|
||||
router.get('/admin/share-cards/settings', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), shareCardController.getAdminSettings);
|
||||
router.patch('/admin/share-cards/settings', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.shareCardSettingsBodySchema), shareCardController.updateAdminSettings);
|
||||
/** Admin — mobile APK release management */
|
||||
router.get('/admin/mobile-releases/stats', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.view'), mobileAppReleaseController.adminStats);
|
||||
router.get('/admin/mobile-update-settings', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.view'), mobileAppReleaseController.adminGetSettings);
|
||||
router.patch('/admin/mobile-update-settings', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateBody)(mobileReleaseSchemas_1.mobileUpdateSettingsBodySchema), mobileAppReleaseController.adminUpdateSettings);
|
||||
router.get('/admin/mobile-releases', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.view'), (0, validate_1.validateQuery)(mobileReleaseSchemas_1.mobileReleaseListQuerySchema), mobileAppReleaseController.adminList);
|
||||
router.post('/admin/mobile-releases', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateBody)(mobileReleaseSchemas_1.mobileReleaseCreateBodySchema), mobileAppReleaseController.adminCreate);
|
||||
router.get('/admin/mobile-releases/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.view'), (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), mobileAppReleaseController.adminGet);
|
||||
router.patch('/admin/mobile-releases/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), (0, validate_1.validateBody)(mobileReleaseSchemas_1.mobileReleaseUpdateBodySchema), mobileAppReleaseController.adminUpdate);
|
||||
router.post('/admin/mobile-releases/:id/apk', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), apkUpload_1.apkUpload.single('file'), mobileAppReleaseController.adminUploadApk);
|
||||
router.post('/admin/mobile-releases/:id/submit', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), mobileAppReleaseController.adminSubmit);
|
||||
router.post('/admin/mobile-releases/:id/publish', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), mobileAppReleaseController.adminPublish);
|
||||
router.post('/admin/mobile-releases/:id/suspend', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), mobileAppReleaseController.adminSuspend);
|
||||
router.post('/admin/mobile-releases/:id/retire', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.mobile_releases.manage'), (0, validate_1.validateParams)(mobileReleaseSchemas_1.mobileReleaseIdParamSchema), mobileAppReleaseController.adminRetire);
|
||||
router.get('/admin/solo-encouragement/config', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.getAdminConfig);
|
||||
router.patch('/admin/solo-encouragement/config', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), (0, validate_1.validateBody)(adminResourceSchemas_1.soloEncouragementConfigBodySchema), soloEncouragementController.updateAdminConfig);
|
||||
router.get('/admin/solo-encouragement/streaks', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('settings.admin'), soloEncouragementController.listActiveStreaks);
|
||||
|
||||
2
backend/dist/routes/index.js.map
vendored
2
backend/dist/routes/index.js.map
vendored
File diff suppressed because one or more lines are too long
3
backend/dist/services/referralService.d.ts
vendored
3
backend/dist/services/referralService.d.ts
vendored
@ -289,6 +289,8 @@ export declare function getProgramSettingsForAdmin(): Promise<{
|
||||
predictionCommissionsEnabled: boolean;
|
||||
minFirstDepositRaw: string;
|
||||
commissionWalletTypeId: number;
|
||||
commissionWalletCode: string;
|
||||
commissionWalletLabel: string;
|
||||
updatedAt: Date;
|
||||
};
|
||||
levels: {
|
||||
@ -298,6 +300,7 @@ export declare function getProgramSettingsForAdmin(): Promise<{
|
||||
monthlyMaxAmountRaw: string;
|
||||
monthlyMaxCount: number;
|
||||
}[];
|
||||
/** @deprecated Kept for older clients — always the single ledger type. */
|
||||
walletTypes: {
|
||||
id: number;
|
||||
code: string;
|
||||
|
||||
File diff suppressed because one or more lines are too long
35
backend/dist/services/referralService.js
vendored
35
backend/dist/services/referralService.js
vendored
@ -1180,13 +1180,19 @@ async function getUserReferralInfo(userId) {
|
||||
};
|
||||
}
|
||||
async function getProgramSettingsForAdmin() {
|
||||
const settings = await referralRepository.getSettings();
|
||||
// Hard-lock: one commission wallet + one bonus pool = unified USDT ledger (USDT_TRC20).
|
||||
const { walletTypeId: commissionWalletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
|
||||
let settings = await referralRepository.getSettings();
|
||||
if (settings.commission_wallet_type_id !== commissionWalletTypeId) {
|
||||
settings = await referralRepository.updateSettings({ commissionWalletTypeId });
|
||||
}
|
||||
const levels = await referralRepository.listLevels();
|
||||
const [pools, walletTypes] = await Promise.all([
|
||||
bonusPoolRepository.listPools(),
|
||||
bonusPoolRepository.listCommissionPools(),
|
||||
walletRepository.getWalletTypes(),
|
||||
]);
|
||||
const walletTypeById = new Map(walletTypes.map((wt) => [wt.id, wt]));
|
||||
const ledgerWt = walletTypeById.get(commissionWalletTypeId);
|
||||
const formatWalletLabel = (wt) => `${wt.name} (${wt.code}${wt.network ? ` · ${wt.network}` : ''})`;
|
||||
return {
|
||||
settings: {
|
||||
@ -1210,7 +1216,11 @@ async function getProgramSettingsForAdmin() {
|
||||
withdrawalCommissionsEnabled: settings.withdrawal_commissions_enabled,
|
||||
predictionCommissionsEnabled: settings.prediction_commissions_enabled,
|
||||
minFirstDepositRaw: settings.min_first_deposit_raw,
|
||||
commissionWalletTypeId: settings.commission_wallet_type_id,
|
||||
commissionWalletTypeId,
|
||||
commissionWalletCode: ledgerWt?.code ?? 'USDT_TRC20',
|
||||
commissionWalletLabel: ledgerWt
|
||||
? formatWalletLabel(ledgerWt)
|
||||
: 'USDT (TRC20) · unified ledger',
|
||||
updatedAt: settings.updated_at,
|
||||
},
|
||||
levels: levels.map((l) => ({
|
||||
@ -1220,13 +1230,18 @@ async function getProgramSettingsForAdmin() {
|
||||
monthlyMaxAmountRaw: l.monthly_max_amount_raw,
|
||||
monthlyMaxCount: l.monthly_max_count,
|
||||
})),
|
||||
walletTypes: walletTypes.map((wt) => ({
|
||||
id: wt.id,
|
||||
code: wt.code,
|
||||
name: wt.name,
|
||||
network: wt.network,
|
||||
label: formatWalletLabel(wt),
|
||||
})),
|
||||
/** @deprecated Kept for older clients — always the single ledger type. */
|
||||
walletTypes: ledgerWt
|
||||
? [
|
||||
{
|
||||
id: ledgerWt.id,
|
||||
code: ledgerWt.code,
|
||||
name: ledgerWt.name,
|
||||
network: ledgerWt.network,
|
||||
label: formatWalletLabel(ledgerWt),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
pools: pools.map((p) => {
|
||||
const wt = walletTypeById.get(p.wallet_type_id);
|
||||
return {
|
||||
|
||||
2
backend/dist/services/referralService.js.map
vendored
2
backend/dist/services/referralService.js.map
vendored
File diff suppressed because one or more lines are too long
6
backend/dist/tests/redisRealtime.test.js
vendored
6
backend/dist/tests/redisRealtime.test.js
vendored
@ -65,5 +65,11 @@ const pubsub_1 = require("../realtime/redis/pubsub");
|
||||
const parsed = (0, pubsub_1.parseRealtimeEvent)(raw);
|
||||
strict_1.default.deepEqual(parsed, event);
|
||||
});
|
||||
(0, node_test_1.test)('normalizes missing payload to empty object (avoids WS crash)', () => {
|
||||
const parsed = (0, pubsub_1.parseRealtimeEvent)(JSON.stringify({ type: 'round.updated', intervalMinutes: 1, ts: 1 }));
|
||||
strict_1.default.ok(parsed);
|
||||
strict_1.default.equal(parsed.type, 'round.updated');
|
||||
strict_1.default.deepEqual(parsed.payload, {});
|
||||
});
|
||||
});
|
||||
//# sourceMappingURL=redisRealtime.test.js.map
|
||||
2
backend/dist/tests/redisRealtime.test.js.map
vendored
2
backend/dist/tests/redisRealtime.test.js.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"redisRealtime.test.js","sourceRoot":"","sources":["../../src/tests/redisRealtime.test.ts"],"names":[],"mappings":";;;;;AAAA,yCAA2C;AAC3C,gEAAwC;AAExC,iDAAmD;AACnD,6DAGsC;AACtC,2DAGqC;AACrC,qDAGkC;AAElC,IAAA,oBAAQ,EAAC,WAAW,EAAE,GAAG,EAAE;IACzB,IAAA,gBAAI,EAAC,yBAAyB,EAAE,GAAG,EAAE;QACnC,gBAAM,CAAC,KAAK,CAAC,gBAAS,CAAC,MAAM,EAAE,EAAE,mBAAmB,CAAC,CAAC;QACtD,gBAAM,CAAC,KAAK,CAAC,gBAAS,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,EAAE,mCAAmC,CAAC,CAAC;QACrF,gBAAM,CAAC,KAAK,CAAC,gBAAS,CAAC,KAAK,CAAC,CAAC,EAAE,aAAa,CAAC,EAAE,mCAAmC,CAAC,CAAC;QACrF,gBAAM,CAAC,KAAK,CAAC,gBAAS,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,4BAA4B,CAAC,CAAC;QACrE,gBAAM,CAAC,KAAK,CAAC,gBAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,+BAA+B,CAAC,CAAC;IAChF,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,IAAA,oBAAQ,EAAC,0BAA0B,EAAE,GAAG,EAAE;IACxC,IAAA,gBAAI,EAAC,uBAAuB,EAAE,GAAG,EAAE;QACjC,MAAM,GAAG,GAAG;YACV,EAAE,EAAE,SAAS;YACb,YAAY,EAAE,aAAa;YAC3B,aAAa,EAAE,aAAa;YAC5B,eAAe,EAAE,CAAC;YAClB,MAAM,EAAE,SAAS;YACjB,OAA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AAE;YAC9B,OAAO,EAAE,CAAC;YACV,EAAE,EAAE,aAAa;SAClB,CAAC;QACF,MAAM,GAAG,GAAG,IAAA,+BAAsB,EAAC,KAAK,CAAC,CAAC;QAC1C,MAAM,MAAM,GAAG,IAAA,2BAAkB,EAAC,GAAG,CAAC,CAAC;QACvC,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAClC,CAAC,CAAC,CAAC;IAEH,IAAA,gBAAI,EAAC,8DAA8D,EAAE,GAAG,EAAE;QACxE,MAAM,MAAM,GAAG,IAAA,2BAAkB,EAC/B,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,eAAe,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,CACrE,CAAC;QACF,gBAAM,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC;QAClB,gBAAM,CAAC,KAAK,CAAC,MAAO,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;QAC5C,gBAAM,CAAC,SAAS,CAAC,MAAO,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACxC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
|
||||
256
backend/package-lock.json
generated
256
backend/package-lock.json
generated
@ -9,6 +9,8 @@
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@sentry/node": "^9.47.1",
|
||||
"adm-zip": "^0.6.1",
|
||||
"app-info-parser": "^1.1.6",
|
||||
"argon2": "^0.31.2",
|
||||
"bcrypt": "^5.1.1",
|
||||
"bip39": "^3.1.0",
|
||||
@ -22,6 +24,7 @@
|
||||
"ioredis": "^5.11.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^2.2.0",
|
||||
"node-forge": "^1.4.2",
|
||||
"nodemailer": "^9.0.1",
|
||||
"otplib": "^12.0.1",
|
||||
"pdfkit": "^0.19.1",
|
||||
@ -36,6 +39,7 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "^0.5.8",
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^4.17.21",
|
||||
@ -43,6 +47,7 @@
|
||||
"@types/jsonwebtoken": "^9.0.5",
|
||||
"@types/multer": "^2.1.0",
|
||||
"@types/node": "^20.10.4",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"@types/pdfkit": "^0.17.6",
|
||||
"@types/pdfmake": "^0.3.3",
|
||||
@ -1456,6 +1461,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/adm-zip": {
|
||||
"version": "0.5.8",
|
||||
"resolved": "https://registry.npmjs.org/@types/adm-zip/-/adm-zip-0.5.8.tgz",
|
||||
"integrity": "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/bcrypt": {
|
||||
"version": "5.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/bcrypt/-/bcrypt-5.0.2.tgz",
|
||||
@ -1603,6 +1618,16 @@
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node-forge": {
|
||||
"version": "1.3.14",
|
||||
"resolved": "https://registry.npmjs.org/@types/node-forge/-/node-forge-1.3.14.tgz",
|
||||
"integrity": "sha512-mhVF2BnD4BO+jtOp7z1CdzaK4mbuK0LLQYAvdOLqHTavxFNq4zA1EmYkpnFjP8HOUzedfQkRnp0E2ulSAYSzAw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/nodemailer": {
|
||||
"version": "8.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.1.tgz",
|
||||
@ -1791,6 +1816,15 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@xmldom/xmldom": {
|
||||
"version": "0.9.12",
|
||||
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.12.tgz",
|
||||
"integrity": "sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.6"
|
||||
}
|
||||
},
|
||||
"node_modules/abbrev": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
|
||||
@ -1853,6 +1887,15 @@
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/adm-zip": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.6.1.tgz",
|
||||
"integrity": "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0"
|
||||
}
|
||||
},
|
||||
"node_modules/aes-js": {
|
||||
"version": "4.0.0-beta.5",
|
||||
"resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz",
|
||||
@ -1932,6 +1975,23 @@
|
||||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/app-info-parser": {
|
||||
"version": "1.1.6",
|
||||
"resolved": "https://registry.npmjs.org/app-info-parser/-/app-info-parser-1.1.6.tgz",
|
||||
"integrity": "sha512-ZAFCM0bN88cbpsMoRhL/JfdX3b+nb5iBEXcu30xABvbaqtw6tXfHujDnuKSpNmA3P0uwpkIxTV/Wun5HfEch8A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bplist-parser": "^0.2.0",
|
||||
"bytebuffer": "^5.0.1",
|
||||
"cgbi-to-png": "^1.0.7",
|
||||
"commander": "^7.2.0",
|
||||
"isomorphic-unzip": "^1.1.5",
|
||||
"plist": "^3.0.1"
|
||||
},
|
||||
"bin": {
|
||||
"app-info-parser": "bin/index.js"
|
||||
}
|
||||
},
|
||||
"node_modules/append-field": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
|
||||
@ -2065,6 +2125,15 @@
|
||||
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/big-integer": {
|
||||
"version": "1.6.52",
|
||||
"resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",
|
||||
"integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",
|
||||
"license": "Unlicense",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/bignumber.js": {
|
||||
"version": "9.3.1",
|
||||
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",
|
||||
@ -2126,6 +2195,18 @@
|
||||
"npm": "1.2.8000 || >= 1.4.16"
|
||||
}
|
||||
},
|
||||
"node_modules/bplist-parser": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.2.0.tgz",
|
||||
"integrity": "sha512-z0M+byMThzQmD9NILRniCUXYsYpjwnlO8N5uCFaCqIOpqRsJCrQL9NK3JsD67CN5a08nF5oIL2bD6loTdHOuKw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"big-integer": "^1.6.44"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 5.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.12",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
|
||||
@ -2173,6 +2254,30 @@
|
||||
"pako": "~1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer": {
|
||||
"version": "5.7.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
|
||||
"integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"base64-js": "^1.3.1",
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-crc32": {
|
||||
"version": "0.2.13",
|
||||
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
|
||||
@ -2194,6 +2299,14 @@
|
||||
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bufferpack": {
|
||||
"version": "0.0.6",
|
||||
"resolved": "https://registry.npmjs.org/bufferpack/-/bufferpack-0.0.6.tgz",
|
||||
"integrity": "sha512-MTWvLHElqczrIVhge9qHtqgNigJFyh0+tCDId5yCbFAfuekHWIG+uAgvoHVflwrDPuY/e47JE1ki5qcM7w4uLg==",
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/busboy": {
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
|
||||
@ -2205,6 +2318,18 @@
|
||||
"node": ">=10.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/bytebuffer": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/bytebuffer/-/bytebuffer-5.0.1.tgz",
|
||||
"integrity": "sha512-IuzSdmADppkZ6DlpycMkm8l9zeEq16fWtLvunEwFiYciR/BHo4E8/xs5piFquG+Za8OWmMqHF8zuRviz2LHvRQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"long": "~3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/bytes": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
|
||||
@ -2265,6 +2390,18 @@
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/cgbi-to-png": {
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/cgbi-to-png/-/cgbi-to-png-1.0.7.tgz",
|
||||
"integrity": "sha512-YR80kxTPuq9oRpZUdQmNEQWrmTKLINk1cfLVfyrV7Rfr9KLtLJdcockPKbreIr4JYAq+DhHBR7w+WA/tF5VDaQ==",
|
||||
"license": "mit",
|
||||
"dependencies": {
|
||||
"bufferpack": "0.0.6",
|
||||
"crc": "^3.3.0",
|
||||
"stream-to-buffer": "^0.1.0",
|
||||
"streamifier": "^0.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/chalk": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||
@ -2398,6 +2535,15 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/commander": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
|
||||
"integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/component-emitter": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.1.tgz",
|
||||
@ -2495,6 +2641,15 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/crc": {
|
||||
"version": "3.8.0",
|
||||
"resolved": "https://registry.npmjs.org/crc/-/crc-3.8.0.tgz",
|
||||
"integrity": "sha512-iX3mfgcTMIq3ZKLIsVFAbv7+Mc10kxabAGQb8HvjA1o3T1PIYprbakQ65d3I+2HGHt6nSKkM9PYjgoJO2KcFBQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer": "^5.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/crc-32": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
|
||||
@ -3622,6 +3777,26 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ieee754": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
|
||||
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/feross"
|
||||
},
|
||||
{
|
||||
"type": "patreon",
|
||||
"url": "https://www.patreon.com/feross"
|
||||
},
|
||||
{
|
||||
"type": "consulting",
|
||||
"url": "https://feross.org/support"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/import-in-the-middle": {
|
||||
"version": "1.15.0",
|
||||
"resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-1.15.0.tgz",
|
||||
@ -3811,6 +3986,16 @@
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/isomorphic-unzip": {
|
||||
"version": "1.1.5",
|
||||
"resolved": "https://registry.npmjs.org/isomorphic-unzip/-/isomorphic-unzip-1.1.5.tgz",
|
||||
"integrity": "sha512-2McA51lWhmO3Kk438jxVcYeh6L+AOqVnl9XdX1yI7GlLA9RwEyTBgGem1rNuRIU2abAmOiv+IagThdUxASY4IA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer": "^5.0.7",
|
||||
"yauzl": "^2.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/js-md5": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/js-md5/-/js-md5-0.8.3.tgz",
|
||||
@ -3975,6 +4160,15 @@
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/long": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/long/-/long-3.2.0.tgz",
|
||||
"integrity": "sha512-ZYvPPOMqUwPoDsbJaR10iQJYnMuZhRTvHYl62ErLIEX7RgFlziSBUUvrt3OVfc47QlHHpzPZYP17g3Fv7oeJkg==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/make-dir": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
|
||||
@ -4239,6 +4433,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/node-forge": {
|
||||
"version": "1.4.2",
|
||||
"resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.2.tgz",
|
||||
"integrity": "sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==",
|
||||
"license": "(BSD-3-Clause OR GPL-2.0)",
|
||||
"engines": {
|
||||
"node": ">= 6.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/nodemailer": {
|
||||
"version": "9.0.1",
|
||||
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-9.0.1.tgz",
|
||||
@ -4578,6 +4781,20 @@
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/plist": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz",
|
||||
"integrity": "sha512-ZIfcLJC+7E7FBFnDxm9MPmt7D+DidyQ26lewieO75AdhA2ayMtsJSES0iWzqJQbcVRSrTufQoy0DR94xHue0oA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@xmldom/xmldom": "^0.9.10",
|
||||
"base64-js": "^1.5.1",
|
||||
"xmlbuilder": "^15.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/png-js": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/png-js/-/png-js-1.1.0.tgz",
|
||||
@ -5185,6 +5402,36 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/stream-to": {
|
||||
"version": "0.2.2",
|
||||
"resolved": "https://registry.npmjs.org/stream-to/-/stream-to-0.2.2.tgz",
|
||||
"integrity": "sha512-Kg1BSDTwgGiVMtTCJNlo7kk/xzL33ZuZveEBRt6rXw+f1WLK/8kmz2NVCT/Qnv0JkV85JOHcLhD82mnXsR3kPw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/stream-to-buffer": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/stream-to-buffer/-/stream-to-buffer-0.1.0.tgz",
|
||||
"integrity": "sha512-Da4WoKaZyu3nf+bIdIifh7IPkFjARBnBK+pYqn0EUJqksjV9afojjaCCHUemH30Jmu7T2qcKvlZm2ykN38uzaw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"stream-to": "~0.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/streamifier": {
|
||||
"version": "0.1.1",
|
||||
"resolved": "https://registry.npmjs.org/streamifier/-/streamifier-0.1.1.tgz",
|
||||
"integrity": "sha512-zDgl+muIlWzXNsXeyUfOk9dChMjlpkq0DRsxujtYPgyJ676yQ8jEm6zzaaWHFDg5BNcLuif0eD2MTyJdZqXpdg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10"
|
||||
}
|
||||
},
|
||||
"node_modules/streamsearch": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
|
||||
@ -5822,6 +6069,15 @@
|
||||
"node": ">=0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/xmlbuilder": {
|
||||
"version": "15.1.1",
|
||||
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
|
||||
"integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/xmldoc": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/xmldoc/-/xmldoc-2.0.3.tgz",
|
||||
|
||||
@ -51,6 +51,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@sentry/node": "^9.47.1",
|
||||
"adm-zip": "^0.6.1",
|
||||
"app-info-parser": "^1.1.6",
|
||||
"argon2": "^0.31.2",
|
||||
"bcrypt": "^5.1.1",
|
||||
"bip39": "^3.1.0",
|
||||
@ -64,6 +66,7 @@
|
||||
"ioredis": "^5.11.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^2.2.0",
|
||||
"node-forge": "^1.4.2",
|
||||
"nodemailer": "^9.0.1",
|
||||
"otplib": "^12.0.1",
|
||||
"pdfkit": "^0.19.1",
|
||||
@ -78,6 +81,7 @@
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "^0.5.8",
|
||||
"@types/bcrypt": "^5.0.2",
|
||||
"@types/cors": "^2.8.17",
|
||||
"@types/express": "^4.17.21",
|
||||
@ -85,6 +89,7 @@
|
||||
"@types/jsonwebtoken": "^9.0.5",
|
||||
"@types/multer": "^2.1.0",
|
||||
"@types/node": "^20.10.4",
|
||||
"@types/node-forge": "^1.3.14",
|
||||
"@types/nodemailer": "^8.0.1",
|
||||
"@types/pdfkit": "^0.17.6",
|
||||
"@types/pdfmake": "^0.3.3",
|
||||
|
||||
@ -298,4 +298,16 @@ export const config = {
|
||||
port: parseInt(process.env.CLAMAV_PORT || '3310', 10),
|
||||
timeoutMs: readEnvInt('CLAMAV_TIMEOUT_MS', 30_000, 5000, 120_000),
|
||||
},
|
||||
mobileReleases: {
|
||||
/** Expected Android signing certificate SHA-256 (hex, no colons). Empty = skip cert check (dev only). */
|
||||
expectedCertSha256: (process.env.ANDROID_APK_EXPECTED_CERT_SHA256 || '').trim().toLowerCase().replace(/:/g, ''),
|
||||
expectedPackage: (process.env.ANDROID_APK_EXPECTED_PACKAGE || 'com.prediqo.mobile').trim(),
|
||||
maxUploadBytes: readEnvInt('APK_MAX_UPLOAD_BYTES', 120 * 1024 * 1024, 1_000_000, 300 * 1024 * 1024),
|
||||
/** HMAC secret for short-lived download tokens (falls back to JWT secret). */
|
||||
downloadTokenSecret:
|
||||
process.env.APK_DOWNLOAD_TOKEN_SECRET ||
|
||||
process.env.JWT_SECRET ||
|
||||
'change-me-in-production',
|
||||
downloadTokenTtlSeconds: readEnvInt('APK_DOWNLOAD_TOKEN_TTL_SECONDS', 3600, 60, 86_400),
|
||||
},
|
||||
};
|
||||
|
||||
211
backend/src/controllers/mobileAppReleaseController.ts
Normal file
211
backend/src/controllers/mobileAppReleaseController.ts
Normal file
@ -0,0 +1,211 @@
|
||||
/**
|
||||
* HTTP handlers for mobile app release admin + public update check/download.
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import { Response } from 'express';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
import * as mobileAppReleaseService from '../services/mobileAppReleaseService';
|
||||
import { MobileReleaseError } from '../services/mobileAppReleaseService';
|
||||
|
||||
function sendError(res: Response, e: unknown, fallback: string): void {
|
||||
if (e instanceof MobileReleaseError || (e instanceof Error && 'statusCode' in e)) {
|
||||
const err = e as { statusCode?: number; message: string; code?: string };
|
||||
res.status(err.statusCode ?? 400).json({ error: err.message, ...(err.code ? { code: err.code } : {}) });
|
||||
return;
|
||||
}
|
||||
console.error(e);
|
||||
res.status(500).json({ error: e instanceof Error ? e.message : fallback });
|
||||
}
|
||||
|
||||
export async function checkAndroid(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const q = req.query as unknown as {
|
||||
versionCode: number;
|
||||
versionName?: string;
|
||||
channel?: 'production' | 'beta' | 'internal';
|
||||
deviceId: string;
|
||||
};
|
||||
const result = await mobileAppReleaseService.checkAndroidUpdate({
|
||||
versionCode: Number(q.versionCode),
|
||||
versionName: q.versionName,
|
||||
channel: q.channel,
|
||||
deviceId: q.deviceId,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Update check failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadAndroid(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const id = String(req.params.id || '');
|
||||
const token = String(req.query.token || '');
|
||||
const { release, absolutePath } = await mobileAppReleaseService.openDownloadStream(id, token);
|
||||
const stat = fs.statSync(absolutePath);
|
||||
res.setHeader('Content-Type', 'application/vnd.android.package-archive');
|
||||
res.setHeader('Content-Length', String(stat.size));
|
||||
res.setHeader('Content-Disposition', `attachment; filename="tloto-${release.versionName}.apk"`);
|
||||
res.setHeader('X-Content-SHA256', release.sha256 || '');
|
||||
res.setHeader('Accept-Ranges', 'bytes');
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
|
||||
|
||||
const range = req.headers.range;
|
||||
if (range) {
|
||||
const match = /^bytes=(\d+)-(\d*)$/.exec(range);
|
||||
if (match) {
|
||||
const start = parseInt(match[1], 10);
|
||||
const end = match[2] ? parseInt(match[2], 10) : stat.size - 1;
|
||||
if (start >= 0 && end < stat.size && start <= end) {
|
||||
res.status(206);
|
||||
res.setHeader('Content-Range', `bytes ${start}-${end}/${stat.size}`);
|
||||
res.setHeader('Content-Length', String(end - start + 1));
|
||||
fs.createReadStream(absolutePath, { start, end }).pipe(res);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fs.createReadStream(absolutePath).pipe(res);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Download failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function postEvent(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const body = req.body as {
|
||||
eventType: 'download_start' | 'download_ok' | 'download_fail' | 'install_confirm';
|
||||
releaseId?: string;
|
||||
versionCode?: number;
|
||||
deviceId?: string;
|
||||
channel?: 'production' | 'beta' | 'internal';
|
||||
};
|
||||
await mobileAppReleaseService.recordClientEvent({
|
||||
...body,
|
||||
userId: req.user?.userId ?? null,
|
||||
});
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Event failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminList(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const q = req.query as Record<string, string | undefined>;
|
||||
const result = await mobileAppReleaseService.listReleases({
|
||||
platform: q.platform as 'android' | undefined,
|
||||
channel: q.channel as 'production' | undefined,
|
||||
status: q.status as 'draft' | undefined,
|
||||
search: q.search,
|
||||
limit: q.limit ? Number(q.limit) : undefined,
|
||||
offset: q.offset ? Number(q.offset) : undefined,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'List failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminGet(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const release = await mobileAppReleaseService.getRelease(String(req.params.id));
|
||||
res.json(release);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Get failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminCreate(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const release = await mobileAppReleaseService.createRelease({
|
||||
...req.body,
|
||||
createdBy: req.user?.userId ?? null,
|
||||
});
|
||||
res.status(201).json(release);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Create failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminUpdate(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const release = await mobileAppReleaseService.updateReleaseMeta(String(req.params.id), req.body);
|
||||
res.json(release);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Update failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminUploadApk(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
const file = req.file;
|
||||
if (!file?.path) {
|
||||
res.status(400).json({ error: 'APK file is required (field name: file)' });
|
||||
return;
|
||||
}
|
||||
const release = await mobileAppReleaseService.attachApk(String(req.params.id), file.path);
|
||||
res.json(release);
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Upload failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminSubmit(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await mobileAppReleaseService.submitForValidation(String(req.params.id)));
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Submit failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminPublish(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await mobileAppReleaseService.publish(String(req.params.id)));
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Publish failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminSuspend(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await mobileAppReleaseService.suspend(String(req.params.id)));
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Suspend failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminRetire(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await mobileAppReleaseService.retire(String(req.params.id)));
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Retire failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminStats(_req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await mobileAppReleaseService.getStats());
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Stats failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminGetSettings(_req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await mobileAppReleaseService.getSettings());
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Settings failed');
|
||||
}
|
||||
}
|
||||
|
||||
export async function adminUpdateSettings(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
res.json(await mobileAppReleaseService.updateSettings(req.body));
|
||||
} catch (e) {
|
||||
sendError(res, e, 'Settings update failed');
|
||||
}
|
||||
}
|
||||
@ -2913,3 +2913,70 @@ VALUES
|
||||
('i2***g1', TRUE, 19),
|
||||
('j8***h6', TRUE, 20)
|
||||
ON CONFLICT (public_id) DO NOTHING;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Mobile app releases (Android APK distribution)
|
||||
-- ---------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mobile_app_update_settings (
|
||||
id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||
min_supported_version_code INT NOT NULL DEFAULT 1 CHECK (min_supported_version_code >= 1),
|
||||
check_interval_seconds INT NOT NULL DEFAULT 21600 CHECK (check_interval_seconds >= 60 AND check_interval_seconds <= 604800),
|
||||
expected_package_name TEXT NOT NULL DEFAULT 'com.prediqo.mobile',
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
INSERT INTO mobile_app_update_settings (id)
|
||||
VALUES (1)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mobile_app_releases (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
platform TEXT NOT NULL DEFAULT 'android' CHECK (platform IN ('android', 'ios')),
|
||||
channel TEXT NOT NULL DEFAULT 'production' CHECK (channel IN ('production', 'beta', 'internal')),
|
||||
version_name TEXT NOT NULL,
|
||||
version_code INT NOT NULL CHECK (version_code >= 1),
|
||||
package_name TEXT,
|
||||
previous_version_name TEXT,
|
||||
whats_new TEXT NOT NULL DEFAULT '',
|
||||
bug_fixes TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'draft'
|
||||
CHECK (status IN ('draft', 'pending_validation', 'published', 'suspended', 'retired')),
|
||||
update_policy TEXT NOT NULL DEFAULT 'optional'
|
||||
CHECK (update_policy IN ('optional', 'recommended', 'mandatory')),
|
||||
rollout_percent INT NOT NULL DEFAULT 100 CHECK (rollout_percent >= 0 AND rollout_percent <= 100),
|
||||
storage_key TEXT,
|
||||
file_size_bytes BIGINT,
|
||||
sha256 TEXT,
|
||||
signing_cert_sha256 TEXT,
|
||||
published_at TIMESTAMPTZ,
|
||||
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
download_count BIGINT NOT NULL DEFAULT 0,
|
||||
download_fail_count BIGINT NOT NULL DEFAULT 0,
|
||||
install_confirm_count BIGINT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
UNIQUE (platform, channel, version_code)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mobile_app_releases_lookup
|
||||
ON mobile_app_releases (platform, channel, status, version_code DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mobile_app_release_events (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
release_id UUID REFERENCES mobile_app_releases(id) ON DELETE SET NULL,
|
||||
event_type TEXT NOT NULL
|
||||
CHECK (event_type IN ('check', 'download_start', 'download_ok', 'download_fail', 'install_confirm')),
|
||||
platform TEXT NOT NULL DEFAULT 'android',
|
||||
channel TEXT NOT NULL DEFAULT 'production',
|
||||
client_version_code INT,
|
||||
device_id_hash TEXT,
|
||||
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
meta JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mobile_app_release_events_release
|
||||
ON mobile_app_release_events (release_id, event_type, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_mobile_app_release_events_created
|
||||
ON mobile_app_release_events (created_at DESC);
|
||||
|
||||
38
backend/src/middleware/apkUpload.ts
Normal file
38
backend/src/middleware/apkUpload.ts
Normal file
@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Multer middleware for Android APK uploads into the staging directory.
|
||||
*/
|
||||
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { ensureApkStagingDir, getApkMaxUploadBytes } from '../services/apkStorageService';
|
||||
|
||||
const APK_MIMES = new Set([
|
||||
'application/vnd.android.package-archive',
|
||||
'application/octet-stream',
|
||||
'application/zip',
|
||||
'application/java-archive',
|
||||
]);
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination(_req, _file, cb) {
|
||||
cb(null, ensureApkStagingDir());
|
||||
},
|
||||
filename(_req, file, cb) {
|
||||
const ext = path.extname(file.originalname).toLowerCase() === '.apk' ? '.apk' : '.apk';
|
||||
cb(null, `${uuidv4()}${ext}`);
|
||||
},
|
||||
});
|
||||
|
||||
export const apkUpload = multer({
|
||||
storage,
|
||||
limits: { fileSize: getApkMaxUploadBytes(), files: 1 },
|
||||
fileFilter(_req, file, cb) {
|
||||
const extOk = path.extname(file.originalname).toLowerCase() === '.apk';
|
||||
if (extOk || APK_MIMES.has(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error('Only .apk files are allowed'));
|
||||
}
|
||||
},
|
||||
});
|
||||
48
backend/src/middleware/requireSupportedAppVersion.ts
Normal file
48
backend/src/middleware/requireSupportedAppVersion.ts
Normal file
@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Blocks sensitive mobile API calls when the client app version is below
|
||||
* min_supported or behind a published mandatory release (HTTP 426).
|
||||
* Web clients without X-Tloto-App-Version-Code are not gated.
|
||||
*/
|
||||
|
||||
import { Response, NextFunction } from 'express';
|
||||
import { AuthRequest } from './auth';
|
||||
import * as mobileAppReleaseService from '../services/mobileAppReleaseService';
|
||||
|
||||
function parseVersionCode(req: AuthRequest): number | null {
|
||||
const raw = req.get('x-tloto-app-version-code') || req.get('X-Tloto-App-Version-Code');
|
||||
if (!raw) return null;
|
||||
const n = parseInt(raw, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
export async function requireSupportedAppVersion(
|
||||
req: AuthRequest,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<void> {
|
||||
try {
|
||||
const platform = (req.get('x-tloto-platform') || '').toLowerCase();
|
||||
// Only enforce for Android clients that send the header.
|
||||
if (platform && platform !== 'android') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const versionCode = parseVersionCode(req);
|
||||
if (versionCode == null) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const gate = await mobileAppReleaseService.evaluateClientVersionGate(versionCode);
|
||||
if (gate.allowed) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
res.status(426).json({
|
||||
error: 'App update required',
|
||||
code: 'APP_UPDATE_REQUIRED',
|
||||
update: gate.update,
|
||||
});
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
}
|
||||
64
backend/src/models/mobileAppRelease.model.ts
Normal file
64
backend/src/models/mobileAppRelease.model.ts
Normal file
@ -0,0 +1,64 @@
|
||||
/** Mobile app release domain types (Android APK distribution). */
|
||||
|
||||
export type MobilePlatform = 'android' | 'ios';
|
||||
export type MobileChannel = 'production' | 'beta' | 'internal';
|
||||
export type MobileReleaseStatus =
|
||||
| 'draft'
|
||||
| 'pending_validation'
|
||||
| 'published'
|
||||
| 'suspended'
|
||||
| 'retired';
|
||||
export type MobileUpdatePolicy = 'optional' | 'recommended' | 'mandatory';
|
||||
export type MobileReleaseEventType =
|
||||
| 'check'
|
||||
| 'download_start'
|
||||
| 'download_ok'
|
||||
| 'download_fail'
|
||||
| 'install_confirm';
|
||||
|
||||
export type MobileAppRelease = {
|
||||
id: string;
|
||||
platform: MobilePlatform;
|
||||
channel: MobileChannel;
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
packageName: string | null;
|
||||
previousVersionName: string | null;
|
||||
whatsNew: string;
|
||||
bugFixes: string;
|
||||
status: MobileReleaseStatus;
|
||||
updatePolicy: MobileUpdatePolicy;
|
||||
rolloutPercent: number;
|
||||
storageKey: string | null;
|
||||
fileSizeBytes: number | null;
|
||||
sha256: string | null;
|
||||
signingCertSha256: string | null;
|
||||
publishedAt: Date | null;
|
||||
createdBy: string | null;
|
||||
downloadCount: number;
|
||||
downloadFailCount: number;
|
||||
installConfirmCount: number;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type MobileAppUpdateSettings = {
|
||||
id: number;
|
||||
minSupportedVersionCode: number;
|
||||
checkIntervalSeconds: number;
|
||||
expectedPackageName: string;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
export type MobileAppReleaseEvent = {
|
||||
id: string;
|
||||
releaseId: string | null;
|
||||
eventType: MobileReleaseEventType;
|
||||
platform: MobilePlatform;
|
||||
channel: MobileChannel;
|
||||
clientVersionCode: number | null;
|
||||
deviceIdHash: string | null;
|
||||
userId: string | null;
|
||||
meta: Record<string, unknown>;
|
||||
createdAt: Date;
|
||||
};
|
||||
@ -206,6 +206,10 @@ export const PERMISSION_CATALOG: PermissionDef[] = [
|
||||
p('solo_encouragement', 'view', 'View solo encouragement settings', 'solo_encouragement', ['games.admin']),
|
||||
p('solo_encouragement', 'edit', 'Edit solo encouragement settings', 'solo_encouragement', ['games.admin']),
|
||||
|
||||
// Mobile APK release management
|
||||
p('mobile_releases', 'view', 'View mobile app versions', 'mobile_releases', ['settings.admin']),
|
||||
p('mobile_releases', 'manage', 'Publish and manage mobile APK releases', 'mobile_releases', ['settings.admin']),
|
||||
|
||||
// RBAC self-management
|
||||
p('rbac', 'view', 'View roles and permissions', 'rbac', ['user.manage_roles']),
|
||||
p('rbac', 'manage', 'Create and edit custom roles', 'rbac', ['user.manage_roles']),
|
||||
@ -251,6 +255,8 @@ export const DEFAULT_ADMIN_PERMISSION_KEYS = [
|
||||
'admin.share_cards.edit',
|
||||
'admin.solo_encouragement.view',
|
||||
'admin.solo_encouragement.edit',
|
||||
'admin.mobile_releases.view',
|
||||
'admin.mobile_releases.manage',
|
||||
'admin.rbac.view',
|
||||
'admin.rbac.manage',
|
||||
];
|
||||
|
||||
397
backend/src/repositories/mobileAppReleaseRepository.ts
Normal file
397
backend/src/repositories/mobileAppReleaseRepository.ts
Normal file
@ -0,0 +1,397 @@
|
||||
/**
|
||||
* Persistence for mobile app releases, settings, and telemetry events.
|
||||
*/
|
||||
|
||||
import { query } from '../db/connection';
|
||||
import type {
|
||||
MobileAppRelease,
|
||||
MobileAppUpdateSettings,
|
||||
MobileChannel,
|
||||
MobilePlatform,
|
||||
MobileReleaseEventType,
|
||||
MobileReleaseStatus,
|
||||
MobileUpdatePolicy,
|
||||
} from '../models/mobileAppRelease.model';
|
||||
|
||||
type ReleaseRow = {
|
||||
id: string;
|
||||
platform: MobilePlatform;
|
||||
channel: MobileChannel;
|
||||
version_name: string;
|
||||
version_code: number;
|
||||
package_name: string | null;
|
||||
previous_version_name: string | null;
|
||||
whats_new: string;
|
||||
bug_fixes: string;
|
||||
status: MobileReleaseStatus;
|
||||
update_policy: MobileUpdatePolicy;
|
||||
rollout_percent: number;
|
||||
storage_key: string | null;
|
||||
file_size_bytes: string | number | null;
|
||||
sha256: string | null;
|
||||
signing_cert_sha256: string | null;
|
||||
published_at: Date | null;
|
||||
created_by: string | null;
|
||||
download_count: string | number;
|
||||
download_fail_count: string | number;
|
||||
install_confirm_count: string | number;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
};
|
||||
|
||||
function mapRelease(row: ReleaseRow): MobileAppRelease {
|
||||
return {
|
||||
id: row.id,
|
||||
platform: row.platform,
|
||||
channel: row.channel,
|
||||
versionName: row.version_name,
|
||||
versionCode: Number(row.version_code),
|
||||
packageName: row.package_name,
|
||||
previousVersionName: row.previous_version_name,
|
||||
whatsNew: row.whats_new,
|
||||
bugFixes: row.bug_fixes,
|
||||
status: row.status,
|
||||
updatePolicy: row.update_policy,
|
||||
rolloutPercent: Number(row.rollout_percent),
|
||||
storageKey: row.storage_key,
|
||||
fileSizeBytes: row.file_size_bytes == null ? null : Number(row.file_size_bytes),
|
||||
sha256: row.sha256,
|
||||
signingCertSha256: row.signing_cert_sha256,
|
||||
publishedAt: row.published_at,
|
||||
createdBy: row.created_by,
|
||||
downloadCount: Number(row.download_count),
|
||||
downloadFailCount: Number(row.download_fail_count),
|
||||
installConfirmCount: Number(row.install_confirm_count),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
const RELEASE_COLS = `
|
||||
id, platform, channel, version_name, version_code, package_name, previous_version_name,
|
||||
whats_new, bug_fixes, status, update_policy, rollout_percent, storage_key, file_size_bytes,
|
||||
sha256, signing_cert_sha256, published_at, created_by, download_count, download_fail_count,
|
||||
install_confirm_count, created_at, updated_at
|
||||
`;
|
||||
|
||||
export async function getSettings(): Promise<MobileAppUpdateSettings> {
|
||||
const rows = await query<
|
||||
Array<{
|
||||
id: number;
|
||||
min_supported_version_code: number;
|
||||
check_interval_seconds: number;
|
||||
expected_package_name: string;
|
||||
updated_at: Date;
|
||||
}>
|
||||
>(
|
||||
`SELECT id, min_supported_version_code, check_interval_seconds, expected_package_name, updated_at
|
||||
FROM mobile_app_update_settings WHERE id = 1`
|
||||
);
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return {
|
||||
id: 1,
|
||||
minSupportedVersionCode: 1,
|
||||
checkIntervalSeconds: 21600,
|
||||
expectedPackageName: 'com.prediqo.mobile',
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
minSupportedVersionCode: Number(row.min_supported_version_code),
|
||||
checkIntervalSeconds: Number(row.check_interval_seconds),
|
||||
expectedPackageName: row.expected_package_name,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
export async function updateSettings(input: {
|
||||
minSupportedVersionCode?: number;
|
||||
checkIntervalSeconds?: number;
|
||||
expectedPackageName?: string;
|
||||
}): Promise<MobileAppUpdateSettings> {
|
||||
await query(
|
||||
`UPDATE mobile_app_update_settings SET
|
||||
min_supported_version_code = COALESCE($1, min_supported_version_code),
|
||||
check_interval_seconds = COALESCE($2, check_interval_seconds),
|
||||
expected_package_name = COALESCE($3, expected_package_name),
|
||||
updated_at = NOW()
|
||||
WHERE id = 1`,
|
||||
[
|
||||
input.minSupportedVersionCode ?? null,
|
||||
input.checkIntervalSeconds ?? null,
|
||||
input.expectedPackageName ?? null,
|
||||
]
|
||||
);
|
||||
return getSettings();
|
||||
}
|
||||
|
||||
export async function createRelease(input: {
|
||||
platform: MobilePlatform;
|
||||
channel: MobileChannel;
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
previousVersionName?: string | null;
|
||||
whatsNew?: string;
|
||||
bugFixes?: string;
|
||||
updatePolicy?: MobileUpdatePolicy;
|
||||
rolloutPercent?: number;
|
||||
createdBy?: string | null;
|
||||
}): Promise<MobileAppRelease> {
|
||||
const rows = await query<ReleaseRow[]>(
|
||||
`INSERT INTO mobile_app_releases (
|
||||
platform, channel, version_name, version_code, previous_version_name,
|
||||
whats_new, bug_fixes, update_policy, rollout_percent, created_by
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
|
||||
RETURNING ${RELEASE_COLS}`,
|
||||
[
|
||||
input.platform,
|
||||
input.channel,
|
||||
input.versionName,
|
||||
input.versionCode,
|
||||
input.previousVersionName ?? null,
|
||||
input.whatsNew ?? '',
|
||||
input.bugFixes ?? '',
|
||||
input.updatePolicy ?? 'optional',
|
||||
input.rolloutPercent ?? 100,
|
||||
input.createdBy ?? null,
|
||||
]
|
||||
);
|
||||
return mapRelease(rows[0]);
|
||||
}
|
||||
|
||||
export async function findById(id: string): Promise<MobileAppRelease | null> {
|
||||
const rows = await query<ReleaseRow[]>(
|
||||
`SELECT ${RELEASE_COLS} FROM mobile_app_releases WHERE id = $1`,
|
||||
[id]
|
||||
);
|
||||
return rows[0] ? mapRelease(rows[0]) : null;
|
||||
}
|
||||
|
||||
export async function listReleases(filters: {
|
||||
platform?: MobilePlatform;
|
||||
channel?: MobileChannel;
|
||||
status?: MobileReleaseStatus;
|
||||
search?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<{ items: MobileAppRelease[]; total: number }> {
|
||||
const where: string[] = [];
|
||||
const params: unknown[] = [];
|
||||
let i = 1;
|
||||
if (filters.platform) {
|
||||
where.push(`platform = $${i++}`);
|
||||
params.push(filters.platform);
|
||||
}
|
||||
if (filters.channel) {
|
||||
where.push(`channel = $${i++}`);
|
||||
params.push(filters.channel);
|
||||
}
|
||||
if (filters.status) {
|
||||
where.push(`status = $${i++}`);
|
||||
params.push(filters.status);
|
||||
}
|
||||
if (filters.search?.trim()) {
|
||||
where.push(`(version_name ILIKE $${i} OR CAST(version_code AS TEXT) ILIKE $${i})`);
|
||||
params.push(`%${filters.search.trim()}%`);
|
||||
i++;
|
||||
}
|
||||
const whereSql = where.length ? `WHERE ${where.join(' AND ')}` : '';
|
||||
const limit = Math.min(Math.max(filters.limit ?? 50, 1), 200);
|
||||
const offset = Math.max(filters.offset ?? 0, 0);
|
||||
|
||||
const countRows = await query<Array<{ c: number }>>(
|
||||
`SELECT COUNT(*)::int AS c FROM mobile_app_releases ${whereSql}`,
|
||||
params
|
||||
);
|
||||
const total = Number(countRows[0]?.c ?? 0);
|
||||
|
||||
const rows = await query<ReleaseRow[]>(
|
||||
`SELECT ${RELEASE_COLS} FROM mobile_app_releases ${whereSql}
|
||||
ORDER BY version_code DESC, created_at DESC
|
||||
LIMIT $${i++} OFFSET $${i++}`,
|
||||
[...params, limit, offset]
|
||||
);
|
||||
return { items: rows.map(mapRelease), total };
|
||||
}
|
||||
|
||||
export async function updateRelease(
|
||||
id: string,
|
||||
patch: Partial<{
|
||||
versionName: string;
|
||||
previousVersionName: string | null;
|
||||
whatsNew: string;
|
||||
bugFixes: string;
|
||||
updatePolicy: MobileUpdatePolicy;
|
||||
rolloutPercent: number;
|
||||
status: MobileReleaseStatus;
|
||||
packageName: string | null;
|
||||
storageKey: string | null;
|
||||
fileSizeBytes: number | null;
|
||||
sha256: string | null;
|
||||
signingCertSha256: string | null;
|
||||
publishedAt: Date | null;
|
||||
}>
|
||||
): Promise<MobileAppRelease | null> {
|
||||
const rows = await query<ReleaseRow[]>(
|
||||
`UPDATE mobile_app_releases SET
|
||||
version_name = COALESCE($2, version_name),
|
||||
previous_version_name = CASE WHEN $3::boolean THEN $4 ELSE previous_version_name END,
|
||||
whats_new = COALESCE($5, whats_new),
|
||||
bug_fixes = COALESCE($6, bug_fixes),
|
||||
update_policy = COALESCE($7, update_policy),
|
||||
rollout_percent = COALESCE($8, rollout_percent),
|
||||
status = COALESCE($9, status),
|
||||
package_name = CASE WHEN $10::boolean THEN $11 ELSE package_name END,
|
||||
storage_key = CASE WHEN $12::boolean THEN $13 ELSE storage_key END,
|
||||
file_size_bytes = CASE WHEN $14::boolean THEN $15 ELSE file_size_bytes END,
|
||||
sha256 = CASE WHEN $16::boolean THEN $17 ELSE sha256 END,
|
||||
signing_cert_sha256 = CASE WHEN $18::boolean THEN $19 ELSE signing_cert_sha256 END,
|
||||
published_at = CASE WHEN $20::boolean THEN $21 ELSE published_at END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING ${RELEASE_COLS}`,
|
||||
[
|
||||
id,
|
||||
patch.versionName ?? null,
|
||||
patch.previousVersionName !== undefined,
|
||||
patch.previousVersionName ?? null,
|
||||
patch.whatsNew ?? null,
|
||||
patch.bugFixes ?? null,
|
||||
patch.updatePolicy ?? null,
|
||||
patch.rolloutPercent ?? null,
|
||||
patch.status ?? null,
|
||||
patch.packageName !== undefined,
|
||||
patch.packageName ?? null,
|
||||
patch.storageKey !== undefined,
|
||||
patch.storageKey ?? null,
|
||||
patch.fileSizeBytes !== undefined,
|
||||
patch.fileSizeBytes ?? null,
|
||||
patch.sha256 !== undefined,
|
||||
patch.sha256 ?? null,
|
||||
patch.signingCertSha256 !== undefined,
|
||||
patch.signingCertSha256 ?? null,
|
||||
patch.publishedAt !== undefined,
|
||||
patch.publishedAt ?? null,
|
||||
]
|
||||
);
|
||||
return rows[0] ? mapRelease(rows[0]) : null;
|
||||
}
|
||||
|
||||
export async function findLatestPublished(
|
||||
platform: MobilePlatform,
|
||||
channel: MobileChannel
|
||||
): Promise<MobileAppRelease | null> {
|
||||
const rows = await query<ReleaseRow[]>(
|
||||
`SELECT ${RELEASE_COLS} FROM mobile_app_releases
|
||||
WHERE platform = $1 AND channel = $2 AND status = 'published'
|
||||
ORDER BY version_code DESC
|
||||
LIMIT 1`,
|
||||
[platform, channel]
|
||||
);
|
||||
return rows[0] ? mapRelease(rows[0]) : null;
|
||||
}
|
||||
|
||||
export async function findHighestMandatoryPublished(
|
||||
platform: MobilePlatform,
|
||||
channel: MobileChannel
|
||||
): Promise<MobileAppRelease | null> {
|
||||
const rows = await query<ReleaseRow[]>(
|
||||
`SELECT ${RELEASE_COLS} FROM mobile_app_releases
|
||||
WHERE platform = $1 AND channel = $2 AND status = 'published' AND update_policy = 'mandatory'
|
||||
ORDER BY version_code DESC
|
||||
LIMIT 1`,
|
||||
[platform, channel]
|
||||
);
|
||||
return rows[0] ? mapRelease(rows[0]) : null;
|
||||
}
|
||||
|
||||
export async function incrementCounter(
|
||||
id: string,
|
||||
field: 'download_count' | 'download_fail_count' | 'install_confirm_count'
|
||||
): Promise<void> {
|
||||
await query(`UPDATE mobile_app_releases SET ${field} = ${field} + 1, updated_at = NOW() WHERE id = $1`, [id]);
|
||||
}
|
||||
|
||||
export async function insertEvent(input: {
|
||||
releaseId?: string | null;
|
||||
eventType: MobileReleaseEventType;
|
||||
platform?: MobilePlatform;
|
||||
channel?: MobileChannel;
|
||||
clientVersionCode?: number | null;
|
||||
deviceIdHash?: string | null;
|
||||
userId?: string | null;
|
||||
meta?: Record<string, unknown>;
|
||||
}): Promise<void> {
|
||||
await query(
|
||||
`INSERT INTO mobile_app_release_events (
|
||||
release_id, event_type, platform, channel, client_version_code, device_id_hash, user_id, meta
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8::jsonb)`,
|
||||
[
|
||||
input.releaseId ?? null,
|
||||
input.eventType,
|
||||
input.platform ?? 'android',
|
||||
input.channel ?? 'production',
|
||||
input.clientVersionCode ?? null,
|
||||
input.deviceIdHash ?? null,
|
||||
input.userId ?? null,
|
||||
JSON.stringify(input.meta ?? {}),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
export async function getStatsSummary(platform: MobilePlatform = 'android'): Promise<{
|
||||
byStatus: Array<{ status: string; count: number }>;
|
||||
byVersion: Array<{
|
||||
id: string;
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
status: string;
|
||||
downloadCount: number;
|
||||
downloadFailCount: number;
|
||||
installConfirmCount: number;
|
||||
}>;
|
||||
eventCounts: Array<{ eventType: string; count: number }>;
|
||||
}> {
|
||||
const statusRows = await query<Array<{ status: string; c: number }>>(
|
||||
`SELECT status, COUNT(*)::int AS c FROM mobile_app_releases WHERE platform = $1 GROUP BY status`,
|
||||
[platform]
|
||||
);
|
||||
const versionRows = await query<
|
||||
Array<{
|
||||
id: string;
|
||||
version_name: string;
|
||||
version_code: number;
|
||||
status: string;
|
||||
download_count: string | number;
|
||||
download_fail_count: string | number;
|
||||
install_confirm_count: string | number;
|
||||
}>
|
||||
>(
|
||||
`SELECT id, version_name, version_code, status, download_count, download_fail_count, install_confirm_count
|
||||
FROM mobile_app_releases WHERE platform = $1
|
||||
ORDER BY version_code DESC LIMIT 50`,
|
||||
[platform]
|
||||
);
|
||||
const eventRows = await query<Array<{ event_type: string; c: number }>>(
|
||||
`SELECT event_type, COUNT(*)::int AS c FROM mobile_app_release_events
|
||||
WHERE platform = $1 AND created_at > NOW() - INTERVAL '30 days'
|
||||
GROUP BY event_type`,
|
||||
[platform]
|
||||
);
|
||||
|
||||
return {
|
||||
byStatus: statusRows.map((r) => ({ status: r.status, count: Number(r.c) })),
|
||||
byVersion: versionRows.map((r) => ({
|
||||
id: r.id,
|
||||
versionName: r.version_name,
|
||||
versionCode: Number(r.version_code),
|
||||
status: r.status,
|
||||
downloadCount: Number(r.download_count),
|
||||
downloadFailCount: Number(r.download_fail_count),
|
||||
installConfirmCount: Number(r.install_confirm_count),
|
||||
})),
|
||||
eventCounts: eventRows.map((r) => ({ eventType: r.event_type, count: Number(r.c) })),
|
||||
};
|
||||
}
|
||||
@ -120,6 +120,18 @@ import * as adminCreditController from '../controllers/adminCreditController';
|
||||
import * as testWalletController from '../controllers/testWalletController';
|
||||
import * as soloEncouragementController from '../controllers/soloEncouragementController';
|
||||
import * as shareCardController from '../controllers/shareCardController';
|
||||
import * as mobileAppReleaseController from '../controllers/mobileAppReleaseController';
|
||||
import { apkUpload } from '../middleware/apkUpload';
|
||||
import { requireSupportedAppVersion } from '../middleware/requireSupportedAppVersion';
|
||||
import {
|
||||
mobileReleaseCreateBodySchema,
|
||||
mobileReleaseUpdateBodySchema,
|
||||
mobileUpdateSettingsBodySchema,
|
||||
mobileReleaseListQuerySchema,
|
||||
mobileUpdateCheckQuerySchema,
|
||||
mobileUpdateEventBodySchema,
|
||||
mobileReleaseIdParamSchema,
|
||||
} from '../validation/mobileReleaseSchemas';
|
||||
import * as countryController from '../controllers/countryController';
|
||||
import * as presenceController from '../controllers/presenceController';
|
||||
import * as supportController from '../controllers/supportController';
|
||||
@ -180,6 +192,24 @@ router.get('/marketing/withdrawal-feed', marketingController.getWithdrawalFeed);
|
||||
/** Public Share Card verification (HMAC token). */
|
||||
router.get('/share-cards/verify/:token', shareCardController.verifyShareCard);
|
||||
|
||||
/** Public Android in-app update check / APK download / telemetry (no auth). */
|
||||
router.get(
|
||||
'/app-updates/android',
|
||||
validateQuery(mobileUpdateCheckQuerySchema),
|
||||
mobileAppReleaseController.checkAndroid
|
||||
);
|
||||
router.get(
|
||||
'/app-updates/android/download/:id',
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
mobileAppReleaseController.downloadAndroid
|
||||
);
|
||||
router.post(
|
||||
'/app-updates/android/events',
|
||||
optionalAuthMiddleware,
|
||||
validateBody(mobileUpdateEventBodySchema),
|
||||
mobileAppReleaseController.postEvent
|
||||
);
|
||||
|
||||
/** Support messaging — guests (visitor token) and optional authenticated users. */
|
||||
router.get('/support/files/:filename', supportController.getAttachment);
|
||||
router.post('/support/conversations/current', optionalAuthMiddleware, supportController.getOrCreateConversation);
|
||||
@ -263,14 +293,36 @@ router.post('/2fa/enable', validateBody(totpEnableBodySchema), authController.en
|
||||
router.post('/2fa/disable', validateBody(totpDisableBodySchema), authController.disable2FA);
|
||||
router.post('/2fa/recovery/regenerate', authController.regenerateRecoveryCodes);
|
||||
|
||||
router.post('/withdraw', validateBody(withdrawBodySchema), auditAction('withdrawal_requested', 'wallet'), asyncHandler(withdrawalController.withdraw));
|
||||
router.post('/transfer', validateBody(transferBodySchema), auditAction('transfer_requested', 'wallet'), asyncHandler(transferController.transfer));
|
||||
router.post(
|
||||
'/withdraw',
|
||||
requireSupportedAppVersion,
|
||||
validateBody(withdrawBodySchema),
|
||||
auditAction('withdrawal_requested', 'wallet'),
|
||||
asyncHandler(withdrawalController.withdraw)
|
||||
);
|
||||
router.post(
|
||||
'/transfer',
|
||||
requireSupportedAppVersion,
|
||||
validateBody(transferBodySchema),
|
||||
auditAction('transfer_requested', 'wallet'),
|
||||
asyncHandler(transferController.transfer)
|
||||
);
|
||||
|
||||
router.get('/games/candle-predict/state', candlePredictController.getState);
|
||||
router.get('/games/candle-predict/candles', candlePredictController.getCandles);
|
||||
router.post('/games/candle-predict/bets', validateBody(candlePredictBetBodySchema), candlePredictController.placeBet);
|
||||
router.post(
|
||||
'/games/candle-predict/bets',
|
||||
requireSupportedAppVersion,
|
||||
validateBody(candlePredictBetBodySchema),
|
||||
candlePredictController.placeBet
|
||||
);
|
||||
router.get('/games/candle-predict/bets/outcome/:idempotencyKey', candlePredictController.getBetOutcome);
|
||||
router.post('/games/candle-predict/bets/multi', validateBody(candlePredictMultiBetBodySchema), candlePredictController.placeMultiBet);
|
||||
router.post(
|
||||
'/games/candle-predict/bets/multi',
|
||||
requireSupportedAppVersion,
|
||||
validateBody(candlePredictMultiBetBodySchema),
|
||||
candlePredictController.placeMultiBet
|
||||
);
|
||||
router.get('/games/candle-predict/bets/me', candlePredictController.getMyBets);
|
||||
router.get('/games/candle-predict/auto', candlePredictController.getAutoSettings);
|
||||
router.put('/games/candle-predict/auto', validateBody(candlePredictAutoBodySchema), candlePredictController.updateAutoSettings);
|
||||
@ -553,6 +605,92 @@ router.get('/admin/test-wallet/credits', requireRoles('admin'), requirePermissio
|
||||
router.get('/admin/share-cards/settings', requireRoles('admin'), requirePermissions('settings.admin'), shareCardController.getAdminSettings);
|
||||
router.patch('/admin/share-cards/settings', requireRoles('admin'), requirePermissions('settings.admin'), validateBody(shareCardSettingsBodySchema), shareCardController.updateAdminSettings);
|
||||
|
||||
/** Admin — mobile APK release management */
|
||||
router.get(
|
||||
'/admin/mobile-releases/stats',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.view'),
|
||||
mobileAppReleaseController.adminStats
|
||||
);
|
||||
router.get(
|
||||
'/admin/mobile-update-settings',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.view'),
|
||||
mobileAppReleaseController.adminGetSettings
|
||||
);
|
||||
router.patch(
|
||||
'/admin/mobile-update-settings',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateBody(mobileUpdateSettingsBodySchema),
|
||||
mobileAppReleaseController.adminUpdateSettings
|
||||
);
|
||||
router.get(
|
||||
'/admin/mobile-releases',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.view'),
|
||||
validateQuery(mobileReleaseListQuerySchema),
|
||||
mobileAppReleaseController.adminList
|
||||
);
|
||||
router.post(
|
||||
'/admin/mobile-releases',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateBody(mobileReleaseCreateBodySchema),
|
||||
mobileAppReleaseController.adminCreate
|
||||
);
|
||||
router.get(
|
||||
'/admin/mobile-releases/:id',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.view'),
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
mobileAppReleaseController.adminGet
|
||||
);
|
||||
router.patch(
|
||||
'/admin/mobile-releases/:id',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
validateBody(mobileReleaseUpdateBodySchema),
|
||||
mobileAppReleaseController.adminUpdate
|
||||
);
|
||||
router.post(
|
||||
'/admin/mobile-releases/:id/apk',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
apkUpload.single('file'),
|
||||
mobileAppReleaseController.adminUploadApk
|
||||
);
|
||||
router.post(
|
||||
'/admin/mobile-releases/:id/submit',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
mobileAppReleaseController.adminSubmit
|
||||
);
|
||||
router.post(
|
||||
'/admin/mobile-releases/:id/publish',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
mobileAppReleaseController.adminPublish
|
||||
);
|
||||
router.post(
|
||||
'/admin/mobile-releases/:id/suspend',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
mobileAppReleaseController.adminSuspend
|
||||
);
|
||||
router.post(
|
||||
'/admin/mobile-releases/:id/retire',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.mobile_releases.manage'),
|
||||
validateParams(mobileReleaseIdParamSchema),
|
||||
mobileAppReleaseController.adminRetire
|
||||
);
|
||||
|
||||
router.get('/admin/solo-encouragement/config', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.getAdminConfig);
|
||||
router.patch('/admin/solo-encouragement/config', requireRoles('admin'), requirePermissions('settings.admin'), validateBody(soloEncouragementConfigBodySchema), soloEncouragementController.updateAdminConfig);
|
||||
router.get('/admin/solo-encouragement/streaks', requireRoles('admin'), requirePermissions('settings.admin'), soloEncouragementController.listActiveStreaks);
|
||||
|
||||
77
backend/src/services/apkStorageService.ts
Normal file
77
backend/src/services/apkStorageService.ts
Normal file
@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Dedicated on-disk storage for Android APK releases (staging vs published).
|
||||
* Files are never executed — only stored and streamed for download.
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
import { config } from '../config';
|
||||
|
||||
const ROOT_REL = path.join('data', 'apk-releases');
|
||||
|
||||
export function getApkReleasesRoot(): string {
|
||||
const root = path.resolve(process.cwd(), ROOT_REL);
|
||||
fs.mkdirSync(path.join(root, 'staging'), { recursive: true });
|
||||
fs.mkdirSync(path.join(root, 'published'), { recursive: true });
|
||||
return root;
|
||||
}
|
||||
|
||||
export function ensureApkStagingDir(): string {
|
||||
const dir = path.join(getApkReleasesRoot(), 'staging');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
export function ensureApkPublishedDir(): string {
|
||||
const dir = path.join(getApkReleasesRoot(), 'published');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** Absolute path for a relative storage key like `staging/uuid.apk` or `published/uuid.apk`. */
|
||||
export function resolveApkStoragePath(storageKey: string): string {
|
||||
const root = getApkReleasesRoot();
|
||||
const normalized = storageKey.replace(/\\/g, '/').replace(/^\/+/, '');
|
||||
if (normalized.includes('..') || (!normalized.startsWith('staging/') && !normalized.startsWith('published/'))) {
|
||||
throw new Error('Invalid APK storage key');
|
||||
}
|
||||
const absolute = path.resolve(root, normalized);
|
||||
if (!absolute.startsWith(root)) {
|
||||
throw new Error('Invalid APK storage key');
|
||||
}
|
||||
return absolute;
|
||||
}
|
||||
|
||||
export function sha256File(filePath: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = crypto.createHash('sha256');
|
||||
const stream = fs.createReadStream(filePath);
|
||||
stream.on('error', reject);
|
||||
stream.on('data', (chunk) => hash.update(chunk));
|
||||
stream.on('end', () => resolve(hash.digest('hex')));
|
||||
});
|
||||
}
|
||||
|
||||
export function moveApkToPublished(stagingKey: string, releaseId: string): string {
|
||||
const from = resolveApkStoragePath(stagingKey);
|
||||
const publishedKey = `published/${releaseId}.apk`;
|
||||
const to = resolveApkStoragePath(publishedKey);
|
||||
fs.mkdirSync(path.dirname(to), { recursive: true });
|
||||
fs.renameSync(from, to);
|
||||
return publishedKey;
|
||||
}
|
||||
|
||||
export function removeApkIfExists(storageKey: string | null | undefined): void {
|
||||
if (!storageKey) return;
|
||||
try {
|
||||
const p = resolveApkStoragePath(storageKey);
|
||||
if (fs.existsSync(p)) fs.unlinkSync(p);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function getApkMaxUploadBytes(): number {
|
||||
return config.mobileReleases.maxUploadBytes;
|
||||
}
|
||||
@ -12,6 +12,7 @@ import * as auditLogRepository from '../repositories/auditLogRepository';
|
||||
import { raiseAlert } from './securityService';
|
||||
import { ensureFaqUploadDir } from '../middleware/faqUpload';
|
||||
import { ensureUploadDir } from './supportService';
|
||||
import { ensureApkPublishedDir } from './apkStorageService';
|
||||
|
||||
export type FileIntegrityIssue = {
|
||||
rootKey: string;
|
||||
@ -24,12 +25,14 @@ export type FileIntegrityIssue = {
|
||||
export const FILE_INTEGRITY_ROOTS = {
|
||||
faq: 'faq-uploads',
|
||||
support: 'support-uploads',
|
||||
apkPublished: 'apk-releases-published',
|
||||
} as const;
|
||||
|
||||
export type FileIntegrityRootKey = (typeof FILE_INTEGRITY_ROOTS)[keyof typeof FILE_INTEGRITY_ROOTS];
|
||||
|
||||
function resolveRootDir(rootKey: FileIntegrityRootKey): string {
|
||||
if (rootKey === FILE_INTEGRITY_ROOTS.faq) return ensureFaqUploadDir();
|
||||
if (rootKey === FILE_INTEGRITY_ROOTS.apkPublished) return ensureApkPublishedDir();
|
||||
return ensureUploadDir();
|
||||
}
|
||||
|
||||
|
||||
532
backend/src/services/mobileAppReleaseService.ts
Normal file
532
backend/src/services/mobileAppReleaseService.ts
Normal file
@ -0,0 +1,532 @@
|
||||
/**
|
||||
* Mobile app release lifecycle: admin CRUD, APK validation, public check/download, telemetry.
|
||||
*/
|
||||
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { config } from '../config';
|
||||
import { HttpError } from '../utils/httpError';
|
||||
import { parseApkFile } from '../utils/apkParser';
|
||||
import { scanUploadedFile } from './virusScanService';
|
||||
import {
|
||||
getApkMaxUploadBytes,
|
||||
moveApkToPublished,
|
||||
removeApkIfExists,
|
||||
resolveApkStoragePath,
|
||||
sha256File,
|
||||
} from './apkStorageService';
|
||||
import * as repo from '../repositories/mobileAppReleaseRepository';
|
||||
import { recordUploadedFile, FILE_INTEGRITY_ROOTS } from './fileIntegrityService';
|
||||
import type {
|
||||
MobileAppRelease,
|
||||
MobileChannel,
|
||||
MobileReleaseEventType,
|
||||
MobileUpdatePolicy,
|
||||
} from '../models/mobileAppRelease.model';
|
||||
|
||||
export class MobileReleaseError extends HttpError {
|
||||
constructor(status: number, message: string, code?: string) {
|
||||
super(status, message, code);
|
||||
this.name = 'MobileReleaseError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Deterministic rollout bucket 0–99 from device id. */
|
||||
export function rolloutBucket(deviceId: string): number {
|
||||
const hash = crypto.createHash('sha256').update(String(deviceId || 'anonymous')).digest();
|
||||
return hash.readUInt32BE(0) % 100;
|
||||
}
|
||||
|
||||
export function isRolloutEligible(deviceId: string, rolloutPercent: number): boolean {
|
||||
if (rolloutPercent >= 100) return true;
|
||||
if (rolloutPercent <= 0) return false;
|
||||
return rolloutBucket(deviceId) < rolloutPercent;
|
||||
}
|
||||
|
||||
export function hashDeviceId(deviceId: string): string {
|
||||
return crypto.createHash('sha256').update(`tloto-device:${deviceId}`).digest('hex').slice(0, 32);
|
||||
}
|
||||
|
||||
function signDownloadToken(releaseId: string, exp: number): string {
|
||||
const payload = `${releaseId}.${exp}`;
|
||||
const sig = crypto
|
||||
.createHmac('sha256', config.mobileReleases.downloadTokenSecret)
|
||||
.update(payload)
|
||||
.digest('base64url');
|
||||
return `${payload}.${sig}`;
|
||||
}
|
||||
|
||||
export function createDownloadToken(releaseId: string): { token: string; expiresAt: number } {
|
||||
const expiresAt = Math.floor(Date.now() / 1000) + config.mobileReleases.downloadTokenTtlSeconds;
|
||||
return { token: signDownloadToken(releaseId, expiresAt), expiresAt };
|
||||
}
|
||||
|
||||
export function verifyDownloadToken(token: string, releaseId: string): boolean {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) return false;
|
||||
const [id, expStr, sig] = parts;
|
||||
if (id !== releaseId) return false;
|
||||
const exp = parseInt(expStr, 10);
|
||||
if (!Number.isFinite(exp) || exp < Math.floor(Date.now() / 1000)) return false;
|
||||
const expected = signDownloadToken(releaseId, exp);
|
||||
try {
|
||||
return crypto.timingSafeEqual(Buffer.from(token), Buffer.from(expected));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function publicDownloadUrl(releaseId: string, token: string): string {
|
||||
const base = config.app.publicUrl.replace(/\/$/, '');
|
||||
const api = config.apiPrefix.replace(/\/$/, '');
|
||||
return `${base}${api}/app-updates/android/download/${releaseId}?token=${encodeURIComponent(token)}`;
|
||||
}
|
||||
|
||||
export async function getSettings() {
|
||||
return repo.getSettings();
|
||||
}
|
||||
|
||||
export async function updateSettings(input: {
|
||||
minSupportedVersionCode?: number;
|
||||
checkIntervalSeconds?: number;
|
||||
expectedPackageName?: string;
|
||||
}) {
|
||||
return repo.updateSettings(input);
|
||||
}
|
||||
|
||||
export async function listReleases(filters: Parameters<typeof repo.listReleases>[0]) {
|
||||
return repo.listReleases(filters);
|
||||
}
|
||||
|
||||
export async function getRelease(id: string) {
|
||||
const release = await repo.findById(id);
|
||||
if (!release) throw new MobileReleaseError(404, 'Release not found');
|
||||
return release;
|
||||
}
|
||||
|
||||
export async function createRelease(input: {
|
||||
platform?: 'android' | 'ios';
|
||||
channel?: MobileChannel;
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
previousVersionName?: string | null;
|
||||
whatsNew?: string;
|
||||
bugFixes?: string;
|
||||
updatePolicy?: MobileUpdatePolicy;
|
||||
rolloutPercent?: number;
|
||||
createdBy?: string | null;
|
||||
}) {
|
||||
if (input.platform === 'ios') {
|
||||
throw new MobileReleaseError(400, 'iOS IPA distribution is not supported; use App Store / TestFlight');
|
||||
}
|
||||
try {
|
||||
return await repo.createRelease({
|
||||
platform: 'android',
|
||||
channel: input.channel ?? 'production',
|
||||
versionName: input.versionName,
|
||||
versionCode: input.versionCode,
|
||||
previousVersionName: input.previousVersionName,
|
||||
whatsNew: input.whatsNew,
|
||||
bugFixes: input.bugFixes,
|
||||
updatePolicy: input.updatePolicy,
|
||||
rolloutPercent: input.rolloutPercent,
|
||||
createdBy: input.createdBy,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (/unique|duplicate/i.test(msg)) {
|
||||
throw new MobileReleaseError(409, 'A release with this versionCode already exists for the channel');
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateReleaseMeta(
|
||||
id: string,
|
||||
patch: {
|
||||
versionName?: string;
|
||||
previousVersionName?: string | null;
|
||||
whatsNew?: string;
|
||||
bugFixes?: string;
|
||||
updatePolicy?: MobileUpdatePolicy;
|
||||
rolloutPercent?: number;
|
||||
}
|
||||
) {
|
||||
const existing = await getRelease(id);
|
||||
if (existing.status === 'retired') {
|
||||
throw new MobileReleaseError(400, 'Retired releases cannot be edited');
|
||||
}
|
||||
const updated = await repo.updateRelease(id, patch);
|
||||
if (!updated) throw new MobileReleaseError(404, 'Release not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function attachApk(id: string, uploadedAbsolutePath: string): Promise<MobileAppRelease> {
|
||||
const release = await getRelease(id);
|
||||
if (!['draft', 'pending_validation', 'suspended'].includes(release.status)) {
|
||||
throw new MobileReleaseError(400, 'APK can only be uploaded for draft, pending, or suspended releases');
|
||||
}
|
||||
|
||||
const stat = fs.statSync(uploadedAbsolutePath);
|
||||
if (stat.size > getApkMaxUploadBytes()) {
|
||||
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
|
||||
throw new MobileReleaseError(400, 'APK exceeds maximum upload size');
|
||||
}
|
||||
|
||||
try {
|
||||
await scanUploadedFile(uploadedAbsolutePath);
|
||||
} catch (e) {
|
||||
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
|
||||
throw new MobileReleaseError(422, e instanceof Error ? e.message : 'Virus scan failed');
|
||||
}
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = await parseApkFile(uploadedAbsolutePath);
|
||||
} catch (e) {
|
||||
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
|
||||
throw new MobileReleaseError(400, e instanceof Error ? e.message : 'Invalid APK');
|
||||
}
|
||||
|
||||
const settings = await repo.getSettings();
|
||||
const expectedPackage = config.mobileReleases.expectedPackage || settings.expectedPackageName;
|
||||
if (parsed.packageName !== expectedPackage) {
|
||||
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
|
||||
throw new MobileReleaseError(
|
||||
400,
|
||||
`APK package "${parsed.packageName}" does not match expected "${expectedPackage}"`
|
||||
);
|
||||
}
|
||||
|
||||
if (parsed.versionCode !== release.versionCode) {
|
||||
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
|
||||
throw new MobileReleaseError(
|
||||
400,
|
||||
`APK versionCode ${parsed.versionCode} does not match release versionCode ${release.versionCode}`
|
||||
);
|
||||
}
|
||||
|
||||
const expectedCert = config.mobileReleases.expectedCertSha256;
|
||||
if (expectedCert) {
|
||||
if (!parsed.signingCertSha256) {
|
||||
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
|
||||
throw new MobileReleaseError(400, 'Could not read APK signing certificate');
|
||||
}
|
||||
if (parsed.signingCertSha256.toLowerCase() !== expectedCert) {
|
||||
removeApkIfExists(`staging/${path.basename(uploadedAbsolutePath)}`);
|
||||
throw new MobileReleaseError(400, 'APK signing certificate does not match the expected fingerprint');
|
||||
}
|
||||
}
|
||||
|
||||
if (release.storageKey) removeApkIfExists(release.storageKey);
|
||||
|
||||
const stagingKey = `staging/${path.basename(uploadedAbsolutePath)}`;
|
||||
const fileSha = await sha256File(uploadedAbsolutePath);
|
||||
|
||||
const updated = await repo.updateRelease(id, {
|
||||
packageName: parsed.packageName,
|
||||
versionName: parsed.versionName || release.versionName,
|
||||
storageKey: stagingKey,
|
||||
fileSizeBytes: stat.size,
|
||||
sha256: fileSha,
|
||||
signingCertSha256: parsed.signingCertSha256,
|
||||
status: release.status === 'draft' ? 'pending_validation' : release.status,
|
||||
});
|
||||
if (!updated) throw new MobileReleaseError(404, 'Release not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function submitForValidation(id: string) {
|
||||
const release = await getRelease(id);
|
||||
if (!release.storageKey || !release.sha256) {
|
||||
throw new MobileReleaseError(400, 'Upload an APK before submitting for validation');
|
||||
}
|
||||
if (release.status !== 'draft' && release.status !== 'pending_validation') {
|
||||
throw new MobileReleaseError(400, 'Only draft releases can be submitted');
|
||||
}
|
||||
const updated = await repo.updateRelease(id, { status: 'pending_validation' });
|
||||
if (!updated) throw new MobileReleaseError(404, 'Release not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function publish(id: string) {
|
||||
const release = await getRelease(id);
|
||||
if (!['pending_validation', 'suspended', 'draft'].includes(release.status)) {
|
||||
throw new MobileReleaseError(400, 'Release cannot be published from its current status');
|
||||
}
|
||||
if (!release.storageKey || !release.sha256 || !release.fileSizeBytes) {
|
||||
throw new MobileReleaseError(400, 'APK file is required before publication');
|
||||
}
|
||||
|
||||
const settings = await repo.getSettings();
|
||||
const expectedPackage = config.mobileReleases.expectedPackage || settings.expectedPackageName;
|
||||
if (release.packageName && release.packageName !== expectedPackage) {
|
||||
throw new MobileReleaseError(400, 'Package name mismatch — re-upload the APK');
|
||||
}
|
||||
|
||||
const expectedCert = config.mobileReleases.expectedCertSha256;
|
||||
if (expectedCert && release.signingCertSha256?.toLowerCase() !== expectedCert) {
|
||||
throw new MobileReleaseError(400, 'Signing certificate fingerprint mismatch');
|
||||
}
|
||||
|
||||
const latest = await repo.findLatestPublished(release.platform, release.channel);
|
||||
if (latest && latest.versionCode >= release.versionCode && latest.id !== release.id) {
|
||||
throw new MobileReleaseError(
|
||||
400,
|
||||
`versionCode must be strictly greater than the current published release (${latest.versionCode})`
|
||||
);
|
||||
}
|
||||
|
||||
let storageKey = release.storageKey;
|
||||
if (storageKey.startsWith('staging/')) {
|
||||
storageKey = moveApkToPublished(storageKey, release.id);
|
||||
try {
|
||||
await recordUploadedFile(FILE_INTEGRITY_ROOTS.apkPublished, `${release.id}.apk`);
|
||||
} catch (e) {
|
||||
console.warn('[mobile-releases] FIM baseline skipped:', e);
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await repo.updateRelease(id, {
|
||||
storageKey,
|
||||
status: 'published',
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
if (!updated) throw new MobileReleaseError(404, 'Release not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function suspend(id: string) {
|
||||
const release = await getRelease(id);
|
||||
if (release.status !== 'published') {
|
||||
throw new MobileReleaseError(400, 'Only published releases can be suspended');
|
||||
}
|
||||
const updated = await repo.updateRelease(id, { status: 'suspended' });
|
||||
if (!updated) throw new MobileReleaseError(404, 'Release not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
export async function retire(id: string) {
|
||||
const release = await getRelease(id);
|
||||
if (release.status === 'retired') return release;
|
||||
const updated = await repo.updateRelease(id, { status: 'retired' });
|
||||
if (!updated) throw new MobileReleaseError(404, 'Release not found');
|
||||
return updated;
|
||||
}
|
||||
|
||||
export type UpdateCheckResult = {
|
||||
updateAvailable: boolean;
|
||||
blocked: boolean;
|
||||
policy: MobileUpdatePolicy | null;
|
||||
versionName: string | null;
|
||||
versionCode: number | null;
|
||||
whatsNew: string | null;
|
||||
bugFixes: string | null;
|
||||
fileSizeBytes: number | null;
|
||||
sha256: string | null;
|
||||
downloadUrl: string | null;
|
||||
minSupportedVersionCode: number;
|
||||
checkIntervalSeconds: number;
|
||||
publishedAt: string | null;
|
||||
packageName: string | null;
|
||||
};
|
||||
|
||||
export async function checkAndroidUpdate(input: {
|
||||
versionCode: number;
|
||||
versionName?: string;
|
||||
channel?: MobileChannel;
|
||||
deviceId: string;
|
||||
}): Promise<UpdateCheckResult> {
|
||||
const channel = input.channel ?? 'production';
|
||||
const settings = await repo.getSettings();
|
||||
const latest = await repo.findLatestPublished('android', channel);
|
||||
const mandatory = await repo.findHighestMandatoryPublished('android', channel);
|
||||
|
||||
const minSupported = settings.minSupportedVersionCode;
|
||||
const blocked = input.versionCode < minSupported;
|
||||
|
||||
await repo.insertEvent({
|
||||
releaseId: latest?.id ?? null,
|
||||
eventType: 'check',
|
||||
platform: 'android',
|
||||
channel,
|
||||
clientVersionCode: input.versionCode,
|
||||
deviceIdHash: hashDeviceId(input.deviceId),
|
||||
});
|
||||
|
||||
const base: UpdateCheckResult = {
|
||||
updateAvailable: false,
|
||||
blocked,
|
||||
policy: null,
|
||||
versionName: null,
|
||||
versionCode: null,
|
||||
whatsNew: null,
|
||||
bugFixes: null,
|
||||
fileSizeBytes: null,
|
||||
sha256: null,
|
||||
downloadUrl: null,
|
||||
minSupportedVersionCode: minSupported,
|
||||
checkIntervalSeconds: settings.checkIntervalSeconds,
|
||||
publishedAt: null,
|
||||
packageName: settings.expectedPackageName,
|
||||
};
|
||||
|
||||
if (!latest || latest.versionCode <= input.versionCode) {
|
||||
return base;
|
||||
}
|
||||
|
||||
if (!isRolloutEligible(input.deviceId, latest.rolloutPercent)) {
|
||||
return base;
|
||||
}
|
||||
|
||||
const { token } = createDownloadToken(latest.id);
|
||||
let policy: MobileUpdatePolicy = latest.updatePolicy;
|
||||
if (mandatory && mandatory.versionCode > input.versionCode) {
|
||||
policy = 'mandatory';
|
||||
}
|
||||
if (blocked) policy = 'mandatory';
|
||||
|
||||
return {
|
||||
...base,
|
||||
updateAvailable: true,
|
||||
policy,
|
||||
versionName: latest.versionName,
|
||||
versionCode: latest.versionCode,
|
||||
whatsNew: latest.whatsNew,
|
||||
bugFixes: latest.bugFixes,
|
||||
fileSizeBytes: latest.fileSizeBytes,
|
||||
sha256: latest.sha256,
|
||||
downloadUrl: publicDownloadUrl(latest.id, token),
|
||||
publishedAt: latest.publishedAt?.toISOString() ?? null,
|
||||
packageName: latest.packageName,
|
||||
};
|
||||
}
|
||||
|
||||
export async function openDownloadStream(releaseId: string, token: string): Promise<{
|
||||
release: MobileAppRelease;
|
||||
absolutePath: string;
|
||||
}> {
|
||||
if (!verifyDownloadToken(token, releaseId)) {
|
||||
throw new MobileReleaseError(403, 'Invalid or expired download token');
|
||||
}
|
||||
const release = await getRelease(releaseId);
|
||||
if (release.status !== 'published' || !release.storageKey) {
|
||||
throw new MobileReleaseError(404, 'Release is not available for download');
|
||||
}
|
||||
const absolutePath = resolveApkStoragePath(release.storageKey);
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
throw new MobileReleaseError(404, 'APK file missing on server');
|
||||
}
|
||||
await repo.insertEvent({
|
||||
releaseId,
|
||||
eventType: 'download_start',
|
||||
platform: release.platform,
|
||||
channel: release.channel,
|
||||
});
|
||||
await repo.incrementCounter(releaseId, 'download_count');
|
||||
return { release, absolutePath };
|
||||
}
|
||||
|
||||
export async function recordClientEvent(input: {
|
||||
eventType: MobileReleaseEventType;
|
||||
releaseId?: string;
|
||||
versionCode?: number;
|
||||
deviceId?: string;
|
||||
userId?: string | null;
|
||||
channel?: MobileChannel;
|
||||
}) {
|
||||
const allowed: MobileReleaseEventType[] = [
|
||||
'download_start',
|
||||
'download_ok',
|
||||
'download_fail',
|
||||
'install_confirm',
|
||||
];
|
||||
if (!allowed.includes(input.eventType)) {
|
||||
throw new MobileReleaseError(400, 'Unsupported event type');
|
||||
}
|
||||
// download_count is incremented when the authenticated download stream starts.
|
||||
if (input.releaseId && input.eventType === 'download_fail') {
|
||||
await repo.incrementCounter(input.releaseId, 'download_fail_count');
|
||||
}
|
||||
if (input.releaseId && input.eventType === 'install_confirm') {
|
||||
await repo.incrementCounter(input.releaseId, 'install_confirm_count');
|
||||
}
|
||||
await repo.insertEvent({
|
||||
releaseId: input.releaseId ?? null,
|
||||
eventType: input.eventType,
|
||||
platform: 'android',
|
||||
channel: input.channel ?? 'production',
|
||||
clientVersionCode: input.versionCode ?? null,
|
||||
deviceIdHash: input.deviceId ? hashDeviceId(input.deviceId) : null,
|
||||
userId: input.userId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getStats() {
|
||||
return repo.getStatsSummary('android');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a client versionCode is allowed to call sensitive APIs.
|
||||
* When blocked, returns the update payload for a 426 response.
|
||||
*/
|
||||
export async function evaluateClientVersionGate(versionCode: number | null): Promise<{
|
||||
allowed: boolean;
|
||||
update?: UpdateCheckResult;
|
||||
}> {
|
||||
if (versionCode == null || !Number.isFinite(versionCode)) {
|
||||
// Web / unknown clients are not gated by mobile version headers.
|
||||
return { allowed: true };
|
||||
}
|
||||
const settings = await repo.getSettings();
|
||||
const mandatory = await repo.findHighestMandatoryPublished('android', 'production');
|
||||
const latest = await repo.findLatestPublished('android', 'production');
|
||||
const belowMin = versionCode < settings.minSupportedVersionCode;
|
||||
const behindMandatory = !!mandatory && mandatory.versionCode > versionCode;
|
||||
if (!belowMin && !behindMandatory) return { allowed: true };
|
||||
|
||||
const target = mandatory && mandatory.versionCode > versionCode ? mandatory : latest;
|
||||
if (!target) {
|
||||
return {
|
||||
allowed: false,
|
||||
update: {
|
||||
updateAvailable: false,
|
||||
blocked: true,
|
||||
policy: 'mandatory',
|
||||
versionName: null,
|
||||
versionCode: null,
|
||||
whatsNew: null,
|
||||
bugFixes: null,
|
||||
fileSizeBytes: null,
|
||||
sha256: null,
|
||||
downloadUrl: null,
|
||||
minSupportedVersionCode: settings.minSupportedVersionCode,
|
||||
checkIntervalSeconds: settings.checkIntervalSeconds,
|
||||
publishedAt: null,
|
||||
packageName: settings.expectedPackageName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const { token } = createDownloadToken(target.id);
|
||||
return {
|
||||
allowed: false,
|
||||
update: {
|
||||
updateAvailable: true,
|
||||
blocked: true,
|
||||
policy: 'mandatory',
|
||||
versionName: target.versionName,
|
||||
versionCode: target.versionCode,
|
||||
whatsNew: target.whatsNew,
|
||||
bugFixes: target.bugFixes,
|
||||
fileSizeBytes: target.fileSizeBytes,
|
||||
sha256: target.sha256,
|
||||
downloadUrl: publicDownloadUrl(target.id, token),
|
||||
minSupportedVersionCode: settings.minSupportedVersionCode,
|
||||
checkIntervalSeconds: settings.checkIntervalSeconds,
|
||||
publishedAt: target.publishedAt?.toISOString() ?? null,
|
||||
packageName: target.packageName,
|
||||
},
|
||||
};
|
||||
}
|
||||
41
backend/src/tests/mobileAppRelease.test.ts
Normal file
41
backend/src/tests/mobileAppRelease.test.ts
Normal file
@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Unit tests for mobile APK release helpers (rollout, download tokens).
|
||||
*/
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
createDownloadToken,
|
||||
isRolloutEligible,
|
||||
rolloutBucket,
|
||||
verifyDownloadToken,
|
||||
} from '../services/mobileAppReleaseService';
|
||||
|
||||
describe('mobileAppReleaseService helpers', () => {
|
||||
it('rolloutBucket is deterministic for the same device id', () => {
|
||||
const a = rolloutBucket('device-abc');
|
||||
const b = rolloutBucket('device-abc');
|
||||
assert.equal(a, b);
|
||||
assert.ok(a >= 0 && a < 100);
|
||||
});
|
||||
|
||||
it('isRolloutEligible respects 0 / 100 percent', () => {
|
||||
assert.equal(isRolloutEligible('any', 0), false);
|
||||
assert.equal(isRolloutEligible('any', 100), true);
|
||||
});
|
||||
|
||||
it('isRolloutEligible is stable for a given device', () => {
|
||||
const device = 'stable-device-42';
|
||||
const eligible20 = isRolloutEligible(device, 20);
|
||||
assert.equal(isRolloutEligible(device, 20), eligible20);
|
||||
// Raising percent to 100 always includes the device.
|
||||
assert.equal(isRolloutEligible(device, 100), true);
|
||||
});
|
||||
|
||||
it('download token round-trips and rejects tampering', () => {
|
||||
const releaseId = '11111111-1111-1111-1111-111111111111';
|
||||
const { token } = createDownloadToken(releaseId);
|
||||
assert.equal(verifyDownloadToken(token, releaseId), true);
|
||||
assert.equal(verifyDownloadToken(token, '22222222-2222-2222-2222-222222222222'), false);
|
||||
assert.equal(verifyDownloadToken(token.slice(0, -2) + 'xx', releaseId), false);
|
||||
});
|
||||
});
|
||||
91
backend/src/utils/apkParser.ts
Normal file
91
backend/src/utils/apkParser.ts
Normal file
@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Parse Android APK metadata and signing certificate fingerprint.
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import crypto from 'crypto';
|
||||
import path from 'path';
|
||||
import AdmZip from 'adm-zip';
|
||||
import forge from 'node-forge';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const AppInfoParser = require('app-info-parser');
|
||||
|
||||
export type ApkParsedMeta = {
|
||||
packageName: string;
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
signingCertSha256: string | null;
|
||||
};
|
||||
|
||||
/** True when file starts with ZIP/APK magic bytes. */
|
||||
export function assertApkZipMagic(filePath: string): void {
|
||||
const fd = fs.openSync(filePath, 'r');
|
||||
try {
|
||||
const buf = Buffer.alloc(4);
|
||||
const read = fs.readSync(fd, buf, 0, 4, 0);
|
||||
if (read < 4 || buf[0] !== 0x50 || buf[1] !== 0x4b || buf[2] !== 0x03 || buf[3] !== 0x04) {
|
||||
throw new Error('File is not a valid APK/ZIP archive');
|
||||
}
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function sha256OfDer(der: Buffer): string {
|
||||
return crypto.createHash('sha256').update(der).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract SHA-256 of the first signing certificate found in META-INF (JAR/APK signature).
|
||||
* Returns null when no PKCS#7 cert block can be parsed (e.g. v3-only signing edge cases).
|
||||
*/
|
||||
export function extractSigningCertSha256(filePath: string): string | null {
|
||||
const zip = new AdmZip(filePath);
|
||||
const entries = zip.getEntries().filter((e) => {
|
||||
const name = e.entryName.replace(/\\/g, '/');
|
||||
return (
|
||||
name.startsWith('META-INF/') &&
|
||||
!e.isDirectory &&
|
||||
/\.(RSA|DSA|EC)$/i.test(path.basename(name))
|
||||
);
|
||||
});
|
||||
|
||||
for (const entry of entries) {
|
||||
try {
|
||||
const der = entry.getData();
|
||||
const asn1 = forge.asn1.fromDer(der.toString('binary'));
|
||||
const p7 = (forge.pkcs7 as unknown as { messageFromAsn1: (a: unknown) => { certificates?: Array<{ toAsn1: () => unknown }> } }).messageFromAsn1(asn1);
|
||||
const certs = p7.certificates || [];
|
||||
if (!certs.length) continue;
|
||||
const asn1Cert = certs[0].toAsn1();
|
||||
const derBytes = Buffer.from(forge.asn1.toDer(asn1Cert as forge.asn1.Asn1).getBytes(), 'binary');
|
||||
return sha256OfDer(derBytes);
|
||||
} catch {
|
||||
// try next entry
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Parse packageName / versionCode / versionName and signing cert fingerprint. */
|
||||
export async function parseApkFile(filePath: string): Promise<ApkParsedMeta> {
|
||||
assertApkZipMagic(filePath);
|
||||
|
||||
const parser = new AppInfoParser(filePath);
|
||||
const info = await parser.parse();
|
||||
const packageName = String(info.package || info.packageName || '').trim();
|
||||
const versionName = String(info.versionName || info.version || '').trim();
|
||||
const versionCodeRaw = info.versionCode ?? info.version_code ?? 0;
|
||||
const versionCode = typeof versionCodeRaw === 'number' ? versionCodeRaw : parseInt(String(versionCodeRaw), 10);
|
||||
|
||||
if (!packageName) throw new Error('APK package name could not be read');
|
||||
if (!Number.isFinite(versionCode) || versionCode < 1) {
|
||||
throw new Error('APK versionCode could not be read');
|
||||
}
|
||||
if (!versionName) throw new Error('APK versionName could not be read');
|
||||
|
||||
const signingCertSha256 = extractSigningCertSha256(filePath);
|
||||
|
||||
return { packageName, versionName, versionCode, signingCertSha256 };
|
||||
}
|
||||
56
backend/src/validation/mobileReleaseSchemas.ts
Normal file
56
backend/src/validation/mobileReleaseSchemas.ts
Normal file
@ -0,0 +1,56 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
export const mobileReleaseCreateBodySchema = z.object({
|
||||
platform: z.enum(['android', 'ios']).optional().default('android'),
|
||||
channel: z.enum(['production', 'beta', 'internal']).optional().default('production'),
|
||||
versionName: z.string().trim().min(1).max(64),
|
||||
versionCode: z.coerce.number().int().min(1).max(2_000_000_000),
|
||||
previousVersionName: z.string().trim().max(64).nullable().optional(),
|
||||
whatsNew: z.string().max(8000).optional().default(''),
|
||||
bugFixes: z.string().max(8000).optional().default(''),
|
||||
updatePolicy: z.enum(['optional', 'recommended', 'mandatory']).optional().default('optional'),
|
||||
rolloutPercent: z.coerce.number().int().min(0).max(100).optional().default(100),
|
||||
});
|
||||
|
||||
export const mobileReleaseUpdateBodySchema = z.object({
|
||||
versionName: z.string().trim().min(1).max(64).optional(),
|
||||
previousVersionName: z.string().trim().max(64).nullable().optional(),
|
||||
whatsNew: z.string().max(8000).optional(),
|
||||
bugFixes: z.string().max(8000).optional(),
|
||||
updatePolicy: z.enum(['optional', 'recommended', 'mandatory']).optional(),
|
||||
rolloutPercent: z.coerce.number().int().min(0).max(100).optional(),
|
||||
});
|
||||
|
||||
export const mobileUpdateSettingsBodySchema = z.object({
|
||||
minSupportedVersionCode: z.coerce.number().int().min(1).max(2_000_000_000).optional(),
|
||||
checkIntervalSeconds: z.coerce.number().int().min(60).max(604800).optional(),
|
||||
expectedPackageName: z.string().trim().min(3).max(255).optional(),
|
||||
});
|
||||
|
||||
export const mobileReleaseListQuerySchema = z.object({
|
||||
platform: z.enum(['android', 'ios']).optional(),
|
||||
channel: z.enum(['production', 'beta', 'internal']).optional(),
|
||||
status: z.enum(['draft', 'pending_validation', 'published', 'suspended', 'retired']).optional(),
|
||||
search: z.string().max(100).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).optional(),
|
||||
offset: z.coerce.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const mobileUpdateCheckQuerySchema = z.object({
|
||||
versionCode: z.coerce.number().int().min(1),
|
||||
versionName: z.string().max(64).optional(),
|
||||
channel: z.enum(['production', 'beta', 'internal']).optional().default('production'),
|
||||
deviceId: z.string().trim().min(4).max(128),
|
||||
});
|
||||
|
||||
export const mobileUpdateEventBodySchema = z.object({
|
||||
eventType: z.enum(['download_start', 'download_ok', 'download_fail', 'install_confirm']),
|
||||
releaseId: z.string().uuid().optional(),
|
||||
versionCode: z.coerce.number().int().min(1).optional(),
|
||||
deviceId: z.string().trim().min(4).max(128).optional(),
|
||||
channel: z.enum(['production', 'beta', 'internal']).optional(),
|
||||
});
|
||||
|
||||
export const mobileReleaseIdParamSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
});
|
||||
@ -8,7 +8,7 @@ server {
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 20m;
|
||||
client_max_body_size 150m;
|
||||
|
||||
location /api/ {
|
||||
proxy_pass http://crypto_wallet_api:4000/api/;
|
||||
|
||||
@ -93,6 +93,10 @@ x-backend-common: &backend-common
|
||||
CLAMAV_PORT: ${CLAMAV_PORT:-3310}
|
||||
CLAMAV_TIMEOUT_MS: ${CLAMAV_TIMEOUT_MS:-30000}
|
||||
REQUIRE_ADMIN_2FA: ${REQUIRE_ADMIN_2FA:-}
|
||||
ANDROID_APK_EXPECTED_CERT_SHA256: ${ANDROID_APK_EXPECTED_CERT_SHA256:-}
|
||||
ANDROID_APK_EXPECTED_PACKAGE: ${ANDROID_APK_EXPECTED_PACKAGE:-com.prediqo.mobile}
|
||||
APK_MAX_UPLOAD_BYTES: ${APK_MAX_UPLOAD_BYTES:-125829120}
|
||||
APK_DOWNLOAD_TOKEN_TTL_SECONDS: ${APK_DOWNLOAD_TOKEN_TTL_SECONDS:-3600}
|
||||
|
||||
services:
|
||||
postgres:
|
||||
@ -218,8 +222,10 @@ services:
|
||||
WS_ENABLED: "false"
|
||||
command: ["sh", "-c", "if [ \"${RUN_MIGRATE_ON_START:-0}\" = \"1\" ]; then node dist/db/migrate.js || exit 1; fi; exec node dist/apps/api.js"]
|
||||
# Persist support/FAQ uploads — without this, FIM baselines outlive files and spam "deleted" alerts.
|
||||
# Nested apk_releases volume keeps APK binaries separable for backup/migration.
|
||||
volumes:
|
||||
- upload_data:/app/data
|
||||
- apk_releases:/app/data/apk-releases
|
||||
expose:
|
||||
- "4000"
|
||||
healthcheck:
|
||||
@ -486,5 +492,6 @@ volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
upload_data:
|
||||
apk_releases:
|
||||
letsencrypt:
|
||||
certbot-www:
|
||||
|
||||
105
docs/MOBILE_APP_RELEASES.md
Normal file
105
docs/MOBILE_APP_RELEASES.md
Normal file
@ -0,0 +1,105 @@
|
||||
# Mobile app releases (Android APK)
|
||||
|
||||
Tloto can distribute Android APK updates from its own infrastructure without Google Play.
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Admin web**: Options → Mobile versions (`/admin/mobile-versions`)
|
||||
- **API public**: `GET /api/v1/app-updates/android`, download + events
|
||||
- **API admin**: `/api/v1/admin/mobile-releases*`
|
||||
- **Storage**: Docker volume `apk_releases` → `/app/data/apk-releases/{staging|published}`
|
||||
- **Flutter**: checks at splash + resume, downloads APK, verifies SHA-256, opens system installer
|
||||
|
||||
## Prerequisites — Android signing
|
||||
|
||||
Upgrades replace the installed app **only if**:
|
||||
|
||||
1. Same `applicationId` (`com.prediqo.mobile`)
|
||||
2. Same signing certificate
|
||||
3. Higher `versionCode`
|
||||
|
||||
### Create a release keystore (once)
|
||||
|
||||
```bash
|
||||
keytool -genkey -v -keystore tloto-release.jks -keyalg RSA -keysize 2048 -validity 10000 -alias tloto
|
||||
```
|
||||
|
||||
Store the `.jks` **offline** (password manager / encrypted backup). Never commit it or leave it only on the VPS.
|
||||
|
||||
### Wire Flutter release signing
|
||||
|
||||
1. Copy `prediqo_mobile/android/key.properties.example` → `key.properties`
|
||||
2. Fill `storePassword`, `keyPassword`, `keyAlias`, `storeFile`
|
||||
3. Build: `flutter build apk --release`
|
||||
|
||||
### Fingerprint for the backend
|
||||
|
||||
```bash
|
||||
keytool -list -v -keystore tloto-release.jks -alias tloto
|
||||
# Copy SHA-256 certificate fingerprint (hex), strip colons
|
||||
```
|
||||
|
||||
Set in `.env` / Compose:
|
||||
|
||||
```env
|
||||
ANDROID_APK_EXPECTED_CERT_SHA256=<hex without colons>
|
||||
ANDROID_APK_EXPECTED_PACKAGE=com.prediqo.mobile
|
||||
```
|
||||
|
||||
Empty fingerprint skips cert check (dev only).
|
||||
|
||||
## Admin publish flow
|
||||
|
||||
1. Create a release (version name + **versionCode** strictly greater than the current published one)
|
||||
2. Upload the signed `.apk`
|
||||
3. Backend validates package name, versionCode, optional cert fingerprint, computes file SHA-256
|
||||
4. Submit → Publish
|
||||
5. Optionally set rollout % (5 / 20 / 50 / 100) and update policy (optional / recommended / mandatory)
|
||||
|
||||
### Suspend / rollback
|
||||
|
||||
- **Suspend** or **retire** stops offering that APK to new checks
|
||||
- Devices that already installed it **cannot** be downgraded; ship a higher `versionCode` hotfix instead
|
||||
|
||||
## Mobile client behaviour
|
||||
|
||||
- Compares installed `buildNumber` (versionCode) to server
|
||||
- Policies:
|
||||
- optional / recommended → dismissible dialog
|
||||
- mandatory (or below `min_supported_version_code`) → blocking dialog; sensitive APIs return **426**
|
||||
- Download over HTTPS with HMAC token; size + SHA-256 verified before install
|
||||
- Android system installer prompt is never bypassed
|
||||
|
||||
## Backup & VPS migration
|
||||
|
||||
```bash
|
||||
# List volumes
|
||||
docker volume ls | grep apk
|
||||
|
||||
# Backup APK volume
|
||||
docker run --rm -v <project>_apk_releases:/data -v "$(pwd)":/backup alpine \
|
||||
tar czf /backup/apk_releases.tgz -C /data .
|
||||
|
||||
# Restore on new host then recreate stack with the same volume name
|
||||
```
|
||||
|
||||
Also dump PostgreSQL tables `mobile_app_releases`, `mobile_app_release_events`, `mobile_app_update_settings`.
|
||||
|
||||
`storage_key` values are relative (`published/<uuid>.apk`) so the mobile `downloadUrl` contract stays API-driven if you later move blobs to object storage.
|
||||
|
||||
## iOS
|
||||
|
||||
Architecture reserves `platform=ios` but **does not** distribute IPA files. Future: App Store / TestFlight links only.
|
||||
|
||||
## Manual test checklist
|
||||
|
||||
- [ ] Detect new version (versionCode +1)
|
||||
- [ ] Optional update — Later still uses the app
|
||||
- [ ] Recommended update messaging
|
||||
- [ ] Mandatory update blocks bets / withdraw (426)
|
||||
- [ ] Interrupted download / bad network
|
||||
- [ ] Corrupted APK / wrong SHA-256 rejected
|
||||
- [ ] Wrong signing cert rejected on upload
|
||||
- [ ] User cancels Android installer
|
||||
- [ ] Local session retained after successful update
|
||||
- [ ] Suspended release no longer offered
|
||||
@ -6,7 +6,7 @@ server {
|
||||
server_name ${CERTBOT_DOMAIN1} _;
|
||||
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||
|
||||
client_max_body_size 20m;
|
||||
client_max_body_size 150m;
|
||||
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
|
||||
@ -25,7 +25,7 @@ server {
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 20m;
|
||||
client_max_body_size 150m;
|
||||
|
||||
location /api/ {
|
||||
set $backend_api backend;
|
||||
|
||||
@ -23,7 +23,7 @@ server {
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
|
||||
client_max_body_size 20m;
|
||||
client_max_body_size 150m;
|
||||
|
||||
location /api/ {
|
||||
set $backend_api backend;
|
||||
|
||||
@ -1,3 +1,6 @@
|
||||
import java.util.Properties
|
||||
import java.io.FileInputStream
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("kotlin-android")
|
||||
@ -5,6 +8,15 @@ plugins {
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
val keystorePropertiesFile = rootProject.file("key.properties")
|
||||
val keystoreProperties = Properties()
|
||||
val hasReleaseKeystore =
|
||||
keystorePropertiesFile.exists().also { exists ->
|
||||
if (exists) {
|
||||
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.prediqo.mobile"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
@ -20,21 +32,33 @@ android {
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.prediqo.mobile"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = flutter.minSdkVersion
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
if (hasReleaseKeystore) {
|
||||
create("release") {
|
||||
keyAlias = keystoreProperties["keyAlias"] as String
|
||||
keyPassword = keystoreProperties["keyPassword"] as String
|
||||
storeFile = file(keystoreProperties["storeFile"] as String)
|
||||
storePassword = keystoreProperties["storePassword"] as String
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// TODO: Add your own signing config for the release build.
|
||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
// Prefer key.properties release keystore; fall back to debug for local flutter run --release.
|
||||
signingConfig =
|
||||
if (hasReleaseKeystore) {
|
||||
signingConfigs.getByName("release")
|
||||
} else {
|
||||
signingConfigs.getByName("debug")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
|
||||
<application
|
||||
android:label="Tloto"
|
||||
android:name="${applicationName}"
|
||||
@ -23,6 +24,15 @@
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileProvider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
<meta-data
|
||||
android:name="flutterEmbedding"
|
||||
android:value="2" />
|
||||
@ -40,5 +50,9 @@
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
<data android:scheme="http"/>
|
||||
</intent>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.VIEW"/>
|
||||
<data android:mimeType="application/vnd.android.package-archive"/>
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
|
||||
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths>
|
||||
<cache-path name="cache" path="." />
|
||||
<external-cache-path name="external_cache" path="." />
|
||||
<files-path name="files" path="." />
|
||||
</paths>
|
||||
6
prediqo_mobile/android/key.properties.example
Normal file
6
prediqo_mobile/android/key.properties.example
Normal file
@ -0,0 +1,6 @@
|
||||
# Copy to key.properties (gitignored) and fill with your release keystore values.
|
||||
# Never commit key.properties, *.jks, or *.keystore. Keep a secure offline backup of the keystore.
|
||||
storePassword=CHANGE_ME
|
||||
keyPassword=CHANGE_ME
|
||||
keyAlias=tloto
|
||||
storeFile=../keystore/tloto-release.jks
|
||||
@ -31,6 +31,8 @@ import '../network/connectivity_controller.dart';
|
||||
import '../realtime/game_socket_service.dart';
|
||||
import '../realtime/support_socket_service.dart';
|
||||
import '../../l10n/locale_controller.dart';
|
||||
import '../../features/app_update/app_update_coordinator.dart';
|
||||
import '../../features/app_update/data/app_update_repository.dart';
|
||||
|
||||
final sl = GetIt.instance;
|
||||
|
||||
@ -51,6 +53,14 @@ Future<void> configureDependencies({AppConfig? config}) async {
|
||||
if (!sl.isRegistered<ApiClient>()) {
|
||||
sl.registerLazySingleton<ApiClient>(() => ApiClient(config: sl()));
|
||||
}
|
||||
if (!sl.isRegistered<AppUpdateRepository>()) {
|
||||
sl.registerLazySingleton<AppUpdateRepository>(() => AppUpdateRepository(sl()));
|
||||
}
|
||||
if (!sl.isRegistered<AppUpdateCoordinator>()) {
|
||||
sl.registerLazySingleton<AppUpdateCoordinator>(
|
||||
() => AppUpdateCoordinator(sl(), config: sl()),
|
||||
);
|
||||
}
|
||||
if (!sl.isRegistered<GameSocketService>()) {
|
||||
sl.registerLazySingleton<GameSocketService>(() => GameSocketService(sl(), sl()));
|
||||
}
|
||||
|
||||
@ -1,7 +1,9 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import '../config/app_config.dart';
|
||||
import '../storage/secure_storage.dart';
|
||||
|
||||
@ -23,6 +25,7 @@ class ApiClient {
|
||||
},
|
||||
),
|
||||
);
|
||||
_dio.interceptors.add(_AppVersionInterceptor());
|
||||
_dio.interceptors.add(_AuthInterceptor(this));
|
||||
if (config.enableApiLogging && kDebugMode) {
|
||||
_dio.interceptors.add(
|
||||
@ -72,6 +75,30 @@ class ApiClient {
|
||||
Future<String?> readAccessToken() => _storage.readAccessToken();
|
||||
}
|
||||
|
||||
/// Attaches mobile version headers used by backend force-update gates.
|
||||
class _AppVersionInterceptor extends Interceptor {
|
||||
static String? _cachedVersionCode;
|
||||
static String? _cachedPlatform;
|
||||
|
||||
@override
|
||||
void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
|
||||
try {
|
||||
_cachedPlatform ??= Platform.isAndroid
|
||||
? 'android'
|
||||
: (Platform.isIOS ? 'ios' : 'unknown');
|
||||
if (_cachedVersionCode == null) {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
_cachedVersionCode = info.buildNumber;
|
||||
}
|
||||
options.headers['X-Tloto-App-Version-Code'] = _cachedVersionCode;
|
||||
options.headers['X-Tloto-Platform'] = _cachedPlatform;
|
||||
} catch (_) {
|
||||
// Headers are best-effort.
|
||||
}
|
||||
handler.next(options);
|
||||
}
|
||||
}
|
||||
|
||||
class _AuthInterceptor extends Interceptor {
|
||||
_AuthInterceptor(this._client);
|
||||
|
||||
|
||||
@ -20,6 +20,9 @@ class ConnectivityController extends ChangeNotifier with WidgetsBindingObserver
|
||||
bool _online = true;
|
||||
bool _started = false;
|
||||
|
||||
/// Optional hook set by app bootstrap (e.g. AppUpdateCoordinator.onResume).
|
||||
void Function()? onAppResumed;
|
||||
|
||||
bool get isOnline => _online;
|
||||
bool get isOffline => !_online;
|
||||
|
||||
@ -63,6 +66,7 @@ class ConnectivityController extends ChangeNotifier with WidgetsBindingObserver
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
unawaited(refresh());
|
||||
onAppResumed?.call();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -0,0 +1,83 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../core/di/injection.dart';
|
||||
import '../../core/router/app_router.dart';
|
||||
import 'data/app_update_models.dart';
|
||||
import 'data/app_update_repository.dart';
|
||||
import 'presentation/app_update_dialog.dart';
|
||||
|
||||
/// Coordinates splash / resume update checks and UI prompts.
|
||||
class AppUpdateCoordinator {
|
||||
AppUpdateCoordinator(this._repository, {AppConfig? config}) : _config = config;
|
||||
|
||||
final AppUpdateRepository _repository;
|
||||
final AppConfig? _config;
|
||||
|
||||
AppUpdateCheckResult? lastResult;
|
||||
bool _dialogOpen = false;
|
||||
|
||||
Future<void> onColdStart() async {
|
||||
await _repository.confirmInstallIfNeeded();
|
||||
await checkAndPrompt(force: true, blockNavigationIfMandatory: true);
|
||||
}
|
||||
|
||||
Future<void> onResume() async {
|
||||
await checkAndPrompt(force: false, blockNavigationIfMandatory: false);
|
||||
}
|
||||
|
||||
Future<AppUpdateCheckResult?> checkAndPrompt({
|
||||
required bool force,
|
||||
required bool blockNavigationIfMandatory,
|
||||
}) async {
|
||||
AppUpdateCheckResult? result;
|
||||
try {
|
||||
result = await _repository.checkForUpdate(force: force);
|
||||
} catch (_) {
|
||||
// Fall back to compile-time store URL hint when API is unreachable.
|
||||
return null;
|
||||
}
|
||||
if (result == null) return lastResult;
|
||||
lastResult = result;
|
||||
|
||||
final interval = result.checkIntervalSeconds;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final lastPromptMs = prefs.getInt('tloto_update_last_prompt_ms') ?? 0;
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
if (!force && !result.isMandatory && now - lastPromptMs < interval * 1000) {
|
||||
return result;
|
||||
}
|
||||
|
||||
final show = await _repository.shouldShowOptional(result);
|
||||
if (!result.updateAvailable || !show) return result;
|
||||
|
||||
final ctx = rootNavigatorKey.currentContext;
|
||||
if (ctx == null || !ctx.mounted || _dialogOpen) return result;
|
||||
|
||||
_dialogOpen = true;
|
||||
await prefs.setInt('tloto_update_last_prompt_ms', now);
|
||||
try {
|
||||
await showAppUpdateDialog(ctx, update: result, repository: _repository);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Legacy tap handler: prefer in-app flow, else open APP_STORE_URL.
|
||||
Future<void> handleManualTap(BuildContext context) async {
|
||||
final result = await checkAndPrompt(force: true, blockNavigationIfMandatory: false);
|
||||
if (result != null && result.updateAvailable) return;
|
||||
|
||||
final store = _config?.appStoreUrl?.trim() ??
|
||||
(sl.isRegistered<AppConfig>() ? sl<AppConfig>().appStoreUrl?.trim() : null);
|
||||
if (store != null && store.isNotEmpty) {
|
||||
final uri = Uri.tryParse(store);
|
||||
if (uri != null) {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
/// Server payload for Android in-app APK updates.
|
||||
class AppUpdateCheckResult {
|
||||
const AppUpdateCheckResult({
|
||||
required this.updateAvailable,
|
||||
required this.blocked,
|
||||
required this.minSupportedVersionCode,
|
||||
required this.checkIntervalSeconds,
|
||||
this.policy,
|
||||
this.versionName,
|
||||
this.versionCode,
|
||||
this.whatsNew,
|
||||
this.bugFixes,
|
||||
this.fileSizeBytes,
|
||||
this.sha256,
|
||||
this.downloadUrl,
|
||||
this.publishedAt,
|
||||
this.packageName,
|
||||
});
|
||||
|
||||
final bool updateAvailable;
|
||||
final bool blocked;
|
||||
final String? policy;
|
||||
final String? versionName;
|
||||
final int? versionCode;
|
||||
final String? whatsNew;
|
||||
final String? bugFixes;
|
||||
final int? fileSizeBytes;
|
||||
final String? sha256;
|
||||
final String? downloadUrl;
|
||||
final int minSupportedVersionCode;
|
||||
final int checkIntervalSeconds;
|
||||
final String? publishedAt;
|
||||
final String? packageName;
|
||||
|
||||
bool get isMandatory =>
|
||||
blocked || policy == 'mandatory' || (versionCode != null && versionCode! > 0 && blocked);
|
||||
|
||||
bool get isRecommended => policy == 'recommended';
|
||||
|
||||
factory AppUpdateCheckResult.fromJson(Map<String, dynamic> json) {
|
||||
return AppUpdateCheckResult(
|
||||
updateAvailable: json['updateAvailable'] == true,
|
||||
blocked: json['blocked'] == true,
|
||||
policy: json['policy'] as String?,
|
||||
versionName: json['versionName'] as String?,
|
||||
versionCode: (json['versionCode'] as num?)?.toInt(),
|
||||
whatsNew: json['whatsNew'] as String?,
|
||||
bugFixes: json['bugFixes'] as String?,
|
||||
fileSizeBytes: (json['fileSizeBytes'] as num?)?.toInt(),
|
||||
sha256: json['sha256'] as String?,
|
||||
downloadUrl: json['downloadUrl'] as String?,
|
||||
minSupportedVersionCode: (json['minSupportedVersionCode'] as num?)?.toInt() ?? 1,
|
||||
checkIntervalSeconds: (json['checkIntervalSeconds'] as num?)?.toInt() ?? 21600,
|
||||
publishedAt: json['publishedAt'] as String?,
|
||||
packageName: json['packageName'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,208 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/network/api_client.dart';
|
||||
import 'app_update_models.dart';
|
||||
|
||||
const _kDeviceIdKey = 'tloto_update_device_id';
|
||||
const _kSnoozeVersionCodeKey = 'tloto_update_snooze_vc';
|
||||
const _kLastCheckMsKey = 'tloto_update_last_check_ms';
|
||||
const _kPendingInstallVcKey = 'tloto_pending_install_vc';
|
||||
const _kPendingInstallReleaseIdKey = 'tloto_pending_install_release_id';
|
||||
|
||||
/// Fetches update manifests, downloads APKs, and reports telemetry.
|
||||
class AppUpdateRepository {
|
||||
AppUpdateRepository(this._api);
|
||||
|
||||
final ApiClient _api;
|
||||
|
||||
Future<String> getOrCreateDeviceId() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
var id = prefs.getString(_kDeviceIdKey);
|
||||
if (id == null || id.length < 8) {
|
||||
id = const Uuid().v4();
|
||||
await prefs.setString(_kDeviceIdKey, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
Future<PackageInfo> packageInfo() => PackageInfo.fromPlatform();
|
||||
|
||||
Future<int> installedVersionCode() async {
|
||||
final info = await packageInfo();
|
||||
return int.tryParse(info.buildNumber) ?? 0;
|
||||
}
|
||||
|
||||
Future<AppUpdateCheckResult?> checkForUpdate({bool force = false}) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final lastMs = prefs.getInt(_kLastCheckMsKey) ?? 0;
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
// Soft client throttle; server also returns checkIntervalSeconds.
|
||||
if (!force && lastMs > 0 && now - lastMs < 60 * 1000) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final versionCode = await installedVersionCode();
|
||||
final info = await packageInfo();
|
||||
final deviceId = await getOrCreateDeviceId();
|
||||
|
||||
try {
|
||||
final res = await _api.dio.get<Map<String, dynamic>>(
|
||||
'/api/v1/app-updates/android',
|
||||
queryParameters: {
|
||||
'versionCode': versionCode,
|
||||
'versionName': info.version,
|
||||
'channel': 'production',
|
||||
'deviceId': deviceId,
|
||||
},
|
||||
options: Options(
|
||||
receiveTimeout: const Duration(seconds: 20),
|
||||
extra: {'skipAuthRefresh': true},
|
||||
),
|
||||
);
|
||||
await prefs.setInt(_kLastCheckMsKey, now);
|
||||
final data = res.data;
|
||||
if (data == null) return null;
|
||||
return AppUpdateCheckResult.fromJson(data);
|
||||
} on DioException catch (e) {
|
||||
throw AppException.fromDio(e, fallback: 'Update check failed');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> shouldShowOptional(AppUpdateCheckResult update) async {
|
||||
if (!update.updateAvailable || update.versionCode == null) return false;
|
||||
if (update.isMandatory) return true;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final snoozed = prefs.getInt(_kSnoozeVersionCodeKey);
|
||||
return snoozed != update.versionCode;
|
||||
}
|
||||
|
||||
Future<void> snooze(int versionCode) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setInt(_kSnoozeVersionCodeKey, versionCode);
|
||||
}
|
||||
|
||||
Future<void> markPendingInstall({required int versionCode, String? releaseId}) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setInt(_kPendingInstallVcKey, versionCode);
|
||||
if (releaseId != null) {
|
||||
await prefs.setString(_kPendingInstallReleaseIdKey, releaseId);
|
||||
}
|
||||
}
|
||||
|
||||
/// Confirms install after cold start if buildNumber matches pending target.
|
||||
Future<void> confirmInstallIfNeeded() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final pending = prefs.getInt(_kPendingInstallVcKey);
|
||||
if (pending == null) return;
|
||||
final current = await installedVersionCode();
|
||||
if (current < pending) return;
|
||||
final releaseId = prefs.getString(_kPendingInstallReleaseIdKey);
|
||||
final deviceId = await getOrCreateDeviceId();
|
||||
try {
|
||||
await _api.dio.post(
|
||||
'/api/v1/app-updates/android/events',
|
||||
data: {
|
||||
'eventType': 'install_confirm',
|
||||
'versionCode': current,
|
||||
'deviceId': deviceId,
|
||||
if (releaseId != null) 'releaseId': releaseId,
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
// best-effort telemetry
|
||||
}
|
||||
await prefs.remove(_kPendingInstallVcKey);
|
||||
await prefs.remove(_kPendingInstallReleaseIdKey);
|
||||
}
|
||||
|
||||
Future<void> reportEvent({
|
||||
required String eventType,
|
||||
String? releaseId,
|
||||
int? versionCode,
|
||||
}) async {
|
||||
final deviceId = await getOrCreateDeviceId();
|
||||
try {
|
||||
await _api.dio.post(
|
||||
'/api/v1/app-updates/android/events',
|
||||
data: {
|
||||
'eventType': eventType,
|
||||
'deviceId': deviceId,
|
||||
if (releaseId != null) 'releaseId': releaseId,
|
||||
if (versionCode != null) 'versionCode': versionCode,
|
||||
},
|
||||
);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// Downloads APK to temp dir, verifies size + SHA-256, returns local file.
|
||||
Future<File> downloadApk(
|
||||
AppUpdateCheckResult update, {
|
||||
void Function(int received, int total)? onProgress,
|
||||
CancelToken? cancelToken,
|
||||
}) async {
|
||||
final url = update.downloadUrl;
|
||||
if (url == null || url.isEmpty) {
|
||||
throw AppException('Missing download URL');
|
||||
}
|
||||
final dir = await getTemporaryDirectory();
|
||||
final file = File('${dir.path}/tloto-update-${update.versionCode}.apk');
|
||||
if (await file.exists()) {
|
||||
await file.delete();
|
||||
}
|
||||
|
||||
final releaseId = _releaseIdFromUrl(url);
|
||||
await reportEvent(eventType: 'download_start', releaseId: releaseId, versionCode: update.versionCode);
|
||||
|
||||
try {
|
||||
await _api.dio.download(
|
||||
url,
|
||||
file.path,
|
||||
cancelToken: cancelToken,
|
||||
onReceiveProgress: onProgress,
|
||||
options: Options(
|
||||
receiveTimeout: const Duration(minutes: 10),
|
||||
sendTimeout: const Duration(minutes: 2),
|
||||
followRedirects: true,
|
||||
validateStatus: (s) => s != null && s < 400,
|
||||
),
|
||||
);
|
||||
} on DioException catch (e) {
|
||||
await reportEvent(eventType: 'download_fail', releaseId: releaseId, versionCode: update.versionCode);
|
||||
throw AppException.fromDio(e, fallback: 'Download failed');
|
||||
}
|
||||
|
||||
final bytes = await file.length();
|
||||
if (update.fileSizeBytes != null && update.fileSizeBytes! > 0 && bytes != update.fileSizeBytes) {
|
||||
await file.delete();
|
||||
await reportEvent(eventType: 'download_fail', releaseId: releaseId, versionCode: update.versionCode);
|
||||
throw AppException('Downloaded size mismatch');
|
||||
}
|
||||
|
||||
final digest = await sha256.bind(file.openRead()).first;
|
||||
final hex = digest.toString();
|
||||
if (update.sha256 != null && update.sha256!.isNotEmpty && hex.toLowerCase() != update.sha256!.toLowerCase()) {
|
||||
await file.delete();
|
||||
await reportEvent(eventType: 'download_fail', releaseId: releaseId, versionCode: update.versionCode);
|
||||
throw AppException('SHA-256 verification failed');
|
||||
}
|
||||
|
||||
await reportEvent(eventType: 'download_ok', releaseId: releaseId, versionCode: update.versionCode);
|
||||
if (update.versionCode != null) {
|
||||
await markPendingInstall(versionCode: update.versionCode!, releaseId: releaseId);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
String? _releaseIdFromUrl(String url) {
|
||||
final match = RegExp(r'/download/([0-9a-fA-F-]{36})').firstMatch(url);
|
||||
return match?.group(1);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,166 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:open_filex/open_filex.dart';
|
||||
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../data/app_update_models.dart';
|
||||
import '../data/app_update_repository.dart';
|
||||
|
||||
String _formatBytes(int? n) {
|
||||
if (n == null) return '—';
|
||||
if (n < 1024 * 1024) return '${(n / 1024).toFixed(1)} KB';
|
||||
return '${(n / (1024 * 1024)).toFixed(1)} MB';
|
||||
}
|
||||
|
||||
extension on double {
|
||||
String toFixed(int fraction) => toStringAsFixed(fraction);
|
||||
}
|
||||
|
||||
/// Shows a policy-aware update dialog; returns true if user started install.
|
||||
Future<bool> showAppUpdateDialog(
|
||||
BuildContext context, {
|
||||
required AppUpdateCheckResult update,
|
||||
required AppUpdateRepository repository,
|
||||
}) async {
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
barrierDismissible: !update.isMandatory,
|
||||
builder: (ctx) => _AppUpdateDialog(update: update, repository: repository),
|
||||
);
|
||||
return result == true;
|
||||
}
|
||||
|
||||
class _AppUpdateDialog extends StatefulWidget {
|
||||
const _AppUpdateDialog({required this.update, required this.repository});
|
||||
|
||||
final AppUpdateCheckResult update;
|
||||
final AppUpdateRepository repository;
|
||||
|
||||
@override
|
||||
State<_AppUpdateDialog> createState() => _AppUpdateDialogState();
|
||||
}
|
||||
|
||||
class _AppUpdateDialogState extends State<_AppUpdateDialog> {
|
||||
bool _downloading = false;
|
||||
double? _progress;
|
||||
String? _error;
|
||||
CancelToken? _cancelToken;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_cancelToken?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _downloadAndInstall() async {
|
||||
setState(() {
|
||||
_downloading = true;
|
||||
_error = null;
|
||||
_progress = 0;
|
||||
});
|
||||
_cancelToken = CancelToken();
|
||||
try {
|
||||
final file = await widget.repository.downloadApk(
|
||||
widget.update,
|
||||
cancelToken: _cancelToken,
|
||||
onProgress: (received, total) {
|
||||
if (!mounted || total <= 0) return;
|
||||
setState(() => _progress = received / total);
|
||||
},
|
||||
);
|
||||
if (!mounted) return;
|
||||
final open = await OpenFilex.open(file.path, type: 'application/vnd.android.package-archive');
|
||||
if (!mounted) return;
|
||||
if (open.type != ResultType.done) {
|
||||
setState(() {
|
||||
_downloading = false;
|
||||
_error = open.message;
|
||||
});
|
||||
return;
|
||||
}
|
||||
Navigator.of(context).pop(true);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_downloading = false;
|
||||
_error = e.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
final u = widget.update;
|
||||
final title = u.isMandatory
|
||||
? s.updateRequiredTitle
|
||||
: (u.isRecommended ? s.updateRecommendedTitle : s.updateAvailableTitle);
|
||||
|
||||
return PopScope(
|
||||
canPop: !u.isMandatory && !_downloading,
|
||||
child: AlertDialog(
|
||||
title: Text(title, style: const TextStyle(fontWeight: FontWeight.w800)),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'${s.updateVersionLabel}: ${u.versionName ?? '—'} (${u.versionCode ?? '—'})',
|
||||
style: const TextStyle(fontWeight: FontWeight.w700),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text('${s.updateSizeLabel}: ${_formatBytes(u.fileSizeBytes)}'),
|
||||
if ((u.whatsNew ?? '').trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(s.updateWhatsNew, style: const TextStyle(fontWeight: FontWeight.w700)),
|
||||
const SizedBox(height: 4),
|
||||
Text(u.whatsNew!.trim()),
|
||||
],
|
||||
if ((u.bugFixes ?? '').trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(s.updateBugFixes, style: const TextStyle(fontWeight: FontWeight.w700)),
|
||||
const SizedBox(height: 4),
|
||||
Text(u.bugFixes!.trim()),
|
||||
],
|
||||
if (_downloading) ...[
|
||||
const SizedBox(height: 16),
|
||||
LinearProgressIndicator(
|
||||
value: _progress,
|
||||
color: AppColors.primary,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
_progress == null
|
||||
? s.updateDownloading
|
||||
: '${s.updateDownloading} ${((_progress ?? 0) * 100).toStringAsFixed(0)}%',
|
||||
),
|
||||
],
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
if (!u.isMandatory && !_downloading)
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
if (u.versionCode != null) {
|
||||
await widget.repository.snooze(u.versionCode!);
|
||||
}
|
||||
if (context.mounted) Navigator.of(context).pop(false);
|
||||
},
|
||||
child: Text(s.updateLater),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _downloading ? null : _downloadAndInstall,
|
||||
child: Text(s.updateNow),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -2,12 +2,11 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import '../../../core/config/app_config.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/prediqo_logo.dart';
|
||||
import '../../app_update/app_update_coordinator.dart';
|
||||
import '../../auth/bloc/auth_bloc.dart';
|
||||
|
||||
/// Minimum branding dwell before leaving splash (real session still required).
|
||||
@ -81,13 +80,12 @@ class _SplashScreenState extends State<SplashScreen> {
|
||||
}
|
||||
|
||||
Future<void> _checkAppUpdate() async {
|
||||
final config = sl.isRegistered<AppConfig>() ? sl<AppConfig>() : null;
|
||||
final latest = config?.latestAppVersion?.trim();
|
||||
if (latest == null || latest.isEmpty) return;
|
||||
if (!sl.isRegistered<AppUpdateCoordinator>()) return;
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
await sl<AppUpdateCoordinator>().onColdStart();
|
||||
if (!mounted) return;
|
||||
setState(() => _updateAvailable = splashIsNewerVersion(latest, info.version));
|
||||
final last = sl<AppUpdateCoordinator>().lastResult;
|
||||
setState(() => _updateAvailable = last?.updateAvailable == true);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
|
||||
@ -661,6 +661,16 @@ class AppStrings {
|
||||
'A new version is available. Open the store to update.',
|
||||
'Une nouvelle version est disponible. Ouvrez le store pour mettre à jour.',
|
||||
);
|
||||
String get updateAvailableTitle => t('Update available', 'Mise à jour disponible');
|
||||
String get updateRecommendedTitle => t('Update recommended', 'Mise à jour recommandée');
|
||||
String get updateRequiredTitle => t('Update required', 'Mise à jour obligatoire');
|
||||
String get updateVersionLabel => t('Version', 'Version');
|
||||
String get updateSizeLabel => t('Download size', 'Taille du téléchargement');
|
||||
String get updateWhatsNew => t("What's new", 'Nouveautés');
|
||||
String get updateBugFixes => t('Fixes', 'Corrections');
|
||||
String get updateNow => t('Update now', 'Mettre à jour');
|
||||
String get updateLater => t('Later', 'Plus tard');
|
||||
String get updateDownloading => t('Downloading…', 'Téléchargement…');
|
||||
String get notificationsTitle => t('Notifications', 'Notifications');
|
||||
String get noNotifications => t('No notifications yet', 'Aucune notification');
|
||||
String get markAllRead => t('Mark all read', 'Tout marquer lu');
|
||||
|
||||
@ -1,10 +1,20 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'app.dart';
|
||||
import 'core/config/app_config.dart';
|
||||
import 'core/di/injection.dart';
|
||||
import 'core/network/connectivity_controller.dart';
|
||||
import 'features/app_update/app_update_coordinator.dart';
|
||||
|
||||
Future<void> main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await configureDependencies(config: AppConfig.fromEnvironment());
|
||||
// Soft update re-check when the app returns to foreground.
|
||||
if (sl.isRegistered<ConnectivityController>() && sl.isRegistered<AppUpdateCoordinator>()) {
|
||||
sl<ConnectivityController>().onAppResumed = () {
|
||||
unawaited(sl<AppUpdateCoordinator>().onResume());
|
||||
};
|
||||
}
|
||||
runApp(const PrediqoApp());
|
||||
}
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import '../../core/config/app_config.dart';
|
||||
import '../../core/di/injection.dart';
|
||||
import '../../features/app_update/app_update_coordinator.dart';
|
||||
import '../../l10n/app_strings.dart';
|
||||
import '../../shared/widgets/app_snackbar.dart';
|
||||
|
||||
@ -21,13 +19,17 @@ bool isNewerAppVersion(String latest, String current) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/// True when the last server check reported an available update.
|
||||
Future<bool> checkAppUpdateAvailable() async {
|
||||
final config = sl.isRegistered<AppConfig>() ? sl<AppConfig>() : null;
|
||||
final latest = config?.latestAppVersion?.trim();
|
||||
if (latest == null || latest.isEmpty) return false;
|
||||
if (!sl.isRegistered<AppUpdateCoordinator>()) return false;
|
||||
final last = sl<AppUpdateCoordinator>().lastResult;
|
||||
if (last != null) return last.updateAvailable;
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
return isNewerAppVersion(latest, info.version);
|
||||
final result = await sl<AppUpdateCoordinator>().checkAndPrompt(
|
||||
force: false,
|
||||
blockNavigationIfMandatory: false,
|
||||
);
|
||||
return result?.updateAvailable == true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
@ -37,20 +39,14 @@ Future<void> handleAppUpdateTap(
|
||||
BuildContext context, {
|
||||
required bool updateAvailable,
|
||||
}) async {
|
||||
final s = context.strings;
|
||||
final config = sl.isRegistered<AppConfig>() ? sl<AppConfig>() : null;
|
||||
final storeUrl = config?.appStoreUrl?.trim();
|
||||
if (updateAvailable && storeUrl != null && storeUrl.isNotEmpty) {
|
||||
final uri = Uri.tryParse(storeUrl);
|
||||
if (uri != null) {
|
||||
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
if (sl.isRegistered<AppUpdateCoordinator>()) {
|
||||
await sl<AppUpdateCoordinator>().handleManualTap(context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!context.mounted) return;
|
||||
if (updateAvailable) {
|
||||
showSuccessSnackBar(context, s.updateAvailableHint);
|
||||
showSuccessSnackBar(context, context.strings.updateAvailableHint);
|
||||
} else {
|
||||
showSuccessSnackBar(context, s.appUpToDate);
|
||||
showSuccessSnackBar(context, context.strings.appUpToDate);
|
||||
}
|
||||
}
|
||||
|
||||
@ -114,13 +114,13 @@ packages:
|
||||
source: hosted
|
||||
version: "0.3.5+2"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: crypto
|
||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.7"
|
||||
version: "3.0.8"
|
||||
csslib:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -604,6 +604,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.6.0"
|
||||
open_filex:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: open_filex
|
||||
sha256: "0c3fe80e73f0b3200fef6e175b83dae9790dd23c9cdbb6d15f46e2ff10ae84ad"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.0"
|
||||
package_info_plus:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
|
||||
@ -32,6 +32,8 @@ dependencies:
|
||||
path_provider: ^2.1.5
|
||||
image_picker: ^1.1.2
|
||||
connectivity_plus: ^7.3.2
|
||||
crypto: ^3.0.8
|
||||
open_filex: ^5.0.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@ -223,6 +223,11 @@ export const AdminUserPermissionsPage = lazyNamed(
|
||||
() => import('../../features/rbac/AdminUserPermissionsPage'),
|
||||
'AdminUserPermissionsPage'
|
||||
);
|
||||
export const MobileVersionsAdminPage = lazyNamed(
|
||||
'MobileVersionsAdminPage',
|
||||
() => import('../../features/mobile-versions/MobileVersionsAdminPage'),
|
||||
'MobileVersionsAdminPage'
|
||||
);
|
||||
|
||||
/** Exact path → page preload. Longest match wins for nested paths. */
|
||||
const PATH_PRELOAD: Array<{ path: string; preload: () => Promise<unknown> }> = [
|
||||
@ -262,6 +267,7 @@ const PATH_PRELOAD: Array<{ path: string; preload: () => Promise<unknown> }> = [
|
||||
{ path: '/admin/network', preload: NetworkStatusPage.preload },
|
||||
{ path: '/admin/rbac', preload: RoleManagementPage.preload },
|
||||
{ path: '/admin/admin-users', preload: AdminUsersPage.preload },
|
||||
{ path: '/admin/mobile-versions', preload: MobileVersionsAdminPage.preload },
|
||||
].sort((a, b) => b.path.length - a.path.length);
|
||||
|
||||
/** Warm the JS chunk for a destination before navigation. */
|
||||
|
||||
@ -48,6 +48,7 @@ import {
|
||||
RoleManagementPage,
|
||||
AdminUsersPage,
|
||||
AdminUserPermissionsPage,
|
||||
MobileVersionsAdminPage,
|
||||
} from './routePrefetch';
|
||||
|
||||
function RouteFallback() {
|
||||
@ -335,6 +336,14 @@ export const router = createBrowserRouter([
|
||||
</L>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/mobile-versions',
|
||||
element: (
|
||||
<L>
|
||||
<MobileVersionsAdminPage />
|
||||
</L>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/solo-encouragement',
|
||||
element: (
|
||||
|
||||
@ -0,0 +1,563 @@
|
||||
/**
|
||||
* Admin UI for Android APK release lifecycle: create, upload, publish, suspend, stats.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
MenuItem,
|
||||
Select,
|
||||
Stack,
|
||||
Tab,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Tabs,
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import PhoneAndroidRoundedIcon from '@mui/icons-material/PhoneAndroidRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { PermissionGate } from '../../shared/auth/PermissionGate';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
import {
|
||||
createMobileRelease,
|
||||
getMobileReleaseStats,
|
||||
getMobileUpdateSettings,
|
||||
listMobileReleases,
|
||||
publishMobileRelease,
|
||||
retireMobileRelease,
|
||||
submitMobileRelease,
|
||||
suspendMobileRelease,
|
||||
updateMobileRelease,
|
||||
updateMobileUpdateSettings,
|
||||
uploadMobileApk,
|
||||
type MobileAppRelease,
|
||||
type MobileUpdatePolicy,
|
||||
} from './api/mobileVersionsApi';
|
||||
|
||||
function formatBytes(n: number | null): string {
|
||||
if (n == null) return '—';
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function statusColor(status: string): 'default' | 'success' | 'warning' | 'error' | 'info' {
|
||||
switch (status) {
|
||||
case 'published':
|
||||
return 'success';
|
||||
case 'pending_validation':
|
||||
return 'info';
|
||||
case 'suspended':
|
||||
return 'warning';
|
||||
case 'retired':
|
||||
return 'error';
|
||||
default:
|
||||
return 'default';
|
||||
}
|
||||
}
|
||||
|
||||
type CreateForm = {
|
||||
versionName: string;
|
||||
versionCode: string;
|
||||
previousVersionName: string;
|
||||
whatsNew: string;
|
||||
bugFixes: string;
|
||||
updatePolicy: MobileUpdatePolicy;
|
||||
rolloutPercent: string;
|
||||
};
|
||||
|
||||
const emptyCreate: CreateForm = {
|
||||
versionName: '',
|
||||
versionCode: '',
|
||||
previousVersionName: '',
|
||||
whatsNew: '',
|
||||
bugFixes: '',
|
||||
updatePolicy: 'optional',
|
||||
rolloutPercent: '100',
|
||||
};
|
||||
|
||||
function errMsg(e: unknown, fallback: string): string {
|
||||
return (e as { response?: { data?: { error?: string } } })?.response?.data?.error || fallback;
|
||||
}
|
||||
|
||||
export function MobileVersionsAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const { can } = useAuth();
|
||||
const canManage = can('admin.mobile_releases.manage');
|
||||
const qc = useQueryClient();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [tab, setTab] = useState(0);
|
||||
const [statusFilter, setStatusFilter] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [form, setForm] = useState<CreateForm>(emptyCreate);
|
||||
const [selected, setSelected] = useState<MobileAppRelease | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [settingsForm, setSettingsForm] = useState({
|
||||
minSupportedVersionCode: '1',
|
||||
checkIntervalSeconds: '21600',
|
||||
expectedPackageName: 'com.prediqo.mobile',
|
||||
});
|
||||
|
||||
const listQ = useQuery({
|
||||
queryKey: ['admin-mobile-releases', statusFilter, search],
|
||||
queryFn: () =>
|
||||
listMobileReleases({
|
||||
status: statusFilter || undefined,
|
||||
search: search || undefined,
|
||||
limit: 100,
|
||||
}),
|
||||
});
|
||||
|
||||
const statsQ = useQuery({
|
||||
queryKey: ['admin-mobile-release-stats'],
|
||||
queryFn: getMobileReleaseStats,
|
||||
enabled: tab === 1,
|
||||
});
|
||||
|
||||
const settingsQ = useQuery({
|
||||
queryKey: ['admin-mobile-update-settings'],
|
||||
queryFn: async () => {
|
||||
const s = await getMobileUpdateSettings();
|
||||
setSettingsForm({
|
||||
minSupportedVersionCode: String(s.minSupportedVersionCode),
|
||||
checkIntervalSeconds: String(s.checkIntervalSeconds),
|
||||
expectedPackageName: s.expectedPackageName,
|
||||
});
|
||||
return s;
|
||||
},
|
||||
enabled: tab === 2,
|
||||
});
|
||||
|
||||
const invalidate = () => {
|
||||
void qc.invalidateQueries({ queryKey: ['admin-mobile-releases'] });
|
||||
void qc.invalidateQueries({ queryKey: ['admin-mobile-release-stats'] });
|
||||
};
|
||||
|
||||
const createMut = useMutation({
|
||||
mutationFn: createMobileRelease,
|
||||
onSuccess: (rel) => {
|
||||
setCreateOpen(false);
|
||||
setForm(emptyCreate);
|
||||
setSelected(rel);
|
||||
setError(null);
|
||||
invalidate();
|
||||
},
|
||||
onError: (e: unknown) => setError(errMsg(e, t('admin.mobileVersions.actionFailed'))),
|
||||
});
|
||||
|
||||
const actionMut = useMutation({
|
||||
mutationFn: async (args: {
|
||||
action: string;
|
||||
id: string;
|
||||
file?: File;
|
||||
patch?: Parameters<typeof updateMobileRelease>[1];
|
||||
}) => {
|
||||
const { action, id, file, patch } = args;
|
||||
if (action === 'upload' && file) return uploadMobileApk(id, file);
|
||||
if (action === 'submit') return submitMobileRelease(id);
|
||||
if (action === 'publish') return publishMobileRelease(id);
|
||||
if (action === 'suspend') return suspendMobileRelease(id);
|
||||
if (action === 'retire') return retireMobileRelease(id);
|
||||
if (action === 'patch' && patch) return updateMobileRelease(id, patch);
|
||||
throw new Error('Unknown action');
|
||||
},
|
||||
onSuccess: (rel) => {
|
||||
setSelected(rel);
|
||||
setError(null);
|
||||
invalidate();
|
||||
},
|
||||
onError: (e: unknown) => setError(errMsg(e, t('admin.mobileVersions.actionFailed'))),
|
||||
});
|
||||
|
||||
const settingsMut = useMutation({
|
||||
mutationFn: updateMobileUpdateSettings,
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: ['admin-mobile-update-settings'] });
|
||||
setError(null);
|
||||
},
|
||||
onError: (e: unknown) => setError(errMsg(e, t('admin.mobileVersions.actionFailed'))),
|
||||
});
|
||||
|
||||
const rows = listQ.data?.items ?? [];
|
||||
const detail = selected;
|
||||
|
||||
const policyLabel = useMemo(
|
||||
() => ({
|
||||
optional: t('admin.mobileVersions.policyOptional'),
|
||||
recommended: t('admin.mobileVersions.policyRecommended'),
|
||||
mandatory: t('admin.mobileVersions.policyMandatory'),
|
||||
}),
|
||||
[t]
|
||||
);
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center', mb: 2 }}>
|
||||
<PhoneAndroidRoundedIcon color="primary" />
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
{t('admin.mobileVersions.title')}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{t('admin.mobileVersions.subtitle')}
|
||||
</Typography>
|
||||
</Box>
|
||||
<PermissionGate permission="admin.mobile_releases.manage">
|
||||
<Button variant="contained" onClick={() => setCreateOpen(true)}>
|
||||
{t('admin.mobileVersions.newRelease')}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Stack>
|
||||
|
||||
{error && (
|
||||
<Alert severity="error" sx={{ mb: 2 }} onClose={() => setError(null)}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 2 }}>
|
||||
<Tab label={t('admin.mobileVersions.tabReleases')} />
|
||||
<Tab label={t('admin.mobileVersions.tabStats')} />
|
||||
<Tab label={t('admin.mobileVersions.tabSettings')} />
|
||||
</Tabs>
|
||||
|
||||
{tab === 0 && (
|
||||
<Stack spacing={2}>
|
||||
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1.5}>
|
||||
<TextField
|
||||
size="small"
|
||||
label={t('admin.mobileVersions.search')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
sx={{ minWidth: 220 }}
|
||||
/>
|
||||
<FormControl size="small" sx={{ minWidth: 180 }}>
|
||||
<InputLabel>{t('admin.mobileVersions.status')}</InputLabel>
|
||||
<Select
|
||||
label={t('admin.mobileVersions.status')}
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
>
|
||||
<MenuItem value="">{t('admin.mobileVersions.allStatuses')}</MenuItem>
|
||||
<MenuItem value="draft">draft</MenuItem>
|
||||
<MenuItem value="pending_validation">pending_validation</MenuItem>
|
||||
<MenuItem value="published">published</MenuItem>
|
||||
<MenuItem value="suspended">suspended</MenuItem>
|
||||
<MenuItem value="retired">retired</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Stack>
|
||||
|
||||
<ScrollableTable minWidth={720}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.mobileVersions.version')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.versionCode')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.status')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.policy')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.size')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.downloads')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.publishedAt')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{rows.map((r) => (
|
||||
<TableRow
|
||||
key={r.id}
|
||||
hover
|
||||
selected={selected?.id === r.id}
|
||||
onClick={() => setSelected(r)}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
>
|
||||
<TableCell>{r.versionName}</TableCell>
|
||||
<TableCell>{r.versionCode}</TableCell>
|
||||
<TableCell>
|
||||
<Chip size="small" label={r.status} color={statusColor(r.status)} />
|
||||
</TableCell>
|
||||
<TableCell>{policyLabel[r.updatePolicy]}</TableCell>
|
||||
<TableCell>{formatBytes(r.fileSizeBytes)}</TableCell>
|
||||
<TableCell>{r.downloadCount}</TableCell>
|
||||
<TableCell>{r.publishedAt ? new Date(r.publishedAt).toLocaleString() : '—'}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{!listQ.isLoading && rows.length === 0 && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} align="center">
|
||||
{t('admin.mobileVersions.empty')}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
|
||||
{detail && (
|
||||
<Box
|
||||
sx={{
|
||||
p: 2,
|
||||
borderRadius: 2,
|
||||
border: '1px solid',
|
||||
borderColor: 'divider',
|
||||
bgcolor: 'background.paper',
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" justifyContent="space-between" alignItems="center" sx={{ mb: 1 }}>
|
||||
<Typography variant="h6" sx={{ fontWeight: 800 }}>
|
||||
{detail.versionName} (#{detail.versionCode})
|
||||
</Typography>
|
||||
<Chip size="small" label={detail.status} color={statusColor(detail.status)} />
|
||||
</Stack>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
|
||||
{t('admin.mobileVersions.package')}: {detail.packageName || '—'} · SHA-256:{' '}
|
||||
{detail.sha256 ? `${detail.sha256.slice(0, 16)}…` : '—'} · rollout {detail.rolloutPercent}%
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap', mb: 1 }}>
|
||||
<strong>{t('admin.mobileVersions.whatsNew')}</strong>
|
||||
{'\n'}
|
||||
{detail.whatsNew || '—'}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap', mb: 2 }}>
|
||||
<strong>{t('admin.mobileVersions.bugFixes')}</strong>
|
||||
{'\n'}
|
||||
{detail.bugFixes || '—'}
|
||||
</Typography>
|
||||
|
||||
<PermissionGate permission="admin.mobile_releases.manage">
|
||||
<Stack direction="row" flexWrap="wrap" gap={1}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".apk,application/vnd.android.package-archive"
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) actionMut.mutate({ action: 'upload', id: detail.id, file });
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
variant="outlined"
|
||||
disabled={!canManage || actionMut.isPending}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{t('admin.mobileVersions.uploadApk')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outlined"
|
||||
disabled={actionMut.isPending || !detail.storageKey}
|
||||
onClick={() => actionMut.mutate({ action: 'submit', id: detail.id })}
|
||||
>
|
||||
{t('admin.mobileVersions.submit')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={actionMut.isPending || !detail.storageKey}
|
||||
onClick={() => actionMut.mutate({ action: 'publish', id: detail.id })}
|
||||
>
|
||||
{t('admin.mobileVersions.publish')}
|
||||
</Button>
|
||||
<Button
|
||||
color="warning"
|
||||
disabled={actionMut.isPending || detail.status !== 'published'}
|
||||
onClick={() => actionMut.mutate({ action: 'suspend', id: detail.id })}
|
||||
>
|
||||
{t('admin.mobileVersions.suspend')}
|
||||
</Button>
|
||||
<Button
|
||||
color="error"
|
||||
disabled={actionMut.isPending || detail.status === 'retired'}
|
||||
onClick={() => actionMut.mutate({ action: 'retire', id: detail.id })}
|
||||
>
|
||||
{t('admin.mobileVersions.retire')}
|
||||
</Button>
|
||||
</Stack>
|
||||
</PermissionGate>
|
||||
</Box>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{tab === 1 && (
|
||||
<Stack spacing={2}>
|
||||
{statsQ.isLoading && <Typography>{t('admin.mobileVersions.loading')}</Typography>}
|
||||
{statsQ.data && (
|
||||
<>
|
||||
<Stack direction="row" flexWrap="wrap" gap={1}>
|
||||
{statsQ.data.byStatus.map((s) => (
|
||||
<Chip key={s.status} label={`${s.status}: ${s.count}`} />
|
||||
))}
|
||||
</Stack>
|
||||
<Stack direction="row" flexWrap="wrap" gap={1}>
|
||||
{statsQ.data.eventCounts.map((e) => (
|
||||
<Chip key={e.eventType} color="info" variant="outlined" label={`${e.eventType}: ${e.count}`} />
|
||||
))}
|
||||
</Stack>
|
||||
<ScrollableTable minWidth={640}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.mobileVersions.version')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.versionCode')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.status')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.downloads')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.downloadFails')}</TableCell>
|
||||
<TableCell>{t('admin.mobileVersions.installs')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{statsQ.data.byVersion.map((r) => (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell>{r.versionName}</TableCell>
|
||||
<TableCell>{r.versionCode}</TableCell>
|
||||
<TableCell>{r.status}</TableCell>
|
||||
<TableCell>{r.downloadCount}</TableCell>
|
||||
<TableCell>{r.downloadFailCount}</TableCell>
|
||||
<TableCell>{r.installConfirmCount}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
</>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{tab === 2 && (
|
||||
<Stack spacing={2} sx={{ maxWidth: 480 }}>
|
||||
{settingsQ.isLoading && <Typography>{t('admin.mobileVersions.loading')}</Typography>}
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.minSupported')}
|
||||
value={settingsForm.minSupportedVersionCode}
|
||||
onChange={(e) => setSettingsForm((s) => ({ ...s, minSupportedVersionCode: e.target.value }))}
|
||||
disabled={!canManage}
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.checkInterval')}
|
||||
value={settingsForm.checkIntervalSeconds}
|
||||
onChange={(e) => setSettingsForm((s) => ({ ...s, checkIntervalSeconds: e.target.value }))}
|
||||
disabled={!canManage}
|
||||
helperText={t('admin.mobileVersions.checkIntervalHint')}
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.expectedPackage')}
|
||||
value={settingsForm.expectedPackageName}
|
||||
onChange={(e) => setSettingsForm((s) => ({ ...s, expectedPackageName: e.target.value }))}
|
||||
disabled={!canManage}
|
||||
/>
|
||||
<PermissionGate permission="admin.mobile_releases.manage">
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={settingsMut.isPending}
|
||||
onClick={() =>
|
||||
settingsMut.mutate({
|
||||
minSupportedVersionCode: Number(settingsForm.minSupportedVersionCode),
|
||||
checkIntervalSeconds: Number(settingsForm.checkIntervalSeconds),
|
||||
expectedPackageName: settingsForm.expectedPackageName,
|
||||
})
|
||||
}
|
||||
>
|
||||
{t('admin.mobileVersions.saveSettings')}
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
<Dialog open={createOpen} onClose={() => setCreateOpen(false)} fullWidth maxWidth="sm">
|
||||
<DialogTitle>{t('admin.mobileVersions.newRelease')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2} sx={{ mt: 1 }}>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.version')}
|
||||
value={form.versionName}
|
||||
onChange={(e) => setForm((f) => ({ ...f, versionName: e.target.value }))}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.versionCode')}
|
||||
value={form.versionCode}
|
||||
onChange={(e) => setForm((f) => ({ ...f, versionCode: e.target.value }))}
|
||||
required
|
||||
type="number"
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.previousVersion')}
|
||||
value={form.previousVersionName}
|
||||
onChange={(e) => setForm((f) => ({ ...f, previousVersionName: e.target.value }))}
|
||||
/>
|
||||
<FormControl>
|
||||
<InputLabel>{t('admin.mobileVersions.policy')}</InputLabel>
|
||||
<Select
|
||||
label={t('admin.mobileVersions.policy')}
|
||||
value={form.updatePolicy}
|
||||
onChange={(e) => setForm((f) => ({ ...f, updatePolicy: e.target.value as MobileUpdatePolicy }))}
|
||||
>
|
||||
<MenuItem value="optional">{policyLabel.optional}</MenuItem>
|
||||
<MenuItem value="recommended">{policyLabel.recommended}</MenuItem>
|
||||
<MenuItem value="mandatory">{policyLabel.mandatory}</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.rollout')}
|
||||
value={form.rolloutPercent}
|
||||
onChange={(e) => setForm((f) => ({ ...f, rolloutPercent: e.target.value }))}
|
||||
type="number"
|
||||
helperText={t('admin.mobileVersions.rolloutHint')}
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.whatsNew')}
|
||||
value={form.whatsNew}
|
||||
onChange={(e) => setForm((f) => ({ ...f, whatsNew: e.target.value }))}
|
||||
multiline
|
||||
minRows={3}
|
||||
/>
|
||||
<TextField
|
||||
label={t('admin.mobileVersions.bugFixes')}
|
||||
value={form.bugFixes}
|
||||
onChange={(e) => setForm((f) => ({ ...f, bugFixes: e.target.value }))}
|
||||
multiline
|
||||
minRows={2}
|
||||
/>
|
||||
</Stack>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setCreateOpen(false)}>{t('admin.mobileVersions.cancel')}</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
disabled={createMut.isPending || !form.versionName || !form.versionCode}
|
||||
onClick={() =>
|
||||
createMut.mutate({
|
||||
versionName: form.versionName.trim(),
|
||||
versionCode: Number(form.versionCode),
|
||||
previousVersionName: form.previousVersionName.trim() || null,
|
||||
whatsNew: form.whatsNew,
|
||||
bugFixes: form.bugFixes,
|
||||
updatePolicy: form.updatePolicy,
|
||||
rolloutPercent: Number(form.rolloutPercent) || 100,
|
||||
})
|
||||
}
|
||||
>
|
||||
{t('admin.mobileVersions.create')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@ -0,0 +1,150 @@
|
||||
/**
|
||||
* Admin + typed helpers for mobile APK release management.
|
||||
*/
|
||||
import { api } from '../../../shared/services/api';
|
||||
|
||||
export type MobileReleaseStatus =
|
||||
| 'draft'
|
||||
| 'pending_validation'
|
||||
| 'published'
|
||||
| 'suspended'
|
||||
| 'retired';
|
||||
|
||||
export type MobileUpdatePolicy = 'optional' | 'recommended' | 'mandatory';
|
||||
|
||||
export type MobileAppRelease = {
|
||||
id: string;
|
||||
platform: string;
|
||||
channel: string;
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
packageName: string | null;
|
||||
previousVersionName: string | null;
|
||||
whatsNew: string;
|
||||
bugFixes: string;
|
||||
status: MobileReleaseStatus;
|
||||
updatePolicy: MobileUpdatePolicy;
|
||||
rolloutPercent: number;
|
||||
storageKey: string | null;
|
||||
fileSizeBytes: number | null;
|
||||
sha256: string | null;
|
||||
signingCertSha256: string | null;
|
||||
publishedAt: string | null;
|
||||
downloadCount: number;
|
||||
downloadFailCount: number;
|
||||
installConfirmCount: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type MobileUpdateSettings = {
|
||||
minSupportedVersionCode: number;
|
||||
checkIntervalSeconds: number;
|
||||
expectedPackageName: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type MobileReleaseStats = {
|
||||
byStatus: Array<{ status: string; count: number }>;
|
||||
byVersion: Array<{
|
||||
id: string;
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
status: string;
|
||||
downloadCount: number;
|
||||
downloadFailCount: number;
|
||||
installConfirmCount: number;
|
||||
}>;
|
||||
eventCounts: Array<{ eventType: string; count: number }>;
|
||||
};
|
||||
|
||||
export async function listMobileReleases(params?: {
|
||||
status?: string;
|
||||
search?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}) {
|
||||
const { data } = await api.get<{ items: MobileAppRelease[]; total: number }>(
|
||||
'/api/v1/admin/mobile-releases',
|
||||
{ params }
|
||||
);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getMobileRelease(id: string) {
|
||||
const { data } = await api.get<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function createMobileRelease(body: {
|
||||
versionName: string;
|
||||
versionCode: number;
|
||||
previousVersionName?: string | null;
|
||||
whatsNew?: string;
|
||||
bugFixes?: string;
|
||||
updatePolicy?: MobileUpdatePolicy;
|
||||
rolloutPercent?: number;
|
||||
}) {
|
||||
const { data } = await api.post<MobileAppRelease>('/api/v1/admin/mobile-releases', body);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateMobileRelease(
|
||||
id: string,
|
||||
body: Partial<{
|
||||
versionName: string;
|
||||
previousVersionName: string | null;
|
||||
whatsNew: string;
|
||||
bugFixes: string;
|
||||
updatePolicy: MobileUpdatePolicy;
|
||||
rolloutPercent: number;
|
||||
}>
|
||||
) {
|
||||
const { data } = await api.patch<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}`, body);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function uploadMobileApk(id: string, file: File) {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const { data } = await api.post<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}/apk`, form, {
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
timeout: 300_000,
|
||||
});
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function submitMobileRelease(id: string) {
|
||||
const { data } = await api.post<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}/submit`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function publishMobileRelease(id: string) {
|
||||
const { data } = await api.post<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}/publish`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function suspendMobileRelease(id: string) {
|
||||
const { data } = await api.post<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}/suspend`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function retireMobileRelease(id: string) {
|
||||
const { data } = await api.post<MobileAppRelease>(`/api/v1/admin/mobile-releases/${id}/retire`);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getMobileReleaseStats() {
|
||||
const { data } = await api.get<MobileReleaseStats>('/api/v1/admin/mobile-releases/stats');
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getMobileUpdateSettings() {
|
||||
const { data } = await api.get<MobileUpdateSettings>('/api/v1/admin/mobile-update-settings');
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function updateMobileUpdateSettings(body: Partial<MobileUpdateSettings>) {
|
||||
const { data } = await api.patch<MobileUpdateSettings>('/api/v1/admin/mobile-update-settings', body);
|
||||
return data;
|
||||
}
|
||||
@ -22,6 +22,7 @@ import HelpOutlineRoundedIcon from '@mui/icons-material/HelpOutlineRounded';
|
||||
import AdminPanelSettingsRoundedIcon from '@mui/icons-material/AdminPanelSettingsRounded';
|
||||
import ManageAccountsRoundedIcon from '@mui/icons-material/ManageAccountsRounded';
|
||||
import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded';
|
||||
import PhoneAndroidRoundedIcon from '@mui/icons-material/PhoneAndroidRounded';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
@ -47,7 +48,8 @@ type OptionCardKey =
|
||||
| 'support'
|
||||
| 'countries'
|
||||
| 'rbac'
|
||||
| 'adminUsers';
|
||||
| 'adminUsers'
|
||||
| 'mobileVersions';
|
||||
|
||||
type OptionCardConfig = {
|
||||
key: OptionCardKey;
|
||||
@ -232,6 +234,15 @@ const OPTION_CARDS: OptionCardConfig[] = [
|
||||
bg: 'rgba(214,178,94,0.16)',
|
||||
border: 'rgba(214,178,94,0.22)',
|
||||
},
|
||||
{
|
||||
key: 'mobileVersions',
|
||||
path: '/admin/mobile-versions',
|
||||
icon: PhoneAndroidRoundedIcon,
|
||||
badgeKey: 'apk',
|
||||
badgeColor: 'success',
|
||||
bg: 'rgba(16,185,129,0.14)',
|
||||
border: 'rgba(16,185,129,0.28)',
|
||||
},
|
||||
];
|
||||
|
||||
/** Landing page for administrative tools and configuration shortcuts. */
|
||||
|
||||
@ -13,7 +13,12 @@ const LEGACY_IMPLIES: Record<string, string[]> = {
|
||||
],
|
||||
'games.admin': ['admin.games.view', 'admin.games.edit', 'admin.games.delete'],
|
||||
'reports.admin': ['admin.reports.view', 'admin.reports.export'],
|
||||
'settings.admin': ['admin.settings.view', 'admin.settings.edit'],
|
||||
'settings.admin': [
|
||||
'admin.settings.view',
|
||||
'admin.settings.edit',
|
||||
'admin.mobile_releases.view',
|
||||
'admin.mobile_releases.manage',
|
||||
],
|
||||
'referral.admin': ['admin.referral.view', 'admin.referral.manage', 'admin.referral_fraud.view'],
|
||||
'treasury.view': ['admin.treasury.view', 'admin.treasury.manage'],
|
||||
'security.admin': ['admin.security.view', 'admin.security.manage'],
|
||||
@ -77,6 +82,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record<string, string> = {
|
||||
'/admin/admin-users': 'admin.rbac.view',
|
||||
'/admin/support': 'admin.support.view',
|
||||
'/admin/faq': 'admin.faq.view',
|
||||
'/admin/mobile-versions': 'admin.mobile_releases.view',
|
||||
};
|
||||
|
||||
export const OPTIONS_CARD_PERMISSIONS: Record<string, string> = {
|
||||
@ -100,4 +106,5 @@ export const OPTIONS_CARD_PERMISSIONS: Record<string, string> = {
|
||||
countries: 'admin.countries.view',
|
||||
rbac: 'admin.rbac.view',
|
||||
adminUsers: 'admin.rbac.view',
|
||||
mobileVersions: 'admin.mobile_releases.view',
|
||||
};
|
||||
|
||||
@ -1060,6 +1060,7 @@ export const en = {
|
||||
staff: 'Staff',
|
||||
registration: 'Registration',
|
||||
accessControl: 'Access control',
|
||||
apk: 'APK / Android',
|
||||
},
|
||||
options: {
|
||||
title: 'Options',
|
||||
@ -1142,8 +1143,55 @@ export const en = {
|
||||
title: 'Admin users',
|
||||
description: 'Manage staff accounts and individual permission exceptions on top of roles.',
|
||||
},
|
||||
mobileVersions: {
|
||||
title: 'Mobile versions',
|
||||
description: 'Publish Android APK updates, set update policies, and track download stats.',
|
||||
},
|
||||
},
|
||||
},
|
||||
mobileVersions: {
|
||||
title: 'Mobile versions',
|
||||
subtitle: 'Manage Android APK releases distributed from Tloto servers.',
|
||||
loading: 'Loading…',
|
||||
newRelease: 'New release',
|
||||
tabReleases: 'Releases',
|
||||
tabStats: 'Statistics',
|
||||
tabSettings: 'Settings',
|
||||
search: 'Search version',
|
||||
status: 'Status',
|
||||
allStatuses: 'All statuses',
|
||||
version: 'Version',
|
||||
versionCode: 'Version code',
|
||||
policy: 'Update policy',
|
||||
policyOptional: 'Optional',
|
||||
policyRecommended: 'Recommended',
|
||||
policyMandatory: 'Mandatory',
|
||||
size: 'APK size',
|
||||
downloads: 'Downloads',
|
||||
downloadFails: 'Failed downloads',
|
||||
installs: 'Installs confirmed',
|
||||
publishedAt: 'Published',
|
||||
empty: 'No releases yet.',
|
||||
package: 'Package',
|
||||
whatsNew: "What's new",
|
||||
bugFixes: 'Bug fixes',
|
||||
uploadApk: 'Upload APK',
|
||||
submit: 'Submit for validation',
|
||||
publish: 'Publish',
|
||||
suspend: 'Suspend',
|
||||
retire: 'Retire',
|
||||
previousVersion: 'Previous version',
|
||||
rollout: 'Rollout %',
|
||||
rolloutHint: 'Percentage of devices that receive this release (deterministic by device id).',
|
||||
minSupported: 'Minimum supported version code',
|
||||
checkInterval: 'Client check interval (seconds)',
|
||||
checkIntervalHint: 'How often the app should re-check for updates while running.',
|
||||
expectedPackage: 'Expected package name',
|
||||
saveSettings: 'Save settings',
|
||||
cancel: 'Cancel',
|
||||
create: 'Create',
|
||||
actionFailed: 'Action failed',
|
||||
},
|
||||
rbac: {
|
||||
title: 'Roles & permissions',
|
||||
subtitle: 'Manage system and custom roles with fine-grained admin permissions.',
|
||||
@ -1180,6 +1228,7 @@ export const en = {
|
||||
test_wallet: 'Test wallet',
|
||||
share_cards: 'Share cards',
|
||||
solo_encouragement: 'Solo encouragement',
|
||||
mobile_releases: 'Mobile releases',
|
||||
},
|
||||
adminUsers: {
|
||||
title: 'Admin users',
|
||||
|
||||
@ -1074,6 +1074,7 @@ export const fr = {
|
||||
staff: 'Équipe',
|
||||
registration: 'Inscription',
|
||||
accessControl: 'Contrôle d’accès',
|
||||
apk: 'APK / Android',
|
||||
},
|
||||
options: {
|
||||
title: 'Options',
|
||||
@ -1160,8 +1161,55 @@ export const fr = {
|
||||
title: 'Utilisateurs admin',
|
||||
description: 'Gérer les comptes staff et les exceptions de permissions individuelles en plus des rôles.',
|
||||
},
|
||||
mobileVersions: {
|
||||
title: 'Versions mobiles',
|
||||
description: 'Publier les mises à jour APK Android, définir les politiques et suivre les téléchargements.',
|
||||
},
|
||||
},
|
||||
},
|
||||
mobileVersions: {
|
||||
title: 'Versions mobiles',
|
||||
subtitle: 'Gérer les releases APK Android distribuées depuis les serveurs Tloto.',
|
||||
loading: 'Chargement…',
|
||||
newRelease: 'Nouvelle version',
|
||||
tabReleases: 'Versions',
|
||||
tabStats: 'Statistiques',
|
||||
tabSettings: 'Paramètres',
|
||||
search: 'Rechercher une version',
|
||||
status: 'Statut',
|
||||
allStatuses: 'Tous les statuts',
|
||||
version: 'Version',
|
||||
versionCode: 'Code de version',
|
||||
policy: 'Politique de mise à jour',
|
||||
policyOptional: 'Facultative',
|
||||
policyRecommended: 'Recommandée',
|
||||
policyMandatory: 'Obligatoire',
|
||||
size: 'Taille APK',
|
||||
downloads: 'Téléchargements',
|
||||
downloadFails: 'Échecs de téléchargement',
|
||||
installs: 'Installations confirmées',
|
||||
publishedAt: 'Publiée',
|
||||
empty: 'Aucune version pour le moment.',
|
||||
package: 'Package',
|
||||
whatsNew: 'Nouveautés',
|
||||
bugFixes: 'Corrections',
|
||||
uploadApk: 'Importer l’APK',
|
||||
submit: 'Soumettre à validation',
|
||||
publish: 'Publier',
|
||||
suspend: 'Suspendre',
|
||||
retire: 'Retirer',
|
||||
previousVersion: 'Version précédente',
|
||||
rollout: 'Déploiement %',
|
||||
rolloutHint: 'Pourcentage d’appareils qui reçoivent cette version (déterministe par device id).',
|
||||
minSupported: 'Code de version minimum supporté',
|
||||
checkInterval: 'Intervalle de vérification client (secondes)',
|
||||
checkIntervalHint: 'Fréquence à laquelle l’app doit revérifier les mises à jour.',
|
||||
expectedPackage: 'Nom de package attendu',
|
||||
saveSettings: 'Enregistrer',
|
||||
cancel: 'Annuler',
|
||||
create: 'Créer',
|
||||
actionFailed: 'Action échouée',
|
||||
},
|
||||
rbac: {
|
||||
title: 'Rôles & permissions',
|
||||
subtitle: 'Gérer les rôles système et personnalisés avec des permissions admin fines.',
|
||||
@ -1198,6 +1246,7 @@ export const fr = {
|
||||
test_wallet: 'Portefeuille test',
|
||||
share_cards: 'Cartes de partage',
|
||||
solo_encouragement: 'Encouragement solo',
|
||||
mobile_releases: 'Versions mobiles',
|
||||
},
|
||||
adminUsers: {
|
||||
title: 'Utilisateurs admin',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user