mohith2309 commited on
Commit
cf67874
·
verified ·
1 Parent(s): a4b81df

Plan switching, resubscribe, honest cancel flow, token-based limits with model weights

Browse files
Files changed (7) hide show
  1. api/access.mjs +10 -0
  2. api/app.mjs +183 -49
  3. api/config.json +40 -17
  4. api/core.mjs +14 -2
  5. api/package.json +1 -1
  6. api/store.mjs +29 -15
  7. spark_server.py +3 -2
api/access.mjs CHANGED
@@ -37,3 +37,13 @@ export function subscriptionPaidUp(sub, now=Date.now()) {
37
  if(!['cancelled','completed','expired'].includes(sub?.status) || !(sub.paid_count>0))return false;
38
  return Math.min(sub.current_end||0, sub.ended_at||Infinity)*1000>now;
39
  }
 
 
 
 
 
 
 
 
 
 
 
37
  if(!['cancelled','completed','expired'].includes(sub?.status) || !(sub.paid_count>0))return false;
38
  return Math.min(sub.current_end||0, sub.ended_at||Infinity)*1000>now;
39
  }
40
+ // Still renews: not finished, and no cancellation scheduled (by Razorpay or recorded by us).
41
+ export function renews(sub, row={}) {
42
+ return Boolean(sub && !['cancelled','completed','expired'].includes(sub.status) && !sub.has_scheduled_changes && !row.cancel_at);
43
+ }
44
+ // When a plan switch or a resubscription starts: the end of the current paid period (Unix seconds). Null when that is
45
+ // under 10 minutes away or already past, so the buyer is asked to wait for the renewal instead of racing it.
46
+ export function successorStart(sub, now=Date.now()) {
47
+ const end=Number(sub?.current_end);
48
+ return Number.isSafeInteger(end) && end*1000-now>10*60e3 ? end : null;
49
+ }
api/app.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {cachedAccess,deliverEvent,capturedPayment,refundRevokes,subscriptionPaidUp} from './access.mjs';
2
  // m.ai API: subscriptions (Razorpay) and chat (Spark), behind Firebase sign-in.
3
  // Every paid action is decided here, never in the browser: the plan is read from Razorpay,
4
  // and chat usage limits are counted in Firestore. One handler, two hosts:
@@ -7,7 +7,7 @@ import {readFileSync} from 'node:fs';
7
  import {randomUUID} from 'node:crypto';
8
  import {fileURLToPath} from 'node:url';
9
  import {dirname,join} from 'node:path';
10
- import {signature,ready,keyMode,planId,checkedPlan,verifyPlan,publicStatus,limiter,clientIp,parseJson,bodies,checkBody,reusableOrder,reuseDecision} from './core.mjs';
11
  import {storage} from './store.mjs';
12
  import {initializeApp,applicationDefault,cert,getApps} from 'firebase-admin/app';
13
  import {getAuth} from 'firebase-admin/auth';
@@ -16,7 +16,7 @@ const root=dirname(fileURLToPath(import.meta.url));
16
  const config=JSON.parse(readFileSync(join(root,'config.json')));
17
  const SESSION=config.usage.sessionHours*3600e3, WEEK=config.usage.weekDays*86400e3, BODY_LIMIT=32768;
18
  const MODEL_TIMEOUT=50e3; // Firebase Hosting ends a rewritten request at 60 s, so a reply must finish before that
19
- let key,secret,webhookSecret,origin,modelUrl,trustProxy,mode,live,enabled,plans,store,stopping=false;
20
 
21
  // Reads keys and settings once per process: from Functions secrets and params (index.mjs) or the shell (server.mjs).
22
  export function init(env=process.env){
@@ -25,6 +25,8 @@ export function init(env=process.env){
25
  modelUrl=env.MAI_MODEL_URL || ''; // Spark's chat endpoint; empty: chat answers that Spark is offline
26
  trustProxy=env.TRUST_PROXY==='yes'; // set behind Firebase Hosting / Cloud Run / any reverse proxy
27
  mode=keyMode(key); live=mode==='live';
 
 
28
  // Live keys need deliveryReady (config.json) AND ALLOW_LIVE_PAYMENTS=yes; test keys need deliveryReady or ALLOW_TEST_CHECKOUT=yes.
29
  enabled=Boolean(mode && secret && webhookSecret && ready(config,{live,allowTest:env.ALLOW_TEST_CHECKOUT==='yes'}) && (!live || env.ALLOW_LIVE_PAYMENTS==='yes'));
30
  plans=config.plans.filter(p=>planId(p,mode));
@@ -63,7 +65,7 @@ async function razor(path,method='GET',body) {
63
  const what={method,resource:path.split('/')[0]};
64
  let r,data;
65
  try{
66
- r=await fetch('https://api.razorpay.com/v1/'+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});
67
  data=await r.json();
68
  }catch(e){
69
  const slow=['TimeoutError','AbortError'].includes(e.name);
@@ -121,6 +123,10 @@ async function entitlement(uid,fresh=false){
121
  const paidUp=subscriptionPaidUp(sub);
122
  const plan=config.plans.find(p=>p.id===row.plan);
123
  if(paidUp && plan)value={tier:plan.tier,plan:plan.id};
 
 
 
 
124
  }
125
  const pass=await store.pass(uid);
126
  if(!value && pass)value={tier:config.plans.find(p=>p.id===pass.plan).tier,plan:pass.plan,until:pass.ends};
@@ -164,11 +170,14 @@ async function revokeRefunded(paymentId){
164
  plansSeen.delete(local.uid);
165
  }
166
 
 
167
  function usageView(tier,{session:s,week:w}){
168
  const t=config.tiers[tier];
169
- return {plan:{tier,name:t.name},limits:{session:t.session,week:t.week},used:{session:s.count,week:w.count},
170
  resets:{session:s.start?Math.round((s.start+SESSION)/1000):null,week:w.start?Math.round((w.start+WEEK)/1000):null}};
171
  }
 
 
172
  function cleanMessages(list){
173
  if(!Array.isArray(list)||!list.length||list.length>12)throw fail(400,'Send between 1 and 12 messages.');
174
  let total=0;
@@ -189,27 +198,27 @@ async function chat(req,res,path,user,body){
189
  if(!ent)throw fail(402,'Chat with Spark comes with an m.ai plan.',{code:'no-plan'});
190
  if(path==='/usage')return send(res,200,usageView(ent.tier,await store.usage(uid)));
191
  const messages=cleanMessages(body.messages);
192
- if(!modelUrl)throw fail(503,'Spark is offline right now. Your message was not counted. Try again soon.');
 
 
193
  if(chatting.has(uid))throw fail(409,'Spark is still answering your last message.');
194
  chatting.add(uid);
195
  try{
196
- // Count the message before asking the model (checked and counted in one transaction); refund it on failure.
197
- const t=config.tiers[ent.tier], took=await store.take(uid,{session:t.session,week:t.week});
198
- if(!took.ok){
199
- const u=usageView(ent.tier,took);
200
- if(u.used.session>=u.limits.session)throw fail(429,`You've used this session's ${u.limits.session} messages. They reset at ${new Date(u.resets.session*1000).toLocaleTimeString('en-IN',{hour:'numeric',minute:'2-digit',timeZone:'Asia/Kolkata'})}.`,{usage:u});
201
- throw fail(429,`You've used this week's ${u.limits.week} messages. They reset on ${new Date(u.resets.week*1000).toLocaleDateString('en-IN',{weekday:'long',day:'numeric',month:'long',timeZone:'Asia/Kolkata'})}.`,{usage:u});
202
- }
203
- const refund=()=>store.refund(uid).catch(e=>log('error','refund',{uid,error:e.name}));
204
  const stop=new AbortController();
205
  res.on('close',()=>stop.abort());
206
  let upstream;
207
  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})});}
208
- catch{await refund();throw fail(503,'Spark is offline right now. Your message was not counted. Try again soon.');}
209
- if(!upstream.ok){await refund();const busy=upstream.status===429;throw fail(503,busy?'Spark is busy with another reply. Your message was not counted; try again in a moment.':'Spark could not answer right now. Your message was not counted.');}
210
  res.writeHead(200,{'Content-Type':'text/event-stream'});
211
  const reader=upstream.body.getReader(), decoder=new TextDecoder();
212
- let buffer='', produced=false, ok=true;
213
  try{
214
  for(;;){
215
  const {value,done}=await reader.read();
@@ -220,39 +229,129 @@ async function chat(req,res,path,user,body){
220
  const line=buffer.slice(0,cut).replace(/^data: /,''); buffer=buffer.slice(cut+2);
221
  if(!line)continue;
222
  let event; try{event=JSON.parse(line);}catch{continue;}
223
- if(event.t){produced=true;res.write('data: '+JSON.stringify({t:event.t})+'\n\n');}
224
  if(event.error){ok=false;}
225
- if(event.done&&event.unavailable)ok=false;
226
  }
227
  }
228
- }catch(e){ // the model stopped mid-reply or the reader left: nothing shown means nothing counted
229
- if(!produced)await refund();
230
  if(stop.signal.aborted)return res.end();
231
  throw e;
232
  }
233
- if(!ok||!produced){await refund();res.write('data: '+JSON.stringify({error:'Spark could not answer that. Your message was not counted.'})+'\n\n');}
 
234
  res.end('data: '+JSON.stringify({done:true,usage:usageView(ent.tier,await store.usage(uid))})+'\n\n');
235
  }finally{chatting.delete(uid);}
236
  }
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  // ---------------------------------------------------------------- billing routes (signed in, checkout enabled)
239
  async function billing(req,res,path,uid,body){
240
  if(locks.has(uid))return send(res,409,{error:'A billing request is already in progress.'});
241
  locks.add(uid);
242
  try {
243
- const row=await store.account(uid);
244
  if(path==='/account'){
245
  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);
246
  const pass=await store.pass(uid);
247
- if(!row)return send(res,200,{subscription:null,pass:pass?passView(pass):null,queuedPasses});
248
- if(row.sid.startsWith('pending:'))return send(res,409,{error:'An earlier checkout needs support reconciliation. Do not start another payment.'});
249
- return send(res,200,{subscription:status(await razor('subscriptions/'+row.sid),row),plan:row.plan,pass:pass?passView(pass):null,queuedPasses});
 
 
250
  }
251
  if(path==='/create-order'){ // Razorpay Standard Checkout: one-time payment for one month or one year of a plan
252
  const plan=config.plans.find(p=>p.id===body.plan);
253
  if(!plan||!Number.isSafeInteger(plan.amountPaise)||plan.amountPaise<100)throw fail(400,'Choose a plan.');
254
- if(row && !row.sid.startsWith('pending:') && ['active','pending','authenticated'].includes((await razor('subscriptions/'+row.sid)).status))
 
 
255
  throw fail(409,'You already have an active subscription. Manage it from Account.');
 
256
  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}});
257
  // A double click or a retry within 15 minutes gets the same unpaid order back, never a second payable one.
258
  const earlier=reusableOrder(await store.ordersOf(uid),{uid,plan:plan.id,amount:plan.amountPaise,now:Date.now()});
@@ -286,15 +385,20 @@ async function billing(req,res,path,uid,body){
286
  const paidUntil=Math.max(0,...(await store.ordersOf(uid)).filter(o=>o.status==='paid'&&o.ends>Date.now()).map(o=>o.ends));
287
  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'});
288
  if(row){
289
- if(row.sid.startsWith('pending:'))throw fail(409,'An earlier checkout needs support reconciliation. Do not start another payment.');
290
- const existing=await razor('subscriptions/'+row.sid);
 
 
 
 
291
  if(['created','authenticated'].includes(existing.status) && row.plan===plan.id)return send(res,200,{keyId:key,subscriptionId:row.sid});
292
- // An unpaid checkout for a different plan is replaced; a paid period must end before a new purchase.
 
293
  if(existing.status==='created')await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:0});
294
- else if(!finished(existing) || subscriptionPaidUp(existing))throw fail(409,'You already have a subscription or paid period. Manage it from Account.');
 
295
  }
296
- const remotePlan=await razor('plans/'+plan.razorpayPlanId);
297
- try{verifyPlan(plan,remotePlan);}catch{log('error','plan-mismatch',{plan:plan.id});throw fail(503,'This plan is temporarily unavailable. Please contact support.');}
298
  const pending='pending:'+randomUUID();
299
  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.');
300
  // If the request times out or Razorpay fails on its side, keep pending: a subscription may exist, and a retry
@@ -306,23 +410,50 @@ async function billing(req,res,path,uid,body){
306
  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.');}
307
  return send(res,200,{keyId:key,subscriptionId:sub.id});
308
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  if(!row || row.sid.startsWith('pending:'))return send(res,409,{error:'No subscription ready to manage.'});
310
- if(path==='/verify'){
311
- if(body.razorpay_subscription_id!==row.sid || !signature(body.razorpay_payment_id+'|'+row.sid,secret,body.razorpay_signature))return send(res,400,{error:'Payment verification failed.'});
312
- plansSeen.delete(uid);
313
- const sub=await razor('subscriptions/'+row.sid);
314
- return send(res,200,{verified:true,subscription:status(sub,row)});
 
 
315
  }
316
  if(path==='/cancel'){
317
  const sub=await razor('subscriptions/'+row.sid);
318
- if(!finished(sub) && !row.cancel_at && !sub.has_scheduled_changes){
319
  // Active plans end at the close of the paid period; unpaid (created/authenticated) ones stop now.
320
  await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:sub.status==='active'?1:0});
321
- row.cancel_at=Date.now();
322
- await store.setCancelAt(uid,row.cancel_at);
 
323
  }
324
  plansSeen.delete(uid);
325
- return send(res,200,{subscription:status(await razor('subscriptions/'+row.sid),row)});
 
 
 
 
 
 
 
 
 
 
326
  }
327
  return send(res,404,{error:'Not found'});
328
  } finally {locks.delete(uid);}
@@ -335,13 +466,15 @@ async function deleteAccount(res,uid){
335
  if(locks.has(uid))return send(res,409,{error:'A billing request is already in progress.'});
336
  locks.add(uid);
337
  try{
338
- const row=await store.account(uid);
339
- if(row){
340
- if(row.sid.startsWith('pending:'))throw fail(409,'An earlier checkout needs support reconciliation. Email us to delete your account.');
341
  if(!enabled)throw fail(503,'We cannot check your subscription right now, so nothing was deleted. Please try again later.');
342
- const sub=await razor('subscriptions/'+row.sid);
343
- if(['created','authenticated'].includes(sub.status))await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:0}); // never charged: stop it now
344
- else if(!finished(sub)&&!sub.has_scheduled_changes&&!row.cancel_at)throw fail(409,'Cancel your subscription renewal first (on this page), then delete your account.',{code:'cancel-first'});
 
 
345
  }
346
  await store.forget(uid);
347
  await getAuth().deleteUser(uid);
@@ -361,7 +494,7 @@ async function webhook(req,res){
361
  complete: eventId=>store.claimEvent(eventId),
362
  process: async()=>{
363
  const uid=event?.payload?.subscription?.entity?.notes?.mai_uid;
364
- if(typeof uid==='string')plansSeen.delete(uid);
365
  const orderId=event?.payload?.order?.entity?.id||event?.payload?.payment?.entity?.order_id;
366
  if(['order.paid','payment.captured'].includes(event.event)&&typeof orderId==='string'&&/^order_[A-Za-z0-9]+$/.test(orderId)) {
367
  // Unknown orders may race creation/persistence; retry instead of losing a captured payment.
@@ -382,6 +515,7 @@ const routes={
382
  'POST /api/billing/webhook':null,'POST /api/chat/send':'chat',
383
  'POST /api/billing/create':'pay','POST /api/billing/create-order':'pay','POST /api/billing/verify':'pay',
384
  'POST /api/billing/verify-payment':'pay','POST /api/billing/cancel':'pay','POST /api/account/delete':'pay',
 
385
  };
386
  const security={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Frame-Options':'DENY','Referrer-Policy':'no-referrer','Vary':'Origin'};
387
  const within=(promise,ms)=>Promise.race([promise,new Promise((_,no)=>setTimeout(()=>no(Error('timeout')),ms).unref())]);
 
1
+ import {cachedAccess,deliverEvent,capturedPayment,refundRevokes,subscriptionPaidUp,renews,successorStart} from './access.mjs';
2
  // m.ai API: subscriptions (Razorpay) and chat (Spark), behind Firebase sign-in.
3
  // Every paid action is decided here, never in the browser: the plan is read from Razorpay,
4
  // and chat usage limits are counted in Firestore. One handler, two hosts:
 
7
  import {randomUUID} from 'node:crypto';
8
  import {fileURLToPath} from 'node:url';
9
  import {dirname,join} from 'node:path';
10
+ import {signature,ready,keyMode,planId,checkedPlan,verifyPlan,publicStatus,limiter,clientIp,parseJson,bodies,checkBody,reusableOrder,reuseDecision,estimateTokens,replyCost} from './core.mjs';
11
  import {storage} from './store.mjs';
12
  import {initializeApp,applicationDefault,cert,getApps} from 'firebase-admin/app';
13
  import {getAuth} from 'firebase-admin/auth';
 
16
  const config=JSON.parse(readFileSync(join(root,'config.json')));
17
  const SESSION=config.usage.sessionHours*3600e3, WEEK=config.usage.weekDays*86400e3, BODY_LIMIT=32768;
18
  const MODEL_TIMEOUT=50e3; // Firebase Hosting ends a rewritten request at 60 s, so a reply must finish before that
19
+ let key,secret,webhookSecret,origin,modelUrl,trustProxy,mode,live,enabled,plans,store,rzp='https://api.razorpay.com/v1/',stopping=false;
20
 
21
  // Reads keys and settings once per process: from Functions secrets and params (index.mjs) or the shell (server.mjs).
22
  export function init(env=process.env){
 
25
  modelUrl=env.MAI_MODEL_URL || ''; // Spark's chat endpoint; empty: chat answers that Spark is offline
26
  trustProxy=env.TRUST_PROXY==='yes'; // set behind Firebase Hosting / Cloud Run / any reverse proxy
27
  mode=keyMode(key); live=mode==='live';
28
+ // Local UI tests only: a stand-in Razorpay on this machine. Ignored unless the key is a test key and the address is local.
29
+ if(mode==='test' && /^http:\/\/127\.0\.0\.1:\d+\/v1\/$/.test(env.RAZORPAY_API_BASE||''))rzp=env.RAZORPAY_API_BASE;
30
  // Live keys need deliveryReady (config.json) AND ALLOW_LIVE_PAYMENTS=yes; test keys need deliveryReady or ALLOW_TEST_CHECKOUT=yes.
31
  enabled=Boolean(mode && secret && webhookSecret && ready(config,{live,allowTest:env.ALLOW_TEST_CHECKOUT==='yes'}) && (!live || env.ALLOW_LIVE_PAYMENTS==='yes'));
32
  plans=config.plans.filter(p=>planId(p,mode));
 
65
  const what={method,resource:path.split('/')[0]};
66
  let r,data;
67
  try{
68
+ 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});
69
  data=await r.json();
70
  }catch(e){
71
  const slow=['TimeoutError','AbortError'].includes(e.name);
 
123
  const paidUp=subscriptionPaidUp(sub);
124
  const plan=config.plans.find(p=>p.id===row.plan);
125
  if(paidUp && plan)value={tier:plan.tier,plan:plan.id};
126
+ if(!value && row.next_sid && !row.next_sid.startsWith('pending:')){ // a switch or resubscription that has started
127
+ const nextPlan=config.plans.find(p=>p.id===row.next_plan);
128
+ if(nextPlan && subscriptionPaidUp(await razor('subscriptions/'+row.next_sid)))value={tier:nextPlan.tier,plan:nextPlan.id};
129
+ }
130
  }
131
  const pass=await store.pass(uid);
132
  if(!value && pass)value={tier:config.plans.find(p=>p.id===pass.plan).tier,plan:pass.plan,until:pass.ends};
 
170
  plansSeen.delete(local.uid);
171
  }
172
 
173
+ // Limits and use are in tokens (see replyCost). The page shows them as a share of each window.
174
  function usageView(tier,{session:s,week:w}){
175
  const t=config.tiers[tier];
176
+ return {plan:{tier,name:t.name},unit:'tokens',limits:{session:t.session,week:t.week},used:{session:s.count,week:w.count},
177
  resets:{session:s.start?Math.round((s.start+SESSION)/1000):null,week:w.start?Math.round((w.start+WEEK)/1000):null}};
178
  }
179
+ const at=sec=>new Date(sec*1000).toLocaleTimeString('en-IN',{hour:'numeric',minute:'2-digit',timeZone:'Asia/Kolkata'});
180
+ const onDay=sec=>new Date(sec*1000).toLocaleDateString('en-IN',{weekday:'long',day:'numeric',month:'long',timeZone:'Asia/Kolkata'});
181
  function cleanMessages(list){
182
  if(!Array.isArray(list)||!list.length||list.length>12)throw fail(400,'Send between 1 and 12 messages.');
183
  let total=0;
 
198
  if(!ent)throw fail(402,'Chat with Spark comes with an m.ai plan.',{code:'no-plan'});
199
  if(path==='/usage')return send(res,200,usageView(ent.tier,await store.usage(uid)));
200
  const messages=cleanMessages(body.messages);
201
+ const model=config.models[body.model||'spark'];
202
+ if(!model?.available)throw fail(400,'That model is not available yet.');
203
+ if(!modelUrl)throw fail(503,'Spark is offline right now. Nothing was counted. Try again soon.');
204
  if(chatting.has(uid))throw fail(409,'Spark is still answering your last message.');
205
  chatting.add(uid);
206
  try{
207
+ // Limits are checked before the reply and the reply's tokens charged after it, so a failed reply costs nothing.
208
+ const t=config.tiers[ent.tier], u=usageView(ent.tier,await store.usage(uid));
209
+ 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});
210
+ 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});
211
+ const sent=messages.map(m=>m.content).join('\n');
212
+ const charge=(promptTokens,outputTokens)=>store.charge(uid,replyCost(model.weight,promptTokens,outputTokens)).catch(e=>log('error','charge',{uid,error:e.name}));
 
 
213
  const stop=new AbortController();
214
  res.on('close',()=>stop.abort());
215
  let upstream;
216
  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})});}
217
+ catch{throw fail(503,'Spark is offline right now. Nothing was counted. Try again soon.');}
218
+ 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.');}
219
  res.writeHead(200,{'Content-Type':'text/event-stream'});
220
  const reader=upstream.body.getReader(), decoder=new TextDecoder();
221
+ let buffer='', produced='', ok=true, promptTokens=null, outputTokens=null;
222
  try{
223
  for(;;){
224
  const {value,done}=await reader.read();
 
229
  const line=buffer.slice(0,cut).replace(/^data: /,''); buffer=buffer.slice(cut+2);
230
  if(!line)continue;
231
  let event; try{event=JSON.parse(line);}catch{continue;}
232
+ if(typeof event.t==='string'&&event.t){produced+=event.t;res.write('data: '+JSON.stringify({t:event.t})+'\n\n');}
233
  if(event.error){ok=false;}
234
+ if(event.done){if(event.unavailable)ok=false; promptTokens=event.prompt_tokens; outputTokens=event.tokens;}
235
  }
236
  }
237
+ }catch(e){ // the model stopped mid-reply or the reader left: only what was shown is charged
238
+ if(produced)await charge(promptTokens??estimateTokens(sent)+40,estimateTokens(produced));
239
  if(stop.signal.aborted)return res.end();
240
  throw e;
241
  }
242
+ if(!ok||!produced){res.write('data: '+JSON.stringify({error:'Spark could not answer that. Nothing was counted.'})+'\n\n');}
243
+ else await charge(promptTokens??estimateTokens(sent)+40,outputTokens??estimateTokens(produced));
244
  res.end('data: '+JSON.stringify({done:true,usage:usageView(ent.tier,await store.usage(uid))})+'\n\n');
245
  }finally{chatting.delete(uid);}
246
  }
247
 
248
+ // ---------------------------------------------------------------- plan switches and resubscribing
249
+ // Razorpay cannot resume a cancelled subscription, and UPI AutoPay / e-mandate subscriptions cannot change plan in place.
250
+ // So both work one way for every payment method: a "next" subscription starts the day the current paid period ends
251
+ // (Razorpay checks the payment method with ₹5 now and refunds it). The current one stops renewing only once the next one
252
+ // is authorised, so nobody pays twice for a period and nobody loses paid days.
253
+ const RECONCILE='An earlier checkout needs support reconciliation. Do not start another payment.';
254
+ const NO_NEXT={next_sid:null,next_plan:null,next_start:null,next_kind:null};
255
+ const day=sec=>new Date(sec*1000).toLocaleDateString('en-IN',{day:'numeric',month:'long',year:'numeric',timeZone:'Asia/Kolkata'});
256
+ const fetchNext=row=>row.next_sid&&!row.next_sid.startsWith('pending:')?razor('subscriptions/'+row.next_sid):null;
257
+ 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;
258
+
259
+ // Brings the account in line with Razorpay before anything is shown or changed. Returns {row,current,next,problem}.
260
+ async function reconcile(uid,row,current,next){
261
+ let problem='';
262
+ if(next && finished(next) && !subscriptionPaidUp(next)){ // a next plan that ended before it began (cancelled or abandoned)
263
+ await store.clearNext(uid,row.next_sid); row={...row,...NO_NEXT}; next=null;
264
+ }
265
+ if(next && ['authenticated','active','pending'].includes(next.status) && renews(current,row)){
266
+ // The next plan is authorised: the current one now stops renewing at the end of its paid period.
267
+ let stopped=false;
268
+ try{await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:current.status==='active'?1:0});stopped=true;}
269
+ catch(e){log('error','plan-switch-cancel',{uid,error:String(e.message).slice(0,120)});}
270
+ if(stopped){
271
+ const at=Date.now(); await store.setCancelAt(uid,at); row={...row,cancel_at:at};
272
+ log('info','plan-switch',{uid,from:row.sid,to:row.next_sid});
273
+ current=await razor('subscriptions/'+row.sid);
274
+ }else{
275
+ // The old plan would keep renewing beside the new one: cancel the new one instead, so nobody pays twice.
276
+ try{
277
+ await razor('subscriptions/'+row.next_sid+'/cancel','POST',{cancel_at_cycle_end:0});
278
+ await store.clearNext(uid,row.next_sid); row={...row,...NO_NEXT}; next=null;
279
+ problem='We could not switch your plan, so nothing changed and nothing extra was charged. Please try again in a few minutes.';
280
+ }catch{
281
+ log('error','plan-switch-stuck',{uid,current:row.sid,next:row.next_sid});
282
+ problem='Your plan change needs a quick check from us. You will not be charged twice; we will email you.';
283
+ }
284
+ }
285
+ }
286
+ if(next && finished(current) && !subscriptionPaidUp(current) && ['authenticated','active','pending'].includes(next.status)){
287
+ // The current period is over and the next subscription has taken over.
288
+ if(await store.promote(uid,row.sid,row.next_sid)){
289
+ log('info','plan-promoted',{uid,from:row.sid,to:row.next_sid});
290
+ row={...row,sid:row.next_sid,plan:row.next_plan,cancel_at:null,...NO_NEXT}; current=next; next=null;
291
+ }
292
+ }
293
+ plansSeen.delete(uid);
294
+ return {row,current,next,problem};
295
+ }
296
+ // Webhook path: only accounts with a next subscription need anything done.
297
+ async function reconcileUid(uid){
298
+ const row=await store.account(uid);
299
+ if(!row || !row.next_sid || row.sid.startsWith('pending:') || row.next_sid.startsWith('pending:'))return;
300
+ if(locks.has(uid))throw fail(503,'Account busy; retry this notification.');
301
+ locks.add(uid);
302
+ try{await reconcile(uid,row,await razor('subscriptions/'+row.sid),await razor('subscriptions/'+row.next_sid));}
303
+ finally{locks.delete(uid);}
304
+ }
305
+ // A next plan whose checkout was never finished: the same plan picks it up again (returns the reply); another plan
306
+ // replaces it (returns null after cancelling it). A next plan already authorised must be cancelled by the buyer first.
307
+ async function reuseNext(uid,row,next,plan){
308
+ if(next.status==='created' && row.next_plan===plan.id)return {keyId:key,subscriptionId:row.next_sid,startsAt:row.next_start,next:true};
309
+ 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'});
310
+ await razor('subscriptions/'+row.next_sid+'/cancel','POST',{cancel_at_cycle_end:0});
311
+ await store.clearNext(uid,row.next_sid);
312
+ return null;
313
+ }
314
+ async function verifiedPlan(plan){
315
+ const remote=await razor('plans/'+plan.razorpayPlanId);
316
+ try{verifyPlan(plan,remote);}catch{log('error','plan-mismatch',{plan:plan.id});throw fail(503,'This plan is temporarily unavailable. Please contact support.');}
317
+ }
318
+ // Creates the next subscription, starting when the current paid period ends.
319
+ async function createNext(res,uid,row,plan,current,kind){
320
+ const startAt=successorStart(current);
321
+ 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'});
322
+ const pending='pending:'+randomUUID();
323
+ 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.');
324
+ let sub;
325
+ 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}});}
326
+ catch(e){if(e.rejected)await store.clearNext(uid,pending);throw e;}
327
+ if(!/^sub_[A-Za-z0-9]+$/.test(sub.id))throw fail(502,'Unexpected provider response; contact support.');
328
+ 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);}
329
+ return send(res,200,{keyId:key,subscriptionId:sub.id,startsAt:startAt,next:true});
330
+ }
331
+
332
  // ---------------------------------------------------------------- billing routes (signed in, checkout enabled)
333
  async function billing(req,res,path,uid,body){
334
  if(locks.has(uid))return send(res,409,{error:'A billing request is already in progress.'});
335
  locks.add(uid);
336
  try {
337
+ let row=await store.account(uid);
338
  if(path==='/account'){
339
  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);
340
  const pass=await store.pass(uid);
341
+ if(!row)return send(res,200,{subscription:null,next:null,pass:pass?passView(pass):null,queuedPasses});
342
+ if(row.sid.startsWith('pending:'))return send(res,409,{error:RECONCILE});
343
+ const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
344
+ 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:')),
345
+ problem:r.problem||null,pass:pass?passView(pass):null,queuedPasses});
346
  }
347
  if(path==='/create-order'){ // Razorpay Standard Checkout: one-time payment for one month or one year of a plan
348
  const plan=config.plans.find(p=>p.id===body.plan);
349
  if(!plan||!Number.isSafeInteger(plan.amountPaise)||plan.amountPaise<100)throw fail(400,'Choose a plan.');
350
+ // A subscription that is live, or a next one that has started or is scheduled, already covers this time.
351
+ const live=s=>s && ['active','pending','authenticated'].includes(s.status);
352
+ if(row && !row.sid.startsWith('pending:') && (live(await razor('subscriptions/'+row.sid)) || live(await fetchNext(row))))
353
  throw fail(409,'You already have an active subscription. Manage it from Account.');
354
+ if(row?.next_sid?.startsWith('pending:'))throw fail(409,RECONCILE);
355
  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}});
356
  // A double click or a retry within 15 minutes gets the same unpaid order back, never a second payable one.
357
  const earlier=reusableOrder(await store.ordersOf(uid),{uid,plan:plan.id,amount:plan.amountPaise,now:Date.now()});
 
385
  const paidUntil=Math.max(0,...(await store.ordersOf(uid)).filter(o=>o.status==='paid'&&o.ends>Date.now()).map(o=>o.ends));
386
  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'});
387
  if(row){
388
+ if(row.sid.startsWith('pending:') || row.next_sid?.startsWith('pending:'))throw fail(409,RECONCILE);
389
+ const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
390
+ if(r.problem)throw fail(409,r.problem);
391
+ row=r.row;
392
+ const existing=r.current;
393
+ if(r.next){const again=await reuseNext(uid,row,r.next,plan); if(again)return send(res,200,again); row={...row,...NO_NEXT};}
394
  if(['created','authenticated'].includes(existing.status) && row.plan===plan.id)return send(res,200,{keyId:key,subscriptionId:row.sid});
395
+ // An unpaid checkout for a different plan is replaced. A renewing plan is switched with Change plan. With renewal
396
+ // off and paid time left, subscribing again starts the day that time ends (no paying twice, no lost days).
397
  if(existing.status==='created')await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:0});
398
+ 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'});
399
+ else if(subscriptionPaidUp(existing)){await verifiedPlan(plan); return await createNext(res,uid,row,plan,existing,'resubscribe');}
400
  }
401
+ await verifiedPlan(plan);
 
402
  const pending='pending:'+randomUUID();
403
  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.');
404
  // If the request times out or Razorpay fails on its side, keep pending: a subscription may exist, and a retry
 
410
  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.');}
411
  return send(res,200,{keyId:key,subscriptionId:sub.id});
412
  }
413
+ if(path==='/change'){ // switch plans from the next billing period: the new plan starts when the paid period ends
414
+ let plan;
415
+ try{plan=checkedPlan(config,body.plan,mode);}catch{throw fail(400,'Choose a plan.');}
416
+ if(!row)throw fail(409,'You have no subscription to change. Choose a plan to subscribe.');
417
+ if(row.sid.startsWith('pending:') || row.next_sid?.startsWith('pending:'))throw fail(409,RECONCILE);
418
+ const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
419
+ if(r.problem)throw fail(409,r.problem);
420
+ row=r.row;
421
+ if(r.next){const again=await reuseNext(uid,row,r.next,plan); if(again)return send(res,200,again); row={...row,...NO_NEXT};}
422
+ 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'});
423
+ if(plan.id===row.plan)throw fail(400,'That is already your plan.');
424
+ await verifiedPlan(plan);
425
+ return await createNext(res,uid,row,plan,r.current,'switch');
426
+ }
427
  if(!row || row.sid.startsWith('pending:'))return send(res,409,{error:'No subscription ready to manage.'});
428
+ if(path==='/verify'){ // the current subscription's checkout, or the next one's (switch or resubscribe)
429
+ const id=body.razorpay_subscription_id;
430
+ const target=id===row.sid ? row.sid : row.next_sid && !row.next_sid.startsWith('pending:') && id===row.next_sid ? row.next_sid : null;
431
+ if(!target || !signature(body.razorpay_payment_id+'|'+target,secret,body.razorpay_signature))return send(res,400,{error:'Payment verification failed.'});
432
+ const r=await reconcile(uid,row,await razor('subscriptions/'+row.sid),await fetchNext(row));
433
+ if(r.problem)throw fail(409,r.problem);
434
+ return send(res,200,{verified:true,subscription:status(r.current,r.row),plan:r.row.plan,next:nextView(r.next,r.row)});
435
  }
436
  if(path==='/cancel'){
437
  const sub=await razor('subscriptions/'+row.sid);
438
+ if(renews(sub,row)){
439
  // Active plans end at the close of the paid period; unpaid (created/authenticated) ones stop now.
440
  await razor('subscriptions/'+row.sid+'/cancel','POST',{cancel_at_cycle_end:sub.status==='active'?1:0});
441
+ row={...row,cancel_at:Date.now()};
442
+ await store.setCancelAt(uid,row.cancel_at,body.reason);
443
+ log('info','renewal-cancelled',{uid,reason:body.reason||'none'});
444
  }
445
  plansSeen.delete(uid);
446
+ return send(res,200,{subscription:status(await razor('subscriptions/'+row.sid),row),plan:row.plan,next:nextView(await fetchNext(row),row)});
447
+ }
448
+ if(path==='/cancel-next'){ // drops a scheduled plan before it starts (nothing was charged except the refunded ₹5 check)
449
+ if(!row.next_sid || row.next_sid.startsWith('pending:'))return send(res,409,{error:'There is no scheduled plan to cancel.'});
450
+ const next=await razor('subscriptions/'+row.next_sid);
451
+ if(['created','authenticated'].includes(next.status))await razor('subscriptions/'+row.next_sid+'/cancel','POST',{cancel_at_cycle_end:0});
452
+ else if(!finished(next))throw fail(409,'That plan has already started. Cancel its renewal instead.');
453
+ await store.clearNext(uid,row.next_sid);
454
+ row={...row,...NO_NEXT};
455
+ plansSeen.delete(uid);
456
+ return send(res,200,{subscription:status(await razor('subscriptions/'+row.sid),row),plan:row.plan,next:null});
457
  }
458
  return send(res,404,{error:'Not found'});
459
  } finally {locks.delete(uid);}
 
466
  if(locks.has(uid))return send(res,409,{error:'A billing request is already in progress.'});
467
  locks.add(uid);
468
  try{
469
+ const saved=await store.account(uid);
470
+ if(saved){
471
+ 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.');
472
  if(!enabled)throw fail(503,'We cannot check your subscription right now, so nothing was deleted. Please try again later.');
473
+ const {row,current,next}=await reconcile(uid,saved,await razor('subscriptions/'+saved.sid),await fetchNext(saved));
474
+ const unpaid=s=>s && ['created','authenticated'].includes(s.status);
475
+ if((!unpaid(current) && renews(current,row)) || (next && !unpaid(next) && renews(next)))
476
+ throw fail(409,'Cancel your subscription renewal first (on this page), then delete your account.',{code:'cancel-first'});
477
+ 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
478
  }
479
  await store.forget(uid);
480
  await getAuth().deleteUser(uid);
 
494
  complete: eventId=>store.claimEvent(eventId),
495
  process: async()=>{
496
  const uid=event?.payload?.subscription?.entity?.notes?.mai_uid;
497
+ if(typeof uid==='string'){plansSeen.delete(uid); if(String(event.event).startsWith('subscription.'))await reconcileUid(uid);}
498
  const orderId=event?.payload?.order?.entity?.id||event?.payload?.payment?.entity?.order_id;
499
  if(['order.paid','payment.captured'].includes(event.event)&&typeof orderId==='string'&&/^order_[A-Za-z0-9]+$/.test(orderId)) {
500
  // Unknown orders may race creation/persistence; retry instead of losing a captured payment.
 
515
  'POST /api/billing/webhook':null,'POST /api/chat/send':'chat',
516
  'POST /api/billing/create':'pay','POST /api/billing/create-order':'pay','POST /api/billing/verify':'pay',
517
  'POST /api/billing/verify-payment':'pay','POST /api/billing/cancel':'pay','POST /api/account/delete':'pay',
518
+ 'POST /api/billing/change':'pay','POST /api/billing/cancel-next':'pay',
519
  };
520
  const security={'Cache-Control':'no-store','X-Content-Type-Options':'nosniff','X-Frame-Options':'DENY','Referrer-Policy':'no-referrer','Vary':'Origin'};
521
  const within=(promise,ms)=>Promise.race([promise,new Promise((_,no)=>setTimeout(()=>no(Error('timeout')),ms).unref())]);
api/config.json CHANGED
@@ -30,7 +30,7 @@
30
  "features": [
31
  "Supporter badge on your m.ai account",
32
  "Early tester: first access to Spark chat (research preview)",
33
- "When chat opens: 15 messages per 5-hour session, 100 a week",
34
  "Your support funds m.ai’s own models"
35
  ]
36
  },
@@ -48,7 +48,7 @@
48
  "features": [
49
  "Supporter badge on your m.ai account",
50
  "Early tester: first access to Spark chat (research preview)",
51
- "When chat opens: 15 messages per 5-hour session, 100 a week",
52
  "Your support funds m.ai’s own models"
53
  ]
54
  },
@@ -66,7 +66,7 @@
66
  "features": [
67
  "Pro supporter badge",
68
  "Everything in Plus",
69
- "When chat opens: 5× Plus usage (75 per session, 500 a week)",
70
  "Feedback goes straight to the team"
71
  ]
72
  },
@@ -84,7 +84,7 @@
84
  "features": [
85
  "Pro supporter badge",
86
  "Everything in Plus",
87
- "When chat opens: 5× Plus usage (75 per session, 500 a week)",
88
  "Feedback goes straight to the team"
89
  ]
90
  },
@@ -102,7 +102,7 @@
102
  "features": [
103
  "Max 10× supporter badge",
104
  "Everything in Pro",
105
- "When chat opens: 10× Plus usage (150 per session, 1,000 a week)",
106
  "Planned: Cowork tasks and MyBot bundle"
107
  ]
108
  },
@@ -120,7 +120,7 @@
120
  "features": [
121
  "Max 10× supporter badge",
122
  "Everything in Pro",
123
- "When chat opens: 10× Plus usage (150 per session, 1,000 a week)",
124
  "Planned: Cowork tasks and MyBot bundle"
125
  ]
126
  },
@@ -138,7 +138,7 @@
138
  "features": [
139
  "Max 20× supporter badge",
140
  "Everything in Max 10×",
141
- "When chat opens: 20× Plus usage (300 per session, 2,000 a week)",
142
  "Planned: early access to new models"
143
  ]
144
  },
@@ -156,7 +156,7 @@
156
  "features": [
157
  "Max 20× supporter badge",
158
  "Everything in Max 10×",
159
- "When chat opens: 20× Plus usage (300 per session, 2,000 a week)",
160
  "Planned: early access to new models"
161
  ]
162
  }
@@ -164,35 +164,58 @@
164
  "usage": {
165
  "sessionHours": 5,
166
  "weekDays": 7,
167
- "note": "A session starts with your first message and resets 5 hours later. The weekly limit resets 7 days after the first message of that week."
 
168
  },
169
  "tiers": {
170
  "plus": {
171
  "name": "Plus",
172
  "multiple": 1,
173
- "session": 15,
174
- "week": 100
175
  },
176
  "pro": {
177
  "name": "Pro",
178
  "multiple": 5,
179
- "session": 75,
180
- "week": 500
181
  },
182
  "max10": {
183
  "name": "Max 10×",
184
  "multiple": 10,
185
- "session": 150,
186
- "week": 1000
187
  },
188
  "max20": {
189
  "name": "Max 20×",
190
  "multiple": 20,
191
- "session": 300,
192
- "week": 2000
193
  }
194
  },
195
  "supporter": {
196
  "note": "m.ai is in early development. Subscribing supports development: you get a supporter badge now and early-tester access to Spark chat (research preview) before anyone else."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  }
198
  }
 
30
  "features": [
31
  "Supporter badge on your m.ai account",
32
  "Early tester: first access to Spark chat (research preview)",
33
+ "When chat opens: 6,000 tokens per 5-hour session, 40,000 a week",
34
  "Your support funds m.ai’s own models"
35
  ]
36
  },
 
48
  "features": [
49
  "Supporter badge on your m.ai account",
50
  "Early tester: first access to Spark chat (research preview)",
51
+ "When chat opens: 6,000 tokens per 5-hour session, 40,000 a week",
52
  "Your support funds m.ai’s own models"
53
  ]
54
  },
 
66
  "features": [
67
  "Pro supporter badge",
68
  "Everything in Plus",
69
+ "When chat opens: 5× Plus usage (30,000 tokens per session, 200,000 a week)",
70
  "Feedback goes straight to the team"
71
  ]
72
  },
 
84
  "features": [
85
  "Pro supporter badge",
86
  "Everything in Plus",
87
+ "When chat opens: 5× Plus usage (30,000 tokens per session, 200,000 a week)",
88
  "Feedback goes straight to the team"
89
  ]
90
  },
 
102
  "features": [
103
  "Max 10× supporter badge",
104
  "Everything in Pro",
105
+ "When chat opens: 10× Plus usage (60,000 tokens per session, 400,000 a week)",
106
  "Planned: Cowork tasks and MyBot bundle"
107
  ]
108
  },
 
120
  "features": [
121
  "Max 10× supporter badge",
122
  "Everything in Pro",
123
+ "When chat opens: 10× Plus usage (60,000 tokens per session, 400,000 a week)",
124
  "Planned: Cowork tasks and MyBot bundle"
125
  ]
126
  },
 
138
  "features": [
139
  "Max 20× supporter badge",
140
  "Everything in Max 10×",
141
+ "When chat opens: 20× Plus usage (120,000 tokens per session, 800,000 a week)",
142
  "Planned: early access to new models"
143
  ]
144
  },
 
156
  "features": [
157
  "Max 20× supporter badge",
158
  "Everything in Max 10×",
159
+ "When chat opens: 20× Plus usage (120,000 tokens per session, 800,000 a week)",
160
  "Planned: early access to new models"
161
  ]
162
  }
 
164
  "usage": {
165
  "sessionHours": 5,
166
  "weekDays": 7,
167
+ "note": "Limits are in tokens. Each reply counts your message, the conversation sent with it and the answer. Bigger models use tokens faster: Spark counts 1×, and larger m.ai models will count more when they arrive. A session starts with your first reply and resets 5 hours later; the weekly limit resets 7 days after the first reply of that week.",
168
+ "unit": "tokens"
169
  },
170
  "tiers": {
171
  "plus": {
172
  "name": "Plus",
173
  "multiple": 1,
174
+ "session": 6000,
175
+ "week": 40000
176
  },
177
  "pro": {
178
  "name": "Pro",
179
  "multiple": 5,
180
+ "session": 30000,
181
+ "week": 200000
182
  },
183
  "max10": {
184
  "name": "Max 10×",
185
  "multiple": 10,
186
+ "session": 60000,
187
+ "week": 400000
188
  },
189
  "max20": {
190
  "name": "Max 20×",
191
  "multiple": 20,
192
+ "session": 120000,
193
+ "week": 800000
194
  }
195
  },
196
  "supporter": {
197
  "note": "m.ai is in early development. Subscribing supports development: you get a supporter badge now and early-tester access to Spark chat (research preview) before anyone else."
198
+ },
199
+ "models": {
200
+ "spark": {
201
+ "name": "Spark",
202
+ "weight": 1,
203
+ "available": true
204
+ },
205
+ "pulse": {
206
+ "name": "Pulse",
207
+ "weight": 2,
208
+ "available": false
209
+ },
210
+ "horizon": {
211
+ "name": "Horizon",
212
+ "weight": 4,
213
+ "available": false
214
+ },
215
+ "orbit": {
216
+ "name": "Orbit",
217
+ "weight": 8,
218
+ "available": false
219
+ }
220
  }
221
  }
api/core.mjs CHANGED
@@ -36,7 +36,16 @@ export function passEnd(startMs, period) {
36
  return d.getTime();
37
  }
38
 
39
- // A chat usage window ({start,count}) starts with the first message and lasts `length` ms; expired or missing is empty.
 
 
 
 
 
 
 
 
 
40
  export function usageWindow(w, length, now=Date.now()) {
41
  return !w || w.start==null || now>=w.start+length ? {start:null,count:0} : {start:w.start,count:w.count};
42
  }
@@ -89,13 +98,16 @@ export const fields={
89
  razorpay_signature:[v=>typeof v==='string' && /^[a-f0-9]{64}$/i.test(v),'Missing payment details.'],
90
  messages:[v=>Array.isArray(v) && v.length>=1 && v.length<=12,'Send between 1 and 12 messages.'],
91
  confirm:[v=>v===true,'Confirm that you want to delete your account.'],
 
 
92
  };
93
  // Strict bodies per POST route: exactly these fields, nothing else.
94
  export const bodies={
95
  '/api/billing/create':['plan','acceptTerms'], '/api/billing/create-order':['plan','acceptTerms'],
96
  '/api/billing/verify-payment':['razorpay_order_id','razorpay_payment_id','razorpay_signature'],
97
  '/api/billing/verify':['razorpay_payment_id','razorpay_subscription_id','razorpay_signature'],
98
- '/api/billing/cancel':[], '/api/chat/send':['messages'], '/api/account/delete':['confirm'],
 
99
  };
100
  // Returns '' when the body is acceptable, else a message safe to show the user.
101
  export function checkBody(body, names) {
 
36
  return d.getTime();
37
  }
38
 
39
+ // A chat usage window ({start,count}: count is tokens) starts with the first reply and lasts `length` ms; expired or missing is empty.
40
+ // Tokens one reply costs: (everything sent to the model + what came back) × the model's weight, so bigger models use a
41
+ // plan faster. Counts the model reports are trusted within sane bounds; missing ones are estimated (about 4 characters
42
+ // a token). Anything produced costs at least 1.
43
+ export function estimateTokens(text){return Math.ceil(String(text??'').length/4);}
44
+ export function replyCost(weight, promptTokens, outputTokens){
45
+ const w=Number(weight)>0?Number(weight):1;
46
+ const n=Math.min(8192,Math.max(0,Math.round(Number(promptTokens)||0)))+Math.min(4096,Math.max(0,Math.round(Number(outputTokens)||0)));
47
+ return Math.max(1,Math.ceil(w*n));
48
+ }
49
  export function usageWindow(w, length, now=Date.now()) {
50
  return !w || w.start==null || now>=w.start+length ? {start:null,count:0} : {start:w.start,count:w.count};
51
  }
 
98
  razorpay_signature:[v=>typeof v==='string' && /^[a-f0-9]{64}$/i.test(v),'Missing payment details.'],
99
  messages:[v=>Array.isArray(v) && v.length>=1 && v.length<=12,'Send between 1 and 12 messages.'],
100
  confirm:[v=>v===true,'Confirm that you want to delete your account.'],
101
+ model:[v=>v===undefined || (typeof v==='string' && /^[a-z0-9-]{1,20}$/.test(v)),'Choose a model.'],
102
+ reason:[v=>v===undefined || ['price','not-using','waiting-for-chat','switching','other'].includes(v),'Choose a reason from the list.'],
103
  };
104
  // Strict bodies per POST route: exactly these fields, nothing else.
105
  export const bodies={
106
  '/api/billing/create':['plan','acceptTerms'], '/api/billing/create-order':['plan','acceptTerms'],
107
  '/api/billing/verify-payment':['razorpay_order_id','razorpay_payment_id','razorpay_signature'],
108
  '/api/billing/verify':['razorpay_payment_id','razorpay_subscription_id','razorpay_signature'],
109
+ '/api/billing/cancel':['reason'], '/api/chat/send':['messages','model'], '/api/account/delete':['confirm'],
110
+ '/api/billing/change':['plan','acceptTerms'], '/api/billing/cancel-next':[],
111
  };
112
  // Returns '' when the body is acceptable, else a message safe to show the user.
113
  export function checkBody(body, names) {
api/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"mai-billing","private":true,"type":"module","engines":{"node":">=22.13"},"scripts":{"start":"node server.mjs","dev":"node --env-file=.env dev.mjs","setup-test-plans":"node --env-file=.env setup-plans.mjs","setup-live-plans":"node --env-file=.env setup-plans.mjs --live","test":"node --test"},"dependencies":{"firebase-admin":"^13.0.0"}}
 
1
+ {"name":"mai-billing","private":true,"type":"module","engines":{"node":">=22.13"},"scripts":{"start":"node main.mjs","dev":"node --env-file=.env dev.mjs","setup-test-plans":"node --env-file=.env setup-plans.mjs","setup-live-plans":"node --env-file=.env setup-plans.mjs --live","test":"node --test"},"dependencies":{"firebase-admin":"^13.0.0"}}
api/store.mjs CHANGED
@@ -1,8 +1,9 @@
1
  import {activePass} from './access.mjs';
2
  // Firestore storage for the m.ai API (firebase-admin). firestore.rules deny every client; only this server reads and writes.
3
- // accounts/{uid} {sid, plan, created, cancel_at} the account's Razorpay subscription
 
4
  // orders/{orderId} {uid, plan, amount, status, created, payment, starts, ends} one-time payments (status created|paid|refunded)
5
- // usage/{uid} {session:{start,count}, week:{start,count}} chat messages per window
6
  // events/{eventId} {created} webhook deliveries already handled
7
  // Queries are equality on one field (uid) only, so no composite index is needed; each user has few orders.
8
  // Anything two requests could race on runs in a transaction (or a create, which fails if the document exists).
@@ -33,7 +34,27 @@ export function storage(db, {session, week}) {
33
  if(previous){const {id,...fields}=previous;t.set(ref,fields);}else t.delete(ref);
34
  return true;
35
  }),
36
- setCancelAt:(uid,at)=>accounts.doc(uid).update({cancel_at:at}),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  order:async id=>data(await orders.doc(id).get()),
38
  ordersOf,
39
  addOrder:({id,...o})=>orders.doc(id).create(o),
@@ -57,20 +78,13 @@ export function storage(db, {session, week}) {
57
  // Account deletion: the chat usage record goes; payment records stay (no personal details, kept for tax law).
58
  forget:uid=>usage.doc(uid).delete(),
59
  usage:async(uid,now=Date.now())=>windows((await usage.doc(uid).get()).data(),now),
60
- // Checks the limits and counts one message in one transaction, so parallel requests can never pass the limits.
61
- take:(uid,limits,now=Date.now())=>db.runTransaction(async t=>{
 
62
  const ref=usage.doc(uid), w=windows((await t.get(ref)).data(),now);
63
- if(w.session.count>=limits.session||w.week.count>=limits.week)return {ok:false,...w};
64
- const next={session:{start:w.session.start??now,count:w.session.count+1},week:{start:w.week.start??now,count:w.week.count+1}};
65
  t.set(ref,next);
66
- return {ok:true,...next};
67
- }),
68
- // Gives one message back, only inside the windows it was counted in (an expired window stays expired).
69
- refund:(uid,now=Date.now())=>db.runTransaction(async t=>{
70
- const ref=usage.doc(uid), w=windows((await t.get(ref)).data(),now);
71
- if(w.session.start===null&&w.week.start===null)return;
72
- const back=x=>x.start===null?x:{start:x.start,count:Math.max(0,x.count-1)};
73
- t.set(ref,{session:back(w.session),week:back(w.week)});
74
  }),
75
  eventDone:async id=>(await eventDoc(id).get()).exists,
76
  // Mark complete only after idempotent processing succeeds. True for first completion; false for a repeated (or parallel) delivery.
 
1
  import {activePass} from './access.mjs';
2
  // Firestore storage for the m.ai API (firebase-admin). firestore.rules deny every client; only this server reads and writes.
3
+ // accounts/{uid} {sid, plan, created, cancel_at, cancel_reason, the account's Razorpay subscription, and
4
+ // next_sid, next_plan, next_start, next_kind} the one that starts when it ends
5
  // orders/{orderId} {uid, plan, amount, status, created, payment, starts, ends} one-time payments (status created|paid|refunded)
6
+ // usage/{uid} {session:{start,count}, week:{start,count}} chat tokens used per window
7
  // events/{eventId} {created} webhook deliveries already handled
8
  // Queries are equality on one field (uid) only, so no composite index is needed; each user has few orders.
9
  // Anything two requests could race on runs in a transaction (or a create, which fails if the document exists).
 
34
  if(previous){const {id,...fields}=previous;t.set(ref,fields);}else t.delete(ref);
35
  return true;
36
  }),
37
+ setCancelAt:(uid,at,reason)=>accounts.doc(uid).update({cancel_at:at,...(reason?{cancel_reason:reason}:{})}),
38
+ // The next subscription (a plan switch or a resubscription), set only if the current next is still `expected`.
39
+ setNext:(uid,expected,fields)=>db.runTransaction(async t=>{
40
+ const ref=accounts.doc(uid), now=(await t.get(ref)).data();
41
+ if(!now||(now.next_sid??null)!==expected)return false;
42
+ t.set(ref,{...now,...fields});
43
+ return true;
44
+ }),
45
+ clearNext:(uid,expected)=>db.runTransaction(async t=>{
46
+ const ref=accounts.doc(uid), now=(await t.get(ref)).data();
47
+ if(!now||now.next_sid!==expected)return false;
48
+ t.set(ref,{...now,next_sid:null,next_plan:null,next_start:null,next_kind:null});
49
+ return true;
50
+ }),
51
+ // The current period is over and the next subscription took over: it becomes the account's subscription.
52
+ promote:(uid,sid,next)=>db.runTransaction(async t=>{
53
+ const ref=accounts.doc(uid), now=(await t.get(ref)).data();
54
+ if(!now||now.sid!==sid||now.next_sid!==next)return false;
55
+ t.set(ref,{...now,sid:next,plan:now.next_plan,created:Date.now(),cancel_at:null,cancel_reason:null,next_sid:null,next_plan:null,next_start:null,next_kind:null});
56
+ return true;
57
+ }),
58
  order:async id=>data(await orders.doc(id).get()),
59
  ordersOf,
60
  addOrder:({id,...o})=>orders.doc(id).create(o),
 
78
  // Account deletion: the chat usage record goes; payment records stay (no personal details, kept for tax law).
79
  forget:uid=>usage.doc(uid).delete(),
80
  usage:async(uid,now=Date.now())=>windows((await usage.doc(uid).get()).data(),now),
81
+ // Adds one reply's tokens to both windows, after the reply (a window starts with its first reply). The limits are
82
+ // checked before the reply; one reply at a time per account, so a reply can pass a limit by at most itself.
83
+ charge:(uid,tokens,now=Date.now())=>db.runTransaction(async t=>{
84
  const ref=usage.doc(uid), w=windows((await t.get(ref)).data(),now);
85
+ const next={session:{start:w.session.start??now,count:w.session.count+tokens},week:{start:w.week.start??now,count:w.week.count+tokens}};
 
86
  t.set(ref,next);
87
+ return next;
 
 
 
 
 
 
 
88
  }),
89
  eventDone:async id=>(await eventDoc(id).get()).exists,
90
  // Mark complete only after idempotent processing succeeds. True for first completion; false for a repeated (or parallel) delivery.
spark_server.py CHANGED
@@ -1,7 +1,7 @@
1
  """Spark chat server for the m.ai Hugging Face Space (research preview).
2
 
3
  Same contract as the m.ai app's /api/chat: POST {"messages": [...], "max_tokens": n} -> Server-Sent Events
4
- `data: {"t": "..."}` ... `data: {"done": true, "tokens": n}`. Only the m.ai API inside the same container calls it
5
  (it binds to 127.0.0.1), and the API has already checked sign-in, plan and usage limits.
6
  Decoding matches the app: the checkpoint's own system prompt, greedy, repetition penalty 1.1, at most 128 tokens.
7
  """
@@ -111,7 +111,8 @@ class Handler(BaseHTTPRequestHandler):
111
  self.wfile.write(('data: ' + json.dumps({'t': text[len(sent):]}) + '\n\n').encode())
112
  self.wfile.flush()
113
  sent = text
114
- self.wfile.write(('data: ' + json.dumps({'done': True, 'tokens': len(out)}) + '\n\n').encode())
 
115
  except (BrokenPipeError, ConnectionResetError):
116
  pass
117
  except Exception as e:
 
1
  """Spark chat server for the m.ai Hugging Face Space (research preview).
2
 
3
  Same contract as the m.ai app's /api/chat: POST {"messages": [...], "max_tokens": n} -> Server-Sent Events
4
+ `data: {"t": "..."}` ... `data: {"done": true, "tokens": n, "prompt_tokens": m}`. Only the m.ai API inside the same container calls it
5
  (it binds to 127.0.0.1), and the API has already checked sign-in, plan and usage limits.
6
  Decoding matches the app: the checkpoint's own system prompt, greedy, repetition penalty 1.1, at most 128 tokens.
7
  """
 
111
  self.wfile.write(('data: ' + json.dumps({'t': text[len(sent):]}) + '\n\n').encode())
112
  self.wfile.flush()
113
  sent = text
114
+ # prompt_tokens + tokens: what the m.ai API charges against the plan's token limits
115
+ self.wfile.write(('data: ' + json.dumps({'done': True, 'tokens': len(out), 'prompt_tokens': len(ids)}) + '\n\n').encode())
116
  except (BrokenPipeError, ConnectionResetError):
117
  pass
118
  except Exception as e: