Carry app data through a social sign-in
For: an app developer who must know what the person chose before a social sign-in, such as a plan or an invitation code.
What it does: the social start takes a JSON object in data. Core seals it in the state row, and the callback gives it to your hooks as stateData.
Before you start
Section titled “Before you start”- A working social sign-in from Sign in with Google and Apple.
- A hook of the app at
hooks.session.afterCreateorhooks.identity.afterLink. Run your code at a hook point tells how.
- Set
social.stateDatain the config.maxBytesis 1 to 1024, and the default is 1024. - Read
stateDatainhooks.session.afterCreate. A link gives it tohooks.identity.afterLink, withvia: "link".
import { createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/** The plan that each new sign-in asked for. A real app writes its own table. */export const chosenPlans: string[] = [];
export function createStateDataAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string;}) { return createAuth({ baseURL: "https://api.example.com", appURL: "https://app.example.com", trustedOrigins: ["https://app.example.com"], secret: deps.secret, storage: deps.storage, mail: deps.mail, social: { google: { clientId: "google-client-id", clientSecret: "google-client-secret" }, // The start takes `data`: at most 512 bytes of JSON here, sealed in the state row. stateData: { maxBytes: 512 }, }, hooks: { session: { // The browser sent the payload: read it as a wish, never as a right. async afterCreate({ user, stateData }) { if (typeof stateData?.plan === "string") chosenPlans.push(`${user.id} ${stateData.plan}`); }, }, }, });}
/** The start URL with the payload: the base64url of its UTF-8 JSON. */export function startUrl(next: string, payload: Record<string, unknown>): string { let binary = ""; for (const byte of new TextEncoder().encode(JSON.stringify(payload))) binary += String.fromCharCode(byte); const data = btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); return `/auth/social/google/start?${new URLSearchParams({ next, data })}`;}- Encode the object as UTF-8 JSON, then as base64url with no padding.
- Put it in
dataon the start URL, besidenext. The link start takesdatain its body.
import { describe, expect, it } from "vitest";import { call, harness } from "../support/harness.ts";import { createStateDataAuth, startUrl } from "./social-state-data.ts";
describe("carry app data through a social sign-in", () => { it("starts the flow with the payload and keeps it out of the provider URL", async () => { const auth = createStateDataAuth(harness()); const res = await call(auth, "GET", startUrl("/welcome", { plan: "pro" })); expect(res.status).toBe(302); const to = new URL(res.headers.get("location") ?? ""); expect(to.origin).toBe("https://accounts.google.com"); expect(to.searchParams.has("data")).toBe(false); });
it("refuses a payload over the bound and a list", async () => { const auth = createStateDataAuth(harness()); for (const path of [ startUrl("/welcome", { note: "x".repeat(600) }), "/auth/social/google/start?data=WzFd", ]) { const res = await call(auth, "GET", path); expect(new URL(res.headers.get("location") ?? "").searchParams.get("auth_error")).toBe( "invalid_body", ); } });});How it behaves
Section titled “How it behaves”- The person’s browser sends the payload, so it is never a secret and never a trust decision. Check each value against your own rules.
- The value must be an object, not a list, with a depth of 4 at most. The depth of the object itself is 1.
- The state row holds the payload sealed with AES-256-GCM under the current secret version. The row id binds it, so a payload moved to another row does not open.
- The payload goes to the two hooks only. No redirect, no answer, and no log line holds it.
- A user with the second factor on gets a challenge at the callback. The challenge row holds the payload sealed, and
session.afterCreategets it at the challenge verify.identity.afterLinkgets it at the callback when the sign-in links a new provider account. - A state lives 10 minutes. After you make a new secret version current, keep the old version in
secretsfor 10 minutes at least. Else a flow in progress fails withinvalid_token. - The Better Auth shim refuses
additionalDatawithNOT_SUPPORTED, because it serves nogetOAuthState(). Use core’screateAuthfor the payload.
If it fails
Section titled “If it fails”invalid_body:social.stateDatais off, ordatais not base64url JSON. It also answers for a list, more thanmaxBytesbytes, or a depth over 4. Core writes no state row.invalid_token: the payload did not open at the callback or at the challenge verify. Its secret version left the config, or the row changed. Start again.