Shoraky commited on
Commit
523ba8d
Β·
1 Parent(s): dce0b2f

Return OAuth through the first-party frontend API proxy

Browse files
Files changed (4) hide show
  1. README.md +7 -7
  2. src/auth.ts +1 -1
  3. src/config.ts +2 -0
  4. src/server.ts +2 -2
README.md CHANGED
@@ -6,7 +6,7 @@ app_port: 7860
6
 
7
  # Sporalize Backend
8
 
9
- One Docker service runs Express for authentication, subscriptions and Supabase access, and FastAPI for video analysis. Node exposes port 7860 in the Space; Python binds only to 127.0.0.1:8000. `start.py` supervises both processes and stops the service if either exits. Python calls Node over loopback; `BACKEND_URL` remains the public origin for authentication redirects and media links.
10
 
11
  ## Local development
12
 
@@ -51,7 +51,7 @@ Apply `../Database/migrations/20261016_node_analysis.sql` before analyses. It as
51
  2. Authentication β†’ Providers β†’ Google: enable it, add the Google client ID/secret, and use Supabase's displayed callback URL in Google Cloud.
52
  3. Authentication β†’ URL Configuration:
53
  - Site URL: `http://localhost:8080` during development.
54
- - Redirect URLs: `http://localhost:4000/api/auth/callback` and the production equivalent.
55
 
56
  ## Brevo email verification
57
 
@@ -67,14 +67,14 @@ Brevo is configured as Supabase Auth's SMTP provider; the Express API does not s
67
  - Sender email: the verified Brevo sender
68
  - Sender name: `Sporalize`
69
  4. Keep **Confirm email** enabled under Authentication β†’ Providers β†’ Email.
70
- 5. In **Authentication β†’ Email Templates β†’ Confirm signup**, set the confirmation link to the backend's absolute URL (replace `https://your-api-domain` with the deployed API origin):
71
 
72
  ```html
73
  <h2>Confirm your Sporalize account</h2>
74
- <p><a href="https://your-api-domain/api/auth/confirm?token_hash={{ .TokenHash }}">Confirm email</a></p>
75
  ```
76
 
77
- Set **Site URL** to the frontend origin. Keep the backend callback URL in **Authentication β†’ URL Configuration β†’ Redirect URLs** for Google sign-in, and add its production equivalent. The email template links directly to the backend confirmation endpoint, which verifies the one-time token and creates the application's secure session cookies.
78
 
79
  Brevo credentials stay in Supabase SMTP settings and are not added to the browser or committed to `.env`.
80
 
@@ -109,9 +109,9 @@ That helper upserts the user's single current plan in `users_subscriptions`. The
109
 
110
  The frontend sends JSON as `text/plain` and carries PUT/PATCH/DELETE through POST with an `_method` query parameter because the Space edge can omit credential headers on preflight responses. Express checks the frontend Origin before restoring the method, parses the JSON with the same body-size limit, and retains route authentication. Internal AI requests remain standard JSON. Do not remove the Origin check or use this transport for internal routes.
111
 
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
 
 
6
 
7
  # Sporalize Backend
8
 
9
+ One Docker service runs Express for authentication, subscriptions and Supabase access, and FastAPI for video analysis. Node exposes port 7860 in the Space; Python binds only to 127.0.0.1:8000. `start.py` supervises both processes and stops the service if either exits. Python calls Node over loopback. `BACKEND_URL` remains the Space origin; production OAuth callbacks use `FRONTEND_URL` through the Cloudflare Pages proxy so browser cookies stay first-party.
10
 
11
  ## Local development
12
 
 
51
  2. Authentication β†’ Providers β†’ Google: enable it, add the Google client ID/secret, and use Supabase's displayed callback URL in Google Cloud.
52
  3. Authentication β†’ URL Configuration:
53
  - Site URL: `http://localhost:8080` during development.
54
+ - Redirect URLs: `http://localhost:4000/api/auth/callback` (and its `?next=**` variant) for development; `https://sporalizer.pages.dev/api/auth/callback` and `https://sporalizer.pages.dev/api/auth/callback?next=**` for production. Replace the frontend origin if deploying elsewhere. The Google Cloud redirect URI stays the Supabase provider callback.
55
 
56
  ## Brevo email verification
57
 
 
67
  - Sender email: the verified Brevo sender
68
  - Sender name: `Sporalize`
69
  4. Keep **Confirm email** enabled under Authentication β†’ Providers β†’ Email.
70
+ 5. In **Authentication β†’ Email Templates β†’ Confirm signup**, set the confirmation link to the frontend's proxied API URL (replace the domain if deploying elsewhere):
71
 
72
  ```html
73
  <h2>Confirm your Sporalize account</h2>
74
+ <p><a href="https://sporalizer.pages.dev/api/auth/confirm?token_hash={{ .TokenHash }}">Confirm email</a></p>
75
  ```
76
 
77
+ Set **Site URL** to the frontend origin. Allow the frontend callback URLs listed above. The Pages proxy forwards confirmation to the backend, which verifies the one-time token and sets secure, host-only HttpOnly cookies on the frontend domain. Existing email links using the Space origin should be replaced by newly issued emails.
78
 
79
  Brevo credentials stay in Supabase SMTP settings and are not added to the browser or committed to `.env`.
80
 
 
109
 
110
  The frontend sends JSON as `text/plain` and carries PUT/PATCH/DELETE through POST with an `_method` query parameter because the Space edge can omit credential headers on preflight responses. Express checks the frontend Origin before restoring the method, parses the JSON with the same body-size limit, and retains route authentication. Internal AI requests remain standard JSON. Do not remove the Origin check or use this transport for internal routes.
111
 
112
+ Google PKCE verifiers are stored in a short-lived HttpOnly, SameSite=Lax cookie tied to the initiating browser. In production, OAuth start, callback, session checks and protected API/media requests all pass through the Pages proxy. Access and refresh cookies are also SameSite=Lax and host-only. Do not redirect OAuth back to the Space domain: that puts the verifier and session on different hosts. In development, the frontend calls the local backend directly.
113
 
114
+ The Pages proxy streams uploads and media without buffering. Cloudflare's request-body limit still applies (100 MB on Free/Pro, including all multipart files and overhead). Google Drive import transfers the video server-side and avoids that browser-upload limit. Processing progress and cancellation remain available.
115
 
116
  ## Session and access caching
117
 
src/auth.ts CHANGED
@@ -5,7 +5,7 @@ import { supabaseAuth } from "./supabase.js";
5
 
6
  const accessCookie = "sp_access";
7
  const refreshCookie = "sp_refresh";
8
- const sameSite = isProduction ? "none" as const : "lax" as const;
9
  const cookieOptions = { httpOnly: true, secure: isProduction, sameSite, path: "/" };
10
 
11
  export function setSessionCookies(res: Response, session: Session) {
 
5
 
6
  const accessCookie = "sp_access";
7
  const refreshCookie = "sp_refresh";
8
+ const sameSite = "lax" as const;
9
  const cookieOptions = { httpOnly: true, secure: isProduction, sameSite, path: "/" };
10
 
11
  export function setSessionCookies(res: Response, session: Session) {
src/config.ts CHANGED
@@ -22,6 +22,8 @@ if (!parsed.success) {
22
 
23
  export const env = parsed.data;
24
  export const isProduction = env.NODE_ENV === "production";
 
 
25
 
26
  if (isProduction) {
27
  for (const name of ["FRONTEND_URL", "BACKEND_URL", "SUPABASE_URL"] as const) {
 
22
 
23
  export const env = parsed.data;
24
  export const isProduction = env.NODE_ENV === "production";
25
+ // Production browsers reach auth through Cloudflare Pages, including OAuth.
26
+ export const authPublicOrigin = new URL(isProduction ? env.FRONTEND_URL : env.BACKEND_URL).origin;
27
 
28
  if (isProduction) {
29
  for (const name of ["FRONTEND_URL", "BACKEND_URL", "SUPABASE_URL"] as const) {
src/server.ts CHANGED
@@ -7,7 +7,7 @@ import rateLimit from "express-rate-limit";
7
  import { Readable } from "node:stream";
8
  import { pipeline } from "node:stream/promises";
9
  import { z } from "zod";
10
- import { env } from "./config.js";
11
  import { analysisRouter } from "./analysis.js";
12
  import { authenticatedUser, clearSessionCookies, safeRedirect, setSessionCookies } from "./auth.js";
13
  import { hashPassword, oauthClient, supabaseAdmin, supabaseAuth, syncProfile, userHasPassword, userPayload } from "./supabase.js";
@@ -423,7 +423,7 @@ app.post("/api/auth/login", authLimiter, async (req, res, next) => {
423
  app.get("/api/auth/google", authLimiter, async (req, res, next) => {
424
  try {
425
  const redirect = typeof req.query.redirect === "string" ? req.query.redirect : "/labs";
426
- const { data, error } = await oauthClient(req, res).auth.signInWithOAuth({ provider: "google", options: { redirectTo: `${env.BACKEND_URL}/api/auth/callback?next=${encodeURIComponent(redirect)}` } });
427
  if (error || !data.url) return res.status(502).json({ error: "Google sign-in is currently unavailable." });
428
  return res.redirect(data.url);
429
  } catch (error) { next(error); }
 
7
  import { Readable } from "node:stream";
8
  import { pipeline } from "node:stream/promises";
9
  import { z } from "zod";
10
+ import { authPublicOrigin, env } from "./config.js";
11
  import { analysisRouter } from "./analysis.js";
12
  import { authenticatedUser, clearSessionCookies, safeRedirect, setSessionCookies } from "./auth.js";
13
  import { hashPassword, oauthClient, supabaseAdmin, supabaseAuth, syncProfile, userHasPassword, userPayload } from "./supabase.js";
 
423
  app.get("/api/auth/google", authLimiter, async (req, res, next) => {
424
  try {
425
  const redirect = typeof req.query.redirect === "string" ? req.query.redirect : "/labs";
426
+ const { data, error } = await oauthClient(req, res).auth.signInWithOAuth({ provider: "google", options: { redirectTo: `${authPublicOrigin}/api/auth/callback?next=${encodeURIComponent(redirect)}` } });
427
  if (error || !data.url) return res.status(502).json({ error: "Google sign-in is currently unavailable." });
428
  return res.redirect(data.url);
429
  } catch (error) { next(error); }