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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +67 -2
  3. package/dist/cli.mjs +1759 -0
  4. package/package.json +42 -3
  5. package/skills/REVISION +1 -0
  6. package/skills/index.json +405 -0
  7. package/skills/passflow-nextjs/SKILL.md +205 -0
  8. package/skills/passflow-nextjs/assets/.env.example +5 -0
  9. package/skills/passflow-nextjs/assets/app/account/page.tsx +29 -0
  10. package/skills/passflow-nextjs/assets/app/actions.example.ts +21 -0
  11. package/skills/passflow-nextjs/assets/app/api/me/route.ts +22 -0
  12. package/skills/passflow-nextjs/assets/components/auth-links.tsx +11 -0
  13. package/skills/passflow-nextjs/assets/lib/call-api.example.ts +15 -0
  14. package/skills/passflow-nextjs/assets/lib/passflow.ts +4 -0
  15. package/skills/passflow-nextjs/assets/proxy.ts +10 -0
  16. package/skills/passflow-nextjs/references/guardrails.md +87 -0
  17. package/skills/passflow-nextjs/scripts/index.json +405 -0
  18. package/skills/passflow-nextjs/scripts/lib.sh +1069 -0
  19. package/skills/passflow-nextjs/scripts/verify.sh +467 -0
  20. package/skills/passflow-node-api/SKILL.md +189 -0
  21. package/skills/passflow-node-api/assets/examples/explain-rejection.ts +22 -0
  22. package/skills/passflow-node-api/assets/examples/express-routes.ts +22 -0
  23. package/skills/passflow-node-api/assets/examples/fastify-routes.ts +28 -0
  24. package/skills/passflow-node-api/assets/examples/hono-routes.ts +19 -0
  25. package/skills/passflow-node-api/assets/src/express-cors.ts +11 -0
  26. package/skills/passflow-node-api/assets/src/express.ts +13 -0
  27. package/skills/passflow-node-api/assets/src/fastify-cors.ts +11 -0
  28. package/skills/passflow-node-api/assets/src/fastify.ts +14 -0
  29. package/skills/passflow-node-api/assets/src/fetch-handler.ts +13 -0
  30. package/skills/passflow-node-api/assets/src/hono-cors.ts +11 -0
  31. package/skills/passflow-node-api/assets/src/hono.ts +16 -0
  32. package/skills/passflow-node-api/assets/src/passflow.ts +21 -0
  33. package/skills/passflow-node-api/references/guardrails.md +66 -0
  34. package/skills/passflow-node-api/scripts/index.json +405 -0
  35. package/skills/passflow-node-api/scripts/lib.sh +1069 -0
  36. package/skills/passflow-node-api/scripts/verify.sh +283 -0
  37. package/skills/passflow-react-vite/SKILL.md +225 -0
  38. package/skills/passflow-react-vite/assets/server/express-cors.ts +9 -0
  39. package/skills/passflow-react-vite/assets/server/express.ts +14 -0
  40. package/skills/passflow-react-vite/assets/server/fastify-cors.ts +11 -0
  41. package/skills/passflow-react-vite/assets/server/fastify.ts +15 -0
  42. package/skills/passflow-react-vite/assets/server/hono-cors.ts +8 -0
  43. package/skills/passflow-react-vite/assets/server/hono.ts +17 -0
  44. package/skills/passflow-react-vite/assets/server/passflow.ts +30 -0
  45. package/skills/passflow-react-vite/assets/server/tsconfig.json +14 -0
  46. package/skills/passflow-react-vite/assets/src/passflow.tsx +28 -0
  47. package/skills/passflow-react-vite/assets/src/require-sign-in.tsx +35 -0
  48. package/skills/passflow-react-vite/assets/src/use-api.ts +23 -0
  49. package/skills/passflow-react-vite/references/guardrails.md +82 -0
  50. package/skills/passflow-react-vite/scripts/index.json +405 -0
  51. package/skills/passflow-react-vite/scripts/lib.sh +1069 -0
  52. package/skills/passflow-react-vite/scripts/verify.sh +678 -0
  53. package/skills/passflow-tanstack-start/SKILL.md +182 -0
  54. package/skills/passflow-tanstack-start/assets/.env.example +5 -0
  55. package/skills/passflow-tanstack-start/assets/src/components/auth-links.tsx +10 -0
  56. package/skills/passflow-tanstack-start/assets/src/lib/call-api.example.ts +14 -0
  57. package/skills/passflow-tanstack-start/assets/src/lib/passflow.ts +14 -0
  58. package/skills/passflow-tanstack-start/assets/src/lib/server-functions.example.ts +20 -0
  59. package/skills/passflow-tanstack-start/assets/src/routes/account.tsx +25 -0
  60. package/skills/passflow-tanstack-start/assets/src/routes/api/me.ts +25 -0
  61. package/skills/passflow-tanstack-start/assets/src/start.ts +14 -0
  62. package/skills/passflow-tanstack-start/references/guardrails.md +73 -0
  63. package/skills/passflow-tanstack-start/scripts/index.json +405 -0
  64. package/skills/passflow-tanstack-start/scripts/lib.sh +1069 -0
  65. package/skills/passflow-tanstack-start/scripts/verify.sh +470 -0
@@ -0,0 +1,283 @@
1
+ #!/usr/bin/env bash
2
+ # Checks a Node API (Express, Fastify or Hono) protected with @passflow/node.
3
+ #
4
+ # bash verify.sh static [--dir DIR]
5
+ # bash verify.sh run [--dir DIR] [--port N] [--api PATH] [--origin URL]
6
+ #
7
+ # Exit 0: every check passed. 1: a check failed. 2: refused or usage error.
8
+ # Prints one "PASS <check>", "FAIL <check>: <reason>" or "SKIP <check>: <reason>" line per check,
9
+ # then "RESULT pass|fail".
10
+ set -euo pipefail
11
+
12
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ # shellcheck source=SCRIPTDIR/lib.sh
14
+ . "$SCRIPT_DIR/lib.sh"
15
+
16
+ STACK_ID='node-api'
17
+ PACKAGE='@passflow/node'
18
+ ENV_FILE_NAME='.env'
19
+ ENV_KEYS='PASSFLOW_ISSUER PASSFLOW_AUDIENCE'
20
+ NODE_MIN='22.12'
21
+ DEFAULT_PORT='8087'
22
+ DEFAULT_API='/api/me'
23
+
24
+ usage() {
25
+ cat >&2 <<'EOF'
26
+ Usage:
27
+ bash verify.sh static [--dir DIR]
28
+ Install with lifecycle scripts off, type-check, build (if there is a build script)
29
+ and scan the source for guardrail breaks. Needs no env file and no network beyond the install.
30
+
31
+ bash verify.sh run [--dir DIR] [--port N] [--api PATH] [--origin URL]
32
+ Build (with a start script and a build script), start the API with its start (else dev) script
33
+ and check the protected route's answers.
34
+ Refused when something already listens on the port: only a server this script starts is tested.
35
+ --port port for the API, passed as PORT (default 8087)
36
+ --api protected route to call (default /api/me)
37
+ --origin a browser origin the API's CORS allows; checks that the 401 allows it and exposes
38
+ WWW-Authenticate. Leave it out for an API without CORS.
39
+
40
+ DIR defaults to the current directory.
41
+ Exit 0 pass, 1 a check failed, 2 refused or usage error.
42
+ EOF
43
+ }
44
+
45
+ MODE="${1:-}"
46
+ if [ "$MODE" != static ] && [ "$MODE" != run ]; then
47
+ usage
48
+ exit 2
49
+ fi
50
+ shift
51
+
52
+ DIR="$PWD"
53
+ PORT_ARG="$DEFAULT_PORT"
54
+ API_PATH="$DEFAULT_API"
55
+ ORIGIN=''
56
+
57
+ while [ "$#" -gt 0 ]; do
58
+ case "$1" in
59
+ --dir) DIR="${2:-}"; shift 2 || { usage; exit 2; } ;;
60
+ --port) PORT_ARG="${2:-}"; shift 2 || { usage; exit 2; } ;;
61
+ --api) API_PATH="${2:-}"; shift 2 || { usage; exit 2; } ;;
62
+ --origin) ORIGIN="${2:-}"; shift 2 || { usage; exit 2; } ;;
63
+ -h | --help) usage; exit 2 ;;
64
+ *) printf 'Unknown argument: %s\n' "$1" >&2; usage; exit 2 ;;
65
+ esac
66
+ done
67
+
68
+ if [ -z "$DIR" ] || [ ! -f "$DIR/package.json" ]; then
69
+ printf 'REFUSED: no package.json in %s\n' "${DIR:-<empty>}" >&2
70
+ exit 2
71
+ fi
72
+ DIR="$(cd "$DIR" && pwd)"
73
+ case "$PORT_ARG" in
74
+ '' | *[!0-9]*) printf 'REFUSED: --port must be a number\n' >&2; exit 2 ;;
75
+ esac
76
+ case "$API_PATH" in
77
+ /*) ;;
78
+ *) printf 'REFUSED: --api must start with /\n' >&2; exit 2 ;;
79
+ esac
80
+
81
+ pf_require_tool node || exit 2
82
+ if ! pf_node_at_least "$NODE_MIN"; then
83
+ printf 'REFUSED: Node.js %s or newer is required\n' "$NODE_MIN" >&2
84
+ exit 2
85
+ fi
86
+
87
+ STACK="$(pf_detect_stack "$DIR" "$(pf_index_file)")"
88
+ case "$STACK" in
89
+ "$STACK_ID") ;;
90
+ refused:*) printf 'REFUSED: %s\n' "$(pf_stack_refusal "$DIR" "$(pf_index_file)" "${STACK#refused:}")" >&2; exit 2 ;;
91
+ *)
92
+ printf 'REFUSED: package.json does not describe a Node API on Express, Fastify or Hono (detected: %s)\n' "$STACK" >&2
93
+ exit 2
94
+ ;;
95
+ esac
96
+
97
+ PM="$(pf_detect_pm "$DIR")"
98
+ if ! pf_pm_supported "$PM"; then
99
+ printf 'REFUSED: %s\n' "$(pf_pm_refusal "$PM")" >&2
100
+ exit 2
101
+ fi
102
+ pf_require_tool "$(pf_pm_tool "$PM")" || exit 2
103
+
104
+ # ---------------------------------------------------------------- static
105
+
106
+ run_static() {
107
+ local rc
108
+
109
+ if pf_has_dep "$DIR" "$PACKAGE"; then
110
+ pf_pass "dependency $PACKAGE"
111
+ else
112
+ pf_fail "dependency $PACKAGE" "not in dependencies or devDependencies of package.json"
113
+ fi
114
+
115
+ rc=0
116
+ pf_install "$DIR" >"$WORK/install.log" 2>&1 || rc=$?
117
+ if [ "$rc" -eq 0 ]; then
118
+ pf_pass "install ($PM)"
119
+ else
120
+ pf_fail "install ($PM)" "exit $rc; log: $WORK/install.log"
121
+ return 0
122
+ fi
123
+
124
+ rc=0
125
+ pf_typecheck "$DIR" >"$WORK/typecheck.log" 2>&1 || rc=$?
126
+ case "$rc" in
127
+ 0) pf_pass typecheck ;;
128
+ 3) pf_skip typecheck "no typecheck script and no tsconfig.json" ;;
129
+ *) pf_fail typecheck "exit $rc; log: $WORK/typecheck.log" ;;
130
+ esac
131
+
132
+ if pf_has_script "$DIR" build; then
133
+ rc=0
134
+ pf_run_script "$DIR" build >"$WORK/build.log" 2>&1 || rc=$?
135
+ if [ "$rc" -eq 0 ]; then
136
+ pf_pass build
137
+ else
138
+ pf_fail build "exit $rc; log: $WORK/build.log"
139
+ fi
140
+ else
141
+ pf_skip build "no build script"
142
+ fi
143
+
144
+ rc=0
145
+ pf_guardrail_scan "$DIR" api >"$WORK/guardrails.log" 2>&1 || rc=$?
146
+ if [ "$rc" -eq 0 ]; then
147
+ pf_pass guardrails
148
+ else
149
+ pf_fail guardrails "see below"
150
+ cat "$WORK/guardrails.log"
151
+ fi
152
+ }
153
+
154
+ # ---------------------------------------------------------------- run
155
+
156
+ stop_server() {
157
+ if [ -n "$PF_BG_PID" ]; then
158
+ pf_kill_tree "$PF_BG_PID"
159
+ PF_BG_PID=''
160
+ fi
161
+ }
162
+
163
+ run_live() {
164
+ local env_file="$DIR/$ENV_FILE_NAME" missing script base www cc expose allow status rc
165
+ if [ ! -f "$env_file" ]; then
166
+ printf 'REFUSED: %s not found; run mode needs it\n' "$env_file" >&2
167
+ exit 2
168
+ fi
169
+ # shellcheck disable=SC2086
170
+ missing="$(pf_env_missing_keys "$env_file" $ENV_KEYS)"
171
+ if [ -n "$missing" ]; then
172
+ printf 'REFUSED: %s has no value for: %s\n' "$ENV_FILE_NAME" "$(printf '%s' "$missing" | tr '\n' ' ')" >&2
173
+ exit 2
174
+ fi
175
+ pf_require_tool curl || exit 2
176
+
177
+ script=''
178
+ if pf_has_script "$DIR" start; then
179
+ script=start
180
+ elif pf_has_script "$DIR" dev; then
181
+ script=dev
182
+ else
183
+ printf 'REFUSED: package.json has no start or dev script\n' >&2
184
+ exit 2
185
+ fi
186
+
187
+ if ! pf_port_free "$PORT_ARG"; then
188
+ printf 'REFUSED: %s\n' "$(pf_port_busy_refusal "$PORT_ARG")" >&2
189
+ exit 2
190
+ fi
191
+
192
+ # shellcheck disable=SC2086
193
+ pf_load_env "$env_file" $ENV_KEYS
194
+
195
+ # A start script usually runs the build output (node dist/server.js): build first, so the run tests the
196
+ # current code. A dev script builds or transpiles by itself.
197
+ if [ "$script" = start ] && pf_has_script "$DIR" build; then
198
+ rc=0
199
+ pf_run_script "$DIR" build "$PM" >"$WORK/build.log" 2>&1 || rc=$?
200
+ if [ "$rc" -eq 0 ]; then
201
+ pf_pass build
202
+ else
203
+ pf_fail build "exit $rc; log: $WORK/build.log"
204
+ return 0
205
+ fi
206
+ fi
207
+
208
+ export PORT="$PORT_ARG"
209
+ pf_traps stop_server
210
+ case "$PM" in
211
+ npm) pf_start_bg "$DIR" "$WORK/server.log" npm run "$script" ;;
212
+ pnpm) pf_start_bg "$DIR" "$WORK/server.log" pnpm run "$script" ;;
213
+ yarn-classic) pf_start_bg "$DIR" "$WORK/server.log" yarn run "$script" ;;
214
+ esac
215
+
216
+ # localhost, not 127.0.0.1: an API bound to localhost may listen on ::1 only.
217
+ base="http://localhost:$PORT_ARG"
218
+ if pf_wait_http "$base$API_PATH" 60 "$PF_BG_PID"; then
219
+ pf_pass "server starts on port $PORT_ARG ($script script)"
220
+ elif pf_alive "$PF_BG_PID"; then
221
+ pf_fail "server starts on port $PORT_ARG ($script script)" "no answer within 60 s; log: $WORK/server.log"
222
+ return 0
223
+ else
224
+ pf_fail "server starts on port $PORT_ARG ($script script)" "the process exited; log: $WORK/server.log"
225
+ return 0
226
+ fi
227
+ pf_check_listener "$PORT_ARG" "$PF_BG_PID"
228
+
229
+ pf_http "$WORK/no-token" GET "$base$API_PATH" || true
230
+ www="$(pf_header "$WORK/no-token" WWW-Authenticate)"
231
+ cc="$(pf_header "$WORK/no-token" Cache-Control)"
232
+ if [ "$(cat "$WORK/no-token/status")" = 401 ] && [ "$www" = Bearer ]; then
233
+ pf_pass "GET $API_PATH without a token: 401, WWW-Authenticate: Bearer"
234
+ else
235
+ pf_fail "GET $API_PATH without a token" "status $(cat "$WORK/no-token/status"), WWW-Authenticate '${www}'; want 401 and 'Bearer' (status 000: no answer)"
236
+ fi
237
+ if pf_has_token "$cc" no-store; then
238
+ pf_pass "GET $API_PATH without a token: Cache-Control no-store"
239
+ else
240
+ pf_fail "GET $API_PATH without a token" "Cache-Control '${cc}' has no no-store"
241
+ fi
242
+
243
+ pf_http "$WORK/bogus-token" GET "$base$API_PATH" -H 'Authorization: Bearer not.a.token' || true
244
+ www="$(pf_header "$WORK/bogus-token" WWW-Authenticate)"
245
+ case "$(cat "$WORK/bogus-token/status") $www" in
246
+ '401 Bearer error="invalid_token"'*) pf_pass "GET $API_PATH with an invalid token: 401 invalid_token" ;;
247
+ *) pf_fail "GET $API_PATH with an invalid token" "status $(cat "$WORK/bogus-token/status"), WWW-Authenticate '${www}'; want 401 and error=\"invalid_token\"" ;;
248
+ esac
249
+
250
+ if [ -n "$ORIGIN" ]; then
251
+ pf_http "$WORK/origin" GET "$base$API_PATH" -H "Origin: $ORIGIN" || true
252
+ status="$(cat "$WORK/origin/status")"
253
+ allow="$(pf_header "$WORK/origin" Access-Control-Allow-Origin)"
254
+ expose="$(pf_header "$WORK/origin" Access-Control-Expose-Headers)"
255
+ if [ "$status" = 401 ] && [ "$allow" = "$ORIGIN" ] && pf_has_token "$expose" WWW-Authenticate; then
256
+ pf_pass "CORS: the 401 to $ORIGIN allows that origin and exposes WWW-Authenticate"
257
+ else
258
+ pf_fail "CORS: the 401 to $ORIGIN" "status $status, Access-Control-Allow-Origin '${allow}', Access-Control-Expose-Headers '${expose}'; want 401, the origin and WWW-Authenticate"
259
+ fi
260
+ else
261
+ pf_skip "CORS" "no --origin given"
262
+ fi
263
+
264
+ if ! pf_alive "$PF_BG_PID"; then
265
+ pf_fail "server still running after the checks" "the process exited; log: $WORK/server.log"
266
+ fi
267
+ stop_server
268
+ }
269
+
270
+ WORK="$(mktemp -d "$PF_TMP/passflow-verify.XXXXXX")"
271
+ printf 'verify.sh %s: %s (%s, %s)\n' "$MODE" "$DIR" "$STACK_ID" "$PM"
272
+ printf 'logs: %s\n' "$WORK"
273
+
274
+ if [ "$MODE" = static ]; then
275
+ run_static
276
+ else
277
+ run_live
278
+ fi
279
+
280
+ if pf_result; then
281
+ exit 0
282
+ fi
283
+ exit 1
@@ -0,0 +1,225 @@
1
+ ---
2
+ name: passflow-react-vite
3
+ description: Adds Passflow sign-in to a React single-page app built with Vite, using @passflow/react in the browser, and protects the existing Node API it calls (Express, Fastify or Hono) with @passflow/node access-token checks and CORS for the app's origin. Use when asked to add Passflow sign-in or login to a React + Vite app, call an API with a Passflow token from a React SPA, or protect that SPA's backend with Passflow. Applies when the root package.json depends on both vite and react, and not on next or @tanstack/react-start (those have their own Passflow skills).
4
+ compatibility: Node.js 22.12 or newer; React 18 or 19 with Vite; an existing API on Express 4 or 5, Fastify 5 or Hono 4; npm, pnpm or Yarn 1.
5
+ license: MIT
6
+ ---
7
+
8
+ # Passflow for React + Vite with a Node API
9
+
10
+ ## What this does
11
+
12
+ Adds sign-in to a React + Vite single-page app and protects the Node API it calls. The SPA signs in through Passflow's hosted sign-in (PKCE) with `@passflow/react`, keeps the tokens in browser storage, and sends the access token to the API's origin only. The API checks that token on every protected route with `@passflow/node`, and its CORS allows the SPA's origin and exposes the `WWW-Authenticate` challenge.
13
+
14
+ The API must exist already, on Express, Fastify or Hono. This skill never creates a server and never picks a framework. The only packages it adds are `@passflow/react` and `@passflow/node`. It never adds another dependency, never edits `package.json` scripts and never creates or edits a `.env*` file (`.env.example` included). Whatever else the developer has to do is listed in the last step.
15
+
16
+ ## Where this runs
17
+
18
+ The skill runs on one of two paths. Where a step differs, it is labelled.
19
+
20
+ - **On the developer's machine** (`npx passflow integrate`, or an agent the developer runs): you have a shell. You install with the package manager and run `verify.sh` yourself.
21
+ - **In a Passflow GitHub App run**: you have no shell. Your tools are Read, Write, Edit, Glob, Grep and Skill, plus `add_passflow_package({ name })`, `run_build()` and `run_typecheck()`. The last two return an exit code and a short tail of the output. 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.
22
+
23
+ Every other step uses only reading and writing files, so it is the same on both paths.
24
+
25
+ ## Preconditions
26
+
27
+ Check each one before you change a file. Read the `package.json` files and look for the files named below with Glob (Grep for a line inside one). If one fails, stop and tell the user why.
28
+
29
+ 1. **Stack.** The root `package.json` lists both `vite` and `react` in `dependencies` or `devDependencies`, and lists neither `next` nor `@tanstack/react-start`. If it lists `next`, or `@tanstack/react-start` together with `@tanstack/react-router`, use that stack's Passflow skill instead. If that stack's version rule fails (Next.js older than 16; TanStack Start older than 1.169.5 or TanStack Router older than 1.170.46; or a range that cannot be compared), stop: the project is refused, not handled as a React + Vite app.
30
+ 2. **A single-page app.** If the root `package.json` lists a framework that renders React on a server (`@tanstack/react-start` without `@tanstack/react-router`, `@react-router/dev`, `@remix-run/dev`, `vike`, `vite-plugin-ssr`, `waku`, `astro`, `rakkasjs`), stop: this skill is for a single-page app only.
31
+ 3. **An existing API.** The root `package.json`, or the `package.json` of an `api/` or `server/` folder, lists `express`, `fastify` or `hono`. If none does, stop and tell the user: "add an API first". Do not create one.
32
+ 4. **Node.js 22.12 or newer.** On the developer's machine, check `node --version`. In a Passflow GitHub App run, the runner checks for Node.js 22.12 or newer; you do not.
33
+ 5. **Package manager.** Look at the project root, which takes only `package.json` and a Glob for the lockfiles:
34
+ - a `packageManager` field in `package.json` that names `yarn@2` or newer, or `bun`, means Yarn Berry or Bun;
35
+ - an `npm-shrinkwrap.json`: stop. npm would write the change into it, and this skill updates `package-lock.json`, `pnpm-lock.yaml` or `yarn.lock` only;
36
+ - 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;
37
+ - 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;
38
+ - a `packageManager` field naming npm, pnpm or Yarn 1 while the lockfile belongs to another manager (`pnpm@9` beside `package-lock.json`): stop. Tell the user to make them agree.
39
+
40
+ **Yarn Berry or Bun: stop.** Tell the user that this skill supports npm, pnpm and Yarn 1 (classic) only. If the API has its own `package.json`, decide its package manager the same way; an API folder with no lockfile of its own uses the root's.
41
+ 6. **Env file `.env.local`** at the project root. You never create or edit it (nor `.env`, nor `.env.example`), and you never print its values. The values come from the env file `npx passflow integrate` writes, or from the run page in the Passflow portal; `.env.example` is written by the CLI or, in a Passflow GitHub App run, by the service, which fills in the public values and leaves any secret empty (this stack has none). Leave it as it is. `.env.local` holds six names:
42
+
43
+ | Name | Read by | Value |
44
+ |---|---|---|
45
+ | `VITE_PASSFLOW_URL` | SPA | The Passflow issuer URL. Public. |
46
+ | `VITE_PASSFLOW_APP_ID` | SPA | The SPA app's client ID. Public. |
47
+ | `VITE_API_URL` | SPA | The API's origin as the browser calls it. |
48
+ | `PASSFLOW_ISSUER` | API | The same issuer URL as `VITE_PASSFLOW_URL`. |
49
+ | `PASSFLOW_AUDIENCE` | API | The SPA app's client ID: the same value as `VITE_PASSFLOW_APP_ID`. A comma-separated list when the API also accepts other apps' tokens. |
50
+ | `APP_BASE_URL` | API | The SPA's origin, for example `http://localhost:5173`, with no path, query or fragment: an SPA served under a sub-path is not supported, and `npx passflow integrate` refuses a `--base-url` with a path. It is the origin the API's CORS allows. |
51
+
52
+ - `PASSFLOW_AUDIENCE` is the SPA app's client ID, because the access tokens the SPA gets carry `aud = [app ID]`. Never invent an audience string such as `api` or a URL: every token would then get 401.
53
+ - When the API also accepts the access tokens of other Passflow apps, `PASSFLOW_AUDIENCE` is a comma-separated list of client IDs (`spa-id,other-id`) that includes the SPA's. Each entry is an app's client ID, never an invented string. Every app in the list gets the same access to the API.
54
+ - `VITE_API_URL` is not provisioned. When it is absent, the CLI writes `http://localhost:8086`, or the origin given to its `--api-url` flag. The developer sets it to the real API origin in each environment.
55
+ - Nothing secret goes in a `VITE_` variable. Vite puts every `VITE_` value into the browser bundle. The SPA needs no secret, and this stack has none.
56
+ - If `.env.local` is missing or a value is empty, do not invent values: carry on with the code, and the last step tells the developer how to get them.
57
+ - In a Passflow GitHub App run there is no `.env.local`: that is expected. Do not look for its values.
58
+ - A committed `.env.local`: on the developer's machine, check with `git ls-files --error-unmatch .env.local`. If it succeeds, git tracks the file: stop. Tell the user to run `git rm --cached .env.local`, commit, and add `.env.local` to `.gitignore`. 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.
59
+ 7. **App settings in Passflow.** The SPA app is of type `spa` with PKCE. Its redirect URLs include the SPA's root URL (`APP_BASE_URL` followed by `/`), and its allowed origins include the SPA's origin. An app the Passflow CLI or service created has both. For an app made by hand, the last step tells the developer to add them; sign-in fails with "redirect_uri not registered" without the first and at the token call without the second.
60
+
61
+ ## Steps
62
+
63
+ 1. **Install the packages.** `@passflow/react` goes into the SPA's `package.json`. `@passflow/node` goes into the API's: the root one when the API lives in the same package, else the API folder's. Install nothing else.
64
+
65
+ In a Passflow GitHub App run, call `add_passflow_package({ name: "@passflow/react" })` and `add_passflow_package({ name: "@passflow/node" })`. Each runs the detected package manager's add in the project root with lifecycle scripts off. The service pins the version, and the tool adds that exact version. Do not edit a `package.json` or a lockfile by hand. If one returns a non-zero exit code, stop and report its tail. When the API has its own `package.json` in a folder (`api/` or `server/`), stop before you copy anything, and tell the user that this layout needs the developer's machine (`npx passflow integrate`): the service refuses a change to a `package.json` or lockfile that is not at the repository root.
66
+
67
+ On the developer's machine, use the project's package manager. Versions come from `PASSFLOW_REACT_VERSION` and `PASSFLOW_NODE_VERSION`; unset means the latest release. Run the lines as they are, the `@passflow/node` one in the API's folder when it has its own `package.json`:
68
+
69
+ ```sh
70
+ npm install "@passflow/react${PASSFLOW_REACT_VERSION:+@$PASSFLOW_REACT_VERSION}"
71
+ pnpm add "@passflow/react${PASSFLOW_REACT_VERSION:+@$PASSFLOW_REACT_VERSION}"
72
+ yarn add "@passflow/react${PASSFLOW_REACT_VERSION:+@$PASSFLOW_REACT_VERSION}"
73
+ ```
74
+
75
+ ```sh
76
+ npm install "@passflow/node${PASSFLOW_NODE_VERSION:+@$PASSFLOW_NODE_VERSION}"
77
+ pnpm add "@passflow/node${PASSFLOW_NODE_VERSION:+@$PASSFLOW_NODE_VERSION}"
78
+ yarn add "@passflow/node${PASSFLOW_NODE_VERSION:+@$PASSFLOW_NODE_VERSION}"
79
+ ```
80
+
81
+ 2. **Find the API's code.** It is the code that creates the `express()`, `Fastify()` or `new Hono()` instance, in the package that lists the framework (precondition 3). Its folder is the API folder below: usually `server/` beside `src/` in the same package, or the separate `api/` or `server/` folder, or that folder's `src/`. Do not add a second server.
82
+
83
+ 3. **Copy the SPA assets.** Do not change the Passflow calls in them.
84
+
85
+ | Asset | Target | Adapt |
86
+ |---|---|---|
87
+ | `assets/src/passflow.tsx` | `src/passflow.tsx` | Nothing. It also imports `@passflow/react/dist/style.css`. |
88
+ | `assets/src/use-api.ts` | `src/use-api.ts` | Nothing. |
89
+ | `assets/src/require-sign-in.tsx` | `src/require-sign-in.tsx` | Nothing. |
90
+
91
+ JavaScript project (no `tsconfig.json`): save them as `.jsx` and `.js`, and remove everything that is TypeScript only: type annotations, `import type ...` lines and `type` names inside an import list.
92
+
93
+ 4. **Copy the API assets** into the API folder. Do not change the Passflow calls in them.
94
+
95
+ | Asset | Target | When |
96
+ |---|---|---|
97
+ | `assets/server/passflow.ts` | `passflow.ts` | Always. |
98
+ | `assets/server/express.ts` | `passflow-express.ts` | Express. |
99
+ | `assets/server/fastify.ts` | `passflow-fastify.ts` | Fastify. |
100
+ | `assets/server/hono.ts` | `passflow-hono.ts` | Hono. |
101
+ | `assets/server/express-cors.ts` | `passflow-express-cors.ts` | Express with `cors` already a dependency and no CORS middleware yet. See step 6. |
102
+ | `assets/server/fastify-cors.ts` | `passflow-fastify-cors.ts` | Fastify with `@fastify/cors` already a dependency and no CORS registered yet. See step 6. |
103
+ | `assets/server/hono-cors.ts` | `passflow-hono-cors.ts` | Hono with no CORS middleware yet (`hono/cors` ships with `hono`). |
104
+ | `assets/server/tsconfig.json` | `server/tsconfig.json` | Only when the API's TypeScript files sit in the SPA's package in `server/` and nothing type-checks them yet. |
105
+
106
+ - Imports between these files use `./passflow.js`, which fits an API built with `tsc` and one run with `tsx`. Change it to match the API's own relative imports: drop the extension when they have none (a bundler); use `./passflow.ts` when Node runs the `.ts` files as they are (`node --experimental-strip-types`, or `node` on a `.ts` entry), because Node then loads the file by its real name.
107
+ - JavaScript or CommonJS API: as for the SPA, remove what is TypeScript only; for CommonJS turn each `import` into `require` and each `export` into a `module.exports` entry. The package ships CommonJS too.
108
+ - **`/api/me`.** The framework assets add `GET /api/me`, which `verify.sh run` calls. Look at the API's routes first (Grep for `/api/me`). If it already has `/api/me`, do not add a second one: protect its handler in place (step 7), or change only the path string in the copied asset to an unused one such as `/api/passflow/me`, and pass that path to `verify.sh run --api`.
109
+
110
+ 5. **Wire the SPA.** In `src/main.tsx`, wrap the root component in `PassflowRoot`:
111
+
112
+ ```tsx
113
+ import { PassflowRoot } from './passflow';
114
+
115
+ createRoot(document.getElementById('root')!).render(
116
+ <StrictMode>
117
+ <PassflowRoot>
118
+ <App />
119
+ </PassflowRoot>
120
+ </StrictMode>,
121
+ );
122
+ ```
123
+
124
+ Then use the three pieces where the app needs them:
125
+
126
+ | Place | Use |
127
+ |---|---|
128
+ | The header or nav: sign-in and sign-out | `<AccountButton />` from `./passflow` |
129
+ | A page or part only a signed-in user sees | `<RequireSignIn>…</RequireSignIn>` from `./require-sign-in` |
130
+ | A component that calls the API | `const api = useApi();` then `await api(apiUrl('/api/me'))`, both from `./use-api` |
131
+
132
+ `RequireSignIn` renders nothing until the first session check ends, then its children when a user is signed in, else the sign-in button. `useApi()` adds the token for `VITE_API_URL`'s origin only: it returns `passflow.withAuth(fetch, { origins: [apiOrigin] })`, where `passflow` is `usePassflow()`. Never add an `Authorization` header by hand, and never read the token yourself.
133
+
134
+ Sign-in and sign-out return to the app's root URL, because that is the redirect URL the app has registered. A user who signs in from a deeper page lands on the root.
135
+
136
+ 6. **Wire the API.** CORS first, then the routes, on the existing instance (`app`).
137
+
138
+ **CORS.** Pick the first case that fits:
139
+ - The API already mounts a CORS middleware: keep it where it is, before the routes. Add `appOrigin` (from `./passflow.js`) to the origins it allows, or set its origin to it, and wrap its options in `exposeChallengeHeader` from `@passflow/node/express`, `/fastify` or `/hono`: `cors(exposeChallengeHeader({ origin: appOrigin }))`. Keep its `credentials` setting; never turn `credentials` on, since the API takes a bearer token and needs none.
140
+ - The CORS package is a dependency (Express: `cors`; Fastify: `@fastify/cors`; Hono: always) but nothing is mounted: mount the CORS asset before every route:
141
+ ```ts
142
+ app.use(passflowCors); // Express, from ./passflow-express-cors.js
143
+ await passflowCors(app); // Fastify, from ./passflow-fastify-cors.js
144
+ app.use(passflowCors); // Hono, from ./passflow-hono-cors.js
145
+ ```
146
+ - Express without `cors`, or Fastify without `@fastify/cors`: change nothing for CORS. The last step tells the developer what to add.
147
+
148
+ **Routes.** Mount the protected route after CORS:
149
+ ```ts
150
+ app.use(passflowRoutes); // Express, from ./passflow-express.js
151
+ await passflowPlugin(app); // Fastify, from ./passflow-fastify.js
152
+ app.route('/', passflowRoutes); // Hono, from ./passflow-hono.js; give the app the PassflowEnv type
153
+ ```
154
+
155
+ A CommonJS Fastify API has no top-level `await`: put both `await` lines in the async function that starts the server, before `app.listen`, or add one if there is none:
156
+ ```js
157
+ async function start() {
158
+ await passflowCors(app);
159
+ await passflowPlugin(app);
160
+ await app.listen({ port: Number(process.env.PORT ?? 3000) });
161
+ }
162
+ start();
163
+ ```
164
+
165
+ 7. **Protect every API route that returns or changes private data.** Hiding a page in the SPA protects nothing: anyone can call the API without the SPA. So the API checks the token on each protected route, and a public route gets nothing.
166
+
167
+ | Place | Call | Signed out or invalid token |
168
+ |---|---|---|
169
+ | Express route | `app.get('/path', passflow.authenticate, handler)` | 401, `WWW-Authenticate: Bearer` |
170
+ | Fastify route | `{ preHandler: app.passflow.authenticate }` | same |
171
+ | Hono route | `passflow.authenticate` | same |
172
+
173
+ `passflow` is exported by `passflow-express.ts` and `passflow-hono.ts`. Read the claims in a handler with `getAuth(req)` (Express), `getAuth(request)` (Fastify) or `getAuth(c)` (Hono), each imported from the same adapter path. A missing role is a plain 403 with no `WWW-Authenticate`.
174
+
175
+ 8. **Tell the developer.** End with a short message that lists what they still have to do, each as a command or a line to add. Include only the items that apply:
176
+ - **Env values.** If `.env.local` is missing or a value is empty: run `npx passflow integrate`, or copy `.env.example` to `.env.local` and fill in the names from the table in precondition 6 (from the Passflow portal). Set `VITE_API_URL` to the API's origin. Names only in your message, never values.
177
+ - **Loading `.env.local` in the API.** If the API does not read it already (dotenv, `--env-file`, its framework): start it with `--env-file-if-exists=.env.local` (`../.env.local` from a separate API folder), for example `node --env-file-if-exists=.env.local --experimental-strip-types server/index.ts` for TypeScript run as it is. Vite reads the `VITE_` names from the same file for the SPA.
178
+ - **CORS package.** If it is missing: `npm install cors` (plus `npm install -D @types/cors` in a TypeScript API) for Express, or `npm install @fastify/cors` for Fastify, in the API's package and written for its package manager. Then copy the CORS asset and add the one line from step 6, before the routes.
179
+ - **App settings.** For an app made by hand: add `<APP_BASE_URL's origin>/` to its redirect URLs and the origin to its allowed origins (precondition 7).
180
+ - **Run and check.** The SPA with `npm run dev`, the API with its own start command, side by side. Then `bash <skill>/scripts/verify.sh run` with the API stopped (it starts its own copy), plus `--api <path>` when the route is not `/api/me`.
181
+ - In a Passflow GitHub App run, say also which of `run_typecheck()` and `run_build()` passed, and name the route path in your final summary when it is not `/api/me`. The summary goes into the draft PR's description, which tells the developer to run `verify.sh run --api <path>` before merging.
182
+
183
+ ## Guardrails
184
+
185
+ Read `references/guardrails.md` before you edit auth code. In short:
186
+
187
+ - Nothing secret in a `VITE_` variable: Vite ships every one to the browser.
188
+ - The API checks the token on every protected route. Hiding a page in the SPA protects nothing.
189
+ - `PASSFLOW_AUDIENCE` is the SPA app's client ID, the same value as `VITE_PASSFLOW_APP_ID`, or a comma-separated list of client IDs that includes it. Never invent one.
190
+ - Tokens go to the API's origin only, through `useApi()`. Never build an `Authorization` header by hand, and never send the token to another origin.
191
+ - Verify tokens on the API with `createVerifier`; never decode one by hand, in the SPA or the API.
192
+ - CORS goes first on the API, allows the SPA's origin only, and exposes `WWW-Authenticate` through `exposeChallengeHeader`. Never turn on `credentials`.
193
+ - No server code in `src/`: the SPA never imports from the API's folder or from `@passflow/node`.
194
+ - Copy Passflow calls from `assets/`, never from memory.
195
+ - Never print or log a token, an `Authorization` header or an env value.
196
+ - Add no dependency other than `@passflow/react` and `@passflow/node`, edit no `package.json` script, and create or edit no `.env*` file.
197
+
198
+ ## Verification
199
+
200
+ On the developer's machine, run these from the project root; `<skill>` is this skill's directory:
201
+
202
+ ```sh
203
+ bash <skill>/scripts/verify.sh static
204
+ bash <skill>/scripts/verify.sh run
205
+ ```
206
+
207
+ In a Passflow GitHub App run, call `run_typecheck()`, then `run_build()`. If one returns a non-zero exit code, read its tail and fix the copied or wired code, then call it again. The fix never touches a `package.json` script, a dependency or a config file. `run_typecheck()` runs the same checks as `verify.sh static`: for the SPA the `typecheck` script, else `tsc -b` for a `tsconfig.json` with `references`, else `tsc -p tsconfig.json`; for the API also `server/tsconfig.json` when there is one. 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.
208
+
209
+ What `verify.sh` checks. Add `--api-dir api` when the API has its own `package.json` somewhere other than `api/` or `server/` (those are found by themselves when their `package.json` lists `express`, `fastify` or `hono`). Both modes refuse a project with no such API: add an API first.
210
+
211
+ - `static` needs no env values. It installs with lifecycle scripts off (the SPA, and the API folder when it is separate), type-checks the SPA (the `typecheck` script; else `tsc -b --noEmit` for a `tsconfig.json` with project references, as Vite's has, `tsc -p tsconfig.json --noEmit` otherwise) and the API (`server/tsconfig.json`, or the API folder's own check), and builds the SPA. A `VITE_` name that neither the environment nor `.env`, `.env.local`, `.env.production` or `.env.production.local` sets is built with a placeholder, so the bundle holds the whole app; the output says so, and that `dist/` is removed after the scans, so build again before you deploy. Then it scans `dist/` for the names and values of secrets (from `.env.local` and from the environment) and for the API's env names (which appear only when server code reached the bundle), checks that nothing in `src/` imports `@passflow/node`, a server framework or the API's code (relative imports are resolved to real paths, so a browser client in `src/api/` is fine; an alias such as `@/server/` is listed as a `SKIP` to check by hand), checks the env file has no secret-looking `VITE_` name, and scans the source for the guardrail breaks above.
212
+ - `run` needs `.env.local` with `PASSFLOW_ISSUER`, `PASSFLOW_AUDIENCE` and `APP_BASE_URL`. It refuses when something already listens on the port (8086, or `--port`): stop the API you run yourself first. It starts the API with those three names and `PORT` set: the API's `api` script, a separate API folder's `start` or `dev` script, else `server/index.ts` with Node, or the file given with `--entry`; a separate API folder with `start` and `build` scripts is built first, and a build error fails the run. It checks that the process it started is the one answering on the port (with `lsof`; skipped without it). It calls `/api/me` (`--api`) with no token and expects 401 `Bearer` with `Cache-Control: no-store`, then with an invalid token and expects 401 `invalid_token`. With `Origin` set to `APP_BASE_URL`'s origin it checks that the 401 allows that origin and exposes `WWW-Authenticate`, and that a preflight allows the `Authorization` header; another origin gets the 401 without being allowed. The CORS checks are skipped, with the reason, when the API lacks its CORS package (`cors`, `@fastify/cors`) or with `--no-cors` (the SPA calls the API on its own origin, through a Vite proxy for example). A transport failure (no answer) is a `FAIL`. It fails if the API it started exits, and it stops that API at the end. It does not sign in: that takes a browser.
213
+
214
+ Each check prints `PASS`, `FAIL` or `SKIP` (a check that does not apply, such as a bundle scan after a failed build), then `RESULT pass` or `RESULT fail`. Exit 0 is a pass, 1 a failed check, 2 a refusal (unsupported package manager or framework, no API, missing tool or env file, busy port).
215
+
216
+ ## Troubleshooting
217
+
218
+ - **The page is blank and the console says `VITE_PASSFLOW_URL and VITE_PASSFLOW_APP_ID must be set in .env.local`** (or `VITE_API_URL`). The value was missing when Vite started or built. Fill in `.env.local`, then restart `npm run dev` or build again.
219
+ - **Passflow shows "redirect_uri not registered for this client".** The app's redirect URLs lack the SPA's root URL, or the SPA runs on another origin or port than `APP_BASE_URL`. Add `<origin>/` to the app's redirect URLs, or open the SPA on the registered origin.
220
+ - **Every API call gets 401 `invalid_token`.** `PASSFLOW_AUDIENCE` is not, or does not include, the SPA app's client ID, or `PASSFLOW_ISSUER` differs from the token's `iss` (a trailing slash counts). `PASSFLOW_ISSUER` must equal `VITE_PASSFLOW_URL`, and `PASSFLOW_AUDIENCE` must be or include `VITE_PASSFLOW_APP_ID`.
221
+ - **The API call has no `Authorization` header.** The request did not go through `useApi()`, its URL is not on `VITE_API_URL`'s origin, or no user is signed in.
222
+ - **The browser reports a CORS error.** `APP_BASE_URL` does not match the origin the SPA runs on, CORS is mounted after the routes, or the API has no CORS at all. See step 6.
223
+ - **`TypeError: [passflow] issuer must be a non-empty string` when the API starts.** The API did not load `.env.local`. See step 8.
224
+ - **`verify.sh run` refuses: something already listens on the port.** The API (or another server) is running there. Stop it, or pass a free `--port`.
225
+ - **`npx passflow integrate` did not update this skill.** The CLI replaces only a skill copy it installed itself and that is unchanged, as recorded in `.passflow-skill.json`. A skill folder you changed is not overwritten: delete it to get the new version.
@@ -0,0 +1,9 @@
1
+ import { exposeChallengeHeader } from '@passflow/node/express';
2
+ import cors from 'cors';
3
+ import type { RequestHandler } from 'express';
4
+ import { appOrigin } from './passflow.js';
5
+
6
+ // For an API that already depends on cors and mounts no CORS middleware yet: `app.use(passflowCors)` before
7
+ // every route, so a preflight never reaches authentication and a 401 still carries the CORS headers. Only the
8
+ // SPA's origin is allowed; exposeChallengeHeader adds WWW-Authenticate to the exposed headers.
9
+ export const passflowCors: RequestHandler = cors(exposeChallengeHeader({ origin: appOrigin }));
@@ -0,0 +1,14 @@
1
+ import { getAuth, passflowExpress } from '@passflow/node/express';
2
+ import { Router } from 'express';
3
+ import { verifier } from './passflow.js';
4
+
5
+ // authenticate: a verified access token. requireACR(AAL2): a second factor. requireFresh(300): a recent sign-in.
6
+ export const passflow = passflowExpress(verifier);
7
+
8
+ // A protected route: `app.use(passflowRoutes)`, after CORS. Every route that returns or changes private data
9
+ // gets passflow.authenticate.
10
+ export const passflowRoutes = Router();
11
+
12
+ passflowRoutes.get('/api/me', passflow.authenticate, (req, res) => {
13
+ res.set('Cache-Control', 'no-store').json({ sub: getAuth(req).sub });
14
+ });
@@ -0,0 +1,11 @@
1
+ import cors from '@fastify/cors';
2
+ import { exposeChallengeHeader } from '@passflow/node/fastify';
3
+ import type { FastifyInstance } from 'fastify';
4
+ import { appOrigin } from './passflow.js';
5
+
6
+ // For an API that already depends on @fastify/cors and registers no CORS yet: `await passflowCors(app)` before
7
+ // passflowPlugin, so a preflight never reaches authentication and a 401 still carries the CORS headers. Only
8
+ // the SPA's origin is allowed; exposeChallengeHeader adds WWW-Authenticate to the exposed headers.
9
+ export async function passflowCors(app: FastifyInstance): Promise<void> {
10
+ await app.register(cors, exposeChallengeHeader({ origin: appOrigin }));
11
+ }
@@ -0,0 +1,15 @@
1
+ import { getAuth, passflowFastify } from '@passflow/node/fastify';
2
+ import type { FastifyInstance } from 'fastify';
3
+ import { verifier } from './passflow.js';
4
+
5
+ // `await passflowPlugin(app)`, after CORS. Decorates the instance with app.passflow: authenticate,
6
+ // requireACR(level) and requireFresh(seconds). It registers no hook, so each route that returns or changes
7
+ // private data opts in with a preHandler. Register it once per instance.
8
+ export async function passflowPlugin(app: FastifyInstance): Promise<void> {
9
+ await app.register(passflowFastify, { verifier });
10
+
11
+ app.get('/api/me', { preHandler: app.passflow.authenticate }, async (request, reply) => {
12
+ reply.header('Cache-Control', 'no-store');
13
+ return { sub: getAuth(request).sub };
14
+ });
15
+ }
@@ -0,0 +1,8 @@
1
+ import { exposeChallengeHeader } from '@passflow/node/hono';
2
+ import { cors } from 'hono/cors';
3
+ import { appOrigin } from './passflow.js';
4
+
5
+ // For an API that mounts no CORS middleware yet (hono/cors ships with hono): `app.use(passflowCors)` before
6
+ // every route, so a preflight never reaches authentication and a 401 still carries the CORS headers. Only the
7
+ // SPA's origin is allowed; exposeChallengeHeader adds WWW-Authenticate to the exposed headers.
8
+ export const passflowCors = cors(exposeChallengeHeader({ origin: appOrigin }));
@@ -0,0 +1,17 @@
1
+ import { getAuth, type PassflowVariables, passflowHono } from '@passflow/node/hono';
2
+ import { Hono } from 'hono';
3
+ import { verifier } from './passflow.js';
4
+
5
+ export type PassflowEnv = { Variables: PassflowVariables };
6
+
7
+ // authenticate: a verified access token. requireACR(AAL2): a second factor. requireFresh(300): a recent sign-in.
8
+ export const passflow = passflowHono(verifier);
9
+
10
+ // A protected route: `app.route('/', passflowRoutes)`, after CORS. Every route that returns or changes private
11
+ // data gets passflow.authenticate.
12
+ export const passflowRoutes = new Hono<PassflowEnv>();
13
+
14
+ passflowRoutes.get('/api/me', passflow.authenticate, (c) => {
15
+ c.header('Cache-Control', 'no-store');
16
+ return c.json({ sub: getAuth(c).sub });
17
+ });
@@ -0,0 +1,30 @@
1
+ import { createVerifier } from '@passflow/node';
2
+
3
+ // One verifier per trust policy, built once at startup. It owns the key cache.
4
+ // PASSFLOW_ISSUER is matched exactly against the token's `iss`; it is the same URL as VITE_PASSFLOW_URL.
5
+ // PASSFLOW_AUDIENCE is the SPA app's client ID, the same value as VITE_PASSFLOW_APP_ID: the access tokens the
6
+ // SPA sends carry aud = [app ID]. When the API also accepts the tokens of other Passflow apps, it is a
7
+ // comma-separated list of client IDs that includes the SPA's.
8
+ // A missing value throws a TypeError when this module loads.
9
+ export const verifier = createVerifier({
10
+ issuer: process.env.PASSFLOW_ISSUER,
11
+ audience: clientIds(process.env.PASSFLOW_AUDIENCE),
12
+ });
13
+
14
+ // Splits a comma-separated list of client IDs, trims each and drops empty entries. Nothing left counts as
15
+ // missing.
16
+ function clientIds(value: string | undefined): string[] | undefined {
17
+ const ids = (value ?? '')
18
+ .split(',')
19
+ .map((id) => id.trim())
20
+ .filter((id) => id !== '');
21
+ return ids.length > 0 ? ids : undefined;
22
+ }
23
+
24
+ // The SPA's origin, the one origin the API's CORS allows. APP_BASE_URL is the SPA's URL, for example
25
+ // http://localhost:5173.
26
+ const appBaseUrl = process.env.APP_BASE_URL;
27
+ if (!appBaseUrl) {
28
+ throw new TypeError('[passflow] APP_BASE_URL must be set to the SPA URL');
29
+ }
30
+ export const appOrigin = new URL(appBaseUrl).origin;