|
| 1 | +const crypto = require('crypto'); |
| 2 | + |
| 3 | +const WEIGHTS = { |
| 4 | + onTimePayments: 0.5, |
| 5 | + leaseCompletion: 0.3, |
| 6 | + successfulDepositReturns: 0.2 |
| 7 | +}; |
| 8 | + |
| 9 | +const SCORE_RANGE = { |
| 10 | + min: 300, |
| 11 | + max: 850 |
| 12 | +}; |
| 13 | + |
| 14 | +const DEFAULT_CACHE_TTL_SECONDS = 60 * 60; |
| 15 | +const DEFAULT_TOKEN_TTL_SECONDS = 60 * 30; |
| 16 | + |
| 17 | +function safeRatio(numerator, denominator) { |
| 18 | + if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator <= 0) { |
| 19 | + return 0; |
| 20 | + } |
| 21 | + return Math.max(0, Math.min(1, numerator / denominator)); |
| 22 | +} |
| 23 | + |
| 24 | +function getBreakdown(metrics) { |
| 25 | + const onTimePaymentsRatio = safeRatio(metrics.onTimePayments, metrics.totalPayments); |
| 26 | + const leaseCompletionRatio = safeRatio(metrics.completedLeases, metrics.totalLeases); |
| 27 | + const successfulDepositReturnsRatio = safeRatio( |
| 28 | + metrics.successfulDepositReturns, |
| 29 | + metrics.totalDepositReturns |
| 30 | + ); |
| 31 | + |
| 32 | + return { |
| 33 | + onTimePayments: Math.round(onTimePaymentsRatio * 100), |
| 34 | + leaseCompletion: Math.round(leaseCompletionRatio * 100), |
| 35 | + successfulDepositReturns: Math.round(successfulDepositReturnsRatio * 100) |
| 36 | + }; |
| 37 | +} |
| 38 | + |
| 39 | +function calculateScore(metrics) { |
| 40 | + const breakdown = getBreakdown(metrics); |
| 41 | + const weightedPercent = |
| 42 | + breakdown.onTimePayments * WEIGHTS.onTimePayments + |
| 43 | + breakdown.leaseCompletion * WEIGHTS.leaseCompletion + |
| 44 | + breakdown.successfulDepositReturns * WEIGHTS.successfulDepositReturns; |
| 45 | + |
| 46 | + const spread = SCORE_RANGE.max - SCORE_RANGE.min; |
| 47 | + const score = Math.round(SCORE_RANGE.min + (weightedPercent / 100) * spread); |
| 48 | + |
| 49 | + return { |
| 50 | + score, |
| 51 | + breakdown |
| 52 | + }; |
| 53 | +} |
| 54 | + |
| 55 | +function parseDurationSeconds(value, fallback) { |
| 56 | + if (!Number.isFinite(value) || value <= 0) { |
| 57 | + return fallback; |
| 58 | + } |
| 59 | + return Math.floor(value); |
| 60 | +} |
| 61 | + |
| 62 | +function toBase64Url(value) { |
| 63 | + return Buffer.from(value) |
| 64 | + .toString('base64') |
| 65 | + .replace(/=/g, '') |
| 66 | + .replace(/\+/g, '-') |
| 67 | + .replace(/\//g, '_'); |
| 68 | +} |
| 69 | + |
| 70 | +function fromBase64Url(value) { |
| 71 | + const normalized = value.replace(/-/g, '+').replace(/_/g, '/'); |
| 72 | + const padded = normalized + '==='.slice((normalized.length + 3) % 4); |
| 73 | + return Buffer.from(padded, 'base64').toString('utf8'); |
| 74 | +} |
| 75 | + |
| 76 | +function createSignedToken(payload, secret) { |
| 77 | + const header = { alg: 'HS256', typ: 'JWT' }; |
| 78 | + const encodedHeader = toBase64Url(JSON.stringify(header)); |
| 79 | + const encodedPayload = toBase64Url(JSON.stringify(payload)); |
| 80 | + const content = `${encodedHeader}.${encodedPayload}`; |
| 81 | + const signature = crypto |
| 82 | + .createHmac('sha256', secret) |
| 83 | + .update(content) |
| 84 | + .digest('base64') |
| 85 | + .replace(/=/g, '') |
| 86 | + .replace(/\+/g, '-') |
| 87 | + .replace(/\//g, '_'); |
| 88 | + return `${content}.${signature}`; |
| 89 | +} |
| 90 | + |
| 91 | +function verifySignedToken(token, secret) { |
| 92 | + const parts = String(token || '').split('.'); |
| 93 | + if (parts.length !== 3) { |
| 94 | + throw new Error('Invalid token format'); |
| 95 | + } |
| 96 | + |
| 97 | + const [encodedHeader, encodedPayload, signature] = parts; |
| 98 | + const content = `${encodedHeader}.${encodedPayload}`; |
| 99 | + const expectedSignature = crypto |
| 100 | + .createHmac('sha256', secret) |
| 101 | + .update(content) |
| 102 | + .digest('base64') |
| 103 | + .replace(/=/g, '') |
| 104 | + .replace(/\+/g, '-') |
| 105 | + .replace(/\//g, '_'); |
| 106 | + |
| 107 | + const expected = Buffer.from(expectedSignature); |
| 108 | + const received = Buffer.from(signature); |
| 109 | + if (expected.length !== received.length || !crypto.timingSafeEqual(expected, received)) { |
| 110 | + throw new Error('Invalid token signature'); |
| 111 | + } |
| 112 | + |
| 113 | + return JSON.parse(fromBase64Url(encodedPayload)); |
| 114 | +} |
| 115 | + |
| 116 | +class TenantCreditScoreAggregator { |
| 117 | + constructor(options = {}) { |
| 118 | + this.cacheTtlSeconds = parseDurationSeconds( |
| 119 | + options.cacheTtlSeconds, |
| 120 | + DEFAULT_CACHE_TTL_SECONDS |
| 121 | + ); |
| 122 | + this.tokenTtlSeconds = parseDurationSeconds( |
| 123 | + options.tokenTtlSeconds, |
| 124 | + DEFAULT_TOKEN_TTL_SECONDS |
| 125 | + ); |
| 126 | + this.signingSecret = options.signingSecret || process.env.SHARE_TOKEN_SECRET || 'leaseflow-dev-secret'; |
| 127 | + this.cache = new Map(); |
| 128 | + } |
| 129 | + |
| 130 | + getCached(tenantId) { |
| 131 | + const key = String(tenantId || ''); |
| 132 | + const item = this.cache.get(key); |
| 133 | + if (!item) return null; |
| 134 | + |
| 135 | + if (Date.now() >= item.expiresAtMs) { |
| 136 | + this.cache.delete(key); |
| 137 | + return null; |
| 138 | + } |
| 139 | + |
| 140 | + return { |
| 141 | + tenantId: key, |
| 142 | + score: item.score, |
| 143 | + breakdown: item.breakdown, |
| 144 | + expiresAt: new Date(item.expiresAtMs).toISOString() |
| 145 | + }; |
| 146 | + } |
| 147 | + |
| 148 | + computeAndCache(tenantId, metrics, ttlSeconds) { |
| 149 | + const key = String(tenantId || '').trim(); |
| 150 | + if (!key) { |
| 151 | + throw new Error('tenantId is required'); |
| 152 | + } |
| 153 | + |
| 154 | + const { score, breakdown } = calculateScore(metrics); |
| 155 | + const ttl = parseDurationSeconds(ttlSeconds, this.cacheTtlSeconds); |
| 156 | + const expiresAtMs = Date.now() + ttl * 1000; |
| 157 | + this.cache.set(key, { score, breakdown, expiresAtMs }); |
| 158 | + |
| 159 | + return { |
| 160 | + tenantId: key, |
| 161 | + score, |
| 162 | + breakdown, |
| 163 | + expiresAt: new Date(expiresAtMs).toISOString() |
| 164 | + }; |
| 165 | + } |
| 166 | + |
| 167 | + getOrCompute(tenantId, metrics, ttlSeconds) { |
| 168 | + const cached = this.getCached(tenantId); |
| 169 | + if (cached) { |
| 170 | + return { ...cached, cached: true }; |
| 171 | + } |
| 172 | + const computed = this.computeAndCache(tenantId, metrics, ttlSeconds); |
| 173 | + return { ...computed, cached: false }; |
| 174 | + } |
| 175 | + |
| 176 | + generateShareToken(tenantId, tokenTtlSeconds) { |
| 177 | + const cached = this.getCached(tenantId); |
| 178 | + if (!cached) { |
| 179 | + throw new Error('No cached score found for tenant'); |
| 180 | + } |
| 181 | + |
| 182 | + const nowSeconds = Math.floor(Date.now() / 1000); |
| 183 | + const ttl = parseDurationSeconds(tokenTtlSeconds, this.tokenTtlSeconds); |
| 184 | + const payload = { |
| 185 | + tenantId: cached.tenantId, |
| 186 | + score: cached.score, |
| 187 | + breakdown: cached.breakdown, |
| 188 | + iat: nowSeconds, |
| 189 | + exp: nowSeconds + ttl |
| 190 | + }; |
| 191 | + |
| 192 | + const token = createSignedToken(payload, this.signingSecret); |
| 193 | + return { token, payload }; |
| 194 | + } |
| 195 | + |
| 196 | + verifyShareToken(token) { |
| 197 | + const payload = verifySignedToken(token, this.signingSecret); |
| 198 | + const nowSeconds = Math.floor(Date.now() / 1000); |
| 199 | + if (!Number.isFinite(payload.exp) || payload.exp < nowSeconds) { |
| 200 | + throw new Error('Token expired'); |
| 201 | + } |
| 202 | + return payload; |
| 203 | + } |
| 204 | +} |
| 205 | + |
| 206 | +module.exports = { |
| 207 | + TenantCreditScoreAggregator, |
| 208 | + calculateScore |
| 209 | +}; |
0 commit comments