Spaces:
Running on Zero
Running on Zero
Plan switching, resubscribe, honest cancel flow, token-based limits with model weights
cf67874 verified Download api/core.mjs from mohith2309/mai-api: direct link, hf CLI and curl.
- Browser
- Download file 8.31 kB
-
https://huggingface.co/spaces/mohith2309/mai-api/resolve/main/api/core.mjs
- Command line
-
hf download hf://spaces/mohith2309/mai-api/api/core.mjs
-
curl -L -o core.mjs https://huggingface.co/spaces/mohith2309/mai-api/resolve/main/api/core.mjs
8.31 kB
| import {createHmac, timingSafeEqual} from 'node:crypto'; | |
| export function signature(body, secret, received) { | |
| if (!secret || !/^[a-f0-9]{64}$/i.test(received || '')) return false; | |
| const expected=createHmac('sha256',secret).update(body).digest(); | |
| return timingSafeEqual(expected,Buffer.from(received,'hex')); | |
| } | |
| // Razorpay key mode from the key id: rzp_test_… or rzp_live_… | |
| export function keyMode(keyId) { | |
| return keyId?.startsWith('rzp_live_') ? 'live' : keyId?.startsWith('rzp_test_') ? 'test' : null; | |
| } | |
| // Live checkout needs real paid-feature delivery (deliveryReady). Test checkout may run before that | |
| // only when the operator opts in (ALLOW_TEST_CHECKOUT=yes); test mode never moves money. | |
| export function ready(c, {live=true, allowTest=false}={}) { | |
| const base=Boolean(c.enabled && c.seller?.legalName && c.seller?.phone && c.seller?.address && c.firebase?.projectId && c.plans?.length); | |
| return base && Boolean(c.deliveryReady || (!live && allowTest)); | |
| } | |
| export function planId(p, mode) { | |
| return (typeof p.razorpayPlanId==='string' ? p.razorpayPlanId : p.razorpayPlanId?.[mode]) || ''; | |
| } | |
| export function checkedPlan(c,id,mode='live') { | |
| const p=c.plans.find(p=>p.id===id); | |
| const rid=p && planId(p,mode); | |
| if(!p || !/^plan_[A-Za-z0-9]+$/.test(rid) || !Number.isSafeInteger(p.amountPaise) || p.amountPaise<100 || !['monthly','yearly'].includes(p.period) || !Number.isSafeInteger(p.totalCount) || p.totalCount<1 || p.totalCount>(p.period==='monthly'?120:10)) throw Error('Invalid plan configuration'); | |
| return {...p,razorpayPlanId:rid}; | |
| } | |
| export function verifyPlan(local,remote) { | |
| if(remote.id!==local.razorpayPlanId || remote.item?.amount!==local.amountPaise || remote.item?.currency!=='INR' || remote.period!==local.period || remote.interval!==1) throw Error('Plan differs from displayed price or billing period'); | |
| } | |
| export function publicStatus(s) { | |
| return {id:s.id,status:s.status,paidCycles:s.paid_count||0,currentEnd:s.current_end||null,cancelScheduled:Boolean(s.has_scheduled_changes),remainingCycles:s.remaining_count}; | |
| } | |
| // A one-time payment covers one calendar month or year from when it starts (UTC calendar arithmetic). | |
| export function passEnd(startMs, period) { | |
| const d=new Date(startMs); | |
| if(period==='yearly')d.setUTCFullYear(d.getUTCFullYear()+1);else d.setUTCMonth(d.getUTCMonth()+1); | |
| return d.getTime(); | |
| } | |
| // A chat usage window ({start,count}: count is tokens) starts with the first reply and lasts `length` ms; expired or missing is empty. | |
| // Tokens one reply costs: (everything sent to the model + what came back) × the model's weight, so bigger models use a | |
| // plan faster. Counts the model reports are trusted within sane bounds; missing ones are estimated (about 4 characters | |
| // a token). Anything produced costs at least 1. | |
| export function estimateTokens(text){return Math.ceil(String(text??'').length/4);} | |
| export function replyCost(weight, promptTokens, outputTokens){ | |
| const w=Number(weight)>0?Number(weight):1; | |
| const n=Math.min(8192,Math.max(0,Math.round(Number(promptTokens)||0)))+Math.min(4096,Math.max(0,Math.round(Number(outputTokens)||0))); | |
| return Math.max(1,Math.ceil(w*n)); | |
| } | |
| export function usageWindow(w, length, now=Date.now()) { | |
| return !w || w.start==null || now>=w.start+length ? {start:null,count:0} : {start:w.start,count:w.count}; | |
| } | |
| // ---------------------------------------------------------------- request hardening (pure, unit-tested) | |
| // Token bucket per key: `capacity` requests, refilled evenly over `windowMs`. In memory, so it is per server instance. | |
| // take() returns 0 when allowed, else the seconds to wait (for Retry-After). Idle keys are pruned past `maxKeys`. | |
| export function limiter(capacity, windowMs, maxKeys=20000) { | |
| const buckets=new Map(), rate=capacity/windowMs; | |
| const level=(b,now)=>Math.min(capacity,b.tokens+Math.max(0,now-b.at)*rate); | |
| return { | |
| take(key, now=Date.now()) { | |
| let b=buckets.get(key); | |
| if(!b){ | |
| if(buckets.size>=maxKeys){ | |
| for(const [k,old] of buckets) if(level(old,now)>=capacity) buckets.delete(k); | |
| for(const k of buckets.keys()){ if(buckets.size<maxKeys) break; buckets.delete(k); } // still full: drop the oldest | |
| } | |
| b={tokens:capacity,at:now}; buckets.set(key,b); | |
| } | |
| b.tokens=level(b,now); b.at=Math.max(b.at,now); | |
| if(b.tokens>=1){b.tokens-=1;return 0;} | |
| return Math.max(1,Math.ceil((1-b.tokens)/rate/1000)); | |
| }, | |
| size:()=>buckets.size, | |
| }; | |
| } | |
| // Client address: the first X-Forwarded-For hop only behind a trusted proxy (TRUST_PROXY=yes), else the socket address. | |
| export function clientIp(headers, remote, trustProxy=false) { | |
| const hop=trustProxy ? String(headers?.['x-forwarded-for']||'').split(',')[0].trim() : ''; | |
| return (hop || remote || 'unknown').slice(0,64); | |
| } | |
| // JSON request bodies: malformed JSON or anything but an object is a 400. An empty body counts as {}. | |
| export function parseJson(buf) { | |
| const text=Buffer.isBuffer(buf) ? buf.toString('utf8') : String(buf??''); | |
| if(!text.trim()) return {}; | |
| let value; | |
| try { value=JSON.parse(text); } catch { throw Object.assign(Error('Malformed JSON.'),{http:400}); } | |
| if(!value || typeof value!=='object' || Array.isArray(value)) throw Object.assign(Error('Send a JSON object.'),{http:400}); | |
| return value; | |
| } | |
| const idOf=prefix=>v=>typeof v==='string' && new RegExp('^'+prefix+'_[A-Za-z0-9]{1,40}$').test(v); | |
| // Every field the API accepts, with its rule and the message shown when it is wrong. | |
| export const fields={ | |
| plan:[v=>typeof v==='string' && /^[a-z0-9-]{1,40}$/.test(v),'Choose a plan.'], | |
| acceptTerms:[v=>v===true,'Accept the terms before continuing.'], | |
| razorpay_order_id:[idOf('order'),'Missing payment details.'], | |
| razorpay_payment_id:[idOf('pay'),'Missing payment details.'], | |
| razorpay_subscription_id:[idOf('sub'),'Missing payment details.'], | |
| razorpay_signature:[v=>typeof v==='string' && /^[a-f0-9]{64}$/i.test(v),'Missing payment details.'], | |
| messages:[v=>Array.isArray(v) && v.length>=1 && v.length<=12,'Send between 1 and 12 messages.'], | |
| confirm:[v=>v===true,'Confirm that you want to delete your account.'], | |
| model:[v=>v===undefined || (typeof v==='string' && /^[a-z0-9-]{1,20}$/.test(v)),'Choose a model.'], | |
| reason:[v=>v===undefined || ['price','not-using','waiting-for-chat','switching','other'].includes(v),'Choose a reason from the list.'], | |
| }; | |
| // Strict bodies per POST route: exactly these fields, nothing else. | |
| export const bodies={ | |
| '/api/billing/create':['plan','acceptTerms'], '/api/billing/create-order':['plan','acceptTerms'], | |
| '/api/billing/verify-payment':['razorpay_order_id','razorpay_payment_id','razorpay_signature'], | |
| '/api/billing/verify':['razorpay_payment_id','razorpay_subscription_id','razorpay_signature'], | |
| '/api/billing/cancel':['reason'], '/api/chat/send':['messages','model'], '/api/account/delete':['confirm'], | |
| '/api/billing/change':['plan','acceptTerms'], '/api/billing/cancel-next':[], | |
| }; | |
| // Returns '' when the body is acceptable, else a message safe to show the user. | |
| export function checkBody(body, names) { | |
| if(Object.keys(body).some(k=>!names.includes(k))) return 'Unexpected field in request.'; | |
| for(const n of names){ const [ok,message]=fields[n]; if(!ok(body[n])) return message; } | |
| return ''; | |
| } | |
| // create-order reuses the buyer's own unpaid order for the same plan and amount from the last 15 minutes, so a double | |
| // click or a retry never leaves two payable orders open. Razorpay's own record then decides what to do with it. | |
| export const REUSE_MS=15*60e3; | |
| export function reusableOrder(rows, {uid, plan, amount, now=Date.now()}) { | |
| return rows.filter(o=>o.uid===uid && o.plan===plan && o.amount===amount && o.status==='created' && o.created<=now && now-o.created<REUSE_MS) | |
| .sort((a,b)=>b.created-a.created)[0] || null; | |
| } | |
| // 'reuse' (still unpaid), 'settle' (money arrived or is held: confirm it, never open another order), or 'new'. | |
| export function reuseDecision(local, remote, payments=[]) { | |
| if(!local || !remote || remote.id!==local.id || remote.amount!==local.amount || remote.currency!=='INR') return 'new'; | |
| if(remote.status==='paid' || remote.amount_paid>0 || payments.some(p=>['authorized','captured'].includes(p.status))) return 'settle'; | |
| return ['created','attempted'].includes(remote.status) ? 'reuse' : 'new'; | |
| } | |