# Sign in with your Ghosty account in previews

> The preview proxy tells your app who is viewing it (X-Ghosty-Identity header signed by Ghosty). With 15 lines your app creates the session and any PR can be tested logged in, without OAuth.

URL: https://www.ghosty.studio/en/docs/factory/identity-in-previews

Whoever opens a PR preview from Ghosty (owner, workspace member or accepted guest) is already signed in. Ghosty signs that identity and the preview proxy passes it to your app in the `X-Ghosty-Identity` header, like Cloudflare Access (`Cf-Access-Jwt-Assertion`), oauth2-proxy or Tailscale do. Your app verifies it and creates its session: a PR based on `main` can test the dashboard logged in, with no preview login of its own and no OAuth callback to register.

## What arrives

- `X-Ghosty-Identity`: a 12-hour `EdDSA` JWT with `sub` (Ghosty id), `email`, `name`, `role` (`owner`, `member` or `guest`), `iss` = `https://www.ghosty.studio` and `aud` = that preview's host. It is useless in another preview or in production.
- The proxy strips any `X-Ghosty-Identity` sent by the browser: only Ghosty's reaches the app.
- **Every Ghosty link carries the identity**: «Open preview» on a task or PR, the stable link `/c/dev/pr/<owner>/<repo>/<n>/preview`, the box card and the signed links (`/preview/s/…`, `/pv/…`) when the opener has a Ghosty session. The proxy keeps the identity in a preview cookie (12 h), so navigating inside the app keeps it too. The public `/pv/…` link opened without an account carries no identity.
- In every preview: `GS_PREVIEW_IDENTITY_JWKS_URL` (public key) and `GS_PREVIEW_IDENTITY_ISSUER`. They do not exist in production, so the recipe does nothing there.

- **The smoke comes in the same way**: the «Ghosty · Smoke» check arrives with a service identity (`sub: "ghosty-smoke"`, `email: "smoke@ghosty.studio"`, `role: "member"`). If your app creates its session from this header, the smoke exercises your main feature signed in; you can treat that `sub` as a test user.

## The complete recipe (once, on `main`)

Four pieces that go together: with one missing, preview login gets fixed piecemeal and breaks the piece next to it (Formmy found out over three rounds: `/login`, then the button, then Google, and logout stopped working along the way).

**1. Verify the identity.** Only in Ghosty previews (the variable does not exist in production):

```js
// app/preview-identity.server.js
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS_URL = process.env.GS_PREVIEW_IDENTITY_JWKS_URL;
const jwks = JWKS_URL ? createRemoteJWKSet(new URL(JWKS_URL)) : null;
export const isGhostyPreview = () => Boolean(jwks);
// "I signed out" mark: the header arrives on EVERY request, so without it logout reopens by itself.
export const LOGGED_OUT = "preview_logged_out";
export const loggedOut = (request) => /(?:^|;\s*)preview_logged_out=1/.test(request.headers.get("cookie") ?? "");
export async function previewIdentity(request, { ignoreMark = false } = {}) {
  const token = request.headers.get("x-ghosty-identity");
  if (!jwks || !token || (!ignoreMark && loggedOut(request))) return null;
  try {
    const { payload } = await jwtVerify(token, jwks, { issuer: process.env.GS_PREVIEW_IDENTITY_ISSUER, audience: process.env.PREVIEW_HOST, algorithms: ["EdDSA"] });
    return { id: payload.sub, email: payload.email, name: payload.name ?? null, role: payload.role };
  } catch {
    return null;
  }
}
```

**2. Sign in automatically.** In the loader that reads the session (the one for `/dashboard` and the one for `/login`): with no session and `previewIdentity(request)` returning someone, sign in as a **test user seeded in the preview database** (find or create it with a test email such as `preview-${role}@ghosty.test`, keep `sub` and `email` only as data) and create the session like your normal login. If your session cookie carries a production `Domain`, drop it in the preview (`isGhostyPreview()`) or the browser will not store it.

**3. Sign out and back in.** Logout clears the session **and sets the mark**; the "Sign in with Ghosty" button clears it and signs in with the identity even if the mark exists:

```js
// logout (in the preview)
headers.append("Set-Cookie", await destroySession(session));
if (isGhostyPreview()) headers.append("Set-Cookie", `${LOGGED_OUT}=1; Path=/; HttpOnly; SameSite=Lax; Secure`);

// intent=ghosty-login ("Sign in with Ghosty" button, rendered only if isGhostyPreview())
const who = await previewIdentity(request, { ignoreMark: true });
if (!who) return enterFromGhosty();               // piece 4
headers.append("Set-Cookie", `${LOGGED_OUT}=; Path=/; Max-Age=0`);
headers.append("Set-Cookie", await commitSession(/* test user for `who` */));
```

**4. No identity, a clean screen.** Whoever opens the preview outside Ghosty (public link, another browser) sees no "Oops" or 500 and is not asked for credentials:

```js
export const enterFromGhosty = () => new Response(
  `<!doctype html><meta charset="utf-8"><title>Open it from Ghosty</title><h1>Open it from Ghosty</h1><p>Open this preview from Ghosty ("Open preview") and you will be signed in with your account.</p>`,
  { status: 401, headers: { "Content-Type": "text/html; charset=utf-8" } });
// In /login and in the Google action: preview without provider keys → enterFromGhosty().
```

**Real Google (or other OAuth), optional.** If you uploaded to the preview the keys of a **separate OAuth client for previews only**, the Google button goes to Google with two changes: `redirect_uri = process.env.GS_PREVIEW_OAUTH_REDIRECT_URI` (when requesting the code **and** when exchanging it) and `state = previewOAuthState(csrf, "/auth/google/callback")` (signed with `GS_PREVIEW_OAUTH_STATE_KEY`; the 8-line helper is in [OAuth in previews](/en/docs/factory/oauth-in-previews)). Render both buttons, "Sign in with Ghosty" and "Sign in with Google", and if the keys are missing disable Google with the reason. Never edit the production client or copy its secret.

**The preview database must be disposable** (a copy or an empty seeded one), never production: testing with a session writes data. `ghosty-dev doctor` warns if the preview carries `DATABASE_URL`, `MONGO_*` or another database variable.

## From an agent or the terminal

```bash
ghosty-dev preview 101 --login --path /dashboard   # ONE-time link (10 min) with the service identity
curl -sL -c /tmp/jar "<the link>" -o /dev/null      # the cookie jar now holds the test session
curl -s -b /tmp/jar https://<preview-host>/dashboard
```

The link signs in as `smoke@ghosty.studio` (the smoke identity) and carries no visible keys. Creating it does not spend it: it is spent the first time it is opened (`--open` opens it in your browser).

## Check it end to end

Declare in the `.ghosty/factory.md` frontmatter the protected route and how the session is closed and reopened:

```yaml
login_path: /dashboard
logout: POST /api/login intent=logout
relogin: POST /api/login intent=ghosty-login
```

`ghosty-dev preview <pr> --login --check` (and `ghosty-dev doctor`) makes the real requests, following redirects like a browser, and reports each step:

1. **enter**: with identity the route ends in 2xx and without it ends elsewhere (`/dashboard → /dashboard/agents (200)` vs `→ / (200)` counts as signed in).
2. **sign out**: the `logout` action does not crash.
3. **stays out**: with the header still arriving, the route no longer signs in (the mark is respected).
4. **sign back in**: `relogin` reopens the session.
5. **no identity**: `relogin` without identity returns the "Open it from Ghosty" screen, not a 500.

Without `logout`/`relogin` only step 1 runs and the rest shows "untested". Flags work too: `--logout "POST /api/login intent=logout" --relogin "…"`.

## In the evidence

"Tested in the preview of PR #N" only counts if #N contains the same commit being merged; `ghosty-dev evidence` and the gate check it.

The evidence and the PR template carry the required line **"Flujo principal probado con sesión: <what and how>"** (main flow tested with a session) with a screenshot or a `$ …` command and its output: opening the page or a `/login` smoke does not count. The `ghosty-dev/evidencia` gate requires it.
