Shoraky commited on
Commit
0ffd170
·
1 Parent(s): f496327

Cache subscription authorization lookups

Browse files
Files changed (3) hide show
  1. README.md +6 -0
  2. src/server.ts +4 -13
  3. src/subscriptions.ts +35 -0
README.md CHANGED
@@ -112,3 +112,9 @@ The frontend sends JSON as `text/plain` and carries PUT/PATCH/DELETE through POS
112
  Google PKCE verifiers are stored in a short-lived HttpOnly, SameSite=Lax cookie tied to the initiating browser. Allow the backend callback and its `?next=**` variant in Supabase's redirect list. Cross-site session cookies still require the browser to allow cookies for the Space.
113
 
114
  Cross-origin video uploads do not attach upload-progress listeners, since those also trigger preflight. Uploads still go directly to the Space and can be cancelled; processing progress remains available after acceptance.
 
 
 
 
 
 
 
112
  Google PKCE verifiers are stored in a short-lived HttpOnly, SameSite=Lax cookie tied to the initiating browser. Allow the backend callback and its `?next=**` variant in Supabase's redirect list. Cross-site session cookies still require the browser to allow cookies for the Space.
113
 
114
  Cross-origin video uploads do not attach upload-progress listeners, since those also trigger preflight. Uploads still go directly to the Space and can be cancelled; processing progress remains available after acceptance.
115
+
116
+ ## Session and access caching
117
+
118
+ `/api/auth/me` returns identity and subscription access together. The frontend keeps that UI snapshot in tab-scoped sessionStorage for 60 seconds, including across reloads, and shares concurrent checks. Logout, account deletion, and starting Google sign-in clear the snapshot. No access or refresh token is stored in browser storage; HttpOnly cookies and backend authorization remain authoritative.
119
+
120
+ The backend caches subscription lookup results per user for at most 30 seconds (never beyond UTC midnight), with concurrent lookup deduplication and a 1,000-entry bound. Assigning a subscription through `assignPaidSubscription` invalidates that user's entry immediately. Direct database changes can take up to 30 seconds to affect backend authorization; the UI snapshot can take up to 60 seconds to refresh. Authentication is still verified for protected API requests.
src/server.ts CHANGED
@@ -1,3 +1,4 @@
 
1
  import express, { type NextFunction, type Request, type Response } from "express";
2
  import cors from "cors";
3
  import cookieParser from "cookie-parser";
@@ -56,18 +57,6 @@ const profileSchema = z.object({
56
  });
57
  const passwordSchema = z.object({ currentPassword: z.string().max(128).optional(), newPassword: z.string().min(8).max(128) });
58
 
59
- async function activeSubscriptionFor(userId: string) {
60
- const today = new Date().toISOString().slice(0, 10);
61
- const { data: assignment, error } = await supabaseAdmin.from("users_subscriptions")
62
- .select("subscription_id,startdate,enddate").eq("user_id", userId).maybeSingle();
63
- if (error) throw new Error(`Unable to check subscription: ${error.message}`);
64
- if (!assignment?.subscription_id || assignment.startdate > today || assignment.enddate < today) return null;
65
-
66
- const { data: plan, error: planError } = await supabaseAdmin.from("subscriptions")
67
- .select("subscription_id,plan,price").eq("subscription_id", assignment.subscription_id).maybeSingle();
68
- if (planError) throw new Error(`Unable to load subscription plan: ${planError.message}`);
69
- return plan ? { ...plan, startdate: assignment.startdate, enddate: assignment.enddate } : null;
70
- }
71
 
72
  async function requireActiveSubscription(req: Request, res: Response) {
73
  const current = await authenticatedUser(req, res);
@@ -366,7 +355,9 @@ app.get("/api/auth/me", async (req, res, next) => {
366
  try {
367
  const current = await authenticatedUser(req, res);
368
  if (!current) return res.status(401).json({ error: "Authentication required." });
369
- return res.json({ user: userPayload(current.user) });
 
 
370
  } catch (error) { next(error); }
371
  });
372
 
 
1
+ import { activeSubscriptionFor } from "./subscriptions.js";
2
  import express, { type NextFunction, type Request, type Response } from "express";
3
  import cors from "cors";
4
  import cookieParser from "cookie-parser";
 
57
  });
58
  const passwordSchema = z.object({ currentPassword: z.string().max(128).optional(), newPassword: z.string().min(8).max(128) });
59
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  async function requireActiveSubscription(req: Request, res: Response) {
62
  const current = await authenticatedUser(req, res);
 
355
  try {
356
  const current = await authenticatedUser(req, res);
357
  if (!current) return res.status(401).json({ error: "Authentication required." });
358
+ const subscription = await activeSubscriptionFor(current.user.id);
359
+ res.set("Cache-Control", "no-store");
360
+ return res.json({ user: userPayload(current.user), access: { active: Boolean(subscription), subscription } });
361
  } catch (error) { next(error); }
362
  });
363
 
src/subscriptions.ts CHANGED
@@ -33,5 +33,40 @@ export async function assignPaidSubscription(input: AssignSubscriptionInput) {
33
  .select("user_id,subscription_id,startdate,enddate")
34
  .single();
35
  if (error) throw new Error(`Unable to assign paid subscription: ${error.message}`);
 
 
36
  return data;
37
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  .select("user_id,subscription_id,startdate,enddate")
34
  .single();
35
  if (error) throw new Error(`Unable to assign paid subscription: ${error.message}`);
36
+ accessCache.delete(userId);
37
+ accessRequests.delete(userId);
38
  return data;
39
  }
40
+
41
+ async function loadActiveSubscription(userId: string) {
42
+ const today = new Date().toISOString().slice(0, 10);
43
+ const { data: assignment, error } = await supabaseAdmin.from("users_subscriptions")
44
+ .select("subscription_id,startdate,enddate").eq("user_id", userId).maybeSingle();
45
+ if (error) throw new Error(`Unable to check subscription: ${error.message}`);
46
+ if (!assignment?.subscription_id || assignment.startdate > today || assignment.enddate < today) return null;
47
+
48
+ const { data: plan, error: planError } = await supabaseAdmin.from("subscriptions")
49
+ .select("subscription_id,plan,price").eq("subscription_id", assignment.subscription_id).maybeSingle();
50
+ if (planError) throw new Error(`Unable to load subscription plan: ${planError.message}`);
51
+ return plan ? { ...plan, startdate: assignment.startdate, enddate: assignment.enddate } : null;
52
+ }
53
+
54
+ // Brief, per-user cache shared by polling, media and session requests.
55
+ const accessCache = new Map<string, { value: Awaited<ReturnType<typeof loadActiveSubscription>>; expires: number }>();
56
+ const accessRequests = new Map<string, Promise<Awaited<ReturnType<typeof loadActiveSubscription>>>>();
57
+ export async function activeSubscriptionFor(userId: string) {
58
+ const cached = accessCache.get(userId);
59
+ if (cached && cached.expires > Date.now()) return cached.value;
60
+ const existing = accessRequests.get(userId);
61
+ if (existing) return existing;
62
+ const pending = loadActiveSubscription(userId).then((value) => {
63
+ if (accessRequests.get(userId) === pending) {
64
+ if (accessCache.size >= 1000) accessCache.delete(accessCache.keys().next().value!);
65
+ const tomorrow = new Date(); tomorrow.setUTCHours(24, 0, 0, 0);
66
+ accessCache.set(userId, { value, expires: Math.min(Date.now() + 30_000, tomorrow.getTime()) });
67
+ }
68
+ return value;
69
+ }).finally(() => { if (accessRequests.get(userId) === pending) accessRequests.delete(userId); });
70
+ accessRequests.set(userId, pending);
71
+ return pending;
72
+ }