passflow 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/dist/cli.mjs +1759 -0
- package/package.json +42 -3
- package/skills/REVISION +1 -0
- package/skills/index.json +405 -0
- package/skills/passflow-nextjs/SKILL.md +205 -0
- package/skills/passflow-nextjs/assets/.env.example +5 -0
- package/skills/passflow-nextjs/assets/app/account/page.tsx +29 -0
- package/skills/passflow-nextjs/assets/app/actions.example.ts +21 -0
- package/skills/passflow-nextjs/assets/app/api/me/route.ts +22 -0
- package/skills/passflow-nextjs/assets/components/auth-links.tsx +11 -0
- package/skills/passflow-nextjs/assets/lib/call-api.example.ts +15 -0
- package/skills/passflow-nextjs/assets/lib/passflow.ts +4 -0
- package/skills/passflow-nextjs/assets/proxy.ts +10 -0
- package/skills/passflow-nextjs/references/guardrails.md +87 -0
- package/skills/passflow-nextjs/scripts/index.json +405 -0
- package/skills/passflow-nextjs/scripts/lib.sh +1069 -0
- package/skills/passflow-nextjs/scripts/verify.sh +467 -0
- package/skills/passflow-node-api/SKILL.md +189 -0
- package/skills/passflow-node-api/assets/examples/explain-rejection.ts +22 -0
- package/skills/passflow-node-api/assets/examples/express-routes.ts +22 -0
- package/skills/passflow-node-api/assets/examples/fastify-routes.ts +28 -0
- package/skills/passflow-node-api/assets/examples/hono-routes.ts +19 -0
- package/skills/passflow-node-api/assets/src/express-cors.ts +11 -0
- package/skills/passflow-node-api/assets/src/express.ts +13 -0
- package/skills/passflow-node-api/assets/src/fastify-cors.ts +11 -0
- package/skills/passflow-node-api/assets/src/fastify.ts +14 -0
- package/skills/passflow-node-api/assets/src/fetch-handler.ts +13 -0
- package/skills/passflow-node-api/assets/src/hono-cors.ts +11 -0
- package/skills/passflow-node-api/assets/src/hono.ts +16 -0
- package/skills/passflow-node-api/assets/src/passflow.ts +21 -0
- package/skills/passflow-node-api/references/guardrails.md +66 -0
- package/skills/passflow-node-api/scripts/index.json +405 -0
- package/skills/passflow-node-api/scripts/lib.sh +1069 -0
- package/skills/passflow-node-api/scripts/verify.sh +283 -0
- package/skills/passflow-react-vite/SKILL.md +225 -0
- package/skills/passflow-react-vite/assets/server/express-cors.ts +9 -0
- package/skills/passflow-react-vite/assets/server/express.ts +14 -0
- package/skills/passflow-react-vite/assets/server/fastify-cors.ts +11 -0
- package/skills/passflow-react-vite/assets/server/fastify.ts +15 -0
- package/skills/passflow-react-vite/assets/server/hono-cors.ts +8 -0
- package/skills/passflow-react-vite/assets/server/hono.ts +17 -0
- package/skills/passflow-react-vite/assets/server/passflow.ts +30 -0
- package/skills/passflow-react-vite/assets/server/tsconfig.json +14 -0
- package/skills/passflow-react-vite/assets/src/passflow.tsx +28 -0
- package/skills/passflow-react-vite/assets/src/require-sign-in.tsx +35 -0
- package/skills/passflow-react-vite/assets/src/use-api.ts +23 -0
- package/skills/passflow-react-vite/references/guardrails.md +82 -0
- package/skills/passflow-react-vite/scripts/index.json +405 -0
- package/skills/passflow-react-vite/scripts/lib.sh +1069 -0
- package/skills/passflow-react-vite/scripts/verify.sh +678 -0
- package/skills/passflow-tanstack-start/SKILL.md +182 -0
- package/skills/passflow-tanstack-start/assets/.env.example +5 -0
- package/skills/passflow-tanstack-start/assets/src/components/auth-links.tsx +10 -0
- package/skills/passflow-tanstack-start/assets/src/lib/call-api.example.ts +14 -0
- package/skills/passflow-tanstack-start/assets/src/lib/passflow.ts +14 -0
- package/skills/passflow-tanstack-start/assets/src/lib/server-functions.example.ts +20 -0
- package/skills/passflow-tanstack-start/assets/src/routes/account.tsx +25 -0
- package/skills/passflow-tanstack-start/assets/src/routes/api/me.ts +25 -0
- package/skills/passflow-tanstack-start/assets/src/start.ts +14 -0
- package/skills/passflow-tanstack-start/references/guardrails.md +73 -0
- package/skills/passflow-tanstack-start/scripts/index.json +405 -0
- package/skills/passflow-tanstack-start/scripts/lib.sh +1069 -0
- package/skills/passflow-tanstack-start/scripts/verify.sh +470 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: passflow-tanstack-start
|
|
3
|
+
description: Adds Passflow sign-in on the server to a TanStack Start app using @passflow/tanstack-react-start. A request middleware serves /auth/login, /auth/callback and /auth/logout and checks the Origin of cookie-carrying changes, the session lives in an encrypted HttpOnly cookie, and route guards, server functions and server routes check it. Use when asked to add Passflow sign-in, login or auth to a TanStack Start app, or to protect TanStack Start routes, server functions or API routes with Passflow. Applies when the root package.json depends on @tanstack/react-start 1.169.5 or newer and @tanstack/react-router 1.170.46 or newer.
|
|
4
|
+
compatibility: TanStack Start 1.169.5 or newer with TanStack Router 1.170.46 or newer (React), Node.js 22.12 or newer; npm, pnpm or Yarn 1.
|
|
5
|
+
license: MIT
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Passflow for TanStack Start
|
|
9
|
+
|
|
10
|
+
## What this does
|
|
11
|
+
|
|
12
|
+
Adds sign-in on the server to a TanStack Start app. A request middleware registered in `src/start.ts` serves `/auth/login`, `/auth/callback` and `/auth/logout`, refreshes the session when its access token is due, and refuses a cross-origin change that carries cookies. The session lives in an encrypted HttpOnly cookie, `__Host-passflow_session` on https and `passflow_session` on http localhost, split into `.0`, `.1`, … chunks when it is large. Sign-in keeps its state in a `__Host-passflow_txn` cookie (`passflow_txn` on http localhost). Both cookies use `Path=/`, and no token reaches the browser. Route guards call the `requireUser` server function; server functions and server routes check the session themselves.
|
|
13
|
+
|
|
14
|
+
## Where this runs
|
|
15
|
+
|
|
16
|
+
The steps are the same in both places, except where a step is labelled.
|
|
17
|
+
|
|
18
|
+
- **On the developer's machine** (`npx passflow integrate`): you have a shell. Run the commands shown for this place.
|
|
19
|
+
- **In a Passflow GitHub App run**: you have no shell. Your only tools are Read, Write, Edit, Glob, Grep and Skill, plus:
|
|
20
|
+
- `add_passflow_package({name})`, which adds one `@passflow/*` package with the project's package manager, scripts off;
|
|
21
|
+
- `run_build()` and `run_typecheck()`, which each return the exit code and a short tail of the output.
|
|
22
|
+
|
|
23
|
+
Never try to run `curl`, `cat`, `npx`, `node` or a script there. After you finish, the runner runs the install, `run_build()`, `run_typecheck()` and then `verify.sh static`. It never runs `verify.sh run`, because the issuer and the client secret stay out of the sandbox: the draft PR's description tells the developer to run `bash <skill>/scripts/verify.sh run` on their machine before merging.
|
|
24
|
+
|
|
25
|
+
## Preconditions
|
|
26
|
+
|
|
27
|
+
Check each one before you change a file. Every check reads files with Read, Glob or Grep, unless it is labelled. If one fails, stop and tell the user why.
|
|
28
|
+
|
|
29
|
+
1. **Stack.** Read the root `package.json`. It lists both `@tanstack/react-start` and `@tanstack/react-router` in `dependencies` or `devDependencies`.
|
|
30
|
+
- The `@tanstack/react-start` range must admit only 1.169.5 or newer: `^1.169.5`, `^1.169.7` and `>=1.169.5` pass; `^1.169.0`, `>=1.169` and `^1.168.0` fail.
|
|
31
|
+
- The `@tanstack/react-router` range must admit only 1.170.46 or newer: `^1.170.46` and `>=1.170.46` pass; `^1.170.0` fails.
|
|
32
|
+
- A range that cannot be compared fails too: a tag such as `latest`, `workspace:`, a URL, `a || b`, `a - b`.
|
|
33
|
+
|
|
34
|
+
If either range fails, stop: the project needs TanStack Start 1.169.5 or newer and TanStack Router 1.170.46 or newer, written as version ranges. The package was tested with exactly those versions. Do not update them yourself. If `@tanstack/react-router` is not listed at all, the project is not detected as a TanStack Start app: stop and tell the user. The React + Vite skill refuses it too, naming the missing router.
|
|
35
|
+
2. **Layout.** Glob for `src/routes/` (the default) or `app/routes/` (an older layout, or `srcDirectory: 'app'` in the Start plugin options in `vite.config.*`). Call the directory that holds `routes/` `<root>`: `src` or `app`, never the `routes` directory itself. So `<root>/lib/passflow.ts` is `src/lib/passflow.ts`, and `<root>/routes/api/me.ts` is `src/routes/api/me.ts`.
|
|
36
|
+
3. **Node.js 22.12 or newer.** *On the developer's machine:* `node --version`. *In a Passflow GitHub App run:* the runner checks for Node.js 22.12 or newer; you do not.
|
|
37
|
+
4. **Package manager.** Glob the project root for lockfiles and Read the `packageManager` field of `package.json`:
|
|
38
|
+
- a `packageManager` field that names `yarn@2` or newer, or `bun`, means Yarn Berry or Bun;
|
|
39
|
+
- otherwise the lockfiles, in this order: `pnpm-lock.yaml` → pnpm, `package-lock.json` → npm, `yarn.lock` → Yarn 1 (classic), `.yarnrc.yml` → Yarn Berry, `bun.lock` or `bun.lockb` → Bun. If any file present points to Yarn Berry or Bun, that decides; otherwise the first one present does. A `yarn.lock` with a `__metadata:` line (Grep for it) is also Yarn Berry;
|
|
40
|
+
- no lockfile at all: stop. The change needs a committed lockfile. Tell the user to install once with npm, pnpm or Yarn 1 (classic) and commit the lockfile;
|
|
41
|
+
- a `packageManager` field that names a manager other than the one the lockfile picks (for example `pnpm@9.0.0` beside `package-lock.json`): stop, and tell the user to make the two agree;
|
|
42
|
+
- an `npm-shrinkwrap.json` at the root: stop. This skill does not support it.
|
|
43
|
+
|
|
44
|
+
**Yarn Berry or Bun: stop.** Tell the user that this skill supports npm, pnpm and Yarn 1 (classic) only.
|
|
45
|
+
5. **Env files.** The app reads `PASSFLOW_ISSUER`, `PASSFLOW_CLIENT_ID`, `PASSFLOW_CLIENT_SECRET`, `PASSFLOW_SECRET` and `APP_BASE_URL` from `.env.local`.
|
|
46
|
+
- **You never create or edit any `.env*` file: not `.env`, not `.env.local`, not `.env.example`.** On the developer's machine, `npx passflow integrate` writes `.env.local` and `.env.example`. In a Passflow GitHub App run, the service writes `.env.example` with the public values filled in (`PASSFLOW_ISSUER`, `PASSFLOW_CLIENT_ID`, `APP_BASE_URL`) and the secrets empty (`PASSFLOW_CLIENT_SECRET`, `PASSFLOW_SECRET`). Empty secrets there are expected, not a failed setup.
|
|
47
|
+
- If `.env.local` is missing or a value is empty, do not invent values. The code changes, the build and the type check need no values.
|
|
48
|
+
- *On the developer's machine:* if `git ls-files --error-unmatch .env.local` succeeds, git tracks the file: stop. Tell the user to run `git rm --cached .env.local`, commit, and add `.env.local` to `.gitignore`.
|
|
49
|
+
- *In a Passflow GitHub App run:* the service refuses a repository with a committed `.env`, `.env.local` or `.env.*.local` before you start, so there is nothing to check.
|
|
50
|
+
- Never read out, print or repeat a value from an env file.
|
|
51
|
+
6. **What you may change in `package.json`.** Only add `@passflow/tanstack-react-start` to `dependencies`, through step 1. Never add any other dependency, and never edit `scripts`. If a step seems to need either, stop and put it in the message to the developer (step 8).
|
|
52
|
+
|
|
53
|
+
## Steps
|
|
54
|
+
|
|
55
|
+
1. **Install the package.**
|
|
56
|
+
- *On the developer's machine:* use the project's package manager. The version comes from `PASSFLOW_TANSTACK_REACT_START_VERSION`; unset means the latest release. Run the line as it is:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
npm install "@passflow/tanstack-react-start${PASSFLOW_TANSTACK_REACT_START_VERSION:+@$PASSFLOW_TANSTACK_REACT_START_VERSION}"
|
|
60
|
+
pnpm add "@passflow/tanstack-react-start${PASSFLOW_TANSTACK_REACT_START_VERSION:+@$PASSFLOW_TANSTACK_REACT_START_VERSION}"
|
|
61
|
+
yarn add "@passflow/tanstack-react-start${PASSFLOW_TANSTACK_REACT_START_VERSION:+@$PASSFLOW_TANSTACK_REACT_START_VERSION}"
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
- *In a Passflow GitHub App run:* call `add_passflow_package({name: "@passflow/tanstack-react-start"})`. The service pins the version, and the tool adds that exact version. Never edit `package.json` or the lockfile by hand.
|
|
65
|
+
|
|
66
|
+
2. **Copy the assets.** Read each asset and Write it to its target. Asset paths start with `src/`, which stands for `<root>`: when `<root>` is `app`, `assets/src/lib/passflow.ts` goes to `app/lib/passflow.ts`. The assets import each other with relative paths. Do not change the Passflow calls in them.
|
|
67
|
+
|
|
68
|
+
| Asset | Target | Adapt |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| `assets/src/lib/passflow.ts` | `<root>/lib/passflow.ts` | Nothing. |
|
|
71
|
+
| `assets/src/start.ts` | `<root>/start.ts` | If the file exists, merge instead: step 3. |
|
|
72
|
+
| `assets/src/routes/api/me.ts` | `<root>/routes/api/me.ts`, or the path chosen below | Keep it: `verify.sh run` calls it. Check the app's routes first, below. |
|
|
73
|
+
| `assets/src/routes/account.tsx` | `<root>/routes/account.tsx` | An example protected page. If the app has its own route to protect, apply the pattern there (step 4) and skip this file. |
|
|
74
|
+
| `assets/src/components/auth-links.tsx` | `<root>/components/auth-links.tsx` | Render `<AuthLinks user={user} />` where the app shows its navigation (step 6). |
|
|
75
|
+
| `assets/src/lib/server-functions.example.ts` | not copied | The pattern for server functions (step 4). |
|
|
76
|
+
| `assets/src/lib/call-api.example.ts` | `<root>/lib/call-api.ts`, only if server code calls an API as the user | The pattern for sending the access token to an API (step 7). |
|
|
77
|
+
|
|
78
|
+
**Before you add `/api/me`,** look for an existing route at that path. Glob for `<root>/routes/api/me.ts` or `.tsx`, `<root>/routes/api.me.ts` and `<root>/routes/api/me/index.ts`, and Grep `<root>/routes` for `createFileRoute('/api/me')`. If one exists, never overwrite it or add a second. Either protect that handler in place with the server-route pattern from step 4, or copy the asset to an unused path such as `<root>/routes/api/passflow/me.ts` and change its `createFileRoute('/api/me')` to `createFileRoute('/api/passflow/me')`. Name the path you used in the message to the developer (step 8), because `verify.sh run` then needs `--api /api/passflow/me`. In a Passflow GitHub App run, name it in your final summary: the summary goes into the draft PR's description, which tells the developer to run `verify.sh run --api <path>` before merging.
|
|
79
|
+
|
|
80
|
+
The router plugin regenerates `routeTree.gen.ts` on the next `dev` or `build`; do not edit it by hand.
|
|
81
|
+
|
|
82
|
+
3. **Merge an existing `start.ts`.** Never overwrite it. Keep every item and option it has, and make its `requestMiddleware` list start with these two, as the asset does:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' }),
|
|
86
|
+
passflow.middleware(),
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
with `import { createCsrfMiddleware } from '@tanstack/react-start';` and `import { passflow } from './lib/passflow';`. If the file has no `requestMiddleware` yet, add the key. If it already has a `createCsrfMiddleware(...)` with this filter, keep that one instead of adding a second.
|
|
90
|
+
|
|
91
|
+
Copy the `createCsrfMiddleware` line exactly, filter included, and never call `createCsrfMiddleware()` bare. Setting `requestMiddleware` turns off Start's default check on server-function calls, so the line puts it back, limited to server functions as Start's default is. Bare, it checks every request: it refuses page loads that come from another site, including the return from sign-in to `/auth/callback`, and every request that carries no `Origin`, `Referer` or `Sec-Fetch-Site`, such as webhooks.
|
|
92
|
+
|
|
93
|
+
Sign-in is served by `passflow.middleware()` alone. Do not add a server route for `/auth/login`, `/auth/callback` or `/auth/logout`.
|
|
94
|
+
|
|
95
|
+
4. **Protect each place that shows or changes private data.** Public routes get nothing. `getSession()` and `requireSession()` read the server's request, so they run only inside a server function or a server route. `beforeLoad` and loaders also run in the browser, so a route guard calls a server function.
|
|
96
|
+
|
|
97
|
+
| Place | Call | Signed out |
|
|
98
|
+
|---|---|---|
|
|
99
|
+
| Route guard | `beforeLoad: async ({ location }) => ({ user: await requireUser({ data: { returnTo: location.href } }) }),` | The whole page goes to `/auth/login`, then back to this page |
|
|
100
|
+
| A page that shows the user when there is one | `getUser()` from `lib/passflow`, in `beforeLoad` or a loader | `null` |
|
|
101
|
+
| Server function that reads or changes data | `const { user } = await passflow.requireSession();` as the first line of its `.handler` | The rest of the function never runs; the page goes to sign-in |
|
|
102
|
+
| Server route | `const session = await passflow.getSession();` then `if (session === null) { return passflow.unauthorized(); }` | 401 with `Cache-Control: no-store`, never a redirect |
|
|
103
|
+
|
|
104
|
+
`assets/src/routes/account.tsx`, `assets/src/lib/server-functions.example.ts` and `assets/src/routes/api/me.ts` show each one in full. Read the guard's user in the component with `Route.useRouteContext()`. A guard protects navigation, not data: every server function and server route that returns private data checks the session itself.
|
|
105
|
+
|
|
106
|
+
5. **Origin checks.** A `start.ts` that registers request middleware turns off Start's default protection for server functions, so the asset lists Start's `createCsrfMiddleware` again, limited to server-function calls. Passflow's middleware adds the check for everything else: it refuses with 403 every request other than GET, HEAD and OPTIONS that carries a `Cookie` header and comes from another origin. That covers any cookie, whatever its name, not only Passflow's, so the app's own cookie-based endpoints are covered too. Requests without cookies, such as webhooks and bearer-token APIs, pass it. Keep both in the list, and do not add another Origin check for the same routes.
|
|
107
|
+
|
|
108
|
+
6. **Sign-in and sign-out links.** `assets/src/components/auth-links.tsx` is one component that takes the user:
|
|
109
|
+
|
|
110
|
+
```tsx
|
|
111
|
+
export function AuthLinks({ user, returnTo = '/' }: { user: PassflowUser | null; returnTo?: string }) {
|
|
112
|
+
if (user === null) {
|
|
113
|
+
return <a href={`/auth/login?returnTo=${encodeURIComponent(returnTo)}`}>Sign in</a>;
|
|
114
|
+
}
|
|
115
|
+
return <a href="/auth/logout">Sign out</a>;
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Render it where the app shows its navigation, with the user from `requireUser` or `getUser`, as `assets/src/routes/account.tsx` does with `<AuthLinks user={user} />`. Pass `returnTo="/some/path"` to come back to that page after sign-in; only a same-origin path is honoured. Links to `/auth/login` and `/auth/logout` are always plain `<a href>`, never the router's `<Link>`. These paths are served by the middleware, not by a route, and act on GET. `/auth/logout` ignores preloads and requests another site starts, so a preloading `<Link>` never signs the user out by itself, but a preload of `/auth/login` can still start a sign-in before anyone clicks. A plain `<a href>` keeps sign-in and sign-out working.
|
|
120
|
+
|
|
121
|
+
7. **Keep tokens on the server.** `requireUser` and `getUser` return the session's user (`sub`, `email`, `emailVerified`, and `name` and `picture` when known), which holds no token.
|
|
122
|
+
|
|
123
|
+
Server code that calls an API as the signed-in user copies `assets/src/lib/call-api.example.ts`, which sends the access token as a bearer token:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const token = await passflow.getAccessToken();
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Call `fetchAsUser` only inside a server function's handler or a server route, with a URL the app chose, and return only the API's data. Never return the token, or a whole session, from a server function or a loader, never put it in a cookie or browser storage, and never log it. The app itself never reads claims from the token: it reads the session's user. The API that receives the token verifies it; for a Node.js API that is the Passflow Node API skill.
|
|
130
|
+
|
|
131
|
+
8. **Check your work, then tell the developer.**
|
|
132
|
+
- *On the developer's machine:* run `bash <skill>/scripts/verify.sh static` (see Verification) and fix what it reports.
|
|
133
|
+
- *In a Passflow GitHub App run:* call `run_build()`, then `run_typecheck()`, and fix what they report. The build also writes the route tree the type check needs. `run_typecheck()` runs the same check as `verify.sh static`: the `typecheck` script, else `tsc -b` for a `tsconfig.json` with `references`, else `tsc -p tsconfig.json`.
|
|
134
|
+
|
|
135
|
+
End with one message that lists what the developer does next, and change none of it yourself:
|
|
136
|
+
- the env file: if `.env.local` is missing, `cp .env.example .env.local`, then fill in the values from the Passflow portal or the run page (`npx passflow integrate` writes it instead). If `.env.example` lacks a name from `assets/.env.example`, list that name;
|
|
137
|
+
- the Passflow app's callback URL: `APP_BASE_URL` followed by `/auth/callback`. `APP_BASE_URL` must be the origin the browser opens, `localhost` and `127.0.0.1` being different origins. It is an origin only, with no path, query or fragment; an app served under a sub-path is not supported, and `npx passflow integrate` refuses a `--base-url` with a path;
|
|
138
|
+
- `bash <skill>/scripts/verify.sh run` once `.env.local` is filled in, with `--api <path>` when the route is not at `/api/me`;
|
|
139
|
+
- anything you stopped short of: a dependency or `package.json` script the app would need.
|
|
140
|
+
|
|
141
|
+
## Guardrails
|
|
142
|
+
|
|
143
|
+
Read `references/guardrails.md` before you edit auth code. In short:
|
|
144
|
+
|
|
145
|
+
- The session check is in server code. A route guard calls the `requireUser` server function; `getSession()` and `requireSession()` stay inside server functions and server routes.
|
|
146
|
+
- Close the backend too: every server function and server route that touches private data checks the session, not only the route that shows it.
|
|
147
|
+
- No secret in a `VITE_` variable.
|
|
148
|
+
- No token in browser storage, and no token returned from a server function or a loader.
|
|
149
|
+
- Never decode a token by hand; read the user from the session, and let the API that receives the token verify it.
|
|
150
|
+
- Keep both request middlewares registered: Start's `createCsrfMiddleware` with the server-function filter, never bare, and Passflow's, which is the Origin check for cookie-carrying changes.
|
|
151
|
+
- Sign-in and sign-out links are plain `<a href>`, never `<Link>`.
|
|
152
|
+
- Copy Passflow calls from `assets/`, never from memory.
|
|
153
|
+
- Never create or edit any `.env*` file, `.env.example` included. Never edit `package.json` scripts or add a dependency other than `@passflow/tanstack-react-start`.
|
|
154
|
+
|
|
155
|
+
## Verification
|
|
156
|
+
|
|
157
|
+
*On the developer's machine*, run from the project root; `<skill>` is this skill's directory:
|
|
158
|
+
|
|
159
|
+
```sh
|
|
160
|
+
bash <skill>/scripts/verify.sh static
|
|
161
|
+
bash <skill>/scripts/verify.sh run
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
*In a Passflow GitHub App run*, you run `run_build()` and `run_typecheck()` only (step 8). The runner then runs `verify.sh static` itself, and its result is part of the run. It never runs `verify.sh run`; the draft PR's description tells the developer to run it on their machine before merging, with `--api <path>` when the route moved.
|
|
165
|
+
|
|
166
|
+
- `static` needs no env values. It checks that `@passflow/tanstack-react-start` is a dependency and that `start.ts` registers `passflow.middleware()`, and lists `createCsrfMiddleware` with the server-function filter, installs with lifecycle scripts off, runs `build` (which also writes the route tree), then type-checks: the `typecheck` script when there is one, else `tsc -b --noEmit` for a solution-style `tsconfig.json`, else `tsc -p tsconfig.json --noEmit`. It searches `.output/public` and `dist/client` for the names `PASSFLOW_CLIENT_SECRET` and `PASSFLOW_SECRET`, for their values (from `.env.local` and from the process environment, never printed), and for `node:async_hooks`. It scans the source for the guardrail breaks above, including a `getSession`, `requireSession` or `getAccessToken` call in a route file outside a server function's handler and outside a server route. A helper module such as `call-api.example.ts` is not flagged; keep it called from server code only. It proves the copied calls compile and nothing secret or server-only reaches the browser.
|
|
167
|
+
- `run` needs the developer's `.env.local` with all five values, a `build` script, and a `start` script, Nitro output or a `preview` script, on a free port (default 3101, `--port` to change), and a reachable `PASSFLOW_ISSUER`: `/auth/login` reads the issuer's discovery document before it redirects, and answers 503 when the issuer gives no answer within 10 seconds or answers with a 5xx. It builds, starts the app and checks, signed out: `/account` (change with `--page`) has no `data-passflow-protected` content and redirects to `/auth/login`, by a redirect status or a meta refresh, never only a sign-in link in the page; `/api/me` (change with `--api`) answers 401 with `Cache-Control: no-store`; `/auth/login` redirects to the issuer's `/oidc/authorize` with `code_challenge_method=S256` and sets an HttpOnly transaction cookie (`passflow_txn` over http, `__Host-passflow_txn` over https). Then it sends four `POST`s to `/api/me`: from `https://evil.example` carrying only `Cookie: passflow_session.0=x`, and carrying an ordinary cookie, each expecting 403; from `https://evil.example` with no cookie, expecting exactly 401, because the route answers it; and from `APP_BASE_URL`'s origin, expecting exactly 401. When the route answers the no-cookie `POST` with 405 (it has no `POST` handler), the no-cookie and same-origin checks are skipped with a reason; the two 403 checks still run, because the middleware answers them before the route. It stops the server it started.
|
|
168
|
+
|
|
169
|
+
Each check prints `PASS`, `FAIL` or `SKIP`, then `RESULT pass` or `RESULT fail`. Exit 0 is a pass, 1 a failed check, 2 a refusal (unsupported stack or package manager, missing tool or env file).
|
|
170
|
+
|
|
171
|
+
## Troubleshooting
|
|
172
|
+
|
|
173
|
+
- **`TypeError` naming a `PASSFLOW_` variable or `APP_BASE_URL` on the first request.** `.env.local` is missing that value. The developer fills it in; you do not.
|
|
174
|
+
- **`/auth/login` answers 404.** `start.ts` does not register `passflow.middleware()`, or it is in the wrong directory. See step 3.
|
|
175
|
+
- **A route guard throws in the browser, or every client-side navigation ends on sign-in.** `beforeLoad` or a loader calls `passflow.getSession()` or `passflow.requireSession()` directly. Call `requireUser` or `getUser` instead (step 4).
|
|
176
|
+
- **Type error: a server function's result "may not be serializable".** It returns something with a value of type `unknown`, a class instance or a function. Return plain data, as `requireUser` and `getUser` in `lib/passflow.ts` do.
|
|
177
|
+
- **The dev server warns that server functions are not protected by the CSRF middleware.** `start.ts` lacks the `createCsrfMiddleware(...)` line. Add it as in step 3.
|
|
178
|
+
- **Every page answers 403 `Forbidden`, or sign-in fails on the way back.** `createCsrfMiddleware()` is called without the server-function filter. Add the filter (step 3).
|
|
179
|
+
- **`/auth/login` or the return to `/auth/callback` answers 503 `Sign-in is unavailable: the Passflow issuer could not be reached. Try again later.`** The app could not reach `PASSFLOW_ISSUER`: no answer within 10 seconds, a refused connection or an unknown host, or a 5xx from the issuer. Nothing retries; the user tries again later. Check the value for a typo and for a proxy or firewall in between. *On the developer's machine*, `curl -i "$PASSFLOW_ISSUER/.well-known/openid-configuration"` from the app's machine must answer 200.
|
|
180
|
+
- **Sign-in works on http localhost but not on the deployed https site, or the browser drops the session cookie.** On https the cookies are named `__Host-passflow_session` and `__Host-passflow_txn`, and the browser takes them only over https with `Path=/`. `APP_BASE_URL` must use `https://` there, and a proxy in front of the app must not rewrite the cookie's path or domain.
|
|
181
|
+
- **A webhook or another site's legitimate POST gets 403.** It sends cookies from another origin. Webhooks normally send none; if a trusted caller must send cookies cross-origin, ask the user before changing anything.
|
|
182
|
+
- **`npx passflow integrate` did not update this skill.** The CLI replaces only a skill folder it installed and that is still unchanged; a skill folder you changed is not overwritten. Delete the folder to get the new version.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { PassflowUser } from '@passflow/tanstack-react-start';
|
|
2
|
+
|
|
3
|
+
// Plain <a href>, never <Link>: a preloading link would run sign-in or sign-out before anyone clicks, and the
|
|
4
|
+
// router doesn't know these routes. Sign-in returns to `returnTo`, a path on this app.
|
|
5
|
+
export function AuthLinks({ user, returnTo = '/' }: { user: PassflowUser | null; returnTo?: string }) {
|
|
6
|
+
if (user === null) {
|
|
7
|
+
return <a href={`/auth/login?returnTo=${encodeURIComponent(returnTo)}`}>Sign in</a>;
|
|
8
|
+
}
|
|
9
|
+
return <a href="/auth/logout">Sign out</a>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { passflow } from './passflow';
|
|
2
|
+
|
|
3
|
+
// Server code that calls an API as the signed-in user. The access token goes from this server to the API and
|
|
4
|
+
// nowhere else: return the API's data, never the token. Call it only inside a server function's handler or a
|
|
5
|
+
// server route, with a URL the app chose; never pass a URL from the browser. The API verifies the token itself.
|
|
6
|
+
export async function fetchAsUser(url: string, init: RequestInit = {}): Promise<Response | null> {
|
|
7
|
+
const token = await passflow.getAccessToken();
|
|
8
|
+
if (token === null) {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
const headers = new Headers(init.headers);
|
|
12
|
+
headers.set('Authorization', `Bearer ${token}`);
|
|
13
|
+
return fetch(url, { ...init, headers });
|
|
14
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createPassflow } from '@passflow/tanstack-react-start';
|
|
2
|
+
import { createServerFn } from '@tanstack/react-start';
|
|
3
|
+
|
|
4
|
+
// Reads PASSFLOW_ISSUER, PASSFLOW_CLIENT_ID, PASSFLOW_CLIENT_SECRET, PASSFLOW_SECRET and APP_BASE_URL on first use.
|
|
5
|
+
export const passflow = createPassflow();
|
|
6
|
+
|
|
7
|
+
// The signed-in user, or null. For a page that shows the user when there is one.
|
|
8
|
+
export const getUser = createServerFn().handler(async () => (await passflow.getSession())?.user ?? null);
|
|
9
|
+
|
|
10
|
+
// The signed-in user. Signed out, it redirects to sign-in, which returns to `returnTo`. For a route guard: pass the
|
|
11
|
+
// router's location.href, because inside a server function the request is the server function's own.
|
|
12
|
+
export const requireUser = createServerFn()
|
|
13
|
+
.validator((data: { returnTo: string }) => data)
|
|
14
|
+
.handler(async ({ data }) => (await passflow.requireSession({ returnTo: data.returnTo })).user);
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createServerFn } from '@tanstack/react-start';
|
|
2
|
+
import { passflow } from './passflow';
|
|
3
|
+
|
|
4
|
+
// Every server function that reads or changes private data checks the session itself: a route guard
|
|
5
|
+
// protects navigation, not data. Signed out, the rest of the function never runs.
|
|
6
|
+
export const saveNote = createServerFn({ method: 'POST' })
|
|
7
|
+
.validator((data: { note: string }) => data)
|
|
8
|
+
.handler(async ({ data }) => {
|
|
9
|
+
const { user } = await passflow.requireSession();
|
|
10
|
+
|
|
11
|
+
if (data.note.length === 0) return { saved: false };
|
|
12
|
+
await storeNote(user.sub, data.note);
|
|
13
|
+
return { saved: true };
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
// The app's own data layer goes here.
|
|
17
|
+
async function storeNote(userId: string, note: string): Promise<void> {
|
|
18
|
+
void userId;
|
|
19
|
+
void note;
|
|
20
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createFileRoute } from '@tanstack/react-router';
|
|
2
|
+
import { AuthLinks } from '../components/auth-links';
|
|
3
|
+
import { requireUser } from '../lib/passflow';
|
|
4
|
+
|
|
5
|
+
export const Route = createFileRoute('/account')({
|
|
6
|
+
// The guard runs on the server for a page load and in the browser for a link click, so it calls a server
|
|
7
|
+
// function. Signed out, it redirects to sign-in, which returns to this page.
|
|
8
|
+
beforeLoad: async ({ location }) => ({ user: await requireUser({ data: { returnTo: location.href } }) }),
|
|
9
|
+
component: Account,
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
function Account() {
|
|
13
|
+
const { user } = Route.useRouteContext();
|
|
14
|
+
return (
|
|
15
|
+
<main>
|
|
16
|
+
<h1>Account</h1>
|
|
17
|
+
<section data-passflow-protected>
|
|
18
|
+
<p>
|
|
19
|
+
Signed in as <span data-passflow-email>{user.email}</span>
|
|
20
|
+
</p>
|
|
21
|
+
<AuthLinks user={user} />
|
|
22
|
+
</section>
|
|
23
|
+
</main>
|
|
24
|
+
);
|
|
25
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createFileRoute } from '@tanstack/react-router';
|
|
2
|
+
import { passflow } from '../../lib/passflow';
|
|
3
|
+
|
|
4
|
+
export const Route = createFileRoute('/api/me')({
|
|
5
|
+
server: {
|
|
6
|
+
handlers: {
|
|
7
|
+
// A server route answers 401 when signed out, never a redirect.
|
|
8
|
+
GET: async () => {
|
|
9
|
+
const session = await passflow.getSession();
|
|
10
|
+
if (session === null) {
|
|
11
|
+
return passflow.unauthorized();
|
|
12
|
+
}
|
|
13
|
+
return Response.json({ user: session.user }, { headers: { 'Cache-Control': 'no-store' } });
|
|
14
|
+
},
|
|
15
|
+
// A request from another site that carries a cookie never gets here: the middleware answers 403.
|
|
16
|
+
POST: async () => {
|
|
17
|
+
const session = await passflow.getSession();
|
|
18
|
+
if (session === null) {
|
|
19
|
+
return passflow.unauthorized();
|
|
20
|
+
}
|
|
21
|
+
return new Response(null, { status: 204, headers: { 'Cache-Control': 'no-store' } });
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
});
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createCsrfMiddleware, createStart } from '@tanstack/react-start';
|
|
2
|
+
import { passflow } from './lib/passflow';
|
|
3
|
+
|
|
4
|
+
export const startInstance = createStart(() => ({
|
|
5
|
+
requestMiddleware: [
|
|
6
|
+
// Start's own check that a server function call comes from this site. It is off once requestMiddleware is
|
|
7
|
+
// set, so it is listed here again.
|
|
8
|
+
createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' }),
|
|
9
|
+
// Serves /auth/login, /auth/callback and /auth/logout, refreshes the session, and refuses a request from
|
|
10
|
+
// another site that changes data and carries a cookie. It protects no page by itself: every route guard,
|
|
11
|
+
// server function and server route checks the session.
|
|
12
|
+
passflow.middleware(),
|
|
13
|
+
],
|
|
14
|
+
}));
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Guardrails: TanStack Start
|
|
2
|
+
|
|
3
|
+
Read this before you edit any auth code in the app. Each rule says what to do, why, what to do instead, and whether `scripts/verify.sh` checks it. On the developer's machine you run `verify.sh`; in a Passflow GitHub App run you check your work with `run_build()` and `run_typecheck()`, the runner runs `verify.sh static` after you finish, and the developer runs `verify.sh run` on their machine before merging.
|
|
4
|
+
|
|
5
|
+
## 1. A route guard calls a server function; session reads stay on the server
|
|
6
|
+
|
|
7
|
+
- **Rule:** `passflow.getSession()`, `passflow.requireSession()` and `passflow.getAccessToken()` are called only inside a `createServerFn(...).handler(...)`, a server route's `server.handlers`, or a helper module that only those call, such as `fetchAsUser` in `assets/src/lib/call-api.example.ts`. A route's `beforeLoad` calls `requireUser` (or `getUser`) from `lib/passflow`.
|
|
8
|
+
- **Why:** `beforeLoad` and loaders run on the server for a document request and in the browser for a client-side navigation. In the browser there is no request to read, so a direct call fails, or protects only the first page load.
|
|
9
|
+
- **Instead:** copy the `beforeLoad` line of `assets/src/routes/account.tsx`. It passes `location.href` as `returnTo`, so sign-in returns to the page that was navigated to.
|
|
10
|
+
- **Checked:** `verify.sh static` fails on a route file that calls one of the three outside a server function's handler and outside a server route. A helper module outside `routes/` that is called only from server code, such as `call-api.example.ts`, is not flagged; keeping it server-only is your job.
|
|
11
|
+
|
|
12
|
+
## 2. Close the backend, not only the route
|
|
13
|
+
|
|
14
|
+
- **Rule:** every server function and server route that returns or changes private data checks the session itself.
|
|
15
|
+
- **Why:** a route guard protects navigation. Server functions and server routes are HTTP endpoints that anyone can call without loading the route.
|
|
16
|
+
- **Instead:** server functions start their handler with `const { user } = await passflow.requireSession();` (`assets/src/lib/server-functions.example.ts`). Server routes call `getSession()` and return `passflow.unauthorized()` when `session === null` (`assets/src/routes/api/me.ts`); they never redirect.
|
|
17
|
+
- **Checked:** `verify.sh run` expects 401 with `Cache-Control: no-store` from the server route, and a signed-out `/account` that leads to sign-in with no `data-passflow-protected` content.
|
|
18
|
+
|
|
19
|
+
## 3. No secret in a `VITE_` variable
|
|
20
|
+
|
|
21
|
+
- **Rule:** `PASSFLOW_CLIENT_SECRET` and `PASSFLOW_SECRET` keep their names. Nothing named `VITE_…SECRET` exists, and no secret's value is copied into a `VITE_` variable.
|
|
22
|
+
- **Why:** Vite inlines every `VITE_` value into the JavaScript sent to the browser.
|
|
23
|
+
- **Instead:** read secrets in server code only. The package reads them itself; the app does not need to.
|
|
24
|
+
- **Checked:** `verify.sh static` fails on a `VITE_…SECRET` name in the source, and on either secret's name or value in the client bundle. The values come from `.env.local` and from the process environment, and are never printed.
|
|
25
|
+
|
|
26
|
+
## 4. Tokens stay on the server
|
|
27
|
+
|
|
28
|
+
- **Rule:** no access token in `localStorage`, `sessionStorage`, a non-HttpOnly cookie, a server function's or loader's result, or a log line. `getAccessToken()` is called only by server code that sends the token to an API.
|
|
29
|
+
- **Why:** a server function's result is serialized into the page or the client's response. Anything the browser can read, an injected script can read.
|
|
30
|
+
- **Instead:** return the session's user, which holds no token, as `requireUser` and `getUser` in `assets/src/lib/passflow.ts` do. Call the API inside a server function's handler or a server route through `fetchAsUser` in `assets/src/lib/call-api.example.ts`, with a URL the app chose, and return only the API's data.
|
|
31
|
+
- **Checked:** `verify.sh static` fails on storage calls near the word "token", and on `node:async_hooks` in the client bundle, which means server-only code was bundled for the browser.
|
|
32
|
+
|
|
33
|
+
## 5. Verify tokens, never decode them by hand
|
|
34
|
+
|
|
35
|
+
- **Rule:** no `jwt-decode`, `jsonwebtoken`, `atob(...)` or base64 `Buffer.from` on a token.
|
|
36
|
+
- **Why:** decoding is not verifying. A hand-decoded token has no signature, issuer, audience or expiry check.
|
|
37
|
+
- **Instead:** read the user from the session, through `requireUser` or `getUser`. The app never reads claims from the access token: it sends the token to an API (`assets/src/lib/call-api.example.ts`), and the API verifies it. A Node.js API does that with the Passflow Node API skill.
|
|
38
|
+
- **Checked:** `verify.sh static` (guardrails).
|
|
39
|
+
|
|
40
|
+
## 6. SameSite cookies plus two Origin checks
|
|
41
|
+
|
|
42
|
+
- **Rule:** `requestMiddleware` in `start.ts` starts with `createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' })` and `passflow.middleware()`.
|
|
43
|
+
- **Why:** registering any request middleware turns off Start's default protection for server functions, so Start's own CSRF middleware is listed again, limited to server-function calls as Start's default is. Without the filter it refuses every page load that comes from another site, including the return from sign-in, and every request with no `Origin`, `Referer` or `Sec-Fetch-Site`. The session cookie (`__Host-passflow_session` on https, `passflow_session` on http localhost) is `SameSite=Lax`, which still lets a same-site page on another origin send it. Passflow's middleware refuses with 403 every request other than GET, HEAD and OPTIONS that carries any `Cookie` header and comes from another origin, whatever the cookie's name, so the app's other cookie-based endpoints keep that protection too. Requests without cookies, such as webhooks, pass.
|
|
44
|
+
- **Instead:** copy the two lines from `assets/src/start.ts` exactly, filter included, and keep the project's own items after them. Never call `createCsrfMiddleware()` bare. Do not add CORS for the app's own routes.
|
|
45
|
+
- **Checked:** `verify.sh static` fails when `start.ts` does not register Passflow's middleware, or lacks `createCsrfMiddleware` with the server-function filter. `verify.sh run` sends cross-site `POST`s to the server route: one carrying only `passflow_session.0` and one carrying an ordinary cookie each expect 403; one with no cookie expects exactly 401, the route's own signed-out answer. A same-origin `POST` also expects exactly 401. When the route answers the no-cookie `POST` with 405 (it has no `POST` handler), the no-cookie and same-origin checks are skipped with a reason; the two 403 checks still run, because the middleware answers them before the route.
|
|
46
|
+
|
|
47
|
+
## 7. Copy SDK calls from `assets/`, never from memory
|
|
48
|
+
|
|
49
|
+
- **Rule:** every `@passflow/tanstack-react-start` import and call in the app matches an asset file.
|
|
50
|
+
- **Why:** the package has a small, exact surface, and Start's builder names change between releases. A remembered name compiles badly or, worse, compiles and checks nothing.
|
|
51
|
+
- **Instead:** copy the asset, then adapt only what `SKILL.md` allows (target root, the route to protect).
|
|
52
|
+
- **Checked:** `verify.sh static` builds and type-checks the app.
|
|
53
|
+
|
|
54
|
+
## 8. Sign-in and sign-out links are plain `<a href>`
|
|
55
|
+
|
|
56
|
+
- **Rule:** links to `/auth/login` and `/auth/logout` are `<a href>`, never the router's `<Link>`.
|
|
57
|
+
- **Why:** these paths are served by the middleware, not by a route, and act on GET, and `<Link>` preloads on intent. `/auth/logout` ignores a preload and a request another site starts, so a preload never signs the user out, but a preload of `/auth/login` can still start a sign-in before anyone clicks. A plain `<a href>` keeps sign-in and sign-out working.
|
|
58
|
+
- **Instead:** render `<AuthLinks user={user} />` from `assets/src/components/auth-links.tsx`, with the user from `requireUser` or `getUser`, as `assets/src/routes/account.tsx` does. Pass `returnTo` to come back to a page after sign-in. A component that needs its own link writes a plain `<a href="/auth/login?returnTo=…">` or `<a href="/auth/logout">`.
|
|
59
|
+
- **Checked:** `verify.sh static` fails on a `<Link` whose `href` or `to` starts with `/auth/`.
|
|
60
|
+
|
|
61
|
+
## 9. Never write an env file, `package.json` scripts or another dependency
|
|
62
|
+
|
|
63
|
+
- **Rule:** never create or edit any `.env*` file: `.env`, `.env.local` and `.env.example` alike. In `package.json`, only add `@passflow/tanstack-react-start`; never edit `scripts` and never add another dependency.
|
|
64
|
+
- **Why:** the env file holds the developer's secrets. `npx passflow integrate` writes `.env.local` and `.env.example` on the developer's machine, and the Passflow service writes `.env.example` in a GitHub App run, with the public values filled in and the secrets empty. The service refuses a change to any `.env*` file, to `scripts`, or to a dependency other than `@passflow/*`.
|
|
65
|
+
- **Instead:** the last message to the developer lists what they do: `cp .env.example .env.local` and fill in the values, any name `.env.example` lacks, and any script or dependency the app would need.
|
|
66
|
+
- **Checked:** no.
|
|
67
|
+
|
|
68
|
+
## 10. The env file stays out of git
|
|
69
|
+
|
|
70
|
+
- **Rule:** `.env.local` is never committed. On the developer's machine, if `git ls-files --error-unmatch .env.local` succeeds, stop and tell the user. A Passflow GitHub App run never starts on such a repository: the service refuses a committed `.env`, `.env.local` or `.env.*.local` before the agent runs.
|
|
71
|
+
- **Why:** a `.gitignore` line does not cover a file git already tracks.
|
|
72
|
+
- **Instead:** tell the user to run `git rm --cached .env.local`, commit, and add `.env.local` to `.gitignore`.
|
|
73
|
+
- **Checked:** no.
|