Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
feat(auth): sign in with Google
spacesdrive4780b6d1de5f
diff --git a/.github/workflows/deploy-frontend.yml b/.github/workflows/deploy-frontend.ymlindex 6d156d2..ed2184d 100644--- a/.github/workflows/deploy-frontend.yml+++ b/.github/workflows/deploy-frontend.yml@@ -33,6 +33,7 @@ jobs:VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }}VITE_API_URL: ${{ secrets.VITE_API_URL }}VITE_ADMIN_EMAIL: ${{ secrets.VITE_ADMIN_EMAIL }}+ VITE_GOOGLE_CLIENT_ID: ${{ secrets.VITE_GOOGLE_CLIENT_ID }}- name: Deploy to Cloudflare Pagesuses: cloudflare/wrangler-action@v4diff --git a/frontend/.env.example b/frontend/.env.exampleindex d5b8413..0a2dbd4 100644--- a/frontend/.env.example+++ b/frontend/.env.example@@ -12,3 +12,9 @@ VITE_API_URL=https://twiligent.your-subdomain.workers.dev/api# Shown to people who need Instagram tester access or whose scheduled posts# are not publishing. Defaults to [email protected] when unset.++# ── Sign in with Google (optional) ───────────────────────────────────────────+# Web client ID from Google Auth Platform, Clients. Public by design.+# Leave unset to hide the Google button. Also enable Google in Supabase,+# Authentication, Sign In / Providers, with the same client ID.+VITE_GOOGLE_CLIENT_ID=1234567890-abc.apps.googleusercontent.comdiff --git a/frontend/src/components/GoogleSignInButton.jsx b/frontend/src/components/GoogleSignInButton.jsxnew file mode 100644index 0000000..dda5c5d--- /dev/null+++ b/frontend/src/components/GoogleSignInButton.jsx@@ -0,0 +1,60 @@+import { useEffect, useRef, useState } from 'react';+import { useTheme } from 'next-themes';+import { Skeleton } from '@/components/ui/skeleton';+import { GOOGLE_CLIENT_ID, createNonce, loadGoogleIdentity } from '@/lib/googleIdentity';++// Google renders its own button inside an iframe; its width is capped at 400px by Google.+const MAX_WIDTH = 400;++export default function GoogleSignInButton({ onCredential, onError, text = 'continue_with' }) {+ const containerRef = useRef(null);+ const handlers = useRef({ onCredential, onError });+ const { resolvedTheme } = useTheme();+ const [ready, setReady] = useState(false);++ useEffect(() => {+ handlers.current = { onCredential, onError };+ }, [onCredential, onError]);++ useEffect(() => {+ if (!GOOGLE_CLIENT_ID) return undefined;+ let cancelled = false;++ (async () => {+ try {+ const [gsi, nonce] = await Promise.all([loadGoogleIdentity(), createNonce()]);+ if (cancelled || !containerRef.current) return;+ gsi.initialize({+ client_id: GOOGLE_CLIENT_ID,+ nonce: nonce.hashed,+ use_fedcm_for_button: true,+ callback: response => handlers.current.onCredential(response.credential, nonce.raw),+ });+ containerRef.current.replaceChildren();+ gsi.renderButton(containerRef.current, {+ type: 'standard',+ theme: resolvedTheme === 'dark' ? 'filled_black' : 'outline',+ size: 'large',+ shape: 'rectangular',+ text,+ logo_alignment: 'center',+ width: Math.min(containerRef.current.offsetWidth || MAX_WIDTH, MAX_WIDTH),+ });+ setReady(true);+ } catch (err) {+ if (!cancelled) handlers.current.onError?.(err);+ }+ })();++ return () => { cancelled = true; };+ }, [resolvedTheme, text]);++ if (!GOOGLE_CLIENT_ID) return null;++ return (+ <div className="relative min-h-10 w-full">+ {!ready && <Skeleton className="absolute inset-0 h-10 rounded-control" />}+ <div ref={containerRef} className="flex w-full justify-center [color-scheme:normal]" />+ </div>+ );+}diff --git a/frontend/src/context/AuthContext.jsx b/frontend/src/context/AuthContext.jsxindex 74c8be1..665a803 100644--- a/frontend/src/context/AuthContext.jsx+++ b/frontend/src/context/AuthContext.jsx@@ -20,10 +20,14 @@ export function AuthProvider({ children }) {const signUp = (email, password) =>supabase.auth.signUp({ email, password });+ // Google's button returns an ID token; the raw nonce lets Supabase confirm the token was issued for this sign-in.+ const signInWithGoogle = (idToken, nonce) =>+ supabase.auth.signInWithIdToken({ provider: 'google', token: idToken, nonce });+const signOut = () => supabase.auth.signOut();return (- <AuthContext.Provider value={{ session, user: session?.user ?? null, signIn, signUp, signOut }}>+ <AuthContext.Provider value={{ session, user: session?.user ?? null, signIn, signUp, signInWithGoogle, signOut }}>{children}</AuthContext.Provider>);diff --git a/frontend/src/lib/googleIdentity.js b/frontend/src/lib/googleIdentity.jsnew file mode 100644index 0000000..224612c--- /dev/null+++ b/frontend/src/lib/googleIdentity.js@@ -0,0 +1,36 @@+export const GOOGLE_CLIENT_ID = import.meta.env?.VITE_GOOGLE_CLIENT_ID || '';++const GSI_SRC = 'https://accounts.google.com/gsi/client';+let scriptPromise = null;++// Loads Google Identity Services once per page; later calls reuse the same promise.+export function loadGoogleIdentity() {+ if (typeof window !== 'undefined' && window.google?.accounts?.id) return Promise.resolve(window.google.accounts.id);+ if (!scriptPromise) {+ scriptPromise = new Promise((resolve, reject) => {+ const script = document.createElement('script');+ script.src = GSI_SRC;+ script.async = true;+ script.onload = () => (window.google?.accounts?.id ? resolve(window.google.accounts.id) : reject(new Error('Google sign-in did not start.')));+ script.onerror = () => {+ scriptPromise = null;+ reject(new Error('Google sign-in could not load. Check your connection or any content blocker, then try again.'));+ };+ document.head.appendChild(script);+ });+ }+ return scriptPromise;+}++export async function sha256Hex(text) {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));+ return Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, '0')).join('');+}++// Google embeds the hashed nonce in the ID token; Supabase receives the raw one and checks they match,+// so a captured token cannot be replayed.+export async function createNonce() {+ const bytes = crypto.getRandomValues(new Uint8Array(32));+ const raw = btoa(String.fromCharCode(...bytes)).replace(/[+/=]/g, '');+ return { raw, hashed: await sha256Hex(raw) };+}diff --git a/frontend/src/lib/googleIdentity.test.js b/frontend/src/lib/googleIdentity.test.jsnew file mode 100644index 0000000..c68c5fa--- /dev/null+++ b/frontend/src/lib/googleIdentity.test.js@@ -0,0 +1,18 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createNonce, sha256Hex } from './googleIdentity.js';++test('sha256Hex matches the known digest', async () => {+ assert.equal(await sha256Hex('abc'), 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');+});++test('createNonce returns a raw nonce and its SHA-256 hash', async () => {+ const { raw, hashed } = await createNonce();+ assert.match(raw, /^[A-Za-z0-9]{40,}$/);+ assert.equal(hashed, await sha256Hex(raw));+});++test('each nonce is different', async () => {+ const [a, b] = await Promise.all([createNonce(), createNonce()]);+ assert.notEqual(a.raw, b.raw);+});diff --git a/frontend/src/pages/Login.jsx b/frontend/src/pages/Login.jsxindex db6ac60..1625cee 100644--- a/frontend/src/pages/Login.jsx+++ b/frontend/src/pages/Login.jsx@@ -7,9 +7,11 @@ import { Input } from '@/components/ui/input';import { Spinner } from '@/components/ui/spinner';import { FieldRow } from '@/components/DetailPanel';import { Logo } from '@/components/brand/Logo';+import GoogleSignInButton from '@/components/GoogleSignInButton';+import { GOOGLE_CLIENT_ID } from '@/lib/googleIdentity';export default function Login() {- const { signIn, signUp } = useAuth();+ const { signIn, signUp, signInWithGoogle } = useAuth();const navigate = useNavigate();const [mode, setMode] = useState('login');const [email, setEmail] = useState('');@@ -38,6 +40,19 @@ export default function Login() {}}+ async function handleGoogleCredential(idToken, nonce) {+ setLoading(true);+ try {+ const { error } = await signInWithGoogle(idToken, nonce);+ if (error) throw error;+ navigate('/');+ } catch (err) {+ toast.error(`Couldn't sign in with Google. ${err.message}`);+ } finally {+ setLoading(false);+ }+ }+return (<div className="grid min-h-svh bg-surface lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]"><main className="flex flex-col px-6 py-8 sm:px-10">@@ -55,6 +70,21 @@ export default function Login() {</p></div>+ {GOOGLE_CLIENT_ID && (+ <div className="flex flex-col gap-5">+ <GoogleSignInButton+ text={isLogin ? 'continue_with' : 'signup_with'}+ onCredential={handleGoogleCredential}+ onError={err => toast.error(err.message)}+ />+ <div className="flex items-center gap-3 text-caption text-ink-faint" role="separator" aria-label="or use email">+ <span className="h-px flex-1 bg-divider" />+ or use email+ <span className="h-px flex-1 bg-divider" />+ </div>+ </div>+ )}+<form onSubmit={handleSubmit} className="flex flex-col gap-5"><FieldRow label="Email" htmlFor="email"><Input