type="module">
const SUPABASE_URL = 'https://asradrkkykuibeeamxsp.supabase.co';
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFzcmFkcmtreWt1aWJlZWFteHNwIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njg4MDA0MjksImV4cCI6MjA4NDM3NjQyOX0.eC8qkk0xexiOIMB377egxAhGhw2b8PvptDxFwD5AE8E';
const GOOGLE_CLIENT_ID = '769892472576-2p6t1j16lq8oq8i8i87tifij61oo7fgq.apps.googleusercontent.com';
const MESSAGING_WORKER_URL = 'https://messaging.rapid-shape-8ddf.workers.dev';
const FIREBASE_CONFIG = {
apiKey: 'AIzaSyBQM2xyssg0VcUXk_NaKeFZxRrCnLzqH60',
authDomain: 'business-user-chat.firebaseapp.com',
databaseURL: 'https://business-user-chat-default-rtdb.europe-west1.firebasedatabase.app',
projectId: 'business-user-chat',
storageBucket: 'business-user-chat.firebasestorage.app',
messagingSenderId: '116025906720',
appId: '1:116025906720:web:5b4671e4266cead3c2ce45',
};
const DEBUG = false;
const LOG_PREFIX = '[Supabase Auth]';
const noop = () => {};
const log = {
info: DEBUG ? (msg, data) => console.log(`${LOG_PREFIX} ℹ️ ${msg}`, data !== undefined ? data : '') : noop,
success: DEBUG ? (msg, data) => console.log(`${LOG_PREFIX} ✅ ${msg}`, data !== undefined ? data : '') : noop,
warn: DEBUG ? (msg, data) => console.warn(`${LOG_PREFIX} ⚠️ ${msg}`, data !== undefined ? data : '') : noop,
error: (msg, data) => console.error(`${LOG_PREFIX} ❌ ${msg}`, data !== undefined ? data : ''),
state: DEBUG ? (msg, data) => console.log(`${LOG_PREFIX} 🔄 ${msg}`, data !== undefined ? data : '') : noop,
};
const supabaseScriptUrl = 'https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2';
const firebaseAppUrl = 'https://www.gstatic.com/firebasejs/10.8.0/firebase-app-compat.js';
const firebaseAuthUrl = 'https://www.gstatic.com/firebasejs/10.8.0/firebase-auth-compat.js';
const firebaseDatabaseUrl = 'https://www.gstatic.com/firebasejs/10.8.0/firebase-database-compat.js';
function loadScript(url, cb) {
const s = document.createElement('script');
s.src = url;
s.onload = () => cb();
s.onerror = () => log.error('Failed to load SDK', url);
document.head.appendChild(s);
}
// Chain load scripts sequentially to avoid race conditions
loadScript(supabaseScriptUrl, () => {
loadScript(firebaseAppUrl, () => {
loadScript(firebaseAuthUrl, () => {
loadScript(firebaseDatabaseUrl, () => {
firebase.initializeApp(FIREBASE_CONFIG);
initSupabase();
});
});
});
});
function initSupabase() {
// ─────────────────────────────────────────────────────────────
// SHARED STATE (scoped to this module; nothing new hits global)
// ─────────────────────────────────────────────────────────────
const state = {
googleLoaded: false,
gisInitialized: false,
currentUser: null,
pendingGoogleIdToken: null,
pendingGoogleIntent: null,
gisPromptNonce: null, // raw nonce for the current Sign In With Google button callback
};
// ─────────────────────────────────────────────────────────────
// DOM CACHE
// ─────────────────────────────────────────────────────────────
const DOM = {
signUpForm: document.querySelector('[user-su-form]'),
suFirstName: document.querySelector('[lg-su-element="first name"]'),
suLastName: document.querySelector('[lg-su-element="last name"]'),
suEmail: document.querySelector('[lg-su-element="email"]'),
suPassword: document.querySelector('[lg-su-element="password"]'),
suTandC: document.querySelector('[lg-su-element="tandc"]'),
suTrigger: document.querySelector('[lg-su-element="sign up"]'),
suGoogleAuth: document.querySelector('[lg-su-element="google auth"]'),
loginForm: document.querySelector('[user-li-form]'),
liEmail: document.querySelector('[user-li-form] [lg-su-element="email"]'),
liPassword: document.querySelector('[user-li-form] [lg-su-element="password"]'),
liTrigger: document.querySelector('[user-li-form] [lg-su-element="login"]'),
liGoogleAuth: document.querySelector('[user-li-form] [lg-su-element="google auth"]'),
userDisplay: document.querySelectorAll('[lg-su-element="user display"]'),
logoutBtn: document.querySelector('[lg-su-element="logout"]'),
userNameElements: document.querySelectorAll('[lg-su-element="user name"]'),
userEmailElements: document.querySelectorAll('[lg-su-element="user email"]'),
panel: document.querySelector('.sup-lgn-fxd-wp'),
};
// ─────────────────────────────────────────────────────────────
// Shared helpers used by all sub-modules
// ─────────────────────────────────────────────────────────────
let alertTimeout;
function showAlertError(message) {
const alertWrapper = document.querySelector('.sup-lg-alert-wr');
const alertText = document.querySelector('.sup-lg-alert-txt');
if (!alertWrapper || !alertText) return;
alertText.textContent = message;
alertWrapper.classList.add('alert');
if (alertTimeout) clearTimeout(alertTimeout);
alertTimeout = setTimeout(() => {
alertText.textContent = '';
alertWrapper.classList.remove('alert');
}, 5000);
}
function sanitizeErrorMessage(message) {
if (!message) return 'An error occurred';
const prefixPattern = /^Firebase:\s*/i;
return message
.replace(prefixPattern, '')
.replace(/$$auth\/.*?$$\.?\s*$/i, '')
.trim();
}
function addProcessing(element) {
if (!element) return;
element.classList.add('processing');
}
function removeProcessing(element) {
if (!element) return;
element.classList.remove('processing');
}
function showLoading(element) {
if (!element) return;
element.classList.add('is-loading');
element.setAttribute('disabled', 'true');
log.state(`Loading state ON for`, element.getAttribute('lg-su-element') || element.tagName);
}
function hideLoading(element) {
if (!element) return;
element.classList.remove('is-loading');
element.removeAttribute('disabled');
}
function showError(element, message) {
// NOTE: element param preserved for API parity; global alert used intentionally
showAlertError(sanitizeErrorMessage(message));
}
function clearErrors(form) {
if (!form) return;
form.querySelectorAll('.auth-error-message').forEach((e) => e.remove());
}
function showSuccess(form, message) {
if (!form) return;
const successEl = document.createElement('div');
successEl.className = 'auth-success-message';
successEl.style.cssText = 'color:#27ae60;font-size:13px;margin-top:8px;padding:8px 12px;background:#eafaf1;border-radius:4px;border-left:3px solid #27ae60;';
successEl.textContent = message;
form.appendChild(successEl);
log.success(`Success shown: "${message}"`);
setTimeout(() => successEl.remove(), 6000);
}
function dispatchAuthEvent(user) {
const eventName = user ? 'userLoggedIn' : 'userLoggedOut';
const event = new CustomEvent(eventName, {
detail: user
? {
uid: user.id,
email: user.email,
displayName: user.user_metadata?.full_name || user.user_metadata?.name,
}
: null,
bubbles: true,
});
document.dispatchEvent(event);
log.info(`Dispatched ${eventName} event`);
}
function computeFirstName(user) {
if (!user) return '?';
const metadata = user.user_metadata || {};
const fullName = metadata.full_name || metadata.name || '';
if (fullName) return fullName.split(' ')[0];
if (user.email) return user.email.split('@')[0];
return '?';
}
// ─────────────────────────────────────────────────────────────
// Crypto helper (used by both nonce verification and redirect hashing)
// ─────────────────────────────────────────────────────────────
async function sha256Hex(str) {
const enc = new TextEncoder().encode(str);
const buf = await crypto.subtle.digest('SHA-256', enc);
return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
// ═════════════════════════════════════════════════════════════
// MODULE: URLParamManager — sync UI state to/from URL params
// ═════════════════════════════════════════════════════════════
const URLParamManager = {
// Only update URL after explicit user actions
updateFromUI() {
const params = new URLSearchParams(window.location.search);
if (DOM.panel?.classList.contains('opened')) {
params.set('auth', 'init');
const signUpActive = !DOM.signUpForm?.classList.contains('nochoice');
params.set('auth-form', signUpActive ? 'sign-up' : 'login');
} else {
// Only remove auth params if panel is actually closed
// and we've had a user interaction (not on load)
if (this.userInteracted) {
params.delete('auth');
params.delete('auth-form');
}
}
// Preserve ALL existing params
const queryString = params.toString();
const newUrl = `${window.location.pathname}${queryString ? '?' + queryString : ''}${window.location.hash}`;
history.replaceState(null, '', newUrl);
},
applyFromURL() {
const params = new URLSearchParams(window.location.search);
const authParam = params.get('auth');
if (authParam === 'init' && DOM.panel) {
DOM.panel.classList.add('opened');
const formParam = params.get('auth-form');
if (formParam === 'sign-up') {
this._setActiveForm('signup');
} else if (formParam === 'login') {
this._setActiveForm('login');
}
}
// Don't close panel if auth param is missing - just ignore
},
// Add this flag
userInteracted: false,
_setActiveForm(formType) {
if (formType === 'signup') {
DOM.signUpForm?.classList.remove('nochoice');
DOM.loginForm?.classList.add('nochoice');
} else if (formType === 'login') {
DOM.loginForm?.classList.remove('nochoice');
DOM.signUpForm?.classList.add('nochoice');
}
},
};
// 💡 FIXED: Capture clicks in the capturing phase (3rd param `true`)
// to ensure userInteracted is updated BEFORE our finish trigger executes
document.addEventListener(
'click',
() => {
URLParamManager.userInteracted = true;
},
true,
);
// ═════════════════════════════════════════════════════════════
// MODULE: Validators
// ═════════════════════════════════════════════════════════════
const Validators = {
email(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const valid = re.test(email);
log.info(`Email validation for "${email}": ${valid ? 'PASS' : 'FAIL'}`);
return valid;
},
password(password) {
const issues = [];
if (password.length < 8) issues.push('at least 8 characters');
if (!/[A-Z]/.test(password)) issues.push('one uppercase letter');
if (!/[a-z]/.test(password)) issues.push('one lowercase letter');
if (!/[0-9]/.test(password)) issues.push('one number');
const valid = issues.length === 0;
log.info(`Password validation: ${valid ? 'PASS' : 'FAIL'}`, { issues });
return { valid, issues };
},
};
// ═════════════════════════════════════════════════════════════
// MODULE: UIRenderer — pure(ish) DOM updates based on user state
// ═════════════════════════════════════════════════════════════
const UIRenderer = {
display(user) {
if (!DOM.userDisplay) return;
const els = NodeList.prototype.isPrototypeOf(DOM.userDisplay) ? Array.from(DOM.userDisplay) : [DOM.userDisplay];
if (user) {
const firstName = computeFirstName(user);
const initial = firstName ? firstName.charAt(0).toUpperCase() : '';
els.forEach((el) => {
if (!el) return;
const tag = el.tagName?.toUpperCase();
if (tag === 'INPUT' || tag === 'TEXTAREA') el.value = initial;
else el.textContent = initial;
el.title = firstName;
});
log.info('User display updated', { initial, firstName });
} else {
els.forEach((el) => {
if (!el) return;
const tag = el.tagName?.toUpperCase();
if (tag === 'INPUT' || tag === 'TEXTAREA') el.value = '';
else el.textContent = '';
el.title = '';
});
log.info('User display cleared (no user)');
}
},
nameAndEmail(user) {
const name = user ? computeFirstName(user) : '';
const email = user?.email || '';
DOM.userNameElements.forEach((el) => {
if (!el) return;
const tag = el.tagName?.toUpperCase();
if (tag === 'INPUT' || tag === 'TEXTAREA') el.placeholder = name;
else el.textContent = name;
});
DOM.userEmailElements.forEach((el) => {
if (!el) return;
const tag = el.tagName?.toUpperCase();
if (tag === 'INPUT' || tag === 'TEXTAREA') el.value = email;
else el.textContent = email;
});
},
authClasses(user) {
const loggedOutEls = document.querySelectorAll('[lg-su-define="logged out"]');
const loggedInEls = document.querySelectorAll('[lg-su-define="logged in"]');
if (user) {
loggedOutEls.forEach((e) => e.classList.remove('no-user'));
loggedInEls.forEach((e) => e.classList.remove('no-user'));
log.info('Auth classes updated → LOGGED IN');
} else {
loggedOutEls.forEach((e) => e.classList.add('no-user'));
loggedInEls.forEach((e) => e.classList.add('no-user'));
log.info('Auth classes updated → LOGGED OUT');
}
},
enforceAuthRule(user) {
const requiresAuth = !!document.querySelector('meta[name="require-auth"][content="true"]');
if (requiresAuth && !user && DOM.panel) {
DOM.panel.classList.add('opened');
URLParamManager.updateFromUI();
log.info('Authentication required for this page. Forcing panel open.');
}
},
all(user) {
this.display(user);
this.nameAndEmail(user);
this.authClasses(user);
dispatchAuthEvent(user);
this.enforceAuthRule(user);
},
};
// ═════════════════════════════════════════════════════════════
// MODULE: FirebaseSync — realtime token exchange + lifecycle
// ═════════════════════════════════════════════════════════════
const FirebaseSync = {
async attach(session) {
if (!session) return;
try {
const res = await fetch(`${MESSAGING_WORKER_URL}/api/auth/firebase-token`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-User-Type': 'user',
Authorization: `Bearer ${session.access_token}`,
},
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Failed to exchange Firebase sync token');
await firebase.auth().signInWithCustomToken(data.custom_token);
window.db = firebase.database();
log.success('Firebase realtime session authorized and database initialized');
} catch (err) {
log.error('Firebase realtime synchronizer failed', err);
}
},
async detach() {
try {
await firebase.auth().signOut();
window.db = null;
log.success('Firebase realtime session signed out');
} catch (err) {
log.warn('Could not sign out of Firebase Auth cleanly', err);
}
},
};
// ═════════════════════════════════════════════════════════════
// MODULE: SessionManager — session lifecycle + UI refresh orchestration
// ═════════════════════════════════════════════════════════════
const SessionManager = {
async refreshUI() {
log.state('Refreshing UI based on session...');
const {
data: { user },
} = await supabase.auth.getUser();
state.currentUser = user;
window.currentUserState = user;
log.info('Session check result', {
hasSession: !!user,
userId: user?.id,
email: user?.email,
provider: user?.app_metadata?.provider,
});
UIRenderer.all(user);
if (user) {
const {
data: { session },
} = await supabase.auth.getSession();
FirebaseSync.attach(session);
}
},
async logout() {
log.info('━━━ LOGOUT TRIGGERED ━━━');
addProcessing(DOM.logoutBtn);
try {
await FirebaseSync.detach();
const { error } = await supabase.auth.signOut();
if (error) throw error;
removeProcessing(DOM.logoutBtn);
log.success('Logout SUCCESS');
this.refreshUI();
} catch (error) {
removeProcessing(DOM.logoutBtn);
log.error('Logout FAILED', { message: error.message });
}
},
subscribe() {
supabase.auth.onAuthStateChange((event, session) => {
log.state('Auth state change', {
event,
userId: session?.user?.id,
email: session?.user?.email,
});
if (session?.user) {
log.success('User SIGNED IN');
this.refreshUI();
if (DOM.panel) DOM.panel.classList.remove('opened');
URLParamManager.updateFromUI();
} else {
log.info('User SIGNED OUT');
this.refreshUI();
}
});
},
};
// ═════════════════════════════════════════════════════════════
// MODULE: JWT helpers (Fix #1)
// ═════════════════════════════════════════════════════════════
function decodeJwtPayload(jwt) {
try {
const part = jwt.split('.')[1];
if (!part) return null;
// base64url → base64
const b64 = part.replace(/-/g, '+').replace(/_/g, '/');
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);
const json = atob(padded);
return JSON.parse(json);
} catch (e) {
log.warn('Failed to decode JWT payload', e);
return null;
}
}
// Google hashes the nonce into the id_token claim. Supabase re-hashes
// what we pass to signInWithIdToken. So our client-side verify must
// SHA-256 the stored raw nonce before comparing.
async function verifyGoogleNonce(idToken, expectedRawNonce) {
const expected = expectedRawNonce || sessionStorage.getItem('googleAuthNonceRaw');
if (!expected) {
log.warn('No stored Google nonce — cannot verify redirect token');
return { ok: false, reason: 'missing_stored_nonce' };
}
const payload = decodeJwtPayload(idToken);
if (!payload || !payload.nonce) {
log.warn('Missing nonce claim in id_token');
return { ok: false, reason: 'missing_token_nonce' };
}
const hashed = await sha256Hex(expected);
if (payload.nonce !== hashed) {
log.warn('Nonce mismatch on id_token', { expectedHash: hashed, received: payload.nonce });
return { ok: false, reason: 'nonce_mismatch' };
}
log.success('Google id_token nonce VERIFIED');
return { ok: true };
}
// ═════════════════════════════════════════════════════════════
// MODULE: GoogleAuth — GIS init, redirect, credential handling
// ═════════════════════════════════════════════════════════════
const GoogleAuth = {
initGIS() {
if (state.gisInitialized) {
if (!state.currentUser) {
try {
this._renderGoogleButton();
} catch (e) {
log.warn('Google button re-render failed', e);
}
}
return;
}
if (state.googleLoaded) return;
const gisScript = document.createElement('script');
gisScript.src = 'https://accounts.google.com/gsi/client';
gisScript.async = true;
gisScript.defer = true;
gisScript.onload = () => {
state.googleLoaded = true;
log.success('Google Identity Services loaded');
try {
// One initialize() per page. Generate a raw nonce, pass it to
// Google (Google hashes it into the claim), and hand the same
// raw nonce to Supabase from the callback.
const rawNonce = crypto.randomUUID();
state.gisPromptNonce = rawNonce;
google.accounts.id.initialize({
client_id: GOOGLE_CLIENT_ID,
callback: (resp) => {
const captured = state.gisPromptNonce;
state.gisPromptNonce = null;
this.handleCredentialResponse(resp, { fromRedirect: false, rawNonce: captured });
},
auto_select: false,
cancel_on_tap_outside: true,
context: 'signin',
nonce: rawNonce,
use_fedcm_for_button: false,
});
state.gisInitialized = true;
if (!state.currentUser) {
this._renderGoogleButton();
} else {
log.info('User is already logged in. Skipping Google Sign-In button.');
}
log.success('Google Identity Services initialized');
} catch (e) {
log.warn('Google Identity Services initialize failed', e);
}
};
document.head.appendChild(gisScript);
},
_renderGoogleButton() {
const container = document.getElementById('google-signin-btn-container');
if (!container) {
log.warn('No #google-signin-btn-container found — Google button not rendered. Redirect flow remains available.');
return;
}
container.innerHTML = '';
google.accounts.id.renderButton(container, {
type: 'standard',
theme: 'outline',
size: 'large',
text: 'signin_with',
shape: 'rectangular',
width: 320,
});
log.info('Google Sign-In button rendered');
},
async startRedirect(intent) {
window._googleAuthIntent = intent;
state.pendingGoogleIntent = intent;
// Google OAuth redirect echoes the nonce we pass verbatim into the
// claim. Supabase re-hashes whatever we pass it. Therefore:
// → send Google the HASH (claim = hash)
// → keep the RAW for Supabase (re-hashed = hash)
const rawNonce = crypto.randomUUID();
const hashedNonce = await sha256Hex(rawNonce);
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth');
authUrl.searchParams.set('client_id', GOOGLE_CLIENT_ID);
authUrl.searchParams.set('response_type', 'id_token');
authUrl.searchParams.set('scope', 'openid profile email');
authUrl.searchParams.set('redirect_uri', window.location.origin + window.location.pathname);
authUrl.searchParams.set('nonce', hashedNonce);
authUrl.searchParams.set('prompt', 'select_account');
sessionStorage.setItem('googleAuthNonceRaw', rawNonce);
sessionStorage.setItem('authIntent', intent);
window.location.href = authUrl.toString();
},
/**
* Unified handler for both GIS button callback AND post-redirect id_token.
* Fix #1: verifies nonce for redirect flow.
* Fix #2: uses UsersTable.ensureProfile (idempotent upsert).
*/
async handleCredentialResponse(response, { fromRedirect = true, rawNonce = null } = {}) {
if (!response || !response.credential) {
log.error('No credential in Google response');
return;
}
let nonceForSupabase = null;
if (fromRedirect) {
const storedRaw = sessionStorage.getItem('googleAuthNonceRaw');
if (!storedRaw) {
log.error('Redirect return missing stored nonce (tab/session expired?)');
const target = state.pendingGoogleIntent === 'signup' ? DOM.suGoogleAuth : DOM.liGoogleAuth;
removeProcessing(target);
showError(target, 'Sign-in session expired. Please try again.');
state.pendingGoogleIdToken = null;
state.pendingGoogleIntent = null;
return;
}
const check = await verifyGoogleNonce(response.credential, storedRaw);
if (!check.ok) {
log.error('Rejecting Google id_token from redirect due to nonce failure', check.reason);
const target = state.pendingGoogleIntent === 'signup' ? DOM.suGoogleAuth : DOM.liGoogleAuth;
removeProcessing(target);
showError(target, 'Sign-in could not be verified. Please try again.');
state.pendingGoogleIdToken = null;
state.pendingGoogleIntent = null;
sessionStorage.removeItem('googleAuthNonceRaw');
sessionStorage.removeItem('authIntent');
return;
}
nonceForSupabase = storedRaw;
} else {
// GIS Sign In With Google button callback — raw nonce captured at
// initialize() time. Google hashed it into the claim; Supabase
// re-hashes it server-side to compare.
if (!rawNonce) {
log.warn('Google button callback had no captured raw nonce — Supabase will likely reject');
}
nonceForSupabase = rawNonce;
}
const intent = state.pendingGoogleIntent || window._googleAuthIntent;
try {
const { data, error } = await supabase.auth.signInWithIdToken({
provider: 'google',
token: response.credential,
...(nonceForSupabase ? { nonce: nonceForSupabase } : {}),
});
if (error) {
log.error('Supabase sign in error:', error);
const target = intent === 'signup' ? DOM.suGoogleAuth : DOM.liGoogleAuth;
removeProcessing(target);
showError(target, error.message);
return;
}
log.success('Google sign in successful');
const user = data.user;
if (intent === 'signup') {
removeProcessing(DOM.suGoogleAuth);
showSuccess(DOM.signUpForm, 'Signed up with Google successfully!');
} else if (intent === 'login') {
removeProcessing(DOM.liGoogleAuth);
showSuccess(DOM.loginForm, 'Logged in with Google successfully!');
}
SessionManager.refreshUI();
if (DOM.panel) DOM.panel.classList.remove('opened');
URLParamManager.updateFromUI();
window._googleAuthIntent = null;
state.pendingGoogleIntent = null;
state.pendingGoogleIdToken = null;
sessionStorage.removeItem('googleAuthNonceRaw');
sessionStorage.removeItem('authIntent');
} catch (err) {
log.error('Unexpected error during Google sign in:', err);
const target = intent === 'signup' ? DOM.suGoogleAuth : DOM.liGoogleAuth;
removeProcessing(target);
showError(target, 'An unexpected error occurred');
}
},
};
// ═════════════════════════════════════════════════════════════
// MODULE: FormHandlers — email signup / login / google buttons
// ═════════════════════════════════════════════════════════════
const FormHandlers = {
async emailSignUp() {
log.info('━━━ EMAIL SIGN UP TRIGGERED ━━━');
clearErrors(DOM.signUpForm);
const firstName = DOM.suFirstName?.value?.trim();
const lastName = DOM.suLastName?.value?.trim();
const email = DOM.suEmail?.value?.trim();
const password = DOM.suPassword?.value;
log.info('Sign up form data:', {
firstName,
lastName,
email,
password: password ? '***' : undefined,
});
if (!firstName) {
showError(DOM.suFirstName, 'First name is required');
return;
}
if (!email) {
showError(DOM.suEmail, 'Email is required');
return;
}
if (!Validators.email(email)) {
showError(DOM.suEmail, 'Please enter a valid email address');
return;
}
if (!password) {
showError(DOM.suPassword, 'Password is required');
return;
}
const pwCheck = Validators.password(password);
if (!pwCheck.valid) {
showError(DOM.suPassword, `Password needs: ${pwCheck.issues.join(', ')}`);
return;
}
log.success('All validations PASSED');
addProcessing(DOM.suTrigger);
try {
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
data: {
first_name: firstName,
last_name: lastName || '',
full_name: `${firstName}${lastName ? ' ' + lastName : ''}`,
terms_accepted: false,
},
},
});
if (error) throw error;
removeProcessing(DOM.suTrigger);
log.success('Sign up SUCCESS', { userId: data.user.id, email: data.user.email });
showSuccess(DOM.signUpForm, 'Check your email for a confirmation link.');
} catch (error) {
removeProcessing(DOM.suTrigger);
log.error('Sign up FAILED', { message: error.message, code: error.code });
showError(DOM.suTrigger, error.message);
}
},
async googleSignUp() {
log.info('━━━ GOOGLE SIGN UP TRIGGERED ━━━');
clearErrors(DOM.signUpForm);
addProcessing(DOM.suGoogleAuth);
await GoogleAuth.startRedirect('signup');
},
async emailLogin() {
log.info('━━━ EMAIL LOGIN TRIGGERED ━━━');
clearErrors(DOM.loginForm);
const email = DOM.liEmail?.value?.trim();
const password = DOM.liPassword?.value;
log.info('Login form data:', { email, password: password ? '***' : undefined });
if (!email) {
showError(DOM.liEmail, 'Email is required');
return;
}
if (!Validators.email(email)) {
showError(DOM.liEmail, 'Please enter a valid email address');
return;
}
if (!password) {
showError(DOM.liPassword, 'Password is required');
return;
}
log.success('All validations PASSED');
addProcessing(DOM.liTrigger);
try {
const { data, error } = await supabase.auth.signInWithPassword({ email, password });
if (error) throw error;
removeProcessing(DOM.liTrigger);
log.success('Login SUCCESS', {
userId: data.user.id,
email: data.user.email,
lastSignIn: data.user.last_sign_in_at,
});
showSuccess(DOM.loginForm, 'Logged in successfully!');
SessionManager.refreshUI();
if (DOM.panel) DOM.panel.classList.remove('opened');
URLParamManager.updateFromUI();
} catch (error) {
removeProcessing(DOM.liTrigger);
log.error('Login FAILED', { message: error.message, code: error.code });
showError(DOM.liTrigger, error.message);
}
},
async googleLogin() {
log.info('━━━ GOOGLE LOGIN TRIGGERED ━━━');
clearErrors(DOM.loginForm);
if (!DOM.liGoogleAuth) return;
addProcessing(DOM.liGoogleAuth);
await GoogleAuth.startRedirect('login');
},
};
// ═════════════════════════════════════════════════════════════
// MODULE: PanelController — open/close toggles + auth gate
// ═════════════════════════════════════════════════════════════
const PanelController = {
bind() {
document.querySelectorAll('[lg-sup-control="start"]').forEach((trigger) => {
trigger.addEventListener('click', () => {
if (DOM.panel) DOM.panel.classList.add('opened');
URLParamManager.updateFromUI();
log.info('Panel opened via start trigger');
});
});
document.querySelectorAll('[lg-sup-control="finish"]').forEach((trigger) => {
trigger.addEventListener('click', () => {
const requiresAuth = !!document.querySelector('meta[name="require-auth"][content="true"]');
if (requiresAuth && !state.currentUser) {
log.warn('Close action blocked: This page requires authentication.');
return;
}
if (DOM.panel) DOM.panel.classList.remove('opened');
URLParamManager.updateFromUI();
log.info('Panel closed via finish trigger');
});
});
},
};
// ═════════════════════════════════════════════════════════════
// MODULE: EventWiring — attach listener handlers
// ═════════════════════════════════════════════════════════════
function wireEvents() {
log.info('Attaching event listeners...');
let listenersAttached = 0;
if (DOM.suTrigger) {
DOM.suTrigger.addEventListener('click', FormHandlers.emailSignUp);
listenersAttached++;
log.success(' ✓ Email Sign Up trigger listener attached');
}
if (DOM.suGoogleAuth) {
DOM.suGoogleAuth.addEventListener('click', FormHandlers.googleSignUp);
listenersAttached++;
log.success(' ✓ Google Sign Up trigger listener attached');
}
if (DOM.liTrigger) {
DOM.liTrigger.addEventListener('click', FormHandlers.emailLogin);
listenersAttached++;
log.success(' ✓ Email Login trigger listener attached');
}
if (DOM.liGoogleAuth) {
DOM.liGoogleAuth.addEventListener('click', FormHandlers.googleLogin);
listenersAttached++;
log.success(' ✓ Google Login trigger listener attached');
}
if (DOM.logoutBtn) {
DOM.logoutBtn.addEventListener('click', () => SessionManager.logout());
listenersAttached++;
log.success(' ✓ Logout trigger listener attached');
}
if (DOM.suPassword) {
DOM.suPassword.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
FormHandlers.emailSignUp();
}
});
}
if (DOM.liPassword) {
DOM.liPassword.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
FormHandlers.emailLogin();
}
});
}
const formChoiceEls = document.querySelectorAll('[lg-su-element="user-li-form"], [lg-su-element="user-su-form"]');
formChoiceEls.forEach((el) => {
el.addEventListener('click', () => {
const val = el.getAttribute('lg-su-element');
const targetFormAttr = val;
const targetForm = document.querySelector(`[${targetFormAttr}]`);
const otherForm = targetFormAttr === 'user-su-form' ? document.querySelector('[user-li-form]') : document.querySelector('[user-su-form]');
if (targetForm) targetForm.classList.remove('nochoice');
if (otherForm) {
otherForm.classList.add('nochoice');
// Clear inputs in the form being moved away from
const formInputs = otherForm.querySelectorAll('input[type="text"], input[type="email"], input[type="password"], input[type="checkbox"]');
formInputs.forEach((input) => {
if (input.type === 'checkbox') {
input.checked = false;
} else {
input.value = '';
}
});
log.info(`Cleared inputs in ${targetFormAttr === 'user-su-form' ? 'login' : 'sign up'} form`);
}
URLParamManager.updateFromUI();
log.info('Form choice toggled', { target: targetFormAttr });
});
listenersAttached++;
});
log.info(`Total listeners attached: ${listenersAttached}`);
}
// ═════════════════════════════════════════════════════════════
// BOOTSTRAP — Supabase client + redirect-token pickup + init
// ═════════════════════════════════════════════════════════════
log.success('Supabase SDK loaded');
// Capture redirect id_token BEFORE anything else, clean URL immediately.
if (window.location.hash) {
const hashParams = new URLSearchParams(window.location.hash.substring(1));
const idToken = hashParams.get('id_token');
if (idToken) {
history.replaceState(null, '', window.location.pathname + window.location.search);
state.pendingGoogleIdToken = idToken;
state.pendingGoogleIntent = sessionStorage.getItem('authIntent') || 'login';
window._googleAuthIntent = state.pendingGoogleIntent;
sessionStorage.removeItem('authIntent');
sessionStorage.removeItem('authReturnUrl');
// NOTE: googleAuthNonceRaw is intentionally NOT removed here — it is
// needed for verification inside GoogleAuth.handleCredentialResponse.
}
}
if (!SUPABASE_URL || SUPABASE_URL.includes('xxxxxxxxxxxx')) {
log.warn('DEFAULT CREDENTIALS — Replace SUPABASE_URL with your actual Supabase project URL!');
}
if (!SUPABASE_ANON_KEY || SUPABASE_ANON_KEY === 'your-anon-key-here') {
log.warn('DEFAULT CREDENTIALS — Replace SUPABASE_ANON_KEY with your actual Supabase anon key!');
}
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
window.supabaseClient = supabase;
log.success('Supabase client created');
log.info('Supabase config detected', { url: SUPABASE_URL });
// DOM presence audit (unchanged behavior, just relocated)
Object.entries(DOM).forEach(([key, el]) => {
if (key === 'panel') return; // panel is optional; still log it
if (el) {
if (NodeList.prototype.isPrototypeOf(el)) {
log.success(` ✓ ${key} — found`, `NodeList (${el.length})`);
} else {
log.success(` ✓ ${key} — found`, el.tagName);
}
} else {
log.warn(` ✗ ${key} — NOT FOUND in DOM`);
}
});
// Async coordinator — order preserved exactly from original
async function initializeAuthFlows() {
// 1. Session check first, so EnforceAuthRule + Google button decision are accurate
await SessionManager.refreshUI();
// 2. Handle Google redirect return, if any
if (state.pendingGoogleIdToken) {
log.info('Processing pending Google ID token from redirect...');
window._googleAuthIntent = state.pendingGoogleIntent;
await GoogleAuth.handleCredentialResponse({ credential: state.pendingGoogleIdToken }, { fromRedirect: true });
state.pendingGoogleIdToken = null;
} else if (!state.currentUser) {
log.info('No active session. Initializing Google Identity Services...');
GoogleAuth.initGIS();
// 💡 FIX: Defer applying URL params slightly to allow Webflow's interaction engine
// to fully load first, and only auto-open the panel if the user is logged out.
setTimeout(() => {
URLParamManager.applyFromURL();
URLParamManager.updateFromUI(); // Sync the parameters safely
}, 150);
} else {
log.info('Active session detected. Google Identity Services auto-prompt bypassed.');
// If already logged in, clean up our auth parameters safely without touching others
URLParamManager.updateFromUI();
}
log.success('━━━ SUPABASE AUTH SETUP COMPLETE ━━━');
}
// Wire everything up
wireEvents();
PanelController.bind();
SessionManager.subscribe();
initializeAuthFlows();
}