@pithy-sh/auth 0.8.0 → 0.9.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 (85) hide show
  1. package/README.md +4 -0
  2. package/dist/caller/certificate.d.ts +83 -0
  3. package/dist/caller/certificate.d.ts.map +1 -0
  4. package/dist/caller/certificate.js +92 -0
  5. package/dist/caller/request.d.ts +66 -0
  6. package/dist/caller/request.d.ts.map +1 -0
  7. package/dist/caller/request.js +71 -0
  8. package/dist/caller/token.d.ts +130 -0
  9. package/dist/caller/token.d.ts.map +1 -0
  10. package/dist/caller/token.js +207 -0
  11. package/dist/capability.d.ts +44 -1
  12. package/dist/capability.d.ts.map +1 -1
  13. package/dist/capability.js +7 -4
  14. package/dist/data/betterAuth.d.ts +1 -1
  15. package/dist/data/betterAuth.d.ts.map +1 -1
  16. package/dist/data/betterAuth.js +1 -1
  17. package/dist/data/tables.d.ts +1 -1
  18. package/dist/http/credentialResign.d.ts +46 -0
  19. package/dist/http/credentialResign.d.ts.map +1 -0
  20. package/dist/http/credentialResign.js +203 -0
  21. package/dist/http/errorCallbackUrl.d.ts.map +1 -1
  22. package/dist/http/errorCallbackUrl.js +15 -9
  23. package/dist/http/middleware.d.ts.map +1 -1
  24. package/dist/http/middleware.js +66 -15
  25. package/dist/http/providerRefusal.d.ts +8 -7
  26. package/dist/http/providerRefusal.d.ts.map +1 -1
  27. package/dist/http/providerRefusal.js +29 -32
  28. package/dist/http/resolve.d.ts.map +1 -1
  29. package/dist/http/resolve.js +18 -3
  30. package/dist/instance/auth.d.ts +1225 -2
  31. package/dist/instance/auth.d.ts.map +1 -1
  32. package/dist/instance/auth.js +6 -2
  33. package/dist/instance/jwksReencryption.d.ts +75 -0
  34. package/dist/instance/jwksReencryption.d.ts.map +1 -0
  35. package/dist/instance/jwksReencryption.js +160 -0
  36. package/dist/instance/providerSignInGate.d.ts +7 -6
  37. package/dist/instance/providerSignInGate.d.ts.map +1 -1
  38. package/dist/instance/providerSignInGate.js +16 -14
  39. package/dist/instance/secrets.d.ts +168 -1
  40. package/dist/instance/secrets.d.ts.map +1 -1
  41. package/dist/instance/secrets.js +86 -3
  42. package/dist/instance/sessionSecrets.d.ts +45 -0
  43. package/dist/instance/sessionSecrets.d.ts.map +1 -0
  44. package/dist/instance/sessionSecrets.js +29 -0
  45. package/dist/migrations/0001_init.d.ts.map +1 -1
  46. package/dist/migrations/0003_account_issuer_nullable.d.ts +5 -0
  47. package/dist/migrations/0003_account_issuer_nullable.d.ts.map +1 -0
  48. package/dist/migrations/0003_account_issuer_nullable.js +131 -0
  49. package/dist/migrations/set.d.ts +2 -1
  50. package/dist/migrations/set.d.ts.map +1 -1
  51. package/dist/migrations/set.js +4 -2
  52. package/dist/test-utils/liveApp.d.ts +5 -0
  53. package/dist/test-utils/liveApp.d.ts.map +1 -1
  54. package/dist/test-utils/schemaDrift.d.ts +49 -0
  55. package/dist/test-utils/schemaDrift.d.ts.map +1 -0
  56. package/dist/test-utils/schemaDrift.js +35 -0
  57. package/dist/test-utils/scopedBackend.d.ts +183 -0
  58. package/dist/test-utils/scopedBackend.d.ts.map +1 -0
  59. package/dist/test-utils/scopedBackend.js +160 -0
  60. package/dist/version.generated.d.ts +1 -1
  61. package/dist/version.generated.js +1 -1
  62. package/docs/server-authoritative.md +182 -0
  63. package/package.json +11 -8
  64. package/src/caller/certificate.ts +133 -0
  65. package/src/caller/request.ts +84 -0
  66. package/src/caller/token.ts +276 -0
  67. package/src/capability.ts +65 -4
  68. package/src/data/betterAuth.ts +2 -1
  69. package/src/http/credentialResign.ts +268 -0
  70. package/src/http/errorCallbackUrl.ts +21 -13
  71. package/src/http/middleware.ts +100 -35
  72. package/src/http/providerRefusal.ts +30 -32
  73. package/src/http/resolve.ts +27 -3
  74. package/src/http/routes.ts +1 -1
  75. package/src/instance/auth.ts +22 -4
  76. package/src/instance/jwksReencryption.ts +206 -0
  77. package/src/instance/providerSignInGate.ts +23 -21
  78. package/src/instance/secrets.ts +94 -1
  79. package/src/instance/sessionSecrets.ts +64 -0
  80. package/src/migrations/0001_init.ts +8 -10
  81. package/src/migrations/0003_account_issuer_nullable.ts +199 -0
  82. package/src/migrations/set.ts +3 -1
  83. package/src/test-utils/schemaDrift.ts +82 -0
  84. package/src/test-utils/scopedBackend.ts +136 -0
  85. package/src/version.generated.ts +1 -1
@@ -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
+ }
@@ -0,0 +1,276 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { InternalError } from "@pithy-sh/core/src/error/pithyError";
5
+ import { z } from "zod";
6
+
7
+ /**
8
+ * **A short-lived, audience-restricted caller token — the portable way to prove a request came from the
9
+ * adopter's own backend (#560).**
10
+ *
11
+ * `resolveScopes` asks one question: is this request's caller the adopter's trusted backend, or a device?
12
+ * Where that backend is a Worker, a service binding answers it with no credential at all, and where the
13
+ * zone can run mTLS a client certificate answers it at the edge. Neither works everywhere — a service
14
+ * binding needs both ends on Cloudflare, mTLS needs a proxied zone and an exact hostname, so not
15
+ * `workers.dev`. This is what works on day one anywhere, and it is shipped because the alternative every
16
+ * adopter otherwise reaches for is a long-lived shared secret compared in a header, which fails every
17
+ * control RFC 9700 names at once.
18
+ *
19
+ * So it holds to those controls, each on its own line below:
20
+ *
21
+ * - **Audience-restricted.** `aud` is the origin the token was minted for, and it verifies there and nowhere
22
+ * else — a staging token presented to production is refused, and so is one Worker's token replayed at
23
+ * another that happens to share the key.
24
+ * - **Short-lived.** Five minutes by default, and a ceiling of fifteen that no token and no configuration
25
+ * gets past. A token whose `exp` is a day after its `iat` is refused even when it is otherwise perfect,
26
+ * because honoring it would make it a shared secret with extra steps.
27
+ * - **Signed with a key the Worker reads from `@pithy-sh/secrets`.** The operator supplies it and the
28
+ * backend holds the same value. The `kid` names the stored version the token was signed with, and a kid
29
+ * the store does not hold is refused.
30
+ *
31
+ * What it is not is **sender-constrained**: a token lifted off the wire is usable by whoever lifted it, for
32
+ * the minutes it has left. RFC 9700 says a token SHOULD be bound to its sender, and the two answers are
33
+ * mTLS (`readClientCertificate`) and DPoP, which the kit does not ship yet. Short lifetime is what limits
34
+ * the damage here, which is why the ceiling is not negotiable.
35
+ *
36
+ * **HS256 and nothing else.** One algorithm, one key type, one token shape — the header is validated
37
+ * against a literal, so `alg: none` and an asymmetric algorithm are malformed rather than negotiated. No
38
+ * JWT library: the algorithm agility one brings is where the JWT vulnerabilities live.
39
+ */
40
+
41
+ /** The header a caller token travels on. Not `Authorization`, which carries the player's forwarded session. */
42
+ export const CALLER_TOKEN_HEADER = "pithy-caller";
43
+
44
+ /** How long a minted token lives unless the minter asks for less: five minutes. */
45
+ export const DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS = 5 * 60;
46
+
47
+ /**
48
+ * The longest a caller token may live, from its `iat` to its `exp` — fifteen minutes, minted or verified.
49
+ *
50
+ * A ceiling rather than a default, and it refuses above rather than clamping: a verifier configured past it
51
+ * is a configuration error, and a token claiming more is refused. Minutes because the token is a bearer
52
+ * credential with no sender binding, and its lifetime is the whole of what bounds a stolen one.
53
+ */
54
+ export const MAX_CALLER_TOKEN_LIFETIME_SECONDS = 15 * 60;
55
+
56
+ /** How far in the future an `iat` may sit before the token is refused — clocks disagree by seconds, not minutes. */
57
+ export const CALLER_TOKEN_CLOCK_SKEW_SECONDS = 30;
58
+
59
+ /** The protected header of a caller token. */
60
+ export const CallerTokenHeader = z
61
+ .object({
62
+ alg: z.literal("HS256").describe("The signature algorithm. HMAC-SHA-256, and nothing else is accepted."),
63
+ typ: z.literal("JWT").optional().describe("The media type, `JWT` when present."),
64
+ kid: z.string().min(1).describe("The version of the caller-token key this token was signed with."),
65
+ })
66
+ .describe("The protected header of a caller token: HS256, and which key version signed it.");
67
+ export type CallerTokenHeader = z.infer<typeof CallerTokenHeader>;
68
+
69
+ /** The claims a caller token carries. */
70
+ export const CallerTokenClaims = z
71
+ .object({
72
+ aud: z.string().describe("The origin this token was minted for. It verifies at that origin and nowhere else."),
73
+ iat: z.number().int().describe("When it was minted, in Unix seconds."),
74
+ exp: z.number().int().describe("When it stops verifying, in Unix seconds. At most fifteen minutes after `iat`."),
75
+ sub: z
76
+ .string()
77
+ .optional()
78
+ .describe("Which backend minted it, for the adopter's own logs. The verifier grants nothing on it."),
79
+ })
80
+ .describe("The claims of a caller token: where it is valid, and for how long.");
81
+ export type CallerTokenClaims = z.infer<typeof CallerTokenClaims>;
82
+
83
+ /**
84
+ * Why a caller token was not trusted. Distinct values so the adopter's own log can say which, never so a
85
+ * response can — a resolver answers `[]` for every one of them, and the gate's 403 is the same either way.
86
+ */
87
+ export type CallerTokenRefusal =
88
+ | "absent"
89
+ | "malformed"
90
+ | "unknown_key"
91
+ | "signature"
92
+ | "audience"
93
+ | "expired"
94
+ | "lifetime";
95
+
96
+ /** What {@link verifyCallerToken} decided. */
97
+ export type CallerTokenVerdict =
98
+ | { trusted: true; claims: CallerTokenClaims }
99
+ | { trusted: false; reason: CallerTokenRefusal };
100
+
101
+ /** A key set in the shape `secretsStore(...).getVersions(name)` answers: version → key. */
102
+ export interface CallerTokenKeys {
103
+ versions: Record<string, string>;
104
+ }
105
+
106
+ const encoder = new TextEncoder();
107
+ const decoder = new TextDecoder();
108
+
109
+ /** The url alphabet, unpadded. Padding and the standard alphabet are refused, so a token has one spelling. */
110
+ const BASE64URL = /^[A-Za-z0-9_-]+$/;
111
+
112
+ function encodeSegment(bytes: Uint8Array): string {
113
+ let binary = "";
114
+ for (const byte of bytes) binary += String.fromCharCode(byte);
115
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
116
+ }
117
+
118
+ /** Decode one unpadded base64url segment, or `null` — strict, because every segment is attacker-supplied. */
119
+ function decodeSegment(segment: string): Uint8Array | null {
120
+ if (!BASE64URL.test(segment) || segment.length % 4 === 1) return null;
121
+ try {
122
+ const binary = atob(segment.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (segment.length % 4)) % 4));
123
+ const bytes = new Uint8Array(binary.length);
124
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
125
+ return bytes;
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+
131
+ /** Decode a JSON segment through its schema, or `null` for any failure at all. */
132
+ function decodeJson<T>(segment: string, schema: z.ZodType<T>): T | null {
133
+ const bytes = decodeSegment(segment);
134
+ if (bytes === null) return null;
135
+ let json: unknown;
136
+ try {
137
+ json = JSON.parse(decoder.decode(bytes));
138
+ } catch {
139
+ return null;
140
+ }
141
+ const parsed = schema.safeParse(json);
142
+ return parsed.success ? parsed.data : null;
143
+ }
144
+
145
+ /** The origin a URL names, or the string unchanged when it is not one — so it can only fail to match. */
146
+ function originOf(audience: string): string {
147
+ try {
148
+ return new URL(audience).origin;
149
+ } catch {
150
+ return audience;
151
+ }
152
+ }
153
+
154
+ function hmacKey(key: string, usage: "sign" | "verify"): Promise<CryptoKey> {
155
+ return crypto.subtle.importKey("raw", encoder.encode(key), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
156
+ }
157
+
158
+ /** Refuse a lifetime outside `(0, MAX]` — a configuration error, raised loudly rather than clamped. */
159
+ function assertLifetime(seconds: number, what: string): void {
160
+ if (!Number.isInteger(seconds) || seconds <= 0 || seconds > MAX_CALLER_TOKEN_LIFETIME_SECONDS) {
161
+ throw new InternalError({
162
+ message: `A caller token's ${what} must be a whole number of seconds from 1 to ${MAX_CALLER_TOKEN_LIFETIME_SECONDS}.`,
163
+ action: `Use a lifetime of minutes, not hours — at most ${MAX_CALLER_TOKEN_LIFETIME_SECONDS} seconds.`,
164
+ detail: `got ${String(seconds)}`,
165
+ });
166
+ }
167
+ }
168
+
169
+ /** What {@link mintCallerToken} takes. */
170
+ export interface MintCallerTokenOptions {
171
+ /** The caller-token key, the same value the Worker's store holds under `auth-caller-token-key`. */
172
+ key: string;
173
+ /** The version the Worker's store holds it as. `"1"` for any value `pithy secrets create` or `update` wrote. */
174
+ kid: string;
175
+ /** Any URL on the Worker the token will be presented to. Reduced to its origin. */
176
+ audience: string;
177
+ /** Which backend is minting, for the receiving Worker's logs. Optional; it grants nothing. */
178
+ subject?: string;
179
+ /** How long it lives. Defaults to {@link DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS}; never more than the ceiling. */
180
+ lifetimeSeconds?: number;
181
+ /** The clock. Defaults to now. */
182
+ now?: Date;
183
+ }
184
+
185
+ /**
186
+ * Mint a caller token — on the **trusted backend**, never on a device.
187
+ *
188
+ * Mint one per call, or per few minutes, and present it on {@link CALLER_TOKEN_HEADER}. A backend that is
189
+ * another Worker in this project reads the key the way the verifier does, through `@pithy-sh/secrets`.
190
+ */
191
+ export async function mintCallerToken(options: MintCallerTokenOptions): Promise<string> {
192
+ const lifetime = options.lifetimeSeconds ?? DEFAULT_CALLER_TOKEN_LIFETIME_SECONDS;
193
+ assertLifetime(lifetime, "lifetime");
194
+ const iat = Math.floor((options.now ?? new Date()).getTime() / 1000);
195
+ const header: CallerTokenHeader = { alg: "HS256", typ: "JWT", kid: options.kid };
196
+ const claims: CallerTokenClaims = {
197
+ aud: originOf(options.audience),
198
+ iat,
199
+ exp: iat + lifetime,
200
+ ...(options.subject === undefined ? {} : { sub: options.subject }),
201
+ };
202
+ const input = `${encodeSegment(encoder.encode(JSON.stringify(header)))}.${encodeSegment(encoder.encode(JSON.stringify(claims)))}`;
203
+ const signature = new Uint8Array(
204
+ await crypto.subtle.sign("HMAC", await hmacKey(options.key, "sign"), encoder.encode(input)),
205
+ );
206
+ return `${input}.${encodeSegment(signature)}`;
207
+ }
208
+
209
+ /** What {@link verifyCallerToken} takes. */
210
+ export interface VerifyCallerTokenOptions {
211
+ /** Every still-valid key version, as `getVersions` answers them. */
212
+ keys: CallerTokenKeys;
213
+ /**
214
+ * This Worker's own public origin — the `baseURL` handed to `auth()`. **Never** a value read off the
215
+ * request or the token: a verifier handed the caller's idea of the audience accepts every audience.
216
+ */
217
+ audience: string;
218
+ /** The clock. Defaults to now. */
219
+ now?: Date;
220
+ /** A tighter ceiling than {@link MAX_CALLER_TOKEN_LIFETIME_SECONDS}, for a verifier that wants one. */
221
+ maxLifetimeSeconds?: number;
222
+ }
223
+
224
+ /**
225
+ * Decide whether a caller token is one to trust, and why not when it is not.
226
+ *
227
+ * **In this order, and the order is the security model:** structure, then the key, then the signature,
228
+ * then the audience, then the lifetime, then expiry. Nothing about the claims is read as a fact until the
229
+ * signature has verified, so a forgery learns nothing from the answer about how far it got.
230
+ *
231
+ * Returns a verdict rather than throwing, so a resolver can answer `[]` and log the reason. It throws only
232
+ * for its own misconfiguration — a ceiling past the maximum — which `resolveScopes` turns into no scopes.
233
+ */
234
+ export async function verifyCallerToken(token: string, options: VerifyCallerTokenOptions): Promise<CallerTokenVerdict> {
235
+ const ceiling = options.maxLifetimeSeconds ?? MAX_CALLER_TOKEN_LIFETIME_SECONDS;
236
+ assertLifetime(ceiling, "lifetime ceiling");
237
+
238
+ const segments = token.split(".");
239
+ const [encodedHeader, encodedClaims, encodedSignature] = segments;
240
+ if (segments.length !== 3 || !encodedHeader || !encodedClaims || !encodedSignature) {
241
+ return { trusted: false, reason: "malformed" };
242
+ }
243
+ const header = decodeJson(encodedHeader, CallerTokenHeader);
244
+ const claims = decodeJson(encodedClaims, CallerTokenClaims);
245
+ const signature = decodeSegment(encodedSignature);
246
+ if (header === null || claims === null || signature === null) return { trusted: false, reason: "malformed" };
247
+
248
+ // An own property and a string, or nothing. A bracket lookup with `kid: "__proto__"` would otherwise
249
+ // reach up the prototype chain, hand `importKey` an object it coerces to a fixed string, and sign for it.
250
+ const versions = options.keys.versions;
251
+ const key = Object.hasOwn(versions, header.kid) ? versions[header.kid] : undefined;
252
+ if (typeof key !== "string") return { trusted: false, reason: "unknown_key" };
253
+
254
+ let verified: boolean;
255
+ try {
256
+ verified = await crypto.subtle.verify(
257
+ "HMAC",
258
+ await hmacKey(key, "verify"),
259
+ new Uint8Array(signature),
260
+ encoder.encode(`${encodedHeader}.${encodedClaims}`),
261
+ );
262
+ } catch {
263
+ verified = false;
264
+ }
265
+ if (!verified) return { trusted: false, reason: "signature" };
266
+
267
+ if (claims.aud !== originOf(options.audience)) return { trusted: false, reason: "audience" };
268
+
269
+ const now = Math.floor((options.now ?? new Date()).getTime() / 1000);
270
+ if (claims.exp - claims.iat > ceiling || claims.iat > now + CALLER_TOKEN_CLOCK_SKEW_SECONDS) {
271
+ return { trusted: false, reason: "lifetime" };
272
+ }
273
+ if (claims.exp <= now) return { trusted: false, reason: "expired" };
274
+
275
+ return { trusted: true, claims };
276
+ }
package/src/capability.ts CHANGED
@@ -2,13 +2,14 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
- import type { Capability, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
5
+ import type { Capability, PithyHonoEnv, PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
6
6
  import { defineCapability } from "@pithy-sh/core/src/capability/capability";
7
7
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
8
8
  import type { EmailCapability } from "@pithy-sh/email/src/capability";
9
9
  import { isEmailCapability } from "@pithy-sh/email/src/capability";
10
10
  import { isTurnstileCapability } from "@pithy-sh/turnstile/src/capability";
11
11
  import { TURNSTILE_LOGIN_ACTION, type TurnstileMode } from "@pithy-sh/turnstile/src/config/config";
12
+ import type { Context } from "hono";
12
13
  import { z } from "zod";
13
14
  import type { AuthClientProjection } from "./client/projection";
14
15
  import { authTables } from "./data/tables";
@@ -20,7 +21,7 @@ import { createRateLimitMiddleware } from "./http/rateLimit";
20
21
  import { createAuthRoutes } from "./http/routes";
21
22
  import type { GithubUserInfoResolver } from "./instance/githubUserInfo";
22
23
  import { AuthPlugin, assertAdditivePlugins } from "./instance/plugins";
23
- import { authSecretsRegistry, inapplicableProviderSecrets } from "./instance/secrets";
24
+ import { authSecretsRegistryFor, inapplicableProviderSecrets } from "./instance/secrets";
24
25
  import { AUTH_MIGRATION_ORDER } from "./migrations/0001_init";
25
26
  import { authPluginPlan } from "./migrations/pluginTables";
26
27
  import { AUTH_MIGRATIONS } from "./migrations/set";
@@ -106,6 +107,14 @@ export const AuthConfig = z
106
107
  .int()
107
108
  .default(60 * 60 * 24)
108
109
  .describe("How often (seconds) an active session's expiry slides forward. Defaults to 1 day."),
110
+ sessionSecretRotateEveryDays: z
111
+ .number()
112
+ .int()
113
+ .positive()
114
+ .optional()
115
+ .describe(
116
+ "How often, in days, the secrets manager rotates `auth-session-secret` by itself. Unset by default, so nothing rotates it unattended. The previous version keeps verifying for the session lifetime, so nobody is signed out, and is retired once the JWKS keys sealed under it are re-encrypted. Must be longer than `sessionExpiresIn`.",
117
+ ),
109
118
  verificationExpiresIn: z
110
119
  .number()
111
120
  .int()
@@ -149,8 +158,35 @@ export interface AuthWiring {
149
158
  * is the ordinary case and every harness that builds this shape by hand would otherwise have to say so.
150
159
  */
151
160
  onSessionRevoked?: SessionRevokedListener | undefined;
161
+ /**
162
+ * The adopter's scope resolver, or absent. See {@link AuthOptions.resolveScopes}.
163
+ *
164
+ * Optional on the wiring for the reason `onSessionRevoked` is: no resolver is the ordinary composition.
165
+ */
166
+ resolveScopes?: ScopeResolver | undefined;
167
+ }
168
+
169
+ /** The session a {@link ScopeResolver} is asked about — the one Better Auth just resolved for this request. */
170
+ export interface ScopeResolverSession {
171
+ /** The signed-in user the session belongs to. */
172
+ userId: string;
173
+ /** The session this request presented. */
174
+ sessionId: string;
152
175
  }
153
176
 
177
+ /**
178
+ * Decide what this request's caller is, and answer the scopes that attests to (#560).
179
+ *
180
+ * Called by the session middleware on every authenticated request, after Better Auth has resolved the
181
+ * session and before any route runs. What it returns becomes `AuthContext.scopes`. It reads the **request**,
182
+ * which is where the proof is — a service binding the call arrived over, `request.cf.tlsClientAuth`, a
183
+ * short-lived token on its own header — and never anything the request merely claims about itself.
184
+ */
185
+ export type ScopeResolver = (
186
+ c: Context<PithyHonoEnv>,
187
+ session: ScopeResolverSession,
188
+ ) => readonly string[] | Promise<readonly string[]>;
189
+
154
190
  /**
155
191
  * Called when a session row is deleted — a sign-out, a revoke, an admin ending somebody's devices.
156
192
  *
@@ -201,6 +237,25 @@ export type AuthOptions = AuthConfigInput & {
201
237
  * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
202
238
  */
203
239
  onSessionRevoked?: SessionRevokedListener;
240
+ /**
241
+ * Decide, per request, what this request's caller is — and so which scope gates it opens (#560).
242
+ *
243
+ * `leaderboard:submit`, `rating:record`, `leaderboard:admin` and `ledger:admin` are **attestations about
244
+ * the caller, not permissions granted to the user**: each says *this write came from the adopter's own
245
+ * trusted backend, not from a device*. This is where that is decided, and the seam does not dictate how.
246
+ * A backend calling over a service binding, one presenting a client certificate, and one presenting a
247
+ * short-lived token all answer the same question here. `verifyCallerToken` and `readClientCertificate`
248
+ * are the kit's helpers for the last two; `docs/server-authoritative.md` ranks the three.
249
+ *
250
+ * **Resolved per request, never cached** — a cached scope is a revocation that has not taken effect.
251
+ * **Failure is closed and never fatal**: a resolver that throws, or answers anything but a list of
252
+ * strings, leaves the request with no scopes and logs at warn, and the request goes on to whatever gate
253
+ * it was headed for. **No default**: without one the array is empty and nothing extra runs, so composing
254
+ * this changes nothing until an adopter opts in.
255
+ *
256
+ * A function, so it is destructured off before `AuthConfig.parse` for the reason above.
257
+ */
258
+ resolveScopes?: ScopeResolver;
204
259
  };
205
260
 
206
261
  /** The auth capability, with its resolved config attached for inspection. */
@@ -256,7 +311,7 @@ export function auth(options: AuthOptions): AuthCapability {
256
311
  // Zod 4 objects strip unknown keys silently, so a `resolveGithubUserInfo` handed to `AuthConfig.parse`
257
312
  // would vanish with no error and the adopter's override would simply never run. `payments()` splits
258
313
  // its `resolveSubject` out for the same reason.
259
- const { resolveGithubUserInfo, onSessionRevoked, ...config } = options;
314
+ const { resolveGithubUserInfo, onSessionRevoked, resolveScopes, ...config } = options;
260
315
  const resolved = AuthConfig.parse(config);
261
316
  // What may be composed, before anything is built from the list. The four the kit composes are the
262
317
  // sign-in this product promises and what the control-plane seam verifies against, so a list naming one
@@ -273,6 +328,7 @@ export function auth(options: AuthOptions): AuthCapability {
273
328
  enqueueEmail: undefined,
274
329
  turnstile: undefined,
275
330
  onSessionRevoked,
331
+ resolveScopes,
276
332
  };
277
333
 
278
334
  // Tier-1 edge rate limiter, contributed as middleware so it runs before session resolution.
@@ -290,7 +346,12 @@ export function auth(options: AuthOptions): AuthCapability {
290
346
  package: PACKAGE_NAME,
291
347
  config: AuthConfig,
292
348
  dependsOn: ["secrets", "email"],
293
- secretRegistry: authSecretsRegistry,
349
+ // Whether anything will ever put a string in `AuthContext.scopes` — only when the adopter supplied a
350
+ // resolver. `pithy doctor` reads it against every composed capability's `scopeGates` (#560).
351
+ providesScopes: resolveScopes !== undefined,
352
+ // Built from the config, so the session secret's overlap is this composition's session lifetime and its
353
+ // period is the one the adopter asked for, if any (#602).
354
+ secretRegistry: authSecretsRegistryFor(resolved),
294
355
  // And which of those four credentials this composition cannot reach (#541). A provider that is off
295
356
  // has no code path that reads its pair, so `pithy doctor` listing it as outstanding re-raised a
296
357
  // settled question on every run. Declared rather than inferred: the config key and the secret name
@@ -103,8 +103,9 @@ export const Account = z
103
103
  id: z.string().describe("Primary key. A random/UUID text id."),
104
104
  issuer: z
105
105
  .string()
106
+ .nullable()
106
107
  .describe(
107
- "Who asserted this identity, as the identity provider names itself: an OIDC issuer URL (`https://accounts.google.com`), `local:oauth:<id>` for an OAuth provider that publishes none, or `local:credential` for a password. With `accountId` it is the account's identity and carries a unique index — a provider slug is a name this project chose, so two providers pointed at one directory could assert the same `accountId` and land on two rows.",
108
+ "A relic of Better Auth 1.7.0–1.7.2, which identified an account by `(issuer, accountId)` and wrote who asserted the identity here: an OIDC issuer URL, `local:oauth:<id>`, or `local:credential`. 1.7.3 went back to `(providerId, accountId)` and writes nothing here, so a row created since is null. Kept, with the values a Worker migrated under 1.7.1 holds, and read by nothing (#787).",
108
109
  ),
109
110
  accountId: z.string().describe("The provider's stable id for this user (e.g. the Google `sub` claim)."),
110
111
  providerId: z