A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
feat(common): add secret resolution, tunnel command parser and OAuth state helpers
Abhi Pareek336e97f41f5a
diff --git a/.gitignore b/.gitignoreindex 4fb8a3f..a5d11dc 100644--- a/.gitignore+++ b/.gitignore@@ -19,6 +19,7 @@ data/berry_auth/data/test_berry_auth/data/backups/data/whatsapp_session.json+data/.secrets/berrysdk.db*.berry-sessions/diff --git a/packages/common/src/__tests__/common.test.js b/packages/common/src/__tests__/common.test.jsindex 1691116..117b8dc 100644--- a/packages/common/src/__tests__/common.test.js+++ b/packages/common/src/__tests__/common.test.js@@ -1,6 +1,8 @@import { test, describe } from 'node:test';import assert from 'node:assert/strict';import {+ buildCloudflaredInvocation,+ safeEqual,toPaise,toRupeesString,formatINR,@@ -238,3 +240,35 @@ describe('@youpi/common Unit Tests', () => {});});});++describe('buildCloudflaredInvocation', () => {+ const token = 'eyJhIjoiMDEyMzQ1Njc4OSIsInQiOiJhYmNkZWYifQ==';++ test('extracts the token from pasted cloudflared commands and never returns the pasted text', () => {+ for (const cmd of [+ `cloudflared.exe service install ${token}`,+ `cloudflared tunnel run --token ${token}`,+ token+ ]) {+ const inv = buildCloudflaredInvocation(cmd);+ assert.equal(inv.file, 'cloudflared');+ assert.deepEqual(inv.args, ['tunnel', '--no-autoupdate', 'run', '--token', token]);+ assert.ok(!inv.redacted.includes(token));+ }+ });++ test('rejects commands without a token, including shell payloads', () => {+ assert.throws(() => buildCloudflaredInvocation(''), /empty/);+ assert.throws(() => buildCloudflaredInvocation('calc.exe & whoami'), /No valid Cloudflare tunnel token/);+ assert.throws(() => buildCloudflaredInvocation('curl http://x | sh'), /No valid Cloudflare tunnel token/);+ });+});++describe('safeEqual', () => {+ test('compares strings in constant time and rejects non-strings', () => {+ assert.equal(safeEqual('abc', 'abc'), true);+ assert.equal(safeEqual('abc', 'abd'), false);+ assert.equal(safeEqual('abc', 'abcd'), false);+ assert.equal(safeEqual(undefined, 'abc'), false);+ });+});diff --git a/packages/common/src/index.js b/packages/common/src/index.jsindex 5a9a791..099599b 100644--- a/packages/common/src/index.js+++ b/packages/common/src/index.js@@ -6,3 +6,5 @@ export * from './upi.js';export * from './upi-providers.js';export * from './contracts.js';export * from './runtime-config.js';+export * from './secrets.js';+export * from './tunnel-command.js';diff --git a/packages/common/src/runtime-config.js b/packages/common/src/runtime-config.jsindex 2dbefd7..6035f46 100644--- a/packages/common/src/runtime-config.js+++ b/packages/common/src/runtime-config.js@@ -230,3 +230,17 @@ export function resolvePairingUrl(options = {}) {const urls = resolveRuntimeUrls(options);return urls.apiUrl || 'http://localhost:6100';}++/**+ * OAuth redirect URI for the Gmail observer. `GMAIL_REDIRECT_URI` wins; otherwise it is derived+ * from the configured domain, falling back to the local observer port.+ * @param {object} [branding]+ */+export function resolveGmailRedirectUri(branding = {}) {+ if (process.env.GMAIL_REDIRECT_URI) return process.env.GMAIL_REDIRECT_URI;+ try {+ return `${resolveRuntimeUrls(branding || {}).gmailUrl}/oauth/callback`;+ } catch {+ return `http://localhost:${process.env.GMAIL_OBSERVER_PORT || 6003}/oauth/callback`;+ }+}diff --git a/packages/common/src/secrets.js b/packages/common/src/secrets.jsnew file mode 100644index 0000000..27313ff--- /dev/null+++ b/packages/common/src/secrets.js@@ -0,0 +1,94 @@+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+// Resolved from this file, not cwd: every service must read the same files.+const SECRETS_DIR = path.resolve(__dirname, '../../../data/.secrets');++const cache = new Map();++/**+ * Resolves a service secret: explicit env var first, else a random value+ * generated once and persisted under data/.secrets/ (shared by all local services).+ * @param {string} name file-safe secret name+ * @param {string} [envVar] env var that overrides the file+ * @returns {string}+ */+export function resolveSecret(name, envVar) {+ const fromEnv = envVar ? (process.env[envVar] || '').trim() : '';+ if (fromEnv) return fromEnv;+ if (cache.has(name)) return cache.get(name);++ const file = path.join(SECRETS_DIR, name);+ let value = '';+ try { value = fs.readFileSync(file, 'utf8').trim(); } catch {}+ if (!value) {+ fs.mkdirSync(SECRETS_DIR, { recursive: true });+ const fresh = crypto.randomBytes(32).toString('hex');+ try {+ fs.writeFileSync(file, fresh, { flag: 'wx', mode: 0o600 });+ value = fresh;+ } catch {+ // Another process created it first: use theirs.+ value = fs.readFileSync(file, 'utf8').trim();+ }+ }+ cache.set(name, value);+ return value;+}++/** Constant-time string comparison (length-independent via hashing). */+export function safeEqual(a, b) {+ if (typeof a !== 'string' || typeof b !== 'string') return false;+ const ha = crypto.createHash('sha256').update(a).digest();+ const hb = crypto.createHash('sha256').update(b).digest();+ return crypto.timingSafeEqual(ha, hb);+}++export const getAdminToken = () => resolveSecret('admin_api_token', 'ADMIN_API_TOKEN');+export const getObserverToken = () => resolveSecret('observer_api_token', 'OBSERVER_API_TOKEN');+export const getCoinStoreWebhookSecret = () => resolveSecret('coin_store_webhook_secret', 'COIN_STORE_WEBHOOK_SECRET');++/** Literal that older builds seeded into databases; must never be trusted. */+export const LEGACY_DEFAULT_WEBHOOK_SECRET = 'merchant_webhook_secret_for_wallet_store';++/** True when the request's `Authorization: Bearer` value matches any of the given tokens. */+export function hasBearer(req, ...tokens) {+ const match = /^Bearer\s+(.+)$/i.exec(req.headers?.['authorization'] || '');+ if (!match) return false;+ const presented = match[1].trim();+ return tokens.some(t => safeEqual(presented, t));+}++const OAUTH_STATE_TTL_MS = 10 * 60 * 1000;+const consumedOAuthStates = new Map();++function oauthStateMac(payload) {+ return crypto.createHmac('sha256', getObserverToken()).update(`oauth-state:${payload}`).digest('hex');+}++/**+ * Creates a signed, expiring OAuth `state` value. Mint it only from an authenticated admin route:+ * the callback accepts nothing that was not minted there, which blocks login-CSRF account linking.+ */+export function createOAuthState() {+ const payload = `${crypto.randomBytes(16).toString('hex')}.${Date.now() + OAUTH_STATE_TTL_MS}`;+ return `${payload}.${oauthStateMac(payload)}`;+}++/** Verifies signature and expiry, and accepts each state only once (per process). */+export function consumeOAuthState(state) {+ if (typeof state !== 'string') return false;+ const parts = state.split('.');+ if (parts.length !== 3) return false;+ const [nonce, expiresAt, mac] = parts;+ if (!safeEqual(mac, oauthStateMac(`${nonce}.${expiresAt}`))) return false;+ const now = Date.now();+ if (!(Number(expiresAt) > now)) return false;+ for (const [key, exp] of consumedOAuthStates) if (exp <= now) consumedOAuthStates.delete(key);+ if (consumedOAuthStates.has(nonce)) return false;+ consumedOAuthStates.set(nonce, Number(expiresAt));+ return true;+}diff --git a/packages/common/src/tunnel-command.js b/packages/common/src/tunnel-command.jsnew file mode 100644index 0000000..7e0ada1--- /dev/null+++ b/packages/common/src/tunnel-command.js@@ -0,0 +1,59 @@+import fs from 'node:fs';+import { spawn } from 'node:child_process';++const TOKEN_RE = /^[A-Za-z0-9_\-=+/.]{20,}$/;++/**+ * Extracts the Cloudflare tunnel token from whatever the operator pasted+ * (`cloudflared service install <token>`, `cloudflared tunnel run --token <token>`, or the bare token)+ * and returns a fixed argv for `cloudflared`. Nothing else from the pasted text is ever executed.+ * @param {string} rawCommand+ * @returns {{ file: string, args: string[], redacted: string }}+ */+export function buildCloudflaredInvocation(rawCommand) {+ const text = String(rawCommand || '').trim();+ if (!text) throw new Error('Cloudflare Tunnel command cannot be empty.');++ const explicit = text.match(/--token[\s=]+(\S+)/i) || text.match(/\binstall\s+(\S+)/i);+ const candidates = explicit ? [explicit[1]] : text.split(/\s+/);+ const token = candidates.map(c => c.replace(/^["']|["']$/g, '')).find(c => TOKEN_RE.test(c));+ if (!token) {+ throw new Error('No valid Cloudflare tunnel token found. Paste the command containing your tunnel token.');+ }++ // Keep an explicit path to the binary (e.g. "C:\Tools\cloudflared.exe") when it exists; otherwise rely on PATH.+ const first = text.match(/^"([^"]+)"|^(\S+)/);+ const candidate = first ? (first[1] || first[2]) : '';+ const file = /cloudflared(\.exe)?$/i.test(candidate) && /[\\/]/.test(candidate) && fs.existsSync(candidate)+ ? candidate+ : 'cloudflared';++ return {+ file,+ args: ['tunnel', '--no-autoupdate', 'run', '--token', token],+ redacted: 'cloudflared tunnel --no-autoupdate run --token ***'+ };+}++/**+ * Starts cloudflared for the pasted command without a shell. Never throws: a bad command or a+ * missing binary is logged and boot continues without a tunnel.+ * @param {string} rawCommand+ * @param {import('node:child_process').SpawnOptions} [options]+ * @returns {import('node:child_process').ChildProcess | null}+ */+export function startCloudflaredSafely(rawCommand, options = {}) {+ let invocation;+ try {+ invocation = buildCloudflaredInvocation(rawCommand);+ } catch (err) {+ console.error(`[Cloudflare Tunnel] Not started: ${err.message}`);+ return null;+ }+ console.log(` > ${invocation.redacted}`);+ const child = spawn(invocation.file, invocation.args, { shell: false, env: { ...process.env }, ...options });+ child.on('error', err => {+ console.error(`[Cloudflare Tunnel] Could not run '${invocation.file}': ${err.message}. Install cloudflared or put it on PATH.`);+ });+ return child;+}