File size: 41,449 Bytes
cf67874
6c0a39c
 
 
 
 
 
 
 
cf67874
6c0a39c
 
 
 
 
 
 
 
cf67874
6c0a39c
 
 
 
 
 
 
 
cf67874
 
6c0a39c
 
 
 
 
 
 
 
 
 
 
 
 
2ad3a4f
 
 
 
 
 
 
 
 
 
6c0a39c
 
a4b81df
 
6c0a39c
 
 
 
 
 
 
 
 
 
 
cf67874
6c0a39c
 
 
 
 
 
 
a4b81df
 
6c0a39c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2b3664
6c0a39c
 
cf67874
 
 
 
6c0a39c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234de73
 
 
 
 
 
 
 
 
 
 
cf67874
6c0a39c
 
cf67874
6c0a39c
 
cf67874
 
6c0a39c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf67874
 
 
6c0a39c
 
 
cf67874
 
 
 
 
 
6c0a39c
 
 
 
cf67874
 
6c0a39c
 
cf67874
6c0a39c
 
 
 
 
 
 
 
 
 
cf67874
6c0a39c
cf67874
6c0a39c
 
cf67874
 
6c0a39c
 
 
cf67874
 
6c0a39c
 
 
 
cf67874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c0a39c
 
 
 
 
cf67874
6c0a39c
 
 
cf67874
 
 
 
 
6c0a39c
 
 
 
cf67874
 
 
6c0a39c
cf67874
6c0a39c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4b81df
 
 
6c0a39c
cf67874
 
 
 
 
 
6c0a39c
cf67874
 
6c0a39c
cf67874
 
6c0a39c
cf67874
6c0a39c
 
a4b81df
 
 
 
 
6c0a39c
 
 
 
cf67874
 
 
 
 
 
 
 
 
 
 
 
 
 
6c0a39c
cf67874
 
 
 
 
 
 
6c0a39c
 
 
cf67874
6c0a39c
 
cf67874
 
 
6c0a39c
 
cf67874
 
 
 
 
 
 
 
 
 
 
6c0a39c
 
 
 
 
a4b81df
 
 
 
 
 
 
cf67874
 
 
a4b81df
cf67874
 
 
 
 
a4b81df
 
 
 
 
 
 
 
 
6c0a39c
 
 
 
 
 
 
 
 
 
cf67874
6c0a39c
 
 
 
 
 
234de73
 
6c0a39c
 
 
 
 
 
 
 
 
 
 
a4b81df
cf67874
6c0a39c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4b81df
6c0a39c
 
 
 
 
 
 
 
 
 
 
 
a4b81df
 
 
 
 
6c0a39c
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
import {cachedAccess,deliverEvent,capturedPayment,refundRevokes,subscriptionPaidUp,renews,successorStart} from './access.mjs';
// m.ai API: subscriptions (Razorpay) and chat (Spark), behind Firebase sign-in.
// Every paid action is decided here, never in the browser: the plan is read from Razorpay,
// and chat usage limits are counted in Firestore. One handler, two hosts:
// index.mjs (Firebase Functions, production) and server.mjs (plain Node http server, npm run dev).
import {readFileSync} from 'node:fs';
import {randomUUID} from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {dirname,join} from 'node:path';
import {signature,ready,keyMode,planId,checkedPlan,verifyPlan,publicStatus,limiter,clientIp,parseJson,bodies,checkBody,reusableOrder,reuseDecision,estimateTokens,replyCost} from './core.mjs';
import {storage} from './store.mjs';
import {initializeApp,applicationDefault,cert,getApps} from 'firebase-admin/app';
import {getAuth} from 'firebase-admin/auth';
import {getFirestore} from 'firebase-admin/firestore';
const root=dirname(fileURLToPath(import.meta.url));
const config=JSON.parse(readFileSync(join(root,'config.json')));
const SESSION=config.usage.sessionHours*3600e3, WEEK=config.usage.weekDays*86400e3, BODY_LIMIT=32768;
const MODEL_TIMEOUT=50e3; // Firebase Hosting ends a rewritten request at 60 s, so a reply must finish before that
let key,secret,webhookSecret,origin,modelUrl,trustProxy,mode,live,enabled,plans,store,rzp='https://api.razorpay.com/v1/',stopping=false;

// Reads keys and settings once per process: from Functions secrets and params (index.mjs) or the shell (server.mjs).
export function init(env=process.env){
  key=env.RAZORPAY_KEY_ID; secret=env.RAZORPAY_KEY_SECRET; webhookSecret=env.RAZORPAY_WEBHOOK_SECRET;
  origin=env.SITE_ORIGIN || 'https://mai-alus.web.app';
  modelUrl=env.MAI_MODEL_URL || ''; // Spark's chat endpoint; empty: chat answers that Spark is offline
  trustProxy=env.TRUST_PROXY==='yes'; // set behind Firebase Hosting / Cloud Run / any reverse proxy
  mode=keyMode(key); live=mode==='live';
  // Local UI tests only: a stand-in Razorpay on this machine. Ignored unless the key is a test key and the address is local.
  if(mode==='test' && /^http:\/\/127\.0\.0\.1:\d+\/v1\/$/.test(env.RAZORPAY_API_BASE||''))rzp=env.RAZORPAY_API_BASE;
  // Live keys need deliveryReady (config.json) AND ALLOW_LIVE_PAYMENTS=yes; test keys need deliveryReady or ALLOW_TEST_CHECKOUT=yes.
  enabled=Boolean(mode && secret && webhookSecret && ready(config,{live,allowTest:env.ALLOW_TEST_CHECKOUT==='yes'}) && (!live || env.ALLOW_LIVE_PAYMENTS==='yes'));
  plans=config.plans.filter(p=>planId(p,mode));
  // FIREBASE_AUTH_EMULATOR_HOST / FIRESTORE_EMULATOR_HOST are only set locally (dev.mjs, emulators); production uses the real ones.
  // Hosts outside Google (the Hugging Face Space) log in with a service-account key kept in the FIREBASE_SERVICE_ACCOUNT secret.
  const account=env.FIREBASE_SERVICE_ACCOUNT?JSON.parse(env.FIREBASE_SERVICE_ACCOUNT):null;
  if(!getApps().length)initializeApp({projectId:env.FIREBASE_PROJECT_ID||account?.project_id||env.GCLOUD_PROJECT||config.firebase.projectId,
    ...(env.FIREBASE_AUTH_EMULATOR_HOST?{}:{credential:account?cert(account):applicationDefault()})});
  store=storage(getFirestore(),{session:SESSION,week:WEEK});
  return {checkout:enabled?mode:'disabled',trustProxy,model:modelUrl||'offline'};
}
// Graceful shutdown (server.mjs): health turns 503 and connections close after their reply.
export function drain(){stopping=true;}
// One look at every live plan at startup, so a wrong key, a missing plan or a price mismatch shows in the logs
// before a buyer meets it. Logs Razorpay's error text only (never keys).
export async function providerCheck(){
  if(!enabled)return log('info','provider-check',{checkout:'disabled'});
  for(const p of plans){
    try{verifyPlan(checkedPlan(config,p.id,mode),await razor('plans/'+planId(p,mode)));}
    catch(e){return log('error','provider-check',{plan:p.id,error:String(e.message).slice(0,200)});}
  }
  log('info','provider-check',{ok:true,mode,plans:plans.length});
}

const finished=s=>['cancelled','completed','expired'].includes(s.status);
// paidUp: the server's own answer to "does this subscription still give access" (the page follows it, never guesses).
const status=(s,row)=>({...publicStatus(s),cancelScheduled:Boolean(s.has_scheduled_changes||(row.cancel_at&&!finished(s))),paidUp:subscriptionPaidUp(s)});
// In memory, per server instance (production runs one instance; Firestore transactions guard the data either way).
const locks=new Set(), chatting=new Set(), plansSeen=new Map(), settling=new Map();
// Errors made with fail() carry a status and a message that is safe to show; anything else becomes a generic 500.
const fail=(code,error,extra={},headers={})=>Object.assign(Error(error),{http:code,extra,headers});
// One-line JSON logs. Never log tokens, keys, signatures or payment details (uid and Razorpay ids are fine).
const log=(level,event,data={})=>console[level==='info'?'log':'error'](JSON.stringify({t:new Date().toISOString(),level,event,...data}));

async function razor(path,method='GET',body) {
  const what={method,resource:path.split('/')[0]};
  let r,data;
  try{
    r=await fetch(rzp+path,{method,signal:AbortSignal.timeout(20000),headers:{Authorization:'Basic '+Buffer.from(key+':'+secret).toString('base64'),'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});
    data=await r.json();
  }catch(e){
    const slow=['TimeoutError','AbortError'].includes(e.name);
    log('error','razorpay',{...what,status:r?.status,error:slow?'timeout':e.name});
    throw slow?fail(504,'The payment provider is taking too long to respond. Wait a minute and check Account before trying again.')
              :fail(502,'We could not reach the payment provider. Please try again in a minute.');
  }
  // rejected: Razorpay refused the request outright (4xx), so nothing was created on its side.
  if(!r.ok){log('error','razorpay',{...what,status:r.status,error:String(data?.error?.description||'').slice(0,200)});throw Object.assign(fail(502,'Payment provider request failed; contact support if a payment was attempted.'),{rejected:r.status>=400&&r.status<500});}
  return data;
}
function send(res,code,data,headers={}){res.writeHead(code,{'Content-Type':'application/json; charset=utf-8',...headers});res.end(JSON.stringify(data));}
// The exact request bytes (webhook signatures are computed over them). Firebase Functions has already read the
// body into req.rawBody (and parsed req.body, which is ignored here); the plain http server streams it.
async function raw(req){
  if(Number(req.headers['content-length'])>BODY_LIMIT)throw fail(413,'Request too large.');
  if(Buffer.isBuffer(req.rawBody)){if(req.rawBody.length>BODY_LIMIT)throw fail(413,'Request too large.');return req.rawBody;}
  const chunks=[];let size=0;
  for await(const c of req){size+=c.length;if(size>BODY_LIMIT)throw fail(413,'Request too large.');chunks.push(c);}
  return Buffer.concat(chunks);
}
async function signedIn(req){
  const match=(req.headers.authorization||'').match(/^Bearer (.+)$/);
  if(!match)throw fail(401,'Sign in first.');
  let user;
  try{user=await getAuth().verifyIdToken(match[1],true);}catch{throw fail(401,'Your session expired. Sign in again.');}
  if(!user.email_verified)throw fail(403,'Verify your email first.',{code:'verify-email'});
  return user;
}

// ---------------------------------------------------------------- rate limits (in memory, per server instance)
// Requests per minute, per client address (checked before sign-in) and per signed-in account. Webhooks are exempt.
const limits={
  read:{ip:limiter(120,60e3),uid:limiter(60,60e3)},  // GET: config, account, chat usage, health
  pay:{ip:limiter(30,60e3),uid:limiter(10,60e3)},    // POST: create, create-order, verify, verify-payment, cancel
  chat:{ip:limiter(60,60e3),uid:limiter(20,60e3)},   // POST: chat send (plus the plan's own message limits)
};
const logOnce=limiter(1,60e3);
function limit(group,by,id){
  const wait=limits[group][by].take(id);
  if(!wait)return;
  if(!logOnce.take(group+by+id))log('warn','rate-limited',{group,by,...(by==='uid'?{uid:id}:{})});
  throw fail(429,'Too many requests. Please wait a moment and try again.',{},{'Retry-After':String(wait)});
}

// ---------------------------------------------------------------- plan and usage (server-side only)
// The paid plan comes from Razorpay (cached for a minute); a cancelled plan keeps working until its paid period ends.
async function entitlement(uid,fresh=false){
  const cached=plansSeen.get(uid);
  if(!fresh && cachedAccess(cached))return cached.value;
  const row=await store.account(uid);
  let value=null;
  if(row && !row.sid.startsWith('pending:') && enabled){
    const sub=await razor('subscriptions/'+row.sid);
    const paidUp=subscriptionPaidUp(sub);
    const plan=config.plans.find(p=>p.id===row.plan);
    if(paidUp && plan)value={tier:plan.tier,plan:plan.id};
    if(!value && row.next_sid && !row.next_sid.startsWith('pending:')){ // a switch or resubscription that has started
      const nextPlan=config.plans.find(p=>p.id===row.next_plan);
      if(nextPlan && subscriptionPaidUp(await razor('subscriptions/'+row.next_sid)))value={tier:nextPlan.tier,plan:nextPlan.id};
    }
  }
  const pass=await store.pass(uid);
  if(!value && pass)value={tier:config.plans.find(p=>p.id===pass.plan).tier,plan:pass.plan,until:pass.ends};
  plansSeen.set(uid,{at:Date.now(),value});
  return value;
}
// ---------------------------------------------------------------- one-time payments (Razorpay Orders)
function passView(o){const p=config.plans.find(x=>x.id===o.plan);return {plan:o.plan,name:p.name,period:p.period,amountPaise:o.amount,starts:o.starts,ends:o.ends,orderId:o.id,paymentId:o.payment};}
// One settlement per order at a time in this instance (the browser callback and the webhook may arrive together);
// store.markPaid settles it exactly once in Firestore even across instances.
function settleOrder(id){
  if(!settling.has(id))settling.set(id,settle(id).finally(()=>settling.delete(id)));
  return settling.get(id);
}
// Razorpay's order record is the only proof of payment. Called after a verified browser callback or webhook.
async function settle(id){
  const local=await store.order(id);
  if(!local)return null;
  if(local.status==='paid')return local;
  let remote=await razor('orders/'+id);
  if(remote.status!=='paid'){ // payments left "authorized" (manual capture accounts) are captured for the exact order amount
    const held=(await razor('orders/'+id+'/payments')).items?.find(p=>p.order_id===local.id&&p.status==='authorized'&&p.amount===local.amount&&p.currency==='INR');
    if(held){await razor('payments/'+held.id+'/capture','POST',{amount:local.amount,currency:'INR'});remote=await razor('orders/'+id);}
  }
  if(remote.status!=='paid'||remote.amount!==local.amount||remote.amount_paid!==local.amount||remote.currency!=='INR')return null;
  const paid=capturedPayment(local,remote,(await razor('orders/'+id+'/payments')).items||[]);
  if(!paid)return null;
  const settled=await store.markPaid(id,paid?.id,config.plans.find(p=>p.id===local.plan).period);
  plansSeen.delete(local.uid);
  return settled;
}

// A refunded one-time payment ends its pass (Razorpay's payment record decides). Subscription refunds are left to the
// subscription's own status: cancel the subscription in Razorpay to end that access.
async function revokeRefunded(paymentId){
  const payment=await razor('payments/'+paymentId);
  if(typeof payment.order_id!=='string'||!/^order_[A-Za-z0-9]+$/.test(payment.order_id))return;
  const local=await store.order(payment.order_id);
  if(!refundRevokes(local,payment))return;
  if(await store.markRefunded(local.id))log('info','pass-refunded',{uid:local.uid,order:local.id});
  plansSeen.delete(local.uid);
}

// Limits and use are in tokens (see replyCost). The page shows them as a share of each window.
function usageView(tier,{session:s,week:w}){
  const t=config.tiers[tier];
  return {plan:{tier,name:t.name},unit:'tokens',limits:{session:t.session,week:t.week},used:{session:s.count,week:w.count},
          resets:{session:s.start?Math.round((s.start+SESSION)/1000):null,week:w.start?Math.round((w.start+WEEK)/1000):null}};
}
const at=sec=>new Date(sec*1000).toLocaleTimeString('en-IN',{hour:'numeric',minute:'2-digit',timeZone:'Asia/Kolkata'});
const onDay=sec=>new Date(sec*1000).toLocaleDateString('en-IN',{weekday:'long',day:'numeric',month:'long',timeZone:'Asia/Kolkata'});
function cleanMessages(list){
  if(!Array.isArray(list)||!list.length||list.length>12)throw fail(400,'Send between 1 and 12 messages.');
  let total=0;
  const out=list.map(m=>{
    if(!m||!['user','assistant'].includes(m.role)||typeof m.content!=='string')throw fail(400,'Invalid message.');
    const content=m.content.trim().slice(0,2000); total+=content.length;
    return {role:m.role,content};
  });
  if(total>8000)throw fail(400,'That conversation is too long. Start a new chat.');
  if(out.at(-1).role!=='user'||!out.at(-1).content)throw fail(400,'End with your message.');
  return out;
}

async function chat(req,res,path,user,body){
  const uid=user.uid;
  let ent;
  try{ent=await entitlement(uid);}catch{throw fail(503,'We could not check your plan right now. Please try again in a minute.');}
  if(!ent)throw fail(402,'Chat with Spark comes with an m.ai plan.',{code:'no-plan'});
  if(path==='/usage')return send(res,200,usageView(ent.tier,await store.usage(uid)));
  const messages=cleanMessages(body.messages);
  const model=config.models[body.model||'spark'];
  if(!model?.available)throw fail(400,'That model is not available yet.');
  if(!modelUrl)throw fail(503,'Spark is offline right now. Nothing was counted. Try again soon.');
  if(chatting.has(uid))throw fail(409,'Spark is still answering your last message.');
  chatting.add(uid);
  try{
    // Limits are checked before the reply and the reply's tokens charged after it, so a failed reply costs nothing.
    const t=config.tiers[ent.tier], u=usageView(ent.tier,await store.usage(uid));
    if(u.used.session>=u.limits.session)throw fail(429,`You've reached this session's limit. It resets at ${at(u.resets.session)}.`,{usage:u});
    if(u.used.week>=u.limits.week)throw fail(429,`You've reached this week's limit. It resets on ${onDay(u.resets.week)}.`,{usage:u});
    const sent=messages.map(m=>m.content).join('\n');
    const charge=(promptTokens,outputTokens)=>store.charge(uid,replyCost(model.weight,promptTokens,outputTokens)).catch(e=>log('error','charge',{uid,error:e.name}));
    const stop=new AbortController();
    res.on('close',()=>stop.abort());
    let upstream;
    try{upstream=await fetch(modelUrl,{method:'POST',signal:AbortSignal.any([stop.signal,AbortSignal.timeout(MODEL_TIMEOUT)]),headers:{'Content-Type':'application/json'},body:JSON.stringify({messages,max_tokens:128})});}
    catch{throw fail(503,'Spark is offline right now. Nothing was counted. Try again soon.');}
    if(!upstream.ok){const busy=upstream.status===429;throw fail(503,busy?'Spark is busy with another reply. Nothing was counted; try again in a moment.':'Spark could not answer right now. Nothing was counted.');}
    res.writeHead(200,{'Content-Type':'text/event-stream'});
    const reader=upstream.body.getReader(), decoder=new TextDecoder();
    let buffer='', produced='', ok=true, promptTokens=null, outputTokens=null;
    try{
      for(;;){
        const {value,done}=await reader.read();
        if(done)break;
        buffer+=decoder.decode(value,{stream:true});
        let cut;
        while((cut=buffer.indexOf('\n\n'))>=0){
          const line=buffer.slice(0,cut).replace(/^data: /,''); buffer=buffer.slice(cut+2);
          if(!line)continue;
          let event; try{event=JSON.parse(line);}catch{continue;}
          if(typeof event.t==='string'&&event.t){produced+=event.t;res.write('data: '+JSON.stringify({t:event.t})+'\n\n');}
          if(event.error){ok=false;}
          if(event.done){if(event.unavailable)ok=false; promptTokens=event.prompt_tokens; outputTokens=event.tokens;}
        }
      }
    }catch(e){ // the model stopped mid-reply or the reader left: only what was shown is charged
      if(produced)await charge(promptTokens??estimateTokens(sent)+40,estimateTokens(produced));
      if(stop.signal.aborted)return res.end();
      throw e;
    }
    if(!ok||!produced){res.write('data: '+JSON.stringify({error:'Spark could not answer that. Nothing was counted.'})+'\n\n');}
    else await charge(promptTokens??estimateTokens(sent)+40,outputTokens??estimateTokens(produced));
    res.end('data: '+JSON.stringify({done:true,usage:usageView(ent.tier,await store.usage(uid))})+'\n\n');
  }finally{chatting.delete(uid);}
}

// ---------------------------------------------------------------- plan switches and resubscribing
// Razorpay cannot resume a cancelled subscription, and UPI AutoPay / e-mandate subscriptions cannot change plan in place.
// So both work one way for every payment method: a "next" subscription starts the day the current paid period ends
// (Razorpay checks the payment method with ₹5 now and refunds it). The current one stops renewing only once the next one
// is authorised, so nobody pays twice for a period and nobody loses paid days.
const RECONCILE='An earlier checkout needs support reconciliation. Do not start another payment.';
const NO_NEXT={next_sid:null,next_plan:null,next_start:null,next_kind:null};
const day=sec=>new Date(sec*1000).toLocaleDateString('en-IN',{day:'numeric',month:'long',year:'numeric',timeZone:'Asia/Kolkata'});
const fetchNext=row=>row.next_sid&&!row.next_sid.startsWith('pending:')?razor('subscriptions/'+row.next_sid):null;
const nextView=(n,row)=>n?{plan:row.next_plan,status:n.status,startsAt:n.start_at||row.next_start||null,kind:row.next_kind||'resubscribe',paidUp:subscriptionPaidUp(n)}:null;

// Brings the account in line with Razorpay before anything is shown or changed. Returns {row,current,next,problem}.
async function reconcile(uid,row,current,next){
  let problem='';
  if(next && finished(next) && !subscriptionPaidUp(next)){ // a next plan that ended before it began (cancelled or abandoned)
    await store.clearNext(uid,row.next_sid); row={...row,...NO_NEXT}; next=null;
  }
  if(next && ['authenticated','active','pending'].includes(next.status) && renews(current,row)){
    // The next plan is authorised: the current one now stops renewing at the end of its paid period.
    let stopped=false;
    try{await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:current.status==='active'?1:0});stopped=true;}
    catch(e){log('error','plan-switch-cancel',{uid,error:String(e.message).slice(0,120)});}
    if(stopped){
      const at=Date.now(); await store.setCancelAt(uid,at); row={...row,cancel_at:at};
      log('info','plan-switch',{uid,from:row.sid,to:row.next_sid});
      current=await razor('subscriptions/'+row.sid);
    }else{
      // The old plan would keep renewing beside the new one: cancel the new one instead, so nobody pays twice.
      try{
        await razor('subscriptions/'+row.next_sid+'/cancel','POST',{cancel_at_cycle_end:0});
        await store.clearNext(uid,row.next_sid); row={...row,...NO_NEXT}; next=null;
        problem='We could not switch your plan, so nothing changed and nothing extra was charged. Please try again in a few minutes.';
      }catch{
        log('error','plan-switch-stuck',{uid,current:row.sid,next:row.next_sid});
        problem='Your plan change needs a quick check from us. You will not be charged twice; we will email you.';
      }
    }
  }
  if(next && finished(current) && !subscriptionPaidUp(current) && ['authenticated','active','pending'].includes(next.status)){
    // The current period is over and the next subscription has taken over.
    if(await store.promote(uid,row.sid,row.next_sid)){
      log('info','plan-promoted',{uid,from:row.sid,to:row.next_sid});
      row={...row,sid:row.next_sid,plan:row.next_plan,cancel_at:null,...NO_NEXT}; current=next; next=null;
    }
  }
  plansSeen.delete(uid);
  return {row,current,next,problem};
}
// Webhook path: only accounts with a next subscription need anything done.
async function reconcileUid(uid){
  const row=await store.account(uid);
  if(!row || !row.next_sid || row.sid.startsWith('pending:') || row.next_sid.startsWith('pending:'))return;
  if(locks.has(uid))throw fail(503,'Account busy; retry this notification.');
  locks.add(uid);
  try{await reconcile(uid,row,await razor('subscriptions/'+row.sid),await razor('subscriptions/'+row.next_sid));}
  finally{locks.delete(uid);}
}
// A next plan whose checkout was never finished: the same plan picks it up again (returns the reply); another plan
// replaces it (returns null after cancelling it). A next plan already authorised must be cancelled by the buyer first.
async function reuseNext(uid,row,next,plan){
  if(next.status==='created' && row.next_plan===plan.id)return {keyId:key,subscriptionId:row.next_sid,startsAt:row.next_start,next:true};
  if(next.status!=='created')throw fail(409,'A new plan is already scheduled to start on '+day(row.next_start)+'. Cancel it on your Account page to choose another.',{code:'next-scheduled'});
  await razor('subscriptions/'+row.next_sid+'/cancel','POST',{cancel_at_cycle_end:0});
  await store.clearNext(uid,row.next_sid);
  return null;
}
async function verifiedPlan(plan){
  const remote=await razor('plans/'+plan.razorpayPlanId);
  try{verifyPlan(plan,remote);}catch{log('error','plan-mismatch',{plan:plan.id});throw fail(503,'This plan is temporarily unavailable. Please contact support.');}
}
// Creates the next subscription, starting when the current paid period ends.
async function createNext(res,uid,row,plan,current,kind){
  const startAt=successorStart(current);
  if(!startAt)throw fail(409,'Your current period ends in the next few minutes. Try again once it has renewed or ended.',{code:'too-close'});
  const pending='pending:'+randomUUID();
  if(!await store.setNext(uid,row.next_sid??null,{next_sid:pending,next_plan:plan.id,next_start:startAt,next_kind:kind}))throw fail(409,'A billing request is already in progress.');
  let sub;
  try{sub=await razor('subscriptions','POST',{plan_id:plan.razorpayPlanId,total_count:plan.totalCount,quantity:1,customer_notify:1,start_at:startAt,notes:{mai_uid:uid,mai_plan:plan.id,mai_after:row.sid}});}
  catch(e){if(e.rejected)await store.clearNext(uid,pending);throw e;}
  if(!/^sub_[A-Za-z0-9]+$/.test(sub.id))throw fail(502,'Unexpected provider response; contact support.');
  if(!await store.setNext(uid,pending,{next_sid:sub.id,next_plan:plan.id,next_start:startAt,next_kind:kind})){log('error','next-unrecorded',{uid,subscription:sub.id});throw fail(409,RECONCILE);}
  return send(res,200,{keyId:key,subscriptionId:sub.id,startsAt:startAt,next:true});
}

// ---------------------------------------------------------------- billing routes (signed in, checkout enabled)
async function billing(req,res,path,uid,body){
  if(locks.has(uid))return send(res,409,{error:'A billing request is already in progress.'});
  locks.add(uid);
  try {
    let row=await store.account(uid);
    if(path==='/account'){
      const queuedPasses=(await store.ordersOf(uid)).filter(o=>o.status==='paid'&&o.starts>Date.now()).sort((a,b)=>a.starts-b.starts).slice(0,100).map(passView);
      const pass=await store.pass(uid);
      if(!row)return send(res,200,{subscription:null,next:null,pass:pass?passView(pass):null,queuedPasses});
      if(row.sid.startsWith('pending:'))return send(res,409,{error:RECONCILE});
      const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
      return send(res,200,{subscription:status(r.current,r.row),plan:r.row.plan,next:nextView(r.next,r.row),nextPending:Boolean(r.row.next_sid?.startsWith('pending:')),
                           problem:r.problem||null,pass:pass?passView(pass):null,queuedPasses});
    }
    if(path==='/create-order'){ // Razorpay Standard Checkout: one-time payment for one month or one year of a plan
      const plan=config.plans.find(p=>p.id===body.plan);
      if(!plan||!Number.isSafeInteger(plan.amountPaise)||plan.amountPaise<100)throw fail(400,'Choose a plan.');
      // A subscription that is live, or a next one that has started or is scheduled, already covers this time.
      const live=s=>s && ['active','pending','authenticated'].includes(s.status);
      if(row && !row.sid.startsWith('pending:') && (live(await razor('subscriptions/'+row.sid)) || live(await fetchNext(row))))
        throw fail(409,'You already have an active subscription. Manage it from Account.');
      if(row?.next_sid?.startsWith('pending:'))throw fail(409,RECONCILE);
      const reply=o=>send(res,200,{keyId:key,orderId:o.id,amount:o.amount,currency:'INR',plan:{id:plan.id,name:plan.name,period:plan.period}});
      // A double click or a retry within 15 minutes gets the same unpaid order back, never a second payable one.
      const earlier=reusableOrder(await store.ordersOf(uid),{uid,plan:plan.id,amount:plan.amountPaise,now:Date.now()});
      if(earlier){
        const remote=await razor('orders/'+earlier.id);
        const payments=remote.status==='attempted'?(await razor('orders/'+earlier.id+'/payments')).items||[]:[];
        const decision=reuseDecision(earlier,remote,payments);
        if(decision==='reuse')return reply(earlier);
        if(decision==='settle')throw fail(409,(await settleOrder(earlier.id))?'This plan is already paid. You can see it on your Account page.'
                                                                             :'A payment for this plan is still being confirmed. Check Account in a minute before paying again.');
      }
      const order=await razor('orders','POST',{amount:plan.amountPaise,currency:'INR',receipt:'mai_'+randomUUID().replaceAll('-','').slice(0,24),
                                               notes:{mai_uid:uid,mai_plan:plan.id,kind:'one-time'}});
      if(!/^order_[A-Za-z0-9]+$/.test(order.id)||order.amount!==plan.amountPaise||order.currency!=='INR')throw fail(502,'Unexpected provider response; contact support.');
      await store.addOrder({id:order.id,uid,plan:plan.id,amount:plan.amountPaise,status:'created',created:Date.now(),payment:null,starts:null,ends:null});
      return reply(order);
    }
    if(path==='/verify-payment'){ // idempotent: an order already settled is returned as it is
      const {razorpay_order_id:oid,razorpay_payment_id:pid,razorpay_signature:sig}=body;
      const local=await store.order(oid);
      // HMAC-SHA256(order_id|payment_id, key secret); a mismatch never marks anything as paid.
      if(!local||local.uid!==uid||!signature(oid+'|'+pid,secret,sig))return send(res,400,{error:'Payment verification failed.'});
      const settled=await settleOrder(oid);
      if(!settled)return send(res,409,{error:'Payment received but not confirmed by Razorpay yet. Refresh Account in a minute; contact us if it does not appear.'});
      return send(res,200,{verified:true,pass:passView(settled)});
    }
    if(path==='/create'){
      let plan;
      try{plan=checkedPlan(config,body.plan,mode);}catch{throw fail(400,'Choose a plan.');}
      // One-time time already paid for would overlap a subscription that starts today: never charge twice for the same days.
      const paidUntil=Math.max(0,...(await store.ordersOf(uid)).filter(o=>o.status==='paid'&&o.ends>Date.now()).map(o=>o.ends));
      if(paidUntil)throw fail(409,'Your one-time plan runs until '+new Date(paidUntil).toLocaleDateString('en-IN',{day:'numeric',month:'long',year:'numeric',timeZone:'Asia/Kolkata'})+'. Subscribe after that date, or add time on the Pay page.',{code:'pass-active'});
      if(row){
        if(row.sid.startsWith('pending:') || row.next_sid?.startsWith('pending:'))throw fail(409,RECONCILE);
        const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
        if(r.problem)throw fail(409,r.problem);
        row=r.row;
        const existing=r.current;
        if(r.next){const again=await reuseNext(uid,row,r.next,plan); if(again)return send(res,200,again); row={...row,...NO_NEXT};}
        if(['created','authenticated'].includes(existing.status) && row.plan===plan.id)return send(res,200,{keyId:key,subscriptionId:row.sid});
        // An unpaid checkout for a different plan is replaced. A renewing plan is switched with Change plan. With renewal
        // off and paid time left, subscribing again starts the day that time ends (no paying twice, no lost days).
        if(existing.status==='created')await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:0});
        else if(renews(existing,row))throw fail(409,'You already have a subscription. To switch plans, use Change plan on your Account page.',{code:'use-change'});
        else if(subscriptionPaidUp(existing)){await verifiedPlan(plan); return await createNext(res,uid,row,plan,existing,'resubscribe');}
      }
      await verifiedPlan(plan);
      const pending='pending:'+randomUUID();
      if(!await store.replaceSid(uid,row?.sid??null,pending,{plan:plan.id,created:Date.now(),cancel_at:null}))throw fail(409,'A billing request is already in progress.');
      // If the request times out or Razorpay fails on its side, keep pending: a subscription may exist, and a retry
      // could charge twice. If Razorpay refused it outright, none exists: undo the mark so the buyer can simply retry.
      let sub;
      try{sub=await razor('subscriptions','POST',{plan_id:plan.razorpayPlanId,total_count:plan.totalCount,quantity:1,customer_notify:1,notes:{mai_uid:uid,mai_plan:plan.id}});}
      catch(e){if(e.rejected)await store.restoreSid(uid,pending,row);throw e;}
      if(!/^sub_[A-Za-z0-9]+$/.test(sub.id))throw fail(502,'Unexpected provider response; contact support.');
      if(!await store.replaceSid(uid,pending,sub.id)){log('error','subscription-unrecorded',{uid,subscription:sub.id});throw fail(409,'An earlier checkout needs support reconciliation. Do not start another payment.');}
      return send(res,200,{keyId:key,subscriptionId:sub.id});
    }
    if(path==='/change'){ // switch plans from the next billing period: the new plan starts when the paid period ends
      let plan;
      try{plan=checkedPlan(config,body.plan,mode);}catch{throw fail(400,'Choose a plan.');}
      if(!row)throw fail(409,'You have no subscription to change. Choose a plan to subscribe.');
      if(row.sid.startsWith('pending:') || row.next_sid?.startsWith('pending:'))throw fail(409,RECONCILE);
      const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
      if(r.problem)throw fail(409,r.problem);
      row=r.row;
      if(r.next){const again=await reuseNext(uid,row,r.next,plan); if(again)return send(res,200,again); row={...row,...NO_NEXT};}
      if(r.current.status!=='active' || !renews(r.current,row))throw fail(409,'Only an active subscription that renews can change plan. If renewal is off, use Resubscribe.',{code:'not-renewing'});
      if(plan.id===row.plan)throw fail(400,'That is already your plan.');
      await verifiedPlan(plan);
      return await createNext(res,uid,row,plan,r.current,'switch');
    }
    if(!row || row.sid.startsWith('pending:'))return send(res,409,{error:'No subscription ready to manage.'});
    if(path==='/verify'){ // the current subscription's checkout, or the next one's (switch or resubscribe)
      const id=body.razorpay_subscription_id;
      const target=id===row.sid ? row.sid : row.next_sid && !row.next_sid.startsWith('pending:') && id===row.next_sid ? row.next_sid : null;
      if(!target || !signature(body.razorpay_payment_id+'|'+target,secret,body.razorpay_signature))return send(res,400,{error:'Payment verification failed.'});
      const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
      if(r.problem)throw fail(409,r.problem);
      return send(res,200,{verified:true,subscription:status(r.current,r.row),plan:r.row.plan,next:nextView(r.next,r.row)});
    }
    if(path==='/cancel'){
      const sub=await razor('subscriptions/'+row.sid);
      if(renews(sub,row)){
        // Active plans end at the close of the paid period; unpaid (created/authenticated) ones stop now.
        await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:sub.status==='active'?1:0});
        row={...row,cancel_at:Date.now()};
        await store.setCancelAt(uid,row.cancel_at,body.reason);
        log('info','renewal-cancelled',{uid,reason:body.reason||'none'});
      }
      plansSeen.delete(uid);
      return send(res,200,{subscription:status(await razor('subscriptions/'+row.sid),row),plan:row.plan,next:nextView(await fetchNext(row),row)});
    }
    if(path==='/cancel-next'){ // drops a scheduled plan before it starts (nothing was charged except the refunded ₹5 check)
      if(!row.next_sid || row.next_sid.startsWith('pending:'))return send(res,409,{error:'There is no scheduled plan to cancel.'});
      const next=await razor('subscriptions/'+row.next_sid);
      if(['created','authenticated'].includes(next.status))await razor('subscriptions/'+row.next_sid+'/cancel','POST',{cancel_at_cycle_end:0});
      else if(!finished(next))throw fail(409,'That plan has already started. Cancel its renewal instead.');
      await store.clearNext(uid,row.next_sid);
      row={...row,...NO_NEXT};
      plansSeen.delete(uid);
      return send(res,200,{subscription:status(await razor('subscriptions/'+row.sid),row),plan:row.plan,next:null});
    }
    return send(res,404,{error:'Not found'});
  } finally {locks.delete(uid);}
}

// Deletes an account: the sign-in (email) and the chat usage record. Payment records stay (orders and the subscription
// id: no personal details, needed for tax law and refunds; Razorpay keeps its own records). A subscription that would
// still renew must be cancelled first, so deleting an account can never leave a live mandate charging someone.
async function deleteAccount(res,uid){
  if(locks.has(uid))return send(res,409,{error:'A billing request is already in progress.'});
  locks.add(uid);
  try{
    const saved=await store.account(uid);
    if(saved){
      if(saved.sid.startsWith('pending:') || saved.next_sid?.startsWith('pending:'))throw fail(409,'An earlier checkout needs support reconciliation. Email us to delete your account.');
      if(!enabled)throw fail(503,'We cannot check your subscription right now, so nothing was deleted. Please try again later.');
      const {row,current,next}=await reconcile(uid,saved,await razor('subscriptions/'+saved.sid),await fetchNext(saved));
      const unpaid=s=>s && ['created','authenticated'].includes(s.status);
      if((!unpaid(current) && renews(current,row)) || (next && !unpaid(next) && renews(next)))
        throw fail(409,'Cancel your subscription renewal first (on this page), then delete your account.',{code:'cancel-first'});
      for(const [s,id] of [[next,row.next_sid],[current,row.sid]])if(unpaid(s))await razor('subscriptions/'+id+'/cancel','POST',{cancel_at_cycle_end:0}); // never charged: stop now
    }
    await store.forget(uid);
    await getAuth().deleteUser(uid);
    plansSeen.delete(uid);
    log('info','account-deleted',{uid});
    return send(res,200,{deleted:true});
  }finally{locks.delete(uid);}
}

async function webhook(req,res){
  const body=await raw(req);
  if(!signature(body,webhookSecret,req.headers['x-razorpay-signature']))return send(res,400,{error:'Invalid signature'});
  const event=parseJson(body), id=req.headers['x-razorpay-event-id'];
  if(typeof id!=='string'||!id||id.length>200)return send(res,400,{error:'Missing event ID'});
  await deliverEvent(id, {
    isDone: eventId=>store.eventDone(eventId),
    complete: eventId=>store.claimEvent(eventId),
    process: async()=>{
      const uid=event?.payload?.subscription?.entity?.notes?.mai_uid;
      if(typeof uid==='string'){plansSeen.delete(uid); if(String(event.event).startsWith('subscription.'))await reconcileUid(uid);}
      const orderId=event?.payload?.order?.entity?.id||event?.payload?.payment?.entity?.order_id;
      if(['order.paid','payment.captured'].includes(event.event)&&typeof orderId==='string'&&/^order_[A-Za-z0-9]+$/.test(orderId)) {
        // Unknown orders may race creation/persistence; retry instead of losing a captured payment.
        const local=await store.order(orderId);
        if(!local || !await settleOrder(orderId))throw fail(503,'Payment reconciliation is pending. Retry this notification.');
      }
      const refunded=event?.payload?.refund?.entity?.payment_id;
      if(String(event.event).startsWith('refund.')&&typeof refunded==='string'&&/^pay_[A-Za-z0-9]+$/.test(refunded))await revokeRefunded(refunded);
    }
  });
  return send(res,200,{received:true});
}

// ---------------------------------------------------------------- HTTP
// Every API route and its rate-limit group (null: exempt). Anything else is refused before sign-in.
const routes={
  'GET /api/health':'read','GET /api/billing/config':'read','GET /api/billing/account':'read','GET /api/chat/usage':'read',
  'POST /api/billing/webhook':null,'POST /api/chat/send':'chat',
  'POST /api/billing/create':'pay','POST /api/billing/create-order':'pay','POST /api/billing/verify':'pay',
  'POST /api/billing/verify-payment':'pay','POST /api/billing/cancel':'pay','POST /api/account/delete':'pay',
  'POST /api/billing/change':'pay','POST /api/billing/cancel-next':'pay',
};
const security={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Frame-Options':'DENY','Referrer-Policy':'no-referrer','Vary':'Origin'};
const within=(promise,ms)=>Promise.race([promise,new Promise((_,no)=>setTimeout(()=>no(Error('timeout')),ms).unref())]);
// The request handler for both hosts: (req,res) are Node's http objects (Express's, inside Firebase Functions).
export async function handle(req,res){
  if(!store)init();
  res.removeHeader('X-Powered-By');
  for(const [k,v] of Object.entries(security))res.setHeader(k,v);
  if(stopping)res.setHeader('Connection','close');
  // CORS: only the site's own origin. Razorpay's server-to-server webhook sends no Origin and is checked by signature.
  if(req.headers.origin===origin)res.setHeader('Access-Control-Allow-Origin',origin);
  let pathname='', uid;
  try {
    try{pathname=new URL(req.url,'http://localhost').pathname;}catch{throw fail(400,'Bad request');}
    const method=req.method==='HEAD'&&pathname==='/api/health'?'GET':req.method; // uptime monitors may use HEAD
    if(req.headers.origin && req.headers.origin!==origin && pathname!=='/api/billing/webhook')throw fail(403,'Origin not allowed');
    if(method==='OPTIONS'){res.writeHead(204,{'Access-Control-Allow-Headers':'Authorization, Content-Type','Access-Control-Allow-Methods':'GET, POST','Access-Control-Max-Age':'600'});return res.end();}
    const route=method+' '+pathname;
    if(!(route in routes)){
      const allow=Object.keys(routes).filter(r=>r.endsWith(' '+pathname)).map(r=>r.split(' ')[0]);
      return allow.length?send(res,405,{error:'Method not allowed'},{Allow:allow.join(', ')}):send(res,404,{error:'Not found'});
    }
    const group=routes[route];
    if(group)limit(group,'ip',clientIp(req.headers,req.socket?.remoteAddress,trustProxy));
    if(pathname==='/api/billing/webhook')return await webhook(req,res);
    if(pathname==='/api/health'){
      let ok=!stopping;
      try{await within(store.ping(),5e3);}catch{ok=false;}
      return send(res,ok?200:503,{ok,mode,checkout:enabled});
    }
    if(pathname==='/api/billing/config')return send(res,200,{enabled,mode,seller:config.seller,usage:config.usage,plans:plans.map(({razorpayPlanId,...p})=>({...p,limits:{session:config.tiers[p.tier].session,week:config.tiers[p.tier].week}}))});
    let body={};
    if(method==='POST'){ // JSON only, at most 32 KB, exactly the fields this route accepts
      if(!/^application\/json\s*(;|$)/i.test(req.headers['content-type']||''))throw fail(415,'Send JSON (Content-Type: application/json).');
      body=parseJson(await raw(req));
      const problem=checkBody(body,bodies[pathname]);
      if(problem)throw fail(400,problem);
    }
    if(pathname.startsWith('/api/chat/')){
      const user=await signedIn(req); uid=user.uid;
      limit(group,'uid',uid);
      return await chat(req,res,pathname.slice(9),user,body);
    }
    if(pathname==='/api/account/delete'){ // works even while checkout is closed
      uid=(await signedIn(req)).uid;
      limit(group,'uid',uid);
      return await deleteAccount(res,uid);
    }
    if(!enabled)throw fail(503,'Checkout is not available right now.');
    uid=(await signedIn(req)).uid;
    limit(group,'uid',uid);
    return await billing(req,res,pathname.slice(12),uid,body);
  } catch(e){
    const known=Number.isInteger(e.http);
    if(!known||e.http>=500)log('error','request',{route:req.method+' '+pathname,status:known?e.http:500,uid,error:known?e.message:e.name,...(known?{}:{detail:String(e.message).slice(0,200)})});
    if(res.headersSent){res.end();return;}
    return send(res,known?e.http:500,known?{error:e.message,...e.extra}:{error:'Something went wrong on our side. Please try again; if a payment was attempted, contact support.'},known?e.headers:{});
  }
}