The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Accounts: Continue with Google and Continue with GitHub
Adarshd5a7dad35715
diff --git a/docs/SELF-HOSTING.md b/docs/SELF-HOSTING.mdindex 35145a96..14e52439 100644--- a/docs/SELF-HOSTING.md+++ b/docs/SELF-HOSTING.md@@ -125,6 +125,8 @@ A file that looks like the note but was changed (it has a password or a sign-in| `FUOBE_PASSWORD` | Turns sign-in on; a password set this way can't be changed from Settings || `FUOBE_ALLOWED_ORIGINS` | Extra hosts Fuobe is reached at, comma-separated. Without a password, Fuobe answers only on IP addresses, localhost, single-label and LAN names (`.local`, `.lan`, `.home.arpa`, `.internal`) and the machine's hostname; add any other domain (a reverse proxy, a tunnel, a Tailscale name), or `*` to turn the check off. Also counts as "same site" for the cross-site write check behind a proxy that forwards neither Host nor X-Forwarded-Host || `FUOBE_TRUST_PROXY=1` | Behind a reverse proxy: trust the last `X-Forwarded-For` hop, so wrong passwords, and too many wrong share links, lock out only that visitor (60 s). Without it, everyone shares one limit: passwords are slowed to one attempt every 4 s and never locked, and wrong share links past 100 a minute get 429 while real links still open |+| `FUOBE_OAUTH_GOOGLE_ID`, `FUOBE_OAUTH_GOOGLE_SECRET` | With public sign-up: **Continue with Google** on the sign-in and sign-up forms. Both must be set; off otherwise. **Settings → Security → Sign in with Google** switches it off and on again without a restart. Register `<your site>/api/auth/oauth/google/callback` as an authorized redirect URI of the OAuth client ([Google and GitHub](public-signup.md#google-and-github)) |+| `FUOBE_OAUTH_GITHUB_ID`, `FUOBE_OAUTH_GITHUB_SECRET` | With public sign-up: **Continue with GitHub**. Both must be set; off otherwise. **Settings → Security → Sign in with GitHub** switches it. Register `<your site>/api/auth/oauth/github/callback` as the OAuth app's authorization callback URL || `FUOBE_ALLOW_PRIVATE_URLS=1` | Let inputs, product links and project sources be fetched from private / LAN addresses (they are refused by default), and let Assist connectors use plain http beyond localhost (without it a connector needs https unless it is on localhost; a private https address is accepted, with a warning that Claude can only reach it through a public tunnel) || `FUOBE_DATA_DIR` | Where the database (with the sign-in data) and files live (default `./data`). Back up `secrets.key` there with `fuobe.db`: it opens the fal.ai and Replicate keys accounts saved ([Your keys](public-signup.md#your-keys)), which must be added again without it || `FUOBE_AUTH_REIMPORT=1` | For one start only: an `auth.json` in the data folder when the server starts, after sign-in data moved into the database, replaces the database's sign-in data, instead of being set aside unread ([Sign-in data](#sign-in-data)). It counts only for the server's first look after it starts. Remove it after that start |diff --git a/docs/billing-hook.md b/docs/billing-hook.mdindex 26b2a34f..c8a47cb8 100644--- a/docs/billing-hook.md+++ b/docs/billing-hook.md@@ -42,7 +42,7 @@ twice: the service must treat a repeated call (the same `requestId`, or the sameAll JSON. Times are Unix milliseconds. Amounts are whole numbers in the service's own unit.```ts-type AccountFacts = { id: string; email: string | null; emailVerified: boolean; signIn: "google" | "password"; createdAt: number; adultAt: number | null };+type AccountFacts = { id: string; email: string | null; emailVerified: boolean; signIn: "google" | "github" | "password"; createdAt: number; adultAt: number | null };type Place = "own-gpu" | "own-key" | "pool" | "install-key";type RunFacts = {place: Place; model: string; op: string | null; app: string | null; preset: string | null; studio: string;@@ -78,6 +78,11 @@ type Policy = {};```+`AccountFacts.signIn` is how the account signed in last: `"password"` (its email and password), or `"google"` or+`"github"` (Continue with Google or GitHub, [public-signup.md](public-signup.md#google-and-github)). `emailVerified` is+true once the account has signed in with a provider that verified its email; an email changed later is not verified+until that happens again.+`cardText` is what a preset card says when its run would go to this install's GPUs for the viewer, such as "Try free"(at most 40 characters). With a service set, the cards say only these words, and nothing when the policy has none.With no service, runs there are free (`FUOBE_HOSTED_FREE=1`), and the cards say "Try free".diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 006d9d88..c058457d 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -58,6 +58,8 @@ takes an account's GPU type from the status strip's last check and asks the GPUstill works as before: `POST /api/auth/login` with `{ "password" }`, or the owner's sign-in at`/login?owner=1`. The login page links to it only in development, so a public site doesn'tadvertise it.+- Or **Continue with Google** or **Continue with GitHub**, when the install has set them up+ ([Google and GitHub](#google-and-github)).- Accounts are stored in the database (`fuobe.db` in the data folder, table `auth_accounts`): theemail in lower case (one account per email), a salted scrypt hash of the password (the same schemeas the install password), and the creation time. An install from before this kept them in@@ -157,6 +159,50 @@ An account is signed in, but it sees the owner's studio as a guest does:export id answers 404. The last part answers 201 with the run, within the same run budget (429) and through thesame checks (422).+## Google and GitHub++An install can let visitors sign up and log in with Google or GitHub as well as with an email and a+password. It is off unless the install sets a provider's client id and secret, and it works only+while public sign-up is on. The owner's sign-in (the install password) doesn't change.++| Provider | Variables | Callback URL to register |+|---|---|---|+| Google (an OAuth client of type "Web application") | `FUOBE_OAUTH_GOOGLE_ID`, `FUOBE_OAUTH_GOOGLE_SECRET` | `<your site>/api/auth/oauth/google/callback` |+| GitHub (an OAuth app) | `FUOBE_OAUTH_GITHUB_ID`, `FUOBE_OAUTH_GITHUB_SECRET` | `<your site>/api/auth/oauth/github/callback` |++`<your site>` is the address visitors open, with its scheme (`https://studio.example.com`). Behind a+reverse proxy, the proxy must send `X-Forwarded-Host` and `X-Forwarded-Proto` (or the original `Host`),+so the callback address matches the one registered.++- **Switching one off.** **Settings → Security → Sign in with Google** and **Sign in with GitHub**+ (settings `oauthGoogle` and `oauthGithub`, `on` or `off`) show for each provider whose id and+ secret are set. They are on by default; off hides the button and closes its routes at once, with no+ restart.+- **The buttons.** With a provider set up, the sign-in and sign-up forms show **Continue with Google**+ and **Continue with GitHub** above the email form. `GET /api/auth/me` lists the providers that are+ on (`oauth: ["google", "github"]`) while sign-up is open.+- **The flow.** `GET /api/auth/oauth/<provider>?next=<path>` sends the browser to the provider (the+ authorization-code flow, with PKCE). A random `state` is kept for 10 minutes in an HttpOnly cookie+ signed with the install's secret, and the callback (`GET /api/auth/oauth/<provider>/callback`)+ takes the code only with that browser's state. `next` must be a path on this site: anything else+ goes to the home page. Both routes answer 404 while the provider isn't set up or sign-up is off.+- **A verified email only.** Google's email counts only when Google says it is verified. GitHub's+ counts only when it is the account's primary email and verified. Without one, the login page says+ so, and no account is made.+- **Which account.** A provider's user signs in to the account linked to it before (by the provider's+ own user id), else to the account with the same email, which is then linked. Otherwise an account+ is made as sign-up makes one, within the same sign-up limits for the visitor, and a new account goes+ to the welcome page first. A switched-off account can't log in this way either. Only the provider's+ user id is kept (table `auth_oauth_links`), never a code or a token. The account's email then counts+ as confirmed, and an optional billing service hears `emailVerified: true` and `signIn: "google"` or+ `"github"` ([billing-hook.md](billing-hook.md)).+- **No password at first.** An account made with a provider has no password: no password logs in to+ it. **Settings → Account → Set a password** gives it one (`PATCH /api/auth/me` with+ `{ "next" }`), and deleting it asks for no password. Both need a sign-in with the provider in the+ last 10 minutes; past that they answer 403 with `code: "sign-in-again"`, and the page offers+ **Continue with Google** (or GitHub) again.+- Codes, tokens and the client secret are never logged. A failed provider call logs its status only.+## Managing accountsThe owner sees everyone who signed up in **Settings → Accounts**, the last section of Settings (the@@ -217,7 +263,8 @@ and `totals`; `?format=csv` for the file), `PATCH /api/admin/accounts/<id>` withneeds `runs:read` and `outputs:view`, and `accounts:read` for the email) and`DELETE /api/admin/generations/<id>` (an account's run only).-An account can delete itself: `DELETE /api/auth/me` with `{ "password" }`. When an account is+An account can delete itself: `DELETE /api/auth/me` with `{ "password" }` (an account made with Google+or GitHub that has no password: a recent sign-in with it instead, [Google and GitHub](#google-and-github)). When an account isdeleted (by itself or by the owner), its runs are stopped and removed, and its uploads and resultsare deleted with it.diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex ea3b21b2..bd7a03f3 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -1,7 +1,7 @@import { cookies } from "next/headers";import { z } from "zod";import { accountEvent, accountFacts } from "@/server/billing";-import { authEnabled, createSession, LoginGuard, normalizeEmail, publicSignup, recordLogin, SESSION_COOKIE, verifyAccount, verifyPassword } from "@/server/auth";+import { authEnabled, createSession, LoginGuard, noteSignIn, normalizeEmail, publicSignup, recordLogin, SESSION_COOKIE, verifyAccount, verifyPassword } from "@/server/auth";import { enter, hit } from "@/server/rate";/** The install password alone (the owner), or an account's email and password (public sign-up). */@@ -97,7 +97,7 @@ export async function POST(request: Request) {if (account.disabled) return Response.json({ error: "This account can't log in." }, { status: 403 });accountId = account.id;recordLogin(account.id);- accountEvent("signed-in", accountFacts(account));+ accountEvent("signed-in", accountFacts(noteSignIn(account, "password")));} else {const wait = ownerGuard().blockedFor(key);if (wait > 0) return tooMany(wait, key);diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsindex 9fe5a30c..3acf9cea 100644--- a/src/app/api/auth/me/route.ts+++ b/src/app/api/auth/me/route.ts@@ -1,7 +1,25 @@import { cookies } from "next/headers";import { connection } from "next/server";import { z } from "zod";-import { AccountError, accountGpu, authEnabled, createSession, publicSignup, SESSION_COOKIE, sessionCookieOf, sessionViewer, setAccountPassword, validToken, verifyAccount } from "@/server/auth";+import {+ AccountError,+ accountGpu,+ accountHasPassword,+ accountProviders,+ authEnabled,+ createSession,+ publicSignup,+ SESSION_COOKIE,+ sessionCookieOf,+ sessionIssuedAt,+ sessionViewer,+ setAccountPassword,+ setFirstAccountPassword,+ validToken,+ verifyAccount,+ type Account,+} from "@/server/auth";+import { oauthProviders, PROVIDER_NAME } from "@/server/oauth";import { runnerFacts } from "@/server/computer/tasks";import { getSetting } from "@/server/settings";import { soundLive } from "@/server/sound-live";@@ -21,12 +39,22 @@ export async function GET(request: Request) {const comfyPort = computer ? runnerFacts(account ? `acct:${account.id}` : "owner")?.port : undefined;// The sound features that have passed a real run (src/server/sound-live.ts): their switches start on and show to everyone.const live = Object.entries(soundLive()).flatMap(([k, v]) => (v ? [k] : []));+ // Continue with Google or GitHub: the providers this install set up, while sign-up is open.+ const oauth = open ? oauthProviders() : [];+ const linked = account ? accountProviders(account.id) : [];return Response.json({signedIn: owner || !!account,owner,publicSignup: open,- ...(account && { account: { email: account.email } }),+ ...(oauth.length && { oauth }),+ ...(account && {+ account: {+ email: account.email,+ ...(linked.length && { providers: linked }),+ ...(!accountHasPassword(account) && { noPassword: true }),+ },+ }),...(computer && { computer: true, ...(comfyPort && { comfyPort }) }),...(live.length && { soundLive: live }),},@@ -49,18 +77,42 @@ function notAnAccount(request: Request, signedOut: string, owner: string): Resporeturn Response.json({ error: isOwner ? owner : signedOut }, { status: isOwner ? 403 : 401 });}-/** An account deletes itself (its password again, to be sure). Signs it out. */+/**+ * An account made with Google or GitHub has no password to enter again: deleting it or setting its first password asks+ * for a sign-in with the provider in the last 10 minutes instead.+ */+const RECENT_SIGN_IN_MS = 10 * 60_000;++/** This session's sign-in was in the last 10 minutes. */+const recentSignIn = (cookie: string | undefined) => (sessionIssuedAt(cookie) ?? 0) >= Date.now() - RECENT_SIGN_IN_MS;++/** 403 `sign-in-again`: the page offers the account's provider, and comes back here. */+function signInAgain(account: Account, then: string): Response {+ const p = accountProviders(account.id).find((x) => oauthProviders().includes(x));+ const name = p ? PROVIDER_NAME[p] : "your provider";+ return Response.json(+ { error: `To keep your account safe, continue with ${name} again, then ${then} within 10 minutes.`, code: "sign-in-again", ...(p && { provider: p }) },+ { status: 403 },+ );+}++/** An account deletes itself (its password again, to be sure; or a recent sign-in with its provider). Signs it out. */export async function DELETE(request: Request) {const jar = await cookies();- const session = sessionViewer(sessionCookieOf(request));+ const cookie = sessionCookieOf(request);+ const session = sessionViewer(cookie);const ownerRefusal = "This deletes an account, not the studio";if (!session) return notAnAccount(request, "You're signed out. Log in again to delete your account.", ownerRefusal);if (session.kind !== "account") return Response.json({ error: ownerRefusal }, { status: 403 });- const parsed = z.object({ password: z.string().min(1).max(500) }).safeParse(await request.json().catch(() => null));- if (!parsed.success) return Response.json({ error: "Wrong password" }, { status: 403 });- const rate = passwordCheck(session.account.id);- if (!rate.ok) return Response.json({ error: "Too many tries. Wait a minute, then try again." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });- if (!(await verifyAccount(session.account.email, parsed.data.password))) return Response.json({ error: "Wrong password" }, { status: 403 });+ if (!accountHasPassword(session.account)) {+ if (!recentSignIn(cookie)) return signInAgain(session.account, "delete your account");+ } else {+ const parsed = z.object({ password: z.string().min(1).max(500) }).safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Wrong password" }, { status: 403 });+ const rate = passwordCheck(session.account.id);+ if (!rate.ok) return Response.json({ error: "Too many tries. Wait a minute, then try again." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });+ if (!(await verifyAccount(session.account.email, parsed.data.password))) return Response.json({ error: "Wrong password" }, { status: 403 });+ }// Switched off at once, its running jobs stopped (on its own keys), then its runs, files and record go.await removeAccount(session.account.id);jar.delete(SESSION_COOKIE);@@ -68,17 +120,19 @@ export async function DELETE(request: Request) {}const NewPassword = z.object({- current: z.string().max(500),+ /** Left out by an account setting its first password (made with Google or GitHub). */+ current: z.string().max(500).optional(),next: z.string().min(8, "Use at least 8 characters").max(500, "Use at most 500 characters"),});/**- * An account changes its password (the current one first, to be sure). Its other sign-ins end; this browser gets a new- * session cookie.+ * An account changes its password (the current one first, to be sure), or sets its first one (made with Google or+ * GitHub: a recent sign-in with the provider instead). Its other sign-ins end; this browser gets a new session cookie.*/export async function PATCH(request: Request) {const jar = await cookies();- const session = sessionViewer(sessionCookieOf(request));+ const cookie = sessionCookieOf(request);+ const session = sessionViewer(cookie);const ownerRefusal = "This changes an account's password, not the studio's";if (!session) return notAnAccount(request, "You're signed out. Log in again to change your password.", ownerRefusal);if (session.kind !== "account") return Response.json({ error: ownerRefusal }, { status: 403 });@@ -87,12 +141,18 @@ export async function PATCH(request: Request) {const next = parsed.error.issues.find((i) => i.path[0] === "next");return Response.json({ error: next?.message ?? "Enter your current password and a new one" }, { status: 400 });}+ // Made with Google or GitHub: its first password, after a recent sign-in with the provider (no current one to enter).+ const first = !accountHasPassword(session.account);+ if (first && !recentSignIn(cookie)) return signInAgain(session.account, "set your password");+ const current = parsed.data.current;+ if (!first && current === undefined) return Response.json({ error: "Enter your current password and a new one" }, { status: 400 });// Not a change: it would sign the other browsers out for nothing. (Two of the request's own words: no password check.)- if (parsed.data.next === parsed.data.current) return Response.json({ error: "Choose a new password, not the one you use now" }, { status: 400 });+ if (!first && parsed.data.next === current) return Response.json({ error: "Choose a new password, not the one you use now" }, { status: 400 });const rate = passwordCheck(session.account.id);if (!rate.ok) return Response.json({ error: "Too many tries. Wait a minute, then try again." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });try {- await setAccountPassword(session.account.id, parsed.data.current, parsed.data.next);+ if (first) await setFirstAccountPassword(session.account.id, parsed.data.next);+ else await setAccountPassword(session.account.id, current ?? "", parsed.data.next);} catch (e) {if (e instanceof AccountError) return Response.json({ error: e.message }, { status: e.status });throw e;diff --git a/src/app/api/auth/oauth/[provider]/callback/route.ts b/src/app/api/auth/oauth/[provider]/callback/route.tsnew file mode 100644index 00000000..4286499e--- /dev/null+++ b/src/app/api/auth/oauth/[provider]/callback/route.ts@@ -0,0 +1,120 @@+import { cookies } from "next/headers";+import { connection } from "next/server";+import { welcomePath } from "@/lib/after-signup";+import { safeNext } from "@/lib/safe-redirect";+import {+ AccountError,+ accountWithEmail,+ createOAuthAccount,+ createSession,+ linkOAuth,+ LoginGuard,+ noteSignIn,+ oauthLinkedAccount,+ publicSignup,+ recordLogin,+ SESSION_COOKIE,+ type Account,+} from "@/server/auth";+import { accountEvent, accountFacts } from "@/server/billing";+import { hostedRunsOn } from "@/server/hosted-switch";+import {+ identityFor,+ isOAuthProvider,+ oauthEnabled,+ readState,+ sameState,+ siteOrigin,+ STATE_COOKIE,+ STATE_PATH,+ stateCookieFrom,+ type OAuthErrorCode,+ type OAuthState,+} from "@/server/oauth";+import { hit } from "@/server/rate";+import { beginSignup, signupMade } from "@/server/signup-limits";++/**+ * Provider callbacks a minute (each one calls the provider from this server): per visitor behind a trusted proxy, and+ * for everyone together without one.+ */+const PER_CLIENT_A_MINUTE = 30;+const SHARED_A_MINUTE = 300;++/**+ * The provider sends the browser back here after its sign-in. The code counts only with the state this browser's cookie+ * holds (a code meant for another browser, or a link someone sent, signs nobody in). The account is found by the+ * provider's user id, then by its verified email; with neither, one is made as sign-up makes one (the same limits). A+ * switched-off account stays out. Then the session cookie is set as a log-in sets it, and the browser goes on to `next`+ * (a new account first to the welcome page). Anything that doesn't work goes back to the login page, which says why.+ */+export async function GET(request: Request, ctx: RouteContext<"/api/auth/oauth/[provider]/callback">) {+ await connection();+ const { provider } = await ctx.params;+ if (!isOAuthProvider(provider) || !oauthEnabled(provider) || !publicSignup(request.headers.get("host"))) {+ return Response.json({ error: "This way of signing in isn't available here." }, { status: 404, headers: { "Cache-Control": "no-store" } });+ }+ const url = new URL(request.url);+ const site = siteOrigin(request);+ const secure = url.protocol === "https:";+ const jar = await cookies();+ const saved = readState(stateCookieFrom(request.headers.get("cookie")));+ // A state counts once.+ jar.set(STATE_COOKIE, "", { httpOnly: true, sameSite: "lax", secure, path: STATE_PATH, maxAge: 0 });+ const go = (path: string) => new Response(null, { status: 303, headers: { Location: `${site}${path}`, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" } });+ const back = (code: OAuthErrorCode) => go(loginPath(code, provider, saved));++ if (!saved || saved.provider !== provider || !sameState(url.searchParams.get("state"), saved.state)) return back("expired");+ if (url.searchParams.get("error")) return back("cancelled");+ const code = url.searchParams.get("code");+ if (!code || code.length > 4096) return back("failed");+ const key = LoginGuard.clientKey(request.headers);+ const rate = key === LoginGuard.DIRECT ? hit("oauth:shared", SHARED_A_MINUTE, 60_000) : hit(`oauth:${key}`, PER_CLIENT_A_MINUTE, 60_000);+ if (!rate.ok) return back("busy");++ const who = await identityFor(saved, code);+ if (!who.ok) return back(who.reason);+ // Public sign-up may have been switched off while the visitor was at the provider.+ if (!publicSignup(request.headers.get("host"))) return back("failed");++ let account: Account | undefined = oauthLinkedAccount(provider, who.subject) ?? accountWithEmail(who.email);+ let made = false;+ if (!account) {+ const refused = beginSignup(key);+ if (refused) return back("busy");+ try {+ account = createOAuthAccount(who.email, provider, who.subject);+ made = true;+ signupMade(key);+ } catch (e) {+ // Made a moment ago by another request with the same email: that account is this one's.+ if (!(e instanceof AccountError) || e.status !== 409) throw e;+ account = accountWithEmail(who.email);+ if (!account) return back("failed");+ }+ }+ if (account.disabled) return back("disabled");+ if (made) {+ // An optional billing service hears of it (none set: nothing is sent).+ accountEvent("created", accountFacts(account));+ } else {+ linkOAuth(account.id, provider, who.subject);+ recordLogin(account.id);+ // Signed in with the provider, whose email is verified: the account's email counts as confirmed from now on.+ account = noteSignIn(account, provider);+ accountEvent("signed-in", accountFacts(account));+ }+ const s = createSession(account.id);+ jar.set(SESSION_COOKIE, s.value, { httpOnly: true, sameSite: "lax", secure, path: "/", maxAge: s.maxAge });+ const after = safeNext(saved.next, site);+ // With hosted runs on, a GPU of its own is optional: straight back to where it was.+ return go(made && !hostedRunsOn() ? welcomePath(after, site) : after);+}++/** The form the visitor came from, with why it came back, and where it was headed. */+function loginPath(code: OAuthErrorCode, provider: string, saved: OAuthState | null): string {+ const q = new URLSearchParams({ oauth_error: code, provider });+ if (saved?.mode === "signup") q.set("signup", "1");+ if (saved && saved.next !== "/") q.set("next", saved.next);+ return `/login?${q}`;+}diff --git a/src/app/api/auth/oauth/[provider]/route.ts b/src/app/api/auth/oauth/[provider]/route.tsnew file mode 100644index 00000000..8153acfc--- /dev/null+++ b/src/app/api/auth/oauth/[provider]/route.ts@@ -0,0 +1,32 @@+import { cookies } from "next/headers";+import { connection } from "next/server";+import { publicSignup } from "@/server/auth";+import { authorizeUrl, callbackUrl, isOAuthProvider, newState, oauthEnabled, siteOrigin, STATE_COOKIE, STATE_MS, STATE_PATH } from "@/server/oauth";+import { safeNext } from "@/lib/safe-redirect";++/**+ * Continue with Google or GitHub: sends the browser to the provider to sign in, with a new state kept in a short-lived+ * HttpOnly cookie (src/server/oauth.ts). `next`: a path on this site to go to after (anything else goes home); `mode`:+ * "signup" when it came from the sign-up form, so a refusal goes back to it. 404 while the provider isn't set up or+ * public sign-up is off.+ */+export async function GET(request: Request, ctx: RouteContext<"/api/auth/oauth/[provider]">) {+ await connection();+ const { provider } = await ctx.params;+ const client = isOAuthProvider(provider) ? oauthEnabled(provider) : null;+ if (!client || !isOAuthProvider(provider) || !publicSignup(request.headers.get("host"))) {+ return Response.json({ error: "This way of signing in isn't available here." }, { status: 404, headers: { "Cache-Control": "no-store" } });+ }+ const url = new URL(request.url);+ const site = siteOrigin(request);+ const next = safeNext(url.searchParams.get("next"), site);+ const { state, cookie } = newState(provider, next, callbackUrl(site, provider), url.searchParams.get("mode") === "signup" ? "signup" : "login");+ (await cookies()).set(STATE_COOKIE, cookie, {+ httpOnly: true,+ sameSite: "lax",+ secure: url.protocol === "https:",+ path: STATE_PATH,+ maxAge: STATE_MS / 1000,+ });+ return new Response(null, { status: 303, headers: { Location: authorizeUrl(state, client.id), "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" } });+}diff --git a/src/app/api/auth/public/route.ts b/src/app/api/auth/public/route.tsindex 2acce224..e26eef24 100644--- a/src/app/api/auth/public/route.ts+++ b/src/app/api/auth/public/route.ts@@ -1,6 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { authEnabled, publicSignup, publicSignupFromEnv, publicSignupSetting, sessionCookieOf, setPublicSignup, validSession } from "@/server/auth";+import { oauthStatus } from "@/server/oauth";const status = (request: Request) => ({/** The Settings switch. */@@ -9,6 +10,8 @@ const status = (request: Request) => ({fromEnv: publicSignupFromEnv(),/** On for this address right now. */active: publicSignup(request.headers.get("host")),+ /** Continue with Google or GitHub: whether each one's client id and secret are set, and the owner's switch (Settings: oauthGoogle, oauthGithub). */+ oauth: oauthStatus(),});/** Settings → Security: public sign-up (guests browse read-only, anyone can make an account). */diff --git a/src/app/api/auth/signup/route.ts b/src/app/api/auth/signup/route.tsindex e31519f8..654f80b7 100644--- a/src/app/api/auth/signup/route.ts+++ b/src/app/api/auth/signup/route.ts@@ -2,40 +2,21 @@ import { cookies } from "next/headers";import { z } from "zod";import { accountEvent, accountFacts } from "@/server/billing";import { AccountError, createAccount, createSession, LoginGuard, publicSignup, SESSION_COOKIE } from "@/server/auth";-import { hit, peek } from "@/server/rate";+import { beginSignup, signupMade } from "@/server/signup-limits";const Body = z.object({ email: z.string().max(254), password: z.string().max(500) });-declare global {- var __fuobeSignupGuard: LoginGuard | undefined;-}-/**- * Every sign-up that could make an account counts, made or not: a client makes at most 5 a minute, and everyone slows- * down past 20. A request without an email and a password counts for nothing, so it can't slow anyone else down.- */-const guard = () => (globalThis.__fuobeSignupGuard ??= new LoginGuard());/**- * Accounts a day from one address. One address can be a whole office, class or mobile network, so this is a ceiling- * for scripts, not for people: all accounts together keep at most a share of the disk anyway (account-files.ts).+ * Public sign-up: an account from an email and a password (8+ characters, no verification), signed in at once. A request+ * without an email and a password counts for nothing, so it can't slow anyone else down (src/server/signup-limits.ts).*/-const SIGNUPS_A_DAY = 20;-const DAY = 24 * 60 * 60_000;--/** Public sign-up: an account from an email and a password (8+ characters, no verification), signed in at once. */export async function POST(request: Request) {if (!publicSignup(request.headers.get("host"))) return Response.json({ error: "Sign-up is closed right now." }, { status: 404 });const key = LoginGuard.clientKey(request.headers);const parsed = Body.safeParse(await request.json().catch(() => null));if (!parsed.success) return Response.json({ error: "Enter an email and a password" }, { status: 400 });- const wait = guard().blockedFor(key);- if (wait > 0) {- const secs = Math.ceil(wait / 1000);- return Response.json({ error: `Too many sign-ups. Try again in ${secs} second${secs === 1 ? "" : "s"}.` }, { status: 429, headers: { "Retry-After": String(secs) } });- }- guard().fail(key);- // At most 20 accounts a day from one address (the shared key, without a trusted proxy, is everyone: not capped here).- const today = key === LoginGuard.DIRECT ? null : peek(`signup-day:${key}`, SIGNUPS_A_DAY, DAY);- if (today && !today.ok) return Response.json({ error: "That's a lot of new accounts from one network today. Try again tomorrow." }, { status: 429, headers: { "Retry-After": String(today.retryAfterS) } });+ const refused = beginSignup(key);+ if (refused) return Response.json({ error: refused.error }, { status: 429, headers: { "Retry-After": String(refused.retryAfterS) } });let account;try {account = createAccount(parsed.data.email, parsed.data.password);@@ -43,7 +24,7 @@ export async function POST(request: Request) {if (e instanceof AccountError) return Response.json({ error: e.message }, { status: e.status });throw e;}- if (key !== LoginGuard.DIRECT) hit(`signup-day:${key}`, SIGNUPS_A_DAY, DAY);+ signupMade(key);// An optional billing service hears of it (none set: nothing is sent).accountEvent("created", accountFacts(account));const s = createSession(account.id);diff --git a/src/components/google-mark.tsx b/src/components/google-mark.tsxnew file mode 100644index 00000000..78f1a765--- /dev/null+++ b/src/components/google-mark.tsx@@ -0,0 +1,23 @@+/** Google's "G" in its own four colours (lucide has no brand icons). */+export function GoogleMark({ className }: { className?: string }) {+ return (+ <svg viewBox="0 0 48 48" aria-hidden className={className}>+ <path+ fill="#EA4335"+ d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"+ />+ <path+ fill="#4285F4"+ d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"+ />+ <path+ fill="#FBBC05"+ d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"+ />+ <path+ fill="#34A853"+ d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"+ />+ </svg>+ );+}diff --git a/src/components/login-form.tsx b/src/components/login-form.tsxindex 95541845..32bba84e 100644--- a/src/components/login-form.tsx+++ b/src/components/login-form.tsx@@ -6,8 +6,9 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation";import { useEffect, useState } from "react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";-import { isWay } from "@/lib/ai-setup/ways";-import { announceAuthChange, rememberViewer, signOut, useStatus, useViewer } from "@/lib/api";+import { OAuthButtons, PROVIDER_LABEL } from "@/components/oauth-buttons";+import { welcomePath } from "@/lib/after-signup";+import { announceAuthChange, rememberViewer, signOut, useStatus, useViewer, type OAuthProviderId } from "@/lib/api";import { safeNext } from "@/lib/safe-redirect";import { cn } from "@/lib/utils";@@ -17,6 +18,27 @@ type Mode = "signup" | "login" | "owner";/** On a public site the owner's sign-in isn't advertised: production builds open it at /login?owner=1. */const OWNER_LINK = process.env.NODE_ENV !== "production";+/** Why a sign-in with Google or GitHub came back here (?oauth_error=, src/app/api/auth/oauth/[provider]/callback). */+function oauthMessage(code: string | null, provider: string | null): string | null {+ const name = provider === "google" || provider === "github" ? PROVIDER_LABEL[provider as OAuthProviderId] : "your provider";+ switch (code) {+ case "expired":+ return "That sign-in took a while or started in another browser. Please try again.";+ case "cancelled":+ return `Signing in with ${name} was cancelled. You can try again, or use your email.`;+ case "unverified":+ return `Your ${name} account has no verified email address yet. Verify one with ${name}, or sign up with your email.`;+ case "disabled":+ return "This account can't log in.";+ case "busy":+ return "Lots of sign-ins right now. Please try again in a minute.";+ case "failed":+ return `We couldn't finish signing in with ${name}. Please try again in a moment.`;+ default:+ return null;+ }+}+const COPY: Record<Mode, { title: string; lead: string; button: string }> = {signup: { title: "Create your free account", lead: "Just an email and a password. You're in within seconds.", button: "Sign up" },login: { title: "Welcome back", lead: "Log in with your email and password.", button: "Log in" },@@ -40,6 +62,10 @@ export function LoginForm() {const [shown, setShown] = useState(false);const [busy, setBusy] = useState(false);const next = safeNext(params.get("next"), typeof window === "undefined" ? "http://localhost" : window.location.origin);+ // Continue with Google or GitHub: only the providers this studio set up, and never on the owner's sign-in.+ const providers = mode === "owner" ? [] : (viewer.data?.oauth ?? []);+ // A provider sign-in that came back here, until the visitor does something else.+ const [oauthError, setOauthError] = useState(() => oauthMessage(params.get("oauth_error"), params.get("provider")));// Sign up and log in have their own tab title (the page's metadata says "Sign in" for both).useEffect(() => {@@ -50,6 +76,7 @@ export function LoginForm() {const choose = (m: Mode) => {setChosen(m);setError(null);+ setOauthError(null);setTaken(false);if (m === "owner") return;const q = new URLSearchParams(params.toString());@@ -65,25 +92,16 @@ export function LoginForm() {e.preventDefault();setBusy(true);setError(null);+ setOauthError(null);const url = mode === "signup" ? "/api/auth/signup" : "/api/auth/login";const body = mode === "owner" ? { password } : { email, password };const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });if (res.ok) {// Only a page on this site: never bounce to another origin after signing in.const after = safeNext(params.get("next"), window.location.origin);- // A new account connects its GPU first (the pre-flight board), then goes on to where it was headed. Not back to- // Settings' Your GPU (its Sign up free): the welcome page is that same choice.- const q = new URLSearchParams({ welcome: "1" });- if (after !== "/" && !after.startsWith("/connect") && !after.startsWith("/settings#your-gpu")) q.set("next", after);- // "Set it up with my AI" (a guest's sign-up from it): the welcome page opens with it, on the link's way.- const nextUrl = new URL(after, window.location.origin);- if (nextUrl.pathname === "/connect" && nextUrl.searchParams.get("setup") === "ai") {- q.set("setup", "ai");- const way = nextUrl.searchParams.get("way");- if (isWay(way)) q.set("way", way);- }- // With hosted runs on, a GPU of its own is optional: straight back to where it was.- const dest = mode === "signup" && !hosted ? new URL(`/connect?${q}`, window.location.origin).toString() : after;+ // A new account connects its GPU first (the welcome page), then goes on to where it was headed. With hosted runs+ // on, a GPU of its own is optional: straight back to where it was.+ const dest = mode === "signup" && !hosted ? welcomePath(after, window.location.origin) : after;rememberViewer(mode === "owner" ? "owner" : "account");announceAuthChange();window.location.assign(dest);@@ -123,6 +141,9 @@ export function LoginForm() {}const copy = COPY[mode];+ // With Google or GitHub on, the lead names them first.+ const names = providers.map((p) => PROVIDER_LABEL[p]).join(" or ");+ const lead = !names ? copy.lead : mode === "signup" ? `Continue with ${names}, or use an email and a password.` : `Log in with ${names}, or with your email and password.`;const short = mode === "signup" && password.length > 0 && password.length < 8;return (<form onSubmit={submit} className="w-full max-w-sm animate-fade-up rounded-2xl border bg-background p-7 shadow-soft">@@ -130,7 +151,22 @@ export function LoginForm() {{mode === "signup" ? <Sparkles className="size-5" /> : <Lock className="size-5" />}</div><h1 className="font-heading text-[28px] leading-tight">{copy.title}</h1>- <p className="mt-1 text-[13px] text-muted-foreground">{copy.lead}</p>+ <p className="mt-1 text-[13px] text-muted-foreground">{lead}</p>+ {oauthError && !error && (+ <p role="alert" className="mt-4 text-[13px] text-destructive">+ {oauthError}+ </p>+ )}+ {providers.length > 0 && (+ <>+ <OAuthButtons providers={providers} next={next} mode={mode === "signup" ? "signup" : "login"} className="mt-5" />+ <div className="mt-5 flex items-center gap-3 text-[12px] text-muted-foreground" role="separator" aria-label="or">+ <span className="h-px flex-1 bg-border" />+ or+ <span className="h-px flex-1 bg-border" />+ </div>+ </>+ )}{mode !== "owner" && (<Inputtype="email"@@ -142,7 +178,7 @@ export function LoginForm() {placeholder="Email"value={email}onChange={(e) => setEmail(e.target.value)}- className="mt-5 h-11"+ className={cn(providers.length > 0 ? "mt-4" : "mt-5", "h-11")}aria-invalid={!!error}/>)}diff --git a/src/components/oauth-buttons.tsx b/src/components/oauth-buttons.tsxnew file mode 100644index 00000000..c54f3a84--- /dev/null+++ b/src/components/oauth-buttons.tsx@@ -0,0 +1,43 @@+import { Button } from "@/components/ui/button";+import { GitHubMark } from "@/components/github-mark";+import { GoogleMark } from "@/components/google-mark";+import type { OAuthProviderId } from "@/lib/api";+import { cn } from "@/lib/utils";++export const PROVIDER_LABEL: Record<OAuthProviderId, string> = { google: "Google", github: "GitHub" };++/** Where "Continue with …" goes: the provider's sign-in, then back to `next` (a path on this site). */+export function oauthHref(p: OAuthProviderId, next: string, mode: "signup" | "login"): string {+ const q = new URLSearchParams({ mode });+ if (next !== "/") q.set("next", next);+ return `/api/auth/oauth/${p}?${q}`;+}++/** "Continue with Google" and "Continue with GitHub": full-page links to the provider (GET /api/auth/oauth/<provider>). */+export function OAuthButtons({+ providers,+ next,+ mode,+ className,+ size = "lg",+}: {+ providers: OAuthProviderId[];+ next: string;+ mode: "signup" | "login";+ className?: string;+ size?: "lg" | "sm";+}) {+ if (!providers.length) return null;+ return (+ <div className={cn("grid gap-2.5", className)}>+ {providers.map((p) => (+ <Button key={p} asChild variant="outline" className={cn("w-full gap-2.5", size === "lg" ? "h-11" : "h-9")}>+ <a href={oauthHref(p, next, mode)}>+ {p === "google" ? <GoogleMark className="size-[18px]" /> : <GitHubMark className="size-[18px]" />}+ Continue with {PROVIDER_LABEL[p]}+ </a>+ </Button>+ ))}+ </div>+ );+}diff --git a/src/components/owner-settings.tsx b/src/components/owner-settings.tsxindex 17fe058f..cc71e1db 100644--- a/src/components/owner-settings.tsx+++ b/src/components/owner-settings.tsx@@ -10,8 +10,9 @@ import { Button } from "@/components/ui/button";import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";+import { OAuthButtons } from "@/components/oauth-buttons";import { useHashAnchor } from "@/components/use-hash-anchor";-import { announceAuthChange, leaveNotice, rememberViewer, signInHref, signOut, useHydrated, useViewer } from "@/lib/api";+import { announceAuthChange, leaveNotice, rememberViewer, signInHref, signOut, useHydrated, useViewer, type OAuthProviderId, type ViewerInfo } from "@/lib/api";import { FUOBE_REPO } from "@/lib/connections";import { cn } from "@/lib/utils";@@ -40,7 +41,7 @@ export function OwnerSettings({ children }: { children: React.ReactNode }) {return (<>{v.account ? (- <AccountSection email={v.account.email} />+ <AccountSection account={v.account} />) : (<section className="space-y-3 border-b py-8"><h2 className="text-[15px] font-semibold">Run Fuobe on your own GPU</h2>@@ -101,11 +102,24 @@ function Licences() {);}+/** Where an account made with Google or GitHub signs in again before it sets a password or deletes itself. */+const ACCOUNT_AGAIN = "/settings#account";++/** The answer's 403 `sign-in-again` (an account with no password, signed in a while ago): the provider to offer. */+async function signInAgainOf(res: Response): Promise<{ error?: string; provider?: OAuthProviderId }> {+ const body = (await res.json().catch(() => ({}))) as { error?: string; code?: string; provider?: string };+ const provider = body.code === "sign-in-again" && (body.provider === "google" || body.provider === "github") ? body.provider : undefined;+ return { error: body.error, provider };+}+/**- * An account's own: changing its password, signing out, and deleting it (its password again, DELETE /api/auth/me),- * which takes its runs, files and GPU with it.+ * An account's own: changing its password (or setting its first one, when it was made with Google or GitHub), signing+ * out, and deleting it (its password again, or a recent sign-in with its provider: DELETE /api/auth/me), which takes+ * its runs, files and GPU with it.*/-function AccountSection({ email }: { email: string }) {+function AccountSection({ account }: { account: NonNullable<ViewerInfo["account"]> }) {+ const { email } = account;+ const noPassword = !!account.noPassword;const id = useId();const qc = useQueryClient();const [open, setOpen] = useState(false);@@ -115,6 +129,8 @@ function AccountSection({ email }: { email: string }) {const [error, setError] = useState("");// The password was wrong (403): only then is its field marked, not for "too many tries" or no answer.const [wrong, setWrong] = useState(false);+ // No password, and the sign-in was a while ago: the provider to continue with first.+ const [again, setAgain] = useState<OAuthProviderId | undefined>();// A link to /settings#account arrives before this section exists: it is scrolled to once it does.useHashAnchor("account", true);const remove = async (e: React.FormEvent) => {@@ -122,8 +138,9 @@ function AccountSection({ email }: { email: string }) {setBusy(true);setError("");setWrong(false);+ setAgain(undefined);try {- const res = await fetch("/api/auth/me", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ password }) });+ const res = await fetch("/api/auth/me", { method: "DELETE", headers: { "Content-Type": "application/json" }, body: JSON.stringify(noPassword ? {} : { password }) });if (res.status === 204) {// This browser's other tabs hear it, then a full load (as a guest's): the page and every cached answer were the// account's. The home page says it was deleted, which a sign-out alone would look the same as.@@ -144,9 +161,10 @@ function AccountSection({ email }: { email: string }) {announceAuthChange();return;}- const body = (await res.json().catch(() => ({}))) as { error?: string };+ const body = await signInAgainOf(res);setError(body.error ?? `The account wasn't deleted (${res.status})`);- setWrong(res.status === 403);+ setAgain(body.provider);+ setWrong(res.status === 403 && !noPassword);} catch {setError("We couldn't reach Fuobe. Check your connection and try again.");}@@ -163,7 +181,7 @@ function AccountSection({ email }: { email: string }) {<div className="min-w-0 space-y-6"><div className="flex flex-wrap gap-2"><Button size="sm" variant="secondary" onClick={() => setChanging(true)}>- <KeyRound /> Change password+ <KeyRound /> {noPassword ? "Set a password" : "Change password"}</Button><Button size="sm" variant="ghost" onClick={() => void signOut()}><LogOut /> Sign out@@ -179,7 +197,7 @@ function AccountSection({ email }: { email: string }) {</Button></div></div>- <ChangePassword email={email} open={changing} onOpenChange={setChanging} />+ <ChangePassword email={email} first={noPassword} open={changing} onOpenChange={setChanging} /><Dialogopen={open}onOpenChange={(o) => {@@ -188,6 +206,7 @@ function AccountSection({ email }: { email: string }) {setPassword("");setError("");setWrong(false);+ setAgain(undefined);}}><DialogContent className="sm:max-w-md">@@ -195,36 +214,47 @@ function AccountSection({ email }: { email: string }) {<DialogHeader><DialogTitle>Delete your account?</DialogTitle><DialogDescription>- {email} and everything you made with it go for good. Enter your password to confirm.+ {email} and everything you made with it go for good.{noPassword ? "" : " Enter your password to confirm."}</DialogDescription></DialogHeader>- <div className="space-y-1.5">- <Label htmlFor={`${id}-password`} className="text-[13px]">- Password- </Label>- <Input- id={`${id}-password`}- type="password"- autoComplete="current-password"- value={password}- onChange={(e) => setPassword(e.target.value)}- aria-invalid={wrong}- aria-describedby={error ? `${id}-error` : undefined}- autoFocus- />- {error && (- <p id={`${id}-error`} role="alert" className="text-[12px] text-destructive">- {error}- </p>- )}- </div>+ {noPassword ? (+ error && (+ <div className="space-y-3">+ <p id={`${id}-error`} role="alert" className="text-[13px] text-destructive">+ {error}+ </p>+ {again && <OAuthButtons providers={[again]} next={ACCOUNT_AGAIN} mode="login" size="sm" />}+ </div>+ )+ ) : (+ <div className="space-y-1.5">+ <Label htmlFor={`${id}-password`} className="text-[13px]">+ Password+ </Label>+ <Input+ id={`${id}-password`}+ type="password"+ autoComplete="current-password"+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ aria-invalid={wrong}+ aria-describedby={error ? `${id}-error` : undefined}+ autoFocus+ />+ {error && (+ <p id={`${id}-error`} role="alert" className="text-[12px] text-destructive">+ {error}+ </p>+ )}+ </div>+ )}<DialogFooter><DialogClose asChild><Button type="button" variant="ghost" disabled={busy}>Cancel</Button></DialogClose>- <Button type="submit" variant="destructive" disabled={busy || !password}>+ <Button type="submit" variant="destructive" disabled={busy || (!noPassword && !password)}>{busy && <Loader2 className="animate-spin" />}Delete account</Button>@@ -257,9 +287,10 @@ function PasswordInput({ id, shown, onShow, ...props }: React.ComponentProps<typ/*** Settings → Account → Change password (PATCH /api/auth/me): the current password, then the new one. Every other- * browser signed in to the account is signed out; this one stays signed in.+ * browser signed in to the account is signed out; this one stays signed in. `first`: an account made with Google or+ * GitHub sets its first password (no current one; the server asks for a recent sign-in with the provider instead).*/-function ChangePassword({ email, open, onOpenChange }: { email: string; open: boolean; onOpenChange: (open: boolean) => void }) {+function ChangePassword({ email, first, open, onOpenChange }: { email: string; first: boolean; open: boolean; onOpenChange: (open: boolean) => void }) {const id = useId();const qc = useQueryClient();const [current, setCurrent] = useState("");@@ -269,6 +300,7 @@ function ChangePassword({ email, open, onOpenChange }: { email: string; open: boconst [error, setError] = useState("");// The current password was wrong (403): only then is its field marked, not for "too many tries" or no answer.const [wrong, setWrong] = useState(false);+ const [again, setAgain] = useState<OAuthProviderId | undefined>();const short = next.length > 0 && next.length < 8;const reset = () => {setCurrent("");@@ -276,18 +308,23 @@ function ChangePassword({ email, open, onOpenChange }: { email: string; open: bosetShown(false);setError("");setWrong(false);+ setAgain(undefined);};const save = async (e: React.FormEvent) => {e.preventDefault();setBusy(true);setError("");setWrong(false);+ setAgain(undefined);try {- const res = await fetch("/api/auth/me", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ current, next }) });+ const res = await fetch("/api/auth/me", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ current: first ? "" : current, next }) });if (res.ok) {- toast.success("Password changed", { description: "You're still signed in here. Any other browser signed in to your account is signed out." });+ toast.success(first ? "Password set" : "Password changed", {+ description: first ? "You can now log in with your email and this password too." : "You're still signed in here. Any other browser signed in to your account is signed out.",+ });reset();onOpenChange(false);+ if (first) void qc.invalidateQueries({ queryKey: ["viewer"] });} else if (res.status === 401) {// This browser was signed out (the password was changed in another one): the page shows Log in instead.setBusy(false);@@ -299,9 +336,10 @@ function ChangePassword({ email, open, onOpenChange }: { email: string; open: boannounceAuthChange();return;} else {- const body = (await res.json().catch(() => ({}))) as { error?: string };+ const body = await signInAgainOf(res);setError(body.error ?? `The password wasn't changed (${res.status})`);- setWrong(res.status === 403);+ setAgain(body.provider);+ setWrong(res.status === 403 && !first);}} catch {setError("We couldn't reach Fuobe. Check your connection and try again.");@@ -320,27 +358,33 @@ function ChangePassword({ email, open, onOpenChange }: { email: string; open: bo<DialogContent className="sm:max-w-md"><form onSubmit={save} className="space-y-4"><DialogHeader>- <DialogTitle>Change your password</DialogTitle>- <DialogDescription>Changing your password signs out every other browser where you're signed in. You stay signed in here.</DialogDescription>+ <DialogTitle>{first ? "Set a password" : "Change your password"}</DialogTitle>+ <DialogDescription>+ {first+ ? "Then you can log in with your email and this password as well. You stay signed in here."+ : "Changing your password signs out every other browser where you're signed in. You stay signed in here."}+ </DialogDescription></DialogHeader>{/* The account's email, for password managers: they update its saved login rather than save a new one. */}<input type="email" name="username" autoComplete="username" value={email} readOnly hidden />- <div className="space-y-1.5">- <Label htmlFor={`${id}-current`} className="text-[13px]">- Current password- </Label>- <PasswordInput- id={`${id}-current`}- shown={shown}- onShow={() => setShown((s) => !s)}- autoComplete="current-password"- value={current}- onChange={(e) => setCurrent(e.target.value)}- aria-invalid={wrong}- aria-describedby={error ? `${id}-error` : undefined}- autoFocus- />- </div>+ {!first && (+ <div className="space-y-1.5">+ <Label htmlFor={`${id}-current`} className="text-[13px]">+ Current password+ </Label>+ <PasswordInput+ id={`${id}-current`}+ shown={shown}+ onShow={() => setShown((s) => !s)}+ autoComplete="current-password"+ value={current}+ onChange={(e) => setCurrent(e.target.value)}+ aria-invalid={wrong}+ aria-describedby={error ? `${id}-error` : undefined}+ autoFocus+ />+ </div>+ )}<div className="space-y-1.5"><Label htmlFor={`${id}-new`} className="text-[13px]">New password@@ -352,6 +396,7 @@ function ChangePassword({ email, open, onOpenChange }: { email: string; open: boautoComplete="new-password"value={next}onChange={(e) => setNext(e.target.value)}+ autoFocus={first}aria-invalid={short}aria-describedby={`${id}-hint`}/>@@ -364,15 +409,16 @@ function ChangePassword({ email, open, onOpenChange }: { email: string; open: bo{error}</p>)}+ {again && <OAuthButtons providers={[again]} next={ACCOUNT_AGAIN} mode="login" size="sm" />}<DialogFooter><DialogClose asChild><Button type="button" variant="ghost" disabled={busy}>Cancel</Button></DialogClose>- <Button type="submit" disabled={busy || !current || next.length < 8}>+ <Button type="submit" disabled={busy || (!first && !current) || next.length < 8}>{busy && <Loader2 className="animate-spin" />}- Change password+ {first ? "Set password" : "Change password"}</Button></DialogFooter></form>diff --git a/src/components/security-settings.tsx b/src/components/security-settings.tsxindex 00b7a4a3..41b1e438 100644--- a/src/components/security-settings.tsx+++ b/src/components/security-settings.tsx@@ -273,6 +273,54 @@ interface PublicSignupStatus {setting: boolean;fromEnv: boolean | null;active: boolean;+ /** Continue with Google or GitHub: its client id and secret are set on the server, and the owner's switch. */+ oauth?: { provider: "google" | "github"; configured: boolean; on: boolean }[];+}++const OAUTH_SWITCH = { google: { name: "oauthGoogle", label: "Sign in with Google", env: "FUOBE_OAUTH_GOOGLE_ID" }, github: { name: "oauthGithub", label: "Sign in with GitHub", env: "FUOBE_OAUTH_GITHUB_ID" } } as const;++/**+ * Settings → Security → Sign in with Google / GitHub, under Public sign-up: a switch for each provider whose client id and+ * secret are set on the server (PUT /api/settings oauthGoogle / oauthGithub, "on" or "off"). Off hides its button at once.+ */+function OAuthSwitches({ status }: { status: PublicSignupStatus }) {+ const qc = useQueryClient();+ const id = useId();+ const [busy, setBusy] = useState<string | null>(null);+ const configured = (status.oauth ?? []).filter((o) => o.configured);+ if (!configured.length) {+ return (+ <p className="text-[12px] text-muted-foreground">+ To offer Continue with Google or GitHub, set FUOBE_OAUTH_GOOGLE_ID and FUOBE_OAUTH_GOOGLE_SECRET, or FUOBE_OAUTH_GITHUB_ID and FUOBE_OAUTH_GITHUB_SECRET, on the server.+ </p>+ );+ }+ const set = async (provider: "google" | "github", on: boolean) => {+ setBusy(provider);+ try {+ await call("/api/settings", "PUT", { [OAUTH_SWITCH[provider].name]: on ? "on" : "off" });+ await qc.invalidateQueries({ queryKey: ["auth", "public"] });+ void qc.invalidateQueries({ queryKey: ["viewer"] });+ void qc.invalidateQueries({ queryKey: ["settings"] });+ } catch (e) {+ toastError(e);+ } finally {+ setBusy(null);+ }+ };+ return (+ <div className="space-y-2 pt-2">+ {configured.map((o) => (+ <div key={o.provider} className="flex items-center gap-3">+ <Label htmlFor={`${id}-${o.provider}`} className="flex-1 text-[13px] font-medium">+ {OAUTH_SWITCH[o.provider].label}+ </Label>+ <Switch id={`${id}-${o.provider}`} checked={o.on} disabled={busy !== null} onCheckedChange={(on) => void set(o.provider, on)} />+ </div>+ ))}+ <p className="text-[12px] text-muted-foreground">Shows Continue with {configured.map((o) => (o.provider === "google" ? "Google" : "GitHub")).join(" and ")} on the sign-up and log-in forms while public sign-up is on.</p>+ </div>+ );}/** Public sign-up: guests browse read-only, and anyone can make an account (that runs on its own GPU). */@@ -312,6 +360,7 @@ function PublicSignup() {</a>.</p>+ <OAuthSwitches status={p} /></div>);}diff --git a/src/lib/after-signup.ts b/src/lib/after-signup.tsnew file mode 100644index 00000000..1795194c--- /dev/null+++ b/src/lib/after-signup.ts@@ -0,0 +1,19 @@+import { isWay } from "@/lib/ai-setup/ways";++/**+ * Where a new account goes first: the welcome page, which connects its GPU (the pre-flight board), then on to where it+ * was headed (`after`, a path on this site). Not back to Settings' Your GPU (its Sign up free): the welcome page is that+ * same choice. "Set it up with my AI" (a guest's sign-up from it) opens on the welcome page, on the link's way.+ * Used by the sign-up form and by sign-up with Google or GitHub.+ */+export function welcomePath(after: string, origin: string): string {+ const q = new URLSearchParams({ welcome: "1" });+ if (after !== "/" && !after.startsWith("/connect") && !after.startsWith("/settings#your-gpu")) q.set("next", after);+ const nextUrl = new URL(after, origin);+ if (nextUrl.pathname === "/connect" && nextUrl.searchParams.get("setup") === "ai") {+ q.set("setup", "ai");+ const way = nextUrl.searchParams.get("way");+ if (isWay(way)) q.set("way", way);+ }+ return `/connect?${q}`;+}diff --git a/src/lib/api.ts b/src/lib/api.tsindex fca2f442..e1a6be53 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1475,13 +1475,24 @@ export function useAssistActions() {// ---------------------------------------------------------------------------// Who is looking (public sign-up: GET /api/auth/me)+/** The providers an account can sign in with (src/server/oauth.ts). */+export type OAuthProviderId = "google" | "github";+export interface ViewerInfo {signedIn: boolean;/** The install password's session or an API token (also everyone while no password is set). */owner: boolean;/** Guests may browse and anyone may sign up. */publicSignup: boolean;- account?: { email: string };+ /** Continue with Google or GitHub: the providers this studio set up (only while sign-up is open). */+ oauth?: OAuthProviderId[];+ account?: {+ email: string;+ /** The providers it signs in with besides a password. */+ providers?: OAuthProviderId[];+ /** Made with a provider and no password set yet: Settings offers to set one. */+ noPassword?: true;+ };/** Runs go to the ComfyUI on the person's own computer, which a Fuobe tab of theirs runs (components/gpu/computer-runner.tsx). */computer?: boolean;/** The port their computer's tab last found ComfyUI on (a browser that remembers none starts there). */diff --git a/src/proxy.ts b/src/proxy.tsindex e3011f59..d168c262 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -44,6 +44,8 @@ import { authStoreFailed } from "@/server/auth-store";* "who am I" answer for themselves whether public sign-up is on.*/const OPEN = new Set(["/login", "/api/auth/login", "/api/auth/signup", "/api/auth/me", "/api/gpu/pair/start", "/api/gpu/pair/poll", "/api/version"]);+/** Continue with Google or GitHub, and the provider's way back: open the same way (the routes answer 404 while it's off). */+const OAUTH_ROUTE = /^\/api\/auth\/oauth\/[a-z]+(\/callback)?$/;/*** A worker's token (src/server/computer/workers.ts) works only on the routes a computer runs jobs through; the route@@ -421,7 +423,7 @@ export function proxy(request: NextRequest) {return workerRoute(pathname) ? NextResponse.next() : NextResponse.json({ error: "A worker's token only runs jobs." }, { status: 403, headers: { "Cache-Control": "no-store" } });}if (!authEnabled()) return pass(request);- if (OPEN.has(pathname)) return NextResponse.next();+ if (OPEN.has(pathname) || (read && OAUTH_ROUTE.test(pathname))) return NextResponse.next();const open = publicSignup(request.headers.get("host") ?? request.nextUrl.host);const viewer = viewerOf(request, open);if (viewer?.kind === "owner") return pass(request);diff --git a/src/server/auth.ts b/src/server/auth.tsindex baf5ef3a..c4ef6916 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -75,8 +75,15 @@ export interface Account {gpu?: AccountGpu;/** Its own keys ("Your keys"), sealed: src/server/account-keys.ts opens them. */keys?: Partial<Record<CloudProvider, StoredKey>>;+ /** How it last signed in (kept with the row's other fields, extra_json): its password unless it says otherwise. */+ signIn?: SignInWay;+ /** When its email was first confirmed (a provider's verified email: Google or GitHub). Cleared when the email changes. */+ emailVerifiedAt?: number;}+/** How an account signs in: its email and password, or a provider. */+export type SignInWay = "password" | "google" | "github";+/** The install's own row: the cookie secret, the Settings password and the public sign-up switch. */interface Install {/** scrypt hash of the UI-set password ("salt:hash", hex). */@@ -227,6 +234,26 @@ export function createSession(accountId?: string): { value: string; maxAge: numbreturn { value: `${payload}.${sign(keyFor(d, who), payload)}`, maxAge: SESSION_DAYS * 86_400 };}+/** When a session cookie was made (its expiry less a session's length), or null when it isn't one. Not a check of it. */+export function sessionIssuedAt(value: string | undefined): number | null {+ const exp = value?.split(".")[0];+ return exp && /^\d{1,16}$/.test(exp) ? Number(exp) - SESSION_MS : null;+}++/**+ * A MAC of `payload` for one purpose, with a key made from the install's cookie secret: for short-lived values this+ * server hands a browser and reads back (the provider sign-in's state cookie). Never a session: a session's key differs.+ */+export function installMac(purpose: string, payload: string): string {+ let d = install();+ if (!d.secret) {+ authWrite(ensureSecret);+ d = install();+ }+ const key = crypto.createHmac("sha256", d.secret).update(`fuobe:${purpose}`).digest();+ return crypto.createHmac("sha256", key).update(payload).digest("base64url");+}+/*** An account cookie made before account keys held the password's fingerprint was signed with the secret alone. It is* still taken (it ends with its 30 days, so a deploy signs nobody out) until the account first changes its password.@@ -344,6 +371,148 @@ export function createAccount(email: string, password: string): Account {return account;}+// ---------------------------------------------------------------------------+// Public sign-up: Google and GitHub (src/server/oauth.ts)++/** The providers an account can sign in with besides its password (the install's own settings say which are on). */+export type OAuthProvider = "google" | "github";++/** The account a provider's user signs in to, by the provider's own user id. A link whose account is gone is removed. */+export function oauthLinkedAccount(provider: OAuthProvider, subject: string): Account | undefined {+ if (authStoreClosed()) return undefined;+ const r = sql("SELECT account_id FROM auth_oauth_links WHERE provider = ? AND subject = ?").get(provider, subject) as { account_id: string } | undefined;+ if (!r) return undefined;+ const account = accountById(r.account_id);+ if (!account) authWrite(() => sql("DELETE FROM auth_oauth_links WHERE provider = ? AND subject = ? AND account_id = ?").run(provider, subject, r.account_id));+ return account;+}++/** Remember that this provider's user signs in to this account (and when it last did). */+export function linkOAuth(accountId: string, provider: OAuthProvider, subject: string): void {+ const at = Date.now();+ authWrite(() => {+ mustExist(accountId);+ sql(+ `INSERT INTO auth_oauth_links (provider, subject, account_id, made_account, created_at, last_used_at) VALUES (?, ?, ?, 0, ?, ?)+ ON CONFLICT (provider, subject) DO UPDATE SET account_id = excluded.account_id, last_used_at = excluded.last_used_at`,+ ).run(provider, subject, accountId, at, at);+ });+}++/**+ * Sign-up with a provider: an account as createAccount makes one (the same email rule, one account per email), linked to+ * the provider's user. It has no password of its own: its hash is of 32 random bytes nobody keeps, so no password logs+ * in to it, and its session key (keyFor) is still its own. It can set a password later (setFirstAccountPassword).+ */+export function createOAuthAccount(email: string, provider: OAuthProvider, subject: string): Account {+ const e = normalizeEmail(email);+ if (!e) throw new AccountError("Enter a valid email address", 400);+ const taken = () => new AccountError("An account with this email already exists. Log in instead.", 409);+ if (sql("SELECT 1 FROM auth_accounts WHERE email = ?").get(e)) throw taken();+ const at = Date.now();+ // The provider said the email is verified (src/server/oauth.ts takes no other): it counts as confirmed.+ const account: Account = {+ id: crypto.randomBytes(9).toString("hex"),+ email: e,+ hash: hashPassword(crypto.randomBytes(32).toString("hex")),+ createdAt: at,+ lastLoginAt: at,+ signIn: provider,+ emailVerifiedAt: at,+ };+ try {+ authWrite(() => {+ ensureSecret();+ sql("INSERT INTO auth_accounts (id, email, password_hash, created_at, last_login_at, extra_json) VALUES (?, ?, ?, ?, ?, ?)").run(+ account.id,+ account.email,+ account.hash,+ account.createdAt,+ account.lastLoginAt,+ JSON.stringify({ signIn: provider, emailVerifiedAt: at }),+ );+ sql(+ `INSERT INTO auth_oauth_links (provider, subject, account_id, made_account, created_at, last_used_at) VALUES (?, ?, ?, 1, ?, ?)+ ON CONFLICT (provider, subject) DO UPDATE SET account_id = excluded.account_id, made_account = 1, last_used_at = excluded.last_used_at`,+ ).run(provider, subject, account.id, at, at);+ });+ } catch (err) {+ if ((err as { code?: string }).code === "SQLITE_CONSTRAINT_UNIQUE" && /auth_accounts\.email/.test((err as Error).message)) throw taken();+ throw err;+ }+ return account;+}++/**+ * Inside authWrite: merge fields into an account's extra_json (the fields auth.json kept that have no column); undefined+ * removes one. Writes only when something changes. False when there is no such account.+ */+function patchExtra(id: string, patch: Record<string, unknown>): boolean {+ const r = sql("SELECT extra_json FROM auth_accounts WHERE id = ?").get(id) as { extra_json: string | null } | undefined;+ if (!r) return false;+ const before = r.extra_json ? (JSON.parse(r.extra_json) as Record<string, unknown>) : {};+ const after = { ...before };+ for (const [k, v] of Object.entries(patch)) {+ if (v === undefined) delete after[k];+ else after[k] = v;+ }+ if (JSON.stringify(after) === JSON.stringify(before)) return true;+ sql("UPDATE auth_accounts SET extra_json = ? WHERE id = ?").run(Object.keys(after).length ? JSON.stringify(after) : null, id);+ return true;+}++/**+ * Note how an account just signed in (the billing service's account facts, billing.ts accountFacts). A provider's sign-in+ * also confirms the email, which the provider verified: the first time is kept. A password sign-in writes only when the+ * account last signed in another way. Returns the account as it is now.+ */+export function noteSignIn(account: Account, via: SignInWay): Account {+ const verified = via !== "password" && !account.emailVerifiedAt ? Date.now() : undefined;+ if ((account.signIn ?? "password") === via && !verified) return account;+ if (authStoreClosed()) return account;+ authWrite(() => patchExtra(account.id, { signIn: via === "password" ? undefined : via, ...(verified && { emailVerifiedAt: verified }) }));+ return { ...account, signIn: via === "password" ? undefined : via, ...(verified && { emailVerifiedAt: verified }) };+}++/** The providers an account is linked to, in a fixed order. */+export function accountProviders(id: string): OAuthProvider[] {+ if (authStoreClosed()) return [];+ const have = new Set((sql("SELECT DISTINCT provider FROM auth_oauth_links WHERE account_id = ?").all(id) as { provider: string }[]).map((r) => r.provider));+ return (["google", "github"] as const).filter((p) => have.has(p));+}++/**+ * Whether the account has a password of its own: every account made with an email and a password has one, and one made+ * with a provider has one once it (or the owner) set one.+ */+export function accountHasPassword(account: Pick<Account, "id" | "passwordChangedAt">): boolean {+ if (account.passwordChangedAt) return true;+ if (authStoreClosed()) return true;+ return !sql("SELECT 1 FROM auth_oauth_links WHERE account_id = ? AND made_account = 1").get(account.id);+}++/**+ * An account made with a provider sets its first password (Settings → Account). There is no current one to check: the+ * caller asks for a recent sign-in with the provider instead (sessionIssuedAt). Its other sign-ins end, as with a change.+ */+export async function setFirstAccountPassword(id: string, next: string): Promise<Account> {+ if (next.length < 8) throw new AccountError("Use at least 8 characters", 400);+ const account = accountById(id);+ if (!account) throw new AccountError("No such account", 404);+ if (accountHasPassword(account)) throw new AccountError("Enter your current password", 400);+ const salt = crypto.randomBytes(16);+ const hash = `${salt.toString("hex")}:${(await scrypt(next, salt)).toString("hex")}`;+ const changed = { hash, passwordChangedAt: Date.now() };+ updateAccount(id, "password_hash = ?, password_changed_at = ?", changed.hash, changed.passwordChangedAt);+ return { ...account, ...changed };+}++/** The account with this email (any case), or undefined. */+export function accountWithEmail(email: string): Account | undefined {+ const e = normalizeEmail(email);+ return e ? accountByEmail(e) : undefined;+}+/** The account with this (normalised) email, or undefined: one lookup on the unique email. */function accountByEmail(e: string): Account | undefined {if (authStoreClosed()) return undefined;@@ -430,7 +599,10 @@ export function setAccountEmailAsOwner(id: string, email: string): string {authWrite(() => {const other = sql("SELECT id FROM auth_accounts WHERE email = ?").get(e) as { id: string } | undefined;if (other && other.id !== id) throw taken();+ const was = sql("SELECT email FROM auth_accounts WHERE id = ?").get(id) as { email: string } | undefined;if (!sql("UPDATE auth_accounts SET email = ?, sessions_after = ? WHERE id = ?").run(e, Date.now(), id).changes) throw new AccountError("No such account", 404);+ // A new address isn't confirmed yet.+ if (was && was.email !== e) patchExtra(id, { emailVerifiedAt: undefined });});} catch (err) {if ((err as { code?: string }).code === "SQLITE_CONSTRAINT_UNIQUE" && /auth_accounts\.email/.test((err as Error).message)) throw taken();@@ -537,6 +709,7 @@ export function deleteAccount(id: string): void {authWrite(() => {sql("DELETE FROM auth_account_keys WHERE account_id = ?").run(id);sql("DELETE FROM auth_account_gpu WHERE account_id = ?").run(id);+ sql("DELETE FROM auth_oauth_links WHERE account_id = ?").run(id);if (!sql("DELETE FROM auth_accounts WHERE id = ?").run(id).changes) throw new AccountError("No such account", 404);});}diff --git a/src/server/billing.ts b/src/server/billing.tsindex d08f4981..2bd85214 100644--- a/src/server/billing.ts+++ b/src/server/billing.ts@@ -25,7 +25,8 @@ export interface AccountFacts {id: string;email: string | null;emailVerified: boolean;- signIn: "google" | "password";+ /** How the account signed in last: its email and password, or Google or GitHub. */+ signIn: "google" | "github" | "password";createdAt: number;adultAt: number | null;}@@ -338,7 +339,7 @@ function logDown(what: string, e: unknown): void {}/** An account as the billing service sees it. */-export function accountFacts(a: Pick<Account, "id" | "email" | "createdAt"> & { signIn?: "google" | "password"; emailVerifiedAt?: number; adultAt?: number }): AccountFacts {+export function accountFacts(a: Pick<Account, "id" | "email" | "createdAt"> & { signIn?: "google" | "github" | "password"; emailVerifiedAt?: number; adultAt?: number }): AccountFacts {return { id: a.id, email: a.email || null, emailVerified: !!a.emailVerifiedAt, signIn: a.signIn ?? "password", createdAt: a.createdAt, adultAt: a.adultAt ?? null };}diff --git a/src/server/db.ts b/src/server/db.tsindex f9742572..39db74a6 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1301,6 +1301,8 @@ function open(): Database.Database {db.exec(SKILL_TABLES);// An account's own canvases (account-canvas.ts): not a numbered migration, so branches never clash over its place.db.exec(ACCOUNT_CANVAS_TABLES);+ // Sign-in with Google or GitHub (src/server/oauth.ts): not a numbered migration either.+ db.exec(OAUTH_TABLES);// Fuobe Chat (src/server/chat/store.ts): not a numbered migration either.db.exec(CHAT_TABLES);// When a chat was archived (it leaves the list, kept under Archived), for tables made before it.@@ -1349,6 +1351,23 @@ function open(): Database.Database {return db;}+/**+ * Sign-in with Google or GitHub (public sign-up, src/server/oauth.ts): which account a provider's user signs in to, by the+ * provider's own user id (never a token or an email). `made_account`: the account was made by that sign-in, so it has+ * no password of its own until it sets one. No foreign key: moving auth.json in again rewrites the accounts' rows with+ * the same ids, and a cascade would drop these with them. A row whose account is gone is ignored and removed.+ */+const OAUTH_TABLES = `CREATE TABLE IF NOT EXISTS auth_oauth_links (+ provider TEXT NOT NULL,+ subject TEXT NOT NULL,+ account_id TEXT NOT NULL,+ made_account INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ last_used_at INTEGER,+ PRIMARY KEY (provider, subject)+ );+ CREATE INDEX IF NOT EXISTS auth_oauth_links_account ON auth_oauth_links(account_id);`;+/** An account's own canvases (public sign-up, src/server/account-canvas.ts), never in the owner's `canvases`. */const ACCOUNT_CANVAS_TABLES = `CREATE TABLE IF NOT EXISTS account_canvases (id TEXT PRIMARY KEY,diff --git a/src/server/oauth.ts b/src/server/oauth.tsnew file mode 100644index 00000000..7b4373eb--- /dev/null+++ b/src/server/oauth.ts@@ -0,0 +1,250 @@+import "server-only";+import crypto from "node:crypto";+import { installMac, normalizeEmail, type OAuthProvider } from "./auth";+import { getSetting } from "./settings";++/**+ * Sign-up and sign-in with Google or GitHub, for public sign-up (docs/public-signup.md "Google and GitHub"). Off unless+ * the install sets a provider's client id and secret (FUOBE_OAUTH_GOOGLE_ID and FUOBE_OAUTH_GOOGLE_SECRET,+ * FUOBE_OAUTH_GITHUB_ID and FUOBE_OAUTH_GITHUB_SECRET), and only while public sign-up is on. The owner's sign-in is the+ * install password, as before. The owner can switch either provider off in Settings → Security (oauthGoogle,+ * oauthGithub in settings.ts) without a restart.+ *+ * The authorization-code flow: the start route sends the browser to the provider with a random `state` (and a PKCE+ * challenge), kept in a short-lived HttpOnly cookie signed with the install's secret; the callback takes the code only+ * when its `state` is that cookie's, swaps it for a token from the server, and reads the user's id and a verified email.+ * Codes, tokens and secrets are never logged or stored: only the provider's user id, to find the account next time.+ */++export type { OAuthProvider };+export const OAUTH_PROVIDERS: readonly OAuthProvider[] = ["google", "github"];+export const isOAuthProvider = (s: string): s is OAuthProvider => (OAUTH_PROVIDERS as readonly string[]).includes(s);++/** The name visitors read. */+export const PROVIDER_NAME: Record<OAuthProvider, string> = { google: "Google", github: "GitHub" };++const ENV: Record<OAuthProvider, { id: string; secret: string }> = {+ google: { id: "FUOBE_OAUTH_GOOGLE_ID", secret: "FUOBE_OAUTH_GOOGLE_SECRET" },+ github: { id: "FUOBE_OAUTH_GITHUB_ID", secret: "FUOBE_OAUTH_GITHUB_SECRET" },+};++/** The install's client id and secret for a provider, or null while either is missing (then it is off). */+export function oauthClient(p: OAuthProvider): { id: string; secret: string } | null {+ const id = process.env[ENV[p].id]?.trim();+ const secret = process.env[ENV[p].secret]?.trim();+ return id && secret ? { id, secret } : null;+}++/** The owner's switch for each provider (Settings → Security), on unless switched off. */+const SWITCH: Record<OAuthProvider, "oauthGoogle" | "oauthGithub"> = { google: "oauthGoogle", github: "oauthGithub" };+const switchedOn = (p: OAuthProvider) => getSetting(SWITCH[p]) !== "off";++/** The client id and secret, while the provider is set up and the owner hasn't switched it off; else null (it is off). */+export const oauthEnabled = (p: OAuthProvider): { id: string; secret: string } | null => (switchedOn(p) ? oauthClient(p) : null);++/** The providers that are on (public sign-up decides whether they show). */+export const oauthProviders = (): OAuthProvider[] => OAUTH_PROVIDERS.filter((p) => oauthEnabled(p));++/** For the owner's Settings: each provider, whether its id and secret are set, and its switch. */+export const oauthStatus = () => OAUTH_PROVIDERS.map((p) => ({ provider: p, configured: !!oauthClient(p), on: switchedOn(p) }));++const ENDPOINTS = {+ google: {+ authorize: "https://accounts.google.com/o/oauth2/v2/auth",+ token: "https://oauth2.googleapis.com/token",+ userinfo: "https://openidconnect.googleapis.com/v1/userinfo",+ scope: "openid email",+ },+ github: {+ authorize: "https://github.com/login/oauth/authorize",+ token: "https://github.com/login/oauth/access_token",+ user: "https://api.github.com/user",+ emails: "https://api.github.com/user/emails",+ scope: "user:email",+ },+} as const;++/**+ * This studio's own address, as the browser reached it (behind a reverse proxy: the forwarded host and scheme). The+ * callback address is made from it, and the provider sends the browser only to an address its app has registered, so a+ * made-up Host header can't send a code anywhere else.+ */+export function siteOrigin(request: Request): string {+ const u = new URL(request.url);+ const host = request.headers.get("x-forwarded-host")?.split(",")[0].trim() || request.headers.get("host") || u.host;+ const proto = request.headers.get("x-forwarded-proto")?.split(",")[0].trim().toLowerCase() || u.protocol.replace(":", "");+ return `${proto === "http" ? "http" : "https"}://${host}`;+}++/** The provider's callback on this studio: the address to register with the provider. */+export const callbackUrl = (site: string, p: OAuthProvider) => `${site}/api/auth/oauth/${p}/callback`;++/** Why a provider sign-in came back to the login page (`?oauth_error=`): the page says it in plain words. */+export type OAuthErrorCode = "expired" | "cancelled" | "failed" | "unverified" | "disabled" | "busy";++// ---------------------------------------------------------------------------+// The state cookie++export const STATE_COOKIE = "fuobe_oauth";+/** Only the provider routes read it. */+export const STATE_PATH = "/api/auth/oauth";+/** Time to sign in at the provider. */+export const STATE_MS = 10 * 60_000;++/** Which form the visitor came from: a refusal goes back to it. */+export type OAuthMode = "signup" | "login";++export interface OAuthState {+ provider: OAuthProvider;+ /** Sent to the provider and back: must match. */+ state: string;+ /** The PKCE verifier (its SHA-256 went to the provider). */+ verifier: string;+ /** Where to go after: a path on this site. */+ next: string;+ /** The callback address sent at the start, which the token request must repeat. */+ redirectUri: string;+ mode: OAuthMode;+ /** When the cookie stops counting. */+ exp: number;+}++const b64 = (b: Buffer) => b.toString("base64url");++/** A new sign-in at the provider: its state, verifier and the cookie that keeps them. */+export function newState(provider: OAuthProvider, next: string, redirectUri: string, mode: OAuthMode, now = Date.now()): { state: OAuthState; cookie: string } {+ const state: OAuthState = { provider, state: b64(crypto.randomBytes(24)), verifier: b64(crypto.randomBytes(32)), next, redirectUri, mode, exp: now + STATE_MS };+ const body = b64(Buffer.from(JSON.stringify(state)));+ return { state, cookie: `${body}.${installMac("oauth-state", body)}` };+}++/** The state a cookie holds when this server signed it and it hasn't run out, else null. */+export function readState(cookie: string | undefined, now = Date.now()): OAuthState | null {+ if (!cookie) return null;+ const dot = cookie.indexOf(".");+ if (dot <= 0) return null;+ const body = cookie.slice(0, dot);+ const mac = Buffer.from(cookie.slice(dot + 1));+ const want = Buffer.from(installMac("oauth-state", body));+ if (mac.length !== want.length || !crypto.timingSafeEqual(mac, want)) return null;+ try {+ const s = JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as OAuthState;+ if (!isOAuthProvider(s.provider) || typeof s.state !== "string" || typeof s.verifier !== "string" || typeof s.next !== "string" || typeof s.redirectUri !== "string") return null;+ if (typeof s.exp !== "number" || s.exp < now) return null;+ return { ...s, mode: s.mode === "signup" ? "signup" : "login" };+ } catch {+ return null;+ }+}++/** The state cookie from a Cookie header (one only: two mean none). */+export function stateCookieFrom(header: string | null | undefined): string | undefined {+ let found: string | undefined;+ for (const part of (header ?? "").split(";")) {+ const eq = part.indexOf("=");+ if (eq <= 0 || part.slice(0, eq).trim() !== STATE_COOKIE) continue;+ if (found !== undefined) return undefined;+ found = part.slice(eq + 1).trim();+ }+ return found && /^[\w.-]+$/.test(found) ? found : undefined;+}++/** The `state` the provider sent back is the cookie's (compared in constant time). */+export function sameState(a: string | null, b: string): boolean {+ if (!a) return false;+ const x = Buffer.from(a);+ const y = Buffer.from(b);+ return x.length === y.length && crypto.timingSafeEqual(x, y);+}++/** Where the browser goes to sign in at the provider. */+export function authorizeUrl(s: OAuthState, clientId: string): string {+ const e = ENDPOINTS[s.provider];+ const u = new URL(e.authorize);+ u.searchParams.set("client_id", clientId);+ u.searchParams.set("redirect_uri", s.redirectUri);+ u.searchParams.set("response_type", "code");+ u.searchParams.set("scope", e.scope);+ u.searchParams.set("state", s.state);+ u.searchParams.set("code_challenge", b64(crypto.createHash("sha256").update(s.verifier).digest()));+ u.searchParams.set("code_challenge_method", "S256");+ if (s.provider === "google") u.searchParams.set("prompt", "select_account");+ else u.searchParams.set("allow_signup", "true");+ return u.toString();+}++// ---------------------------------------------------------------------------+// The provider's answer++/** Who signed in at the provider: its own user id, and a verified email (or why there is none). */+export type OAuthIdentity = { ok: true; provider: OAuthProvider; subject: string; email: string } | { ok: false; reason: "unverified" | "failed" };++const TIMEOUT_MS = 10_000;++/** A provider call that failed: its status only (never its body, which can hold a token or a code). */+class ProviderError extends Error {}++async function call(url: string, init: RequestInit): Promise<unknown> {+ const res = await fetch(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: "error", cache: "no-store" });+ if (!res.ok) throw new ProviderError(`${new URL(url).host}${new URL(url).pathname} answered ${res.status}`);+ return res.json();+}++/** Swap the code for an access token at the provider, from this server, with the install's secret and the PKCE verifier. */+async function accessToken(s: OAuthState, code: string, client: { id: string; secret: string }): Promise<string> {+ const form = new URLSearchParams({+ grant_type: "authorization_code",+ code,+ redirect_uri: s.redirectUri,+ client_id: client.id,+ client_secret: client.secret,+ code_verifier: s.verifier,+ });+ const body = (await call(ENDPOINTS[s.provider].token, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },+ body: form,+ })) as { access_token?: unknown; error?: unknown };+ if (typeof body.access_token !== "string" || !body.access_token) throw new ProviderError(`${PROVIDER_NAME[s.provider]} sent no access token${typeof body.error === "string" ? ` (${body.error.slice(0, 40)})` : ""}`);+ return body.access_token;+}++/** Google's userinfo: the user's id (`sub`) and email, taken only when Google says it is verified. */+async function googleIdentity(token: string): Promise<OAuthIdentity> {+ const u = (await call(ENDPOINTS.google.userinfo, { headers: { Authorization: `Bearer ${token}`, Accept: "application/json" } })) as {+ sub?: unknown;+ email?: unknown;+ email_verified?: unknown;+ };+ if (typeof u.sub !== "string" || !u.sub) throw new ProviderError("Google sent no user id");+ const verified = u.email_verified === true || u.email_verified === "true";+ const email = typeof u.email === "string" ? normalizeEmail(u.email) : null;+ return verified && email ? { ok: true, provider: "google", subject: u.sub, email } : { ok: false, reason: "unverified" };+}++/** GitHub: the user's id, and its primary email when GitHub says it is verified (/user/emails). */+async function githubIdentity(token: string): Promise<OAuthIdentity> {+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", "User-Agent": "Fuobe", "X-GitHub-Api-Version": "2022-11-28" };+ const user = (await call(ENDPOINTS.github.user, { headers })) as { id?: unknown };+ if ((typeof user.id !== "number" && typeof user.id !== "string") || user.id === "") throw new ProviderError("GitHub sent no user id");+ const emails = (await call(ENDPOINTS.github.emails, { headers })) as unknown;+ const primary = Array.isArray(emails)+ ? (emails as { email?: unknown; primary?: unknown; verified?: unknown }[]).find((e) => e && e.primary === true && e.verified === true && typeof e.email === "string")+ : undefined;+ const email = primary ? normalizeEmail(primary.email as string) : null;+ return email ? { ok: true, provider: "github", subject: String(user.id), email } : { ok: false, reason: "unverified" };+}++/** Who the code is for: the provider's user id and verified email. A failure is logged by its status only. */+export async function identityFor(s: OAuthState, code: string): Promise<OAuthIdentity> {+ const client = oauthEnabled(s.provider);+ if (!client) return { ok: false, reason: "failed" };+ try {+ const token = await accessToken(s, code, client);+ return s.provider === "google" ? await googleIdentity(token) : await githubIdentity(token);+ } catch (e) {+ const why = e instanceof ProviderError ? e.message : e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError") ? "no answer in time" : "the request failed";+ console.warn(`[auth] ${PROVIDER_NAME[s.provider]} sign-in didn't finish: ${why}`);+ return { ok: false, reason: "failed" };+ }+}diff --git a/src/server/settings.ts b/src/server/settings.tsindex 981cfe04..3665bfef 100644--- a/src/server/settings.ts+++ b/src/server/settings.ts@@ -149,6 +149,12 @@ export const SETTINGS = {* opened its data keeps "friendly", as before (db.ts keepFriendlyFailures).*/runFailureDetail: { key: "runs.failureDetail", env: "FUOBE_RUN_FAILURE_DETAIL", default: "full", options: ["full", "friendly"] },+ /**+ * Settings → Security → Sign in with Google / GitHub (public sign-up, src/server/oauth.ts): "off" hides the button and+ * closes its routes without a restart. On by default, so a provider whose client id and secret are set shows at once.+ */+ oauthGoogle: { key: "oauth.google", default: "on", options: ["on", "off"] },+ oauthGithub: { key: "oauth.github", default: "on", options: ["on", "off"] },/** "1" once the first-run guide was put away, or /api/status first saw something the engine mode generates with connected: Home stops offering it. */onboarded: { key: "onboarding.done", default: "0", options: ["0", "1"] },} satisfies Record<string, SettingDef>;diff --git a/src/server/signup-limits.ts b/src/server/signup-limits.tsnew file mode 100644index 00000000..d9979321--- /dev/null+++ b/src/server/signup-limits.ts@@ -0,0 +1,45 @@+import "server-only";+import { LoginGuard } from "./auth";+import { hit, peek } from "./rate";++declare global {+ var __fuobeSignupGuard: LoginGuard | undefined;+}++/**+ * Every sign-up that could make an account counts, made or not: a client makes at most 5 a minute, and everyone slows+ * down past 20. Sign-up with an email and a password and sign-up with Google or GitHub share these budgets.+ */+const guard = () => (globalThis.__fuobeSignupGuard ??= new LoginGuard());+/**+ * Accounts a day from one address. One address can be a whole office, class or mobile network, so this is a ceiling+ * for scripts, not for people: all accounts together keep at most a share of the disk anyway (account-files.ts).+ */+export const SIGNUPS_A_DAY = 20;+const DAY = 24 * 60 * 60_000;++export interface SignupRefusal {+ error: string;+ retryAfterS: number;+}++/**+ * Before an account is made for the client with this key (LoginGuard.clientKey): null when it may go on (the try is+ * counted), else why not. The shared key (no trusted proxy) is everyone: it isn't capped by the day.+ */+export function beginSignup(key: string): SignupRefusal | null {+ const wait = guard().blockedFor(key);+ if (wait > 0) {+ const secs = Math.ceil(wait / 1000);+ return { error: `Too many sign-ups. Try again in ${secs} second${secs === 1 ? "" : "s"}.`, retryAfterS: secs };+ }+ guard().fail(key);+ const today = key === LoginGuard.DIRECT ? null : peek(`signup-day:${key}`, SIGNUPS_A_DAY, DAY);+ if (today && !today.ok) return { error: "That's a lot of new accounts from one network today. Try again tomorrow.", retryAfterS: today.retryAfterS };+ return null;+}++/** An account was made for this client: it counts toward the day's. */+export function signupMade(key: string): void {+ if (key !== LoginGuard.DIRECT) hit(`signup-day:${key}`, SIGNUPS_A_DAY, DAY);+}diff --git a/tests/oauth-signin.test.ts b/tests/oauth-signin.test.tsnew file mode 100644index 00000000..8568296c--- /dev/null+++ b/tests/oauth-signin.test.ts@@ -0,0 +1,461 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";+import { authDb } from "./helpers/auth-db";+// Route handlers call connection(); outside a request scope it would throw.+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+// Route handlers set cookies through cookies() (no request scope in a test): a jar that only records.+const jar = vi.hoisted(() => ({ set: vi.fn(), delete: vi.fn(), get: vi.fn() }));+vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => jar }));+// What the optional billing service would hear (no service is set: the real one sends nothing).+const events = vi.hoisted(() => ({ accountEvent: vi.fn() }));+vi.mock("@/server/billing", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/server/billing")>()), accountEvent: events.accountEvent }));++const dir = tempDir("fuobe-oauth-");+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_PUBLIC_SIGNUP;+delete process.env.FUOBE_HOSTED_RUNS;+delete process.env.FUOBE_TRUST_PROXY;+const auth = await import("@/server/auth");+const oauth = await import("@/server/oauth");+const { proxy } = await import("@/proxy");+const start = await import("@/app/api/auth/oauth/[provider]/route");+const callback = await import("@/app/api/auth/oauth/[provider]/callback/route");+const me = await import("@/app/api/auth/me/route");+const { hit } = await import("@/server/rate");+const { setSetting } = await import("@/server/settings");+const { accountFacts } = await import("@/server/billing");+const publicRoute = await import("@/app/api/auth/public/route");++const SITE = "http://localhost:3000";+const ctx = (provider: string) => ({ params: Promise.resolve({ provider }) }) as never;++function req(url: string, init: { method?: string; cookie?: string; headers?: Record<string, string>; body?: unknown } = {}) {+ const method = init.method ?? "GET";+ const headers: Record<string, string> = { host: "localhost:3000", ...init.headers };+ if (init.cookie) headers.cookie = init.cookie;+ return new NextRequest(`${SITE}${url}`, { method, headers, ...(init.body !== undefined && { body: JSON.stringify(init.body) }) });+}++/** The value the route set for a cookie in this test (the last one). */+const setCookie = (name: string) => jar.set.mock.calls.filter((c) => c[0] === name).at(-1) as [string, string, Record<string, unknown>] | undefined;+const location = (r: Response) => new URL(r.headers.get("location") ?? "", SITE);++/** The provider's answers: a token for the code, then who signed in. */+type Who = { google?: { sub: string; email?: string; email_verified?: unknown }; github?: { id: number; emails: { email: string; primary: boolean; verified: boolean }[] } };+let who: Who = {};+const fetchMock = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ const url = String(input instanceof Request ? input.url : input);+ const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status, headers: { "Content-Type": "application/json" } });+ if (url === "https://oauth2.googleapis.com/token" || url === "https://github.com/login/oauth/access_token") {+ const form = new URLSearchParams(String(init?.body));+ if (form.get("code") !== "good-code" || !form.get("code_verifier")) return json({ error: "invalid_grant" }, 400);+ return json({ access_token: "provider-token-123", token_type: "Bearer" });+ }+ const bearer = new Headers(init?.headers).get("authorization");+ if (bearer !== "Bearer provider-token-123") return json({ message: "Bad credentials" }, 401);+ if (url === "https://openidconnect.googleapis.com/v1/userinfo") return who.google ? json(who.google) : json({}, 401);+ if (url === "https://api.github.com/user") return who.github ? json({ id: who.github.id, login: "someone" }) : json({}, 401);+ if (url === "https://api.github.com/user/emails") return who.github ? json(who.github.emails) : json([], 401);+ return json({ error: "unexpected" }, 500);+});++/** Start a sign-in and come back from the provider: the callback's answer. */+async function signIn(provider: "google" | "github", opts: { next?: string; mode?: string; code?: string; state?: (s: string) => string; cookie?: (c: string) => string; headers?: Record<string, string> } = {}) {+ const q = new URLSearchParams();+ if (opts.next !== undefined) q.set("next", opts.next);+ if (opts.mode) q.set("mode", opts.mode);+ const began = await start.GET(req(`/api/auth/oauth/${provider}?${q}`, { headers: opts.headers }), ctx(provider));+ expect(began.status).toBe(303);+ const state = new URL(began.headers.get("location")!).searchParams.get("state")!;+ const cookie = setCookie(oauth.STATE_COOKIE)![1];+ jar.set.mockClear();+ const back = new URLSearchParams({ code: opts.code ?? "good-code", state: opts.state ? opts.state(state) : state });+ const c = opts.cookie ? opts.cookie(cookie) : cookie;+ return callback.GET(req(`/api/auth/oauth/${provider}/callback?${back}`, { cookie: `${oauth.STATE_COOKIE}=${c}`, headers: opts.headers }), ctx(provider));+}++const sessionAccount = () => {+ const s = setCookie(auth.SESSION_COOKIE);+ const v = s ? auth.sessionViewer(s[1]) : null;+ return v?.kind === "account" ? v.account : null;+};++beforeAll(() => {+ auth.setPassword("install password");+ vi.stubGlobal("fetch", fetchMock);+});+beforeEach(() => {+ process.env.FUOBE_PUBLIC_SIGNUP = "1";+ process.env.FUOBE_OAUTH_GOOGLE_ID = "google-client";+ process.env.FUOBE_OAUTH_GOOGLE_SECRET = "google-secret-value";+ process.env.FUOBE_OAUTH_GITHUB_ID = "github-client";+ process.env.FUOBE_OAUTH_GITHUB_SECRET = "github-secret-value";+ jar.set.mockClear();+ fetchMock.mockClear();+ events.accountEvent.mockClear();+ who = {};+ // Sign-up's per-minute budget starts again (a test makes several accounts from the one shared address).+ delete (globalThis as Record<string, unknown>).__fuobeSignupGuard;+});+afterEach(() => {+ for (const k of ["FUOBE_PUBLIC_SIGNUP", "FUOBE_OAUTH_GOOGLE_ID", "FUOBE_OAUTH_GOOGLE_SECRET", "FUOBE_OAUTH_GITHUB_ID", "FUOBE_OAUTH_GITHUB_SECRET", "FUOBE_TRUST_PROXY"]) delete process.env[k];+});++describe("switching it on", () => {+ it("is off without a provider's id and secret: both routes answer 404 and the login page offers nothing", async () => {+ delete process.env.FUOBE_OAUTH_GOOGLE_SECRET;+ expect((await start.GET(req("/api/auth/oauth/google"), ctx("google"))).status).toBe(404);+ expect((await callback.GET(req("/api/auth/oauth/google/callback?code=x&state=y"), ctx("google"))).status).toBe(404);+ expect(oauth.oauthProviders()).toEqual(["github"]);+ delete process.env.FUOBE_OAUTH_GITHUB_ID;+ const body = (await (await me.GET(req("/api/auth/me"))).json()) as { oauth?: string[] };+ expect(body.oauth).toBeUndefined();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("answers 404 for a provider it doesn't know, and while public sign-up is off", async () => {+ expect((await start.GET(req("/api/auth/oauth/twitter"), ctx("twitter"))).status).toBe(404);+ process.env.FUOBE_PUBLIC_SIGNUP = "0";+ expect((await start.GET(req("/api/auth/oauth/google"), ctx("google"))).status).toBe(404);+ expect((await callback.GET(req("/api/auth/oauth/github/callback?code=x&state=y"), ctx("github"))).status).toBe(404);+ const body = (await (await me.GET(req("/api/auth/me"))).json()) as { oauth?: string[] };+ expect(body.oauth).toBeUndefined();+ });++ it("lets the owner switch a provider off and on again in Settings, without a restart", async () => {+ setSetting("oauthGoogle", "off");+ try {+ expect(oauth.oauthProviders()).toEqual(["github"]);+ expect((await start.GET(req("/api/auth/oauth/google"), ctx("google"))).status).toBe(404);+ expect((await callback.GET(req("/api/auth/oauth/google/callback?code=x&state=y"), ctx("google"))).status).toBe(404);+ expect((await start.GET(req("/api/auth/oauth/github"), ctx("github"))).status).toBe(303);+ const body = (await (await me.GET(req("/api/auth/me"))).json()) as { oauth?: string[] };+ expect(body.oauth).toEqual(["github"]);+ // The owner's Settings see both: set up, and the switch.+ const status = (await (await publicRoute.GET(req("/api/auth/public"))).json()) as { oauth: unknown };+ expect(status.oauth).toEqual([+ { provider: "google", configured: true, on: false },+ { provider: "github", configured: true, on: true },+ ]);+ } finally {+ setSetting("oauthGoogle", "");+ }+ expect(oauth.oauthProviders()).toEqual(["google", "github"]);+ });++ it("names the providers that are on, while sign-up is open", async () => {+ const body = (await (await me.GET(req("/api/auth/me"))).json()) as { oauth?: string[] };+ expect(body.oauth).toEqual(["google", "github"]);+ });++ it("lets a guest reach the routes through the proxy", () => {+ for (const p of ["/api/auth/oauth/google", "/api/auth/oauth/github/callback?code=x&state=y"]) expect(proxy(req(p)).headers.get("x-middleware-next"), p).toBe("1");+ // Signed out with public sign-up off too: the routes answer for themselves (404).+ process.env.FUOBE_PUBLIC_SIGNUP = "0";+ expect(proxy(req("/api/auth/oauth/google")).headers.get("x-middleware-next")).toBe("1");+ });+});++describe("the start", () => {+ it("sends the browser to Google with a state, a PKCE challenge and this studio's callback, kept in an HttpOnly cookie", async () => {+ const r = await start.GET(req("/api/auth/oauth/google?next=/apps&mode=signup"), ctx("google"));+ expect(r.status).toBe(303);+ const to = new URL(r.headers.get("location")!);+ expect(to.origin + to.pathname).toBe("https://accounts.google.com/o/oauth2/v2/auth");+ expect(to.searchParams.get("client_id")).toBe("google-client");+ expect(to.searchParams.get("redirect_uri")).toBe(`${SITE}/api/auth/oauth/google/callback`);+ expect(to.searchParams.get("scope")).toBe("openid email");+ expect(to.searchParams.get("code_challenge_method")).toBe("S256");+ expect(to.searchParams.get("code_challenge")).toMatch(/^[\w-]{43}$/);+ expect(to.searchParams.get("state")).toMatch(/^[\w-]{32}$/);+ // The secret never leaves the server.+ expect(to.toString()).not.toContain("google-secret-value");+ const [, value, opts] = setCookie(oauth.STATE_COOKIE)!;+ expect(opts).toMatchObject({ httpOnly: true, sameSite: "lax", path: "/api/auth/oauth", maxAge: 600 });+ const saved = oauth.readState(value)!;+ expect(saved).toMatchObject({ provider: "google", state: to.searchParams.get("state"), next: "/apps", mode: "signup" });+ // The verifier is in the cookie only: the provider got its SHA-256.+ expect(to.toString()).not.toContain(saved.verifier);+ });++ it("uses the forwarded host and scheme behind a reverse proxy", async () => {+ const r = await start.GET(req("/api/auth/oauth/github", { headers: { "x-forwarded-host": "studio.example.com", "x-forwarded-proto": "https" } }), ctx("github"));+ const to = new URL(r.headers.get("location")!);+ expect(to.origin + to.pathname).toBe("https://github.com/login/oauth/authorize");+ expect(to.searchParams.get("redirect_uri")).toBe("https://studio.example.com/api/auth/oauth/github/callback");+ expect(to.searchParams.get("scope")).toBe("user:email");+ });++ it("keeps only a path on this site as next", async () => {+ for (const [asked, kept] of [+ ["https://evil.example/x", "/"],+ ["//evil.example", "/"],+ ["/\\evil.example", "/"],+ ["/.//evil.example", "/"],+ ["javascript:alert(1)", "/"],+ ["/shorts?x=1", "/shorts?x=1"],+ ]) {+ jar.set.mockClear();+ await start.GET(req(`/api/auth/oauth/google?next=${encodeURIComponent(asked)}`), ctx("google"));+ expect(oauth.readState(setCookie(oauth.STATE_COOKIE)![1])?.next, asked).toBe(kept);+ }+ });+});++describe("the callback", () => {+ it("refuses a state that isn't this browser's, a missing or changed cookie, and never calls the provider", async () => {+ who.google = { sub: "g-state", email: "[email protected]", email_verified: true };+ for (const r of [+ await signIn("google", { state: () => "someone-elses-state" }),+ await signIn("google", { cookie: () => "" }),+ await signIn("google", { cookie: (c) => c.replace(/.$/, (ch) => (ch === "A" ? "B" : "A")) }),+ // A state for GitHub doesn't count at Google's callback.+ await (async () => {+ await start.GET(req("/api/auth/oauth/github"), ctx("github"));+ const cookie = setCookie(oauth.STATE_COOKIE)![1];+ const state = oauth.readState(cookie)!.state;+ return callback.GET(req(`/api/auth/oauth/google/callback?code=good-code&state=${state}`, { cookie: `${oauth.STATE_COOKIE}=${cookie}` }), ctx("google"));+ })(),+ ]) {+ expect(r.status).toBe(303);+ const to = location(r);+ expect(to.pathname).toBe("/login");+ expect(to.searchParams.get("oauth_error")).toBe("expired");+ }+ expect(fetchMock).not.toHaveBeenCalled();+ expect(setCookie(auth.SESSION_COOKIE)).toBeUndefined();+ expect(auth.accountWithEmail("[email protected]")).toBeUndefined();+ });++ it("refuses a state cookie that ran out", async () => {+ const { state, cookie } = oauth.newState("google", "/", `${SITE}/api/auth/oauth/google/callback`, "login", Date.now() - oauth.STATE_MS - 1000);+ const r = await callback.GET(req(`/api/auth/oauth/google/callback?code=good-code&state=${state.state}`, { cookie: `${oauth.STATE_COOKIE}=${cookie}` }), ctx("google"));+ expect(location(r).searchParams.get("oauth_error")).toBe("expired");+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("goes back to the form it came from when the visitor cancels at the provider", async () => {+ const r = await signIn("github", { mode: "signup", next: "/apps", code: "" });+ const to = location(r);+ expect(to.searchParams.get("oauth_error")).toBe("failed");+ const began = await start.GET(req("/api/auth/oauth/github?mode=signup&next=/apps"), ctx("github"));+ const state = new URL(began.headers.get("location")!).searchParams.get("state")!;+ const cookie = setCookie(oauth.STATE_COOKIE)![1];+ const cancelled = await callback.GET(req(`/api/auth/oauth/github/callback?error=access_denied&state=${state}`, { cookie: `${oauth.STATE_COOKIE}=${cookie}` }), ctx("github"));+ const back = location(cancelled);+ expect(back.pathname).toBe("/login");+ expect(Object.fromEntries(back.searchParams)).toEqual({ oauth_error: "cancelled", provider: "github", signup: "1", next: "/apps" });+ });++ it("uses each state once: the cookie is cleared on the way back", async () => {+ who.google = { sub: "g-once", email: "[email protected]", email_verified: true };+ await signIn("google");+ expect(setCookie(oauth.STATE_COOKIE)).toEqual([oauth.STATE_COOKIE, "", expect.objectContaining({ maxAge: 0, path: "/api/auth/oauth" })]);+ });++ it("refuses an email Google hasn't verified, and makes no account", async () => {+ who.google = { sub: "g-unverified", email: "[email protected]", email_verified: false };+ const r = await signIn("google", { mode: "signup" });+ expect(Object.fromEntries(location(r).searchParams)).toMatchObject({ oauth_error: "unverified", provider: "google", signup: "1" });+ expect(setCookie(auth.SESSION_COOKIE)).toBeUndefined();+ expect(auth.accountWithEmail("[email protected]")).toBeUndefined();+ who.google = { sub: "g-no-email" };+ expect(location(await signIn("google")).searchParams.get("oauth_error")).toBe("unverified");+ });++ it("takes only GitHub's primary verified email", async () => {+ who.github = {+ id: 501,+ emails: [+ { email: "[email protected]", primary: true, verified: false },+ { email: "[email protected]", primary: false, verified: true },+ ],+ };+ expect(location(await signIn("github")).searchParams.get("oauth_error")).toBe("unverified");+ expect(auth.accountWithEmail("[email protected]")).toBeUndefined();+ who.github.emails[0].verified = true;+ const r = await signIn("github");+ expect(location(r).pathname).not.toBe("/login");+ expect(sessionAccount()?.email).toBe("[email protected]");+ });++ it("makes a new account as sign-up does, signed in, linked to the provider, with no password", async () => {+ who.google = { sub: "g-new", email: "[email protected]", email_verified: true };+ const r = await signIn("google", { mode: "signup", next: "/apps" });+ expect(r.status).toBe(303);+ const to = location(r);+ // A new account goes to the welcome page first, then where it was headed.+ expect(to.origin).toBe(SITE);+ expect(to.pathname).toBe("/connect");+ expect(Object.fromEntries(to.searchParams)).toEqual({ welcome: "1", next: "/apps" });+ const [, , opts] = setCookie(auth.SESSION_COOKIE)!;+ expect(opts).toMatchObject({ httpOnly: true, sameSite: "lax", path: "/" });+ const a = sessionAccount()!;+ expect(a.email).toBe("[email protected]");+ expect(authDb().prepare("SELECT provider, subject, made_account FROM auth_oauth_links WHERE account_id = ?").all(a.id)).toEqual([{ provider: "google", subject: "g-new", made_account: 1 }]);+ expect(auth.accountHasPassword(a)).toBe(false);+ // No password logs in to it.+ expect(await auth.verifyAccount("[email protected]", "")).toBeNull();+ expect(await auth.verifyAccount("[email protected]", "long enough")).toBeNull();+ // The token and the code are never stored.+ expect(JSON.stringify(authDb().prepare("SELECT * FROM auth_oauth_links").all())).not.toContain("provider-token-123");+ // Settings: it can set a password, and names its provider.+ const body = (await (await me.GET(req("/api/auth/me", { cookie: `${auth.SESSION_COOKIE}=${setCookie(auth.SESSION_COOKIE)![1]}` }))).json()) as { account?: unknown };+ expect(body.account).toEqual({ email: "[email protected]", providers: ["google"], noPassword: true });+ });++ it("signs in to the account with the same email, and later finds it by the provider's id", async () => {+ const a = auth.createAccount("[email protected]", "long enough");+ who.github = { id: 777, emails: [{ email: "[email protected]", primary: true, verified: true }] };+ const r = await signIn("github", { next: "/shorts" });+ expect(location(r).pathname + location(r).search).toBe("/shorts");+ expect(sessionAccount()?.id).toBe(a.id);+ expect(authDb().prepare("SELECT provider, subject, made_account FROM auth_oauth_links WHERE account_id = ?").all(a.id)).toEqual([{ provider: "github", subject: "777", made_account: 0 }]);+ // Its password still works, and it still has one.+ expect((await auth.verifyAccount("[email protected]", "long enough"))?.id).toBe(a.id);+ expect(auth.accountHasPassword(auth.accountById(a.id)!)).toBe(true);+ // The owner changes its email: GitHub's user still signs in to it.+ auth.setAccountEmailAsOwner(a.id, "[email protected]");+ jar.set.mockClear();+ await signIn("github");+ expect(sessionAccount()?.id).toBe(a.id);+ });++ it("keeps a switched-off account out, found by email or by id", async () => {+ const a = auth.createAccount("[email protected]", "long enough");+ auth.setAccountDisabled(a.id, true);+ who.google = { sub: "g-off", email: "[email protected]", email_verified: true };+ const r = await signIn("google");+ expect(location(r).pathname).toBe("/login");+ expect(location(r).searchParams.get("oauth_error")).toBe("disabled");+ expect(setCookie(auth.SESSION_COOKIE)).toBeUndefined();+ // Linked before it was switched off.+ auth.setAccountDisabled(a.id, false);+ await signIn("google");+ expect(sessionAccount()?.id).toBe(a.id);+ auth.setAccountDisabled(a.id, true);+ jar.set.mockClear();+ expect(location(await signIn("google")).searchParams.get("oauth_error")).toBe("disabled");+ expect(setCookie(auth.SESSION_COOKIE)).toBeUndefined();+ });++ it("refuses a code the provider doesn't take, and logs no code, token or secret", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ who.google = { sub: "g-bad", email: "[email protected]", email_verified: true };+ const r = await signIn("google", { code: "bad-code-xyz" });+ expect(location(r).searchParams.get("oauth_error")).toBe("failed");+ expect(warn).toHaveBeenCalled();+ const logged = JSON.stringify(warn.mock.calls);+ for (const s of ["bad-code-xyz", "google-secret-value", "provider-token-123"]) expect(logged).not.toContain(s);+ warn.mockRestore();+ });++ it("goes only to a path on this site after signing in, whatever the cookie was made with", async () => {+ who.google = { sub: "g-next", email: "[email protected]", email_verified: true };+ await signIn("google");+ // A state signed by this server with an outside address (it never makes one): still a path on this site.+ const { state, cookie } = oauth.newState("google", "//evil.example/x", `${SITE}/api/auth/oauth/google/callback`, "login");+ const r = await callback.GET(req(`/api/auth/oauth/google/callback?code=good-code&state=${state.state}`, { cookie: `${oauth.STATE_COOKIE}=${cookie}` }), ctx("google"));+ expect(location(r).origin).toBe(SITE);+ expect(location(r).pathname).toBe("/");+ });++ it("counts a new account against sign-up's limits for that address", async () => {+ process.env.FUOBE_TRUST_PROXY = "1";+ const headers = { "x-forwarded-for": "198.51.100.7" };+ for (let i = 0; i < 20; i++) hit("signup-day:198.51.100.7", 20, 24 * 60 * 60_000);+ who.google = { sub: "g-limit", email: "[email protected]", email_verified: true };+ expect(location(await signIn("google", { headers })).searchParams.get("oauth_error")).toBe("busy");+ expect(auth.accountWithEmail("[email protected]")).toBeUndefined();+ // Signing in to an account that is there isn't a sign-up.+ auth.createAccount("[email protected]", "long enough");+ const r = await signIn("google", { headers });+ expect(location(r).pathname).toBe("/");+ expect(sessionAccount()?.email).toBe("[email protected]");+ });+});++describe("what the billing service hears", () => {+ it("an account made with Google: created, its email confirmed, signed in with Google", async () => {+ who.google = { sub: "g-facts", email: "[email protected]", email_verified: true };+ await signIn("google");+ const a = sessionAccount()!;+ expect(accountFacts(a)).toMatchObject({ id: a.id, email: "[email protected]", emailVerified: true, signIn: "google" });+ expect(events.accountEvent).toHaveBeenCalledTimes(1);+ expect(events.accountEvent).toHaveBeenCalledWith("created", expect.objectContaining({ id: a.id, emailVerified: true, signIn: "google" }));+ // Kept with the account (a later read says the same).+ expect(accountFacts(auth.accountById(a.id)!)).toMatchObject({ emailVerified: true, signIn: "google" });+ });++ it("an account made with GitHub, then signed in again: signed-in, with GitHub", async () => {+ who.github = { id: 9001, emails: [{ email: "[email protected]", primary: true, verified: true }] };+ await signIn("github");+ const a = sessionAccount()!;+ expect(events.accountEvent).toHaveBeenLastCalledWith("created", expect.objectContaining({ id: a.id, emailVerified: true, signIn: "github" }));+ await signIn("github");+ expect(events.accountEvent).toHaveBeenLastCalledWith("signed-in", expect.objectContaining({ id: a.id, emailVerified: true, signIn: "github" }));+ });++ it("a password account that signs in with a provider: its email counts as confirmed; a password log-in says password again", async () => {+ const a = auth.createAccount("[email protected]", "long enough");+ expect(accountFacts(a)).toMatchObject({ emailVerified: false, signIn: "password" });+ who.google = { sub: "g-pw", email: "[email protected]", email_verified: true };+ await signIn("google");+ expect(events.accountEvent).toHaveBeenLastCalledWith("signed-in", expect.objectContaining({ id: a.id, emailVerified: true, signIn: "google" }));+ const login = await import("@/app/api/auth/login/route");+ const r = await login.POST(req("/api/auth/login", { method: "POST", body: { email: "[email protected]", password: "long enough" } }));+ expect(r.status).toBe(200);+ expect(events.accountEvent).toHaveBeenLastCalledWith("signed-in", expect.objectContaining({ id: a.id, emailVerified: true, signIn: "password" }));+ // A new email from the owner isn't confirmed.+ auth.setAccountEmailAsOwner(a.id, "[email protected]");+ expect(accountFacts(auth.accountById(a.id)!)).toMatchObject({ emailVerified: false });+ });+});++describe("an account made with a provider", () => {+ async function made(sub: string, email: string) {+ who.google = { sub, email, email_verified: true };+ await signIn("google");+ return { account: sessionAccount()!, cookie: setCookie(auth.SESSION_COOKIE)![1] };+ }++ it("sets its first password after a recent sign-in, without a current one, and logs in with it", async () => {+ const { account, cookie } = await made("g-first", "[email protected]");+ const r = await me.PATCH(req("/api/auth/me", { method: "PATCH", cookie: `${auth.SESSION_COOKIE}=${cookie}`, body: { next: "a new password" } }));+ expect(r.status).toBe(200);+ expect((await auth.verifyAccount("[email protected]", "a new password"))?.id).toBe(account.id);+ expect(auth.accountHasPassword(auth.accountById(account.id)!)).toBe(true);+ // Now it is a password change like any other: the current one first.+ const again = setCookie(auth.SESSION_COOKIE)![1];+ const wrong = await me.PATCH(req("/api/auth/me", { method: "PATCH", cookie: `${auth.SESSION_COOKIE}=${again}`, body: { current: "", next: "another password" } }));+ expect(wrong.status).toBe(403);+ });++ it("asks for a new sign-in with the provider when the session is older than 10 minutes", async () => {+ const { account } = await made("g-old", "[email protected]");+ vi.useFakeTimers({ now: Date.now() - 11 * 60_000, toFake: ["Date"] });+ const old = auth.createSession(account.id).value;+ vi.useRealTimers();+ const patch = await me.PATCH(req("/api/auth/me", { method: "PATCH", cookie: `${auth.SESSION_COOKIE}=${old}`, body: { current: "", next: "a new password" } }));+ expect(patch.status).toBe(403);+ expect(await patch.json()).toMatchObject({ code: "sign-in-again", provider: "google" });+ const del = await me.DELETE(req("/api/auth/me", { method: "DELETE", cookie: `${auth.SESSION_COOKIE}=${old}`, body: {} }));+ expect(del.status).toBe(403);+ expect(auth.accountById(account.id)).toBeDefined();+ });++ it("deletes itself after a recent sign-in, with its provider link", async () => {+ const { account, cookie } = await made("g-delete", "[email protected]");+ const r = await me.DELETE(req("/api/auth/me", { method: "DELETE", cookie: `${auth.SESSION_COOKIE}=${cookie}`, body: {} }));+ expect(r.status).toBe(204);+ expect(auth.accountById(account.id)).toBeUndefined();+ expect(authDb().prepare("SELECT COUNT(*) AS n FROM auth_oauth_links WHERE account_id = ?").get(account.id)).toEqual({ n: 0 });+ // The same Google user later makes a new account.+ jar.set.mockClear();+ await signIn("google");+ expect(sessionAccount()?.email).toBe("[email protected]");+ expect(sessionAccount()?.id).not.toBe(account.id);+ });+});diff --git a/vitest.config.ts b/vitest.config.tsindex 6913ae56..bf908eea 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -45,6 +45,11 @@ export default defineConfig({"FIREWORKS_API_KEY","FUOBE_HF_TOKEN","FUOBE_LLM_TEST_BASE",+ // Continue with Google or GitHub: off unless a test sets them (tests/oauth-signin.test.ts).+ "FUOBE_OAUTH_GOOGLE_ID",+ "FUOBE_OAUTH_GOOGLE_SECRET",+ "FUOBE_OAUTH_GITHUB_ID",+ "FUOBE_OAUTH_GITHUB_SECRET",].map((k) => [k, ""]),),},