@pithy-sh/auth 0.8.0 → 0.10.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/README.md +12 -2
- package/dist/audit/actions.d.ts +21 -0
- package/dist/audit/actions.d.ts.map +1 -1
- package/dist/audit/actions.js +22 -1
- package/dist/audit/emit.js +1 -1
- package/dist/caller/certificate.d.ts +83 -0
- package/dist/caller/certificate.d.ts.map +1 -0
- package/dist/caller/certificate.js +92 -0
- package/dist/caller/request.d.ts +66 -0
- package/dist/caller/request.d.ts.map +1 -0
- package/dist/caller/request.js +71 -0
- package/dist/caller/token.d.ts +130 -0
- package/dist/caller/token.d.ts.map +1 -0
- package/dist/caller/token.js +207 -0
- package/dist/capability.d.ts +70 -2
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +28 -7
- package/dist/client/lifecycle.d.ts +19 -0
- package/dist/client/lifecycle.d.ts.map +1 -0
- package/dist/client/lifecycle.js +25 -0
- package/dist/client/projection.d.ts +4 -0
- package/dist/client/projection.d.ts.map +1 -1
- package/dist/data/betterAuth.d.ts +5 -1
- package/dist/data/betterAuth.d.ts.map +1 -1
- package/dist/data/betterAuth.js +7 -3
- package/dist/data/kitFields.d.ts +20 -25
- package/dist/data/kitFields.d.ts.map +1 -1
- package/dist/data/kitFields.js +28 -32
- package/dist/data/tables.d.ts +29 -3
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/tables.js +5 -3
- package/dist/data/userLifecycle.d.ts +61 -0
- package/dist/data/userLifecycle.d.ts.map +1 -0
- package/dist/data/userLifecycle.js +50 -0
- package/dist/http/credentialResign.d.ts +46 -0
- package/dist/http/credentialResign.d.ts.map +1 -0
- package/dist/http/credentialResign.js +203 -0
- package/dist/http/errorCallbackUrl.d.ts.map +1 -1
- package/dist/http/errorCallbackUrl.js +15 -9
- package/dist/http/guards.d.ts +23 -1
- package/dist/http/guards.d.ts.map +1 -1
- package/dist/http/guards.js +28 -3
- package/dist/http/lifecycleGate.d.ts +18 -0
- package/dist/http/lifecycleGate.d.ts.map +1 -0
- package/dist/http/lifecycleGate.js +75 -0
- package/dist/http/middleware.d.ts +5 -0
- package/dist/http/middleware.d.ts.map +1 -1
- package/dist/http/middleware.js +113 -21
- package/dist/http/providerRefusal.d.ts +8 -7
- package/dist/http/providerRefusal.d.ts.map +1 -1
- package/dist/http/providerRefusal.js +37 -32
- package/dist/http/resolve.d.ts.map +1 -1
- package/dist/http/resolve.js +23 -5
- package/dist/http/routes.d.ts.map +1 -1
- package/dist/http/routes.js +20 -1
- package/dist/instance/auth.d.ts +1280 -5
- package/dist/instance/auth.d.ts.map +1 -1
- package/dist/instance/auth.js +59 -4
- package/dist/instance/jwksReencryption.d.ts +75 -0
- package/dist/instance/jwksReencryption.d.ts.map +1 -0
- package/dist/instance/jwksReencryption.js +160 -0
- package/dist/instance/microsoftEmail.d.ts +70 -0
- package/dist/instance/microsoftEmail.d.ts.map +1 -0
- package/dist/instance/microsoftEmail.js +96 -0
- package/dist/instance/providerSignInGate.d.ts +14 -12
- package/dist/instance/providerSignInGate.d.ts.map +1 -1
- package/dist/instance/providerSignInGate.js +23 -20
- package/dist/instance/providers.d.ts +7 -5
- package/dist/instance/providers.d.ts.map +1 -1
- package/dist/instance/providers.js +5 -3
- package/dist/instance/secrets.d.ts +232 -4
- package/dist/instance/secrets.d.ts.map +1 -1
- package/dist/instance/secrets.js +129 -7
- package/dist/instance/sessionSecrets.d.ts +45 -0
- package/dist/instance/sessionSecrets.d.ts.map +1 -0
- package/dist/instance/sessionSecrets.js +29 -0
- package/dist/lifecycle/enforce.d.ts +40 -0
- package/dist/lifecycle/enforce.d.ts.map +1 -0
- package/dist/lifecycle/enforce.js +70 -0
- package/dist/lifecycle/hooks.d.ts +53 -0
- package/dist/lifecycle/hooks.d.ts.map +1 -0
- package/dist/lifecycle/hooks.js +2 -0
- package/dist/lifecycle/request.d.ts +15 -0
- package/dist/lifecycle/request.d.ts.map +1 -0
- package/dist/lifecycle/request.js +27 -0
- package/dist/lifecycle/state.d.ts +64 -0
- package/dist/lifecycle/state.d.ts.map +1 -0
- package/dist/lifecycle/state.js +90 -0
- package/dist/lifecycle/transitions.d.ts +132 -0
- package/dist/lifecycle/transitions.d.ts.map +1 -0
- package/dist/lifecycle/transitions.js +349 -0
- package/dist/migrations/0001_init.d.ts.map +1 -1
- package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
- package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
- package/dist/migrations/0003_account_issuer_nullable.js +131 -0
- package/dist/migrations/0004_user_lifecycle.d.ts +28 -0
- package/dist/migrations/0004_user_lifecycle.d.ts.map +1 -0
- package/dist/migrations/0004_user_lifecycle.js +47 -0
- package/dist/migrations/set.d.ts +3 -1
- package/dist/migrations/set.d.ts.map +1 -1
- package/dist/migrations/set.js +6 -2
- package/dist/peer.d.ts +4 -0
- package/dist/peer.d.ts.map +1 -1
- package/dist/test-utils/liveApp.d.ts +26 -0
- package/dist/test-utils/liveApp.d.ts.map +1 -1
- package/dist/test-utils/liveApp.js +1 -0
- package/dist/test-utils/schemaDrift.d.ts +49 -0
- package/dist/test-utils/schemaDrift.d.ts.map +1 -0
- package/dist/test-utils/schemaDrift.js +35 -0
- package/dist/test-utils/scopedBackend.d.ts +204 -0
- package/dist/test-utils/scopedBackend.d.ts.map +1 -0
- package/dist/test-utils/scopedBackend.js +166 -0
- package/dist/version.generated.d.ts +1 -1
- package/dist/version.generated.d.ts.map +1 -1
- package/dist/version.generated.js +1 -1
- package/docs/account-lifecycle.md +105 -0
- package/docs/apple-signin.md +7 -1
- package/docs/facebook-oauth.md +7 -1
- package/docs/github-oauth.md +7 -1
- package/docs/google-oauth.md +7 -1
- package/docs/microsoft-oauth.md +177 -0
- package/docs/server-authoritative.md +182 -0
- package/package.json +11 -8
- package/pithy.manifest.json +17 -3
- package/src/audit/actions.ts +23 -0
- package/src/audit/emit.ts +1 -1
- package/src/caller/certificate.ts +133 -0
- package/src/caller/request.ts +84 -0
- package/src/caller/token.ts +276 -0
- package/src/capability.ts +170 -38
- package/src/client/lifecycle.ts +27 -0
- package/src/client/projection.ts +4 -0
- package/src/data/betterAuth.ts +23 -2
- package/src/data/kitFields.ts +27 -0
- package/src/data/tables.ts +4 -2
- package/src/data/userLifecycle.ts +80 -0
- package/src/http/credentialResign.ts +268 -0
- package/src/http/errorCallbackUrl.ts +21 -13
- package/src/http/guards.ts +29 -1
- package/src/http/lifecycleGate.ts +78 -0
- package/src/http/middleware.ts +161 -37
- package/src/http/providerRefusal.ts +40 -32
- package/src/http/resolve.ts +34 -5
- package/src/http/routes.ts +39 -2
- package/src/instance/auth.ts +91 -6
- package/src/instance/jwksReencryption.ts +206 -0
- package/src/instance/microsoftEmail.ts +111 -0
- package/src/instance/providerSignInGate.ts +30 -27
- package/src/instance/providers.ts +8 -4
- package/src/instance/secrets.ts +153 -6
- package/src/instance/sessionSecrets.ts +64 -0
- package/src/lifecycle/enforce.ts +89 -0
- package/src/lifecycle/hooks.ts +54 -0
- package/src/lifecycle/request.ts +31 -0
- package/src/lifecycle/state.ts +101 -0
- package/src/lifecycle/transitions.ts +483 -0
- package/src/migrations/0001_init.ts +8 -10
- package/src/migrations/0003_account_issuer_nullable.ts +199 -0
- package/src/migrations/0004_user_lifecycle.ts +68 -0
- package/src/migrations/set.ts +5 -1
- package/src/test-utils/liveApp.ts +2 -1
- package/src/test-utils/schemaDrift.ts +82 -0
- package/src/test-utils/scopedBackend.ts +137 -0
- package/src/version.generated.ts +1 -1
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# Server-authoritative writes
|
|
2
|
+
|
|
3
|
+
_This copy ships in the package because `src/capability.ts` sends an adopter to it by name._
|
|
4
|
+
|
|
5
|
+
Some writes belong to your backend and never to a device. A score, a match result, a balance. `@pithy-sh/auth` decides, per request, whether the caller is your backend. This page is how.
|
|
6
|
+
|
|
7
|
+
## What a scope is
|
|
8
|
+
|
|
9
|
+
Six routes in the kit check one of four scopes on `AuthContext`:
|
|
10
|
+
|
|
11
|
+
| Scope | Capability | What it opens | Off switch |
|
|
12
|
+
|---|---|---|---|
|
|
13
|
+
| `leaderboard:submit` | `@pithy-sh/leaderboard` | `POST /leaderboard/:board` | `serverAuthoritative: false` |
|
|
14
|
+
| `leaderboard:admin` | `@pithy-sh/leaderboard` | hide and remove another player's entry | none |
|
|
15
|
+
| `rating:record` | `@pithy-sh/rating` | `POST /rating/games/:game/outcomes` | `serverAuthoritative: false` |
|
|
16
|
+
| `ledger:admin` | `@pithy-sh/ledger` | credit and debit another player's balance | none |
|
|
17
|
+
|
|
18
|
+
**A scope is an attestation about the caller, not a permission granted to the user.** It says *this write came from your trusted backend*. It is not a role. Tenancy roles live on `c.var.acting`, from `@pithy-sh/organization`. Management access is the control plane's, with its own credential.
|
|
19
|
+
|
|
20
|
+
Every gate fails closed. With nothing to fill the array, each one refuses every caller. `pithy doctor` names each gate in that state, per Worker, on its `scopes` line.
|
|
21
|
+
|
|
22
|
+
## The seam: `resolveScopes`
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// apps/api/pithy.config.ts
|
|
26
|
+
auth({
|
|
27
|
+
baseURL: PUBLIC_ORIGIN,
|
|
28
|
+
resolveScopes: async (c) =>
|
|
29
|
+
(await verifyCallerRequest(c, { audience: PUBLIC_ORIGIN })).trusted ? ["leaderboard:submit", "rating:record"] : [],
|
|
30
|
+
}),
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
The session middleware calls it on every authenticated request, after Better Auth resolves the session. What it returns becomes `c.var.auth.scopes`. It is handed the request context and the session, `{ userId, sessionId }`.
|
|
34
|
+
|
|
35
|
+
- **Per request, never cached.** A cached scope is a revocation that has not taken effect.
|
|
36
|
+
- **Closed on failure, never fatal.** A resolver that throws, or answers anything but a list of strings, leaves the request with no scopes. It logs at warn and the request goes on to its gate, which refuses it.
|
|
37
|
+
- **No default.** Without one the array is empty and nothing extra runs.
|
|
38
|
+
- **Never from what the request says.** Not a header like `x-scopes`, not a body field, not a query parameter. Only from what the request proves.
|
|
39
|
+
|
|
40
|
+
**The session is the player's, and the backend forwards it.** A gated write is still an authenticated request, and the route acts for the session's user. `POST /leaderboard/:board` files the score under that user and takes no player in its body. So the backend relays the player's own session on `Authorization` and adds its proof beside it. A backend that called with a session of its own would put every score under its own account. Rating outcomes, ledger credits and the admin routes name their target in the body or the path, so any session works for them.
|
|
41
|
+
|
|
42
|
+
**The proof is not bound to that session.** A caller token, a certificate or a binding says the request came from your backend. It does not say which player the backend meant. Whichever session arrives beside a valid proof is the one the write is credited to, so the backend must forward only the session of the player the write is for.
|
|
43
|
+
|
|
44
|
+
## Three ways to prove the caller
|
|
45
|
+
|
|
46
|
+
In order. Use the first one you can.
|
|
47
|
+
|
|
48
|
+
### 1. A service binding. No credential at all.
|
|
49
|
+
|
|
50
|
+
If your trusted backend is a Worker, call over a service binding. There is no public network path, so there is nothing to steal, expire or rotate. **Where you can use this, the other two are unnecessary.**
|
|
51
|
+
|
|
52
|
+
A request that arrives over a binding carries no mark of it, so the boundary is the Worker itself. Compose the gated capabilities into a Worker with no public address, and share the database by declaring the same `DB` binding. In its `wrangler.jsonc`, for each environment:
|
|
53
|
+
|
|
54
|
+
```jsonc
|
|
55
|
+
// apps/internal/wrangler.jsonc
|
|
56
|
+
"workers_dev": false,
|
|
57
|
+
"preview_urls": false,
|
|
58
|
+
// and no "routes", no "domains" in pithy.config.ts, no vars.BASE_URL
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
All three, set explicitly. `pithy deploy --env staging|prod` and `pithy doctor` read that shape as a Worker reachable only over a binding, and let it through with no origin. Leave one out and deploy refuses the Worker for having no origin, as it refuses any other.
|
|
62
|
+
|
|
63
|
+
Nothing but a binding can reach that Worker, so its resolver answers for every request it receives:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
// apps/internal/pithy.config.ts — reachable only over a service binding
|
|
67
|
+
const INTERNAL_ORIGIN = "https://internal.invalid";
|
|
68
|
+
|
|
69
|
+
auth({ baseURL: INTERNAL_ORIGIN, resolveScopes: () => ["leaderboard:submit", "rating:record", "ledger:admin"] }),
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`INTERNAL_ORIGIN` is the URL the caller fetches over the binding. A binding routes by its name, never by hostname, so the host is yours to pick; `.invalid` is reserved and resolves nowhere, so nothing outside the binding can reach it by mistake. Use the same origin on both sides: `` env.INTERNAL.fetch(`${INTERNAL_ORIGIN}/leaderboard/weekly`, …) ``. The forwarded session travels on `Authorization`, so the CSRF origin check does not apply.
|
|
73
|
+
|
|
74
|
+
The caller declares `{ type: "service", name: "INTERNAL", service: "internal" }`. Give it a route later and the resolver above trusts the internet, so the two decisions stay together.
|
|
75
|
+
|
|
76
|
+
### 2. mTLS. Refused at the edge.
|
|
77
|
+
|
|
78
|
+
A client certificate is sender-constrained: a stolen token is useless without the private key. Cloudflare-managed client certificates are available on every plan. They need a proxied zone and a hostname that matches the certificate exactly. No wildcards, so not `workers.dev`.
|
|
79
|
+
|
|
80
|
+
**The zone rule is the gate.** Create a WAF custom rule on the hostname, action Block:
|
|
81
|
+
|
|
82
|
+
```
|
|
83
|
+
(http.host eq "api.example.com" and (not cf.tls_client_auth.cert_verified or cf.tls_client_auth.cert_revoked))
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Both halves. A revoked certificate whose chain still verifies reports `cert_verified` true, so the first half alone lets it through. This is the shape of the rule Cloudflare generates for mTLS.
|
|
87
|
+
|
|
88
|
+
It runs before the Worker, so a caller without a verified, unrevoked certificate never reaches your code. Scope it to the paths only your backend calls if devices share the hostname.
|
|
89
|
+
|
|
90
|
+
**The Worker helper is defense in depth, not the gate.** `readClientCertificate` reads `request.cf.tlsClientAuth`, and `isTrustedCertificate` checks it against pins. On its own it blocks nothing. A Worker with no zone rule in front of it receives every request, certificate or not.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { isTrustedCertificate, readClientCertificate } from "@pithy-sh/auth/src/caller/certificate";
|
|
94
|
+
|
|
95
|
+
resolveScopes: (c) =>
|
|
96
|
+
isTrustedCertificate(readClientCertificate(c.req.raw), { fingerprintsSHA256: [GAME_SERVER_CERT] })
|
|
97
|
+
? ["leaderboard:submit"]
|
|
98
|
+
: [],
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The helper answers four states: `absent`, `unverified`, `revoked` and `verified`. Only `verified` with `certVerified === "SUCCESS"` and no revocation is trusted, and only against a fingerprint pin. Without one it trusts nothing, because every certificate your zone's CA issued would pass. An issuer pin is an extra check, never a substitute: on the Cloudflare-managed CA every certificate the zone verifies names the same issuer.
|
|
102
|
+
|
|
103
|
+
### 3. A short-lived token bound to this origin. For a backend off Cloudflare.
|
|
104
|
+
|
|
105
|
+
The option for a backend that is not a Worker, on `workers.dev` or any other host. A token signed with a shared key, minted for this Worker's origin, alive for minutes. A Worker of your own project does not need it: it calls over a service binding.
|
|
106
|
+
|
|
107
|
+
Declare the key in the project registry, so `pithy secrets` knows it:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { callerTokenRegistry } from "@pithy-sh/auth/src/caller/request";
|
|
111
|
+
|
|
112
|
+
secrets({ registry: { ...authSecretsRegistry, ...callerTokenRegistry } }),
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
#### The signing key
|
|
116
|
+
|
|
117
|
+
Two parties hold one value: this Worker, which verifies, and your backend, which signs. **You make it, not the kit.** Nothing in the kit hands a stored value back out, so a key the kit minted is one your backend could never learn. `pithy secrets provision` therefore does not create it.
|
|
118
|
+
|
|
119
|
+
1. Generate the value where your backend's secrets live: `openssl rand -base64 32`. That prints 44 characters of base64 text, and **the text is the key**.
|
|
120
|
+
2. Store that text in your backend's own secret manager, as it was printed.
|
|
121
|
+
3. Pipe the same value into each environment: `printf '%s' "$KEY" | pithy secrets create auth-caller-token-key --env prod`. In `dev`, write it into the dev secrets file with `pithy secrets edit`.
|
|
122
|
+
|
|
123
|
+
**Rotation is a cutover, and it is yours.** `pithy secrets update` replaces the value, and every value it writes is version `1`, so the backend signs with `kid: "1"`. A token signed with the old key is refused from the moment the Worker holds the new one. Generate the new value and change the Worker's copy and the backend's back to back. Writes between the two are refused, so the backend retries a refused write once it holds the new key. `pithy secrets rotate` does not invent a value here; it names this page.
|
|
124
|
+
|
|
125
|
+
Mint on the backend, one token per call or per few minutes, and send it on the `pithy-caller` header beside the player's session:
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
import { mintCallerToken } from "@pithy-sh/auth/src/caller/token";
|
|
129
|
+
|
|
130
|
+
const token = await mintCallerToken({ key: CALLER_TOKEN_KEY, kid: "1", audience: API_ORIGIN });
|
|
131
|
+
await fetch(`${API_ORIGIN}/leaderboard/weekly`, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: { authorization: `Bearer ${playerSession}`, "pithy-caller": token, "content-type": "application/json" },
|
|
134
|
+
body: JSON.stringify({ score }),
|
|
135
|
+
});
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
#### The token, for a backend that does not import the kit
|
|
139
|
+
|
|
140
|
+
`mintCallerToken` is a convenience, not a requirement. Any language can build the token. It is a compact JWS:
|
|
141
|
+
|
|
142
|
+
- **Three segments**, `header.claims.signature`, each **unpadded base64url**. Padding and the standard alphabet are refused.
|
|
143
|
+
- **The header** is `{"alg":"HS256","typ":"JWT","kid":"1"}`. `alg` must be `HS256`. `kid` is required and names the key version. `typ` is optional.
|
|
144
|
+
- **The claims** are `{"aud":"https://api.example.com","iat":1760788800,"exp":1760789100}`. `aud` is one string, the origin of the Worker the token is for, never an array and never a path. `iat` and `exp` are whole Unix seconds. `exp` is at most 900 seconds after `iat`, and `iat` at most 30 seconds in the future. `sub` is optional and grants nothing.
|
|
145
|
+
- **The signature** is HMAC-SHA-256 over the ASCII bytes of `header.claims`, as they appear in the token.
|
|
146
|
+
- **The HMAC key is the UTF-8 bytes of the stored string.** The 44 characters `openssl` printed, not the 32 bytes they decode to. A signer that base64-decodes the key first produces a token refused on its signature, every time.
|
|
147
|
+
|
|
148
|
+
In Python, with nothing but the standard library:
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
import base64, hashlib, hmac, json, time
|
|
152
|
+
|
|
153
|
+
def seg(raw: bytes) -> str:
|
|
154
|
+
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
|
155
|
+
|
|
156
|
+
def caller_token(key: str, audience: str) -> str:
|
|
157
|
+
now = int(time.time())
|
|
158
|
+
header = seg(json.dumps({"alg": "HS256", "typ": "JWT", "kid": "1"}).encode())
|
|
159
|
+
claims = seg(json.dumps({"aud": audience, "iat": now, "exp": now + 300}).encode())
|
|
160
|
+
signing_input = f"{header}.{claims}"
|
|
161
|
+
signature = hmac.new(key.encode("utf-8"), signing_input.encode(), hashlib.sha256).digest()
|
|
162
|
+
return f"{signing_input}.{seg(signature)}"
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### Verifying
|
|
166
|
+
|
|
167
|
+
Verify in the resolver with `verifyCallerRequest`, as in the first example. It refuses, each on its own:
|
|
168
|
+
|
|
169
|
+
- an expired token,
|
|
170
|
+
- a token minted for another origin,
|
|
171
|
+
- a token signed by a key the store does not hold,
|
|
172
|
+
- anything that is not a well-formed HS256 compact JWS.
|
|
173
|
+
|
|
174
|
+
A token lives five minutes by default and fifteen at most. A token claiming longer is refused even when everything else checks out.
|
|
175
|
+
|
|
176
|
+
**It is not sender-constrained.** A token lifted off the wire works for whoever lifted it, for the minutes it has left. The short lifetime is what bounds that. DPoP would bind it to the sender; the kit does not ship it yet.
|
|
177
|
+
|
|
178
|
+
## What not to do
|
|
179
|
+
|
|
180
|
+
**Do not compare a long-lived shared secret in a header.** It is the shape everyone reaches for, and it fails every control RFC 9700 names at once: it is not least-privilege, it is not bound to an audience, it does not expire and it is not bound to its sender. One leak is permanent until somebody notices.
|
|
181
|
+
|
|
182
|
+
**Do not mint a scope from the user.** A player's account is not a trusted backend because of who owns it. Decide from the request, every time.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pithy-sh/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
},
|
|
28
28
|
"scripts": {
|
|
29
29
|
"build": "tsdown && tsc -p tsconfig.build.json && bun ../../tooling/build/src/stampDeclarations.ts",
|
|
30
|
-
"typecheck": "
|
|
30
|
+
"typecheck": "bun check -p tsconfig.json && bun check -p tsconfig.client.json",
|
|
31
31
|
"test": "vitest run",
|
|
32
32
|
"test:node": "vitest run --project=node",
|
|
33
33
|
"test:workers": "vitest run --project=workers",
|
|
@@ -36,16 +36,16 @@
|
|
|
36
36
|
"reset": "bun run clean && rm -rf node_modules"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@better-auth/i18n": "^1.7.
|
|
39
|
+
"@better-auth/i18n": "^1.7.11",
|
|
40
40
|
"@cloudflare/workers-types": "^5.20260729.1",
|
|
41
41
|
"@hono/zod-validator": "^0.9.0",
|
|
42
|
-
"better-auth": "^1.7.
|
|
42
|
+
"better-auth": "^1.7.11"
|
|
43
43
|
},
|
|
44
44
|
"peerDependencies": {
|
|
45
|
-
"@pithy-sh/core": "^0.
|
|
46
|
-
"@pithy-sh/email": "^0.
|
|
47
|
-
"@pithy-sh/secrets": "^0.
|
|
48
|
-
"@pithy-sh/turnstile": "^0.
|
|
45
|
+
"@pithy-sh/core": "^0.12.0",
|
|
46
|
+
"@pithy-sh/email": "^0.6.0",
|
|
47
|
+
"@pithy-sh/secrets": "^0.6.0",
|
|
48
|
+
"@pithy-sh/turnstile": "^0.6.0",
|
|
49
49
|
"hono": "^4.13.2",
|
|
50
50
|
"kysely": "^0.29.0",
|
|
51
51
|
"zod": "^4.4.0"
|
|
@@ -55,6 +55,9 @@
|
|
|
55
55
|
"@pithy-sh/cloudflare": "workspace:*",
|
|
56
56
|
"@pithy-sh/core": "workspace:*",
|
|
57
57
|
"@pithy-sh/email": "workspace:*",
|
|
58
|
+
"@pithy-sh/leaderboard": "workspace:*",
|
|
59
|
+
"@pithy-sh/ledger": "workspace:*",
|
|
60
|
+
"@pithy-sh/rating": "workspace:*",
|
|
58
61
|
"@pithy-sh/secrets": "workspace:*",
|
|
59
62
|
"@pithy-sh/tsconfig": "workspace:*",
|
|
60
63
|
"@pithy-sh/turnstile": "workspace:*",
|
package/pithy.manifest.json
CHANGED
|
@@ -72,9 +72,22 @@
|
|
|
72
72
|
"issuer": "github",
|
|
73
73
|
"documentation": "https://github.com/settings/developers"
|
|
74
74
|
}
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"name": "auth-microsoft-credentials",
|
|
78
|
+
"origin": {
|
|
79
|
+
"kind": "obtained",
|
|
80
|
+
"issuer": "microsoft",
|
|
81
|
+
"documentation": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"
|
|
82
|
+
},
|
|
83
|
+
"rotation": {
|
|
84
|
+
"kind": "manual",
|
|
85
|
+
"issuer": "microsoft",
|
|
86
|
+
"documentation": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"
|
|
87
|
+
}
|
|
75
88
|
}
|
|
76
89
|
],
|
|
77
|
-
"whenToEnable": "Sign-in for your app — passwordless, mobile and web both first-class. Magic link, email OTP, and social sign-in with Google, Apple, Facebook, and
|
|
90
|
+
"whenToEnable": "Sign-in for your app — passwordless, mobile and web both first-class. Magic link, email OTP, and social sign-in with Google, Apple, Facebook, GitHub, and Microsoft. A successful sign-in mints a long-lived refresh session and short-lived JWT access tokens that verify locally with no database hit. It fills core's identity seams, so every other capability just calls `requireAuth()`. This is the keystone capability; add it first.",
|
|
78
91
|
"scaffold": [
|
|
79
92
|
"Create the session signing secret: `pithy secrets create auth-session-secret`.",
|
|
80
93
|
"Add the `AUTH_RATE_LIMITER` Workers Rate Limiting binding to each wrangler.jsonc env — the coarse per-IP edge guard on the auth routes. For example: `\"ratelimits\": [{ \"name\": \"AUTH_RATE_LIMITER\", \"namespace_id\": \"1001\", \"simple\": { \"limit\": 60, \"period\": 60 } }]`. This is tier 1; Better Auth's per-action limiter (tier 2) is built in.",
|
|
@@ -85,7 +98,8 @@
|
|
|
85
98
|
"Apple (optional): set `apple: { enabled: true }`, then `pithy secrets create auth-apple-credentials` with the typed JSON `{ clientId, clientSecret, appBundleIdentifier? }`. See the package's docs/apple-signin.md.",
|
|
86
99
|
"Facebook (optional): set `facebook: { enabled: true }`, then `pithy secrets create auth-facebook-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/facebook-oauth.md.",
|
|
87
100
|
"GitHub (optional): set `github: { enabled: true }`, then `pithy secrets create auth-github-credentials` with the typed JSON `{ clientId, clientSecret }`. See the package's docs/github-oauth.md.",
|
|
88
|
-
"
|
|
101
|
+
"Microsoft (optional): set `microsoft: { enabled: true }`, then `pithy secrets create auth-microsoft-credentials` with the typed JSON `{ clientId, clientSecret, tenantId }`. Add the `xms_edov` optional claim to the ID token in the app registration, or every work and school address is verified by magic link before it links. See the package's docs/microsoft-oauth.md.",
|
|
102
|
+
"Looking a user up and signing them out from a dashboard is a `control-plane` surface, not an admin user, so the routes under /auth/admin are reached with a signed management credential rather than a session. Add `controlplane()` to this Worker and run `pithy dashboard connect`, then grant the connection only what its tooling needs: `auth:users:read` to find people, `auth:devices:read` to walk the device registry, `auth:sessions:revoke` to kill one stolen session, `auth:users:logout` to sign somebody out everywhere, `auth:devices:revoke` for a phone reported lost, and the account lifecycle's three: `auth:users:suspend`, `auth:users:delete`, `auth:users:export`. Eight scopes and not one admin flag — a support tool that looks people up must not also be able to sign the customer base out, and an incident-response tool that kills a session has no business reading every address in the user table. With the seam not composed every /auth/admin route answers `controlplane/not_connected`, and no app session opens any of them whatever it carries. There is deliberately no impersonation: signing in as a user produces a credential indistinguishable from theirs, so it is excluded until it has its own design and security review."
|
|
89
103
|
],
|
|
90
104
|
"configOptions": [
|
|
91
105
|
{
|
|
@@ -97,7 +111,7 @@
|
|
|
97
111
|
"key": "baseURL",
|
|
98
112
|
"default": "https://api.example.com",
|
|
99
113
|
"constant": "publicOrigin",
|
|
100
|
-
"describe": "The public origin of this Worker where it is deployed, no trailing slash. OAuth callbacks, JWKS and magic-link URLs are built from it, so it must be reachable. A `dev` composition ignores it and serves on `http://<the host the request arrived at>` — local dev has no TLS and its port is assigned per run, so it is the one address nobody can write down. Set `trustedOrigins` and the social providers (`google`, `apple`, `facebook`, `github`) by hand — see the scaffold steps below."
|
|
114
|
+
"describe": "The public origin of this Worker where it is deployed, no trailing slash. OAuth callbacks, JWKS and magic-link URLs are built from it, so it must be reachable. A `dev` composition ignores it and serves on `http://<the host the request arrived at>` — local dev has no TLS and its port is assigned per run, so it is the one address nobody can write down. Set `trustedOrigins` and the social providers (`google`, `apple`, `facebook`, `github`, `microsoft`) by hand — see the scaffold steps below."
|
|
101
115
|
},
|
|
102
116
|
{
|
|
103
117
|
"key": "disableSignUp",
|
package/src/audit/actions.ts
CHANGED
|
@@ -150,6 +150,29 @@ export const AuthAuditActions = {
|
|
|
150
150
|
adminUserSessionsRevoked: "auth/admin_user_sessions_revoked",
|
|
151
151
|
/** One of a user's devices was signed out and its registration dropped, from the management surface. */
|
|
152
152
|
adminDeviceRevoked: "auth/admin_device_revoked",
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The account lifecycle (#620). Each is written by the transition in `../lifecycle/transitions.ts`, beside
|
|
156
|
+
* the `pithy_auth_user_lifecycle` row that records the same fact — the trail answers "who, from where", the
|
|
157
|
+
* table answers "what happened to this account". The admin ones carry `actorType: "control-plane"`; the
|
|
158
|
+
* self-service deletion carries the account's own holder, and the purge `system`.
|
|
159
|
+
*
|
|
160
|
+
* The dashboard's own `customer/user_suspended` and `customer/user_restored` are the client side of the
|
|
161
|
+
* same events, recorded where the operator pressed the button.
|
|
162
|
+
*/
|
|
163
|
+
|
|
164
|
+
/** An account was suspended from the management surface. Carries the reason and any end date. */
|
|
165
|
+
adminUserSuspended: "auth/admin_user_suspended",
|
|
166
|
+
/** A suspended account was reinstated from the management surface. */
|
|
167
|
+
adminUserReinstated: "auth/admin_user_reinstated",
|
|
168
|
+
/** An account was deleted from the management surface, with its purge window starting now. */
|
|
169
|
+
adminUserSoftDeleted: "auth/admin_user_soft_deleted",
|
|
170
|
+
/** A deleted account was restored inside its purge window, from the management surface. */
|
|
171
|
+
adminUserRestored: "auth/admin_user_restored",
|
|
172
|
+
/** A deleted account's data was erased. Recorded once, when the last purge step has run. */
|
|
173
|
+
adminUserPurged: "auth/admin_user_purged",
|
|
174
|
+
/** The account's own holder deleted their account. Always a soft deletion, on the configured window. */
|
|
175
|
+
userSelfDeleted: "auth/user_self_deleted",
|
|
153
176
|
} as const;
|
|
154
177
|
|
|
155
178
|
/** One of the auth audit action codes. */
|
package/src/audit/emit.ts
CHANGED
|
@@ -431,7 +431,7 @@ export const ProviderAccount = z
|
|
|
431
431
|
.object({
|
|
432
432
|
id: z.string().describe("The account row's primary key — which link was made or broken."),
|
|
433
433
|
userId: z.string().describe("The user this provider can, or could, sign in as."),
|
|
434
|
-
providerId: z.string().describe("The provider slug (`google`, `apple`, `facebook`, `github`)."),
|
|
434
|
+
providerId: z.string().describe("The provider slug (`google`, `apple`, `facebook`, `github`, `microsoft`)."),
|
|
435
435
|
})
|
|
436
436
|
.describe("The account-row columns `auth/oauth_linked` and `auth/oauth_unlinked` are built from.");
|
|
437
437
|
export type ProviderAccount = z.output<typeof ProviderAccount>;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* **The client certificate a request arrived with, read off `request.cf.tlsClientAuth` (#560).**
|
|
8
|
+
*
|
|
9
|
+
* mTLS is the option that is sender-constrained at the edge: the zone refuses a caller without a
|
|
10
|
+
* certificate **before the Worker runs**, through a WAF custom rule scoped to the hostname that blocks on
|
|
11
|
+
* `not cf.tls_client_auth.cert_verified or cf.tls_client_auth.cert_revoked`. Both halves, because a revoked
|
|
12
|
+
* certificate whose chain verifies still reports `cert_verified`. That rule is the gate. **This helper is not.** It is a defense-in-depth check
|
|
13
|
+
* inside the Worker, for the one question the zone rule cannot answer — which of the certificates your CA
|
|
14
|
+
* issued is this — and on its own it blocks nothing: a Worker with no zone rule in front of it still
|
|
15
|
+
* receives every request, certificate or not, and a resolver that forgot to call this would trust them all.
|
|
16
|
+
*
|
|
17
|
+
* Cloudflare-managed client certificates are available on every plan. They need a proxied zone and a
|
|
18
|
+
* hostname that matches exactly — no wildcards, so not `workers.dev`. `docs/server-authoritative.md` has
|
|
19
|
+
* the rule and the setup.
|
|
20
|
+
*
|
|
21
|
+
* **Anything other than `certVerified === "SUCCESS"` is untrusted**, and so is a revoked certificate whose
|
|
22
|
+
* chain did verify. "No certificate" and "a certificate that did not verify" are different states, because
|
|
23
|
+
* the first is an ordinary device and the second is somebody presenting a certificate your CA did not issue,
|
|
24
|
+
* and an adopter's log should be able to tell them apart.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/** The fields of `request.cf.tlsClientAuth` this reads. Cloudflare sends more; nothing here needs them. */
|
|
28
|
+
export const TlsClientAuth = z
|
|
29
|
+
.object({
|
|
30
|
+
certPresented: z.string().describe('"1" when the client presented a certificate, "0" when it did not.'),
|
|
31
|
+
certVerified: z
|
|
32
|
+
.string()
|
|
33
|
+
.describe(
|
|
34
|
+
'"SUCCESS" when the certificate verified against the zone\'s CA; "NONE" or "FAILED:<reason>" otherwise.',
|
|
35
|
+
),
|
|
36
|
+
certRevoked: z.string().describe('"1" when the certificate has been revoked, "0" when it has not.'),
|
|
37
|
+
certIssuerDN: z.string().describe("The issuer's distinguished name."),
|
|
38
|
+
certSubjectDN: z.string().describe("The subject's distinguished name."),
|
|
39
|
+
certSerial: z.string().describe("The certificate's serial number."),
|
|
40
|
+
certFingerprintSHA1: z.string().describe("The certificate's SHA-1 fingerprint, hex."),
|
|
41
|
+
certFingerprintSHA256: z.string().describe("The certificate's SHA-256 fingerprint, hex."),
|
|
42
|
+
certNotBefore: z.string().describe("When the certificate becomes valid."),
|
|
43
|
+
certNotAfter: z.string().describe("When the certificate stops being valid."),
|
|
44
|
+
})
|
|
45
|
+
.describe("The client-certificate fields Cloudflare puts on `request.cf.tlsClientAuth`.");
|
|
46
|
+
export type TlsClientAuth = z.infer<typeof TlsClientAuth>;
|
|
47
|
+
|
|
48
|
+
/** A certificate that verified against the zone's CA and has not been revoked, and who it names. */
|
|
49
|
+
export interface VerifiedCertificate {
|
|
50
|
+
state: "verified";
|
|
51
|
+
issuerDN: string;
|
|
52
|
+
subjectDN: string;
|
|
53
|
+
serial: string;
|
|
54
|
+
fingerprintSHA1: string;
|
|
55
|
+
fingerprintSHA256: string;
|
|
56
|
+
notBefore: string;
|
|
57
|
+
notAfter: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** What a request's client certificate turned out to be. Only `verified` is ever trusted. */
|
|
61
|
+
export type ClientCertificate =
|
|
62
|
+
| VerifiedCertificate
|
|
63
|
+
| { state: "absent" }
|
|
64
|
+
| { state: "unverified"; verification: string }
|
|
65
|
+
| { state: "revoked" };
|
|
66
|
+
|
|
67
|
+
/** Read the client certificate off a request. Never throws: anything it cannot read is not `verified`. */
|
|
68
|
+
export function readClientCertificate(request: Request): ClientCertificate {
|
|
69
|
+
const cf = (request as { cf?: unknown }).cf;
|
|
70
|
+
const raw = typeof cf === "object" && cf !== null ? (cf as { tlsClientAuth?: unknown }).tlsClientAuth : undefined;
|
|
71
|
+
if (typeof raw !== "object" || raw === null) return { state: "absent" };
|
|
72
|
+
const parsed = TlsClientAuth.safeParse(raw);
|
|
73
|
+
if (!parsed.success) {
|
|
74
|
+
// Present but unreadable. Not `absent` unless it says so, because a malformed record with a
|
|
75
|
+
// certificate in it is not an ordinary device — and never `verified`, whatever it says.
|
|
76
|
+
const presented = (raw as { certPresented?: unknown }).certPresented;
|
|
77
|
+
if (presented === "0") return { state: "absent" };
|
|
78
|
+
const verification = (raw as { certVerified?: unknown }).certVerified;
|
|
79
|
+
return { state: "unverified", verification: typeof verification === "string" ? verification : "unreadable" };
|
|
80
|
+
}
|
|
81
|
+
const auth = parsed.data;
|
|
82
|
+
if (auth.certPresented !== "1") return { state: "absent" };
|
|
83
|
+
if (auth.certVerified !== "SUCCESS") return { state: "unverified", verification: auth.certVerified };
|
|
84
|
+
if (auth.certRevoked !== "0") return { state: "revoked" };
|
|
85
|
+
return {
|
|
86
|
+
state: "verified",
|
|
87
|
+
issuerDN: auth.certIssuerDN,
|
|
88
|
+
subjectDN: auth.certSubjectDN,
|
|
89
|
+
serial: auth.certSerial,
|
|
90
|
+
fingerprintSHA1: auth.certFingerprintSHA1,
|
|
91
|
+
fingerprintSHA256: auth.certFingerprintSHA256,
|
|
92
|
+
notBefore: auth.certNotBefore,
|
|
93
|
+
notAfter: auth.certNotAfter,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Which certificates a resolver trusts. A fingerprint pin is required; the issuer is an extra check. */
|
|
98
|
+
export interface CertificatePins {
|
|
99
|
+
/**
|
|
100
|
+
* The issuer the certificate must also name, exactly — your CA's distinguished name. **Never enough on
|
|
101
|
+
* its own**: on the Cloudflare-managed CA every certificate the zone verifies names the same issuer.
|
|
102
|
+
*/
|
|
103
|
+
issuerDN?: string;
|
|
104
|
+
/**
|
|
105
|
+
* The SHA-256 fingerprints of the certificates you issued to your backend. Case and colons are ignored.
|
|
106
|
+
* Required, and an empty list trusts nothing.
|
|
107
|
+
*/
|
|
108
|
+
fingerprintsSHA256: readonly string[];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A fingerprint in one spelling: uppercase hex, no separators. */
|
|
112
|
+
function normalizeFingerprint(value: string): string {
|
|
113
|
+
return value.replace(/[^0-9a-fA-F]/g, "").toUpperCase();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Whether a certificate is one this Worker trusts: verified, not revoked, one of the pinned fingerprints,
|
|
118
|
+
* and from the pinned issuer when one is given.
|
|
119
|
+
*
|
|
120
|
+
* **No fingerprint is no trust.** Every certificate the zone's CA issued verifies, so with nothing pinned
|
|
121
|
+
* this would trust a certificate minted for any other purpose under the same account. An issuer pin does
|
|
122
|
+
* not close that: on a shared CA, every certificate behind the zone rule already names that issuer. Pin
|
|
123
|
+
* the fingerprints of the certificates your backend holds, and add the issuer if you like.
|
|
124
|
+
*/
|
|
125
|
+
export function isTrustedCertificate(certificate: ClientCertificate, pins: CertificatePins): boolean {
|
|
126
|
+
if (certificate.state !== "verified") return false;
|
|
127
|
+
// Read defensively: a pin object built at runtime can arrive without the field the type requires.
|
|
128
|
+
const fingerprints = Array.isArray(pins.fingerprintsSHA256) ? pins.fingerprintsSHA256 : [];
|
|
129
|
+
if (fingerprints.length === 0) return false;
|
|
130
|
+
if (pins.issuerDN !== undefined && certificate.issuerDN !== pins.issuerDN) return false;
|
|
131
|
+
const presented = normalizeFingerprint(certificate.fingerprintSHA256);
|
|
132
|
+
return presented !== "" && fingerprints.some((pin) => normalizeFingerprint(pin) === presented);
|
|
133
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 Pithy
|
|
2
|
+
// SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import type { PithyHonoEnv } from "@pithy-sh/core/src/capability/capability";
|
|
5
|
+
import type { SecretsStoreEnv } from "@pithy-sh/secrets/src/env/bindings";
|
|
6
|
+
import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
|
|
7
|
+
import { secretsStore } from "@pithy-sh/secrets/src/secretsStore";
|
|
8
|
+
import type { Context } from "hono";
|
|
9
|
+
import { CALLER_TOKEN_HEADER, type CallerTokenVerdict, verifyCallerToken } from "./token";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* **The caller token, verified off a request, with its key read the one way a secret is read (#560).**
|
|
13
|
+
*
|
|
14
|
+
* This is what a `resolveScopes` calls. It reads the token from {@link CALLER_TOKEN_HEADER} and the key
|
|
15
|
+
* from `@pithy-sh/secrets` — `secretsStore(env, registry)`, never `env.X` — and hands both to
|
|
16
|
+
* `verifyCallerToken`.
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* auth({
|
|
20
|
+
* baseURL: PUBLIC_ORIGIN,
|
|
21
|
+
* resolveScopes: async (c) =>
|
|
22
|
+
* (await verifyCallerRequest(c, { audience: PUBLIC_ORIGIN })).trusted ? ["leaderboard:submit"] : [],
|
|
23
|
+
* })
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* **The key is declared here and supplied by the operator.** Spread {@link callerTokenRegistry} into the
|
|
27
|
+
* `secrets({ registry })` call so `pithy secrets` knows it. The kit does not mint it: the backend that signs
|
|
28
|
+
* with it is the one that needs this option, a backend outside Cloudflare, and nothing in the kit hands a
|
|
29
|
+
* minted value back out. So the operator generates one value, stores it with the backend, and writes the
|
|
30
|
+
* same value here with `pithy secrets create`. A Worker that could read this store would be a Worker of
|
|
31
|
+
* this project, and that one calls over a service binding instead.
|
|
32
|
+
*
|
|
33
|
+
* **Read per call, not through the shared cache.** A token arrives rarely next to a session, and a key
|
|
34
|
+
* read fresh is a rotation that takes effect on the next request. A request with no token reads nothing.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/** The secret a caller token is signed with. One per environment, supplied by the operator. */
|
|
38
|
+
export const CALLER_TOKEN_SECRET = "auth-caller-token-key";
|
|
39
|
+
|
|
40
|
+
/** Where an operator is told how to make the caller-token key, hand it to the backend, and replace it. */
|
|
41
|
+
export const CALLER_TOKEN_KEY_PAGE =
|
|
42
|
+
"https://github.com/pithy-sh/pithy/blob/main/packages/auth/docs/server-authoritative.md#the-signing-key";
|
|
43
|
+
|
|
44
|
+
/** The registry entry for {@link CALLER_TOKEN_SECRET}. Spread it into the project's `secrets({ registry })`. */
|
|
45
|
+
export const callerTokenRegistry = defineSecretRegistry({
|
|
46
|
+
[CALLER_TOKEN_SECRET]: {
|
|
47
|
+
backend: "d1",
|
|
48
|
+
scope: "environment",
|
|
49
|
+
// Tracked for age, so `pithy secrets ls --check` says when it is due. Replacing it is the operator's.
|
|
50
|
+
rotatable: true,
|
|
51
|
+
valueType: "text",
|
|
52
|
+
// Obtained, not minted, and replaced by hand. Two parties hold this value — the Worker that verifies
|
|
53
|
+
// and the backend that signs — and the backend is outside the project. A kit-minted value would be one
|
|
54
|
+
// that backend could never learn, and a kit rotation would change it under the backend without a word.
|
|
55
|
+
origin: { kind: "obtained", issuer: "other", documentation: CALLER_TOKEN_KEY_PAGE },
|
|
56
|
+
rotation: { kind: "manual", issuer: "other", documentation: CALLER_TOKEN_KEY_PAGE },
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/** What {@link verifyCallerRequest} takes. */
|
|
61
|
+
export interface VerifyCallerRequestOptions {
|
|
62
|
+
/** This Worker's own public origin — the `baseURL` handed to `auth()`. Never read off the request. */
|
|
63
|
+
audience: string;
|
|
64
|
+
/** A tighter lifetime ceiling than the kit's fifteen minutes. */
|
|
65
|
+
maxLifetimeSeconds?: number;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Verify the caller token on this request. `absent` when there is none — read only from
|
|
70
|
+
* {@link CALLER_TOKEN_HEADER}, never from `Authorization`, which carries the player's forwarded session.
|
|
71
|
+
*/
|
|
72
|
+
export async function verifyCallerRequest(
|
|
73
|
+
c: Context<PithyHonoEnv>,
|
|
74
|
+
options: VerifyCallerRequestOptions,
|
|
75
|
+
): Promise<CallerTokenVerdict> {
|
|
76
|
+
const token = c.req.header(CALLER_TOKEN_HEADER);
|
|
77
|
+
if (token === undefined || token === "") return { trusted: false, reason: "absent" };
|
|
78
|
+
const secrets = await secretsStore(c.env as unknown as SecretsStoreEnv, callerTokenRegistry);
|
|
79
|
+
return verifyCallerToken(token, {
|
|
80
|
+
keys: secrets.getVersions(CALLER_TOKEN_SECRET),
|
|
81
|
+
audience: options.audience,
|
|
82
|
+
...(options.maxLifetimeSeconds === undefined ? {} : { maxLifetimeSeconds: options.maxLifetimeSeconds }),
|
|
83
|
+
});
|
|
84
|
+
}
|